text
stringlengths
517
228k
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TIFFPrintDirectory(TIFF* tif, FILE* fd, long flags) { TIFFDirectory *td = &tif->tif_dir; char *sep; long l, n; #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) fprintf(fd, "TIFF Directory at offset 0x%I64x (%I64u)\n", (unsigned __int64) tif->tif_diroff, (unsigned __int64) tif->tif_diroff); #else fprintf(fd, "TIFF Directory at offset 0x%llx (%llu)\n", (unsigned long long) tif->tif_diroff, (unsigned long long) tif->tif_diroff); #endif if (TIFFFieldSet(tif,FIELD_SUBFILETYPE)) { fprintf(fd, " Subfile Type:"); sep = " "; if (td->td_subfiletype & FILETYPE_REDUCEDIMAGE) { fprintf(fd, "%sreduced-resolution image", sep); sep = "/"; } if (td->td_subfiletype & FILETYPE_PAGE) { fprintf(fd, "%smulti-page document", sep); sep = "/"; } if (td->td_subfiletype & FILETYPE_MASK) fprintf(fd, "%stransparency mask", sep); fprintf(fd, " (%lu = 0x%lx)\n", (unsigned long) td->td_subfiletype, (long) td->td_subfiletype); } if (TIFFFieldSet(tif,FIELD_IMAGEDIMENSIONS)) { fprintf(fd, " Image Width: %lu Image Length: %lu", (unsigned long) td->td_imagewidth, (unsigned long) td->td_imagelength); if (TIFFFieldSet(tif,FIELD_IMAGEDEPTH)) fprintf(fd, " Image Depth: %lu", (unsigned long) td->td_imagedepth); fprintf(fd, "\n"); } if (TIFFFieldSet(tif,FIELD_TILEDIMENSIONS)) { fprintf(fd, " Tile Width: %lu Tile Length: %lu", (unsigned long) td->td_tilewidth, (unsigned long) td->td_tilelength); if (TIFFFieldSet(tif,FIELD_TILEDEPTH)) fprintf(fd, " Tile Depth: %lu", (unsigned long) td->td_tiledepth); fprintf(fd, "\n"); } if (TIFFFieldSet(tif,FIELD_RESOLUTION)) { fprintf(fd, " Resolution: %g, %g", td->td_xresolution, td->td_yresolution); if (TIFFFieldSet(tif,FIELD_RESOLUTIONUNIT)) { switch (td->td_resolutionunit) { case RESUNIT_NONE: fprintf(fd, " (unitless)"); break; case RESUNIT_INCH: fprintf(fd, " pixels/inch"); break; case RESUNIT_CENTIMETER: fprintf(fd, " pixels/cm"); break; default: fprintf(fd, " (unit %u = 0x%x)", td->td_resolutionunit, td->td_resolutionunit); break; } } fprintf(fd, "\n"); } if (TIFFFieldSet(tif,FIELD_POSITION)) fprintf(fd, " Position: %g, %g\n", td->td_xposition, td->td_yposition); if (TIFFFieldSet(tif,FIELD_BITSPERSAMPLE)) fprintf(fd, " Bits/Sample: %u\n", td->td_bitspersample); if (TIFFFieldSet(tif,FIELD_SAMPLEFORMAT)) { fprintf(fd, " Sample Format: "); switch (td->td_sampleformat) { case SAMPLEFORMAT_VOID: fprintf(fd, "void\n"); break; case SAMPLEFORMAT_INT: fprintf(fd, "signed integer\n"); break; case SAMPLEFORMAT_UINT: fprintf(fd, "unsigned integer\n"); break; case SAMPLEFORMAT_IEEEFP: fprintf(fd, "IEEE floating point\n"); break; case SAMPLEFORMAT_COMPLEXINT: fprintf(fd, "complex signed integer\n"); break; case SAMPLEFORMAT_COMPLEXIEEEFP: fprintf(fd, "complex IEEE floating point\n"); break; default: fprintf(fd, "%u (0x%x)\n", td->td_sampleformat, td->td_sampleformat); break; } } if (TIFFFieldSet(tif,FIELD_COMPRESSION)) { const TIFFCodec* c = TIFFFindCODEC(td->td_compression); fprintf(fd, " Compression Scheme: "); if (c) fprintf(fd, "%s\n", c->name); else fprintf(fd, "%u (0x%x)\n", td->td_compression, td->td_compression); } if (TIFFFieldSet(tif,FIELD_PHOTOMETRIC)) { fprintf(fd, " Photometric Interpretation: "); if (td->td_photometric < NPHOTONAMES) fprintf(fd, "%s\n", photoNames[td->td_photometric]); else { switch (td->td_photometric) { case PHOTOMETRIC_LOGL: fprintf(fd, "CIE Log2(L)\n"); break; case PHOTOMETRIC_LOGLUV: fprintf(fd, "CIE Log2(L) (u',v')\n"); break; default: fprintf(fd, "%u (0x%x)\n", td->td_photometric, td->td_photometric); break; } } } if (TIFFFieldSet(tif,FIELD_EXTRASAMPLES) && td->td_extrasamples) { uint16 i; fprintf(fd, " Extra Samples: %u<", td->td_extrasamples); sep = ""; for (i = 0; i < td->td_extrasamples; i++) { switch (td->td_sampleinfo[i]) { case EXTRASAMPLE_UNSPECIFIED: fprintf(fd, "%sunspecified", sep); break; case EXTRASAMPLE_ASSOCALPHA: fprintf(fd, "%sassoc-alpha", sep); break; case EXTRASAMPLE_UNASSALPHA: fprintf(fd, "%sunassoc-alpha", sep); break; default: fprintf(fd, "%s%u (0x%x)", sep, td->td_sampleinfo[i], td->td_sampleinfo[i]); break; } sep = ", "; } fprintf(fd, ">\n"); } if (TIFFFieldSet(tif,FIELD_INKNAMES)) { char* cp; uint16 i; fprintf(fd, " Ink Names: "); i = td->td_samplesperpixel; sep = ""; for (cp = td->td_inknames; i > 0 && cp < td->td_inknames + td->td_inknameslen; cp = strchr(cp,'\0')+1, i--) { size_t max_chars = td->td_inknameslen - (cp - td->td_inknames); fputs(sep, fd); _TIFFprintAsciiBounded(fd, cp, max_chars); sep = ", "; } fputs("\n", fd); } if (TIFFFieldSet(tif,FIELD_THRESHHOLDING)) { fprintf(fd, " Thresholding: "); switch (td->td_threshholding) { case THRESHHOLD_BILEVEL: fprintf(fd, "bilevel art scan\n"); break; case THRESHHOLD_HALFTONE: fprintf(fd, "halftone or dithered scan\n"); break; case THRESHHOLD_ERRORDIFFUSE: fprintf(fd, "error diffused\n"); break; default: fprintf(fd, "%u (0x%x)\n", td->td_threshholding, td->td_threshholding); break; } } if (TIFFFieldSet(tif,FIELD_FILLORDER)) { fprintf(fd, " FillOrder: "); switch (td->td_fillorder) { case FILLORDER_MSB2LSB: fprintf(fd, "msb-to-lsb\n"); break; case FILLORDER_LSB2MSB: fprintf(fd, "lsb-to-msb\n"); break; default: fprintf(fd, "%u (0x%x)\n", td->td_fillorder, td->td_fillorder); break; } } if (TIFFFieldSet(tif,FIELD_YCBCRSUBSAMPLING)) { fprintf(fd, " YCbCr Subsampling: %u, %u\n", td->td_ycbcrsubsampling[0], td->td_ycbcrsubsampling[1] ); } if (TIFFFieldSet(tif,FIELD_YCBCRPOSITIONING)) { fprintf(fd, " YCbCr Positioning: "); switch (td->td_ycbcrpositioning) { case YCBCRPOSITION_CENTERED: fprintf(fd, "centered\n"); break; case YCBCRPOSITION_COSITED: fprintf(fd, "cosited\n"); break; default: fprintf(fd, "%u (0x%x)\n", td->td_ycbcrpositioning, td->td_ycbcrpositioning); break; } } if (TIFFFieldSet(tif,FIELD_HALFTONEHINTS)) fprintf(fd, " Halftone Hints: light %u dark %u\n", td->td_halftonehints[0], td->td_halftonehints[1]); if (TIFFFieldSet(tif,FIELD_ORIENTATION)) { fprintf(fd, " Orientation: "); if (td->td_orientation < NORIENTNAMES) fprintf(fd, "%s\n", orientNames[td->td_orientation]); else fprintf(fd, "%u (0x%x)\n", td->td_orientation, td->td_orientation); } if (TIFFFieldSet(tif,FIELD_SAMPLESPERPIXEL)) fprintf(fd, " Samples/Pixel: %u\n", td->td_samplesperpixel); if (TIFFFieldSet(tif,FIELD_ROWSPERSTRIP)) { fprintf(fd, " Rows/Strip: "); if (td->td_rowsperstrip == (uint32) -1) fprintf(fd, "(infinite)\n"); else fprintf(fd, "%lu\n", (unsigned long) td->td_rowsperstrip); } if (TIFFFieldSet(tif,FIELD_MINSAMPLEVALUE)) fprintf(fd, " Min Sample Value: %u\n", td->td_minsamplevalue); if (TIFFFieldSet(tif,FIELD_MAXSAMPLEVALUE)) fprintf(fd, " Max Sample Value: %u\n", td->td_maxsamplevalue); if (TIFFFieldSet(tif,FIELD_SMINSAMPLEVALUE)) { int i; int count = (tif->tif_flags & TIFF_PERSAMPLE) ? td->td_samplesperpixel : 1; fprintf(fd, " SMin Sample Value:"); for (i = 0; i < count; ++i) fprintf(fd, " %g", td->td_sminsamplevalue[i]); fprintf(fd, "\n"); } if (TIFFFieldSet(tif,FIELD_SMAXSAMPLEVALUE)) { int i; int count = (tif->tif_flags & TIFF_PERSAMPLE) ? td->td_samplesperpixel : 1; fprintf(fd, " SMax Sample Value:"); for (i = 0; i < count; ++i) fprintf(fd, " %g", td->td_smaxsamplevalue[i]); fprintf(fd, "\n"); } if (TIFFFieldSet(tif,FIELD_PLANARCONFIG)) { fprintf(fd, " Planar Configuration: "); switch (td->td_planarconfig) { case PLANARCONFIG_CONTIG: fprintf(fd, "single image plane\n"); break; case PLANARCONFIG_SEPARATE: fprintf(fd, "separate image planes\n"); break; default: fprintf(fd, "%u (0x%x)\n", td->td_planarconfig, td->td_planarconfig); break; } } if (TIFFFieldSet(tif,FIELD_PAGENUMBER)) fprintf(fd, " Page Number: %u-%u\n", td->td_pagenumber[0], td->td_pagenumber[1]); if (TIFFFieldSet(tif,FIELD_COLORMAP)) { fprintf(fd, " Color Map: "); if (flags & TIFFPRINT_COLORMAP) { fprintf(fd, "\n"); n = 1L<<td->td_bitspersample; for (l = 0; l < n; l++) fprintf(fd, " %5ld: %5u %5u %5u\n", l, td->td_colormap[0][l], td->td_colormap[1][l], td->td_colormap[2][l]); } else fprintf(fd, "(present)\n"); } if (TIFFFieldSet(tif,FIELD_REFBLACKWHITE)) { int i; fprintf(fd, " Reference Black/White:\n"); for (i = 0; i < 3; i++) fprintf(fd, " %2d: %5g %5g\n", i, td->td_refblackwhite[2*i+0], td->td_refblackwhite[2*i+1]); } if (TIFFFieldSet(tif,FIELD_TRANSFERFUNCTION)) { fprintf(fd, " Transfer Function: "); if (flags & TIFFPRINT_CURVES) { fprintf(fd, "\n"); n = 1L<<td->td_bitspersample; for (l = 0; l < n; l++) { uint16 i; fprintf(fd, " %2ld: %5u", l, td->td_transferfunction[0][l]); for (i = 1; i < td->td_samplesperpixel; i++) fprintf(fd, " %5u", td->td_transferfunction[i][l]); fputc('\n', fd); } } else fprintf(fd, "(present)\n"); } if (TIFFFieldSet(tif, FIELD_SUBIFD) && (td->td_subifd)) { uint16 i; fprintf(fd, " SubIFD Offsets:"); for (i = 0; i < td->td_nsubifd; i++) #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) fprintf(fd, " %5I64u", (unsigned __int64) td->td_subifd[i]); #else fprintf(fd, " %5llu", (unsigned long long) td->td_subifd[i]); #endif fputc('\n', fd); } /* ** Custom tag support. */ { int i; short count; count = (short) TIFFGetTagListCount(tif); for(i = 0; i < count; i++) { uint32 tag = TIFFGetTagListEntry(tif, i); const TIFFField *fip; uint32 value_count; int mem_alloc = 0; void *raw_data; fip = TIFFFieldWithTag(tif, tag); if(fip == NULL) continue; if(fip->field_passcount) { if (fip->field_readcount == TIFF_VARIABLE2 ) { if(TIFFGetField(tif, tag, &value_count, &raw_data) != 1) continue; } else if (fip->field_readcount == TIFF_VARIABLE ) { uint16 small_value_count; if(TIFFGetField(tif, tag, &small_value_count, &raw_data) != 1) continue; value_count = small_value_count; } else { assert (fip->field_readcount == TIFF_VARIABLE || fip->field_readcount == TIFF_VARIABLE2); continue; } } else { if (fip->field_readcount == TIFF_VARIABLE || fip->field_readcount == TIFF_VARIABLE2) value_count = 1; else if (fip->field_readcount == TIFF_SPP) value_count = td->td_samplesperpixel; else value_count = fip->field_readcount; if (fip->field_tag == TIFFTAG_DOTRANGE && strcmp(fip->field_name,"DotRange") == 0) { /* TODO: This is an evil exception and should not have been handled this way ... likely best if we move it into the directory structure with an explicit field in libtiff 4.1 and assign it a FIELD_ value */ static uint16 dotrange[2]; raw_data = dotrange; TIFFGetField(tif, tag, dotrange+0, dotrange+1); } else if (fip->field_type == TIFF_ASCII || fip->field_readcount == TIFF_VARIABLE || fip->field_readcount == TIFF_VARIABLE2 || fip->field_readcount == TIFF_SPP || value_count > 1) { if(TIFFGetField(tif, tag, &raw_data) != 1) continue; } else { raw_data = _TIFFmalloc( _TIFFDataSize(fip->field_type) * value_count); mem_alloc = 1; if(TIFFGetField(tif, tag, raw_data) != 1) { _TIFFfree(raw_data); continue; } } } /* * Catch the tags which needs to be specially handled * and pretty print them. If tag not handled in * _TIFFPrettyPrintField() fall down and print it as * any other tag. */ if (!_TIFFPrettyPrintField(tif, fip, fd, tag, value_count, raw_data)) _TIFFPrintField(fd, fip, value_count, raw_data); if(mem_alloc) _TIFFfree(raw_data); } } if (tif->tif_tagmethods.printdir) (*tif->tif_tagmethods.printdir)(tif, fd, flags); _TIFFFillStriles( tif ); if ((flags & TIFFPRINT_STRIPS) && TIFFFieldSet(tif,FIELD_STRIPOFFSETS)) { uint32 s; fprintf(fd, " %lu %s:\n", (unsigned long) td->td_nstrips, isTiled(tif) ? "Tiles" : "Strips"); for (s = 0; s < td->td_nstrips; s++) #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) fprintf(fd, " %3lu: [%8I64u, %8I64u]\n", (unsigned long) s, (unsigned __int64) td->td_stripoffset[s], (unsigned __int64) td->td_stripbytecount[s]); #else fprintf(fd, " %3lu: [%8llu, %8llu]\n", (unsigned long) s, (unsigned long long) td->td_stripoffset[s], (unsigned long long) td->td_stripbytecount[s]); #endif } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'libtiff/tif_print.c: TIFFPrintDirectory(): fix null pointer dereference on corrupted file. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2770'</s>
<s>[INST] Given the following code containing errors, provide 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 Decompress::handleZipEntry(std::istream& zipStream, const ZipLocalFileHeader& hdr) { if (hdr.isDirectory()) { // directory have 0 size, nth to read if (!_flattenDirs) { std::string dirName = hdr.getFileName(); if (!ZipCommon::isValidPath(dirName)) throw ZipException("Illegal entry name " + dirName + " containing parent directory reference"); Poco::Path dir(_outDir, dirName); dir.makeDirectory(); Poco::File aFile(dir); aFile.createDirectories(); } return true; } try { std::string fileName = hdr.getFileName(); if (_flattenDirs) { // remove path info Poco::Path p(fileName); p.makeFile(); fileName = p.getFileName(); } if (!ZipCommon::isValidPath(fileName)) throw ZipException("Illegal entry name " + fileName + " containing parent directory reference"); Poco::Path file(fileName); file.makeFile(); Poco::Path dest(_outDir, file); dest.makeFile(); if (dest.depth() > 0) { Poco::File aFile(dest.parent()); aFile.createDirectories(); } Poco::FileOutputStream out(dest.toString()); ZipInputStream inp(zipStream, hdr, false); Poco::StreamCopier::copyStream(inp, out); out.close(); Poco::File aFile(dest.toString()); if (!aFile.exists() || !aFile.isFile()) { std::pair<const ZipLocalFileHeader, const std::string> tmp = std::make_pair(hdr, "Failed to create output stream " + dest.toString()); EError.notify(this, tmp); return false; } if (!inp.crcValid()) { if (!_keepIncompleteFiles) aFile.remove(); std::pair<const ZipLocalFileHeader, const std::string> tmp = std::make_pair(hdr, "CRC mismatch. Corrupt file: " + dest.toString()); EError.notify(this, tmp); return false; } // cannot check against hdr.getUnCompressedSize if CRC and size are not set in hdr but in a ZipDataInfo // crc is typically enough to detect errors if (aFile.getSize() != hdr.getUncompressedSize() && !hdr.searchCRCAndSizesAfterData()) { if (!_keepIncompleteFiles) aFile.remove(); std::pair<const ZipLocalFileHeader, const std::string> tmp = std::make_pair(hdr, "Filesizes do not match. Corrupt file: " + dest.toString()); EError.notify(this, tmp); return false; } std::pair<const ZipLocalFileHeader, const Poco::Path> tmp = std::make_pair(hdr, file); EOk.notify(this, tmp); } catch (Poco::Exception& e) { std::pair<const ZipLocalFileHeader, const std::string> tmp = std::make_pair(hdr, std::string("Exception: " + e.displayText())); EError.notify(this, tmp); return false; } catch (...) { std::pair<const ZipLocalFileHeader, const std::string> tmp = std::make_pair(hdr, std::string("Unknown Exception")); EError.notify(this, tmp); return false; } return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'merge zip entry absolute path vulnerability fix (#1968) from develop'</s>
<s>[INST] Given the following code containing errors, provide 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 CompressTest::testSetZipComment() { std::string comment("Testing...123..."); std::ofstream out("comment.zip", std::ios::binary); Poco::Path theFile(ZipTest::getTestFile("data", "test.zip")); Compress c(out, true); c.addFile(theFile, theFile.getFileName()); c.setZipComment(comment); ZipArchive a(c.close()); assert(a.getZipComment() == comment); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'merge zip entry absolute path vulnerability fix (#1968) from develop'</s>
<s>[INST] Given the following code containing errors, provide 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 long snd_seq_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct snd_seq_client *client = file->private_data; /* To use kernel stack for ioctl data. */ union { int pversion; int client_id; struct snd_seq_system_info system_info; struct snd_seq_running_info running_info; struct snd_seq_client_info client_info; struct snd_seq_port_info port_info; struct snd_seq_port_subscribe port_subscribe; struct snd_seq_queue_info queue_info; struct snd_seq_queue_status queue_status; struct snd_seq_queue_tempo tempo; struct snd_seq_queue_timer queue_timer; struct snd_seq_queue_client queue_client; struct snd_seq_client_pool client_pool; struct snd_seq_remove_events remove_events; struct snd_seq_query_subs query_subs; } buf; const struct ioctl_handler *handler; unsigned long size; int err; if (snd_BUG_ON(!client)) return -ENXIO; for (handler = ioctl_handlers; handler->cmd > 0; ++handler) { if (handler->cmd == cmd) break; } if (handler->cmd == 0) return -ENOTTY; memset(&buf, 0, sizeof(buf)); /* * All of ioctl commands for ALSA sequencer get an argument of size * within 13 bits. We can safely pick up the size from the command. */ size = _IOC_SIZE(handler->cmd); if (handler->cmd & IOC_IN) { if (copy_from_user(&buf, (const void __user *)arg, size)) return -EFAULT; } err = handler->func(client, &buf); if (err >= 0) { /* Some commands includes a bug in 'dir' field. */ if (handler->cmd == SNDRV_SEQ_IOCTL_SET_QUEUE_CLIENT || handler->cmd == SNDRV_SEQ_IOCTL_SET_CLIENT_POOL || (handler->cmd & IOC_OUT)) if (copy_to_user((void __user *)arg, &buf, size)) return -EFAULT; } return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'ALSA: seq: Make ioctls race-free The ALSA sequencer ioctls have no protection against racy calls while the concurrent operations may lead to interfere with each other. As reported recently, for example, the concurrent calls of setting client pool with a combination of write calls may lead to either the unkillable dead-lock or UAF. As a slightly big hammer solution, this patch introduces the mutex to make each ioctl exclusive. Although this may reduce performance via parallel ioctl calls, usually it's not demanded for sequencer usages, hence it should be negligible. Reported-by: Luo Quan <a4651386@163.com> Reviewed-by: Kees Cook <keescook@chromium.org> Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> 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: GetCode_(gdIOCtx *fd, CODE_STATIC_DATA *scd, int code_size, int flag, int *ZeroDataBlockP) { int i, j, ret; unsigned char count; if (flag) { scd->curbit = 0; scd->lastbit = 0; scd->last_byte = 0; scd->done = FALSE; return 0; } if ( (scd->curbit + code_size) >= scd->lastbit) { if (scd->done) { if (scd->curbit >= scd->lastbit) { /* Oh well */ } return -1; } scd->buf[0] = scd->buf[scd->last_byte-2]; scd->buf[1] = scd->buf[scd->last_byte-1]; if ((count = GetDataBlock(fd, &scd->buf[2], ZeroDataBlockP)) <= 0) scd->done = TRUE; scd->last_byte = 2 + count; scd->curbit = (scd->curbit - scd->lastbit) + 16; scd->lastbit = (2+count)*8 ; } if ((scd->curbit + code_size - 1) >= (CSD_BUF_SIZE * 8)) { ret = -1; } else { ret = 0; for (i = scd->curbit, j = 0; j < code_size; ++i, ++j) { ret |= ((scd->buf[i / 8] & (1 << (i % 8))) != 0) << j; } } scd->curbit += code_size; return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-681'], 'message': 'Fixed bug #75571: Potential infinite loop in gdImageCreateFromGifCtx Due to a signedness confusion in `GetCode_` a corrupt GIF file can trigger an infinite loop. Furthermore we make sure that a GIF without any palette entries is treated as invalid *after* open palette entries have been removed.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: feed_table_block_tag(struct table *tbl, char *line, struct table_mode *mode, int indent, int cmd) { int offset; if (mode->indent_level <= 0 && indent == -1) return; if (mode->indent_level >= CHAR_MAX && indent == 1) return; setwidth(tbl, mode); feed_table_inline_tag(tbl, line, mode, -1); clearcontentssize(tbl, mode); if (indent == 1) { mode->indent_level++; if (mode->indent_level <= MAX_INDENT_LEVEL) tbl->indent += INDENT_INCR; } else if (indent == -1) { mode->indent_level--; if (mode->indent_level < MAX_INDENT_LEVEL) tbl->indent -= INDENT_INCR; } offset = tbl->indent; if (cmd == HTML_DT) { if (mode->indent_level > 0 && mode->indent_level <= MAX_INDENT_LEVEL) offset -= INDENT_INCR; } if (tbl->indent > 0) { check_minimum0(tbl, 0); addcontentssize(tbl, offset); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-835'], 'message': 'Prevent negative indent value in feed_table_block_tag() Bug-Debian: https://github.com/tats/w3m/issues/88'</s>
<s>[INST] Given the following code containing errors, provide 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 js_Ast *callexp(js_State *J) { js_Ast *a = newexp(J); loop: if (jsP_accept(J, '.')) { a = EXP2(MEMBER, a, identifiername(J)); goto loop; } if (jsP_accept(J, '[')) { a = EXP2(INDEX, a, expression(J, 0)); jsP_expect(J, ']'); goto loop; } if (jsP_accept(J, '(')) { a = EXP2(CALL, a, arguments(J)); jsP_expect(J, ')'); goto loop; } return a; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-674'], 'message': 'Guard binary expressions from too much recursion.'</s>
<s>[INST] Given the following code containing errors, provide 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 i8042_stop(struct serio *serio) { struct i8042_port *port = serio->port_data; port->exists = false; /* * We synchronize with both AUX and KBD IRQs because there is * a (very unlikely) chance that AUX IRQ is raised for KBD port * and vice versa. */ synchronize_irq(I8042_AUX_IRQ); synchronize_irq(I8042_KBD_IRQ); port->serio = NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Input: i8042 - fix crash at boot time The driver checks port->exists twice in i8042_interrupt(), first when trying to assign temporary "serio" variable, and second time when deciding whether it should call serio_interrupt(). The value of port->exists may change between the 2 checks, and we may end up calling serio_interrupt() with a NULL pointer: BUG: unable to handle kernel NULL pointer dereference at 0000000000000050 IP: [<ffffffff8150feaf>] _spin_lock_irqsave+0x1f/0x40 PGD 0 Oops: 0002 [#1] SMP last sysfs file: CPU 0 Modules linked in: Pid: 1, comm: swapper Not tainted 2.6.32-358.el6.x86_64 #1 QEMU Standard PC (i440FX + PIIX, 1996) RIP: 0010:[<ffffffff8150feaf>] [<ffffffff8150feaf>] _spin_lock_irqsave+0x1f/0x40 RSP: 0018:ffff880028203cc0 EFLAGS: 00010082 RAX: 0000000000010000 RBX: 0000000000000000 RCX: 0000000000000000 RDX: 0000000000000282 RSI: 0000000000000098 RDI: 0000000000000050 RBP: ffff880028203cc0 R08: ffff88013e79c000 R09: ffff880028203ee0 R10: 0000000000000298 R11: 0000000000000282 R12: 0000000000000050 R13: 0000000000000000 R14: 0000000000000000 R15: 0000000000000098 FS: 0000000000000000(0000) GS:ffff880028200000(0000) knlGS:0000000000000000 CS: 0010 DS: 0018 ES: 0018 CR0: 000000008005003b CR2: 0000000000000050 CR3: 0000000001a85000 CR4: 00000000001407f0 DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000 DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400 Process swapper (pid: 1, threadinfo ffff88013e79c000, task ffff88013e79b500) Stack: ffff880028203d00 ffffffff813de186 ffffffffffffff02 0000000000000000 <d> 0000000000000000 0000000000000000 0000000000000000 0000000000000098 <d> ffff880028203d70 ffffffff813e0162 ffff880028203d20 ffffffff8103b8ac Call Trace: <IRQ> [<ffffffff813de186>] serio_interrupt+0x36/0xa0 [<ffffffff813e0162>] i8042_interrupt+0x132/0x3a0 [<ffffffff8103b8ac>] ? kvm_clock_read+0x1c/0x20 [<ffffffff8103b8b9>] ? kvm_clock_get_cycles+0x9/0x10 [<ffffffff810e1640>] handle_IRQ_event+0x60/0x170 [<ffffffff8103b154>] ? kvm_guest_apic_eoi_write+0x44/0x50 [<ffffffff810e3d8e>] handle_edge_irq+0xde/0x180 [<ffffffff8100de89>] handle_irq+0x49/0xa0 [<ffffffff81516c8c>] do_IRQ+0x6c/0xf0 [<ffffffff8100b9d3>] ret_from_intr+0x0/0x11 [<ffffffff81076f63>] ? __do_softirq+0x73/0x1e0 [<ffffffff8109b75b>] ? hrtimer_interrupt+0x14b/0x260 [<ffffffff8100c1cc>] ? call_softirq+0x1c/0x30 [<ffffffff8100de05>] ? do_softirq+0x65/0xa0 [<ffffffff81076d95>] ? irq_exit+0x85/0x90 [<ffffffff81516d80>] ? smp_apic_timer_interrupt+0x70/0x9b [<ffffffff8100bb93>] ? apic_timer_interrupt+0x13/0x20 To avoid the issue let's change the second check to test whether serio is NULL or not. Also, let's take i8042_lock in i8042_start() and i8042_stop() instead of trying to be overly smart and using memory barriers. Signed-off-by: Chen Hong <chenhong3@huawei.com> [dtor: take lock in i8042_start()/i8042_stop()] Cc: stable@vger.kernel.org Signed-off-by: Dmitry Torokhov <dmitry.torokhov@gmail.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 skb_gso_validate_mtu(const struct sk_buff *skb, unsigned int mtu) { const struct skb_shared_info *shinfo = skb_shinfo(skb); const struct sk_buff *iter; unsigned int hlen; hlen = skb_gso_network_seglen(skb); if (shinfo->gso_size != GSO_BY_FRAGS) return hlen <= mtu; /* Undo this so we can re-use header sizes */ hlen -= GSO_BY_FRAGS; skb_walk_frags(skb, iter) { if (hlen + skb_headlen(iter) > mtu) return false; } return true; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'net: create skb_gso_validate_mac_len() If you take a GSO skb, and split it into packets, will the MAC length (L2 + L3 + L4 headers + payload) of those packets be small enough to fit within a given length? Move skb_gso_mac_seglen() to skbuff.h with other related functions like skb_gso_network_seglen() so we can use it, and then create skb_gso_validate_mac_len to do the full calculation. Signed-off-by: Daniel Axtens <dja@axtens.net> 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: side_in_cb (GSocket *socket, GIOCondition condition, gpointer user_data) { ProxySide *side = user_data; FlatpakProxyClient *client = side->client; GError *error = NULL; Buffer *buffer; gboolean retval = G_SOURCE_CONTINUE; g_object_ref (client); while (!side->closed) { if (!side->got_first_byte) buffer = buffer_new (1, NULL); else if (!client->authenticated) buffer = buffer_new (64, NULL); else buffer = side->current_read_buffer; if (!buffer_read (side, buffer, socket)) { if (buffer != side->current_read_buffer) buffer_unref (buffer); break; } if (!client->authenticated) { if (buffer->pos > 0) { gboolean found_auth_end = FALSE; gsize extra_data; buffer->size = buffer->pos; if (!side->got_first_byte) { buffer->send_credentials = TRUE; side->got_first_byte = TRUE; } /* Look for end of authentication mechanism */ else if (side == &client->client_side) { gssize auth_end = find_auth_end (client, buffer); if (auth_end >= 0) { found_auth_end = TRUE; buffer->size = auth_end; extra_data = buffer->pos - buffer->size; /* We may have gotten some extra data which is not part of the auth handshake, keep it for the next iteration. */ if (extra_data > 0) side->extra_input_data = g_bytes_new (buffer->data + buffer->size, extra_data); } } got_buffer_from_side (side, buffer); if (found_auth_end) client->authenticated = TRUE; } else { buffer_unref (buffer); } } else if (buffer->pos == buffer->size) { if (buffer == &side->header_buffer) { gssize required; required = g_dbus_message_bytes_needed (buffer->data, buffer->size, &error); if (required < 0) { g_warning ("Invalid message header read"); side_closed (side); } else { side->current_read_buffer = buffer_new (required, buffer); } } else { got_buffer_from_side (side, buffer); side->header_buffer.pos = 0; side->current_read_buffer = &side->header_buffer; } } } if (side->closed) { side->in_source = NULL; retval = G_SOURCE_REMOVE; } g_object_unref (client); return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-436'], 'message': 'Fix vulnerability in dbus proxy During the authentication all client data is directly forwarded to the dbus daemon as is, until we detect the BEGIN command after which we start filtering the binary dbus protocol. Unfortunately the detection of the BEGIN command in the proxy did not exactly match the detection in the dbus daemon. A BEGIN followed by a space or tab was considered ok in the daemon but not by the proxy. This could be exploited to send arbitrary dbus messages to the host, which can be used to break out of the sandbox. This was noticed by Gabriel Campana of The Google Security Team. This fix makes the detection of the authentication phase end match the dbus code. In addition we duplicate the authentication line validation from dbus, which includes ensuring all data is ASCII, and limiting the size of a line to 16k. In fact, we add some extra stringent checks, disallowing ASCII control chars and requiring that auth lines start with a capital letter.'</s>
<s>[INST] Given the following code containing errors, provide 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 amd_gpio_probe(struct platform_device *pdev) { int ret = 0; int irq_base; struct resource *res; struct amd_gpio *gpio_dev; gpio_dev = devm_kzalloc(&pdev->dev, sizeof(struct amd_gpio), GFP_KERNEL); if (!gpio_dev) return -ENOMEM; spin_lock_init(&gpio_dev->lock); res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) { dev_err(&pdev->dev, "Failed to get gpio io resource.\n"); return -EINVAL; } gpio_dev->base = devm_ioremap_nocache(&pdev->dev, res->start, resource_size(res)); if (!gpio_dev->base) return -ENOMEM; irq_base = platform_get_irq(pdev, 0); if (irq_base < 0) { dev_err(&pdev->dev, "Failed to get gpio IRQ.\n"); return -EINVAL; } gpio_dev->pdev = pdev; gpio_dev->gc.direction_input = amd_gpio_direction_input; gpio_dev->gc.direction_output = amd_gpio_direction_output; gpio_dev->gc.get = amd_gpio_get_value; gpio_dev->gc.set = amd_gpio_set_value; gpio_dev->gc.set_debounce = amd_gpio_set_debounce; gpio_dev->gc.dbg_show = amd_gpio_dbg_show; gpio_dev->gc.base = 0; gpio_dev->gc.label = pdev->name; gpio_dev->gc.owner = THIS_MODULE; gpio_dev->gc.parent = &pdev->dev; gpio_dev->gc.ngpio = TOTAL_NUMBER_OF_PINS; #if defined(CONFIG_OF_GPIO) gpio_dev->gc.of_node = pdev->dev.of_node; #endif gpio_dev->groups = kerncz_groups; gpio_dev->ngroups = ARRAY_SIZE(kerncz_groups); amd_pinctrl_desc.name = dev_name(&pdev->dev); gpio_dev->pctrl = pinctrl_register(&amd_pinctrl_desc, &pdev->dev, gpio_dev); if (IS_ERR(gpio_dev->pctrl)) { dev_err(&pdev->dev, "Couldn't register pinctrl driver\n"); return PTR_ERR(gpio_dev->pctrl); } ret = gpiochip_add_data(&gpio_dev->gc, gpio_dev); if (ret) goto out1; ret = gpiochip_add_pin_range(&gpio_dev->gc, dev_name(&pdev->dev), 0, 0, TOTAL_NUMBER_OF_PINS); if (ret) { dev_err(&pdev->dev, "Failed to add pin range\n"); goto out2; } ret = gpiochip_irqchip_add(&gpio_dev->gc, &amd_gpio_irqchip, 0, handle_simple_irq, IRQ_TYPE_NONE); if (ret) { dev_err(&pdev->dev, "could not add irqchip\n"); ret = -ENODEV; goto out2; } gpiochip_set_chained_irqchip(&gpio_dev->gc, &amd_gpio_irqchip, irq_base, amd_gpio_irq_handler); platform_set_drvdata(pdev, gpio_dev); dev_dbg(&pdev->dev, "amd gpio driver loaded\n"); return ret; out2: gpiochip_remove(&gpio_dev->gc); out1: pinctrl_unregister(gpio_dev->pctrl); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'pinctrl: amd: Use devm_pinctrl_register() for pinctrl registration Use devm_pinctrl_register() for pin control registration and clean error path. Signed-off-by: Laxman Dewangan <ldewangan@nvidia.com> Signed-off-by: Linus Walleij <linus.walleij@linaro.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: intuit_diff_type (bool need_header, mode_t *p_file_type) { file_offset this_line = 0; file_offset first_command_line = -1; char first_ed_command_letter = 0; lin fcl_line = 0; /* Pacify 'gcc -W'. */ bool this_is_a_command = false; bool stars_this_line = false; bool extended_headers = false; enum nametype i; struct stat st[3]; int stat_errno[3]; int version_controlled[3]; enum diff retval; mode_t file_type; size_t indent = 0; for (i = OLD; i <= INDEX; i++) if (p_name[i]) { free (p_name[i]); p_name[i] = 0; } for (i = 0; i < ARRAY_SIZE (invalid_names); i++) invalid_names[i] = NULL; for (i = OLD; i <= NEW; i++) if (p_timestr[i]) { free(p_timestr[i]); p_timestr[i] = 0; } for (i = OLD; i <= NEW; i++) if (p_sha1[i]) { free (p_sha1[i]); p_sha1[i] = 0; } p_git_diff = false; for (i = OLD; i <= NEW; i++) { p_mode[i] = 0; p_copy[i] = false; p_rename[i] = false; } /* Ed and normal format patches don't have filename headers. */ if (diff_type == ED_DIFF || diff_type == NORMAL_DIFF) need_header = false; version_controlled[OLD] = -1; version_controlled[NEW] = -1; version_controlled[INDEX] = -1; p_rfc934_nesting = 0; p_timestamp[OLD].tv_sec = p_timestamp[NEW].tv_sec = -1; p_says_nonexistent[OLD] = p_says_nonexistent[NEW] = 0; Fseek (pfp, p_base, SEEK_SET); p_input_line = p_bline - 1; for (;;) { char *s; char *t; file_offset previous_line = this_line; bool last_line_was_command = this_is_a_command; bool stars_last_line = stars_this_line; size_t indent_last_line = indent; char ed_command_letter; bool strip_trailing_cr; size_t chars_read; indent = 0; this_line = file_tell (pfp); chars_read = pget_line (0, 0, false, false); if (chars_read == (size_t) -1) xalloc_die (); if (! chars_read) { if (first_ed_command_letter) { /* nothing but deletes!? */ p_start = first_command_line; p_sline = fcl_line; retval = ED_DIFF; goto scan_exit; } else { p_start = this_line; p_sline = p_input_line; if (extended_headers) { /* Patch contains no hunks; any diff type will do. */ retval = UNI_DIFF; goto scan_exit; } return NO_DIFF; } } strip_trailing_cr = 2 <= chars_read && buf[chars_read - 2] == '\r'; for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) { if (*s == '\t') indent = (indent + 8) & ~7; else indent++; } if (ISDIGIT (*s)) { for (t = s + 1; ISDIGIT (*t) || *t == ','; t++) /* do nothing */ ; if (*t == 'd' || *t == 'c' || *t == 'a') { for (t++; ISDIGIT (*t) || *t == ','; t++) /* do nothing */ ; for (; *t == ' ' || *t == '\t'; t++) /* do nothing */ ; if (*t == '\r') t++; this_is_a_command = (*t == '\n'); } } if (! need_header && first_command_line < 0 && ((ed_command_letter = get_ed_command_letter (s)) || this_is_a_command)) { first_command_line = this_line; first_ed_command_letter = ed_command_letter; fcl_line = p_input_line; p_indent = indent; /* assume this for now */ p_strip_trailing_cr = strip_trailing_cr; } if (!stars_last_line && strnEQ(s, "*** ", 4)) { fetchname (s+4, strippath, &p_name[OLD], &p_timestr[OLD], &p_timestamp[OLD]); need_header = false; } else if (strnEQ(s, "+++ ", 4)) { /* Swap with NEW below. */ fetchname (s+4, strippath, &p_name[OLD], &p_timestr[OLD], &p_timestamp[OLD]); need_header = false; p_strip_trailing_cr = strip_trailing_cr; } else if (strnEQ(s, "Index:", 6)) { fetchname (s+6, strippath, &p_name[INDEX], (char **) 0, NULL); need_header = false; p_strip_trailing_cr = strip_trailing_cr; } else if (strnEQ(s, "Prereq:", 7)) { for (t = s + 7; ISSPACE ((unsigned char) *t); t++) /* do nothing */ ; revision = t; for (t = revision; *t; t++) if (ISSPACE ((unsigned char) *t)) { char const *u; for (u = t + 1; ISSPACE ((unsigned char) *u); u++) /* do nothing */ ; if (*u) { char numbuf[LINENUM_LENGTH_BOUND + 1]; say ("Prereq: with multiple words at line %s of patch\n", format_linenum (numbuf, this_line)); } break; } if (t == revision) revision = 0; else { char oldc = *t; *t = '\0'; revision = xstrdup (revision); *t = oldc; } } else if (strnEQ (s, "diff --git ", 11)) { char const *u; if (extended_headers) { p_start = this_line; p_sline = p_input_line; /* Patch contains no hunks; any diff type will do. */ retval = UNI_DIFF; goto scan_exit; } for (i = OLD; i <= NEW; i++) { free (p_name[i]); p_name[i] = 0; } if (! ((p_name[OLD] = parse_name (s + 11, strippath, &u)) && ISSPACE ((unsigned char) *u) && (p_name[NEW] = parse_name (u, strippath, &u)) && (u = skip_spaces (u), ! *u))) for (i = OLD; i <= NEW; i++) { free (p_name[i]); p_name[i] = 0; } p_git_diff = true; need_header = false; } else if (p_git_diff && strnEQ (s, "index ", 6)) { char const *u, *v; if ((u = skip_hex_digits (s + 6)) && u[0] == '.' && u[1] == '.' && (v = skip_hex_digits (u + 2)) && (! *v || ISSPACE ((unsigned char) *v))) { get_sha1(&p_sha1[OLD], s + 6, u); get_sha1(&p_sha1[NEW], u + 2, v); p_says_nonexistent[OLD] = sha1_says_nonexistent (p_sha1[OLD]); p_says_nonexistent[NEW] = sha1_says_nonexistent (p_sha1[NEW]); if (*(v = skip_spaces (v))) p_mode[OLD] = p_mode[NEW] = fetchmode (v); extended_headers = true; } } else if (p_git_diff && strnEQ (s, "old mode ", 9)) { p_mode[OLD] = fetchmode (s + 9); extended_headers = true; } else if (p_git_diff && strnEQ (s, "new mode ", 9)) { p_mode[NEW] = fetchmode (s + 9); extended_headers = true; } else if (p_git_diff && strnEQ (s, "deleted file mode ", 18)) { p_mode[OLD] = fetchmode (s + 18); p_says_nonexistent[NEW] = 2; extended_headers = true; } else if (p_git_diff && strnEQ (s, "new file mode ", 14)) { p_mode[NEW] = fetchmode (s + 14); p_says_nonexistent[OLD] = 2; extended_headers = true; } else if (p_git_diff && strnEQ (s, "rename from ", 12)) { /* Git leaves out the prefix in the file name in this header, so we can only ignore the file name. */ p_rename[OLD] = true; extended_headers = true; } else if (p_git_diff && strnEQ (s, "rename to ", 10)) { /* Git leaves out the prefix in the file name in this header, so we can only ignore the file name. */ p_rename[NEW] = true; extended_headers = true; } else if (p_git_diff && strnEQ (s, "copy from ", 10)) { /* Git leaves out the prefix in the file name in this header, so we can only ignore the file name. */ p_copy[OLD] = true; extended_headers = true; } else if (p_git_diff && strnEQ (s, "copy to ", 8)) { /* Git leaves out the prefix in the file name in this header, so we can only ignore the file name. */ p_copy[NEW] = true; extended_headers = true; } else if (p_git_diff && strnEQ (s, "GIT binary patch", 16)) { p_start = this_line; p_sline = p_input_line; retval = GIT_BINARY_DIFF; goto scan_exit; } else { for (t = s; t[0] == '-' && t[1] == ' '; t += 2) /* do nothing */ ; if (strnEQ(t, "--- ", 4)) { struct timespec timestamp; timestamp.tv_sec = -1; fetchname (t+4, strippath, &p_name[NEW], &p_timestr[NEW], &timestamp); need_header = false; if (timestamp.tv_sec != -1) { p_timestamp[NEW] = timestamp; p_rfc934_nesting = (t - s) >> 1; } p_strip_trailing_cr = strip_trailing_cr; } } if (need_header) continue; if ((diff_type == NO_DIFF || diff_type == ED_DIFF) && first_command_line >= 0 && strEQ(s, ".\n") ) { p_start = first_command_line; p_sline = fcl_line; retval = ED_DIFF; goto scan_exit; } if ((diff_type == NO_DIFF || diff_type == UNI_DIFF) && strnEQ(s, "@@ -", 4)) { /* 'p_name', 'p_timestr', and 'p_timestamp' are backwards; swap them. */ struct timespec ti = p_timestamp[OLD]; p_timestamp[OLD] = p_timestamp[NEW]; p_timestamp[NEW] = ti; t = p_name[OLD]; p_name[OLD] = p_name[NEW]; p_name[NEW] = t; t = p_timestr[OLD]; p_timestr[OLD] = p_timestr[NEW]; p_timestr[NEW] = t; s += 4; if (s[0] == '0' && !ISDIGIT (s[1])) p_says_nonexistent[OLD] = 1 + ! p_timestamp[OLD].tv_sec; while (*s != ' ' && *s != '\n') s++; while (*s == ' ') s++; if (s[0] == '+' && s[1] == '0' && !ISDIGIT (s[2])) p_says_nonexistent[NEW] = 1 + ! p_timestamp[NEW].tv_sec; p_indent = indent; p_start = this_line; p_sline = p_input_line; retval = UNI_DIFF; if (! ((p_name[OLD] || ! p_timestamp[OLD].tv_sec) && (p_name[NEW] || ! p_timestamp[NEW].tv_sec)) && ! p_name[INDEX] && need_header) { char numbuf[LINENUM_LENGTH_BOUND + 1]; say ("missing header for unified diff at line %s of patch\n", format_linenum (numbuf, p_sline)); } goto scan_exit; } stars_this_line = strnEQ(s, "********", 8); if ((diff_type == NO_DIFF || diff_type == CONTEXT_DIFF || diff_type == NEW_CONTEXT_DIFF) && stars_last_line && indent_last_line == indent && strnEQ (s, "*** ", 4)) { s += 4; if (s[0] == '0' && !ISDIGIT (s[1])) p_says_nonexistent[OLD] = 1 + ! p_timestamp[OLD].tv_sec; /* if this is a new context diff the character just before */ /* the newline is a '*'. */ while (*s != '\n') s++; p_indent = indent; p_strip_trailing_cr = strip_trailing_cr; p_start = previous_line; p_sline = p_input_line - 1; retval = (*(s-1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF); { /* Scan the first hunk to see whether the file contents appear to have been deleted. */ file_offset saved_p_base = p_base; lin saved_p_bline = p_bline; Fseek (pfp, previous_line, SEEK_SET); p_input_line -= 2; if (another_hunk (retval, false) && ! p_repl_lines && p_newfirst == 1) p_says_nonexistent[NEW] = 1 + ! p_timestamp[NEW].tv_sec; next_intuit_at (saved_p_base, saved_p_bline); } if (! ((p_name[OLD] || ! p_timestamp[OLD].tv_sec) && (p_name[NEW] || ! p_timestamp[NEW].tv_sec)) && ! p_name[INDEX] && need_header) { char numbuf[LINENUM_LENGTH_BOUND + 1]; say ("missing header for context diff at line %s of patch\n", format_linenum (numbuf, p_sline)); } goto scan_exit; } if ((diff_type == NO_DIFF || diff_type == NORMAL_DIFF) && last_line_was_command && (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2)) ) { p_start = previous_line; p_sline = p_input_line - 1; p_indent = indent; retval = NORMAL_DIFF; goto scan_exit; } } scan_exit: /* The old, new, or old and new file types may be defined. When both file types are defined, make sure they are the same, or else assume we do not know the file type. */ file_type = p_mode[OLD] & S_IFMT; if (file_type) { mode_t new_file_type = p_mode[NEW] & S_IFMT; if (new_file_type && file_type != new_file_type) file_type = 0; } else { file_type = p_mode[NEW] & S_IFMT; if (! file_type) file_type = S_IFREG; } *p_file_type = file_type; /* To intuit 'inname', the name of the file to patch, use the algorithm specified by POSIX 1003.1-2001 XCU lines 25680-26599 (with some modifications if posixly_correct is zero): - Take the old and new names from the context header if present, and take the index name from the 'Index:' line if present and if either the old and new names are both absent or posixly_correct is nonzero. Consider the file names to be in the order (old, new, index). - If some named files exist, use the first one if posixly_correct is nonzero, the best one otherwise. - If patch_get is nonzero, and no named files exist, but an RCS or SCCS master file exists, use the first named file with an RCS or SCCS master. - If no named files exist, no RCS or SCCS master was found, some names are given, posixly_correct is zero, and the patch appears to create a file, then use the best name requiring the creation of the fewest directories. - Otherwise, report failure by setting 'inname' to 0; this causes our invoker to ask the user for a file name. */ i = NONE; if (!inname) { enum nametype i0 = NONE; if (! posixly_correct && (p_name[OLD] || p_name[NEW]) && p_name[INDEX]) { free (p_name[INDEX]); p_name[INDEX] = 0; } for (i = OLD; i <= INDEX; i++) if (p_name[i]) { if (i0 != NONE && strcmp (p_name[i0], p_name[i]) == 0) { /* It's the same name as before; reuse stat results. */ stat_errno[i] = stat_errno[i0]; if (! stat_errno[i]) st[i] = st[i0]; } else { stat_errno[i] = stat_file (p_name[i], &st[i]); if (! stat_errno[i]) { if (lookup_file_id (&st[i]) == DELETE_LATER) stat_errno[i] = ENOENT; else if (posixly_correct && name_is_valid (p_name[i])) break; } } i0 = i; } if (! posixly_correct) { /* The best of all existing files. */ i = best_name (p_name, stat_errno); if (i == NONE && patch_get) { enum nametype nope = NONE; for (i = OLD; i <= INDEX; i++) if (p_name[i]) { char const *cs; char *getbuf; char *diffbuf; bool readonly = (outfile && strcmp (outfile, p_name[i]) != 0); if (nope == NONE || strcmp (p_name[nope], p_name[i]) != 0) { cs = (version_controller (p_name[i], readonly, (struct stat *) 0, &getbuf, &diffbuf)); version_controlled[i] = !! cs; if (cs) { if (version_get (p_name[i], cs, false, readonly, getbuf, &st[i])) stat_errno[i] = 0; else version_controlled[i] = 0; free (getbuf); free (diffbuf); if (! stat_errno[i]) break; } } nope = i; } } if (i0 != NONE && (i == NONE || (st[i].st_mode & S_IFMT) == file_type) && maybe_reverse (p_name[i == NONE ? i0 : i], i == NONE, i == NONE || st[i].st_size == 0) && i == NONE) i = i0; if (i == NONE && p_says_nonexistent[reverse]) { int newdirs[3]; int newdirs_min = INT_MAX; int distance_from_minimum[3]; for (i = OLD; i <= INDEX; i++) if (p_name[i]) { newdirs[i] = (prefix_components (p_name[i], false) - prefix_components (p_name[i], true)); if (newdirs[i] < newdirs_min) newdirs_min = newdirs[i]; } for (i = OLD; i <= INDEX; i++) if (p_name[i]) distance_from_minimum[i] = newdirs[i] - newdirs_min; /* The best of the filenames which create the fewest directories. */ i = best_name (p_name, distance_from_minimum); } } } if ((pch_rename () || pch_copy ()) && ! inname && ! ((i == OLD || i == NEW) && p_name[! reverse] && name_is_valid (p_name[! reverse]))) { say ("Cannot %s file without two valid file names\n", pch_rename () ? "rename" : "copy"); skip_rest_of_patch = true; } if (i == NONE) { if (inname) { inerrno = stat_file (inname, &instat); if (inerrno || (instat.st_mode & S_IFMT) == file_type) maybe_reverse (inname, inerrno, inerrno || instat.st_size == 0); } else inerrno = -1; } else { inname = xstrdup (p_name[i]); inerrno = stat_errno[i]; invc = version_controlled[i]; instat = st[i]; } return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fix segfault with mangled rename patch http://savannah.gnu.org/bugs/?53132 * src/pch.c (intuit_diff_type): Ensure that two filenames are specified for renames and copies (fix the existing check).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: check_owner_password_V4(std::string& user_password, std::string const& owner_password, QPDF::EncryptionData const& data) { // Algorithm 3.7 from the PDF 1.7 Reference Manual unsigned char key[OU_key_bytes_V4]; compute_O_rc4_key(user_password, owner_password, data, key); unsigned char O_data[key_bytes]; memcpy(O_data, QUtil::unsigned_char_pointer(data.getO()), key_bytes); iterate_rc4(O_data, key_bytes, key, data.getLengthBytes(), (data.getR() >= 3) ? 20 : 1, true); std::string new_user_password = std::string(reinterpret_cast<char*>(O_data), key_bytes); bool result = false; if (check_user_password(new_user_password, data)) { result = true; user_password = new_user_password; } return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Pad keys to avoid memory errors (fixes #147)'</s>
<s>[INST] Given the following code containing errors, provide 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 parse_version(std::string const& full_version_string, std::string& version, int& extension_level) { PointerHolder<char> vp(true, QUtil::copy_string(full_version_string)); char* v = vp.getPointer(); char* p1 = strchr(v, '.'); char* p2 = (p1 ? strchr(1 + p1, '.') : 0); if (p2 && *(p2 + 1)) { *p2++ = '\0'; extension_level = atoi(p2); } version = v; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Replace all atoi calls with QUtil::string_to_int The latter catches underflow/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: gplotAddPlot(GPLOT *gplot, NUMA *nax, NUMA *nay, l_int32 plotstyle, const char *plottitle) { char buf[L_BUF_SIZE]; char emptystring[] = ""; char *datastr, *title; l_int32 n, i; l_float32 valx, valy, startx, delx; SARRAY *sa; PROCNAME("gplotAddPlot"); if (!gplot) return ERROR_INT("gplot not defined", procName, 1); if (!nay) return ERROR_INT("nay not defined", procName, 1); if (plotstyle < 0 || plotstyle >= NUM_GPLOT_STYLES) return ERROR_INT("invalid plotstyle", procName, 1); if ((n = numaGetCount(nay)) == 0) return ERROR_INT("no points to plot", procName, 1); if (nax && (n != numaGetCount(nax))) return ERROR_INT("nax and nay sizes differ", procName, 1); if (n == 1 && plotstyle == GPLOT_LINES) { L_INFO("only 1 pt; changing style to points\n", procName); plotstyle = GPLOT_POINTS; } /* Save plotstyle and plottitle */ numaGetParameters(nay, &startx, &delx); numaAddNumber(gplot->plotstyles, plotstyle); if (plottitle) { title = stringNew(plottitle); sarrayAddString(gplot->plottitles, title, L_INSERT); } else { sarrayAddString(gplot->plottitles, emptystring, L_COPY); } /* Generate and save data filename */ gplot->nplots++; snprintf(buf, L_BUF_SIZE, "%s.data.%d", gplot->rootname, gplot->nplots); sarrayAddString(gplot->datanames, buf, L_COPY); /* Generate data and save as a string */ sa = sarrayCreate(n); for (i = 0; i < n; i++) { if (nax) numaGetFValue(nax, i, &valx); else valx = startx + i * delx; numaGetFValue(nay, i, &valy); snprintf(buf, L_BUF_SIZE, "%f %f\n", valx, valy); sarrayAddString(sa, buf, L_COPY); } datastr = sarrayToString(sa, 0); sarrayAddString(gplot->plotdata, datastr, L_INSERT); sarrayDestroy(&sa); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Security fixes: expect final changes for release 1.75.3. * Fixed a debian security issue with fscanf() reading a string with possible buffer overflow. * There were also a few similar situations 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 void sig_chatnet_read(IRC_CHATNET_REC *rec, CONFIG_NODE *node) { if (!IS_IRC_CHATNET(rec)) return; rec->usermode = g_strdup(config_node_get_str(node, "usermode", NULL)); rec->max_cmds_at_once = config_node_get_int(node, "cmdmax", 0); rec->cmd_queue_speed = config_node_get_int(node, "cmdspeed", 0); rec->max_query_chans = config_node_get_int(node, "max_query_chans", 0); rec->max_kicks = config_node_get_int(node, "max_kicks", 0); rec->max_msgs = config_node_get_int(node, "max_msgs", 0); rec->max_modes = config_node_get_int(node, "max_modes", 0); rec->max_whois = config_node_get_int(node, "max_whois", 0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'SASL support The only supported methods are PLAIN and EXTERNAL, the latter is untested as of now. The code gets the values from the keys named sasl_{mechanism,username,password} specified for each chatnet.'</s>
<s>[INST] Given the following code containing errors, provide 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 sasl_success(IRC_SERVER_REC *server, const char *data, const char *from) { if (server->sasl_timeout != 0) { g_source_remove(server->sasl_timeout); server->sasl_timeout = 0; } server->sasl_success = TRUE; signal_emit("server sasl success", 1, server); /* The authentication succeeded, time to finish the CAP negotiation */ cap_finish_negotiation(server); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Merge branch 'security' into 'master' Security See merge request irssi/irssi!34 (cherry picked from commit b0d9cb33cd9ef9da7c331409e8b7c57a6f3aef3f)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: valid_host(cupsd_client_t *con) /* I - Client connection */ { cupsd_alias_t *a; /* Current alias */ cupsd_netif_t *netif; /* Current network interface */ const char *end; /* End character */ char *ptr; /* Pointer into host value */ /* * Copy the Host: header for later use... */ strlcpy(con->clientname, httpGetField(con->http, HTTP_FIELD_HOST), sizeof(con->clientname)); if ((ptr = strrchr(con->clientname, ':')) != NULL && !strchr(ptr, ']')) { *ptr++ = '\0'; con->clientport = atoi(ptr); } else con->clientport = con->serverport; /* * Then validate... */ if (httpAddrLocalhost(httpGetAddress(con->http))) { /* * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical * addresses when accessing CUPS via the loopback interface... */ return (!_cups_strcasecmp(con->clientname, "localhost") || !_cups_strcasecmp(con->clientname, "localhost.") || #ifdef __linux !_cups_strcasecmp(con->clientname, "localhost.localdomain") || #endif /* __linux */ !strcmp(con->clientname, "127.0.0.1") || !strcmp(con->clientname, "[::1]")); } #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI) /* * Check if the hostname is something.local (Bonjour); if so, allow it. */ if ((end = strrchr(con->clientname, '.')) != NULL && end > con->clientname && !end[1]) { /* * "." on end, work back to second-to-last "."... */ for (end --; end > con->clientname && *end != '.'; end --); } if (end && (!_cups_strcasecmp(end, ".local") || !_cups_strcasecmp(end, ".local."))) return (1); #endif /* HAVE_DNSSD || HAVE_AVAHI */ /* * Check if the hostname is an IP address... */ if (isdigit(con->clientname[0] & 255) || con->clientname[0] == '[') { /* * Possible IPv4/IPv6 address... */ http_addrlist_t *addrlist; /* List of addresses */ if ((addrlist = httpAddrGetList(con->clientname, AF_UNSPEC, NULL)) != NULL) { /* * Good IPv4/IPv6 address... */ httpAddrFreeList(addrlist); return (1); } } /* * Check for (alias) name matches... */ for (a = (cupsd_alias_t *)cupsArrayFirst(ServerAlias); a; a = (cupsd_alias_t *)cupsArrayNext(ServerAlias)) { /* * "ServerAlias *" allows all host values through... */ if (!strcmp(a->name, "*")) return (1); if (!_cups_strncasecmp(con->clientname, a->name, a->namelen)) { /* * Prefix matches; check the character at the end - it must be "." or nul. */ end = con->clientname + a->namelen; if (!*end || (*end == '.' && !end[1])) return (1); } } #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI) for (a = (cupsd_alias_t *)cupsArrayFirst(DNSSDAlias); a; a = (cupsd_alias_t *)cupsArrayNext(DNSSDAlias)) { /* * "ServerAlias *" allows all host values through... */ if (!strcmp(a->name, "*")) return (1); if (!_cups_strncasecmp(con->clientname, a->name, a->namelen)) { /* * Prefix matches; check the character at the end - it must be "." or nul. */ end = con->clientname + a->namelen; if (!*end || (*end == '.' && !end[1])) return (1); } } #endif /* HAVE_DNSSD || HAVE_AVAHI */ /* * Check for interface hostname matches... */ for (netif = (cupsd_netif_t *)cupsArrayFirst(NetIFList); netif; netif = (cupsd_netif_t *)cupsArrayNext(NetIFList)) { if (!_cups_strncasecmp(con->clientname, netif->hostname, netif->hostlen)) { /* * Prefix matches; check the character at the end - it must be "." or nul. */ end = con->clientname + netif->hostlen; if (!*end || (*end == '.' && !end[1])) return (1); } } return (0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-290'], 'message': 'Don't treat "localhost.localdomain" as an allowed replacement for localhost, since it isn't.'</s>
<s>[INST] Given the following code containing errors, provide 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 get_v4l2_ext_controls32(struct file *file, struct v4l2_ext_controls *kp, struct v4l2_ext_controls32 __user *up) { struct v4l2_ext_control32 __user *ucontrols; struct v4l2_ext_control __user *kcontrols; unsigned int n; compat_caddr_t p; if (!access_ok(VERIFY_READ, up, sizeof(*up)) || get_user(kp->which, &up->which) || get_user(kp->count, &up->count) || get_user(kp->error_idx, &up->error_idx) || copy_from_user(kp->reserved, up->reserved, sizeof(kp->reserved))) return -EFAULT; if (kp->count == 0) { kp->controls = NULL; return 0; } else if (kp->count > V4L2_CID_MAX_CTRLS) { return -EINVAL; } if (get_user(p, &up->controls)) return -EFAULT; ucontrols = compat_ptr(p); if (!access_ok(VERIFY_READ, ucontrols, kp->count * sizeof(*ucontrols))) return -EFAULT; kcontrols = compat_alloc_user_space(kp->count * sizeof(*kcontrols)); kp->controls = (__force struct v4l2_ext_control *)kcontrols; for (n = 0; n < kp->count; n++) { u32 id; if (copy_in_user(kcontrols, ucontrols, sizeof(*ucontrols))) return -EFAULT; if (get_user(id, &kcontrols->id)) return -EFAULT; if (ctrl_is_pointer(file, id)) { void __user *s; if (get_user(p, &ucontrols->string)) return -EFAULT; s = compat_ptr(p); if (put_user(s, &kcontrols->string)) return -EFAULT; } ucontrols++; kcontrols++; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'media: v4l2-compat-ioctl32.c: refactor compat ioctl32 logic The 32-bit compat v4l2 ioctl handling is implemented based on its 64-bit equivalent. It converts 32-bit data structures into its 64-bit equivalents and needs to provide the data to the 64-bit ioctl in user space memory which is commonly allocated using compat_alloc_user_space(). However, due to how that function is implemented, it can only be called a single time for every syscall invocation. Supposedly to avoid this limitation, the existing code uses a mix of memory from the kernel stack and memory allocated through compat_alloc_user_space(). Under normal circumstances, this would not work, because the 64-bit ioctl expects all pointers to point to user space memory. As a workaround, set_fs(KERNEL_DS) is called to temporarily disable this extra safety check and allow kernel pointers. However, this might introduce a security vulnerability: The result of the 32-bit to 64-bit conversion is writeable by user space because the output buffer has been allocated via compat_alloc_user_space(). A malicious user space process could then manipulate pointers inside this output buffer, and due to the previous set_fs(KERNEL_DS) call, functions like get_user() or put_user() no longer prevent kernel memory access. The new approach is to pre-calculate the total amount of user space memory that is needed, allocate it using compat_alloc_user_space() and then divide up the allocated memory to accommodate all data structures that need to be converted. An alternative approach would have been to retain the union type karg that they allocated on the kernel stack in do_video_ioctl(), copy all data from user space into karg and then back to user space. However, we decided against this approach because it does not align with other compat syscall implementations. Instead, we tried to replicate the get_user/put_user pairs as found in other places in the kernel: if (get_user(clipcount, &up->clipcount) || put_user(clipcount, &kp->clipcount)) return -EFAULT; Notes from hans.verkuil@cisco.com: This patch was taken from: https://github.com/LineageOS/android_kernel_samsung_apq8084/commit/97b733953c06e4f0398ade18850f0817778255f7 Clearly nobody could be bothered to upstream this patch or at minimum tell us :-( We only heard about this a week ago. This patch was rebased and cleaned up. Compared to the original I also swapped the order of the convert_in_user arguments so that they matched copy_in_user. It was hard to review otherwise. I also replaced the ALLOC_USER_SPACE/ALLOC_AND_GET by a normal function. Fixes: 6b5a9492ca ("v4l: introduce string control support.") Signed-off-by: Daniel Mentz <danielmentz@google.com> Co-developed-by: Hans Verkuil <hans.verkuil@cisco.com> Acked-by: Sakari Ailus <sakari.ailus@linux.intel.com> Signed-off-by: Hans Verkuil <hans.verkuil@cisco.com> Cc: <stable@vger.kernel.org> # for v4.15 and up Signed-off-by: Mauro Carvalho Chehab <mchehab@s-opensource.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 get_v4l2_buffer32(struct v4l2_buffer *kp, struct v4l2_buffer32 __user *up) { struct v4l2_plane32 __user *uplane32; struct v4l2_plane __user *uplane; compat_caddr_t p; int ret; if (!access_ok(VERIFY_READ, up, sizeof(*up)) || get_user(kp->index, &up->index) || get_user(kp->type, &up->type) || get_user(kp->flags, &up->flags) || get_user(kp->memory, &up->memory) || get_user(kp->length, &up->length)) return -EFAULT; if (V4L2_TYPE_IS_OUTPUT(kp->type)) if (get_user(kp->bytesused, &up->bytesused) || get_user(kp->field, &up->field) || get_user(kp->timestamp.tv_sec, &up->timestamp.tv_sec) || get_user(kp->timestamp.tv_usec, &up->timestamp.tv_usec)) return -EFAULT; if (V4L2_TYPE_IS_MULTIPLANAR(kp->type)) { unsigned int num_planes; if (kp->length == 0) { kp->m.planes = NULL; /* num_planes == 0 is legal, e.g. when userspace doesn't * need planes array on DQBUF*/ return 0; } else if (kp->length > VIDEO_MAX_PLANES) { return -EINVAL; } if (get_user(p, &up->m.planes)) return -EFAULT; uplane32 = compat_ptr(p); if (!access_ok(VERIFY_READ, uplane32, kp->length * sizeof(*uplane32))) return -EFAULT; /* We don't really care if userspace decides to kill itself * by passing a very big num_planes value */ uplane = compat_alloc_user_space(kp->length * sizeof(*uplane)); kp->m.planes = (__force struct v4l2_plane *)uplane; for (num_planes = 0; num_planes < kp->length; num_planes++) { ret = get_v4l2_plane32(uplane, uplane32, kp->memory); if (ret) return ret; ++uplane; ++uplane32; } } else { switch (kp->memory) { case V4L2_MEMORY_MMAP: case V4L2_MEMORY_OVERLAY: if (get_user(kp->m.offset, &up->m.offset)) return -EFAULT; break; case V4L2_MEMORY_USERPTR: { compat_long_t tmp; if (get_user(tmp, &up->m.userptr)) return -EFAULT; kp->m.userptr = (unsigned long)compat_ptr(tmp); } break; case V4L2_MEMORY_DMABUF: if (get_user(kp->m.fd, &up->m.fd)) return -EFAULT; break; } } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'media: v4l2-compat-ioctl32.c: refactor compat ioctl32 logic The 32-bit compat v4l2 ioctl handling is implemented based on its 64-bit equivalent. It converts 32-bit data structures into its 64-bit equivalents and needs to provide the data to the 64-bit ioctl in user space memory which is commonly allocated using compat_alloc_user_space(). However, due to how that function is implemented, it can only be called a single time for every syscall invocation. Supposedly to avoid this limitation, the existing code uses a mix of memory from the kernel stack and memory allocated through compat_alloc_user_space(). Under normal circumstances, this would not work, because the 64-bit ioctl expects all pointers to point to user space memory. As a workaround, set_fs(KERNEL_DS) is called to temporarily disable this extra safety check and allow kernel pointers. However, this might introduce a security vulnerability: The result of the 32-bit to 64-bit conversion is writeable by user space because the output buffer has been allocated via compat_alloc_user_space(). A malicious user space process could then manipulate pointers inside this output buffer, and due to the previous set_fs(KERNEL_DS) call, functions like get_user() or put_user() no longer prevent kernel memory access. The new approach is to pre-calculate the total amount of user space memory that is needed, allocate it using compat_alloc_user_space() and then divide up the allocated memory to accommodate all data structures that need to be converted. An alternative approach would have been to retain the union type karg that they allocated on the kernel stack in do_video_ioctl(), copy all data from user space into karg and then back to user space. However, we decided against this approach because it does not align with other compat syscall implementations. Instead, we tried to replicate the get_user/put_user pairs as found in other places in the kernel: if (get_user(clipcount, &up->clipcount) || put_user(clipcount, &kp->clipcount)) return -EFAULT; Notes from hans.verkuil@cisco.com: This patch was taken from: https://github.com/LineageOS/android_kernel_samsung_apq8084/commit/97b733953c06e4f0398ade18850f0817778255f7 Clearly nobody could be bothered to upstream this patch or at minimum tell us :-( We only heard about this a week ago. This patch was rebased and cleaned up. Compared to the original I also swapped the order of the convert_in_user arguments so that they matched copy_in_user. It was hard to review otherwise. I also replaced the ALLOC_USER_SPACE/ALLOC_AND_GET by a normal function. Fixes: 6b5a9492ca ("v4l: introduce string control support.") Signed-off-by: Daniel Mentz <danielmentz@google.com> Co-developed-by: Hans Verkuil <hans.verkuil@cisco.com> Acked-by: Sakari Ailus <sakari.ailus@linux.intel.com> Signed-off-by: Hans Verkuil <hans.verkuil@cisco.com> Cc: <stable@vger.kernel.org> # for v4.15 and up Signed-off-by: Mauro Carvalho Chehab <mchehab@s-opensource.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 get_v4l2_create32(struct v4l2_create_buffers *kp, struct v4l2_create_buffers32 __user *up) { if (!access_ok(VERIFY_READ, up, sizeof(*up)) || copy_from_user(kp, up, offsetof(struct v4l2_create_buffers32, format))) return -EFAULT; return __get_v4l2_format32(&kp->format, &up->format); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'media: v4l2-compat-ioctl32.c: refactor compat ioctl32 logic The 32-bit compat v4l2 ioctl handling is implemented based on its 64-bit equivalent. It converts 32-bit data structures into its 64-bit equivalents and needs to provide the data to the 64-bit ioctl in user space memory which is commonly allocated using compat_alloc_user_space(). However, due to how that function is implemented, it can only be called a single time for every syscall invocation. Supposedly to avoid this limitation, the existing code uses a mix of memory from the kernel stack and memory allocated through compat_alloc_user_space(). Under normal circumstances, this would not work, because the 64-bit ioctl expects all pointers to point to user space memory. As a workaround, set_fs(KERNEL_DS) is called to temporarily disable this extra safety check and allow kernel pointers. However, this might introduce a security vulnerability: The result of the 32-bit to 64-bit conversion is writeable by user space because the output buffer has been allocated via compat_alloc_user_space(). A malicious user space process could then manipulate pointers inside this output buffer, and due to the previous set_fs(KERNEL_DS) call, functions like get_user() or put_user() no longer prevent kernel memory access. The new approach is to pre-calculate the total amount of user space memory that is needed, allocate it using compat_alloc_user_space() and then divide up the allocated memory to accommodate all data structures that need to be converted. An alternative approach would have been to retain the union type karg that they allocated on the kernel stack in do_video_ioctl(), copy all data from user space into karg and then back to user space. However, we decided against this approach because it does not align with other compat syscall implementations. Instead, we tried to replicate the get_user/put_user pairs as found in other places in the kernel: if (get_user(clipcount, &up->clipcount) || put_user(clipcount, &kp->clipcount)) return -EFAULT; Notes from hans.verkuil@cisco.com: This patch was taken from: https://github.com/LineageOS/android_kernel_samsung_apq8084/commit/97b733953c06e4f0398ade18850f0817778255f7 Clearly nobody could be bothered to upstream this patch or at minimum tell us :-( We only heard about this a week ago. This patch was rebased and cleaned up. Compared to the original I also swapped the order of the convert_in_user arguments so that they matched copy_in_user. It was hard to review otherwise. I also replaced the ALLOC_USER_SPACE/ALLOC_AND_GET by a normal function. Fixes: 6b5a9492ca ("v4l: introduce string control support.") Signed-off-by: Daniel Mentz <danielmentz@google.com> Co-developed-by: Hans Verkuil <hans.verkuil@cisco.com> Acked-by: Sakari Ailus <sakari.ailus@linux.intel.com> Signed-off-by: Hans Verkuil <hans.verkuil@cisco.com> Cc: <stable@vger.kernel.org> # for v4.15 and up Signed-off-by: Mauro Carvalho Chehab <mchehab@s-opensource.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int blkcg_init_queue(struct request_queue *q) { struct blkcg_gq *new_blkg, *blkg; bool preloaded; int ret; new_blkg = blkg_alloc(&blkcg_root, q, GFP_KERNEL); if (!new_blkg) return -ENOMEM; preloaded = !radix_tree_preload(GFP_KERNEL); /* * Make sure the root blkg exists and count the existing blkgs. As * @q is bypassing at this point, blkg_lookup_create() can't be * used. Open code insertion. */ rcu_read_lock(); spin_lock_irq(q->queue_lock); blkg = blkg_create(&blkcg_root, q, new_blkg); spin_unlock_irq(q->queue_lock); rcu_read_unlock(); if (preloaded) radix_tree_preload_end(); if (IS_ERR(blkg)) { blkg_free(new_blkg); return PTR_ERR(blkg); } q->root_blkg = blkg; q->root_rl.blkg = blkg; ret = blk_throtl_init(q); if (ret) { spin_lock_irq(q->queue_lock); blkg_destroy_all(q); spin_unlock_irq(q->queue_lock); } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'blkcg: fix double free of new_blkg in blkcg_init_queue If blkg_create fails, new_blkg passed as an argument will be freed by blkg_create, so there is no need to free it again. Signed-off-by: Hou Tao <houtao1@huawei.com> Signed-off-by: Jens Axboe <axboe@fb.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: php_stream *php_stream_url_wrap_http_ex(php_stream_wrapper *wrapper, const char *path, const char *mode, int options, char **opened_path, php_stream_context *context, int redirect_max, int flags STREAMS_DC TSRMLS_DC) /* {{{ */ { php_stream *stream = NULL; php_url *resource = NULL; int use_ssl; int use_proxy = 0; char *scratch = NULL; char *tmp = NULL; char *ua_str = NULL; zval **ua_zval = NULL, **tmpzval = NULL, *ssl_proxy_peer_name = NULL; int scratch_len = 0; int body = 0; char location[HTTP_HEADER_BLOCK_SIZE]; zval *response_header = NULL; int reqok = 0; char *http_header_line = NULL; char tmp_line[128]; size_t chunk_size = 0, file_size = 0; int eol_detect = 0; char *transport_string, *errstr = NULL; int transport_len, have_header = 0, request_fulluri = 0, ignore_errors = 0; char *protocol_version = NULL; int protocol_version_len = 3; /* Default: "1.0" */ struct timeval timeout; char *user_headers = NULL; int header_init = ((flags & HTTP_WRAPPER_HEADER_INIT) != 0); int redirected = ((flags & HTTP_WRAPPER_REDIRECTED) != 0); int follow_location = 1; php_stream_filter *transfer_encoding = NULL; int response_code; tmp_line[0] = '\0'; if (redirect_max < 1) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Redirection limit reached, aborting"); return NULL; } resource = php_url_parse(path); if (resource == NULL) { return NULL; } if (strncasecmp(resource->scheme, "http", sizeof("http")) && strncasecmp(resource->scheme, "https", sizeof("https"))) { if (!context || php_stream_context_get_option(context, wrapper->wops->label, "proxy", &tmpzval) == FAILURE || Z_TYPE_PP(tmpzval) != IS_STRING || Z_STRLEN_PP(tmpzval) <= 0) { php_url_free(resource); return php_stream_open_wrapper_ex(path, mode, REPORT_ERRORS, NULL, context); } /* Called from a non-http wrapper with http proxying requested (i.e. ftp) */ request_fulluri = 1; use_ssl = 0; use_proxy = 1; transport_len = Z_STRLEN_PP(tmpzval); transport_string = estrndup(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval)); } else { /* Normal http request (possibly with proxy) */ if (strpbrk(mode, "awx+")) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP wrapper does not support writeable connections"); php_url_free(resource); return NULL; } use_ssl = resource->scheme && (strlen(resource->scheme) > 4) && resource->scheme[4] == 's'; /* choose default ports */ if (use_ssl && resource->port == 0) resource->port = 443; else if (resource->port == 0) resource->port = 80; if (context && php_stream_context_get_option(context, wrapper->wops->label, "proxy", &tmpzval) == SUCCESS && Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) { use_proxy = 1; transport_len = Z_STRLEN_PP(tmpzval); transport_string = estrndup(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval)); } else { transport_len = spprintf(&transport_string, 0, "%s://%s:%d", use_ssl ? "ssl" : "tcp", resource->host, resource->port); } } if (context && php_stream_context_get_option(context, wrapper->wops->label, "timeout", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_double_ex(tmpzval); timeout.tv_sec = (time_t) Z_DVAL_PP(tmpzval); timeout.tv_usec = (size_t) ((Z_DVAL_PP(tmpzval) - timeout.tv_sec) * 1000000); } else { timeout.tv_sec = FG(default_socket_timeout); timeout.tv_usec = 0; } stream = php_stream_xport_create(transport_string, transport_len, options, STREAM_XPORT_CLIENT | STREAM_XPORT_CONNECT, NULL, &timeout, context, &errstr, NULL); if (stream) { php_stream_set_option(stream, PHP_STREAM_OPTION_READ_TIMEOUT, 0, &timeout); } if (errstr) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "%s", errstr); efree(errstr); errstr = NULL; } efree(transport_string); if (stream && use_proxy && use_ssl) { smart_str header = {0}; /* Set peer_name or name verification will try to use the proxy server name */ if (!context || php_stream_context_get_option(context, "ssl", "peer_name", &tmpzval) == FAILURE) { MAKE_STD_ZVAL(ssl_proxy_peer_name); ZVAL_STRING(ssl_proxy_peer_name, resource->host, 1); php_stream_context_set_option(stream->context, "ssl", "peer_name", ssl_proxy_peer_name); } smart_str_appendl(&header, "CONNECT ", sizeof("CONNECT ")-1); smart_str_appends(&header, resource->host); smart_str_appendc(&header, ':'); smart_str_append_unsigned(&header, resource->port); smart_str_appendl(&header, " HTTP/1.0\r\n", sizeof(" HTTP/1.0\r\n")-1); /* check if we have Proxy-Authorization header */ if (context && php_stream_context_get_option(context, "http", "header", &tmpzval) == SUCCESS) { char *s, *p; if (Z_TYPE_PP(tmpzval) == IS_ARRAY) { HashPosition pos; zval **tmpheader = NULL; for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(tmpzval), &pos); SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(tmpzval), (void *)&tmpheader, &pos); zend_hash_move_forward_ex(Z_ARRVAL_PP(tmpzval), &pos)) { if (Z_TYPE_PP(tmpheader) == IS_STRING) { s = Z_STRVAL_PP(tmpheader); do { while (*s == ' ' || *s == '\t') s++; p = s; while (*p != 0 && *p != ':' && *p != '\r' && *p !='\n') p++; if (*p == ':') { p++; if (p - s == sizeof("Proxy-Authorization:") - 1 && zend_binary_strcasecmp(s, sizeof("Proxy-Authorization:") - 1, "Proxy-Authorization:", sizeof("Proxy-Authorization:") - 1) == 0) { while (*p != 0 && *p != '\r' && *p !='\n') p++; smart_str_appendl(&header, s, p - s); smart_str_appendl(&header, "\r\n", sizeof("\r\n")-1); goto finish; } else { while (*p != 0 && *p != '\r' && *p !='\n') p++; } } s = p; while (*s == '\r' || *s == '\n') s++; } while (*s != 0); } } } else if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval)) { s = Z_STRVAL_PP(tmpzval); do { while (*s == ' ' || *s == '\t') s++; p = s; while (*p != 0 && *p != ':' && *p != '\r' && *p !='\n') p++; if (*p == ':') { p++; if (p - s == sizeof("Proxy-Authorization:") - 1 && zend_binary_strcasecmp(s, sizeof("Proxy-Authorization:") - 1, "Proxy-Authorization:", sizeof("Proxy-Authorization:") - 1) == 0) { while (*p != 0 && *p != '\r' && *p !='\n') p++; smart_str_appendl(&header, s, p - s); smart_str_appendl(&header, "\r\n", sizeof("\r\n")-1); goto finish; } else { while (*p != 0 && *p != '\r' && *p !='\n') p++; } } s = p; while (*s == '\r' || *s == '\n') s++; } while (*s != 0); } } finish: smart_str_appendl(&header, "\r\n", sizeof("\r\n")-1); if (php_stream_write(stream, header.c, header.len) != header.len) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Cannot connect to HTTPS server through proxy"); php_stream_close(stream); stream = NULL; } smart_str_free(&header); if (stream) { char header_line[HTTP_HEADER_BLOCK_SIZE]; /* get response header */ while (php_stream_gets(stream, header_line, HTTP_HEADER_BLOCK_SIZE-1) != NULL) { if (header_line[0] == '\n' || header_line[0] == '\r' || header_line[0] == '\0') { break; } } } /* enable SSL transport layer */ if (stream) { if (php_stream_xport_crypto_setup(stream, STREAM_CRYPTO_METHOD_SSLv23_CLIENT, NULL TSRMLS_CC) < 0 || php_stream_xport_crypto_enable(stream, 1 TSRMLS_CC) < 0) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Cannot connect to HTTPS server through proxy"); php_stream_close(stream); stream = NULL; } } } if (stream == NULL) goto out; /* avoid buffering issues while reading header */ if (options & STREAM_WILL_CAST) chunk_size = php_stream_set_chunk_size(stream, 1); /* avoid problems with auto-detecting when reading the headers -> the headers * are always in canonical \r\n format */ eol_detect = stream->flags & (PHP_STREAM_FLAG_DETECT_EOL | PHP_STREAM_FLAG_EOL_MAC); stream->flags &= ~(PHP_STREAM_FLAG_DETECT_EOL | PHP_STREAM_FLAG_EOL_MAC); php_stream_context_set(stream, context); php_stream_notify_info(context, PHP_STREAM_NOTIFY_CONNECT, NULL, 0); if (header_init && context && php_stream_context_get_option(context, "http", "max_redirects", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_long_ex(tmpzval); redirect_max = Z_LVAL_PP(tmpzval); } if (context && php_stream_context_get_option(context, "http", "method", &tmpzval) == SUCCESS) { if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) { /* As per the RFC, automatically redirected requests MUST NOT use other methods than * GET and HEAD unless it can be confirmed by the user */ if (!redirected || (Z_STRLEN_PP(tmpzval) == 3 && memcmp("GET", Z_STRVAL_PP(tmpzval), 3) == 0) || (Z_STRLEN_PP(tmpzval) == 4 && memcmp("HEAD",Z_STRVAL_PP(tmpzval), 4) == 0) ) { scratch_len = strlen(path) + 29 + Z_STRLEN_PP(tmpzval); scratch = emalloc(scratch_len); strlcpy(scratch, Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval) + 1); strncat(scratch, " ", 1); } } } if (context && php_stream_context_get_option(context, "http", "protocol_version", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_double_ex(tmpzval); protocol_version_len = spprintf(&protocol_version, 0, "%.1F", Z_DVAL_PP(tmpzval)); } if (!scratch) { scratch_len = strlen(path) + 29 + protocol_version_len; scratch = emalloc(scratch_len); strncpy(scratch, "GET ", scratch_len); } /* Should we send the entire path in the request line, default to no. */ if (!request_fulluri && context && php_stream_context_get_option(context, "http", "request_fulluri", &tmpzval) == SUCCESS) { zval ztmp = **tmpzval; zval_copy_ctor(&ztmp); convert_to_boolean(&ztmp); request_fulluri = Z_BVAL(ztmp) ? 1 : 0; zval_dtor(&ztmp); } if (request_fulluri) { /* Ask for everything */ strcat(scratch, path); } else { /* Send the traditional /path/to/file?query_string */ /* file */ if (resource->path && *resource->path) { strlcat(scratch, resource->path, scratch_len); } else { strlcat(scratch, "/", scratch_len); } /* query string */ if (resource->query) { strlcat(scratch, "?", scratch_len); strlcat(scratch, resource->query, scratch_len); } } /* protocol version we are speaking */ if (protocol_version) { strlcat(scratch, " HTTP/", scratch_len); strlcat(scratch, protocol_version, scratch_len); strlcat(scratch, "\r\n", scratch_len); } else { strlcat(scratch, " HTTP/1.0\r\n", scratch_len); } /* send it */ php_stream_write(stream, scratch, strlen(scratch)); if (context && php_stream_context_get_option(context, "http", "header", &tmpzval) == SUCCESS) { tmp = NULL; if (Z_TYPE_PP(tmpzval) == IS_ARRAY) { HashPosition pos; zval **tmpheader = NULL; smart_str tmpstr = {0}; for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(tmpzval), &pos); SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(tmpzval), (void *)&tmpheader, &pos); zend_hash_move_forward_ex(Z_ARRVAL_PP(tmpzval), &pos) ) { if (Z_TYPE_PP(tmpheader) == IS_STRING) { smart_str_appendl(&tmpstr, Z_STRVAL_PP(tmpheader), Z_STRLEN_PP(tmpheader)); smart_str_appendl(&tmpstr, "\r\n", sizeof("\r\n") - 1); } } smart_str_0(&tmpstr); /* Remove newlines and spaces from start and end. there's at least one extra \r\n at the end that needs to go. */ if (tmpstr.c) { tmp = php_trim(tmpstr.c, strlen(tmpstr.c), NULL, 0, NULL, 3 TSRMLS_CC); smart_str_free(&tmpstr); } } if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval)) { /* Remove newlines and spaces from start and end php_trim will estrndup() */ tmp = php_trim(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval), NULL, 0, NULL, 3 TSRMLS_CC); } if (tmp && strlen(tmp) > 0) { char *s; user_headers = estrdup(tmp); /* Make lowercase for easy comparison against 'standard' headers */ php_strtolower(tmp, strlen(tmp)); if (!header_init) { /* strip POST headers on redirect */ strip_header(user_headers, tmp, "content-length:"); strip_header(user_headers, tmp, "content-type:"); } if ((s = strstr(tmp, "user-agent:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_USER_AGENT; } if ((s = strstr(tmp, "host:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_HOST; } if ((s = strstr(tmp, "from:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_FROM; } if ((s = strstr(tmp, "authorization:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_AUTH; } if ((s = strstr(tmp, "content-length:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_CONTENT_LENGTH; } if ((s = strstr(tmp, "content-type:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_TYPE; } if ((s = strstr(tmp, "connection:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_CONNECTION; } /* remove Proxy-Authorization header */ if (use_proxy && use_ssl && (s = strstr(tmp, "proxy-authorization:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { char *p = s + sizeof("proxy-authorization:") - 1; while (s > tmp && (*(s-1) == ' ' || *(s-1) == '\t')) s--; while (*p != 0 && *p != '\r' && *p != '\n') p++; while (*p == '\r' || *p == '\n') p++; if (*p == 0) { if (s == tmp) { efree(user_headers); user_headers = NULL; } else { while (s > tmp && (*(s-1) == '\r' || *(s-1) == '\n')) s--; user_headers[s - tmp] = 0; } } else { memmove(user_headers + (s - tmp), user_headers + (p - tmp), strlen(p) + 1); } } } if (tmp) { efree(tmp); } } /* auth header if it was specified */ if (((have_header & HTTP_HEADER_AUTH) == 0) && resource->user) { /* decode the strings first */ php_url_decode(resource->user, strlen(resource->user)); /* scratch is large enough, since it was made large enough for the whole URL */ strcpy(scratch, resource->user); strcat(scratch, ":"); /* Note: password is optional! */ if (resource->pass) { php_url_decode(resource->pass, strlen(resource->pass)); strcat(scratch, resource->pass); } tmp = (char*)php_base64_encode((unsigned char*)scratch, strlen(scratch), NULL); if (snprintf(scratch, scratch_len, "Authorization: Basic %s\r\n", tmp) > 0) { php_stream_write(stream, scratch, strlen(scratch)); php_stream_notify_info(context, PHP_STREAM_NOTIFY_AUTH_REQUIRED, NULL, 0); } efree(tmp); tmp = NULL; } /* if the user has configured who they are, send a From: line */ if (((have_header & HTTP_HEADER_FROM) == 0) && FG(from_address)) { if (snprintf(scratch, scratch_len, "From: %s\r\n", FG(from_address)) > 0) php_stream_write(stream, scratch, strlen(scratch)); } /* Send Host: header so name-based virtual hosts work */ if ((have_header & HTTP_HEADER_HOST) == 0) { if ((use_ssl && resource->port != 443 && resource->port != 0) || (!use_ssl && resource->port != 80 && resource->port != 0)) { if (snprintf(scratch, scratch_len, "Host: %s:%i\r\n", resource->host, resource->port) > 0) php_stream_write(stream, scratch, strlen(scratch)); } else { if (snprintf(scratch, scratch_len, "Host: %s\r\n", resource->host) > 0) { php_stream_write(stream, scratch, strlen(scratch)); } } } /* Send a Connection: close header to avoid hanging when the server * interprets the RFC literally and establishes a keep-alive connection, * unless the user specifically requests something else by specifying a * Connection header in the context options. Send that header even for * HTTP/1.0 to avoid issues when the server respond with a HTTP/1.1 * keep-alive response, which is the preferred response type. */ if ((have_header & HTTP_HEADER_CONNECTION) == 0) { php_stream_write_string(stream, "Connection: close\r\n"); } if (context && php_stream_context_get_option(context, "http", "user_agent", &ua_zval) == SUCCESS && Z_TYPE_PP(ua_zval) == IS_STRING) { ua_str = Z_STRVAL_PP(ua_zval); } else if (FG(user_agent)) { ua_str = FG(user_agent); } if (((have_header & HTTP_HEADER_USER_AGENT) == 0) && ua_str) { #define _UA_HEADER "User-Agent: %s\r\n" char *ua; size_t ua_len; ua_len = sizeof(_UA_HEADER) + strlen(ua_str); /* ensure the header is only sent if user_agent is not blank */ if (ua_len > sizeof(_UA_HEADER)) { ua = emalloc(ua_len + 1); if ((ua_len = slprintf(ua, ua_len, _UA_HEADER, ua_str)) > 0) { ua[ua_len] = 0; php_stream_write(stream, ua, ua_len); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot construct User-agent header"); } if (ua) { efree(ua); } } } if (user_headers) { /* A bit weird, but some servers require that Content-Length be sent prior to Content-Type for POST * see bug #44603 for details. Since Content-Type maybe part of user's headers we need to do this check first. */ if ( header_init && context && !(have_header & HTTP_HEADER_CONTENT_LENGTH) && php_stream_context_get_option(context, "http", "content", &tmpzval) == SUCCESS && Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0 ) { scratch_len = slprintf(scratch, scratch_len, "Content-Length: %d\r\n", Z_STRLEN_PP(tmpzval)); php_stream_write(stream, scratch, scratch_len); have_header |= HTTP_HEADER_CONTENT_LENGTH; } php_stream_write(stream, user_headers, strlen(user_headers)); php_stream_write(stream, "\r\n", sizeof("\r\n")-1); efree(user_headers); } /* Request content, such as for POST requests */ if (header_init && context && php_stream_context_get_option(context, "http", "content", &tmpzval) == SUCCESS && Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) { if (!(have_header & HTTP_HEADER_CONTENT_LENGTH)) { scratch_len = slprintf(scratch, scratch_len, "Content-Length: %d\r\n", Z_STRLEN_PP(tmpzval)); php_stream_write(stream, scratch, scratch_len); } if (!(have_header & HTTP_HEADER_TYPE)) { php_stream_write(stream, "Content-Type: application/x-www-form-urlencoded\r\n", sizeof("Content-Type: application/x-www-form-urlencoded\r\n") - 1); php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Content-type not specified assuming application/x-www-form-urlencoded"); } php_stream_write(stream, "\r\n", sizeof("\r\n")-1); php_stream_write(stream, Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval)); } else { php_stream_write(stream, "\r\n", sizeof("\r\n")-1); } location[0] = '\0'; if (!EG(active_symbol_table)) { zend_rebuild_symbol_table(TSRMLS_C); } if (header_init) { zval *ztmp; MAKE_STD_ZVAL(ztmp); array_init(ztmp); ZEND_SET_SYMBOL(EG(active_symbol_table), "http_response_header", ztmp); } { zval **rh; if(zend_hash_find(EG(active_symbol_table), "http_response_header", sizeof("http_response_header"), (void **) &rh) != SUCCESS || Z_TYPE_PP(rh) != IS_ARRAY) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP request failed, http_response_header overwritten"); goto out; } response_header = *rh; Z_ADDREF_P(response_header); } if (!php_stream_eof(stream)) { size_t tmp_line_len; /* get response header */ if (php_stream_get_line(stream, tmp_line, sizeof(tmp_line) - 1, &tmp_line_len) != NULL) { zval *http_response; if (tmp_line_len > 9) { response_code = atoi(tmp_line + 9); } else { response_code = 0; } if (context && SUCCESS==php_stream_context_get_option(context, "http", "ignore_errors", &tmpzval)) { ignore_errors = zend_is_true(*tmpzval); } /* when we request only the header, don't fail even on error codes */ if ((options & STREAM_ONLY_GET_HEADERS) || ignore_errors) { reqok = 1; } /* status codes of 1xx are "informational", and will be followed by a real response * e.g "100 Continue". RFC 7231 states that unexpected 1xx status MUST be parsed, * and MAY be ignored. As such, we need to skip ahead to the "real" status*/ if (response_code >= 100 && response_code < 200) { /* consume lines until we find a line starting 'HTTP/1' */ while ( !php_stream_eof(stream) && php_stream_get_line(stream, tmp_line, sizeof(tmp_line) - 1, &tmp_line_len) != NULL && ( tmp_line_len < sizeof("HTTP/1") - 1 || strncasecmp(tmp_line, "HTTP/1", sizeof("HTTP/1") - 1) ) ); if (tmp_line_len > 9) { response_code = atoi(tmp_line + 9); } else { response_code = 0; } } /* all status codes in the 2xx range are defined by the specification as successful; * all status codes in the 3xx range are for redirection, and so also should never * fail */ if (response_code >= 200 && response_code < 400) { reqok = 1; } else { switch(response_code) { case 403: php_stream_notify_error(context, PHP_STREAM_NOTIFY_AUTH_RESULT, tmp_line, response_code); break; default: /* safety net in the event tmp_line == NULL */ if (!tmp_line_len) { tmp_line[0] = '\0'; } php_stream_notify_error(context, PHP_STREAM_NOTIFY_FAILURE, tmp_line, response_code); } } if (tmp_line[tmp_line_len - 1] == '\n') { --tmp_line_len; if (tmp_line[tmp_line_len - 1] == '\r') { --tmp_line_len; } } MAKE_STD_ZVAL(http_response); ZVAL_STRINGL(http_response, tmp_line, tmp_line_len, 1); zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_response, sizeof(zval *), NULL); } } else { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP request failed, unexpected end of socket!"); goto out; } /* read past HTTP headers */ http_header_line = emalloc(HTTP_HEADER_BLOCK_SIZE); while (!body && !php_stream_eof(stream)) { size_t http_header_line_length; if (php_stream_get_line(stream, http_header_line, HTTP_HEADER_BLOCK_SIZE, &http_header_line_length) && *http_header_line != '\n' && *http_header_line != '\r') { char *e = http_header_line + http_header_line_length - 1; if (*e != '\n') { do { /* partial header */ if (php_stream_get_line(stream, http_header_line, HTTP_HEADER_BLOCK_SIZE, &http_header_line_length) == NULL) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Failed to read HTTP headers"); goto out; } e = http_header_line + http_header_line_length - 1; } while (*e != '\n'); continue; } while (*e == '\n' || *e == '\r') { e--; } http_header_line_length = e - http_header_line + 1; http_header_line[http_header_line_length] = '\0'; if (!strncasecmp(http_header_line, "Location: ", 10)) { if (context && php_stream_context_get_option(context, "http", "follow_location", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_long_ex(tmpzval); follow_location = Z_LVAL_PP(tmpzval); } else if (!(response_code >= 300 && response_code < 304 || 307 == response_code || 308 == response_code)) { /* we shouldn't redirect automatically if follow_location isn't set and response_code not in (300, 301, 302, 303 and 307) see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.1 RFC 7238 defines 308: http://tools.ietf.org/html/rfc7238 */ follow_location = 0; } strlcpy(location, http_header_line + 10, sizeof(location)); } else if (!strncasecmp(http_header_line, "Content-Type: ", 14)) { php_stream_notify_info(context, PHP_STREAM_NOTIFY_MIME_TYPE_IS, http_header_line + 14, 0); } else if (!strncasecmp(http_header_line, "Content-Length: ", 16)) { file_size = atoi(http_header_line + 16); php_stream_notify_file_size(context, file_size, http_header_line, 0); } else if (!strncasecmp(http_header_line, "Transfer-Encoding: chunked", sizeof("Transfer-Encoding: chunked"))) { /* create filter to decode response body */ if (!(options & STREAM_ONLY_GET_HEADERS)) { long decode = 1; if (context && php_stream_context_get_option(context, "http", "auto_decode", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_boolean(*tmpzval); decode = Z_LVAL_PP(tmpzval); } if (decode) { transfer_encoding = php_stream_filter_create("dechunk", NULL, php_stream_is_persistent(stream) TSRMLS_CC); if (transfer_encoding) { /* don't store transfer-encodeing header */ continue; } } } } if (http_header_line[0] == '\0') { body = 1; } else { zval *http_header; MAKE_STD_ZVAL(http_header); ZVAL_STRINGL(http_header, http_header_line, http_header_line_length, 1); zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_header, sizeof(zval *), NULL); } } else { break; } } if (!reqok || (location[0] != '\0' && follow_location)) { if (!follow_location || (((options & STREAM_ONLY_GET_HEADERS) || ignore_errors) && redirect_max <= 1)) { goto out; } if (location[0] != '\0') php_stream_notify_info(context, PHP_STREAM_NOTIFY_REDIRECTED, location, 0); php_stream_close(stream); stream = NULL; if (location[0] != '\0') { char new_path[HTTP_HEADER_BLOCK_SIZE]; char loc_path[HTTP_HEADER_BLOCK_SIZE]; *new_path='\0'; if (strlen(location)<8 || (strncasecmp(location, "http://", sizeof("http://")-1) && strncasecmp(location, "https://", sizeof("https://")-1) && strncasecmp(location, "ftp://", sizeof("ftp://")-1) && strncasecmp(location, "ftps://", sizeof("ftps://")-1))) { if (*location != '/') { if (*(location+1) != '\0' && resource->path) { char *s = strrchr(resource->path, '/'); if (!s) { s = resource->path; if (!s[0]) { efree(s); s = resource->path = estrdup("/"); } else { *s = '/'; } } s[1] = '\0'; if (resource->path && *(resource->path) == '/' && *(resource->path + 1) == '\0') { snprintf(loc_path, sizeof(loc_path) - 1, "%s%s", resource->path, location); } else { snprintf(loc_path, sizeof(loc_path) - 1, "%s/%s", resource->path, location); } } else { snprintf(loc_path, sizeof(loc_path) - 1, "/%s", location); } } else { strlcpy(loc_path, location, sizeof(loc_path)); } if ((use_ssl && resource->port != 443) || (!use_ssl && resource->port != 80)) { snprintf(new_path, sizeof(new_path) - 1, "%s://%s:%d%s", resource->scheme, resource->host, resource->port, loc_path); } else { snprintf(new_path, sizeof(new_path) - 1, "%s://%s%s", resource->scheme, resource->host, loc_path); } } else { strlcpy(new_path, location, sizeof(new_path)); } php_url_free(resource); /* check for invalid redirection URLs */ if ((resource = php_url_parse(new_path)) == NULL) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Invalid redirect URL! %s", new_path); goto out; } #define CHECK_FOR_CNTRL_CHARS(val) { \ if (val) { \ unsigned char *s, *e; \ int l; \ l = php_url_decode(val, strlen(val)); \ s = (unsigned char*)val; e = s + l; \ while (s < e) { \ if (iscntrl(*s)) { \ php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Invalid redirect URL! %s", new_path); \ goto out; \ } \ s++; \ } \ } \ } /* check for control characters in login, password & path */ if (strncasecmp(new_path, "http://", sizeof("http://") - 1) || strncasecmp(new_path, "https://", sizeof("https://") - 1)) { CHECK_FOR_CNTRL_CHARS(resource->user) CHECK_FOR_CNTRL_CHARS(resource->pass) CHECK_FOR_CNTRL_CHARS(resource->path) } stream = php_stream_url_wrap_http_ex(wrapper, new_path, mode, options, opened_path, context, --redirect_max, HTTP_WRAPPER_REDIRECTED STREAMS_CC TSRMLS_CC); } else { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP request failed! %s", tmp_line); } } out: if (protocol_version) { efree(protocol_version); } if (http_header_line) { efree(http_header_line); } if (scratch) { efree(scratch); } if (resource) { php_url_free(resource); } if (stream) { if (header_init) { stream->wrapperdata = response_header; } else { if(response_header) { Z_DELREF_P(response_header); } } php_stream_notify_progress_init(context, 0, file_size); /* Restore original chunk size now that we're done with headers */ if (options & STREAM_WILL_CAST) php_stream_set_chunk_size(stream, chunk_size); /* restore the users auto-detect-line-endings setting */ stream->flags |= eol_detect; /* as far as streams are concerned, we are now at the start of * the stream */ stream->position = 0; /* restore mode */ strlcpy(stream->mode, mode, sizeof(stream->mode)); if (transfer_encoding) { php_stream_filter_append(&stream->readfilters, transfer_encoding); } } else { if(response_header) { Z_DELREF_P(response_header); } if (transfer_encoding) { php_stream_filter_free(transfer_encoding TSRMLS_CC); } } return stream; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix bug #75981: prevent reading beyond buffer start'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static ssize_t o2nm_node_num_store(struct config_item *item, const char *page, size_t count) { struct o2nm_node *node = to_o2nm_node(item); struct o2nm_cluster *cluster = to_o2nm_cluster_from_node(node); unsigned long tmp; char *p = (char *)page; int ret = 0; tmp = simple_strtoul(p, &p, 0); if (!p || (*p && (*p != '\n'))) return -EINVAL; if (tmp >= O2NM_MAX_NODES) return -ERANGE; /* once we're in the cl_nodes tree networking can look us up by * node number and try to use our address and port attributes * to connect to this node.. make sure that they've been set * before writing the node attribute? */ if (!test_bit(O2NM_NODE_ATTR_ADDRESS, &node->nd_set_attributes) || !test_bit(O2NM_NODE_ATTR_PORT, &node->nd_set_attributes)) return -EINVAL; /* XXX */ write_lock(&cluster->cl_nodes_lock); if (cluster->cl_nodes[tmp]) ret = -EEXIST; else if (test_and_set_bit(O2NM_NODE_ATTR_NUM, &node->nd_set_attributes)) ret = -EBUSY; else { cluster->cl_nodes[tmp] = node; node->nd_num = tmp; set_bit(tmp, cluster->cl_nodes_bitmap); } write_unlock(&cluster->cl_nodes_lock); if (ret) return ret; return count; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-284'], 'message': 'ocfs2: subsystem.su_mutex is required while accessing the item->ci_parent The subsystem.su_mutex is required while accessing the item->ci_parent, otherwise, NULL pointer dereference to the item->ci_parent will be triggered in the following situation: add node delete node sys_write vfs_write configfs_write_file o2nm_node_store o2nm_node_local_write do_rmdir vfs_rmdir configfs_rmdir mutex_lock(&subsys->su_mutex); unlink_obj item->ci_group = NULL; item->ci_parent = NULL; to_o2nm_cluster_from_node node->nd_item.ci_parent->ci_parent BUG since of NULL pointer dereference to nd_item.ci_parent Moreover, the o2nm_cluster also should be protected by the subsystem.su_mutex. [alex.chen@huawei.com: v2] Link: http://lkml.kernel.org/r/59EEAA69.9080703@huawei.com Link: http://lkml.kernel.org/r/59E9B36A.10700@huawei.com Signed-off-by: Alex Chen <alex.chen@huawei.com> Reviewed-by: Jun Piao <piaojun@huawei.com> Reviewed-by: Joseph Qi <jiangqi903@gmail.com> Cc: Mark Fasheh <mfasheh@versity.com> Cc: Joel Becker <jlbec@evilplan.org> Cc: Junxiao Bi <junxiao.bi@oracle.com> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: CImg<T>& _load_bmp(std::FILE *const file, const char *const filename) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_bmp(): Specified filename is (null).", cimg_instance); std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); CImg<ucharT> header(54); cimg::fread(header._data,54,nfile); if (*header!='B' || header[1]!='M') { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_bmp(): Invalid BMP file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } // Read header and pixel buffer int file_size = header[0x02] + (header[0x03]<<8) + (header[0x04]<<16) + (header[0x05]<<24), offset = header[0x0A] + (header[0x0B]<<8) + (header[0x0C]<<16) + (header[0x0D]<<24), header_size = header[0x0E] + (header[0x0F]<<8) + (header[0x10]<<16) + (header[0x11]<<24), dx = header[0x12] + (header[0x13]<<8) + (header[0x14]<<16) + (header[0x15]<<24), dy = header[0x16] + (header[0x17]<<8) + (header[0x18]<<16) + (header[0x19]<<24), compression = header[0x1E] + (header[0x1F]<<8) + (header[0x20]<<16) + (header[0x21]<<24), nb_colors = header[0x2E] + (header[0x2F]<<8) + (header[0x30]<<16) + (header[0x31]<<24), bpp = header[0x1C] + (header[0x1D]<<8); if (!file_size || file_size==offset) { cimg::fseek(nfile,0,SEEK_END); file_size = (int)cimg::ftell(nfile); cimg::fseek(nfile,54,SEEK_SET); } if (header_size>40) cimg::fseek(nfile,header_size - 40,SEEK_CUR); const int dx_bytes = (bpp==1)?(dx/8 + (dx%8?1:0)):((bpp==4)?(dx/2 + (dx%2)):(dx*bpp/8)), align_bytes = (4 - dx_bytes%4)%4; const ulongT cimg_iobuffer = (ulongT)24*1024*1024, buf_size = std::min((ulongT)cimg::abs(dy)*(dx_bytes + align_bytes),(ulongT)file_size - offset); CImg<intT> colormap; if (bpp<16) { if (!nb_colors) nb_colors = 1<<bpp; } else nb_colors = 0; if (nb_colors) { colormap.assign(nb_colors); cimg::fread(colormap._data,nb_colors,nfile); } const int xoffset = offset - 14 - header_size - 4*nb_colors; if (xoffset>0) cimg::fseek(nfile,xoffset,SEEK_CUR); CImg<ucharT> buffer; if (buf_size<cimg_iobuffer) { buffer.assign(cimg::abs(dy)*(dx_bytes + align_bytes),1,1,1,0); cimg::fread(buffer._data,buf_size,nfile); } else buffer.assign(dx_bytes + align_bytes); unsigned char *ptrs = buffer; // Decompress buffer (if necessary) if (compression) { if (file) throw CImgIOException(_cimg_instance "load_bmp(): Unable to load compressed data from '(*FILE)' inputs.", cimg_instance); else { if (!file) cimg::fclose(nfile); return load_other(filename); } } // Read pixel data assign(dx,cimg::abs(dy),1,3); switch (bpp) { case 1 : { // Monochrome for (int y = height() - 1; y>=0; --y) { if (buf_size>=cimg_iobuffer) { if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break; cimg::fseek(nfile,align_bytes,SEEK_CUR); } unsigned char mask = 0x80, val = 0; cimg_forX(*this,x) { if (mask==0x80) val = *(ptrs++); const unsigned char *col = (unsigned char*)(colormap._data + (val&mask?1:0)); (*this)(x,y,2) = (T)*(col++); (*this)(x,y,1) = (T)*(col++); (*this)(x,y,0) = (T)*(col++); mask = cimg::ror(mask); } ptrs+=align_bytes; } } break; case 4 : { // 16 colors for (int y = height() - 1; y>=0; --y) { if (buf_size>=cimg_iobuffer) { if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break; cimg::fseek(nfile,align_bytes,SEEK_CUR); } unsigned char mask = 0xF0, val = 0; cimg_forX(*this,x) { if (mask==0xF0) val = *(ptrs++); const unsigned char color = (unsigned char)((mask<16)?(val&mask):((val&mask)>>4)); const unsigned char *col = (unsigned char*)(colormap._data + color); (*this)(x,y,2) = (T)*(col++); (*this)(x,y,1) = (T)*(col++); (*this)(x,y,0) = (T)*(col++); mask = cimg::ror(mask,4); } ptrs+=align_bytes; } } break; case 8 : { // 256 colors for (int y = height() - 1; y>=0; --y) { if (buf_size>=cimg_iobuffer) { if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break; cimg::fseek(nfile,align_bytes,SEEK_CUR); } cimg_forX(*this,x) { const unsigned char *col = (unsigned char*)(colormap._data + *(ptrs++)); (*this)(x,y,2) = (T)*(col++); (*this)(x,y,1) = (T)*(col++); (*this)(x,y,0) = (T)*(col++); } ptrs+=align_bytes; } } break; case 16 : { // 16 bits colors for (int y = height() - 1; y>=0; --y) { if (buf_size>=cimg_iobuffer) { if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break; cimg::fseek(nfile,align_bytes,SEEK_CUR); } cimg_forX(*this,x) { const unsigned char c1 = *(ptrs++), c2 = *(ptrs++); const unsigned short col = (unsigned short)(c1|(c2<<8)); (*this)(x,y,2) = (T)(col&0x1F); (*this)(x,y,1) = (T)((col>>5)&0x1F); (*this)(x,y,0) = (T)((col>>10)&0x1F); } ptrs+=align_bytes; } } break; case 24 : { // 24 bits colors for (int y = height() - 1; y>=0; --y) { if (buf_size>=cimg_iobuffer) { if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break; cimg::fseek(nfile,align_bytes,SEEK_CUR); } cimg_forX(*this,x) { (*this)(x,y,2) = (T)*(ptrs++); (*this)(x,y,1) = (T)*(ptrs++); (*this)(x,y,0) = (T)*(ptrs++); } ptrs+=align_bytes; } } break; case 32 : { // 32 bits colors for (int y = height() - 1; y>=0; --y) { if (buf_size>=cimg_iobuffer) { if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break; cimg::fseek(nfile,align_bytes,SEEK_CUR); } cimg_forX(*this,x) { (*this)(x,y,2) = (T)*(ptrs++); (*this)(x,y,1) = (T)*(ptrs++); (*this)(x,y,0) = (T)*(ptrs++); ++ptrs; } ptrs+=align_bytes; } } break; } if (dy<0) mirror('y'); if (!file) cimg::fclose(nfile); return *this; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix other issues in 'CImg<T>::load_bmp()'.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int read_entry( git_index_entry **out, size_t *out_size, git_index *index, const void *buffer, size_t buffer_size, const char *last) { size_t path_length, entry_size; const char *path_ptr; struct entry_short source; git_index_entry entry = {{0}}; bool compressed = index->version >= INDEX_VERSION_NUMBER_COMP; char *tmp_path = NULL; if (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size) return -1; /* buffer is not guaranteed to be aligned */ memcpy(&source, buffer, sizeof(struct entry_short)); entry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds); entry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds); entry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds); entry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds); entry.dev = ntohl(source.dev); entry.ino = ntohl(source.ino); entry.mode = ntohl(source.mode); entry.uid = ntohl(source.uid); entry.gid = ntohl(source.gid); entry.file_size = ntohl(source.file_size); git_oid_cpy(&entry.id, &source.oid); entry.flags = ntohs(source.flags); if (entry.flags & GIT_IDXENTRY_EXTENDED) { uint16_t flags_raw; size_t flags_offset; flags_offset = offsetof(struct entry_long, flags_extended); memcpy(&flags_raw, (const char *) buffer + flags_offset, sizeof(flags_raw)); flags_raw = ntohs(flags_raw); memcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw)); path_ptr = (const char *) buffer + offsetof(struct entry_long, path); } else path_ptr = (const char *) buffer + offsetof(struct entry_short, path); if (!compressed) { path_length = entry.flags & GIT_IDXENTRY_NAMEMASK; /* if this is a very long string, we must find its * real length without overflowing */ if (path_length == 0xFFF) { const char *path_end; path_end = memchr(path_ptr, '\0', buffer_size); if (path_end == NULL) return -1; path_length = path_end - path_ptr; } entry_size = index_entry_size(path_length, 0, entry.flags); entry.path = (char *)path_ptr; } else { size_t varint_len, last_len, prefix_len, suffix_len, path_len; uintmax_t strip_len; strip_len = git_decode_varint((const unsigned char *)path_ptr, &varint_len); last_len = strlen(last); if (varint_len == 0 || last_len < strip_len) return index_error_invalid("incorrect prefix length"); prefix_len = last_len - strip_len; suffix_len = strlen(path_ptr + varint_len); GITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len); GITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1); tmp_path = git__malloc(path_len); GITERR_CHECK_ALLOC(tmp_path); memcpy(tmp_path, last, prefix_len); memcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1); entry_size = index_entry_size(suffix_len, varint_len, entry.flags); entry.path = tmp_path; } if (entry_size == 0) return -1; if (INDEX_FOOTER_SIZE + entry_size > buffer_size) return -1; if (index_entry_dup(out, index, &entry) < 0) { git__free(tmp_path); return -1; } git__free(tmp_path); *out_size = entry_size; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415', 'CWE-190'], 'message': 'index: error out on unreasonable prefix-compressed path lengths When computing the complete path length from the encoded prefix-compressed path, we end up just allocating the complete path without ever checking what the encoded path length actually is. This can easily lead to a denial of service by just encoding an unreasonable long path name inside of the index. Git already enforces a maximum path length of 4096 bytes. As we also have that enforcement ready in some places, just make sure that the resulting path is smaller than GIT_PATH_MAX. Reported-by: Krishna Ram Prakash R <krp@gtux.in> Reported-by: Vivek Parikh <viv0411.parikh@gmail.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: zzip_disk_entry_fopen(ZZIP_DISK * disk, ZZIP_DISK_ENTRY * entry) { /* keep this in sync with zzip_mem_entry_fopen */ struct zzip_file_header *header = zzip_disk_entry_to_file_header(disk, entry); if (! header) return 0; /* EBADMSG */ ___ ZZIP_DISK_FILE *file = malloc(sizeof(ZZIP_DISK_FILE)); if (! file) return 0; /* ENOMEM */ file->buffer = disk->buffer; file->endbuf = disk->endbuf; file->avail = zzip_file_header_usize(header); if (! file->avail || zzip_file_header_data_stored(header)) { file->stored = zzip_file_header_to_data (header); DBG2("stored size %i", (int) file->avail); if (file->stored + file->avail >= disk->endbuf) goto error; return file; } file->stored = 0; file->zlib.opaque = 0; file->zlib.zalloc = Z_NULL; file->zlib.zfree = Z_NULL; file->zlib.avail_in = zzip_file_header_csize(header); file->zlib.next_in = zzip_file_header_to_data(header); DBG2("compressed size %i", (int) file->zlib.avail_in); if (file->zlib.next_in + file->zlib.avail_in >= disk->endbuf) goto error; if (! zzip_file_header_data_deflated(header)) goto error; if (inflateInit2(&file->zlib, -MAX_WBITS) != Z_OK) goto error; return file; error: free (file); errno = EBADMSG; return 0; ____; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'check zlib space to be within buffer #39'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: zzip_mem_disk_entry_to_data(ZZIP_MEM_DISK* dir, ZZIP_DISK_ENTRY* entry) { return zzip_disk_entry_to_data(dir->disk, entry); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'memdisk (.)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: zzip_mem_disk_fread (void* ptr, _zzip_size_t size, _zzip_size_t nmemb, ZZIP_DISK_FILE* file) { return zzip_disk_fread(ptr, size, nmemb, file); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'memdisk (.)'</s>
<s>[INST] Given the following code containing errors, provide 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 ocfs2_dio_get_block(struct inode *inode, sector_t iblock, struct buffer_head *bh_result, int create) { struct ocfs2_super *osb = OCFS2_SB(inode->i_sb); struct ocfs2_inode_info *oi = OCFS2_I(inode); struct ocfs2_write_ctxt *wc; struct ocfs2_write_cluster_desc *desc = NULL; struct ocfs2_dio_write_ctxt *dwc = NULL; struct buffer_head *di_bh = NULL; u64 p_blkno; loff_t pos = iblock << inode->i_sb->s_blocksize_bits; unsigned len, total_len = bh_result->b_size; int ret = 0, first_get_block = 0; len = osb->s_clustersize - (pos & (osb->s_clustersize - 1)); len = min(total_len, len); mlog(0, "get block of %lu at %llu:%u req %u\n", inode->i_ino, pos, len, total_len); /* * Because we need to change file size in ocfs2_dio_end_io_write(), or * we may need to add it to orphan dir. So can not fall to fast path * while file size will be changed. */ if (pos + total_len <= i_size_read(inode)) { down_read(&oi->ip_alloc_sem); /* This is the fast path for re-write. */ ret = ocfs2_get_block(inode, iblock, bh_result, create); up_read(&oi->ip_alloc_sem); if (buffer_mapped(bh_result) && !buffer_new(bh_result) && ret == 0) goto out; /* Clear state set by ocfs2_get_block. */ bh_result->b_state = 0; } dwc = ocfs2_dio_alloc_write_ctx(bh_result, &first_get_block); if (unlikely(dwc == NULL)) { ret = -ENOMEM; mlog_errno(ret); goto out; } if (ocfs2_clusters_for_bytes(inode->i_sb, pos + total_len) > ocfs2_clusters_for_bytes(inode->i_sb, i_size_read(inode)) && !dwc->dw_orphaned) { /* * when we are going to alloc extents beyond file size, add the * inode to orphan dir, so we can recall those spaces when * system crashed during write. */ ret = ocfs2_add_inode_to_orphan(osb, inode); if (ret < 0) { mlog_errno(ret); goto out; } dwc->dw_orphaned = 1; } ret = ocfs2_inode_lock(inode, &di_bh, 1); if (ret) { mlog_errno(ret); goto out; } down_write(&oi->ip_alloc_sem); if (first_get_block) { if (ocfs2_sparse_alloc(OCFS2_SB(inode->i_sb))) ret = ocfs2_zero_tail(inode, di_bh, pos); else ret = ocfs2_expand_nonsparse_inode(inode, di_bh, pos, total_len, NULL); if (ret < 0) { mlog_errno(ret); goto unlock; } } ret = ocfs2_write_begin_nolock(inode->i_mapping, pos, len, OCFS2_WRITE_DIRECT, NULL, (void **)&wc, di_bh, NULL); if (ret) { mlog_errno(ret); goto unlock; } desc = &wc->w_desc[0]; p_blkno = ocfs2_clusters_to_blocks(inode->i_sb, desc->c_phys); BUG_ON(p_blkno == 0); p_blkno += iblock & (u64)(ocfs2_clusters_to_blocks(inode->i_sb, 1) - 1); map_bh(bh_result, inode->i_sb, p_blkno); bh_result->b_size = len; if (desc->c_needs_zero) set_buffer_new(bh_result); /* May sleep in end_io. It should not happen in a irq context. So defer * it to dio work queue. */ set_buffer_defer_completion(bh_result); if (!list_empty(&wc->w_unwritten_list)) { struct ocfs2_unwritten_extent *ue = NULL; ue = list_first_entry(&wc->w_unwritten_list, struct ocfs2_unwritten_extent, ue_node); BUG_ON(ue->ue_cpos != desc->c_cpos); /* The physical address may be 0, fill it. */ ue->ue_phys = desc->c_phys; list_splice_tail_init(&wc->w_unwritten_list, &dwc->dw_zero_list); dwc->dw_zero_count++; } ret = ocfs2_write_end_nolock(inode->i_mapping, pos, len, len, wc); BUG_ON(ret != len); ret = 0; unlock: up_write(&oi->ip_alloc_sem); ocfs2_inode_unlock(inode, 1); brelse(di_bh); out: if (ret < 0) ret = -EIO; return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'ocfs2: ip_alloc_sem should be taken in ocfs2_get_block() ip_alloc_sem should be taken in ocfs2_get_block() when reading file in DIRECT mode to prevent concurrent access to extent tree with ocfs2_dio_end_io_write(), which may cause BUGON in the following situation: read file 'A' end_io of writing file 'A' vfs_read __vfs_read ocfs2_file_read_iter generic_file_read_iter ocfs2_direct_IO __blockdev_direct_IO do_blockdev_direct_IO do_direct_IO get_more_blocks ocfs2_get_block ocfs2_extent_map_get_blocks ocfs2_get_clusters ocfs2_get_clusters_nocache() ocfs2_search_extent_list return the index of record which contains the v_cluster, that is v_cluster > rec[i]->e_cpos. ocfs2_dio_end_io ocfs2_dio_end_io_write down_write(&oi->ip_alloc_sem); ocfs2_mark_extent_written ocfs2_change_extent_flag ocfs2_split_extent ... --> modify the rec[i]->e_cpos, resulting in v_cluster < rec[i]->e_cpos. BUG_ON(v_cluster < le32_to_cpu(rec->e_cpos)) [alex.chen@huawei.com: v3] Link: http://lkml.kernel.org/r/59EF3614.6050008@huawei.com Link: http://lkml.kernel.org/r/59EF3614.6050008@huawei.com Fixes: c15471f79506 ("ocfs2: fix sparse file & data ordering issue in direct io") Signed-off-by: Alex Chen <alex.chen@huawei.com> Reviewed-by: Jun Piao <piaojun@huawei.com> Reviewed-by: Joseph Qi <jiangqi903@gmail.com> Reviewed-by: Gang He <ghe@suse.com> Acked-by: Changwei Ge <ge.changwei@h3c.com> Cc: Mark Fasheh <mfasheh@versity.com> Cc: Joel Becker <jlbec@evilplan.org> Cc: Junxiao Bi <junxiao.bi@oracle.com> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void sas_discover_domain(struct work_struct *work) { struct domain_device *dev; int error = 0; struct sas_discovery_event *ev = to_sas_discovery_event(work); struct asd_sas_port *port = ev->port; clear_bit(DISCE_DISCOVER_DOMAIN, &port->disc.pending); if (port->port_dev) return; error = sas_get_port_device(port); if (error) return; dev = port->port_dev; SAS_DPRINTK("DOING DISCOVERY on port %d, pid:%d\n", port->id, task_pid_nr(current)); switch (dev->dev_type) { case SAS_END_DEVICE: error = sas_discover_end_dev(dev); break; case SAS_EDGE_EXPANDER_DEVICE: case SAS_FANOUT_EXPANDER_DEVICE: error = sas_discover_root_expander(dev); break; case SAS_SATA_DEV: case SAS_SATA_PM: #ifdef CONFIG_SCSI_SAS_ATA error = sas_discover_sata(dev); break; #else SAS_DPRINTK("ATA device seen but CONFIG_SCSI_SAS_ATA=N so cannot attach\n"); /* Fall through */ #endif default: error = -ENXIO; SAS_DPRINTK("unhandled device %d\n", dev->dev_type); break; } if (error) { sas_rphy_free(dev->rphy); list_del_init(&dev->disco_list_node); spin_lock_irq(&port->dev_list_lock); list_del_init(&dev->dev_list_node); spin_unlock_irq(&port->dev_list_lock); sas_put_device(dev); port->port_dev = NULL; } SAS_DPRINTK("DONE DISCOVERY on port %d, pid:%d, result:%d\n", port->id, task_pid_nr(current), error); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284'], 'message': 'scsi: libsas: direct call probe and destruct In commit 87c8331fcf72 ("[SCSI] libsas: prevent domain rediscovery competing with ata error handling") introduced disco mutex to prevent rediscovery competing with ata error handling and put the whole revalidation in the mutex. But the rphy add/remove needs to wait for the error handling which also grabs the disco mutex. This may leads to dead lock.So the probe and destruct event were introduce to do the rphy add/remove asynchronously and out of the lock. The asynchronously processed workers makes the whole discovery process not atomic, the other events may interrupt the process. For example, if a loss of signal event inserted before the probe event, the sas_deform_port() is called and the port will be deleted. And sas_port_delete() may run before the destruct event, but the port-x:x is the top parent of end device or expander. This leads to a kernel WARNING such as: [ 82.042979] sysfs group 'power' not found for kobject 'phy-1:0:22' [ 82.042983] ------------[ cut here ]------------ [ 82.042986] WARNING: CPU: 54 PID: 1714 at fs/sysfs/group.c:237 sysfs_remove_group+0x94/0xa0 [ 82.043059] Call trace: [ 82.043082] [<ffff0000082e7624>] sysfs_remove_group+0x94/0xa0 [ 82.043085] [<ffff00000864e320>] dpm_sysfs_remove+0x60/0x70 [ 82.043086] [<ffff00000863ee10>] device_del+0x138/0x308 [ 82.043089] [<ffff00000869a2d0>] sas_phy_delete+0x38/0x60 [ 82.043091] [<ffff00000869a86c>] do_sas_phy_delete+0x6c/0x80 [ 82.043093] [<ffff00000863dc20>] device_for_each_child+0x58/0xa0 [ 82.043095] [<ffff000008696f80>] sas_remove_children+0x40/0x50 [ 82.043100] [<ffff00000869d1bc>] sas_destruct_devices+0x64/0xa0 [ 82.043102] [<ffff0000080e93bc>] process_one_work+0x1fc/0x4b0 [ 82.043104] [<ffff0000080e96c0>] worker_thread+0x50/0x490 [ 82.043105] [<ffff0000080f0364>] kthread+0xfc/0x128 [ 82.043107] [<ffff0000080836c0>] ret_from_fork+0x10/0x50 Make probe and destruct a direct call in the disco and revalidate function, but put them outside the lock. The whole discovery or revalidate won't be interrupted by other events. And the DISCE_PROBE and DISCE_DESTRUCT event are deleted as a result of the direct call. Introduce a new list to destruct the sas_port and put the port delete after the destruct. This makes sure the right order of destroying the sysfs kobject and fix the warning above. In sas_ex_revalidate_domain() have a loop to find all broadcasted device, and sometimes we have a chance to find the same expander twice. Because the sas_port will be deleted at the end of the whole revalidate process, sas_port with the same name cannot be added before this. Otherwise the sysfs will complain of creating duplicate filename. Since the LLDD will send broadcast for every device change, we can only process one expander's revalidation. [mkp: kbuild test robot warning] Signed-off-by: Jason Yan <yanaijie@huawei.com> CC: John Garry <john.garry@huawei.com> CC: Johannes Thumshirn <jthumshirn@suse.de> CC: Ewan Milne <emilne@redhat.com> CC: Christoph Hellwig <hch@lst.de> CC: Tomas Henzl <thenzl@redhat.com> CC: Dan Williams <dan.j.williams@intel.com> Reviewed-by: Hannes Reinecke <hare@suse.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: LZWDecodeCompat(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s) { static const char module[] = "LZWDecodeCompat"; LZWCodecState *sp = DecoderState(tif); char *op = (char*) op0; long occ = (long) occ0; char *tp; unsigned char *bp; int code, nbits; long nextbits, nextdata, nbitsmask; code_t *codep, *free_entp, *maxcodep, *oldcodep; (void) s; assert(sp != NULL); /* Fail if value does not fit in long. */ if ((tmsize_t) occ != occ0) return (0); /* * Restart interrupted output operation. */ if (sp->dec_restart) { long residue; codep = sp->dec_codep; residue = codep->length - sp->dec_restart; if (residue > occ) { /* * Residue from previous decode is sufficient * to satisfy decode request. Skip to the * start of the decoded string, place decoded * values in the output buffer, and return. */ sp->dec_restart += occ; do { codep = codep->next; } while (--residue > occ); tp = op + occ; do { *--tp = codep->value; codep = codep->next; } while (--occ); return (1); } /* * Residue satisfies only part of the decode request. */ op += residue; occ -= residue; tp = op; do { *--tp = codep->value; codep = codep->next; } while (--residue); sp->dec_restart = 0; } bp = (unsigned char *)tif->tif_rawcp; #ifdef LZW_CHECKEOS sp->dec_bitsleft = (((uint64)tif->tif_rawcc) << 3); #endif nbits = sp->lzw_nbits; nextdata = sp->lzw_nextdata; nextbits = sp->lzw_nextbits; nbitsmask = sp->dec_nbitsmask; oldcodep = sp->dec_oldcodep; free_entp = sp->dec_free_entp; maxcodep = sp->dec_maxcodep; while (occ > 0) { NextCode(tif, sp, bp, code, GetNextCodeCompat); if (code == CODE_EOI) break; if (code == CODE_CLEAR) { do { free_entp = sp->dec_codetab + CODE_FIRST; _TIFFmemset(free_entp, 0, (CSIZE - CODE_FIRST) * sizeof (code_t)); nbits = BITS_MIN; nbitsmask = MAXCODE(BITS_MIN); maxcodep = sp->dec_codetab + nbitsmask; NextCode(tif, sp, bp, code, GetNextCodeCompat); } while (code == CODE_CLEAR); /* consecutive CODE_CLEAR codes */ if (code == CODE_EOI) break; if (code > CODE_CLEAR) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "LZWDecode: Corrupted LZW table at scanline %d", tif->tif_row); return (0); } *op++ = (char)code; occ--; oldcodep = sp->dec_codetab + code; continue; } codep = sp->dec_codetab + code; /* * Add the new entry to the code table. */ if (free_entp < &sp->dec_codetab[0] || free_entp >= &sp->dec_codetab[CSIZE]) { TIFFErrorExt(tif->tif_clientdata, module, "Corrupted LZW table at scanline %d", tif->tif_row); return (0); } free_entp->next = oldcodep; if (free_entp->next < &sp->dec_codetab[0] || free_entp->next >= &sp->dec_codetab[CSIZE]) { TIFFErrorExt(tif->tif_clientdata, module, "Corrupted LZW table at scanline %d", tif->tif_row); return (0); } free_entp->firstchar = free_entp->next->firstchar; free_entp->length = free_entp->next->length+1; free_entp->value = (codep < free_entp) ? codep->firstchar : free_entp->firstchar; if (++free_entp > maxcodep) { if (++nbits > BITS_MAX) /* should not happen */ nbits = BITS_MAX; nbitsmask = MAXCODE(nbits); maxcodep = sp->dec_codetab + nbitsmask; } oldcodep = codep; if (code >= 256) { /* * Code maps to a string, copy string * value to output (written in reverse). */ if(codep->length == 0) { TIFFErrorExt(tif->tif_clientdata, module, "Wrong length of decoded " "string: data probably corrupted at scanline %d", tif->tif_row); return (0); } if (codep->length > occ) { /* * String is too long for decode buffer, * locate portion that will fit, copy to * the decode buffer, and setup restart * logic for the next decoding call. */ sp->dec_codep = codep; do { codep = codep->next; } while (codep->length > occ); sp->dec_restart = occ; tp = op + occ; do { *--tp = codep->value; codep = codep->next; } while (--occ); break; } assert(occ >= codep->length); op += codep->length; occ -= codep->length; tp = op; do { *--tp = codep->value; } while( (codep = codep->next) != NULL ); } else { *op++ = (char)code; occ--; } } tif->tif_rawcc -= (tmsize_t)( (uint8*) bp - tif->tif_rawcp ); tif->tif_rawcp = (uint8*) bp; sp->lzw_nbits = (unsigned short)nbits; sp->lzw_nextdata = nextdata; sp->lzw_nextbits = nextbits; sp->dec_nbitsmask = nbitsmask; sp->dec_oldcodep = oldcodep; sp->dec_free_entp = free_entp; sp->dec_maxcodep = maxcodep; if (occ > 0) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "Not enough data at scanline %d (short %I64d bytes)", tif->tif_row, (unsigned __int64) occ); #else TIFFErrorExt(tif->tif_clientdata, module, "Not enough data at scanline %d (short %llu bytes)", tif->tif_row, (unsigned long long) occ); #endif return (0); } return (1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'LZWDecodeCompat(): fix potential index-out-of-bounds write. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2780 / CVE-2018-8905 The fix consists in using the similar code LZWDecode() to validate we don't write outside of the output buffer.'</s>
<s>[INST] Given the following code containing errors, provide 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_enc_encodemainbody(jpc_enc_t *enc) { int tileno; int tilex; int tiley; int i; jpc_sot_t *sot; jpc_enc_tcmpt_t *comp; jpc_enc_tcmpt_t *endcomps; jpc_enc_band_t *band; jpc_enc_band_t *endbands; jpc_enc_rlvl_t *lvl; int rlvlno; jpc_qcc_t *qcc; jpc_cod_t *cod; int adjust; int j; int absbandno; long numbytes; long tilehdrlen; long tilelen; jpc_enc_tile_t *tile; jpc_enc_cp_t *cp; double rho; int lyrno; int cmptno; int samestepsizes; jpc_enc_ccp_t *ccps; jpc_enc_tccp_t *tccp; int bandno; uint_fast32_t x; uint_fast32_t y; int mingbits; int actualnumbps; jpc_fix_t mxmag; jpc_fix_t mag; int numgbits; cp = enc->cp; /* Avoid compile warnings. */ numbytes = 0; for (tileno = 0; tileno < JAS_CAST(int, cp->numtiles); ++tileno) { tilex = tileno % cp->numhtiles; tiley = tileno / cp->numhtiles; if (!(enc->curtile = jpc_enc_tile_create(enc->cp, enc->image, tileno))) { jas_eprintf("cannot create tile\n"); return -1; } tile = enc->curtile; if (jas_getdbglevel() >= 10) { jpc_enc_dump(enc); } endcomps = &tile->tcmpts[tile->numtcmpts]; for (cmptno = 0, comp = tile->tcmpts; cmptno < tile->numtcmpts; ++cmptno, ++comp) { if (!cp->ccps[cmptno].sgnd) { adjust = 1 << (cp->ccps[cmptno].prec - 1); for (i = 0; i < jas_matrix_numrows(comp->data); ++i) { for (j = 0; j < jas_matrix_numcols(comp->data); ++j) { *jas_matrix_getref(comp->data, i, j) -= adjust; } } } } if (!tile->intmode) { endcomps = &tile->tcmpts[tile->numtcmpts]; for (comp = tile->tcmpts; comp != endcomps; ++comp) { jas_matrix_asl(comp->data, JPC_FIX_FRACBITS); } } switch (tile->mctid) { case JPC_MCT_RCT: assert(jas_image_numcmpts(enc->image) == 3); jpc_rct(tile->tcmpts[0].data, tile->tcmpts[1].data, tile->tcmpts[2].data); break; case JPC_MCT_ICT: assert(jas_image_numcmpts(enc->image) == 3); jpc_ict(tile->tcmpts[0].data, tile->tcmpts[1].data, tile->tcmpts[2].data); break; default: break; } for (i = 0; i < jas_image_numcmpts(enc->image); ++i) { comp = &tile->tcmpts[i]; jpc_tsfb_analyze(comp->tsfb, comp->data); } endcomps = &tile->tcmpts[tile->numtcmpts]; for (cmptno = 0, comp = tile->tcmpts; comp != endcomps; ++cmptno, ++comp) { mingbits = 0; absbandno = 0; /* All bands must have a corresponding quantizer step size, even if they contain no samples and are never coded. */ /* Some bands may not be hit by the loop below, so we must initialize all of the step sizes to a sane value. */ memset(comp->stepsizes, 0, sizeof(comp->stepsizes)); for (rlvlno = 0, lvl = comp->rlvls; rlvlno < comp->numrlvls; ++rlvlno, ++lvl) { if (!lvl->bands) { absbandno += rlvlno ? 3 : 1; continue; } endbands = &lvl->bands[lvl->numbands]; for (band = lvl->bands; band != endbands; ++band) { if (!band->data) { ++absbandno; continue; } actualnumbps = 0; mxmag = 0; for (y = 0; y < JAS_CAST(uint_fast32_t, jas_matrix_numrows(band->data)); ++y) { for (x = 0; x < JAS_CAST(uint_fast32_t, jas_matrix_numcols(band->data)); ++x) { mag = JAS_ABS(jas_matrix_get(band->data, y, x)); if (mag > mxmag) { mxmag = mag; } } } if (tile->intmode) { actualnumbps = jpc_firstone(mxmag) + 1; } else { actualnumbps = jpc_firstone(mxmag) + 1 - JPC_FIX_FRACBITS; } numgbits = actualnumbps - (cp->ccps[cmptno].prec - 1 + band->analgain); #if 0 jas_eprintf("%d %d mag=%d actual=%d numgbits=%d\n", cp->ccps[cmptno].prec, band->analgain, mxmag, actualnumbps, numgbits); #endif if (numgbits > mingbits) { mingbits = numgbits; } if (!tile->intmode) { band->absstepsize = jpc_fix_div(jpc_inttofix(1 << (band->analgain + 1)), band->synweight); } else { band->absstepsize = jpc_inttofix(1); } band->stepsize = jpc_abstorelstepsize( band->absstepsize, cp->ccps[cmptno].prec + band->analgain); band->numbps = cp->tccp.numgbits + JPC_QCX_GETEXPN(band->stepsize) - 1; if ((!tile->intmode) && band->data) { jpc_quantize(band->data, band->absstepsize); } comp->stepsizes[absbandno] = band->stepsize; ++absbandno; } } assert(JPC_FIX_FRACBITS >= JPC_NUMEXTRABITS); if (!tile->intmode) { jas_matrix_divpow2(comp->data, JPC_FIX_FRACBITS - JPC_NUMEXTRABITS); } else { jas_matrix_asl(comp->data, JPC_NUMEXTRABITS); } #if 0 jas_eprintf("mingbits %d\n", mingbits); #endif if (mingbits > cp->tccp.numgbits) { jas_eprintf("error: too few guard bits (need at least %d)\n", mingbits); return -1; } } if (!(enc->tmpstream = jas_stream_memopen(0, 0))) { jas_eprintf("cannot open tmp file\n"); return -1; } /* Write the tile header. */ if (!(enc->mrk = jpc_ms_create(JPC_MS_SOT))) { return -1; } sot = &enc->mrk->parms.sot; sot->len = 0; sot->tileno = tileno; sot->partno = 0; sot->numparts = 1; if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) { jas_eprintf("cannot write SOT marker\n"); return -1; } jpc_ms_destroy(enc->mrk); enc->mrk = 0; /************************************************************************/ /************************************************************************/ /************************************************************************/ tccp = &cp->tccp; for (cmptno = 0; cmptno < JAS_CAST(int, cp->numcmpts); ++cmptno) { comp = &tile->tcmpts[cmptno]; if (comp->numrlvls != tccp->maxrlvls) { if (!(enc->mrk = jpc_ms_create(JPC_MS_COD))) { return -1; } /* XXX = this is not really correct. we are using comp #0's precint sizes and other characteristics */ comp = &tile->tcmpts[0]; cod = &enc->mrk->parms.cod; cod->compparms.csty = 0; cod->compparms.numdlvls = comp->numrlvls - 1; cod->prg = tile->prg; cod->numlyrs = tile->numlyrs; cod->compparms.cblkwidthval = JPC_COX_CBLKSIZEEXPN(comp->cblkwidthexpn); cod->compparms.cblkheightval = JPC_COX_CBLKSIZEEXPN(comp->cblkheightexpn); cod->compparms.cblksty = comp->cblksty; cod->compparms.qmfbid = comp->qmfbid; cod->mctrans = (tile->mctid != JPC_MCT_NONE); for (i = 0; i < comp->numrlvls; ++i) { cod->compparms.rlvls[i].parwidthval = comp->rlvls[i].prcwidthexpn; cod->compparms.rlvls[i].parheightval = comp->rlvls[i].prcheightexpn; } if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) { return -1; } jpc_ms_destroy(enc->mrk); enc->mrk = 0; } } for (cmptno = 0, comp = tile->tcmpts; cmptno < JAS_CAST(int, cp->numcmpts); ++cmptno, ++comp) { ccps = &cp->ccps[cmptno]; if (JAS_CAST(int, ccps->numstepsizes) == comp->numstepsizes) { samestepsizes = 1; for (bandno = 0; bandno < JAS_CAST(int, ccps->numstepsizes); ++bandno) { if (ccps->stepsizes[bandno] != comp->stepsizes[bandno]) { samestepsizes = 0; break; } } } else { samestepsizes = 0; } if (!samestepsizes) { if (!(enc->mrk = jpc_ms_create(JPC_MS_QCC))) { return -1; } qcc = &enc->mrk->parms.qcc; qcc->compno = cmptno; qcc->compparms.numguard = cp->tccp.numgbits; qcc->compparms.qntsty = (comp->qmfbid == JPC_COX_INS) ? JPC_QCX_SEQNT : JPC_QCX_NOQNT; qcc->compparms.numstepsizes = comp->numstepsizes; qcc->compparms.stepsizes = comp->stepsizes; if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) { return -1; } qcc->compparms.stepsizes = 0; jpc_ms_destroy(enc->mrk); enc->mrk = 0; } } /* Write a SOD marker to indicate the end of the tile header. */ if (!(enc->mrk = jpc_ms_create(JPC_MS_SOD))) { return -1; } if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) { jas_eprintf("cannot write SOD marker\n"); return -1; } jpc_ms_destroy(enc->mrk); enc->mrk = 0; tilehdrlen = jas_stream_getrwcount(enc->tmpstream); assert(tilehdrlen >= 0); /************************************************************************/ /************************************************************************/ /************************************************************************/ if (jpc_enc_enccblks(enc)) { abort(); return -1; } cp = enc->cp; rho = (double) (tile->brx - tile->tlx) * (tile->bry - tile->tly) / ((cp->refgrdwidth - cp->imgareatlx) * (cp->refgrdheight - cp->imgareatly)); tile->rawsize = cp->rawsize * rho; for (lyrno = 0; lyrno < tile->numlyrs - 1; ++lyrno) { tile->lyrsizes[lyrno] = tile->rawsize * jpc_fixtodbl( cp->tcp.ilyrrates[lyrno]); } #if !defined(__clang__) // WARNING: // Some versions of Clang (e.g., 3.7.1 and 3.8.1) appear to generate // incorrect code for the following line. tile->lyrsizes[tile->numlyrs - 1] = (cp->totalsize != UINT_FAST32_MAX) ? (rho * enc->mainbodysize) : UINT_FAST32_MAX; #else if (cp->totalsize != UINT_FAST32_MAX) { tile->lyrsizes[tile->numlyrs - 1] = (rho * enc->mainbodysize); } else { tile->lyrsizes[tile->numlyrs - 1] = UINT_FAST32_MAX; } #endif //jas_eprintf("TESTING %ld %ld\n", cp->totalsize != UINT_FAST32_MAX, tile->lyrsizes[0]); for (lyrno = 0; lyrno < tile->numlyrs; ++lyrno) { if (tile->lyrsizes[lyrno] != UINT_FAST32_MAX) { if (JAS_CAST(uint_fast32_t, tilehdrlen) <= tile->lyrsizes[lyrno]) { tile->lyrsizes[lyrno] -= tilehdrlen; } else { tile->lyrsizes[lyrno] = 0; } } } if (rateallocate(enc, tile->numlyrs, tile->lyrsizes)) { return -1; } #if 0 jas_eprintf("ENCODE TILE DATA\n"); #endif if (jpc_enc_encodetiledata(enc)) { jas_eprintf("dotile failed\n"); return -1; } /************************************************************************/ /************************************************************************/ /************************************************************************/ /************************************************************************/ /************************************************************************/ /************************************************************************/ tilelen = jas_stream_tell(enc->tmpstream); if (jas_stream_seek(enc->tmpstream, 6, SEEK_SET) < 0) { return -1; } jpc_putuint32(enc->tmpstream, tilelen); if (jas_stream_seek(enc->tmpstream, 0, SEEK_SET) < 0) { return -1; } if (jpc_putdata(enc->out, enc->tmpstream, -1)) { return -1; } enc->len += tilelen; jas_stream_close(enc->tmpstream); enc->tmpstream = 0; jpc_enc_tile_destroy(enc->curtile); enc->curtile = 0; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-617'], 'message': 'jpc_math: split jpc_firstone() in int/jpc_fix_t overloads Fixes CVE-2018-9055 (denial of service via a reachable assertion due to integer overflow). Based on a patch from Fridrich Strba <fstrba@suse.com>. Instead of switching to `int_fast32_t`, this patch splits jpc_firstone() into two overloads, one for `int` and one for `jpc_fix_t`. This is safer against future changes on `jpc_fix_t`. To avoid the overhead of 64 bit integer math on 32 bit CPUs, this leaves the `int` overload around. Closes https://github.com/jasper-maint/jasper/issues/9'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: rb_push_glob(VALUE str, VALUE base, int flags) /* '\0' is delimiter */ { long offset = 0; VALUE ary; GlobPathValue(str, TRUE); ary = rb_ary_new(); while (offset < RSTRING_LEN(str)) { char *p, *pend; int status; p = RSTRING_PTR(str) + offset; status = push_glob(ary, rb_enc_str_new(p, strlen(p), rb_enc_get(str)), base, flags); if (status) GLOB_JUMP_TAG(status); if (offset >= RSTRING_LEN(str)) break; p += strlen(p) + 1; pend = RSTRING_PTR(str) + RSTRING_LEN(str); while (p < pend && !*p) p++; offset = p - RSTRING_PTR(str); } return ary; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'dir.c: check NUL bytes * dir.c (GlobPathValue): should be used in rb_push_glob only. other methods should use FilePathValue. https://hackerone.com/reports/302338 * dir.c (rb_push_glob): expand GlobPathValue git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@62989 b2dd03c8-39d4-4d8f-98ff-823fe69b080e'</s>
<s>[INST] Given the following code containing errors, provide 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 sanity_check_raw_super(struct super_block *sb, struct f2fs_super_block *raw_super) { unsigned int blocksize; if (F2FS_SUPER_MAGIC != le32_to_cpu(raw_super->magic)) { f2fs_msg(sb, KERN_INFO, "Magic Mismatch, valid(0x%x) - read(0x%x)", F2FS_SUPER_MAGIC, le32_to_cpu(raw_super->magic)); return 1; } /* Currently, support only 4KB page cache size */ if (F2FS_BLKSIZE != PAGE_CACHE_SIZE) { f2fs_msg(sb, KERN_INFO, "Invalid page_cache_size (%lu), supports only 4KB\n", PAGE_CACHE_SIZE); return 1; } /* Currently, support only 4KB block size */ blocksize = 1 << le32_to_cpu(raw_super->log_blocksize); if (blocksize != F2FS_BLKSIZE) { f2fs_msg(sb, KERN_INFO, "Invalid blocksize (%u), supports only 4KB\n", blocksize); return 1; } /* Currently, support 512/1024/2048/4096 bytes sector size */ if (le32_to_cpu(raw_super->log_sectorsize) > F2FS_MAX_LOG_SECTOR_SIZE || le32_to_cpu(raw_super->log_sectorsize) < F2FS_MIN_LOG_SECTOR_SIZE) { f2fs_msg(sb, KERN_INFO, "Invalid log sectorsize (%u)", le32_to_cpu(raw_super->log_sectorsize)); return 1; } if (le32_to_cpu(raw_super->log_sectors_per_block) + le32_to_cpu(raw_super->log_sectorsize) != F2FS_MAX_LOG_SECTOR_SIZE) { f2fs_msg(sb, KERN_INFO, "Invalid log sectors per block(%u) log sectorsize(%u)", le32_to_cpu(raw_super->log_sectors_per_block), le32_to_cpu(raw_super->log_sectorsize)); return 1; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'f2fs: do more integrity verification for superblock Do more sanity check for superblock during ->mount. Signed-off-by: Chao Yu <chao2.yu@samsung.com> Signed-off-by: Jaegeuk Kim <jaegeuk@kernel.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int __get_data_block(struct inode *inode, sector_t iblock, struct buffer_head *bh, int create, int flag, pgoff_t *next_pgofs) { struct f2fs_map_blocks map; int err; map.m_lblk = iblock; map.m_len = bh->b_size >> inode->i_blkbits; map.m_next_pgofs = next_pgofs; err = f2fs_map_blocks(inode, &map, create, flag); if (!err) { map_bh(bh, inode->i_sb, map.m_pblk); bh->b_state = (bh->b_state & ~F2FS_MAP_FLAGS) | map.m_flags; bh->b_size = map.m_len << inode->i_blkbits; } return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'f2fs: fix a dead loop in f2fs_fiemap() A dead loop can be triggered in f2fs_fiemap() using the test case as below: ... fd = open(); fallocate(fd, 0, 0, 4294967296); ioctl(fd, FS_IOC_FIEMAP, fiemap_buf); ... It's caused by an overflow in __get_data_block(): ... bh->b_size = map.m_len << inode->i_blkbits; ... map.m_len is an unsigned int, and bh->b_size is a size_t which is 64 bits on 64 bits archtecture, type conversion from an unsigned int to a size_t will result in an overflow. In the above-mentioned case, bh->b_size will be zero, and f2fs_fiemap() will call get_data_block() at block 0 again an again. Fix this by adding a force conversion before left shift. Signed-off-by: Wei Fang <fangwei1@huawei.com> Acked-by: Chao Yu <yuchao0@huawei.com> Signed-off-by: Jaegeuk Kim <jaegeuk@kernel.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xz_head(xz_statep state) { lzma_stream *strm = &(state->strm); lzma_stream init = LZMA_STREAM_INIT; int flags; unsigned len; /* allocate read buffers and inflate memory */ if (state->size == 0) { /* allocate buffers */ state->in = xmlMalloc(state->want); state->out = xmlMalloc(state->want << 1); if (state->in == NULL || state->out == NULL) { if (state->out != NULL) xmlFree(state->out); if (state->in != NULL) xmlFree(state->in); xz_error(state, LZMA_MEM_ERROR, "out of memory"); return -1; } state->size = state->want; /* allocate decoder memory */ state->strm = init; state->strm.avail_in = 0; state->strm.next_in = NULL; if (lzma_auto_decoder(&state->strm, UINT64_MAX, 0) != LZMA_OK) { xmlFree(state->out); xmlFree(state->in); state->size = 0; xz_error(state, LZMA_MEM_ERROR, "out of memory"); return -1; } #ifdef HAVE_ZLIB_H /* allocate inflate memory */ state->zstrm.zalloc = Z_NULL; state->zstrm.zfree = Z_NULL; state->zstrm.opaque = Z_NULL; state->zstrm.avail_in = 0; state->zstrm.next_in = Z_NULL; if (state->init == 0) { if (inflateInit2(&(state->zstrm), -15) != Z_OK) {/* raw inflate */ xmlFree(state->out); xmlFree(state->in); state->size = 0; xz_error(state, LZMA_MEM_ERROR, "out of memory"); return -1; } state->init = 1; } #endif } /* get some data in the input buffer */ if (strm->avail_in == 0) { if (xz_avail(state) == -1) return -1; if (strm->avail_in == 0) return 0; } /* look for the xz magic header bytes */ if (is_format_xz(state) || is_format_lzma(state)) { state->how = LZMA; state->direct = 0; return 0; } #ifdef HAVE_ZLIB_H /* look for the gzip magic header bytes 31 and 139 */ if (strm->next_in[0] == 31) { strm->avail_in--; strm->next_in++; if (strm->avail_in == 0 && xz_avail(state) == -1) return -1; if (strm->avail_in && strm->next_in[0] == 139) { /* we have a gzip header, woo hoo! */ strm->avail_in--; strm->next_in++; /* skip rest of header */ if (NEXT() != 8) { /* compression method */ xz_error(state, LZMA_DATA_ERROR, "unknown compression method"); return -1; } flags = NEXT(); if (flags & 0xe0) { /* reserved flag bits */ xz_error(state, LZMA_DATA_ERROR, "unknown header flags set"); return -1; } NEXT(); /* modification time */ NEXT(); NEXT(); NEXT(); NEXT(); /* extra flags */ NEXT(); /* operating system */ if (flags & 4) { /* extra field */ len = (unsigned) NEXT(); len += (unsigned) NEXT() << 8; while (len--) if (NEXT() < 0) break; } if (flags & 8) /* file name */ while (NEXT() > 0) ; if (flags & 16) /* comment */ while (NEXT() > 0) ; if (flags & 2) { /* header crc */ NEXT(); NEXT(); } /* an unexpected end of file is not checked for here -- it will be * noticed on the first request for uncompressed data */ /* set up for decompression */ inflateReset(&state->zstrm); state->zstrm.adler = crc32(0L, Z_NULL, 0); state->how = GZIP; state->direct = 0; return 0; } else { /* not a gzip file -- save first byte (31) and fall to raw i/o */ state->out[0] = 31; state->have = 1; } } #endif /* doing raw i/o, save start of raw data for seeking, copy any leftover * input to output -- this assumes that the output buffer is larger than * the input buffer, which also assures space for gzungetc() */ state->raw = state->pos; state->next = state->out; if (strm->avail_in) { memcpy(state->next + state->have, strm->next_in, strm->avail_in); state->have += strm->avail_in; strm->avail_in = 0; } state->how = COPY; state->direct = 1; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-770'], 'message': 'Set memory limit for LZMA decompression Otherwise malicious LZMA compressed files could consume large amounts of memory when decompressed. According to the xz man page, files compressed with `xz -9` currently require 65 MB to decompress, so set the limit to 100 MB. Should fix bug 786696.'</s>
<s>[INST] Given the following code containing errors, provide 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 ParseWave64HeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int64_t total_samples = 0, infilesize; Wave64ChunkHeader chunk_header; Wave64FileHeader filehdr; WaveHeader WaveHeader; uint32_t bcount; infilesize = DoGetFileSize (infile); memcpy (&filehdr, fourcc, 4); if (!DoReadFile (infile, ((char *) &filehdr) + 4, sizeof (Wave64FileHeader) - 4, &bcount) || bcount != sizeof (Wave64FileHeader) - 4 || memcmp (filehdr.ckID, riff_guid, sizeof (riff_guid)) || memcmp (filehdr.formType, wave_guid, sizeof (wave_guid))) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &filehdr, sizeof (filehdr))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } #if 1 // this might be a little too picky... WavpackLittleEndianToNative (&filehdr, Wave64ChunkHeaderFormat); if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && filehdr.ckSize && filehdr.ckSize + 1 && filehdr.ckSize != infilesize) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } #endif // loop through all elements of the wave64 header // (until the data chuck) and copy them to the output file while (1) { if (!DoReadFile (infile, &chunk_header, sizeof (Wave64ChunkHeader), &bcount) || bcount != sizeof (Wave64ChunkHeader)) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &chunk_header, sizeof (Wave64ChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&chunk_header, Wave64ChunkHeaderFormat); chunk_header.ckSize -= sizeof (chunk_header); // if it's the format chunk, we want to get some info out of there and // make sure it's a .wav file we can handle if (!memcmp (chunk_header.ckID, fmt_guid, sizeof (fmt_guid))) { int supported = TRUE, format; chunk_header.ckSize = (chunk_header.ckSize + 7) & ~7L; if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) || !DoReadFile (infile, &WaveHeader, (uint32_t) chunk_header.ckSize, &bcount) || bcount != chunk_header.ckSize) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &WaveHeader, (uint32_t) chunk_header.ckSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&WaveHeader, WaveHeaderFormat); if (debug_logging_mode) { error_line ("format tag size = %d", chunk_header.ckSize); error_line ("FormatTag = %x, NumChannels = %d, BitsPerSample = %d", WaveHeader.FormatTag, WaveHeader.NumChannels, WaveHeader.BitsPerSample); error_line ("BlockAlign = %d, SampleRate = %d, BytesPerSecond = %d", WaveHeader.BlockAlign, WaveHeader.SampleRate, WaveHeader.BytesPerSecond); if (chunk_header.ckSize > 16) error_line ("cbSize = %d, ValidBitsPerSample = %d", WaveHeader.cbSize, WaveHeader.ValidBitsPerSample); if (chunk_header.ckSize > 20) error_line ("ChannelMask = %x, SubFormat = %d", WaveHeader.ChannelMask, WaveHeader.SubFormat); } if (chunk_header.ckSize > 16 && WaveHeader.cbSize == 2) config->qmode |= QMODE_ADOBE_MODE; format = (WaveHeader.FormatTag == 0xfffe && chunk_header.ckSize == 40) ? WaveHeader.SubFormat : WaveHeader.FormatTag; config->bits_per_sample = (chunk_header.ckSize == 40 && WaveHeader.ValidBitsPerSample) ? WaveHeader.ValidBitsPerSample : WaveHeader.BitsPerSample; if (format != 1 && format != 3) supported = FALSE; if (format == 3 && config->bits_per_sample != 32) supported = FALSE; if (!WaveHeader.NumChannels || WaveHeader.NumChannels > 256 || WaveHeader.BlockAlign / WaveHeader.NumChannels < (config->bits_per_sample + 7) / 8 || WaveHeader.BlockAlign / WaveHeader.NumChannels > 4 || WaveHeader.BlockAlign % WaveHeader.NumChannels) supported = FALSE; if (config->bits_per_sample < 1 || config->bits_per_sample > 32) supported = FALSE; if (!supported) { error_line ("%s is an unsupported .W64 format!", infilename); return WAVPACK_SOFT_ERROR; } if (chunk_header.ckSize < 40) { if (!config->channel_mask && !(config->qmode & QMODE_CHANS_UNASSIGNED)) { if (WaveHeader.NumChannels <= 2) config->channel_mask = 0x5 - WaveHeader.NumChannels; else if (WaveHeader.NumChannels <= 18) config->channel_mask = (1 << WaveHeader.NumChannels) - 1; else config->channel_mask = 0x3ffff; } } else if (WaveHeader.ChannelMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this W64 file already has channel order information!"); return WAVPACK_SOFT_ERROR; } else if (WaveHeader.ChannelMask) config->channel_mask = WaveHeader.ChannelMask; if (format == 3) config->float_norm_exp = 127; else if ((config->qmode & QMODE_ADOBE_MODE) && WaveHeader.BlockAlign / WaveHeader.NumChannels == 4) { if (WaveHeader.BitsPerSample == 24) config->float_norm_exp = 127 + 23; else if (WaveHeader.BitsPerSample == 32) config->float_norm_exp = 127 + 15; } if (debug_logging_mode) { if (config->float_norm_exp == 127) error_line ("data format: normalized 32-bit floating point"); else error_line ("data format: %d-bit integers stored in %d byte(s)", config->bits_per_sample, WaveHeader.BlockAlign / WaveHeader.NumChannels); } } else if (!memcmp (chunk_header.ckID, data_guid, sizeof (data_guid))) { // on the data chunk, get size and exit loop if (!WaveHeader.NumChannels) { // make sure we saw "fmt" chunk error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } if ((config->qmode & QMODE_IGNORE_LENGTH) || chunk_header.ckSize <= 0) { config->qmode |= QMODE_IGNORE_LENGTH; if (infilesize && DoGetFilePosition (infile) != -1) total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign; else total_samples = -1; } else { if (infilesize && infilesize - chunk_header.ckSize > 16777216) { error_line ("this .W64 file has over 16 MB of extra RIFF data, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } total_samples = chunk_header.ckSize / WaveHeader.BlockAlign; if (!total_samples) { error_line ("this .W64 file has no audio samples, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (total_samples > MAX_WAVPACK_SAMPLES) { error_line ("%s has too many samples for WavPack!", infilename); return WAVPACK_SOFT_ERROR; } } config->bytes_per_sample = WaveHeader.BlockAlign / WaveHeader.NumChannels; config->num_channels = WaveHeader.NumChannels; config->sample_rate = WaveHeader.SampleRate; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (chunk_header.ckSize + 7) & ~7L; char *buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", chunk_header.ckID [0], chunk_header.ckID [1], chunk_header.ckID [2], chunk_header.ckID [3], chunk_header.ckSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'issue #33, sanitize size of unknown chunks before malloc()'</s>
<s>[INST] Given the following code containing errors, provide 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 DaemonServer::ms_verify_authorizer(Connection *con, int peer_type, int protocol, ceph::bufferlist& authorizer_data, ceph::bufferlist& authorizer_reply, bool& is_valid, CryptoKey& session_key) { AuthAuthorizeHandler *handler = nullptr; if (peer_type == CEPH_ENTITY_TYPE_OSD || peer_type == CEPH_ENTITY_TYPE_MON || peer_type == CEPH_ENTITY_TYPE_MDS || peer_type == CEPH_ENTITY_TYPE_MGR) { handler = auth_cluster_registry.get_handler(protocol); } else { handler = auth_service_registry.get_handler(protocol); } if (!handler) { dout(0) << "No AuthAuthorizeHandler found for protocol " << protocol << dendl; is_valid = false; return true; } MgrSessionRef s(new MgrSession(cct)); s->inst.addr = con->get_peer_addr(); AuthCapsInfo caps_info; RotatingKeyRing *keys = monc->rotating_secrets.get(); if (keys) { is_valid = handler->verify_authorizer( cct, keys, authorizer_data, authorizer_reply, s->entity_name, s->global_id, caps_info, session_key); } else { dout(10) << __func__ << " no rotating_keys (yet), denied" << dendl; is_valid = false; } if (is_valid) { if (caps_info.allow_all) { dout(10) << " session " << s << " " << s->entity_name << " allow_all" << dendl; s->caps.set_allow_all(); } if (caps_info.caps.length() > 0) { bufferlist::iterator p = caps_info.caps.begin(); string str; try { ::decode(str, p); } catch (buffer::error& e) { } bool success = s->caps.parse(str); if (success) { dout(10) << " session " << s << " " << s->entity_name << " has caps " << s->caps << " '" << str << "'" << dendl; } else { dout(10) << " session " << s << " " << s->entity_name << " failed to parse caps '" << str << "'" << dendl; is_valid = false; } } con->set_priv(s->get()); if (peer_type == CEPH_ENTITY_TYPE_OSD) { Mutex::Locker l(lock); s->osd_id = atoi(s->entity_name.get_id().c_str()); dout(10) << "registering osd." << s->osd_id << " session " << s << " con " << con << dendl; osd_cons[s->osd_id].insert(con); } } return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'auth/cephx: add authorizer challenge Allow the accepting side of a connection to reject an initial authorizer with a random challenge. The connecting side then has to respond with an updated authorizer proving they are able to decrypt the service's challenge and that the new authorizer was produced for this specific connection instance. The accepting side requires this challenge and response unconditionally if the client side advertises they have the feature bit. Servers wishing to require this improved level of authentication simply have to require the appropriate feature. Signed-off-by: Sage Weil <sage@redhat.com> (cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b) # Conflicts: # src/auth/Auth.h # src/auth/cephx/CephxProtocol.cc # src/auth/cephx/CephxProtocol.h # src/auth/none/AuthNoneProtocol.h # src/msg/Dispatcher.h # src/msg/async/AsyncConnection.cc - const_iterator - ::decode vs decode - AsyncConnection ctor arg noise - get_random_bytes(), not cct->random()'</s>
<s>[INST] Given the following code containing errors, provide 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 ms_verify_authorizer(Connection *con, int peer_type, int protocol, bufferlist& authorizer_data, bufferlist& authorizer_reply, bool& isvalid, CryptoKey& session_key) override { isvalid = true; return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'auth/cephx: add authorizer challenge Allow the accepting side of a connection to reject an initial authorizer with a random challenge. The connecting side then has to respond with an updated authorizer proving they are able to decrypt the service's challenge and that the new authorizer was produced for this specific connection instance. The accepting side requires this challenge and response unconditionally if the client side advertises they have the feature bit. Servers wishing to require this improved level of authentication simply have to require the appropriate feature. Signed-off-by: Sage Weil <sage@redhat.com> (cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b) # Conflicts: # src/auth/Auth.h # src/auth/cephx/CephxProtocol.cc # src/auth/cephx/CephxProtocol.h # src/auth/none/AuthNoneProtocol.h # src/msg/Dispatcher.h # src/msg/async/AsyncConnection.cc - const_iterator - ::decode vs decode - AsyncConnection ctor arg noise - get_random_bytes(), not cct->random()'</s>
<s>[INST] Given the following code containing errors, provide 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 cephx_verify_authorizer(CephContext *cct, KeyStore *keys, bufferlist::iterator& indata, CephXServiceTicketInfo& ticket_info, bufferlist& reply_bl) { __u8 authorizer_v; uint32_t service_id; uint64_t global_id; CryptoKey service_secret; // ticket blob CephXTicketBlob ticket; try { ::decode(authorizer_v, indata); ::decode(global_id, indata); ::decode(service_id, indata); ::decode(ticket, indata); } catch (buffer::end_of_buffer &e) { // Unable to decode! return false; } ldout(cct, 10) << "verify_authorizer decrypted service " << ceph_entity_type_name(service_id) << " secret_id=" << ticket.secret_id << dendl; if (ticket.secret_id == (uint64_t)-1) { EntityName name; name.set_type(service_id); if (!keys->get_secret(name, service_secret)) { ldout(cct, 0) << "verify_authorizer could not get general service secret for service " << ceph_entity_type_name(service_id) << " secret_id=" << ticket.secret_id << dendl; return false; } } else { if (!keys->get_service_secret(service_id, ticket.secret_id, service_secret)) { ldout(cct, 0) << "verify_authorizer could not get service secret for service " << ceph_entity_type_name(service_id) << " secret_id=" << ticket.secret_id << dendl; if (cct->_conf->auth_debug && ticket.secret_id == 0) assert(0 == "got secret_id=0"); return false; } } std::string error; if (!service_secret.get_secret().length()) error = "invalid key"; // Bad key? else decode_decrypt_enc_bl(cct, ticket_info, service_secret, ticket.blob, error); if (!error.empty()) { ldout(cct, 0) << "verify_authorizer could not decrypt ticket info: error: " << error << dendl; return false; } if (ticket_info.ticket.global_id != global_id) { ldout(cct, 0) << "verify_authorizer global_id mismatch: declared id=" << global_id << " ticket_id=" << ticket_info.ticket.global_id << dendl; return false; } ldout(cct, 10) << "verify_authorizer global_id=" << global_id << dendl; // CephXAuthorize CephXAuthorize auth_msg; if (decode_decrypt(cct, auth_msg, ticket_info.session_key, indata, error)) { ldout(cct, 0) << "verify_authorizercould not decrypt authorize request with error: " << error << dendl; return false; } /* * Reply authorizer: * {timestamp + 1}^session_key */ CephXAuthorizeReply reply; // reply.trans_id = auth_msg.trans_id; reply.nonce_plus_one = auth_msg.nonce + 1; if (encode_encrypt(cct, reply, ticket_info.session_key, reply_bl, error)) { ldout(cct, 10) << "verify_authorizer: encode_encrypt error: " << error << dendl; return false; } ldout(cct, 10) << "verify_authorizer ok nonce " << hex << auth_msg.nonce << dec << " reply_bl.length()=" << reply_bl.length() << dendl; return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-287', 'CWE-284'], 'message': 'auth/cephx: add authorizer challenge Allow the accepting side of a connection to reject an initial authorizer with a random challenge. The connecting side then has to respond with an updated authorizer proving they are able to decrypt the service's challenge and that the new authorizer was produced for this specific connection instance. The accepting side requires this challenge and response unconditionally if the client side advertises they have the feature bit. Servers wishing to require this improved level of authentication simply have to require the appropriate feature. Signed-off-by: Sage Weil <sage@redhat.com> (cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b) # Conflicts: # src/auth/Auth.h # src/auth/cephx/CephxProtocol.cc # src/auth/cephx/CephxProtocol.h # src/auth/none/AuthNoneProtocol.h # src/msg/Dispatcher.h # src/msg/async/AsyncConnection.cc - const_iterator - ::decode vs decode - AsyncConnection ctor arg noise - get_random_bytes(), not cct->random()'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TIFFWriteDirectorySec(TIFF* tif, int isimage, int imagedone, uint64* pdiroff) { static const char module[] = "TIFFWriteDirectorySec"; uint32 ndir; TIFFDirEntry* dir; uint32 dirsize; void* dirmem; uint32 m; if (tif->tif_mode == O_RDONLY) return (1); _TIFFFillStriles( tif ); /* * Clear write state so that subsequent images with * different characteristics get the right buffers * setup for them. */ if (imagedone) { if (tif->tif_flags & TIFF_POSTENCODE) { tif->tif_flags &= ~TIFF_POSTENCODE; if (!(*tif->tif_postencode)(tif)) { TIFFErrorExt(tif->tif_clientdata,module, "Error post-encoding before directory write"); return (0); } } (*tif->tif_close)(tif); /* shutdown encoder */ /* * Flush any data that might have been written * by the compression close+cleanup routines. But * be careful not to write stuff if we didn't add data * in the previous steps as the "rawcc" data may well be * a previously read tile/strip in mixed read/write mode. */ if (tif->tif_rawcc > 0 && (tif->tif_flags & TIFF_BEENWRITING) != 0 ) { if( !TIFFFlushData1(tif) ) { TIFFErrorExt(tif->tif_clientdata, module, "Error flushing data before directory write"); return (0); } } if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata) { _TIFFfree(tif->tif_rawdata); tif->tif_rawdata = NULL; tif->tif_rawcc = 0; tif->tif_rawdatasize = 0; tif->tif_rawdataoff = 0; tif->tif_rawdataloaded = 0; } tif->tif_flags &= ~(TIFF_BEENWRITING|TIFF_BUFFERSETUP); } dir=NULL; dirmem=NULL; dirsize=0; while (1) { ndir=0; if (isimage) { if (TIFFFieldSet(tif,FIELD_IMAGEDIMENSIONS)) { if (!TIFFWriteDirectoryTagShortLong(tif,&ndir,dir,TIFFTAG_IMAGEWIDTH,tif->tif_dir.td_imagewidth)) goto bad; if (!TIFFWriteDirectoryTagShortLong(tif,&ndir,dir,TIFFTAG_IMAGELENGTH,tif->tif_dir.td_imagelength)) goto bad; } if (TIFFFieldSet(tif,FIELD_TILEDIMENSIONS)) { if (!TIFFWriteDirectoryTagShortLong(tif,&ndir,dir,TIFFTAG_TILEWIDTH,tif->tif_dir.td_tilewidth)) goto bad; if (!TIFFWriteDirectoryTagShortLong(tif,&ndir,dir,TIFFTAG_TILELENGTH,tif->tif_dir.td_tilelength)) goto bad; } if (TIFFFieldSet(tif,FIELD_RESOLUTION)) { if (!TIFFWriteDirectoryTagRational(tif,&ndir,dir,TIFFTAG_XRESOLUTION,tif->tif_dir.td_xresolution)) goto bad; if (!TIFFWriteDirectoryTagRational(tif,&ndir,dir,TIFFTAG_YRESOLUTION,tif->tif_dir.td_yresolution)) goto bad; } if (TIFFFieldSet(tif,FIELD_POSITION)) { if (!TIFFWriteDirectoryTagRational(tif,&ndir,dir,TIFFTAG_XPOSITION,tif->tif_dir.td_xposition)) goto bad; if (!TIFFWriteDirectoryTagRational(tif,&ndir,dir,TIFFTAG_YPOSITION,tif->tif_dir.td_yposition)) goto bad; } if (TIFFFieldSet(tif,FIELD_SUBFILETYPE)) { if (!TIFFWriteDirectoryTagLong(tif,&ndir,dir,TIFFTAG_SUBFILETYPE,tif->tif_dir.td_subfiletype)) goto bad; } if (TIFFFieldSet(tif,FIELD_BITSPERSAMPLE)) { if (!TIFFWriteDirectoryTagShortPerSample(tif,&ndir,dir,TIFFTAG_BITSPERSAMPLE,tif->tif_dir.td_bitspersample)) goto bad; } if (TIFFFieldSet(tif,FIELD_COMPRESSION)) { if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_COMPRESSION,tif->tif_dir.td_compression)) goto bad; } if (TIFFFieldSet(tif,FIELD_PHOTOMETRIC)) { if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_PHOTOMETRIC,tif->tif_dir.td_photometric)) goto bad; } if (TIFFFieldSet(tif,FIELD_THRESHHOLDING)) { if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_THRESHHOLDING,tif->tif_dir.td_threshholding)) goto bad; } if (TIFFFieldSet(tif,FIELD_FILLORDER)) { if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_FILLORDER,tif->tif_dir.td_fillorder)) goto bad; } if (TIFFFieldSet(tif,FIELD_ORIENTATION)) { if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_ORIENTATION,tif->tif_dir.td_orientation)) goto bad; } if (TIFFFieldSet(tif,FIELD_SAMPLESPERPIXEL)) { if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_SAMPLESPERPIXEL,tif->tif_dir.td_samplesperpixel)) goto bad; } if (TIFFFieldSet(tif,FIELD_ROWSPERSTRIP)) { if (!TIFFWriteDirectoryTagShortLong(tif,&ndir,dir,TIFFTAG_ROWSPERSTRIP,tif->tif_dir.td_rowsperstrip)) goto bad; } if (TIFFFieldSet(tif,FIELD_MINSAMPLEVALUE)) { if (!TIFFWriteDirectoryTagShortPerSample(tif,&ndir,dir,TIFFTAG_MINSAMPLEVALUE,tif->tif_dir.td_minsamplevalue)) goto bad; } if (TIFFFieldSet(tif,FIELD_MAXSAMPLEVALUE)) { if (!TIFFWriteDirectoryTagShortPerSample(tif,&ndir,dir,TIFFTAG_MAXSAMPLEVALUE,tif->tif_dir.td_maxsamplevalue)) goto bad; } if (TIFFFieldSet(tif,FIELD_PLANARCONFIG)) { if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_PLANARCONFIG,tif->tif_dir.td_planarconfig)) goto bad; } if (TIFFFieldSet(tif,FIELD_RESOLUTIONUNIT)) { if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_RESOLUTIONUNIT,tif->tif_dir.td_resolutionunit)) goto bad; } if (TIFFFieldSet(tif,FIELD_PAGENUMBER)) { if (!TIFFWriteDirectoryTagShortArray(tif,&ndir,dir,TIFFTAG_PAGENUMBER,2,&tif->tif_dir.td_pagenumber[0])) goto bad; } if (TIFFFieldSet(tif,FIELD_STRIPBYTECOUNTS)) { if (!isTiled(tif)) { if (!TIFFWriteDirectoryTagLongLong8Array(tif,&ndir,dir,TIFFTAG_STRIPBYTECOUNTS,tif->tif_dir.td_nstrips,tif->tif_dir.td_stripbytecount)) goto bad; } else { if (!TIFFWriteDirectoryTagLongLong8Array(tif,&ndir,dir,TIFFTAG_TILEBYTECOUNTS,tif->tif_dir.td_nstrips,tif->tif_dir.td_stripbytecount)) goto bad; } } if (TIFFFieldSet(tif,FIELD_STRIPOFFSETS)) { if (!isTiled(tif)) { /* td_stripoffset might be NULL in an odd OJPEG case. See * tif_dirread.c around line 3634. * XXX: OJPEG hack. * If a) compression is OJPEG, b) it's not a tiled TIFF, * and c) the number of strips is 1, * then we tolerate the absence of stripoffsets tag, * because, presumably, all required data is in the * JpegInterchangeFormat stream. * We can get here when using tiffset on such a file. * See http://bugzilla.maptools.org/show_bug.cgi?id=2500 */ if (tif->tif_dir.td_stripoffset != NULL && !TIFFWriteDirectoryTagLongLong8Array(tif,&ndir,dir,TIFFTAG_STRIPOFFSETS,tif->tif_dir.td_nstrips,tif->tif_dir.td_stripoffset)) goto bad; } else { if (!TIFFWriteDirectoryTagLongLong8Array(tif,&ndir,dir,TIFFTAG_TILEOFFSETS,tif->tif_dir.td_nstrips,tif->tif_dir.td_stripoffset)) goto bad; } } if (TIFFFieldSet(tif,FIELD_COLORMAP)) { if (!TIFFWriteDirectoryTagColormap(tif,&ndir,dir)) goto bad; } if (TIFFFieldSet(tif,FIELD_EXTRASAMPLES)) { if (tif->tif_dir.td_extrasamples) { uint16 na; uint16* nb; TIFFGetFieldDefaulted(tif,TIFFTAG_EXTRASAMPLES,&na,&nb); if (!TIFFWriteDirectoryTagShortArray(tif,&ndir,dir,TIFFTAG_EXTRASAMPLES,na,nb)) goto bad; } } if (TIFFFieldSet(tif,FIELD_SAMPLEFORMAT)) { if (!TIFFWriteDirectoryTagShortPerSample(tif,&ndir,dir,TIFFTAG_SAMPLEFORMAT,tif->tif_dir.td_sampleformat)) goto bad; } if (TIFFFieldSet(tif,FIELD_SMINSAMPLEVALUE)) { if (!TIFFWriteDirectoryTagSampleformatArray(tif,&ndir,dir,TIFFTAG_SMINSAMPLEVALUE,tif->tif_dir.td_samplesperpixel,tif->tif_dir.td_sminsamplevalue)) goto bad; } if (TIFFFieldSet(tif,FIELD_SMAXSAMPLEVALUE)) { if (!TIFFWriteDirectoryTagSampleformatArray(tif,&ndir,dir,TIFFTAG_SMAXSAMPLEVALUE,tif->tif_dir.td_samplesperpixel,tif->tif_dir.td_smaxsamplevalue)) goto bad; } if (TIFFFieldSet(tif,FIELD_IMAGEDEPTH)) { if (!TIFFWriteDirectoryTagLong(tif,&ndir,dir,TIFFTAG_IMAGEDEPTH,tif->tif_dir.td_imagedepth)) goto bad; } if (TIFFFieldSet(tif,FIELD_TILEDEPTH)) { if (!TIFFWriteDirectoryTagLong(tif,&ndir,dir,TIFFTAG_TILEDEPTH,tif->tif_dir.td_tiledepth)) goto bad; } if (TIFFFieldSet(tif,FIELD_HALFTONEHINTS)) { if (!TIFFWriteDirectoryTagShortArray(tif,&ndir,dir,TIFFTAG_HALFTONEHINTS,2,&tif->tif_dir.td_halftonehints[0])) goto bad; } if (TIFFFieldSet(tif,FIELD_YCBCRSUBSAMPLING)) { if (!TIFFWriteDirectoryTagShortArray(tif,&ndir,dir,TIFFTAG_YCBCRSUBSAMPLING,2,&tif->tif_dir.td_ycbcrsubsampling[0])) goto bad; } if (TIFFFieldSet(tif,FIELD_YCBCRPOSITIONING)) { if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_YCBCRPOSITIONING,tif->tif_dir.td_ycbcrpositioning)) goto bad; } if (TIFFFieldSet(tif,FIELD_REFBLACKWHITE)) { if (!TIFFWriteDirectoryTagRationalArray(tif,&ndir,dir,TIFFTAG_REFERENCEBLACKWHITE,6,tif->tif_dir.td_refblackwhite)) goto bad; } if (TIFFFieldSet(tif,FIELD_TRANSFERFUNCTION)) { if (!TIFFWriteDirectoryTagTransferfunction(tif,&ndir,dir)) goto bad; } if (TIFFFieldSet(tif,FIELD_INKNAMES)) { if (!TIFFWriteDirectoryTagAscii(tif,&ndir,dir,TIFFTAG_INKNAMES,tif->tif_dir.td_inknameslen,tif->tif_dir.td_inknames)) goto bad; } if (TIFFFieldSet(tif,FIELD_SUBIFD)) { if (!TIFFWriteDirectoryTagSubifd(tif,&ndir,dir)) goto bad; } { uint32 n; for (n=0; n<tif->tif_nfields; n++) { const TIFFField* o; o = tif->tif_fields[n]; if ((o->field_bit>=FIELD_CODEC)&&(TIFFFieldSet(tif,o->field_bit))) { switch (o->get_field_type) { case TIFF_SETGET_ASCII: { uint32 pa; char* pb; assert(o->field_type==TIFF_ASCII); assert(o->field_readcount==TIFF_VARIABLE); assert(o->field_passcount==0); TIFFGetField(tif,o->field_tag,&pb); pa=(uint32)(strlen(pb)); if (!TIFFWriteDirectoryTagAscii(tif,&ndir,dir,(uint16)o->field_tag,pa,pb)) goto bad; } break; case TIFF_SETGET_UINT16: { uint16 p; assert(o->field_type==TIFF_SHORT); assert(o->field_readcount==1); assert(o->field_passcount==0); TIFFGetField(tif,o->field_tag,&p); if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,(uint16)o->field_tag,p)) goto bad; } break; case TIFF_SETGET_UINT32: { uint32 p; assert(o->field_type==TIFF_LONG); assert(o->field_readcount==1); assert(o->field_passcount==0); TIFFGetField(tif,o->field_tag,&p); if (!TIFFWriteDirectoryTagLong(tif,&ndir,dir,(uint16)o->field_tag,p)) goto bad; } break; case TIFF_SETGET_C32_UINT8: { uint32 pa; void* pb; assert(o->field_type==TIFF_UNDEFINED); assert(o->field_readcount==TIFF_VARIABLE2); assert(o->field_passcount==1); TIFFGetField(tif,o->field_tag,&pa,&pb); if (!TIFFWriteDirectoryTagUndefinedArray(tif,&ndir,dir,(uint16)o->field_tag,pa,pb)) goto bad; } break; default: assert(0); /* we should never get here */ break; } } } } } for (m=0; m<(uint32)(tif->tif_dir.td_customValueCount); m++) { uint16 tag = (uint16)tif->tif_dir.td_customValues[m].info->field_tag; uint32 count = tif->tif_dir.td_customValues[m].count; switch (tif->tif_dir.td_customValues[m].info->field_type) { case TIFF_ASCII: if (!TIFFWriteDirectoryTagAscii(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_UNDEFINED: if (!TIFFWriteDirectoryTagUndefinedArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_BYTE: if (!TIFFWriteDirectoryTagByteArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_SBYTE: if (!TIFFWriteDirectoryTagSbyteArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_SHORT: if (!TIFFWriteDirectoryTagShortArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_SSHORT: if (!TIFFWriteDirectoryTagSshortArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_LONG: if (!TIFFWriteDirectoryTagLongArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_SLONG: if (!TIFFWriteDirectoryTagSlongArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_LONG8: if (!TIFFWriteDirectoryTagLong8Array(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_SLONG8: if (!TIFFWriteDirectoryTagSlong8Array(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_RATIONAL: if (!TIFFWriteDirectoryTagRationalArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_SRATIONAL: if (!TIFFWriteDirectoryTagSrationalArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_FLOAT: if (!TIFFWriteDirectoryTagFloatArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_DOUBLE: if (!TIFFWriteDirectoryTagDoubleArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_IFD: if (!TIFFWriteDirectoryTagIfdArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_IFD8: if (!TIFFWriteDirectoryTagIfdIfd8Array(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value)) goto bad; break; default: assert(0); /* we should never get here */ break; } } if (dir!=NULL) break; dir=_TIFFmalloc(ndir*sizeof(TIFFDirEntry)); if (dir==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); goto bad; } if (isimage) { if ((tif->tif_diroff==0)&&(!TIFFLinkDirectory(tif))) goto bad; } else tif->tif_diroff=(TIFFSeekFile(tif,0,SEEK_END)+1)&(~((toff_t)1)); if (pdiroff!=NULL) *pdiroff=tif->tif_diroff; if (!(tif->tif_flags&TIFF_BIGTIFF)) dirsize=2+ndir*12+4; else dirsize=8+ndir*20+8; tif->tif_dataoff=tif->tif_diroff+dirsize; if (!(tif->tif_flags&TIFF_BIGTIFF)) tif->tif_dataoff=(uint32)tif->tif_dataoff; if ((tif->tif_dataoff<tif->tif_diroff)||(tif->tif_dataoff<(uint64)dirsize)) { TIFFErrorExt(tif->tif_clientdata,module,"Maximum TIFF file size exceeded"); goto bad; } if (tif->tif_dataoff&1) tif->tif_dataoff++; if (isimage) tif->tif_curdir++; } if (isimage) { if (TIFFFieldSet(tif,FIELD_SUBIFD)&&(tif->tif_subifdoff==0)) { uint32 na; TIFFDirEntry* nb; for (na=0, nb=dir; ; na++, nb++) { if( na == ndir ) { TIFFErrorExt(tif->tif_clientdata,module, "Cannot find SubIFD tag"); goto bad; } if (nb->tdir_tag==TIFFTAG_SUBIFD) break; } if (!(tif->tif_flags&TIFF_BIGTIFF)) tif->tif_subifdoff=tif->tif_diroff+2+na*12+8; else tif->tif_subifdoff=tif->tif_diroff+8+na*20+12; } } dirmem=_TIFFmalloc(dirsize); if (dirmem==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); goto bad; } if (!(tif->tif_flags&TIFF_BIGTIFF)) { uint8* n; uint32 nTmp; TIFFDirEntry* o; n=dirmem; *(uint16*)n=(uint16)ndir; if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)n); n+=2; o=dir; for (m=0; m<ndir; m++) { *(uint16*)n=o->tdir_tag; if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)n); n+=2; *(uint16*)n=o->tdir_type; if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)n); n+=2; nTmp = (uint32)o->tdir_count; _TIFFmemcpy(n,&nTmp,4); if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong((uint32*)n); n+=4; /* This is correct. The data has been */ /* swabbed previously in TIFFWriteDirectoryTagData */ _TIFFmemcpy(n,&o->tdir_offset,4); n+=4; o++; } nTmp = (uint32)tif->tif_nextdiroff; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(&nTmp); _TIFFmemcpy(n,&nTmp,4); } else { uint8* n; TIFFDirEntry* o; n=dirmem; *(uint64*)n=ndir; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8((uint64*)n); n+=8; o=dir; for (m=0; m<ndir; m++) { *(uint16*)n=o->tdir_tag; if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)n); n+=2; *(uint16*)n=o->tdir_type; if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)n); n+=2; _TIFFmemcpy(n,&o->tdir_count,8); if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8((uint64*)n); n+=8; _TIFFmemcpy(n,&o->tdir_offset,8); n+=8; o++; } _TIFFmemcpy(n,&tif->tif_nextdiroff,8); if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8((uint64*)n); } _TIFFfree(dir); dir=NULL; if (!SeekOK(tif,tif->tif_diroff)) { TIFFErrorExt(tif->tif_clientdata,module,"IO error writing directory"); goto bad; } if (!WriteOK(tif,dirmem,(tmsize_t)dirsize)) { TIFFErrorExt(tif->tif_clientdata,module,"IO error writing directory"); goto bad; } _TIFFfree(dirmem); if (imagedone) { TIFFFreeDirectory(tif); tif->tif_flags &= ~TIFF_DIRTYDIRECT; tif->tif_flags &= ~TIFF_DIRTYSTRIP; (*tif->tif_cleanup)(tif); /* * Reset directory-related state for subsequent * directories. */ TIFFCreateDirectory(tif); } return(1); bad: if (dir!=NULL) _TIFFfree(dir); if (dirmem!=NULL) _TIFFfree(dirmem); return(0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-617'], 'message': 'TIFFWriteDirectorySec: avoid assertion. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2795. CVE-2018-10963'</s>
<s>[INST] Given the following code containing errors, provide 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_kv_add_internal(struct ldb_module *module, struct ldb_kv_private *ldb_kv, const struct ldb_message *msg, bool check_single_value) { struct ldb_context *ldb = ldb_module_get_ctx(module); int ret = LDB_SUCCESS; unsigned int i; for (i=0;i<msg->num_elements;i++) { struct ldb_message_element *el = &msg->elements[i]; const struct ldb_schema_attribute *a = ldb_schema_attribute_by_name(ldb, el->name); if (el->num_values == 0) { ldb_asprintf_errstring(ldb, "attribute '%s' on '%s' specified, but with 0 values (illegal)", el->name, ldb_dn_get_linearized(msg->dn)); return LDB_ERR_CONSTRAINT_VIOLATION; } if (check_single_value && el->num_values > 1 && ldb_kv_single_valued(a, el)) { ldb_asprintf_errstring(ldb, "SINGLE-VALUE attribute %s on %s specified more than once", el->name, ldb_dn_get_linearized(msg->dn)); return LDB_ERR_CONSTRAINT_VIOLATION; } /* Do not check "@ATTRIBUTES" for duplicated values */ if (ldb_dn_is_special(msg->dn) && ldb_dn_check_special(msg->dn, LDB_KV_ATTRIBUTES)) { continue; } if (check_single_value && !(el->flags & LDB_FLAG_INTERNAL_DISABLE_SINGLE_VALUE_CHECK)) { struct ldb_val *duplicate = NULL; ret = ldb_msg_find_duplicate_val(ldb, discard_const(msg), el, &duplicate, 0); if (ret != LDB_SUCCESS) { return ret; } if (duplicate != NULL) { ldb_asprintf_errstring( ldb, "attribute '%s': value '%.*s' on '%s' " "provided more than once in ADD object", el->name, (int)duplicate->length, duplicate->data, ldb_dn_get_linearized(msg->dn)); return LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS; } } } ret = ldb_kv_store(module, msg, TDB_INSERT); if (ret != LDB_SUCCESS) { /* * Try really hard to get the right error code for * a re-add situation, as this can matter! */ if (ret == LDB_ERR_CONSTRAINT_VIOLATION) { int ret2; struct ldb_dn *dn2 = NULL; TALLOC_CTX *mem_ctx = talloc_new(module); if (mem_ctx == NULL) { return ldb_module_operr(module); } ret2 = ldb_kv_search_base(module, mem_ctx, msg->dn, &dn2); TALLOC_FREE(mem_ctx); if (ret2 == LDB_SUCCESS) { ret = LDB_ERR_ENTRY_ALREADY_EXISTS; } } if (ret == LDB_ERR_ENTRY_ALREADY_EXISTS) { ldb_asprintf_errstring(ldb, "Entry %s already exists", ldb_dn_get_linearized(msg->dn)); } return ret; } ret = ldb_kv_index_add_new(module, ldb_kv, msg); if (ret != LDB_SUCCESS) { /* * If we failed to index, delete the message again. * * This is particularly important for the GUID index * case, which will only fail for a duplicate DN * in the index add. * * Note that the caller may not cancel the transation * and this means the above add might really show up! */ ldb_kv_delete_noindex(module, msg); return ret; } ret = ldb_kv_modified(module, msg->dn); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'CVE-2018-1140 ldb_tdb: Check for DN validity in add, rename and search This ensures we fail with a good error code before an eventual ldb_dn_get_casefold() which would otherwise fail. Signed-off-by: Andrew Bartlett <abartlet@samba.org> Reviewed-by: Douglas Bagnall <douglas.bagnall@catalyst.net.nz> BUG: https://bugzilla.samba.org/show_bug.cgi?id=13374'</s>
<s>[INST] Given the following code containing errors, provide 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 PackLinuxElf32::calls_crt1(Elf32_Rel const *rel, int sz) { for (; 0 < sz; (sz -= sizeof(Elf32_Rel)), ++rel) { unsigned const symnum = get_te32(&rel->r_info) >> 8; char const *const symnam = get_te32(&dynsym[symnum].st_name) + dynstr; if (0==strcmp(symnam, "__libc_start_main") // glibc || 0==strcmp(symnam, "__libc_init") // Android || 0==strcmp(symnam, "__uClibc_main") || 0==strcmp(symnam, "__uClibc_start_main")) return true; } return false; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'More checking of PT_DYNAMIC and its contents. https://github.com/upx/upx/issues/206 modified: p_lx_elf.cpp'</s>
<s>[INST] Given the following code containing errors, provide 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 sr_do_ioctl(Scsi_CD *cd, struct packet_command *cgc) { struct scsi_device *SDev; struct scsi_sense_hdr sshdr; int result, err = 0, retries = 0; SDev = cd->device; retry: if (!scsi_block_when_processing_errors(SDev)) { err = -ENODEV; goto out; } result = scsi_execute(SDev, cgc->cmd, cgc->data_direction, cgc->buffer, cgc->buflen, (unsigned char *)cgc->sense, &sshdr, cgc->timeout, IOCTL_RETRIES, 0, 0, NULL); /* Minimal error checking. Ignore cases we know about, and report the rest. */ if (driver_byte(result) != 0) { switch (sshdr.sense_key) { case UNIT_ATTENTION: SDev->changed = 1; if (!cgc->quiet) sr_printk(KERN_INFO, cd, "disc change detected.\n"); if (retries++ < 10) goto retry; err = -ENOMEDIUM; break; case NOT_READY: /* This happens if there is no disc in drive */ if (sshdr.asc == 0x04 && sshdr.ascq == 0x01) { /* sense: Logical unit is in process of becoming ready */ if (!cgc->quiet) sr_printk(KERN_INFO, cd, "CDROM not ready yet.\n"); if (retries++ < 10) { /* sleep 2 sec and try again */ ssleep(2); goto retry; } else { /* 20 secs are enough? */ err = -ENOMEDIUM; break; } } if (!cgc->quiet) sr_printk(KERN_INFO, cd, "CDROM not ready. Make sure there " "is a disc in the drive.\n"); err = -ENOMEDIUM; break; case ILLEGAL_REQUEST: err = -EIO; if (sshdr.asc == 0x20 && sshdr.ascq == 0x00) /* sense: Invalid command operation code */ err = -EDRIVE_CANT_DO_THIS; break; default: err = -EIO; } } /* Wake up a process waiting for device */ out: cgc->stat = err; return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'sr: pass down correctly sized SCSI sense buffer We're casting the CDROM layer request_sense to the SCSI sense buffer, but the former is 64 bytes and the latter is 96 bytes. As we generally allocate these on the stack, we end up blowing up the stack. Fix this by wrapping the scsi_execute() call with a properly sized sense buffer, and copying back the bits for the CDROM layer. Cc: stable@vger.kernel.org Reported-by: Piotr Gabriel Kosinski <pg.kosinski@gmail.com> Reported-by: Daniel Shapira <daniel@twistlock.com> Tested-by: Kees Cook <keescook@chromium.org> Fixes: 82ed4db499b8 ("block: split scsi_request out of struct request") Signed-off-by: Jens Axboe <axboe@kernel.dk>'</s>
<s>[INST] Given the following code containing errors, provide 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 _slurm_rpc_allocate_resources(slurm_msg_t * msg) { static int active_rpc_cnt = 0; int error_code = SLURM_SUCCESS; slurm_msg_t response_msg; DEF_TIMERS; job_desc_msg_t *job_desc_msg = (job_desc_msg_t *) msg->data; resource_allocation_response_msg_t alloc_msg; /* Locks: Read config, read job, read node, read partition */ slurmctld_lock_t job_read_lock = { READ_LOCK, READ_LOCK, READ_LOCK, READ_LOCK, READ_LOCK }; /* Locks: Read config, write job, write node, read partition */ slurmctld_lock_t job_write_lock = { READ_LOCK, WRITE_LOCK, WRITE_LOCK, READ_LOCK, READ_LOCK }; uid_t uid = g_slurm_auth_get_uid(msg->auth_cred, slurmctld_config.auth_info); int immediate = job_desc_msg->immediate; bool do_unlock = false; bool reject_job = false; struct job_record *job_ptr = NULL; uint16_t port; /* dummy value */ slurm_addr_t resp_addr; char *err_msg = NULL, *job_submit_user_msg = NULL; START_TIMER; if (slurmctld_config.submissions_disabled) { info("Submissions disabled on system"); error_code = ESLURM_SUBMISSIONS_DISABLED; reject_job = true; goto send_msg; } if ((uid != job_desc_msg->user_id) && (!validate_slurm_user(uid))) { error_code = ESLURM_USER_ID_MISSING; error("Security violation, RESOURCE_ALLOCATE from uid=%d", uid); } debug2("sched: Processing RPC: REQUEST_RESOURCE_ALLOCATION from uid=%d", uid); /* do RPC call */ if ((job_desc_msg->alloc_node == NULL) || (job_desc_msg->alloc_node[0] == '\0')) { error_code = ESLURM_INVALID_NODE_NAME; error("REQUEST_RESOURCE_ALLOCATE lacks alloc_node from uid=%d", uid); } if (error_code == SLURM_SUCCESS) { /* Locks are for job_submit plugin use */ lock_slurmctld(job_read_lock); job_desc_msg->pack_job_offset = NO_VAL; error_code = validate_job_create_req(job_desc_msg,uid,&err_msg); unlock_slurmctld(job_read_lock); } /* * In validate_job_create_req(), err_msg is currently only modified in * the call to job_submit_plugin_submit. We save the err_msg in a temp * char *job_submit_user_msg because err_msg can be overwritten later * in the calls to fed_mgr_job_allocate and/or job_allocate, and we * need the job submit plugin value to build the resource allocation * response in the call to _build_alloc_msg. */ if (err_msg) job_submit_user_msg = xstrdup(err_msg); #if HAVE_ALPS_CRAY /* * Catch attempts to nest salloc sessions. It is not possible to use an * ALPS session which has the same alloc_sid, it fails even if PAGG * container IDs are used. */ if (allocated_session_in_use(job_desc_msg)) { error_code = ESLURM_RESERVATION_BUSY; error("attempt to nest ALPS allocation on %s:%d by uid=%d", job_desc_msg->alloc_node, job_desc_msg->alloc_sid, uid); } #endif if (error_code) { reject_job = true; } else if (!slurm_get_peer_addr(msg->conn_fd, &resp_addr)) { /* resp_host could already be set from a federated cluster */ if (!job_desc_msg->resp_host) { job_desc_msg->resp_host = xmalloc(16); slurm_get_ip_str(&resp_addr, &port, job_desc_msg->resp_host, 16); } dump_job_desc(job_desc_msg); do_unlock = true; _throttle_start(&active_rpc_cnt); lock_slurmctld(job_write_lock); if (fed_mgr_fed_rec) { uint32_t job_id; if (fed_mgr_job_allocate(msg, job_desc_msg, true, uid, msg->protocol_version, &job_id, &error_code, &err_msg)) { reject_job = true; } else if (!(job_ptr = find_job_record(job_id))) { error("%s: can't find fed job that was just created. this should never happen", __func__); reject_job = true; error_code = SLURM_ERROR; } } else { job_desc_msg->pack_job_offset = NO_VAL; error_code = job_allocate(job_desc_msg, immediate, false, NULL, true, uid, &job_ptr, &err_msg, msg->protocol_version); /* unlock after finished using the job structure * data */ /* return result */ if (!job_ptr || (error_code && job_ptr->job_state == JOB_FAILED)) reject_job = true; } END_TIMER2("_slurm_rpc_allocate_resources"); } else { reject_job = true; if (errno) error_code = errno; else error_code = SLURM_ERROR; } send_msg: if (!reject_job) { xassert(job_ptr); info("sched: %s JobId=%u NodeList=%s %s", __func__, job_ptr->job_id, job_ptr->nodes, TIME_STR); _build_alloc_msg(job_ptr, &alloc_msg, error_code, job_submit_user_msg); /* * This check really isn't needed, but just doing it * to be more complete. */ if (do_unlock) { unlock_slurmctld(job_write_lock); _throttle_fini(&active_rpc_cnt); } slurm_msg_t_init(&response_msg); response_msg.conn = msg->conn; response_msg.flags = msg->flags; response_msg.protocol_version = msg->protocol_version; response_msg.msg_type = RESPONSE_RESOURCE_ALLOCATION; response_msg.data = &alloc_msg; if (slurm_send_node_msg(msg->conn_fd, &response_msg) < 0) _kill_job_on_msg_fail(job_ptr->job_id); schedule_job_save(); /* has own locks */ schedule_node_save(); /* has own locks */ if (!alloc_msg.node_cnt) /* didn't get an allocation */ queue_job_scheduler(); /* NULL out working_cluster_rec since it's pointing to global * memory */ alloc_msg.working_cluster_rec = NULL; slurm_free_resource_allocation_response_msg_members(&alloc_msg); } else { /* allocate error */ if (do_unlock) { unlock_slurmctld(job_write_lock); _throttle_fini(&active_rpc_cnt); } info("%s: %s ", __func__, slurm_strerror(error_code)); if (err_msg) slurm_send_rc_err_msg(msg, error_code, err_msg); else slurm_send_rc_msg(msg, error_code); } xfree(err_msg); xfree(job_submit_user_msg); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix insecure handling of job requested gid. Only trust MUNGE signed values, unless the RPC was signed by SlurmUser or root. CVE-2018-10995.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: z_check_file_permissions(gs_memory_t *mem, const char *fname, const int len, const char *permission) { i_ctx_t *i_ctx_p = get_minst_from_memory(mem)->i_ctx_p; gs_parsed_file_name_t pname; const char *permitgroup = permission[0] == 'r' ? "PermitFileReading" : "PermitFileWriting"; int code = gs_parse_file_name(&pname, fname, len, imemory); if (code < 0) return code; if (pname.iodev && i_ctx_p->LockFilePermissions && strcmp(pname.iodev->dname, "%pipe%") == 0) return gs_error_invalidfileaccess; code = check_file_permissions(i_ctx_p, fname, len, permitgroup); return code; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Bug 697193: status operator honour SAFER option'</s>
<s>[INST] Given the following code containing errors, provide 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 add_match_busid(char *busid) { int i; int ret = -1; spin_lock(&busid_table_lock); /* already registered? */ if (get_busid_idx(busid) >= 0) { ret = 0; goto out; } for (i = 0; i < MAX_BUSID; i++) if (!busid_table[i].name[0]) { strlcpy(busid_table[i].name, busid, BUSID_SIZE); if ((busid_table[i].status != STUB_BUSID_ALLOC) && (busid_table[i].status != STUB_BUSID_REMOV)) busid_table[i].status = STUB_BUSID_ADDED; ret = 0; break; } out: spin_unlock(&busid_table_lock); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'usbip: usbip_host: fix NULL-ptr deref and use-after-free errors usbip_host updates device status without holding lock from stub probe, disconnect and rebind code paths. When multiple requests to import a device are received, these unprotected code paths step all over each other and drive fails with NULL-ptr deref and use-after-free errors. The driver uses a table lock to protect the busid array for adding and deleting busids to the table. However, the probe, disconnect and rebind paths get the busid table entry and update the status without holding the busid table lock. Add a new finer grain lock to protect the busid entry. This new lock will be held to search and update the busid entry fields from get_busid_idx(), add_match_busid() and del_match_busid(). match_busid_show() does the same to access the busid entry fields. get_busid_priv() changed to return the pointer to the busid entry holding the busid lock. stub_probe(), stub_disconnect() and stub_device_rebind() call put_busid_priv() to release the busid lock before returning. This changes fixes the unprotected code paths eliminating the race conditions in updating the busid entries. Reported-by: Jakub Jirasek Signed-off-by: Shuah Khan (Samsung OSG) <shuah@kernel.org> Cc: stable <stable@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: Statement_Ptr Expand::operator()(Declaration_Ptr d) { Block_Obj ab = d->block(); String_Obj old_p = d->property(); Expression_Obj prop = old_p->perform(&eval); String_Obj new_p = Cast<String>(prop); // we might get a color back if (!new_p) { std::string str(prop->to_string(ctx.c_options)); new_p = SASS_MEMORY_NEW(String_Constant, old_p->pstate(), str); } Expression_Obj value = d->value()->perform(&eval); Block_Obj bb = ab ? operator()(ab) : NULL; if (!bb) { if (!value || (value->is_invisible() && !d->is_important())) return 0; } Declaration_Ptr decl = SASS_MEMORY_NEW(Declaration, d->pstate(), new_p, value, d->is_important(), d->is_custom_property(), bb); decl->tabs(d->tabs()); return decl; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fix segfault on empty custom properties Originally reported in sass/sassc#225 Fixes sass/sassc#225 Spec sass/sass-spec#1249'</s>
<s>[INST] Given the following code containing errors, provide 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 getnum (lua_State *L, const char **fmt, int df) { if (!isdigit(**fmt)) /* no number? */ return df; /* return default value */ else { int a = 0; do { if (a > (INT_MAX / 10) || a * 10 > (INT_MAX - (**fmt - '0'))) luaL_error(L, "integral size overflow"); a = a*10 + *((*fmt)++) - '0'; } while (isdigit(**fmt)); return a; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-787'], 'message': 'Security: update Lua struct package for security. During an auditing Apple found that the "struct" Lua package we ship with Redis (http://www.inf.puc-rio.br/~roberto/struct/) contains a security problem. A bound-checking statement fails because of integer overflow. The bug exists since we initially integrated this package with Lua, when scripting was introduced, so every version of Redis with EVAL/EVALSHA capabilities exposed is affected. Instead of just fixing the bug, the library was updated to the latest version shipped by the author.'</s>
<s>[INST] Given the following code containing errors, provide 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 sock_close(struct inode *inode, struct file *filp) { sock_release(SOCKET_I(inode)); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'socket: close race condition between sock_close() and sockfs_setattr() fchownat() doesn't even hold refcnt of fd until it figures out fd is really needed (otherwise is ignored) and releases it after it resolves the path. This means sock_close() could race with sockfs_setattr(), which leads to a NULL pointer dereference since typically we set sock->sk to NULL in ->release(). As pointed out by Al, this is unique to sockfs. So we can fix this in socket layer by acquiring inode_lock in sock_close() and checking against NULL in sockfs_setattr(). sock_release() is called in many places, only the sock_close() path matters here. And fortunately, this should not affect normal sock_close() as it is only called when the last fd refcnt is gone. It only affects sock_close() with a parallel sockfs_setattr() in progress, which is not common. Fixes: 86741ec25462 ("net: core: Add a UID field to struct sock.") Reported-by: shankarapailoor <shankarapailoor@gmail.com> Cc: Tetsuo Handa <penguin-kernel@i-love.sakura.ne.jp> Cc: Lorenzo Colitti <lorenzo@google.com> Cc: Al Viro <viro@zeniv.linux.org.uk> Signed-off-by: Cong Wang <xiyou.wangcong@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: start_watchdog(ngx_cycle_t *cycle) { ngx_core_conf_t *core_conf; ngx_int_t ret, result; ngx_uint_t i; AfterForkData after_fork_data; ngx_keyval_t *ctl = NULL; ngx_str_t str; PsgJsonValue *w_config = NULL; PsgJsonValue *j_log_target; u_char filename[NGX_MAX_PATH], *last; char *passenger_root = NULL; char *error_message = NULL; passenger_autogenerated_main_conf_t *autogenerated_main_conf = &passenger_main_conf.autogenerated; core_conf = (ngx_core_conf_t *) ngx_get_conf(cycle->conf_ctx, ngx_core_module); result = NGX_OK; w_config = psg_json_value_new_with_type(PSG_JSON_VALUE_TYPE_OBJECT); j_log_target = psg_json_value_new_with_type(PSG_JSON_VALUE_TYPE_OBJECT); after_fork_data.cycle = cycle; after_fork_data.log_fd = -1; passenger_root = ngx_str_null_terminate(&autogenerated_main_conf->root_dir); if (passenger_root == NULL) { goto error_enomem; } if (autogenerated_main_conf->stat_throttle_rate != NGX_CONF_UNSET_UINT) { pp_app_type_detector_set_throttle_rate(pp_app_type_detector, autogenerated_main_conf->stat_throttle_rate); } /* Note: WatchdogLauncher::start() sets a number of default values. */ psg_json_value_set_str_ne (w_config, "web_server_module_version", PASSENGER_VERSION, strlen(PASSENGER_VERSION)); psg_json_value_set_str_ne (w_config, "web_server_version", NGINX_VERSION, strlen(NGINX_VERSION)); psg_json_value_set_str_ne (w_config, "server_software", NGINX_VER, strlen(NGINX_VER)); psg_json_value_set_bool (w_config, "multi_app", 1); psg_json_value_set_bool (w_config, "default_load_shell_envvars", 1); psg_json_value_set_value (w_config, "config_manifest", -1, passenger_main_conf.manifest); psg_json_value_set_ngx_uint (w_config, "log_level", autogenerated_main_conf->log_level); psg_json_value_set_ngx_str_ne(w_config, "file_descriptor_log_target", &autogenerated_main_conf->file_descriptor_log_file); psg_json_value_set_ngx_uint (w_config, "core_file_descriptor_ulimit", autogenerated_main_conf->core_file_descriptor_ulimit); psg_json_value_set_ngx_uint (w_config, "controller_socket_backlog", autogenerated_main_conf->socket_backlog); psg_json_value_set_ngx_str_ne(w_config, "controller_file_buffered_channel_buffer_dir", &autogenerated_main_conf->data_buffer_dir); psg_json_value_set_ngx_str_ne(w_config, "instance_registry_dir", &autogenerated_main_conf->instance_registry_dir); psg_json_value_set_ngx_flag (w_config, "security_update_checker_disabled", autogenerated_main_conf->disable_security_update_check); psg_json_value_set_ngx_str_ne(w_config, "security_update_checker_proxy_url", &autogenerated_main_conf->security_update_check_proxy); psg_json_value_set_ngx_flag (w_config, "user_switching", autogenerated_main_conf->user_switching); psg_json_value_set_ngx_flag (w_config, "show_version_in_header", autogenerated_main_conf->show_version_in_header); psg_json_value_set_ngx_flag (w_config, "turbocaching", autogenerated_main_conf->turbocaching); psg_json_value_set_ngx_str_ne(w_config, "default_user", &autogenerated_main_conf->default_user); psg_json_value_set_ngx_str_ne(w_config, "default_group", &autogenerated_main_conf->default_group); psg_json_value_set_ngx_str_ne(w_config, "default_ruby", &passenger_main_conf.default_ruby); psg_json_value_set_ngx_uint (w_config, "max_pool_size", autogenerated_main_conf->max_pool_size); psg_json_value_set_ngx_uint (w_config, "pool_idle_time", autogenerated_main_conf->pool_idle_time); psg_json_value_set_ngx_uint (w_config, "max_instances_per_app", autogenerated_main_conf->max_instances_per_app); psg_json_value_set_ngx_uint (w_config, "response_buffer_high_watermark", autogenerated_main_conf->response_buffer_high_watermark); psg_json_value_set_ngx_uint (w_config, "stat_throttle_rate", autogenerated_main_conf->stat_throttle_rate); psg_json_value_set_ngx_str_ne(w_config, "admin_panel_url", &autogenerated_main_conf->admin_panel_url); psg_json_value_set_ngx_str_ne(w_config, "admin_panel_auth_type", &autogenerated_main_conf->admin_panel_auth_type); psg_json_value_set_ngx_str_ne(w_config, "admin_panel_username", &autogenerated_main_conf->admin_panel_username); psg_json_value_set_ngx_str_ne(w_config, "admin_panel_password", &autogenerated_main_conf->admin_panel_password); if (autogenerated_main_conf->prestart_uris != NGX_CONF_UNSET_PTR) { psg_json_value_set_strset(w_config, "prestart_urls", (ngx_str_t *) autogenerated_main_conf->prestart_uris->elts, autogenerated_main_conf->prestart_uris->nelts); } if (autogenerated_main_conf->log_file.len > 0) { psg_json_value_set_ngx_str_ne(j_log_target, "path", &autogenerated_main_conf->log_file); } else if (cycle->new_log.file == NULL) { ngx_log_error(NGX_LOG_EMERG, cycle->log, 0, "Cannot initialize " PROGRAM_NAME " because Nginx is not configured with an error log file." " Please either configure Nginx with an error log file, or configure " PROGRAM_NAME " with a `passenger_log_file`"); result = NGX_ERROR; goto cleanup; } else if (cycle->new_log.file->name.len > 0) { psg_json_value_set_ngx_str_ne(j_log_target, "path", &cycle->new_log.file->name); } else if (cycle->log->file->name.len > 0) { psg_json_value_set_ngx_str_ne(j_log_target, "path", &cycle->log->file->name); } if (autogenerated_main_conf->ctl != NULL) { ctl = (ngx_keyval_t *) autogenerated_main_conf->ctl->elts; for (i = 0; i < autogenerated_main_conf->ctl->nelts; i++) { psg_json_value_set_with_autodetected_data_type(w_config, (const char *) ctl[i].key.data, ctl[i].key.len, (const char *) ctl[i].value.data, ctl[i].value.len, &error_message); if (error_message != NULL) { str.data = ctl[i].key.data; str.len = ctl[i].key.len - 1; ngx_log_error(NGX_LOG_EMERG, cycle->log, 0, "Error parsing ctl %V as JSON data: %s", &str, error_message); result = NGX_ERROR; goto cleanup; } } } open_log_file_for_after_forking(&after_fork_data, j_log_target); if (after_fork_data.stderr_equals_log_file) { psg_json_value_set_bool(j_log_target, "stderr", 1); } if (!psg_json_value_empty(j_log_target)) { psg_json_value_set_value(w_config, "log_target", -1, j_log_target); } ret = psg_watchdog_launcher_start(psg_watchdog_launcher, passenger_root, w_config, starting_watchdog_after_fork, &after_fork_data, &error_message); if (!ret) { ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno, "%s", error_message); result = NGX_ERROR; goto cleanup; } /* Create the file instance_dir + "/web_server_info/control_process.pid" * and make it writable by the worker processes. This is because * save_master_process_pid is run after Nginx has lowered privileges. */ last = ngx_snprintf(filename, sizeof(filename) - 1, "%s/web_server_info/control_process.pid", psg_watchdog_launcher_get_instance_dir(psg_watchdog_launcher, NULL)); *last = (u_char) '\0'; if (create_file(cycle, filename, (const u_char *) "", 0) != NGX_OK) { result = NGX_ERROR; goto cleanup; } do { ret = chown((const char *) filename, (uid_t) core_conf->user, (gid_t) -1); } while (ret == -1 && errno == EINTR); if (ret == -1) { result = NGX_ERROR; goto cleanup; } cleanup: psg_json_value_free(w_config); psg_json_value_free(j_log_target); free(passenger_root); free(error_message); if (after_fork_data.log_fd != -1) { close(after_fork_data.log_fd); } if (result == NGX_ERROR && autogenerated_main_conf->abort_on_startup_error) { exit(1); } return result; error_enomem: ngx_log_error(NGX_LOG_ALERT, cycle->log, ENOMEM, "Cannot allocate memory"); result = NGX_ERROR; goto cleanup; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'Fix privilege escalation in the Nginx module The vulnerability is exploitable with a non-standard passenger_instance_registry_dir, via a race condition where after a file was created, it was chowned via the path not the file descriptor. The chown entered the code in 2010, so Passenger 4 + 5 all affected.'</s>
<s>[INST] Given the following code containing errors, provide 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 WriteBMPImage(const ImageInfo *image_info,Image *image) { BMPInfo bmp_info; BMPSubtype bmp_subtype; const char *option; const StringInfo *profile; MagickBooleanType have_color_info, status; MemoryInfo *pixel_info; MagickOffsetType scene; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t i, x; register unsigned char *q; size_t bytes_per_line, imageListLength, type; ssize_t y; unsigned char *bmp_data, *pixels; /* 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); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); type=4; if (LocaleCompare(image_info->magick,"BMP2") == 0) type=2; else if (LocaleCompare(image_info->magick,"BMP3") == 0) type=3; option=GetImageOption(image_info,"bmp:format"); if (option != (char *) NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format=%s",option); if (LocaleCompare(option,"bmp2") == 0) type=2; if (LocaleCompare(option,"bmp3") == 0) type=3; if (LocaleCompare(option,"bmp4") == 0) type=4; } scene=0; imageListLength=GetImageListLength(image); do { /* Initialize BMP raster file header. */ if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace); (void) memset(&bmp_info,0,sizeof(bmp_info)); bmp_info.file_size=14+12; if (type > 2) bmp_info.file_size+=28; bmp_info.offset_bits=bmp_info.file_size; bmp_info.compression=BI_RGB; bmp_info.red_mask=0x00ff0000U; bmp_info.green_mask=0x0000ff00U; bmp_info.blue_mask=0x000000ffU; bmp_info.alpha_mask=0xff000000U; bmp_subtype=UndefinedSubtype; if ((image->storage_class == PseudoClass) && (image->colors > 256)) (void) SetImageStorageClass(image,DirectClass); if (image->storage_class != DirectClass) { /* Colormapped BMP raster. */ bmp_info.bits_per_pixel=8; if (image->colors <= 2) bmp_info.bits_per_pixel=1; else if (image->colors <= 16) bmp_info.bits_per_pixel=4; else if (image->colors <= 256) bmp_info.bits_per_pixel=8; if (image_info->compression == RLECompression) bmp_info.bits_per_pixel=8; bmp_info.number_colors=1U << bmp_info.bits_per_pixel; if (image->matte != MagickFalse) (void) SetImageStorageClass(image,DirectClass); else if ((size_t) bmp_info.number_colors < image->colors) (void) SetImageStorageClass(image,DirectClass); else { bmp_info.file_size+=3*(1UL << bmp_info.bits_per_pixel); bmp_info.offset_bits+=3*(1UL << bmp_info.bits_per_pixel); if (type > 2) { bmp_info.file_size+=(1UL << bmp_info.bits_per_pixel); bmp_info.offset_bits+=(1UL << bmp_info.bits_per_pixel); } } } if (image->storage_class == DirectClass) { /* Full color BMP raster. */ bmp_info.number_colors=0; option=GetImageOption(image_info,"bmp:subtype"); if (option != (const char *) NULL) { if (image->matte != MagickFalse) { if (LocaleNCompare(option,"ARGB4444",8) == 0) { bmp_subtype=ARGB4444; bmp_info.red_mask=0x00000f00U; bmp_info.green_mask=0x000000f0U; bmp_info.blue_mask=0x0000000fU; bmp_info.alpha_mask=0x0000f000U; } else if (LocaleNCompare(option,"ARGB1555",8) == 0) { bmp_subtype=ARGB1555; bmp_info.red_mask=0x00007c00U; bmp_info.green_mask=0x000003e0U; bmp_info.blue_mask=0x0000001fU; bmp_info.alpha_mask=0x00008000U; } } else { if (LocaleNCompare(option,"RGB555",6) == 0) { bmp_subtype=RGB555; bmp_info.red_mask=0x00007c00U; bmp_info.green_mask=0x000003e0U; bmp_info.blue_mask=0x0000001fU; bmp_info.alpha_mask=0U; } else if (LocaleNCompare(option,"RGB565",6) == 0) { bmp_subtype=RGB565; bmp_info.red_mask=0x0000f800U; bmp_info.green_mask=0x000007e0U; bmp_info.blue_mask=0x0000001fU; bmp_info.alpha_mask=0U; } } } if (bmp_subtype != UndefinedSubtype) { bmp_info.bits_per_pixel=16; bmp_info.compression=BI_BITFIELDS; } else { bmp_info.bits_per_pixel=(unsigned short) ((type > 3) && (image->matte != MagickFalse) ? 32 : 24); bmp_info.compression=(unsigned int) ((type > 3) && (image->matte != MagickFalse) ? BI_BITFIELDS : BI_RGB); if ((type == 3) && (image->matte != MagickFalse)) { option=GetImageOption(image_info,"bmp3:alpha"); if (IsStringTrue(option)) bmp_info.bits_per_pixel=32; } } } bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32); bmp_info.ba_offset=0; profile=GetImageProfile(image,"icc"); have_color_info=(image->rendering_intent != UndefinedIntent) || (profile != (StringInfo *) NULL) || (image->gamma != 0.0) ? MagickTrue : MagickFalse; if (type == 2) bmp_info.size=12; else if ((type == 3) || ((image->matte == MagickFalse) && (have_color_info == MagickFalse))) { type=3; bmp_info.size=40; } else { int extra_size; bmp_info.size=108; extra_size=68; if ((image->rendering_intent != UndefinedIntent) || (profile != (StringInfo *) NULL)) { bmp_info.size=124; extra_size+=16; } bmp_info.file_size+=extra_size; bmp_info.offset_bits+=extra_size; } if (((ssize_t) image->columns != (ssize_t) ((signed int) image->columns)) || ((ssize_t) image->rows != (ssize_t) ((signed int) image->rows))) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); bmp_info.width=(ssize_t) image->columns; bmp_info.height=(ssize_t) image->rows; bmp_info.planes=1; bmp_info.image_size=(unsigned int) (bytes_per_line*image->rows); bmp_info.file_size+=bmp_info.image_size; bmp_info.x_pixels=75*39; bmp_info.y_pixels=75*39; switch (image->units) { case UndefinedResolution: case PixelsPerInchResolution: { bmp_info.x_pixels=(unsigned int) (100.0*image->x_resolution/2.54); bmp_info.y_pixels=(unsigned int) (100.0*image->y_resolution/2.54); break; } case PixelsPerCentimeterResolution: { bmp_info.x_pixels=(unsigned int) (100.0*image->x_resolution); bmp_info.y_pixels=(unsigned int) (100.0*image->y_resolution); break; } } bmp_info.colors_important=bmp_info.number_colors; /* Convert MIFF to BMP raster pixels. */ pixel_info=AcquireVirtualMemory((size_t) bmp_info.image_size, sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); (void) memset(pixels,0,(size_t) bmp_info.image_size); switch (bmp_info.bits_per_pixel) { case 1: { size_t bit, byte; /* Convert PseudoClass image to a BMP monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); q=pixels+(image->rows-y-1)*bytes_per_line; bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; byte|=GetPixelIndex(indexes+x) != 0 ? 0x01 : 0x00; bit++; if (bit == 8) { *q++=(unsigned char) byte; bit=0; byte=0; } } if (bit != 0) { *q++=(unsigned char) (byte << (8-bit)); x++; } for (x=(ssize_t) (image->columns+7)/8; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 4: { size_t nibble, byte; /* Convert PseudoClass image to a BMP monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); q=pixels+(image->rows-y-1)*bytes_per_line; nibble=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=4; byte|=((size_t) GetPixelIndex(indexes+x) & 0x0f); nibble++; if (nibble == 2) { *q++=(unsigned char) byte; nibble=0; byte=0; } } if (nibble != 0) { *q++=(unsigned char) (byte << 4); x++; } for (x=(ssize_t) (image->columns+1)/2; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 8: { /* Convert PseudoClass packet to BMP pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) *q++=(unsigned char) GetPixelIndex(indexes+x); for ( ; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 16: { /* Convert DirectClass packet to BMP BGR888. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; q=(pixels+(image->rows-y-1)*bytes_per_line); for (x=0; x < (ssize_t) image->columns; x++) { unsigned short pixel; pixel=0; if (bmp_subtype == ARGB4444) { pixel=(unsigned short) (ScaleQuantumToAny( GetPixelAlpha(p),15) << 12); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelRed(p),15) << 8); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelGreen(p),15) << 4); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelBlue(p),15)); } else if (bmp_subtype == RGB565) { pixel=(unsigned short) (ScaleQuantumToAny( GetPixelRed(p),31) << 11); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelGreen(p),63) << 5); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelBlue(p),31)); } else { if (bmp_subtype == ARGB1555) pixel=(unsigned short) (ScaleQuantumToAny( GetPixelAlpha(p),1) << 15); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelRed(p),31) << 10); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelGreen(p),31) << 5); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelBlue(p),31)); } *((unsigned short *) q)=pixel; q+=2; p++; } for (x=2L*(ssize_t) image->columns; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 24: { /* Convert DirectClass packet to BMP BGR888. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelBlue(p)); *q++=ScaleQuantumToChar(GetPixelGreen(p)); *q++=ScaleQuantumToChar(GetPixelRed(p)); p++; } for (x=3L*(ssize_t) image->columns; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 32: { /* Convert DirectClass packet to ARGB8888 pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelBlue(p)); *q++=ScaleQuantumToChar(GetPixelGreen(p)); *q++=ScaleQuantumToChar(GetPixelRed(p)); *q++=ScaleQuantumToChar(GetPixelAlpha(p)); p++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } } if ((type > 2) && (bmp_info.bits_per_pixel == 8)) if (image_info->compression != NoCompression) { MemoryInfo *rle_info; /* Convert run-length encoded raster pixels. */ rle_info=AcquireVirtualMemory((size_t) (2*(bytes_per_line+2)+2), (image->rows+2)*sizeof(*pixels)); if (rle_info == (MemoryInfo *) NULL) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } bmp_data=(unsigned char *) GetVirtualMemoryBlob(rle_info); bmp_info.file_size-=bmp_info.image_size; bmp_info.image_size=(unsigned int) EncodeImage(image,bytes_per_line, pixels,bmp_data); bmp_info.file_size+=bmp_info.image_size; pixel_info=RelinquishVirtualMemory(pixel_info); pixel_info=rle_info; pixels=bmp_data; bmp_info.compression=BI_RLE8; } /* Write BMP for Windows, all versions, 14-byte header. */ if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing BMP version %.20g datastream",(double) type); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Storage class=DirectClass"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Storage class=PseudoClass"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image depth=%.20g",(double) image->depth); if (image->matte != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Matte=True"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Matte=MagickFalse"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " BMP bits_per_pixel=%.20g",(double) bmp_info.bits_per_pixel); switch ((int) bmp_info.compression) { case BI_RGB: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression=BI_RGB"); break; } case BI_RLE8: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression=BI_RLE8"); break; } case BI_BITFIELDS: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression=BI_BITFIELDS"); break; } default: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression=UNKNOWN (%u)",bmp_info.compression); break; } } if (bmp_info.number_colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number_colors=unspecified"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number_colors=%u",bmp_info.number_colors); } (void) WriteBlob(image,2,(unsigned char *) "BM"); (void) WriteBlobLSBLong(image,bmp_info.file_size); (void) WriteBlobLSBLong(image,bmp_info.ba_offset); /* always 0 */ (void) WriteBlobLSBLong(image,bmp_info.offset_bits); if (type == 2) { /* Write 12-byte version 2 bitmap header. */ (void) WriteBlobLSBLong(image,bmp_info.size); (void) WriteBlobLSBSignedShort(image,(signed short) bmp_info.width); (void) WriteBlobLSBSignedShort(image,(signed short) bmp_info.height); (void) WriteBlobLSBShort(image,bmp_info.planes); (void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel); } else { /* Write 40-byte version 3+ bitmap header. */ (void) WriteBlobLSBLong(image,bmp_info.size); (void) WriteBlobLSBSignedLong(image,(signed long) bmp_info.width); (void) WriteBlobLSBSignedLong(image,(signed long) bmp_info.height); (void) WriteBlobLSBShort(image,bmp_info.planes); (void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel); (void) WriteBlobLSBLong(image,bmp_info.compression); (void) WriteBlobLSBLong(image,bmp_info.image_size); (void) WriteBlobLSBLong(image,bmp_info.x_pixels); (void) WriteBlobLSBLong(image,bmp_info.y_pixels); (void) WriteBlobLSBLong(image,bmp_info.number_colors); (void) WriteBlobLSBLong(image,bmp_info.colors_important); } if ((type > 3) && ((image->matte != MagickFalse) || (have_color_info != MagickFalse))) { /* Write the rest of the 108-byte BMP Version 4 header. */ (void) WriteBlobLSBLong(image,bmp_info.red_mask); (void) WriteBlobLSBLong(image,bmp_info.green_mask); (void) WriteBlobLSBLong(image,bmp_info.blue_mask); (void) WriteBlobLSBLong(image,bmp_info.alpha_mask); (void) WriteBlobLSBLong(image,0x73524742U); /* sRGB */ (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.red_primary.x*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.red_primary.y*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) ((1.000f-(image->chromaticity.red_primary.x+ image->chromaticity.red_primary.y))*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.green_primary.x*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.green_primary.y*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) ((1.000f-(image->chromaticity.green_primary.x+ image->chromaticity.green_primary.y))*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.blue_primary.x*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.blue_primary.y*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) ((1.000f-(image->chromaticity.blue_primary.x+ image->chromaticity.blue_primary.y))*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (bmp_info.gamma_scale.x*0x10000)); (void) WriteBlobLSBLong(image,(unsigned int) (bmp_info.gamma_scale.y*0x10000)); (void) WriteBlobLSBLong(image,(unsigned int) (bmp_info.gamma_scale.z*0x10000)); if ((image->rendering_intent != UndefinedIntent) || (profile != (StringInfo *) NULL)) { ssize_t intent; switch ((int) image->rendering_intent) { case SaturationIntent: { intent=LCS_GM_BUSINESS; break; } case RelativeIntent: { intent=LCS_GM_GRAPHICS; break; } case PerceptualIntent: { intent=LCS_GM_IMAGES; break; } case AbsoluteIntent: { intent=LCS_GM_ABS_COLORIMETRIC; break; } default: { intent=0; break; } } (void) WriteBlobLSBLong(image,(unsigned int) intent); (void) WriteBlobLSBLong(image,0x00); /* dummy profile data */ (void) WriteBlobLSBLong(image,0x00); /* dummy profile length */ (void) WriteBlobLSBLong(image,0x00); /* reserved */ } } if (image->storage_class == PseudoClass) { unsigned char *bmp_colormap; /* Dump colormap to file. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Colormap: %.20g entries",(double) image->colors); bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) (1UL << bmp_info.bits_per_pixel),4*sizeof(*bmp_colormap)); if (bmp_colormap == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); q=bmp_colormap; for (i=0; i < (ssize_t) MagickMin((ssize_t) image->colors,(ssize_t) bmp_info.number_colors); i++) { *q++=ScaleQuantumToChar(image->colormap[i].blue); *q++=ScaleQuantumToChar(image->colormap[i].green); *q++=ScaleQuantumToChar(image->colormap[i].red); if (type > 2) *q++=(unsigned char) 0x0; } for ( ; i < (ssize_t) (1UL << bmp_info.bits_per_pixel); i++) { *q++=(unsigned char) 0x00; *q++=(unsigned char) 0x00; *q++=(unsigned char) 0x00; if (type > 2) *q++=(unsigned char) 0x00; } if (type <= 2) (void) WriteBlob(image,(size_t) (3*(1L << bmp_info.bits_per_pixel)), bmp_colormap); else (void) WriteBlob(image,(size_t) (4*(1L << bmp_info.bits_per_pixel)), bmp_colormap); bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Pixels: %u bytes",bmp_info.image_size); (void) WriteBlob(image,(size_t) bmp_info.image_size,pixels); pixel_info=RelinquishVirtualMemory(pixel_info); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " File_size: %u bytes",bmp_info.file_size); (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/1177'</s>
<s>[INST] Given the following code containing errors, provide 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 handle_vmon(struct kvm_vcpu *vcpu) { int ret; gpa_t vmptr; struct page *page; struct vcpu_vmx *vmx = to_vmx(vcpu); const u64 VMXON_NEEDED_FEATURES = FEATURE_CONTROL_LOCKED | FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX; /* * The Intel VMX Instruction Reference lists a bunch of bits that are * prerequisite to running VMXON, most notably cr4.VMXE must be set to * 1 (see vmx_set_cr4() for when we allow the guest to set this). * Otherwise, we should fail with #UD. But most faulting conditions * have already been checked by hardware, prior to the VM-exit for * VMXON. We do test guest cr4.VMXE because processor CR4 always has * that bit set to 1 in non-root mode. */ if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE)) { kvm_queue_exception(vcpu, UD_VECTOR); return 1; } if (vmx->nested.vmxon) { nested_vmx_failValid(vcpu, VMXERR_VMXON_IN_VMX_ROOT_OPERATION); return kvm_skip_emulated_instruction(vcpu); } if ((vmx->msr_ia32_feature_control & VMXON_NEEDED_FEATURES) != VMXON_NEEDED_FEATURES) { kvm_inject_gp(vcpu, 0); return 1; } if (nested_vmx_get_vmptr(vcpu, &vmptr)) return 1; /* * SDM 3: 24.11.5 * The first 4 bytes of VMXON region contain the supported * VMCS revision identifier * * Note - IA32_VMX_BASIC[48] will never be 1 for the nested case; * which replaces physical address width with 32 */ if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) { nested_vmx_failInvalid(vcpu); return kvm_skip_emulated_instruction(vcpu); } page = kvm_vcpu_gpa_to_page(vcpu, vmptr); if (is_error_page(page)) { nested_vmx_failInvalid(vcpu); return kvm_skip_emulated_instruction(vcpu); } if (*(u32 *)kmap(page) != VMCS12_REVISION) { kunmap(page); kvm_release_page_clean(page); nested_vmx_failInvalid(vcpu); return kvm_skip_emulated_instruction(vcpu); } kunmap(page); kvm_release_page_clean(page); vmx->nested.vmxon_ptr = vmptr; ret = enter_vmx_operation(vcpu); if (ret) return ret; nested_vmx_succeed(vcpu); return kvm_skip_emulated_instruction(vcpu); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284'], 'message': 'kvm: nVMX: Enforce cpl=0 for VMX instructions VMX instructions executed inside a L1 VM will always trigger a VM exit even when executed with cpl 3. This means we must perform the privilege check in software. Fixes: 70f3aac964ae("kvm: nVMX: Remove superfluous VMX instruction fault checks") Cc: stable@vger.kernel.org Signed-off-by: Felix Wilhelm <fwilhelm@google.com> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void RemoteFsDevice::mount() { if (details.isLocalFile()) { return; } if (isConnected() || proc) { return; } if (messageSent) { return; } if (constSambaAvahiProtocol==details.url.scheme()) { Details det=details; AvahiService *srv=Avahi::self()->getService(det.serviceName); if (!srv || srv->getHost().isEmpty() || 0==srv->getPort()) { emit error(tr("Failed to resolve connection details for %1").arg(details.name)); return; } if (constPromptPassword==det.url.password()) { bool ok=false; QString passwd=InputDialog::getPassword(QString(), &ok, QApplication::activeWindow()); if (!ok) { return; } det.url.setPassword(passwd); } det.url.setScheme(constSambaProtocol); det.url.setHost(srv->getHost()); det.url.setPort(srv->getPort()); mounter()->mount(det.url.toString(), mountPoint(details, true), getuid(), getgid(), getpid()); setStatusMessage(tr("Connecting...")); messageSent=true; return; } if (constSambaProtocol==details.url.scheme()) { Details det=details; if (constPromptPassword==det.url.password()) { bool ok=false; QString passwd=InputDialog::getPassword(QString(), &ok, QApplication::activeWindow()); if (!ok) { return; } det.url.setPassword(passwd); } mounter()->mount(det.url.toString(), mountPoint(details, true), getuid(), getgid(), getpid()); setStatusMessage(tr("Connecting...")); messageSent=true; return; } QString cmd; QStringList args; QString askPass; if (!details.isLocalFile() && !details.isEmpty()) { // If user has added 'IdentityFile' to extra options, then no password prompting is required... bool needAskPass=!details.extraOptions.contains("IdentityFile="); if (needAskPass) { QStringList askPassList; if (Utils::KDE==Utils::currentDe()) { askPassList << QLatin1String("ksshaskpass") << QLatin1String("ssh-askpass") << QLatin1String("ssh-askpass-gnome"); } else { askPassList << QLatin1String("ssh-askpass-gnome") << QLatin1String("ssh-askpass") << QLatin1String("ksshaskpass"); } for (const QString &ap: askPassList) { askPass=Utils::findExe(ap); if (!askPass.isEmpty()) { break; } } if (askPass.isEmpty()) { emit error(tr("No suitable ssh-askpass application installed! This is required for entering passwords.")); return; } } QString sshfs=Utils::findExe("sshfs"); if (sshfs.isEmpty()) { emit error(tr("\"sshfs\" is not installed!")); return; } cmd=Utils::findExe("setsid"); if (!cmd.isEmpty()) { QString mp=mountPoint(details, true); if (mp.isEmpty()) { emit error("Failed to determine mount point"); // TODO: 2.4 make translatable. For now, error should never happen! } if (!QDir(mp).entryList(QDir::NoDot|QDir::NoDotDot|QDir::AllEntries|QDir::Hidden).isEmpty()) { emit error(tr("Mount point (\"%1\") is not empty!").arg(mp)); return; } args << sshfs << details.url.userName()+QChar('@')+details.url.host()+QChar(':')+details.url.path()<< QLatin1String("-p") << QString::number(details.url.port()) << mountPoint(details, true) << QLatin1String("-o") << QLatin1String("ServerAliveInterval=15"); //<< QLatin1String("-o") << QLatin1String("Ciphers=arcfour"); if (!details.extraOptions.isEmpty()) { args << details.extraOptions.split(' ', QString::SkipEmptyParts); } } else { emit error(tr("\"sshfs\" is not installed!").replace("sshfs", "setsid")); // TODO: 2.4 use correct string! } } if (!cmd.isEmpty()) { setStatusMessage(tr("Connecting...")); proc=new QProcess(this); proc->setProperty("mount", true); if (!askPass.isEmpty()) { QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); env.insert("SSH_ASKPASS", askPass); proc->setProcessEnvironment(env); } connect(proc, SIGNAL(finished(int)), SLOT(procFinished(int))); proc->start(cmd, args, QIODevice::ReadOnly); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-22'], 'message': 'Remove internal Samba shre mounting code, this had some privilege escalation issues, and is not well tested'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: MpdCantataMounterInterface * RemoteFsDevice::mounter() { if (!mounterIface) { if (!QDBusConnection::systemBus().interface()->isServiceRegistered(MpdCantataMounterInterface::staticInterfaceName())) { QDBusConnection::systemBus().interface()->startService(MpdCantataMounterInterface::staticInterfaceName()); } mounterIface=new MpdCantataMounterInterface(MpdCantataMounterInterface::staticInterfaceName(), "/Mounter", QDBusConnection::systemBus(), this); connect(mounterIface, SIGNAL(mountStatus(const QString &, int, int)), SLOT(mountStatus(const QString &, int, int))); connect(mounterIface, SIGNAL(umountStatus(const QString &, int, int)), SLOT(umountStatus(const QString &, int, int))); } return mounterIface; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-22'], 'message': 'Remove internal Samba shre mounting code, this had some privilege escalation issues, and is not well tested'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: AvahiService::~AvahiService() { stop(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-22'], 'message': 'Remove internal Samba shre mounting code, this had some privilege escalation issues, and is not well tested'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Avahi * Avahi::self() { #ifdef ENABLE_KDE_SUPPORT return instance; #else static Avahi *instance=0; if(!instance) { instance=new Avahi; } return instance; #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-22'], 'message': 'Remove internal Samba shre mounting code, this had some privilege escalation issues, and is not well tested'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int main(int argc G_GNUC_UNUSED, char **argv G_GNUC_UNUSED) { SpiceMarshaller *marshaller; SpiceMsgMainShortDataSubMarshall *msg; size_t len, msg_len; int free_res; uint8_t *data; message_destructor_t free_message; msg = g_new0(SpiceMsgMainShortDataSubMarshall, 1); msg->data = g_new(uint64_t, 2); msg->dummy_byte = 123; msg->data_size = 2; msg->data[0] = 0x1234567890abcdef; msg->data[1] = 0xfedcba0987654321; marshaller = spice_marshaller_new(); spice_marshall_msg_main_ShortDataSubMarshall(marshaller, msg); spice_marshaller_flush(marshaller); data = spice_marshaller_linearize(marshaller, 0, &len, &free_res); g_assert_cmpint(len, ==, G_N_ELEMENTS(expected_data)); g_assert_true(memcmp(data, expected_data, len) == 0); g_free(msg->data); g_free(msg); // test demarshaller msg = (SpiceMsgMainShortDataSubMarshall *) spice_parse_msg(data, data + len, SPICE_CHANNEL_MAIN, SPICE_MSG_MAIN_SHORTDATASUBMARSHALL, 0, &msg_len, &free_message); g_assert_nonnull(msg); g_assert_cmpint(msg->dummy_byte, ==, 123); g_assert_cmpint(msg->data_size, ==, 2); g_assert_nonnull(msg->data); g_assert_cmpint(msg->data[0], ==, 0x1234567890abcdef); g_assert_cmpint(msg->data[1], ==, 0xfedcba0987654321); free_message((uint8_t *) msg); if (free_res) { free(data); } spice_marshaller_reset(marshaller); SpiceMsgMainZeroes msg_zeroes = { 0x0102 }; spice_marshall_msg_main_Zeroes(marshaller, &msg_zeroes); spice_marshaller_flush(marshaller); data = spice_marshaller_linearize(marshaller, 0, &len, &free_res); g_assert_cmpint(len, ==, 7); g_assert_true(memcmp(data, "\x00\x02\x01\x00\x00\x00\x00", 7) == 0); if (free_res) { free(data); } test_overflow(marshaller); spice_marshaller_destroy(marshaller); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix flexible array buffer overflow This is kind of a DoS, possibly flexible array in the protocol causes the network size check to be ignored due to integer overflows. The size of flexible array is computed as (message_end - position), then this size is added to the number of bytes before the array and this number is used to check if we overflow initial message. An example is: message { uint32 dummy[2]; uint8 data[] @end; } LenMessage; which generated this (simplified remove useless code) code: { /* data */ data__nelements = message_end - (start + 8); data__nw_size = data__nelements; } nw_size = 8 + data__nw_size; /* Check if message fits in reported side */ if (nw_size > (uintptr_t) (message_end - start)) { return NULL; } Following code: - data__nelements == message_end - (start + 8) - data__nw_size == data__nelements == message_end - (start + 8) - nw_size == 8 + data__nw_size == 8 + message_end - (start + 8) == 8 + message_end - start - 8 == message_end -start - the check for overflow is (nw_size > (message_end - start)) but nw_size == message_end - start so the check is doing ((message_end - start) > (message_end - start)) which is always false. If message_end - start < 8 then data__nelements (number of element on the array above) computation generate an integer underflow that later create a buffer overflow. Add a check to make sure that the array starts before the message ends to avoid the overflow. Difference is: diff -u save/generated_client_demarshallers1.c common/generated_client_demarshallers1.c --- save/generated_client_demarshallers1.c 2018-06-22 22:13:48.626793919 +0100 +++ common/generated_client_demarshallers1.c 2018-06-22 22:14:03.408163291 +0100 @@ -225,6 +225,9 @@ uint64_t data__nelements; { /* data */ + if (SPICE_UNLIKELY((start + 0) > message_end)) { + goto error; + } data__nelements = message_end - (start + 0); data__nw_size = data__nelements; @@ -243,6 +246,9 @@ *free_message = nofree; return data; + error: + free(data); + return NULL; } static uint8_t * parse_msg_set_ack(uint8_t *message_start, uint8_t *message_end, SPICE_GNUC_UNUSED int minor, size_t *size, message_destructor_t *free_message) @@ -301,6 +307,9 @@ SpiceMsgPing *out; { /* data */ + if (SPICE_UNLIKELY((start + 12) > message_end)) { + goto error; + } data__nelements = message_end - (start + 12); data__nw_size = data__nelements; @@ -5226,6 +5235,9 @@ uint64_t cursor_data__nw_size; uint64_t cursor_data__nelements; { /* data */ + if (SPICE_UNLIKELY((start2 + 22) > message_end)) { + goto error; + } cursor_data__nelements = message_end - (start2 + 22); cursor_data__nw_size = cursor_data__nelements; @@ -5305,6 +5317,9 @@ uint64_t cursor_data__nw_size; uint64_t cursor_data__nelements; { /* data */ + if (SPICE_UNLIKELY((start2 + 22) > message_end)) { + goto error; + } cursor_data__nelements = message_end - (start2 + 22); cursor_data__nw_size = cursor_data__nelements; @@ -5540,6 +5555,9 @@ SpiceMsgPlaybackPacket *out; { /* data */ + if (SPICE_UNLIKELY((start + 4) > message_end)) { + goto error; + } data__nelements = message_end - (start + 4); data__nw_size = data__nelements; @@ -5594,6 +5612,9 @@ SpiceMsgPlaybackMode *out; { /* data */ + if (SPICE_UNLIKELY((start + 8) > message_end)) { + goto error; + } data__nelements = message_end - (start + 8); data__nw_size = data__nelements; diff -u save/generated_client_demarshallers.c common/generated_client_demarshallers.c --- save/generated_client_demarshallers.c 2018-06-22 22:13:48.626793919 +0100 +++ common/generated_client_demarshallers.c 2018-06-22 22:14:03.004153195 +0100 @@ -225,6 +225,9 @@ uint64_t data__nelements; { /* data */ + if (SPICE_UNLIKELY((start + 0) > message_end)) { + goto error; + } data__nelements = message_end - (start + 0); data__nw_size = data__nelements; @@ -243,6 +246,9 @@ *free_message = nofree; return data; + error: + free(data); + return NULL; } static uint8_t * parse_msg_set_ack(uint8_t *message_start, uint8_t *message_end, SPICE_GNUC_UNUSED int minor, size_t *size, message_destructor_t *free_message) @@ -301,6 +307,9 @@ SpiceMsgPing *out; { /* data */ + if (SPICE_UNLIKELY((start + 12) > message_end)) { + goto error; + } data__nelements = message_end - (start + 12); data__nw_size = data__nelements; @@ -6574,6 +6583,9 @@ } { /* data */ + if (SPICE_UNLIKELY((start2 + 2 + cursor_u__nw_size) > message_end)) { + goto error; + } cursor_data__nelements = message_end - (start2 + 2 + cursor_u__nw_size); cursor_data__nw_size = cursor_data__nelements; @@ -6670,6 +6682,9 @@ } { /* data */ + if (SPICE_UNLIKELY((start2 + 2 + cursor_u__nw_size) > message_end)) { + goto error; + } cursor_data__nelements = message_end - (start2 + 2 + cursor_u__nw_size); cursor_data__nw_size = cursor_data__nelements; @@ -6907,6 +6922,9 @@ SpiceMsgPlaybackPacket *out; { /* data */ + if (SPICE_UNLIKELY((start + 4) > message_end)) { + goto error; + } data__nelements = message_end - (start + 4); data__nw_size = data__nelements; @@ -6961,6 +6979,9 @@ SpiceMsgPlaybackMode *out; { /* data */ + if (SPICE_UNLIKELY((start + 6) > message_end)) { + goto error; + } data__nelements = message_end - (start + 6); data__nw_size = data__nelements; @@ -7559,6 +7580,9 @@ SpiceMsgTunnelSocketData *out; { /* data */ + if (SPICE_UNLIKELY((start + 2) > message_end)) { + goto error; + } data__nelements = message_end - (start + 2); data__nw_size = data__nelements; @@ -7840,6 +7864,9 @@ } { /* compressed_data */ + if (SPICE_UNLIKELY((start + 1 + u__nw_size) > message_end)) { + goto error; + } compressed_data__nelements = message_end - (start + 1 + u__nw_size); compressed_data__nw_size = compressed_data__nelements; diff -u save/generated_server_demarshallers.c common/generated_server_demarshallers.c --- save/generated_server_demarshallers.c 2018-06-22 22:13:48.627793944 +0100 +++ common/generated_server_demarshallers.c 2018-06-22 22:14:05.231208847 +0100 @@ -306,6 +306,9 @@ uint64_t data__nelements; { /* data */ + if (SPICE_UNLIKELY((start + 0) > message_end)) { + goto error; + } data__nelements = message_end - (start + 0); data__nw_size = data__nelements; @@ -324,6 +327,9 @@ *free_message = nofree; return data; + error: + free(data); + return NULL; } static uint8_t * parse_msgc_disconnecting(uint8_t *message_start, uint8_t *message_end, SPICE_GNUC_UNUSED int minor, size_t *size, message_destructor_t *free_message) @@ -1259,6 +1265,9 @@ SpiceMsgcRecordPacket *out; { /* data */ + if (SPICE_UNLIKELY((start + 4) > message_end)) { + goto error; + } data__nelements = message_end - (start + 4); data__nw_size = data__nelements; @@ -1313,6 +1322,9 @@ SpiceMsgcRecordMode *out; { /* data */ + if (SPICE_UNLIKELY((start + 6) > message_end)) { + goto error; + } data__nelements = message_end - (start + 6); data__nw_size = data__nelements; @@ -1841,6 +1853,9 @@ SpiceMsgcTunnelSocketData *out; { /* data */ + if (SPICE_UNLIKELY((start + 2) > message_end)) { + goto error; + } data__nelements = message_end - (start + 2); data__nw_size = data__nelements; @@ -2057,6 +2072,9 @@ } { /* compressed_data */ + if (SPICE_UNLIKELY((start + 1 + u__nw_size) > message_end)) { + goto error; + } compressed_data__nelements = message_end - (start + 1 + u__nw_size); compressed_data__nw_size = compressed_data__nelements; Signed-off-by: Frediano Ziglio <fziglio@redhat.com> Signed-off-by: Christophe Fergeau <cfergeau@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int ext4_xattr_set_entry(struct ext4_xattr_info *i, struct ext4_xattr_search *s, handle_t *handle, struct inode *inode, bool is_block) { struct ext4_xattr_entry *last; struct ext4_xattr_entry *here = s->here; size_t min_offs = s->end - s->base, name_len = strlen(i->name); int in_inode = i->in_inode; struct inode *old_ea_inode = NULL; struct inode *new_ea_inode = NULL; size_t old_size, new_size; int ret; /* Space used by old and new values. */ old_size = (!s->not_found && !here->e_value_inum) ? EXT4_XATTR_SIZE(le32_to_cpu(here->e_value_size)) : 0; new_size = (i->value && !in_inode) ? EXT4_XATTR_SIZE(i->value_len) : 0; /* * Optimization for the simple case when old and new values have the * same padded sizes. Not applicable if external inodes are involved. */ if (new_size && new_size == old_size) { size_t offs = le16_to_cpu(here->e_value_offs); void *val = s->base + offs; here->e_value_size = cpu_to_le32(i->value_len); if (i->value == EXT4_ZERO_XATTR_VALUE) { memset(val, 0, new_size); } else { memcpy(val, i->value, i->value_len); /* Clear padding bytes. */ memset(val + i->value_len, 0, new_size - i->value_len); } goto update_hash; } /* Compute min_offs and last. */ last = s->first; for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) { if (!last->e_value_inum && last->e_value_size) { size_t offs = le16_to_cpu(last->e_value_offs); if (offs < min_offs) min_offs = offs; } } /* Check whether we have enough space. */ if (i->value) { size_t free; free = min_offs - ((void *)last - s->base) - sizeof(__u32); if (!s->not_found) free += EXT4_XATTR_LEN(name_len) + old_size; if (free < EXT4_XATTR_LEN(name_len) + new_size) { ret = -ENOSPC; goto out; } /* * If storing the value in an external inode is an option, * reserve space for xattr entries/names in the external * attribute block so that a long value does not occupy the * whole space and prevent futher entries being added. */ if (ext4_has_feature_ea_inode(inode->i_sb) && new_size && is_block && (min_offs + old_size - new_size) < EXT4_XATTR_BLOCK_RESERVE(inode)) { ret = -ENOSPC; goto out; } } /* * Getting access to old and new ea inodes is subject to failures. * Finish that work before doing any modifications to the xattr data. */ if (!s->not_found && here->e_value_inum) { ret = ext4_xattr_inode_iget(inode, le32_to_cpu(here->e_value_inum), le32_to_cpu(here->e_hash), &old_ea_inode); if (ret) { old_ea_inode = NULL; goto out; } } if (i->value && in_inode) { WARN_ON_ONCE(!i->value_len); ret = ext4_xattr_inode_alloc_quota(inode, i->value_len); if (ret) goto out; ret = ext4_xattr_inode_lookup_create(handle, inode, i->value, i->value_len, &new_ea_inode); if (ret) { new_ea_inode = NULL; ext4_xattr_inode_free_quota(inode, NULL, i->value_len); goto out; } } if (old_ea_inode) { /* We are ready to release ref count on the old_ea_inode. */ ret = ext4_xattr_inode_dec_ref(handle, old_ea_inode); if (ret) { /* Release newly required ref count on new_ea_inode. */ if (new_ea_inode) { int err; err = ext4_xattr_inode_dec_ref(handle, new_ea_inode); if (err) ext4_warning_inode(new_ea_inode, "dec ref new_ea_inode err=%d", err); ext4_xattr_inode_free_quota(inode, new_ea_inode, i->value_len); } goto out; } ext4_xattr_inode_free_quota(inode, old_ea_inode, le32_to_cpu(here->e_value_size)); } /* No failures allowed past this point. */ if (!s->not_found && here->e_value_size && here->e_value_offs) { /* Remove the old value. */ void *first_val = s->base + min_offs; size_t offs = le16_to_cpu(here->e_value_offs); void *val = s->base + offs; memmove(first_val + old_size, first_val, val - first_val); memset(first_val, 0, old_size); min_offs += old_size; /* Adjust all value offsets. */ last = s->first; while (!IS_LAST_ENTRY(last)) { size_t o = le16_to_cpu(last->e_value_offs); if (!last->e_value_inum && last->e_value_size && o < offs) last->e_value_offs = cpu_to_le16(o + old_size); last = EXT4_XATTR_NEXT(last); } } if (!i->value) { /* Remove old name. */ size_t size = EXT4_XATTR_LEN(name_len); last = ENTRY((void *)last - size); memmove(here, (void *)here + size, (void *)last - (void *)here + sizeof(__u32)); memset(last, 0, size); } else if (s->not_found) { /* Insert new name. */ size_t size = EXT4_XATTR_LEN(name_len); size_t rest = (void *)last - (void *)here + sizeof(__u32); memmove((void *)here + size, here, rest); memset(here, 0, size); here->e_name_index = i->name_index; here->e_name_len = name_len; memcpy(here->e_name, i->name, name_len); } else { /* This is an update, reset value info. */ here->e_value_inum = 0; here->e_value_offs = 0; here->e_value_size = 0; } if (i->value) { /* Insert new value. */ if (in_inode) { here->e_value_inum = cpu_to_le32(new_ea_inode->i_ino); } else if (i->value_len) { void *val = s->base + min_offs - new_size; here->e_value_offs = cpu_to_le16(min_offs - new_size); if (i->value == EXT4_ZERO_XATTR_VALUE) { memset(val, 0, new_size); } else { memcpy(val, i->value, i->value_len); /* Clear padding bytes. */ memset(val + i->value_len, 0, new_size - i->value_len); } } here->e_value_size = cpu_to_le32(i->value_len); } update_hash: if (i->value) { __le32 hash = 0; /* Entry hash calculation. */ if (in_inode) { __le32 crc32c_hash; /* * Feed crc32c hash instead of the raw value for entry * hash calculation. This is to avoid walking * potentially long value buffer again. */ crc32c_hash = cpu_to_le32( ext4_xattr_inode_get_hash(new_ea_inode)); hash = ext4_xattr_hash_entry(here->e_name, here->e_name_len, &crc32c_hash, 1); } else if (is_block) { __le32 *value = s->base + le16_to_cpu( here->e_value_offs); hash = ext4_xattr_hash_entry(here->e_name, here->e_name_len, value, new_size >> 2); } here->e_hash = hash; } if (is_block) ext4_xattr_rehash((struct ext4_xattr_header *)s->base); ret = 0; out: iput(old_ea_inode); iput(new_ea_inode); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'ext4: add corruption check in ext4_xattr_set_entry() In theory this should have been caught earlier when the xattr list was verified, but in case it got missed, it's simple enough to add check to make sure we don't overrun the xattr buffer. This addresses CVE-2018-10879. https://bugzilla.kernel.org/show_bug.cgi?id=200001 Signed-off-by: Theodore Ts'o <tytso@mit.edu> Reviewed-by: Andreas Dilger <adilger@dilger.ca> Cc: stable@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: int jbd2_journal_dirty_metadata(handle_t *handle, struct buffer_head *bh) { transaction_t *transaction = handle->h_transaction; journal_t *journal; struct journal_head *jh; int ret = 0; if (is_handle_aborted(handle)) return -EROFS; if (!buffer_jbd(bh)) { ret = -EUCLEAN; goto out; } /* * We don't grab jh reference here since the buffer must be part * of the running transaction. */ jh = bh2jh(bh); /* * This and the following assertions are unreliable since we may see jh * in inconsistent state unless we grab bh_state lock. But this is * crucial to catch bugs so let's do a reliable check until the * lockless handling is fully proven. */ if (jh->b_transaction != transaction && jh->b_next_transaction != transaction) { jbd_lock_bh_state(bh); J_ASSERT_JH(jh, jh->b_transaction == transaction || jh->b_next_transaction == transaction); jbd_unlock_bh_state(bh); } if (jh->b_modified == 1) { /* If it's in our transaction it must be in BJ_Metadata list. */ if (jh->b_transaction == transaction && jh->b_jlist != BJ_Metadata) { jbd_lock_bh_state(bh); J_ASSERT_JH(jh, jh->b_transaction != transaction || jh->b_jlist == BJ_Metadata); jbd_unlock_bh_state(bh); } goto out; } journal = transaction->t_journal; jbd_debug(5, "journal_head %p\n", jh); JBUFFER_TRACE(jh, "entry"); jbd_lock_bh_state(bh); if (jh->b_modified == 0) { /* * This buffer's got modified and becoming part * of the transaction. This needs to be done * once a transaction -bzzz */ jh->b_modified = 1; if (handle->h_buffer_credits <= 0) { ret = -ENOSPC; goto out_unlock_bh; } handle->h_buffer_credits--; } /* * fastpath, to avoid expensive locking. If this buffer is already * on the running transaction's metadata list there is nothing to do. * Nobody can take it off again because there is a handle open. * I _think_ we're OK here with SMP barriers - a mistaken decision will * result in this test being false, so we go in and take the locks. */ if (jh->b_transaction == transaction && jh->b_jlist == BJ_Metadata) { JBUFFER_TRACE(jh, "fastpath"); if (unlikely(jh->b_transaction != journal->j_running_transaction)) { printk(KERN_ERR "JBD2: %s: " "jh->b_transaction (%llu, %p, %u) != " "journal->j_running_transaction (%p, %u)\n", journal->j_devname, (unsigned long long) bh->b_blocknr, jh->b_transaction, jh->b_transaction ? jh->b_transaction->t_tid : 0, journal->j_running_transaction, journal->j_running_transaction ? journal->j_running_transaction->t_tid : 0); ret = -EINVAL; } goto out_unlock_bh; } set_buffer_jbddirty(bh); /* * Metadata already on the current transaction list doesn't * need to be filed. Metadata on another transaction's list must * be committing, and will be refiled once the commit completes: * leave it alone for now. */ if (jh->b_transaction != transaction) { JBUFFER_TRACE(jh, "already on other transaction"); if (unlikely(((jh->b_transaction != journal->j_committing_transaction)) || (jh->b_next_transaction != transaction))) { printk(KERN_ERR "jbd2_journal_dirty_metadata: %s: " "bad jh for block %llu: " "transaction (%p, %u), " "jh->b_transaction (%p, %u), " "jh->b_next_transaction (%p, %u), jlist %u\n", journal->j_devname, (unsigned long long) bh->b_blocknr, transaction, transaction->t_tid, jh->b_transaction, jh->b_transaction ? jh->b_transaction->t_tid : 0, jh->b_next_transaction, jh->b_next_transaction ? jh->b_next_transaction->t_tid : 0, jh->b_jlist); WARN_ON(1); ret = -EINVAL; } /* And this case is illegal: we can't reuse another * transaction's data buffer, ever. */ goto out_unlock_bh; } /* That test should have eliminated the following case: */ J_ASSERT_JH(jh, jh->b_frozen_data == NULL); JBUFFER_TRACE(jh, "file as BJ_Metadata"); spin_lock(&journal->j_list_lock); __jbd2_journal_file_buffer(jh, transaction, BJ_Metadata); spin_unlock(&journal->j_list_lock); out_unlock_bh: jbd_unlock_bh_state(bh); out: JBUFFER_TRACE(jh, "exit"); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'jbd2: don't mark block as modified if the handle is out of credits Do not set the b_modified flag in block's journal head should not until after we're sure that jbd2_journal_dirty_metadat() will not abort with an error due to there not being enough space reserved in the jbd2 handle. Otherwise, future attempts to modify the buffer may lead a large number of spurious errors and warnings. This addresses CVE-2018-10883. https://bugzilla.kernel.org/show_bug.cgi?id=200071 Signed-off-by: Theodore Ts'o <tytso@mit.edu> Cc: stable@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: xfs_iget_cache_miss( struct xfs_mount *mp, struct xfs_perag *pag, xfs_trans_t *tp, xfs_ino_t ino, struct xfs_inode **ipp, int flags, int lock_flags) { struct xfs_inode *ip; int error; xfs_agino_t agino = XFS_INO_TO_AGINO(mp, ino); int iflags; ip = xfs_inode_alloc(mp, ino); if (!ip) return -ENOMEM; error = xfs_iread(mp, tp, ip, flags); if (error) goto out_destroy; if (!xfs_inode_verify_forks(ip)) { error = -EFSCORRUPTED; goto out_destroy; } trace_xfs_iget_miss(ip); /* * If we are allocating a new inode, then check what was returned is * actually a free, empty inode. If we are not allocating an inode, * the check we didn't find a free inode. */ if (flags & XFS_IGET_CREATE) { if (VFS_I(ip)->i_mode != 0) { xfs_warn(mp, "Corruption detected! Free inode 0x%llx not marked free on disk", ino); error = -EFSCORRUPTED; goto out_destroy; } if (ip->i_d.di_nblocks != 0) { xfs_warn(mp, "Corruption detected! Free inode 0x%llx has blocks allocated!", ino); error = -EFSCORRUPTED; goto out_destroy; } } else if (VFS_I(ip)->i_mode == 0) { error = -ENOENT; goto out_destroy; } /* * Preload the radix tree so we can insert safely under the * write spinlock. Note that we cannot sleep inside the preload * region. Since we can be called from transaction context, don't * recurse into the file system. */ if (radix_tree_preload(GFP_NOFS)) { error = -EAGAIN; goto out_destroy; } /* * Because the inode hasn't been added to the radix-tree yet it can't * be found by another thread, so we can do the non-sleeping lock here. */ if (lock_flags) { if (!xfs_ilock_nowait(ip, lock_flags)) BUG(); } /* * These values must be set before inserting the inode into the radix * tree as the moment it is inserted a concurrent lookup (allowed by the * RCU locking mechanism) can find it and that lookup must see that this * is an inode currently under construction (i.e. that XFS_INEW is set). * The ip->i_flags_lock that protects the XFS_INEW flag forms the * memory barrier that ensures this detection works correctly at lookup * time. */ iflags = XFS_INEW; if (flags & XFS_IGET_DONTCACHE) iflags |= XFS_IDONTCACHE; ip->i_udquot = NULL; ip->i_gdquot = NULL; ip->i_pdquot = NULL; xfs_iflags_set(ip, iflags); /* insert the new inode */ spin_lock(&pag->pag_ici_lock); error = radix_tree_insert(&pag->pag_ici_root, agino, ip); if (unlikely(error)) { WARN_ON(error != -EEXIST); XFS_STATS_INC(mp, xs_ig_dup); error = -EAGAIN; goto out_preload_end; } spin_unlock(&pag->pag_ici_lock); radix_tree_preload_end(); *ipp = ip; return 0; out_preload_end: spin_unlock(&pag->pag_ici_lock); radix_tree_preload_end(); if (lock_flags) xfs_iunlock(ip, lock_flags); out_destroy: __destroy_inode(VFS_I(ip)); xfs_inode_free(ip); return error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'xfs: validate cached inodes are free when allocated A recent fuzzed filesystem image cached random dcache corruption when the reproducer was run. This often showed up as panics in lookup_slow() on a null inode->i_ops pointer when doing pathwalks. BUG: unable to handle kernel NULL pointer dereference at 0000000000000000 .... Call Trace: lookup_slow+0x44/0x60 walk_component+0x3dd/0x9f0 link_path_walk+0x4a7/0x830 path_lookupat+0xc1/0x470 filename_lookup+0x129/0x270 user_path_at_empty+0x36/0x40 path_listxattr+0x98/0x110 SyS_listxattr+0x13/0x20 do_syscall_64+0xf5/0x280 entry_SYSCALL_64_after_hwframe+0x42/0xb7 but had many different failure modes including deadlocks trying to lock the inode that was just allocated or KASAN reports of use-after-free violations. The cause of the problem was a corrupt INOBT on a v4 fs where the root inode was marked as free in the inobt record. Hence when we allocated an inode, it chose the root inode to allocate, found it in the cache and re-initialised it. We recently fixed a similar inode allocation issue caused by inobt record corruption problem in xfs_iget_cache_miss() in commit ee457001ed6c ("xfs: catch inode allocation state mismatch corruption"). This change adds similar checks to the cache-hit path to catch it, and turns the reproducer into a corruption shutdown situation. Reported-by: Wen Xu <wen.xu@gatech.edu> Signed-Off-By: Dave Chinner <dchinner@redhat.com> Reviewed-by: Christoph Hellwig <hch@lst.de> Reviewed-by: Carlos Maiolino <cmaiolino@redhat.com> Reviewed-by: Darrick J. Wong <darrick.wong@oracle.com> [darrick: fix typos in comment] Signed-off-by: Darrick J. Wong <darrick.wong@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 Image *XMagickCommand(Display *display,XResourceInfo *resource_info, XWindows *windows,const CommandType command_type,Image **image, MagickStatusType *state,ExceptionInfo *exception) { Image *nexus; MagickBooleanType proceed; MagickStatusType status; XTextProperty window_name; /* Process user command. */ nexus=NewImageList(); switch (command_type) { case OpenCommand: { char **filelist; Image *images, *next; ImageInfo *read_info; int number_files; register int i; static char filenames[MagickPathExtent] = "*"; if (resource_info->immutable != MagickFalse) break; /* Request file name from user. */ XFileBrowserWidget(display,windows,"Animate",filenames); if (*filenames == '\0') return((Image *) NULL); /* Expand the filenames. */ filelist=(char **) AcquireMagickMemory(sizeof(char *)); if (filelist == (char **) NULL) { ThrowXWindowException(ResourceLimitError,"MemoryAllocationFailed", filenames); return((Image *) NULL); } number_files=1; filelist[0]=filenames; status=ExpandFilenames(&number_files,&filelist); if ((status == MagickFalse) || (number_files == 0)) { if (number_files == 0) { ThrowXWindowException(ImageError,"NoImagesWereLoaded",filenames); return((Image *) NULL); } ThrowXWindowException(ResourceLimitError,"MemoryAllocationFailed", filenames); return((Image *) NULL); } read_info=CloneImageInfo(resource_info->image_info); images=NewImageList(); XSetCursorState(display,windows,MagickTrue); XCheckRefreshWindows(display,windows); for (i=0; i < number_files; i++) { (void) CopyMagickString(read_info->filename,filelist[i],MagickPathExtent); filelist[i]=DestroyString(filelist[i]); *read_info->magick='\0'; next=ReadImage(read_info,exception); CatchException(exception); if (next != (Image *) NULL) AppendImageToList(&images,next); if (number_files <= 5) continue; proceed=SetImageProgress(images,LoadImageTag,i,(MagickSizeType) number_files); if (proceed == MagickFalse) break; } filelist=(char **) RelinquishMagickMemory(filelist); read_info=DestroyImageInfo(read_info); if (images == (Image *) NULL) { XSetCursorState(display,windows,MagickFalse); ThrowXWindowException(ImageError,"NoImagesWereLoaded",filenames); return((Image *) NULL); } nexus=GetFirstImageInList(images); *state|=ExitState; break; } case PlayCommand: { char basename[MagickPathExtent]; int status; /* Window name is the base of the filename. */ *state|=PlayAnimationState; *state&=(~AutoReverseAnimationState); GetPathComponent((*image)->magick_filename,BasePath,basename); (void) FormatLocaleString(windows->image.name,MagickPathExtent, "%s: %s",MagickPackageName,basename); if (resource_info->title != (char *) NULL) { char *title; title=InterpretImageProperties(resource_info->image_info,*image, resource_info->title,exception); (void) CopyMagickString(windows->image.name,title,MagickPathExtent); title=DestroyString(title); } status=XStringListToTextProperty(&windows->image.name,1,&window_name); if (status == 0) break; XSetWMName(display,windows->image.id,&window_name); (void) XFree((void *) window_name.value); break; } case StepCommand: case StepBackwardCommand: case StepForwardCommand: { *state|=StepAnimationState; *state&=(~PlayAnimationState); if (command_type == StepBackwardCommand) *state&=(~ForwardAnimationState); if (command_type == StepForwardCommand) *state|=ForwardAnimationState; if (resource_info->title != (char *) NULL) break; break; } case RepeatCommand: { *state|=RepeatAnimationState; *state&=(~AutoReverseAnimationState); *state|=PlayAnimationState; break; } case AutoReverseCommand: { *state|=AutoReverseAnimationState; *state&=(~RepeatAnimationState); *state|=PlayAnimationState; break; } case SaveCommand: { /* Save image. */ status=XSaveImage(display,resource_info,windows,*image,exception); if (status == MagickFalse) { char message[MagickPathExtent]; (void) FormatLocaleString(message,MagickPathExtent,"%s:%s", exception->reason != (char *) NULL ? exception->reason : "", exception->description != (char *) NULL ? exception->description : ""); XNoticeWidget(display,windows,"Unable to save file:",message); break; } break; } case SlowerCommand: { resource_info->delay++; break; } case FasterCommand: { if (resource_info->delay == 0) break; resource_info->delay--; break; } case ForwardCommand: { *state=ForwardAnimationState; *state&=(~AutoReverseAnimationState); break; } case ReverseCommand: { *state&=(~ForwardAnimationState); *state&=(~AutoReverseAnimationState); break; } case InfoCommand: { XDisplayImageInfo(display,resource_info,windows,(Image *) NULL,*image, exception); break; } case HelpCommand: { /* User requested help. */ XTextViewWidget(display,resource_info,windows,MagickFalse, "Help Viewer - Animate",AnimateHelp); break; } case BrowseDocumentationCommand: { Atom mozilla_atom; Window mozilla_window, root_window; /* Browse the ImageMagick documentation. */ root_window=XRootWindow(display,XDefaultScreen(display)); mozilla_atom=XInternAtom(display,"_MOZILLA_VERSION",MagickFalse); mozilla_window=XWindowByProperty(display,root_window,mozilla_atom); if (mozilla_window != (Window) NULL) { char command[MagickPathExtent], *url; /* Display documentation using Netscape remote control. */ url=GetMagickHomeURL(); (void) FormatLocaleString(command,MagickPathExtent, "openurl(%s,new-tab)",url); url=DestroyString(url); mozilla_atom=XInternAtom(display,"_MOZILLA_COMMAND",MagickFalse); (void) XChangeProperty(display,mozilla_window,mozilla_atom, XA_STRING,8,PropModeReplace,(unsigned char *) command, (int) strlen(command)); XSetCursorState(display,windows,MagickFalse); break; } XSetCursorState(display,windows,MagickTrue); XCheckRefreshWindows(display,windows); status=InvokeDelegate(resource_info->image_info,*image,"browse", (char *) NULL,exception); if (status == MagickFalse) XNoticeWidget(display,windows,"Unable to browse documentation", (char *) NULL); XDelay(display,1500); XSetCursorState(display,windows,MagickFalse); break; } case VersionCommand: { XNoticeWidget(display,windows,GetMagickVersion((size_t *) NULL), GetMagickCopyright()); break; } case QuitCommand: { /* exit program */ if (resource_info->confirm_exit == MagickFalse) XClientMessage(display,windows->image.id,windows->im_protocols, windows->im_exit,CurrentTime); else { int status; /* Confirm program exit. */ status=XConfirmWidget(display,windows,"Do you really want to exit", resource_info->client_name); if (status != 0) XClientMessage(display,windows->image.id,windows->im_protocols, windows->im_exit,CurrentTime); } break; } default: break; } return(nexus); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-772'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1195'</s>
<s>[INST] Given the following code containing errors, provide 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 RateTransposer::setChannels(int nChannels) { assert(nChannels > 0); if (pTransposer->numChannels == nChannels) return; pTransposer->setChannels(nChannels); inputBuffer.setChannels(nChannels); midBuffer.setChannels(nChannels); outputBuffer.setChannels(nChannels); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-617'], 'message': 'Replaced illegal-number-of-channel assertions with run-time exception'</s>
<s>[INST] Given the following code containing errors, provide 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 pop_sync_mailbox (CONTEXT *ctx, int *index_hint) { int i, j, ret = 0; char buf[LONG_STRING]; POP_DATA *pop_data = (POP_DATA *)ctx->data; progress_t progress; #ifdef USE_HCACHE header_cache_t *hc = NULL; #endif pop_data->check_time = 0; FOREVER { if (pop_reconnect (ctx) < 0) return -1; mutt_progress_init (&progress, _("Marking messages deleted..."), MUTT_PROGRESS_MSG, WriteInc, ctx->deleted); #if USE_HCACHE hc = pop_hcache_open (pop_data, ctx->path); #endif for (i = 0, j = 0, ret = 0; ret == 0 && i < ctx->msgcount; i++) { if (ctx->hdrs[i]->deleted && ctx->hdrs[i]->refno != -1) { j++; if (!ctx->quiet) mutt_progress_update (&progress, j, -1); snprintf (buf, sizeof (buf), "DELE %d\r\n", ctx->hdrs[i]->refno); if ((ret = pop_query (pop_data, buf, sizeof (buf))) == 0) { mutt_bcache_del (pop_data->bcache, ctx->hdrs[i]->data); #if USE_HCACHE mutt_hcache_delete (hc, ctx->hdrs[i]->data, strlen); #endif } } #if USE_HCACHE if (ctx->hdrs[i]->changed) { mutt_hcache_store (hc, ctx->hdrs[i]->data, ctx->hdrs[i], 0, strlen, MUTT_GENERATE_UIDVALIDITY); } #endif } #if USE_HCACHE mutt_hcache_close (hc); #endif if (ret == 0) { strfcpy (buf, "QUIT\r\n", sizeof (buf)); ret = pop_query (pop_data, buf, sizeof (buf)); } if (ret == 0) { pop_data->clear_cache = 1; pop_clear_cache (pop_data); pop_data->status = POP_DISCONNECTED; return 0; } if (ret == -2) { mutt_error ("%s", pop_data->err_msg); mutt_sleep (2); return -1; } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Sanitize POP bcache paths. Protect against bcache directory path traversal for UID values. Thanks for Jeriko One for the bug report and patch, which this commit is based upon.'</s>
<s>[INST] Given the following code containing errors, provide 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 cmd_parse_lsub(struct ImapData *idata, char *s) { char buf[STRING]; char errstr[STRING]; struct Buffer err, token; struct Url url; struct ImapList list; if (idata->cmddata && idata->cmdtype == IMAP_CT_LIST) { /* caller will handle response itself */ cmd_parse_list(idata, s); return; } if (!ImapCheckSubscribed) return; idata->cmdtype = IMAP_CT_LIST; idata->cmddata = &list; cmd_parse_list(idata, s); idata->cmddata = NULL; /* noselect is for a gmail quirk (#3445) */ if (!list.name || list.noselect) return; mutt_debug(3, "Subscribing to %s\n", list.name); mutt_str_strfcpy(buf, "mailboxes \"", sizeof(buf)); mutt_account_tourl(&idata->conn->account, &url); /* escape \ and " */ imap_quote_string(errstr, sizeof(errstr), list.name); url.path = errstr + 1; url.path[strlen(url.path) - 1] = '\0'; if (mutt_str_strcmp(url.user, ImapUser) == 0) url.user = NULL; url_tostring(&url, buf + 11, sizeof(buf) - 11, 0); mutt_str_strcat(buf, sizeof(buf), "\""); mutt_buffer_init(&token); mutt_buffer_init(&err); err.data = errstr; err.dsize = sizeof(errstr); if (mutt_parse_rc_line(buf, &token, &err)) mutt_debug(1, "Error adding subscribed mailbox: %s\n", errstr); FREE(&token.data); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-78', 'CWE-77'], 'message': 'quote imap strings more carefully Co-authored-by: JerikoOne <jeriko.one@gmx.us>'</s>
<s>[INST] Given the following code containing errors, provide 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 fetch_uidl (char *line, void *data) { int i, index; CONTEXT *ctx = (CONTEXT *)data; POP_DATA *pop_data = (POP_DATA *)ctx->data; char *endp; errno = 0; index = strtol(line, &endp, 10); if (errno) return -1; while (*endp == ' ') endp++; memmove(line, endp, strlen(endp) + 1); for (i = 0; i < ctx->msgcount; i++) if (!mutt_strcmp (line, ctx->hdrs[i]->data)) break; if (i == ctx->msgcount) { dprint (1, (debugfile, "pop_fetch_headers: new header %d %s\n", index, line)); if (i >= ctx->hdrmax) mx_alloc_memory(ctx); ctx->msgcount++; ctx->hdrs[i] = mutt_new_header (); ctx->hdrs[i]->data = safe_strdup (line); } else if (ctx->hdrs[i]->index != index - 1) pop_data->clear_cache = 1; ctx->hdrs[i]->refno = index; ctx->hdrs[i]->index = index - 1; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-824'], 'message': 'Ensure UID in fetch_uidl.'</s>
<s>[INST] Given the following code containing errors, provide 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 md_require_https_maybe(request_rec *r) { const md_srv_conf_t *sc; apr_uri_t uri; const char *s; int status; if (opt_ssl_is_https && strncmp(WELL_KNOWN_PREFIX, r->parsed_uri.path, sizeof(WELL_KNOWN_PREFIX)-1)) { sc = ap_get_module_config(r->server->module_config, &md_module); if (sc && sc->assigned && sc->assigned->require_https > MD_REQUIRE_OFF) { if (opt_ssl_is_https(r->connection)) { /* Using https: * if 'permanent' and no one else set a HSTS header already, do it */ if (sc->assigned->require_https == MD_REQUIRE_PERMANENT && sc->mc->hsts_header && !apr_table_get(r->headers_out, MD_HSTS_HEADER)) { apr_table_setn(r->headers_out, MD_HSTS_HEADER, sc->mc->hsts_header); } } else { /* Not using https:, but require it. Redirect. */ if (r->method_number == M_GET) { /* safe to use the old-fashioned codes */ status = ((MD_REQUIRE_PERMANENT == sc->assigned->require_https)? HTTP_MOVED_PERMANENTLY : HTTP_MOVED_TEMPORARILY); } else { /* these should keep the method unchanged on retry */ status = ((MD_REQUIRE_PERMANENT == sc->assigned->require_https)? HTTP_PERMANENT_REDIRECT : HTTP_TEMPORARY_REDIRECT); } s = ap_construct_url(r->pool, r->uri, r); if (APR_SUCCESS == apr_uri_parse(r->pool, s, &uri)) { uri.scheme = (char*)"https"; uri.port = 443; uri.port_str = (char*)"443"; uri.query = r->parsed_uri.query; uri.fragment = r->parsed_uri.fragment; s = apr_uri_unparse(r->pool, &uri, APR_URI_UNP_OMITUSERINFO); if (s && *s) { apr_table_setn(r->headers_out, "Location", s); return status; } } } } } return DECLINED; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'v1.1.12, notifycmd improvements'</s>
<s>[INST] Given the following code containing errors, provide 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 WavInFile::readHeaderBlock() { char label[5]; string sLabel; // lead label string if (fread(label, 1, 4, fptr) !=4) return -1; label[4] = 0; if (isAlphaStr(label) == 0) return -1; // not a valid label // Decode blocks according to their label if (strcmp(label, fmtStr) == 0) { int nLen, nDump; // 'fmt ' block memcpy(header.format.fmt, fmtStr, 4); // read length of the format field if (fread(&nLen, sizeof(int), 1, fptr) != 1) return -1; // swap byte order if necessary _swap32(nLen); // int format_len; header.format.format_len = nLen; // calculate how much length differs from expected nDump = nLen - ((int)sizeof(header.format) - 8); // if format_len is larger than expected, read only as much data as we've space for if (nDump > 0) { nLen = sizeof(header.format) - 8; } // read data if (fread(&(header.format.fixed), nLen, 1, fptr) != 1) return -1; // swap byte order if necessary _swap16((short &)header.format.fixed); // short int fixed; _swap16((short &)header.format.channel_number); // short int channel_number; _swap32((int &)header.format.sample_rate); // int sample_rate; _swap32((int &)header.format.byte_rate); // int byte_rate; _swap16((short &)header.format.byte_per_sample); // short int byte_per_sample; _swap16((short &)header.format.bits_per_sample); // short int bits_per_sample; // if format_len is larger than expected, skip the extra data if (nDump > 0) { fseek(fptr, nDump, SEEK_CUR); } return 0; } else if (strcmp(label, factStr) == 0) { int nLen, nDump; // 'fact' block memcpy(header.fact.fact_field, factStr, 4); // read length of the fact field if (fread(&nLen, sizeof(int), 1, fptr) != 1) return -1; // swap byte order if necessary _swap32(nLen); // int fact_len; header.fact.fact_len = nLen; // calculate how much length differs from expected nDump = nLen - ((int)sizeof(header.fact) - 8); // if format_len is larger than expected, read only as much data as we've space for if (nDump > 0) { nLen = sizeof(header.fact) - 8; } // read data if (fread(&(header.fact.fact_sample_len), nLen, 1, fptr) != 1) return -1; // swap byte order if necessary _swap32((int &)header.fact.fact_sample_len); // int sample_length; // if fact_len is larger than expected, skip the extra data if (nDump > 0) { fseek(fptr, nDump, SEEK_CUR); } return 0; } else if (strcmp(label, dataStr) == 0) { // 'data' block memcpy(header.data.data_field, dataStr, 4); if (fread(&(header.data.data_len), sizeof(uint), 1, fptr) != 1) return -1; // swap byte order if necessary _swap32((int &)header.data.data_len); return 1; } else { uint len, i; uint temp; // unknown block // read length if (fread(&len, sizeof(len), 1, fptr) != 1) return -1; // scan through the block for (i = 0; i < len; i ++) { if (fread(&temp, 1, 1, fptr) != 1) return -1; if (feof(fptr)) return -1; // unexpected eof } } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Added minimum size check for WAV header block lengh values'</s>
<s>[INST] Given the following code containing errors, provide 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 *ReadMIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define BZipMaxExtent(x) ((x)+((x)/100)+600) #define LZMAMaxExtent(x) ((x)+((x)/3)+128) #define ThrowMIFFException(exception,message) \ { \ if (quantum_info != (QuantumInfo *) NULL) \ quantum_info=DestroyQuantumInfo(quantum_info); \ if (compress_pixels != (unsigned char *) NULL) \ compress_pixels=(unsigned char *) RelinquishMagickMemory(compress_pixels); \ ThrowReaderException((exception),(message)); \ } #define ZipMaxExtent(x) ((x)+(((x)+7) >> 3)+(((x)+63) >> 6)+11) #if defined(MAGICKCORE_BZLIB_DELEGATE) bz_stream bzip_info; #endif char id[MagickPathExtent], keyword[MagickPathExtent], *options; double version; GeometryInfo geometry_info; Image *image; int c; LinkedListInfo *profiles; #if defined(MAGICKCORE_LZMA_DELEGATE) lzma_stream initialize_lzma = LZMA_STREAM_INIT, lzma_info; lzma_allocator allocator; #endif MagickBooleanType status; PixelInfo pixel; MagickStatusType flags; QuantumFormatType quantum_format; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t compress_extent, length, packet_size; ssize_t count; unsigned char *compress_pixels, *pixels; size_t colors; ssize_t y; #if defined(MAGICKCORE_ZLIB_DELEGATE) z_stream zip_info; #endif /* 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); } /* Decode image header; header terminates one character beyond a ':'. */ c=ReadBlobByte(image); if (c == EOF) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); *id='\0'; compress_pixels=(unsigned char *) NULL; quantum_info=(QuantumInfo *) NULL; (void) memset(keyword,0,sizeof(keyword)); version=0.0; (void) version; do { /* Decode image header; header terminates one character beyond a ':'. */ SetGeometryInfo(&geometry_info); length=MagickPathExtent; options=AcquireString((char *) NULL); quantum_format=UndefinedQuantumFormat; profiles=(LinkedListInfo *) NULL; colors=0; image->depth=8UL; image->compression=NoCompression; while ((isgraph(c) != MagickFalse) && (c != (int) ':')) { register char *p; if (c == (int) '{') { char *comment; /* Read comment-- any text between { }. */ length=MagickPathExtent; comment=AcquireString((char *) NULL); for (p=comment; comment != (char *) NULL; p++) { c=ReadBlobByte(image); if (c == (int) '\\') c=ReadBlobByte(image); else if ((c == EOF) || (c == (int) '}')) break; if ((size_t) (p-comment+1) >= length) { *p='\0'; length<<=1; comment=(char *) ResizeQuantumMemory(comment,length+ MagickPathExtent,sizeof(*comment)); if (comment == (char *) NULL) break; p=comment+strlen(comment); } *p=(char) c; } if (comment == (char *) NULL) { options=DestroyString(options); ThrowMIFFException(ResourceLimitError,"MemoryAllocationFailed"); } *p='\0'; (void) SetImageProperty(image,"comment",comment,exception); comment=DestroyString(comment); c=ReadBlobByte(image); } else if (isalnum(c) != MagickFalse) { /* Get the keyword. */ length=MagickPathExtent-1; p=keyword; do { if (c == (int) '=') break; if ((size_t) (p-keyword) < (MagickPathExtent-1)) *p++=(char) c; c=ReadBlobByte(image); } while (c != EOF); *p='\0'; p=options; while ((isspace((int) ((unsigned char) c)) != 0) && (c != EOF)) c=ReadBlobByte(image); if (c == (int) '=') { /* Get the keyword value. */ c=ReadBlobByte(image); while ((c != (int) '}') && (c != EOF)) { if ((size_t) (p-options+1) >= length) { *p='\0'; length<<=1; options=(char *) ResizeQuantumMemory(options,length+ MagickPathExtent,sizeof(*options)); if (options == (char *) NULL) break; p=options+strlen(options); } *p++=(char) c; c=ReadBlobByte(image); if (c == '\\') { c=ReadBlobByte(image); if (c == (int) '}') { *p++=(char) c; c=ReadBlobByte(image); } } if (*options != '{') if (isspace((int) ((unsigned char) c)) != 0) break; } if (options == (char *) NULL) ThrowMIFFException(ResourceLimitError, "MemoryAllocationFailed"); } *p='\0'; if (*options == '{') (void) CopyMagickString(options,options+1,strlen(options)); /* Assign a value to the specified keyword. */ switch (*keyword) { case 'a': case 'A': { if (LocaleCompare(keyword,"alpha-trait") == 0) { ssize_t alpha_trait; alpha_trait=ParseCommandOption(MagickPixelTraitOptions, MagickFalse,options); if (alpha_trait < 0) break; image->alpha_trait=(PixelTrait) alpha_trait; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'b': case 'B': { if (LocaleCompare(keyword,"background-color") == 0) { (void) QueryColorCompliance(options,AllCompliance, &image->background_color,exception); break; } if (LocaleCompare(keyword,"blue-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.blue_primary.x=geometry_info.rho; image->chromaticity.blue_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.blue_primary.y= image->chromaticity.blue_primary.x; break; } if (LocaleCompare(keyword,"border-color") == 0) { (void) QueryColorCompliance(options,AllCompliance, &image->border_color,exception); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'c': case 'C': { if (LocaleCompare(keyword,"class") == 0) { ssize_t storage_class; storage_class=ParseCommandOption(MagickClassOptions, MagickFalse,options); if (storage_class < 0) break; image->storage_class=(ClassType) storage_class; break; } if (LocaleCompare(keyword,"colors") == 0) { colors=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"colorspace") == 0) { ssize_t colorspace; colorspace=ParseCommandOption(MagickColorspaceOptions, MagickFalse,options); if (colorspace < 0) break; image->colorspace=(ColorspaceType) colorspace; break; } if (LocaleCompare(keyword,"compression") == 0) { ssize_t compression; compression=ParseCommandOption(MagickCompressOptions, MagickFalse,options); if (compression < 0) break; image->compression=(CompressionType) compression; break; } if (LocaleCompare(keyword,"columns") == 0) { image->columns=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'd': case 'D': { if (LocaleCompare(keyword,"delay") == 0) { image->delay=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"depth") == 0) { image->depth=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"dispose") == 0) { ssize_t dispose; dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse, options); if (dispose < 0) break; image->dispose=(DisposeType) dispose; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'e': case 'E': { if (LocaleCompare(keyword,"endian") == 0) { ssize_t endian; endian=ParseCommandOption(MagickEndianOptions,MagickFalse, options); if (endian < 0) break; image->endian=(EndianType) endian; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'g': case 'G': { if (LocaleCompare(keyword,"gamma") == 0) { image->gamma=StringToDouble(options,(char **) NULL); break; } if (LocaleCompare(keyword,"gravity") == 0) { ssize_t gravity; gravity=ParseCommandOption(MagickGravityOptions,MagickFalse, options); if (gravity < 0) break; image->gravity=(GravityType) gravity; break; } if (LocaleCompare(keyword,"green-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.green_primary.x=geometry_info.rho; image->chromaticity.green_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.green_primary.y= image->chromaticity.green_primary.x; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'i': case 'I': { if (LocaleCompare(keyword,"id") == 0) { (void) CopyMagickString(id,options,MagickPathExtent); break; } if (LocaleCompare(keyword,"iterations") == 0) { image->iterations=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'm': case 'M': { if (LocaleCompare(keyword,"matte") == 0) { ssize_t matte; matte=ParseCommandOption(MagickBooleanOptions,MagickFalse, options); if (matte < 0) break; image->alpha_trait=matte == 0 ? UndefinedPixelTrait : BlendPixelTrait; break; } if (LocaleCompare(keyword,"mattecolor") == 0) { (void) QueryColorCompliance(options,AllCompliance, &image->matte_color,exception); break; } if (LocaleCompare(keyword,"montage") == 0) { (void) CloneString(&image->montage,options); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'o': case 'O': { if (LocaleCompare(keyword,"orientation") == 0) { ssize_t orientation; orientation=ParseCommandOption(MagickOrientationOptions, MagickFalse,options); if (orientation < 0) break; image->orientation=(OrientationType) orientation; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'p': case 'P': { if (LocaleCompare(keyword,"page") == 0) { char *geometry; geometry=GetPageGeometry(options); (void) ParseAbsoluteGeometry(geometry,&image->page); geometry=DestroyString(geometry); break; } if (LocaleCompare(keyword,"pixel-intensity") == 0) { ssize_t intensity; intensity=ParseCommandOption(MagickPixelIntensityOptions, MagickFalse,options); if (intensity < 0) break; image->intensity=(PixelIntensityMethod) intensity; break; } if (LocaleCompare(keyword,"profile") == 0) { if (profiles == (LinkedListInfo *) NULL) profiles=NewLinkedList(0); (void) AppendValueToLinkedList(profiles, AcquireString(options)); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'q': case 'Q': { if (LocaleCompare(keyword,"quality") == 0) { image->quality=StringToUnsignedLong(options); break; } if ((LocaleCompare(keyword,"quantum-format") == 0) || (LocaleCompare(keyword,"quantum:format") == 0)) { ssize_t format; format=ParseCommandOption(MagickQuantumFormatOptions, MagickFalse,options); if (format < 0) break; quantum_format=(QuantumFormatType) format; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'r': case 'R': { if (LocaleCompare(keyword,"red-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.red_primary.x=geometry_info.rho; image->chromaticity.red_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.red_primary.y= image->chromaticity.red_primary.x; break; } if (LocaleCompare(keyword,"rendering-intent") == 0) { ssize_t rendering_intent; rendering_intent=ParseCommandOption(MagickIntentOptions, MagickFalse,options); if (rendering_intent < 0) break; image->rendering_intent=(RenderingIntent) rendering_intent; break; } if (LocaleCompare(keyword,"resolution") == 0) { flags=ParseGeometry(options,&geometry_info); image->resolution.x=geometry_info.rho; image->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->resolution.y=image->resolution.x; break; } if (LocaleCompare(keyword,"rows") == 0) { image->rows=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 's': case 'S': { if (LocaleCompare(keyword,"scene") == 0) { image->scene=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 't': case 'T': { if (LocaleCompare(keyword,"ticks-per-second") == 0) { image->ticks_per_second=(ssize_t) StringToLong(options); break; } if (LocaleCompare(keyword,"tile-offset") == 0) { char *geometry; geometry=GetPageGeometry(options); (void) ParseAbsoluteGeometry(geometry,&image->tile_offset); geometry=DestroyString(geometry); break; } if (LocaleCompare(keyword,"type") == 0) { ssize_t type; type=ParseCommandOption(MagickTypeOptions,MagickFalse, options); if (type < 0) break; image->type=(ImageType) type; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'u': case 'U': { if (LocaleCompare(keyword,"units") == 0) { ssize_t units; units=ParseCommandOption(MagickResolutionOptions, MagickFalse,options); if (units < 0) break; image->units=(ResolutionType) units; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'v': case 'V': { if (LocaleCompare(keyword,"version") == 0) { version=StringToDouble(options,(char **) NULL); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'w': case 'W': { if (LocaleCompare(keyword,"white-point") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.white_point.x=geometry_info.rho; image->chromaticity.white_point.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.white_point.y= image->chromaticity.white_point.x; break; } (void) SetImageProperty(image,keyword,options,exception); break; } default: { (void) SetImageProperty(image,keyword,options,exception); break; } } } else c=ReadBlobByte(image); while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } options=DestroyString(options); (void) ReadBlobByte(image); /* Verify that required image information is defined. */ if ((LocaleCompare(id,"ImageMagick") != 0) || (image->depth > 64) || (image->storage_class == UndefinedClass) || (image->compression == UndefinedCompression) || (image->colorspace == UndefinedColorspace) || (image->columns == 0) || (image->rows == 0)) { if (profiles != (LinkedListInfo *) NULL) profiles=DestroyLinkedList(profiles,RelinquishMagickMemory); if (image->previous == (Image *) NULL) ThrowMIFFException(CorruptImageError,"ImproperImageHeader"); DeleteImageFromList(&image); (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageError,"ImproperImageHeader","`%s'",image->filename); break; } if (image->montage != (char *) NULL) { register char *p; /* Image directory. */ length=MagickPathExtent; image->directory=AcquireString((char *) NULL); p=image->directory; do { *p='\0'; if ((strlen(image->directory)+MagickPathExtent) >= length) { /* Allocate more memory for the image directory. */ length<<=1; image->directory=(char *) ResizeQuantumMemory(image->directory, length+MagickPathExtent,sizeof(*image->directory)); if (image->directory == (char *) NULL) ThrowMIFFException(CorruptImageError,"UnableToReadImageData"); p=image->directory+strlen(image->directory); } c=ReadBlobByte(image); if (c == EOF) break; *p++=(char) c; } while (c != (int) '\0'); } if (profiles != (LinkedListInfo *) NULL) { const char *name; StringInfo *profile; /* Read image profiles. */ ResetLinkedListIterator(profiles); name=(const char *) GetNextValueInLinkedList(profiles); while (name != (const char *) NULL) { length=ReadBlobMSBLong(image); if ((MagickSizeType) length > GetBlobSize(image)) break; profile=AcquireStringInfo(length); if (profile == (StringInfo *) NULL) break; count=ReadBlob(image,length,GetStringInfoDatum(profile)); if (count != (ssize_t) length) { profile=DestroyStringInfo(profile); break; } status=SetImageProfile(image,name,profile,exception); profile=DestroyStringInfo(profile); if (status == MagickFalse) break; name=(const char *) GetNextValueInLinkedList(profiles); } profiles=DestroyLinkedList(profiles,RelinquishMagickMemory); } image->depth=GetImageQuantumDepth(image,MagickFalse); if (image->storage_class == PseudoClass) { unsigned char *colormap; /* Create image colormap. */ packet_size=(size_t) (3UL*image->depth/8UL); if ((MagickSizeType) colors > GetBlobSize(image)) ThrowMIFFException(CorruptImageError,"InsufficientImageDataInFile"); if (((MagickSizeType) packet_size*colors) > GetBlobSize(image)) ThrowMIFFException(CorruptImageError,"InsufficientImageDataInFile"); status=AcquireImageColormap(image,colors != 0 ? colors : 256,exception); if (status == MagickFalse) ThrowMIFFException(ResourceLimitError,"MemoryAllocationFailed"); if (colors != 0) { const unsigned char *p; /* Read image colormap from file. */ colormap=(unsigned char *) AcquireQuantumMemory(image->colors, packet_size*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowMIFFException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,packet_size*image->colors,colormap); p=colormap; switch (image->depth) { default: colormap=(unsigned char *) RelinquishMagickMemory(colormap); ThrowMIFFException(CorruptImageError,"ImageDepthNotSupported"); case 8: { unsigned char char_pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushCharPixel(p,&char_pixel); image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(char_pixel); p=PushCharPixel(p,&char_pixel); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(char_pixel); p=PushCharPixel(p,&char_pixel); image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(char_pixel); } break; } case 16: { unsigned short short_pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushShortPixel(MSBEndian,p,&short_pixel); image->colormap[i].red=(MagickRealType) ScaleShortToQuantum(short_pixel); p=PushShortPixel(MSBEndian,p,&short_pixel); image->colormap[i].green=(MagickRealType) ScaleShortToQuantum(short_pixel); p=PushShortPixel(MSBEndian,p,&short_pixel); image->colormap[i].blue=(MagickRealType) ScaleShortToQuantum(short_pixel); } break; } case 32: { unsigned int long_pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushLongPixel(MSBEndian,p,&long_pixel); image->colormap[i].red=(MagickRealType) ScaleLongToQuantum(long_pixel); p=PushLongPixel(MSBEndian,p,&long_pixel); image->colormap[i].green=(MagickRealType) ScaleLongToQuantum(long_pixel); p=PushLongPixel(MSBEndian,p,&long_pixel); image->colormap[i].blue=(MagickRealType) ScaleLongToQuantum(long_pixel); } break; } } colormap=(unsigned char *) RelinquishMagickMemory(colormap); } } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); status=ResetImagePixels(image,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Allocate image pixels. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowMIFFException(ResourceLimitError,"MemoryAllocationFailed"); if (quantum_format != UndefinedQuantumFormat) { status=SetQuantumFormat(image,quantum_info,quantum_format); if (status == MagickFalse) ThrowMIFFException(ResourceLimitError,"MemoryAllocationFailed"); } packet_size=(size_t) (quantum_info->depth/8); if (image->storage_class == DirectClass) packet_size=(size_t) (3*quantum_info->depth/8); if (IsGrayColorspace(image->colorspace) != MagickFalse) packet_size=quantum_info->depth/8; if (image->alpha_trait != UndefinedPixelTrait) packet_size+=quantum_info->depth/8; if (image->colorspace == CMYKColorspace) packet_size+=quantum_info->depth/8; if (image->compression == RLECompression) packet_size++; compress_extent=MagickMax(MagickMax(BZipMaxExtent(packet_size* image->columns),LZMAMaxExtent(packet_size*image->columns)), ZipMaxExtent(packet_size*image->columns)); compress_pixels=(unsigned char *) AcquireQuantumMemory(compress_extent, sizeof(*compress_pixels)); if (compress_pixels == (unsigned char *) NULL) ThrowMIFFException(ResourceLimitError,"MemoryAllocationFailed"); /* Read image pixels. */ quantum_type=RGBQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=RGBAQuantum; if (image->colorspace == CMYKColorspace) { quantum_type=CMYKQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=CMYKAQuantum; } if (IsGrayColorspace(image->colorspace) != MagickFalse) { quantum_type=GrayQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=GrayAlphaQuantum; } if (image->storage_class == PseudoClass) { quantum_type=IndexQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=IndexAlphaQuantum; } status=MagickTrue; GetPixelInfo(image,&pixel); #if defined(MAGICKCORE_BZLIB_DELEGATE) (void) memset(&bzip_info,0,sizeof(bzip_info)); #endif #if defined(MAGICKCORE_LZMA_DELEGATE) (void) memset(&allocator,0,sizeof(allocator)); #endif #if defined(MAGICKCORE_ZLIB_DELEGATE) (void) memset(&zip_info,0,sizeof(zip_info)); #endif switch (image->compression) { #if defined(MAGICKCORE_BZLIB_DELEGATE) case BZipCompression: { int code; bzip_info.bzalloc=AcquireBZIPMemory; bzip_info.bzfree=RelinquishBZIPMemory; bzip_info.opaque=(void *) image; code=BZ2_bzDecompressInit(&bzip_info,(int) image_info->verbose, MagickFalse); if (code != BZ_OK) status=MagickFalse; break; } #endif #if defined(MAGICKCORE_LZMA_DELEGATE) case LZMACompression: { int code; allocator.alloc=AcquireLZMAMemory; allocator.free=RelinquishLZMAMemory; allocator.opaque=(void *) image; lzma_info=initialize_lzma; lzma_info.allocator=(&allocator); code=lzma_auto_decoder(&lzma_info,(uint64_t) -1,0); if (code != LZMA_OK) status=MagickFalse; break; } #endif #if defined(MAGICKCORE_ZLIB_DELEGATE) case LZWCompression: case ZipCompression: { int code; zip_info.zalloc=AcquireZIPMemory; zip_info.zfree=RelinquishZIPMemory; zip_info.opaque=(voidpf) image; code=inflateInit(&zip_info); if (code != Z_OK) status=MagickFalse; break; } #endif case RLECompression: break; default: break; } pixels=(unsigned char *) GetQuantumPixels(quantum_info); length=0; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; switch (image->compression) { #if defined(MAGICKCORE_BZLIB_DELEGATE) case BZipCompression: { bzip_info.next_out=(char *) pixels; bzip_info.avail_out=(unsigned int) (packet_size*image->columns); do { int code; if (bzip_info.avail_in == 0) { bzip_info.next_in=(char *) compress_pixels; length=(size_t) BZipMaxExtent(packet_size*image->columns); if (version != 0.0) length=(size_t) ReadBlobMSBLong(image); if (length <= compress_extent) bzip_info.avail_in=(unsigned int) ReadBlob(image,length, (unsigned char *) bzip_info.next_in); if ((length > compress_extent) || ((size_t) bzip_info.avail_in != length)) { (void) BZ2_bzDecompressEnd(&bzip_info); ThrowMIFFException(CorruptImageError, "UnableToReadImageData"); } } code=BZ2_bzDecompress(&bzip_info); if ((code != BZ_OK) && (code != BZ_STREAM_END)) { status=MagickFalse; break; } if (code == BZ_STREAM_END) break; } while (bzip_info.avail_out != 0); (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } #endif #if defined(MAGICKCORE_LZMA_DELEGATE) case LZMACompression: { lzma_info.next_out=pixels; lzma_info.avail_out=packet_size*image->columns; do { int code; if (lzma_info.avail_in == 0) { lzma_info.next_in=compress_pixels; length=(size_t) ReadBlobMSBLong(image); if (length <= compress_extent) lzma_info.avail_in=(unsigned int) ReadBlob(image,length, (unsigned char *) lzma_info.next_in); if ((length > compress_extent) || (lzma_info.avail_in != length)) { lzma_end(&lzma_info); ThrowMIFFException(CorruptImageError, "UnableToReadImageData"); } } code=lzma_code(&lzma_info,LZMA_RUN); if ((code != LZMA_OK) && (code != LZMA_STREAM_END)) { status=MagickFalse; break; } if (code == LZMA_STREAM_END) break; } while (lzma_info.avail_out != 0); (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } #endif #if defined(MAGICKCORE_ZLIB_DELEGATE) case LZWCompression: case ZipCompression: { zip_info.next_out=pixels; zip_info.avail_out=(uInt) (packet_size*image->columns); do { int code; if (zip_info.avail_in == 0) { zip_info.next_in=compress_pixels; length=(size_t) ZipMaxExtent(packet_size*image->columns); if (version != 0.0) length=(size_t) ReadBlobMSBLong(image); if (length <= compress_extent) zip_info.avail_in=(unsigned int) ReadBlob(image,length, zip_info.next_in); if ((length > compress_extent) || ((size_t) zip_info.avail_in != length)) { (void) inflateEnd(&zip_info); ThrowMIFFException(CorruptImageError, "UnableToReadImageData"); } } code=inflate(&zip_info,Z_SYNC_FLUSH); if ((code != Z_OK) && (code != Z_STREAM_END)) { status=MagickFalse; break; } if (code == Z_STREAM_END) break; } while (zip_info.avail_out != 0); (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } #endif case RLECompression: { for (x=0; x < (ssize_t) image->columns; x++) { if (length == 0) { count=ReadBlob(image,packet_size,pixels); if (count != (ssize_t) packet_size) ThrowMIFFException(CorruptImageError,"UnableToReadImageData"); PushRunlengthPacket(image,pixels,&length,&pixel,exception); } length--; if (image->storage_class == PseudoClass) SetPixelIndex(image,ClampToQuantum(pixel.index),q); else { SetPixelRed(image,ClampToQuantum(pixel.red),q); SetPixelGreen(image,ClampToQuantum(pixel.green),q); SetPixelBlue(image,ClampToQuantum(pixel.blue),q); if (image->colorspace == CMYKColorspace) SetPixelBlack(image,ClampToQuantum(pixel.black),q); } if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); q+=GetPixelChannels(image); } break; } default: { count=ReadBlob(image,packet_size*image->columns,pixels); if (count != (ssize_t) (packet_size*image->columns)) ThrowMIFFException(CorruptImageError,"UnableToReadImageData"); (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } SetQuantumImageType(image,quantum_type); switch (image->compression) { #if defined(MAGICKCORE_BZLIB_DELEGATE) case BZipCompression: { int code; if (version == 0.0) { MagickOffsetType offset; offset=SeekBlob(image,-((MagickOffsetType) bzip_info.avail_in), SEEK_CUR); if (offset < 0) { (void) BZ2_bzDecompressEnd(&bzip_info); ThrowMIFFException(CorruptImageError,"ImproperImageHeader"); } } code=BZ2_bzDecompressEnd(&bzip_info); if (code != BZ_OK) status=MagickFalse; break; } #endif #if defined(MAGICKCORE_LZMA_DELEGATE) case LZMACompression: { int code; code=lzma_code(&lzma_info,LZMA_FINISH); if ((code != LZMA_STREAM_END) && (code != LZMA_OK)) status=MagickFalse; lzma_end(&lzma_info); break; } #endif #if defined(MAGICKCORE_ZLIB_DELEGATE) case LZWCompression: case ZipCompression: { int code; if (version == 0.0) { MagickOffsetType offset; offset=SeekBlob(image,-((MagickOffsetType) zip_info.avail_in), SEEK_CUR); if (offset < 0) { (void) inflateEnd(&zip_info); ThrowMIFFException(CorruptImageError,"ImproperImageHeader"); } } code=inflateEnd(&zip_info); if (code != Z_OK) status=MagickFalse; break; } #endif default: break; } quantum_info=DestroyQuantumInfo(quantum_info); compress_pixels=(unsigned char *) RelinquishMagickMemory(compress_pixels); if (((y != (ssize_t) image->rows)) || (status == MagickFalse)) { image=DestroyImageList(image); return((Image *) NULL); } 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; do { c=ReadBlobByte(image); } while ((isgraph(c) == MagickFalse) && (c != EOF)); if (c != EOF) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (c != EOF); (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-772'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1191'</s>
<s>[INST] Given the following code containing errors, provide 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 kwajd_read_headers(struct mspack_system *sys, struct mspack_file *fh, struct mskwajd_header *hdr) { unsigned char buf[16]; int i; /* read in the header */ if (sys->read(fh, &buf[0], kwajh_SIZEOF) != kwajh_SIZEOF) { return MSPACK_ERR_READ; } /* check for "KWAJ" signature */ if (((unsigned int) EndGetI32(&buf[kwajh_Signature1]) != 0x4A41574B) || ((unsigned int) EndGetI32(&buf[kwajh_Signature2]) != 0xD127F088)) { return MSPACK_ERR_SIGNATURE; } /* basic header fields */ hdr->comp_type = EndGetI16(&buf[kwajh_CompMethod]); hdr->data_offset = EndGetI16(&buf[kwajh_DataOffset]); hdr->headers = EndGetI16(&buf[kwajh_Flags]); hdr->length = 0; hdr->filename = NULL; hdr->extra = NULL; hdr->extra_length = 0; /* optional headers */ /* 4 bytes: length of unpacked file */ if (hdr->headers & MSKWAJ_HDR_HASLENGTH) { if (sys->read(fh, &buf[0], 4) != 4) return MSPACK_ERR_READ; hdr->length = EndGetI32(&buf[0]); } /* 2 bytes: unknown purpose */ if (hdr->headers & MSKWAJ_HDR_HASUNKNOWN1) { if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ; } /* 2 bytes: length of section, then [length] bytes: unknown purpose */ if (hdr->headers & MSKWAJ_HDR_HASUNKNOWN2) { if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ; i = EndGetI16(&buf[0]); if (sys->seek(fh, (off_t)i, MSPACK_SYS_SEEK_CUR)) return MSPACK_ERR_SEEK; } /* filename and extension */ if (hdr->headers & (MSKWAJ_HDR_HASFILENAME | MSKWAJ_HDR_HASFILEEXT)) { off_t pos = sys->tell(fh); char *fn = (char *) sys->alloc(sys, (size_t) 13); /* allocate memory for maximum length filename */ if (! fn) return MSPACK_ERR_NOMEMORY; hdr->filename = fn; /* copy filename if present */ if (hdr->headers & MSKWAJ_HDR_HASFILENAME) { if (sys->read(fh, &buf[0], 9) != 9) return MSPACK_ERR_READ; for (i = 0; i < 9; i++, fn++) if (!(*fn = buf[i])) break; pos += (i < 9) ? i+1 : 9; if (sys->seek(fh, pos, MSPACK_SYS_SEEK_START)) return MSPACK_ERR_SEEK; } /* copy extension if present */ if (hdr->headers & MSKWAJ_HDR_HASFILEEXT) { *fn++ = '.'; if (sys->read(fh, &buf[0], 4) != 4) return MSPACK_ERR_READ; for (i = 0; i < 4; i++, fn++) if (!(*fn = buf[i])) break; pos += (i < 4) ? i+1 : 4; if (sys->seek(fh, pos, MSPACK_SYS_SEEK_START)) return MSPACK_ERR_SEEK; } *fn = '\0'; } /* 2 bytes: extra text length then [length] bytes of extra text data */ if (hdr->headers & MSKWAJ_HDR_HASEXTRATEXT) { if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ; i = EndGetI16(&buf[0]); hdr->extra = (char *) sys->alloc(sys, (size_t)i+1); if (! hdr->extra) return MSPACK_ERR_NOMEMORY; if (sys->read(fh, hdr->extra, i) != i) return MSPACK_ERR_READ; hdr->extra[i] = '\0'; hdr->extra_length = i; } return MSPACK_ERR_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310', 'CWE-787'], 'message': 'kwaj_read_headers(): fix handling of non-terminated strings'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: plain(void) { test(PTR1_ZEROES PTR1_STR " " PTR2_STR, "%p %p", PTR1, PTR2); /* * The field width is overloaded for some %p extensions to * pass another piece of information. For plain pointers, the * behaviour is slightly odd: One cannot pass either the 0 * flag nor a precision to %p without gcc complaining, and if * one explicitly gives a field width, the number is no longer * zero-padded. */ test("|" PTR1_STR PTR1_SPACES " | " PTR1_SPACES PTR1_STR "|", "|%-*p|%*p|", PTR_WIDTH+2, PTR1, PTR_WIDTH+2, PTR1); test("|" PTR2_STR " | " PTR2_STR "|", "|%-*p|%*p|", PTR_WIDTH+2, PTR2, PTR_WIDTH+2, PTR2); /* * Unrecognized %p extensions are treated as plain %p, but the * alphanumeric suffix is ignored (that is, does not occur in * the output.) */ test("|"PTR1_ZEROES PTR1_STR"|", "|%p0y|", PTR1); test("|"PTR2_STR"|", "|%p0y|", PTR2); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'printk: hash addresses printed with %p Currently there exist approximately 14 000 places in the kernel where addresses are being printed using an unadorned %p. This potentially leaks sensitive information regarding the Kernel layout in memory. Many of these calls are stale, instead of fixing every call lets hash the address by default before printing. This will of course break some users, forcing code printing needed addresses to be updated. Code that _really_ needs the address will soon be able to use the new printk specifier %px to print the address. For what it's worth, usage of unadorned %p can be broken down as follows (thanks to Joe Perches). $ git grep -E '%p[^A-Za-z0-9]' | cut -f1 -d"/" | sort | uniq -c 1084 arch 20 block 10 crypto 32 Documentation 8121 drivers 1221 fs 143 include 101 kernel 69 lib 100 mm 1510 net 40 samples 7 scripts 11 security 166 sound 152 tools 2 virt Add function ptr_to_id() to map an address to a 32 bit unique identifier. Hash any unadorned usage of specifier %p and any malformed specifiers. Signed-off-by: Tobin C. Harding <me@tobin.cc>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: CompileKeymap(XkbFile *file, struct xkb_keymap *keymap, enum merge_mode merge) { bool ok; XkbFile *files[LAST_KEYMAP_FILE_TYPE + 1] = { NULL }; enum xkb_file_type type; struct xkb_context *ctx = keymap->ctx; /* Collect section files and check for duplicates. */ for (file = (XkbFile *) file->defs; file; file = (XkbFile *) file->common.next) { if (file->file_type < FIRST_KEYMAP_FILE_TYPE || file->file_type > LAST_KEYMAP_FILE_TYPE) { log_err(ctx, "Cannot define %s in a keymap file\n", xkb_file_type_to_string(file->file_type)); continue; } if (files[file->file_type]) { log_err(ctx, "More than one %s section in keymap file; " "All sections after the first ignored\n", xkb_file_type_to_string(file->file_type)); continue; } files[file->file_type] = file; } /* * Check that all required section were provided. * Report everything before failing. */ ok = true; for (type = FIRST_KEYMAP_FILE_TYPE; type <= LAST_KEYMAP_FILE_TYPE; type++) { if (files[type] == NULL) { log_err(ctx, "Required section %s missing from keymap\n", xkb_file_type_to_string(type)); ok = false; } } if (!ok) return false; /* Compile sections. */ for (type = FIRST_KEYMAP_FILE_TYPE; type <= LAST_KEYMAP_FILE_TYPE; type++) { log_dbg(ctx, "Compiling %s \"%s\"\n", xkb_file_type_to_string(type), files[type]->name); ok = compile_file_fns[type](files[type], keymap, merge); if (!ok) { log_err(ctx, "Failed to compile %s\n", xkb_file_type_to_string(type)); return false; } } return UpdateDerivedKeymapFields(keymap); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'xkbcomp: fix crash when parsing an xkb_geometry section xkb_geometry sections are ignored; previously the had done so by returning NULL for the section's XkbFile, however some sections of the code do not expect this. Instead, create an XkbFile for it, it will never be processes and discarded later. Caught with the afl fuzzer. Signed-off-by: Ran Benita <ran234@gmail.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 inline void CheckEventLogging() { /* Are we logging events? */ if (IsLinkedListEmpty(log_cache) != MagickFalse) event_logging=MagickFalse; else { LogInfo *p; ResetLinkedListIterator(log_cache); p=(LogInfo *) GetNextValueInLinkedList(log_cache); event_logging=p->event_mask != NoEvents ? MagickTrue: MagickFalse; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1224'</s>
<s>[INST] Given the following code containing errors, provide 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 *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { Image *alpha_image, *color_image, *image, *jng_image; ImageInfo *alpha_image_info, *color_image_info; MagickBooleanType logging; ssize_t y; MagickBooleanType status; png_uint_32 jng_height, jng_width; png_byte jng_color_type, jng_image_sample_depth, jng_image_compression_method, jng_image_interlace_method, jng_alpha_sample_depth, jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method; register const Quantum *s; register ssize_t i, x; register Quantum *q; register unsigned char *p; unsigned int read_JSEP, reading_idat; size_t length; jng_alpha_compression_method=0; jng_alpha_sample_depth=8; jng_color_type=0; jng_height=0; jng_width=0; alpha_image=(Image *) NULL; color_image=(Image *) NULL; alpha_image_info=(ImageInfo *) NULL; color_image_info=(ImageInfo *) NULL; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneJNGImage()"); image=mng_info->image; if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireNextImage()"); AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; /* Signature bytes have already been read. */ read_JSEP=MagickFalse; reading_idat=MagickFalse; for (;;) { char type[MagickPathExtent]; unsigned char *chunk; unsigned int count; /* Read a new JNG chunk. */ status=SetImageProgress(image,LoadImagesTag,TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) break; type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MagickPathExtent); length=(size_t) ReadBlobMSBLong(image); count=(unsigned int) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading JNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX || count == 0) { DestroyJNG(NULL,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (length > GetBlobSize(image)) { DestroyJNG(NULL,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } for ( ; i < (ssize_t) length; i++) chunk[i]='\0'; p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ if (memcmp(type,mng_JHDR,4) == 0) { if (length == 16) { jng_width=(png_uint_32)mng_get_long(p); jng_height=(png_uint_32)mng_get_long(&p[4]); if ((jng_width == 0) || (jng_height == 0)) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(CorruptImageError, "NegativeOrZeroImageSize"); } jng_color_type=p[8]; jng_image_sample_depth=p[9]; jng_image_compression_method=p[10]; jng_image_interlace_method=p[11]; image->interlace=jng_image_interlace_method != 0 ? PNGInterlace : NoInterlace; jng_alpha_sample_depth=p[12]; jng_alpha_compression_method=p[13]; jng_alpha_filter_method=p[14]; jng_alpha_interlace_method=p[15]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_width: %16lu, jng_height: %16lu\n" " jng_color_type: %16d, jng_image_sample_depth: %3d\n" " jng_image_compression_method:%3d", (unsigned long) jng_width, (unsigned long) jng_height, jng_color_type, jng_image_sample_depth, jng_image_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_image_interlace_method: %3d" " jng_alpha_sample_depth: %3d", jng_image_interlace_method, jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_alpha_compression_method:%3d\n" " jng_alpha_filter_method: %3d\n" " jng_alpha_interlace_method: %3d", jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method); } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (jng_width > 65535 || jng_height > 65535 || (long) jng_width > GetMagickResourceLimit(WidthResource) || (long) jng_height > GetMagickResourceLimit(HeightResource)) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG width or height too large: (%lu x %lu)", (long) jng_width, (long) jng_height); DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } continue; } if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) && ((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) || (memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0))) { /* o create color_image o open color_blob, attached to color_image o if (color type has alpha) open alpha_blob, attached to alpha_image */ color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo)); if (color_image_info == (ImageInfo *) NULL) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } GetImageInfo(color_image_info); color_image=AcquireImage(color_image_info,exception); if (color_image == (Image *) NULL) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating color_blob."); (void) AcquireUniqueFilename(color_image->filename); status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); return(DestroyImageList(image)); } if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) { alpha_image_info=(ImageInfo *) AcquireMagickMemory(sizeof(ImageInfo)); if (alpha_image_info == (ImageInfo *) NULL) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } GetImageInfo(alpha_image_info); alpha_image=AcquireImage(alpha_image_info,exception); if (alpha_image == (Image *) NULL) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating alpha_blob."); (void) AcquireUniqueFilename(alpha_image->filename); status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); return(DestroyImageList(image)); } if (jng_alpha_compression_method == 0) { unsigned char data[18]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing IHDR chunk to alpha_blob."); (void) WriteBlob(alpha_image,8,(const unsigned char *) "\211PNG\r\n\032\n"); (void) WriteBlobMSBULong(alpha_image,13L); PNGType(data,mng_IHDR); LogPNGChunk(logging,mng_IHDR,13L); PNGLong(data+4,jng_width); PNGLong(data+8,jng_height); data[12]=jng_alpha_sample_depth; data[13]=0; /* color_type gray */ data[14]=0; /* compression method 0 */ data[15]=0; /* filter_method 0 */ data[16]=0; /* interlace_method 0 */ (void) WriteBlob(alpha_image,17,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,17)); } } reading_idat=MagickTrue; } if (memcmp(type,mng_JDAT,4) == 0) { /* Copy chunk to color_image->blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAT chunk data to color_blob."); if ((length != 0) && (color_image != (Image *) NULL)) (void) WriteBlob(color_image,length,chunk); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IDAT,4) == 0) { png_byte data[5]; /* Copy IDAT header and chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying IDAT chunk data to alpha_blob."); (void) WriteBlobMSBULong(alpha_image,(size_t) length); PNGType(data,mng_IDAT); LogPNGChunk(logging,mng_IDAT,length); (void) WriteBlob(alpha_image,4,data); (void) WriteBlob(alpha_image,length,chunk); (void) WriteBlobMSBULong(alpha_image, crc32(crc32(0,data,4),chunk,(uInt) length)); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0)) { /* Copy chunk data to alpha_image->blob */ if ((alpha_image != NULL) && (image_info->ping == MagickFalse) && (length != 0)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAA chunk data to alpha_blob."); (void) WriteBlob(alpha_image,length,chunk); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_JSEP,4) == 0) { read_JSEP=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { if (length == 2) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=image->background_color.red; image->background_color.blue=image->background_color.red; } if (length == 6) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=ScaleCharToQuantum(p[3]); image->background_color.blue=ScaleCharToQuantum(p[5]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) image->gamma=((float) mng_get_long(p))*0.00001; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { if (length == 32) { image->chromaticity.white_point.x=0.00001*mng_get_long(p); image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]); image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]); image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]); image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]); image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]); image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]); image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { if (length == 1) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); image->gamma=1.000f/2.200f; image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_oFFs,4) == 0) { if (length > 8) { image->page.x=(ssize_t) mng_get_long(p); image->page.y=(ssize_t) mng_get_long(&p[4]); if ((int) p[8] != 0) { image->page.x/=10000; image->page.y/=10000; } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { image->resolution.x=(double) mng_get_long(p); image->resolution.y=(double) mng_get_long(&p[4]); if ((int) p[8] == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->resolution.x=image->resolution.x/100.0f; image->resolution.y=image->resolution.y/100.0f; } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if 0 if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (memcmp(type,mng_IEND,4)) continue; break; } /* IEND found */ /* Finish up reading image data: o read main image from color_blob. o close color_blob. o if (color_type has alpha) if alpha_encoding is PNG read secondary image from alpha_blob via ReadPNG if alpha_encoding is JPEG read secondary image from alpha_blob via ReadJPEG o close alpha_blob. o copy intensity of secondary image into alpha samples of main image. o destroy the secondary image. */ if (color_image_info == (ImageInfo *) NULL) { assert(color_image == (Image *) NULL); assert(alpha_image == (Image *) NULL); if (color_image != (Image *) NULL) color_image=DestroyImageList(color_image); return(DestroyImageList(image)); } if (color_image == (Image *) NULL) { assert(alpha_image == (Image *) NULL); ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); } (void) SeekBlob(color_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading jng_image from color_blob."); assert(color_image_info != (ImageInfo *) NULL); (void) FormatLocaleString(color_image_info->filename,MagickPathExtent, "jpeg:%s",color_image->filename); color_image_info->ping=MagickFalse; /* To do: avoid this */ jng_image=ReadImage(color_image_info,exception); (void) RelinquishUniqueFileResource(color_image->filename); color_image=DestroyImage(color_image); color_image_info=DestroyImageInfo(color_image_info); if (jng_image == (Image *) NULL) { DestroyJNG(NULL,NULL,NULL,&alpha_image,&alpha_image_info); return(DestroyImageList(image)); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying jng_image pixels to main image."); image->rows=jng_height; image->columns=jng_width; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { DestroyJNG(NULL,&color_image,&color_image_info,&alpha_image, &alpha_image_info); jng_image=DestroyImageList(jng_image); return(DestroyImageList(image)); } if ((image->columns != jng_image->columns) || (image->rows != jng_image->rows)) { DestroyJNG(NULL,&color_image,&color_image_info,&alpha_image, &alpha_image_info); jng_image=DestroyImageList(jng_image); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1,exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if ((s == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=(ssize_t) image->columns; x != 0; x--) { SetPixelRed(image,GetPixelRed(jng_image,s),q); SetPixelGreen(image,GetPixelGreen(jng_image,s),q); SetPixelBlue(image,GetPixelBlue(jng_image,s),q); q+=GetPixelChannels(image); s+=GetPixelChannels(jng_image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } jng_image=DestroyImage(jng_image); if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) { if (jng_alpha_compression_method == 0) { png_byte data[5]; (void) WriteBlobMSBULong(alpha_image,0x00000000L); PNGType(data,mng_IEND); LogPNGChunk(logging,mng_IEND,0L); (void) WriteBlob(alpha_image,4,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,4)); } (void) CloseBlob(alpha_image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading alpha from alpha_blob."); (void) FormatLocaleString(alpha_image_info->filename,MagickPathExtent, "%s",alpha_image->filename); jng_image=ReadImage(alpha_image_info,exception); if (jng_image != (Image *) NULL) for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1,exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if ((s == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; if (image->alpha_trait != UndefinedPixelTrait) for (x=(ssize_t) image->columns; x != 0; x--) { SetPixelAlpha(image,GetPixelRed(jng_image,s),q); q+=GetPixelChannels(image); s+=GetPixelChannels(jng_image); } else for (x=(ssize_t) image->columns; x != 0; x--) { SetPixelAlpha(image,GetPixelRed(jng_image,s),q); if (GetPixelAlpha(image,q) != OpaqueAlpha) image->alpha_trait=BlendPixelTrait; q+=GetPixelChannels(image); s+=GetPixelChannels(jng_image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } (void) RelinquishUniqueFileResource(alpha_image->filename); alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); if (jng_image != (Image *) NULL) jng_image=DestroyImage(jng_image); } /* Read the JNG image. */ if (mng_info->mng_type == 0) { mng_info->mng_width=jng_width; mng_info->mng_height=jng_height; } if (image->page.width == 0 && image->page.height == 0) { image->page.width=jng_width; image->page.height=jng_height; } if (image->page.x == 0 && image->page.y == 0) { image->page.x=mng_info->x_off[mng_info->object_id]; image->page.y=mng_info->y_off[mng_info->object_id]; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } mng_info->image_found++; status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneJNGImage()"); return(image); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-772'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1201'</s>
<s>[INST] Given the following code containing errors, provide 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 *ReadPWPImage(const ImageInfo *image_info,ExceptionInfo *exception) { char filename[MaxTextExtent]; FILE *file; Image *image, *next_image, *pwp_image; ImageInfo *read_info; int c, unique_file; MagickBooleanType status; register Image *p; register ssize_t i; size_t filesize, length; ssize_t count; unsigned char magick[MaxTextExtent]; /* 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=DestroyImage(image); return((Image *) NULL); } pwp_image=image; memset(magick,0,sizeof(magick)); count=ReadBlob(pwp_image,5,magick); if ((count != 5) || (LocaleNCompare((char *) magick,"SFW95",5) != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); read_info=CloneImageInfo(image_info); (void) SetImageInfoProgressMonitor(read_info,(MagickProgressMonitor) NULL, (void *) NULL); SetImageInfoBlob(read_info,(void *) NULL,0); unique_file=AcquireUniqueFileResource(filename); (void) FormatLocaleString(read_info->filename,MagickPathExtent,"sfw:%s", filename); for ( ; ; ) { (void) memset(magick,0,sizeof(magick)); for (c=ReadBlobByte(pwp_image); c != EOF; c=ReadBlobByte(pwp_image)) { for (i=0; i < 17; i++) magick[i]=magick[i+1]; magick[17]=(unsigned char) c; if (LocaleNCompare((char *) (magick+12),"SFW94A",6) == 0) break; } if (c == EOF) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } if (LocaleNCompare((char *) (magick+12),"SFW94A",6) != 0) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } /* Dump SFW image to a temporary file. */ file=(FILE *) NULL; if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowFileException(exception,FileOpenError,"UnableToWriteFile", image->filename); image=DestroyImageList(image); return((Image *) NULL); } length=fwrite("SFW94A",1,6,file); (void) length; filesize=65535UL*magick[2]+256L*magick[1]+magick[0]; for (i=0; i < (ssize_t) filesize; i++) { c=ReadBlobByte(pwp_image); if (c == EOF) break; (void) fputc(c,file); } (void) fclose(file); if (c == EOF) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } next_image=ReadImage(read_info,exception); if (next_image == (Image *) NULL) break; (void) FormatLocaleString(next_image->filename,MaxTextExtent, "slide_%02ld.sfw",(long) next_image->scene); if (image == (Image *) NULL) image=next_image; else { /* Link image into image list. */ for (p=image; p->next != (Image *) NULL; p=GetNextImageInList(p)) ; next_image->previous=p; next_image->scene=p->scene+1; p->next=next_image; } if (image_info->number_scenes != 0) if (next_image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageProgress(image,LoadImagesTag,TellBlob(pwp_image), GetBlobSize(pwp_image)); if (status == MagickFalse) break; } if (unique_file != -1) (void) close(unique_file); (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); if (image != (Image *) NULL) { if (EOFBlob(image) != MagickFalse) { char *message; message=GetExceptionMessage(errno); (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageError,"UnexpectedEndOfFile","`%s': %s",image->filename, message); message=DestroyString(message); } (void) CloseBlob(image); } return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-252'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1199'</s>
<s>[INST] Given the following code containing errors, provide 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 formatIPTC(Image *ifile, Image *ofile) { char temp[MaxTextExtent]; unsigned int foundiptc, tagsfound; unsigned char recnum, dataset; unsigned char *readable, *str; ssize_t tagindx, taglen; int i, tagcount = (int) (sizeof(tags) / sizeof(tag_spec)); int c; foundiptc = 0; /* found the IPTC-Header */ tagsfound = 0; /* number of tags found */ c = ReadBlobByte(ifile); while (c != EOF) { if (c == 0x1c) foundiptc=1; else { if (foundiptc) return(-1); else { c=0; continue; } } /* we found the 0x1c tag and now grab the dataset and record number tags */ c = ReadBlobByte(ifile); if (c == EOF) return(-1); dataset = (unsigned char) c; c = ReadBlobByte(ifile); if (c == EOF) return(-1); recnum = (unsigned char) c; /* try to match this record to one of the ones in our named table */ for (i=0; i< tagcount; i++) { if (tags[i].id == (short) recnum) break; } if (i < tagcount) readable = (unsigned char *) tags[i].name; else readable = (unsigned char *) ""; /* We decode the length of the block that follows - ssize_t or short fmt. */ c=ReadBlobByte(ifile); if (c == EOF) return(-1); if (c & (unsigned char) 0x80) return(0); else { int c0; c0=ReadBlobByte(ifile); if (c0 == EOF) return(-1); taglen = (c << 8) | c0; } if (taglen < 0) return(-1); /* make a buffer to hold the tag datand snag it from the input stream */ str=(unsigned char *) AcquireQuantumMemory((size_t) (taglen+MaxTextExtent), sizeof(*str)); if (str == (unsigned char *) NULL) return(0); for (tagindx=0; tagindx<taglen; tagindx++) { c=ReadBlobByte(ifile); if (c == EOF) { str=(unsigned char *) RelinquishMagickMemory(str); return(-1); } str[tagindx] = (unsigned char) c; } str[taglen] = 0; /* now finish up by formatting this binary data into ASCII equivalent */ if (strlen((char *)readable) > 0) (void) FormatLocaleString(temp,MaxTextExtent,"%d#%d#%s=", (unsigned int) dataset, (unsigned int) recnum, readable); else (void) FormatLocaleString(temp,MaxTextExtent,"%d#%d=", (unsigned int) dataset,(unsigned int) recnum); (void) WriteBlobString(ofile,temp); formatString( ofile, (char *)str, taglen ); str=(unsigned char *) RelinquishMagickMemory(str); tagsfound++; c=ReadBlobByte(ifile); } return((int) tagsfound); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-772'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1118'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int read_private_key(RSA *rsa) { int r; sc_path_t path; sc_file_t *file; const sc_acl_entry_t *e; u8 buf[2048], *p = buf; size_t bufsize, keysize; r = select_app_df(); if (r) return 1; sc_format_path("I0012", &path); r = sc_select_file(card, &path, &file); if (r) { fprintf(stderr, "Unable to select private key file: %s\n", sc_strerror(r)); return 2; } e = sc_file_get_acl_entry(file, SC_AC_OP_READ); if (e == NULL || e->method == SC_AC_NEVER) return 10; bufsize = file->size; sc_file_free(file); r = sc_read_binary(card, 0, buf, bufsize, 0); if (r < 0) { fprintf(stderr, "Unable to read private key file: %s\n", sc_strerror(r)); return 2; } bufsize = r; do { if (bufsize < 4) return 3; keysize = (p[0] << 8) | p[1]; if (keysize == 0) break; if (keysize < 3) return 3; if (p[2] == opt_key_num) break; p += keysize; bufsize -= keysize; } while (1); if (keysize == 0) { printf("Key number %d not found.\n", opt_key_num); return 2; } return parse_private_key(p, keysize, rsa); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415', 'CWE-119'], 'message': 'fixed out of bounds writes Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting the problems.'</s>
<s>[INST] Given the following code containing errors, provide 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 muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen) { muscle_private_t* priv = MUSCLE_DATA(card); mscfs_t *fs = priv->fs; int x; int count = 0; mscfs_check_cache(priv->fs); for(x = 0; x < fs->cache.size; x++) { u8* oid= fs->cache.array[x].objectId.id; sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "FILE: %02X%02X%02X%02X\n", oid[0],oid[1],oid[2],oid[3]); if(0 == memcmp(fs->currentPath, oid, 2)) { buf[0] = oid[2]; buf[1] = oid[3]; if(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */ buf += 2; count+=2; } } return count; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415', 'CWE-119'], 'message': 'fixed out of bounds writes Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting the problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: show_signal_msg(struct pt_regs *regs, unsigned long error_code, unsigned long address, struct task_struct *tsk) { const char *loglvl = task_pid_nr(tsk) > 1 ? KERN_INFO : KERN_EMERG; if (!unhandled_signal(tsk, SIGSEGV)) return; if (!printk_ratelimit()) return; printk("%s%s[%d]: segfault at %lx ip %px sp %px error %lx", loglvl, tsk->comm, task_pid_nr(tsk), address, (void *)regs->ip, (void *)regs->sp, error_code); print_vma_addr(KERN_CONT " in ", regs->ip); printk(KERN_CONT "\n"); show_opcodes((u8 *)regs->ip, loglvl); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'x86/dumpstack: Don't dump kernel memory based on usermode RIP show_opcodes() is used both for dumping kernel instructions and for dumping user instructions. If userspace causes #PF by jumping to a kernel address, show_opcodes() can be reached with regs->ip controlled by the user, pointing to kernel code. Make sure that userspace can't trick us into dumping kernel memory into dmesg. Fixes: 7cccf0725cf7 ("x86/dumpstack: Add a show_ip() function") Signed-off-by: Jann Horn <jannh@google.com> Signed-off-by: Thomas Gleixner <tglx@linutronix.de> Reviewed-by: Kees Cook <keescook@chromium.org> Reviewed-by: Borislav Petkov <bp@suse.de> Cc: "H. Peter Anvin" <hpa@zytor.com> Cc: Andy Lutomirski <luto@kernel.org> Cc: security@kernel.org Cc: stable@vger.kernel.org Link: https://lkml.kernel.org/r/20180828154901.112726-1-jannh@google.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: void WavOutFile::write(const short *buffer, int numElems) { int res; // 16 bit samples if (numElems < 1) return; // nothing to do switch (header.format.bits_per_sample) { case 8: { int i; unsigned char *temp = (unsigned char *)getConvBuffer(numElems); // convert from 16bit format to 8bit format for (i = 0; i < numElems; i ++) { temp[i] = (unsigned char)(buffer[i] / 256 + 128); } // write in 8bit format write(temp, numElems); break; } case 16: { // 16bit format // use temp buffer to swap byte order if necessary short *pTemp = (short *)getConvBuffer(numElems * sizeof(short)); memcpy(pTemp, buffer, numElems * 2); _swap16Buffer(pTemp, numElems); res = (int)fwrite(pTemp, 2, numElems, fptr); if (res != numElems) { ST_THROW_RT_ERROR("Error while writing to a wav file."); } bytesWritten += 2 * numElems; break; } default: { stringstream ss; ss << "\nOnly 8/16 bit sample WAV files supported in integer compilation. Can't open WAV file with "; ss << (int)header.format.bits_per_sample; ss << " bit sample format. "; ST_THROW_RT_ERROR(ss.str().c_str()); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'New take on CVE-2018-17097 i.e. avoiding writing beyond end of buffer in case of 24-bit samples'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: struct posix_acl *ovl_get_acl(struct inode *inode, int type) { struct inode *realinode = ovl_inode_real(inode); if (!realinode) return ERR_PTR(-ENOENT); if (!IS_POSIXACL(realinode)) return NULL; if (!realinode->i_op->get_acl) return NULL; return realinode->i_op->get_acl(realinode, type); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-863'], 'message': 'ovl: modify ovl_permission() to do checks on two inodes Right now ovl_permission() calls __inode_permission(realinode), to do permission checks on real inode and no checks are done on overlay inode. Modify it to do checks both on overlay inode as well as underlying inode. Checks on overlay inode will be done with the creds of calling task while checks on underlying inode will be done with the creds of mounter. Signed-off-by: Vivek Goyal <vgoyal@redhat.com> Signed-off-by: Miklos Szeredi <mszeredi@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: udisks_log (UDisksLogLevel level, const gchar *function, const gchar *location, const gchar *format, ...) { va_list var_args; gchar *message; va_start (var_args, format); message = g_strdup_vprintf (format, var_args); va_end (var_args); #if GLIB_CHECK_VERSION(2, 50, 0) g_log_structured ("udisks", (GLogLevelFlags) level, "MESSAGE", message, "THREAD_ID", "%d", (gint) syscall (SYS_gettid), "CODE_FUNC", function, "CODE_FILE", location); #else g_log ("udisks", level, "[%d]: %s [%s, %s()]", (gint) syscall (SYS_gettid), message, location, function); #endif g_free (message); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-134'], 'message': 'Fix string format vulnerability If the message in g_log_structured itself contained format sequences like %d or %n they were applied again, leading to leaked stack contents and possibly memory corruption. It can be triggered e.g. by a volume label containing format sequences. Print the message argument itself into a "%s" string to avoid intepreting format sequences. https://github.com/storaged-project/udisks/issues/578'</s>
<s>[INST] Given the following code containing errors, provide 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 WriteSGIImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { CompressionType compression; const char *value; MagickBooleanType status; MagickOffsetType scene; MagickSizeType number_pixels; MemoryInfo *pixel_info; SGIInfo iris_info; register const Quantum *p; register ssize_t i, x; register unsigned char *q; ssize_t y, z; unsigned char *pixels, *packets; /* 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); if ((image->columns > 65535UL) || (image->rows > 65535UL)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); scene=0; do { /* Initialize SGI raster file header. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); (void) memset(&iris_info,0,sizeof(iris_info)); iris_info.magic=0x01DA; compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; if (image->depth > 8) compression=NoCompression; if (compression == NoCompression) iris_info.storage=(unsigned char) 0x00; else iris_info.storage=(unsigned char) 0x01; iris_info.bytes_per_pixel=(unsigned char) (image->depth > 8 ? 2 : 1); iris_info.dimension=3; iris_info.columns=(unsigned short) image->columns; iris_info.rows=(unsigned short) image->rows; if (image->alpha_trait != UndefinedPixelTrait) iris_info.depth=4; else { if ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse)) { iris_info.dimension=2; iris_info.depth=1; } else iris_info.depth=3; } iris_info.minimum_value=0; iris_info.maximum_value=(size_t) (image->depth <= 8 ? 1UL*ScaleQuantumToChar(QuantumRange) : 1UL*ScaleQuantumToShort(QuantumRange)); /* Write SGI header. */ (void) WriteBlobMSBShort(image,iris_info.magic); (void) WriteBlobByte(image,iris_info.storage); (void) WriteBlobByte(image,iris_info.bytes_per_pixel); (void) WriteBlobMSBShort(image,iris_info.dimension); (void) WriteBlobMSBShort(image,iris_info.columns); (void) WriteBlobMSBShort(image,iris_info.rows); (void) WriteBlobMSBShort(image,iris_info.depth); (void) WriteBlobMSBLong(image,(unsigned int) iris_info.minimum_value); (void) WriteBlobMSBLong(image,(unsigned int) iris_info.maximum_value); (void) WriteBlobMSBLong(image,(unsigned int) iris_info.sans); value=GetImageProperty(image,"label",exception); if (value != (const char *) NULL) (void) CopyMagickString(iris_info.name,value,sizeof(iris_info.name)); (void) WriteBlob(image,sizeof(iris_info.name),(unsigned char *) iris_info.name); (void) WriteBlobMSBLong(image,(unsigned int) iris_info.pixel_format); (void) WriteBlob(image,sizeof(iris_info.filler),iris_info.filler); /* Allocate SGI pixels. */ number_pixels=(MagickSizeType) image->columns*image->rows; if ((4*iris_info.bytes_per_pixel*number_pixels) != ((MagickSizeType) (size_t) (4*iris_info.bytes_per_pixel*number_pixels))) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info=AcquireVirtualMemory((size_t) number_pixels,4* iris_info.bytes_per_pixel*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Convert image pixels to uncompressed SGI 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; if (image->depth <= 8) for (x=0; x < (ssize_t) image->columns; x++) { register unsigned char *q; q=(unsigned char *) pixels; q+=((iris_info.rows-1)-y)*(4*iris_info.columns)+4*x; *q++=ScaleQuantumToChar(GetPixelRed(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); *q++=ScaleQuantumToChar(GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } else for (x=0; x < (ssize_t) image->columns; x++) { register unsigned short *q; q=(unsigned short *) pixels; q+=((iris_info.rows-1)-y)*(4*iris_info.columns)+4*x; *q++=ScaleQuantumToShort(GetPixelRed(image,p)); *q++=ScaleQuantumToShort(GetPixelGreen(image,p)); *q++=ScaleQuantumToShort(GetPixelBlue(image,p)); *q++=ScaleQuantumToShort(GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } switch (compression) { case NoCompression: { /* Write uncompressed SGI pixels. */ for (z=0; z < (ssize_t) iris_info.depth; z++) { for (y=0; y < (ssize_t) iris_info.rows; y++) { if (image->depth <= 8) for (x=0; x < (ssize_t) iris_info.columns; x++) { register unsigned char *q; q=(unsigned char *) pixels; q+=y*(4*iris_info.columns)+4*x+z; (void) WriteBlobByte(image,*q); } else for (x=0; x < (ssize_t) iris_info.columns; x++) { register unsigned short *q; q=(unsigned short *) pixels; q+=y*(4*iris_info.columns)+4*x+z; (void) WriteBlobMSBShort(image,*q); } } } break; } default: { MemoryInfo *packet_info; size_t length, number_packets, *runlength; ssize_t offset, *offsets; /* Convert SGI uncompressed pixels. */ offsets=(ssize_t *) AcquireQuantumMemory(iris_info.rows, iris_info.depth*sizeof(*offsets)); runlength=(size_t *) AcquireQuantumMemory(iris_info.rows, iris_info.depth*sizeof(*runlength)); packet_info=AcquireVirtualMemory((2*(size_t) iris_info.columns+10)* image->rows,4*sizeof(*packets)); if ((offsets == (ssize_t *) NULL) || (runlength == (size_t *) NULL) || (packet_info == (MemoryInfo *) NULL)) { if (offsets != (ssize_t *) NULL) offsets=(ssize_t *) RelinquishMagickMemory(offsets); if (runlength != (size_t *) NULL) runlength=(size_t *) RelinquishMagickMemory(runlength); if (packet_info != (MemoryInfo *) NULL) packet_info=RelinquishVirtualMemory(packet_info); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } packets=(unsigned char *) GetVirtualMemoryBlob(packet_info); offset=512+4*2*((ssize_t) iris_info.rows*iris_info.depth); number_packets=0; q=pixels; for (y=0; y < (ssize_t) iris_info.rows; y++) { for (z=0; z < (ssize_t) iris_info.depth; z++) { length=SGIEncode(q+z,(size_t) iris_info.columns,packets+ number_packets); number_packets+=length; offsets[y+z*iris_info.rows]=offset; runlength[y+z*iris_info.rows]=(size_t) length; offset+=(ssize_t) length; } q+=(iris_info.columns*4); } /* Write out line start and length tables and runlength-encoded pixels. */ for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++) (void) WriteBlobMSBLong(image,(unsigned int) offsets[i]); for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++) (void) WriteBlobMSBLong(image,(unsigned int) runlength[i]); (void) WriteBlob(image,number_packets,packets); /* Relinquish resources. */ offsets=(ssize_t *) RelinquishMagickMemory(offsets); runlength=(size_t *) RelinquishMagickMemory(runlength); packet_info=RelinquishVirtualMemory(packet_info); break; } } pixel_info=RelinquishVirtualMemory(pixel_info); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); 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-772'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1052'</s>
<s>[INST] Given the following code containing errors, provide 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 *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception) { BMPInfo bmp_info; Image *image; IndexPacket index; MagickBooleanType status; MagickOffsetType offset, start_position; MemoryInfo *pixel_info; register IndexPacket *indexes; register PixelPacket *q; register ssize_t i, x; register unsigned char *p; size_t bit, bytes_per_line, length; ssize_t count, y; unsigned char magick[12], *pixels; unsigned int blue, green, offset_bits, red; /* 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); } /* Determine if this a BMP file. */ (void) memset(&bmp_info,0,sizeof(bmp_info)); bmp_info.ba_offset=0; start_position=0; offset_bits=0; count=ReadBlob(image,2,magick); if (count != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { LongPixelPacket shift; PixelPacket quantum_bits; /* Verify BMP identifier. */ if (bmp_info.ba_offset == 0) start_position=TellBlob(image)-2; bmp_info.ba_offset=0; while (LocaleNCompare((char *) magick,"BA",2) == 0) { bmp_info.file_size=ReadBlobLSBLong(image); bmp_info.ba_offset=ReadBlobLSBLong(image); bmp_info.offset_bits=ReadBlobLSBLong(image); count=ReadBlob(image,2,magick); if (count != 2) break; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Magick: %c%c", magick[0],magick[1]); if ((count != 2) || ((LocaleNCompare((char *) magick,"BM",2) != 0) && (LocaleNCompare((char *) magick,"CI",2) != 0))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); bmp_info.file_size=ReadBlobLSBLong(image); (void) ReadBlobLSBLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " File_size in header: %u bytes",bmp_info.file_size); bmp_info.offset_bits=ReadBlobLSBLong(image); bmp_info.size=ReadBlobLSBLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," BMP size: %u", bmp_info.size); if (bmp_info.size == 12) { /* OS/2 BMP image file. */ (void) CopyMagickString(image->magick,"BMP2",MaxTextExtent); bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.x_pixels=0; bmp_info.y_pixels=0; bmp_info.number_colors=0; bmp_info.compression=BI_RGB; bmp_info.image_size=0; bmp_info.alpha_mask=0; if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format: OS/2 Bitmap"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Geometry: %.20gx%.20g",(double) bmp_info.width,(double) bmp_info.height); } } else { /* Microsoft Windows BMP image file. */ if (bmp_info.size < 40) ThrowReaderException(CorruptImageError,"NonOS2HeaderSizeError"); bmp_info.width=(ssize_t) ReadBlobLSBSignedLong(image); bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(image); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.compression=ReadBlobLSBLong(image); bmp_info.image_size=ReadBlobLSBLong(image); bmp_info.x_pixels=ReadBlobLSBLong(image); bmp_info.y_pixels=ReadBlobLSBLong(image); bmp_info.number_colors=ReadBlobLSBLong(image); if (bmp_info.number_colors > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); bmp_info.colors_important=ReadBlobLSBLong(image); if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format: MS Windows bitmap"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Geometry: %.20gx%.20g",(double) bmp_info.width,(double) bmp_info.height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Bits per pixel: %.20g",(double) bmp_info.bits_per_pixel); switch (bmp_info.compression) { case BI_RGB: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RGB"); break; } case BI_RLE4: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RLE4"); break; } case BI_RLE8: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RLE8"); break; } case BI_BITFIELDS: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_BITFIELDS"); break; } case BI_PNG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_PNG"); break; } case BI_JPEG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_JPEG"); break; } default: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: UNKNOWN (%u)",bmp_info.compression); } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %u",bmp_info.number_colors); } bmp_info.red_mask=ReadBlobLSBLong(image); bmp_info.green_mask=ReadBlobLSBLong(image); bmp_info.blue_mask=ReadBlobLSBLong(image); if (bmp_info.size > 40) { double gamma; /* Read color management information. */ bmp_info.alpha_mask=ReadBlobLSBLong(image); bmp_info.colorspace=ReadBlobLSBSignedLong(image); /* Decode 2^30 fixed point formatted CIE primaries. */ # define BMP_DENOM ((double) 0x40000000) bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; gamma=bmp_info.red_primary.x+bmp_info.red_primary.y+ bmp_info.red_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.red_primary.x*=gamma; bmp_info.red_primary.y*=gamma; image->chromaticity.red_primary.x=bmp_info.red_primary.x; image->chromaticity.red_primary.y=bmp_info.red_primary.y; gamma=bmp_info.green_primary.x+bmp_info.green_primary.y+ bmp_info.green_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.green_primary.x*=gamma; bmp_info.green_primary.y*=gamma; image->chromaticity.green_primary.x=bmp_info.green_primary.x; image->chromaticity.green_primary.y=bmp_info.green_primary.y; gamma=bmp_info.blue_primary.x+bmp_info.blue_primary.y+ bmp_info.blue_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.blue_primary.x*=gamma; bmp_info.blue_primary.y*=gamma; image->chromaticity.blue_primary.x=bmp_info.blue_primary.x; image->chromaticity.blue_primary.y=bmp_info.blue_primary.y; /* Decode 16^16 fixed point formatted gamma_scales. */ bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000; /* Compute a single gamma from the BMP 3-channel gamma. */ image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+ bmp_info.gamma_scale.z)/3.0; } else (void) CopyMagickString(image->magick,"BMP3",MaxTextExtent); if (bmp_info.size > 108) { size_t intent; /* Read BMP Version 5 color management information. */ intent=ReadBlobLSBLong(image); switch ((int) intent) { case LCS_GM_BUSINESS: { image->rendering_intent=SaturationIntent; break; } case LCS_GM_GRAPHICS: { image->rendering_intent=RelativeIntent; break; } case LCS_GM_IMAGES: { image->rendering_intent=PerceptualIntent; break; } case LCS_GM_ABS_COLORIMETRIC: { image->rendering_intent=AbsoluteIntent; break; } } (void) ReadBlobLSBLong(image); /* Profile data */ (void) ReadBlobLSBLong(image); /* Profile size */ (void) ReadBlobLSBLong(image); /* Reserved byte */ } } if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, "LengthAndFilesizeDoNotMatch","`%s'",image->filename); else if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageWarning,"LengthAndFilesizeDoNotMatch","`%s'", image->filename); if (bmp_info.width <= 0) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); if (bmp_info.height == 0) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); if (bmp_info.planes != 1) ThrowReaderException(CorruptImageError,"StaticPlanesValueNotEqualToOne"); if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) && (bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) && (bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if (bmp_info.bits_per_pixel < 16 && bmp_info.number_colors > (1U << bmp_info.bits_per_pixel)) ThrowReaderException(CorruptImageError,"UnrecognizedNumberOfColors"); if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); switch (bmp_info.compression) { case BI_RGB: image->compression=NoCompression; break; case BI_RLE8: case BI_RLE4: image->compression=RLECompression; break; case BI_BITFIELDS: break; case BI_JPEG: ThrowReaderException(CoderError,"JPEGCompressNotSupported"); case BI_PNG: ThrowReaderException(CoderError,"PNGCompressNotSupported"); default: ThrowReaderException(CorruptImageError,"UnrecognizedImageCompression"); } image->columns=(size_t) MagickAbsoluteValue(bmp_info.width); image->rows=(size_t) MagickAbsoluteValue(bmp_info.height); image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8; image->matte=((bmp_info.alpha_mask != 0) && (bmp_info.compression == BI_BITFIELDS)) ? MagickTrue : MagickFalse; if (bmp_info.bits_per_pixel < 16) { size_t one; image->storage_class=PseudoClass; image->colors=bmp_info.number_colors; one=1; if (image->colors == 0) image->colors=one << bmp_info.bits_per_pixel; } image->x_resolution=(double) bmp_info.x_pixels/100.0; image->y_resolution=(double) bmp_info.y_pixels/100.0; image->units=PixelsPerCentimeterResolution; 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) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (image->storage_class == PseudoClass) { unsigned char *bmp_colormap; size_t packet_size; /* Read BMP raster colormap. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading colormap of %.20g colors",(double) image->colors); if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) image->colors,4*sizeof(*bmp_colormap)); if (bmp_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if ((bmp_info.size == 12) || (bmp_info.size == 64)) packet_size=3; else packet_size=4; offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET); if (offset < 0) { bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } count=ReadBlob(image,packet_size*image->colors,bmp_colormap); if (count != (ssize_t) (packet_size*image->colors)) { bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } p=bmp_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].blue=ScaleCharToQuantum(*p++); image->colormap[i].green=ScaleCharToQuantum(*p++); image->colormap[i].red=ScaleCharToQuantum(*p++); if (packet_size == 4) p++; } bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); } /* Read image data. */ if (bmp_info.offset_bits == offset_bits) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); offset_bits=bmp_info.offset_bits; offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (bmp_info.compression == BI_RLE4) bmp_info.bits_per_pixel<<=1; bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32); length=(size_t) bytes_per_line*image->rows; if (((MagickSizeType) length/8) > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); if ((bmp_info.compression == BI_RGB) || (bmp_info.compression == BI_BITFIELDS)) { pixel_info=AcquireVirtualMemory(image->rows,MagickMax(bytes_per_line, image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading pixels (%.20g bytes)",(double) length); count=ReadBlob(image,length,pixels); if (count != (ssize_t) length) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } } else { /* Convert run-length encoded raster pixels. */ pixel_info=AcquireVirtualMemory(image->rows,MagickMax(bytes_per_line, image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); status=DecodeImage(image,bmp_info.compression,pixels, image->columns*image->rows); if (status == MagickFalse) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnableToRunlengthDecodeImage"); } } /* Convert BMP raster image to pixel packets. */ if (bmp_info.compression == BI_RGB) { /* We should ignore the alpha value in BMP3 files but there have been reports about 32 bit files with alpha. We do a quick check to see if the alpha channel contains a value that is not zero (default value). If we find a non zero value we asume the program that wrote the file wants to use the alpha channel. */ if ((image->matte == MagickFalse) && (bmp_info.size == 40) && (bmp_info.bits_per_pixel == 32)) { bytes_per_line=4*(image->columns); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { if (*(p+3) != 0) { image->matte=MagickTrue; y=-1; break; } p+=4; } } } bmp_info.alpha_mask=image->matte != MagickFalse ? 0xff000000U : 0U; bmp_info.red_mask=0x00ff0000U; bmp_info.green_mask=0x0000ff00U; bmp_info.blue_mask=0x000000ffU; if (bmp_info.bits_per_pixel == 16) { /* RGB555. */ bmp_info.red_mask=0x00007c00U; bmp_info.green_mask=0x000003e0U; bmp_info.blue_mask=0x0000001fU; } } (void) memset(&shift,0,sizeof(shift)); (void) memset(&quantum_bits,0,sizeof(quantum_bits)); if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32)) { register size_t sample; /* Get shift and quantum bits info from bitfield masks. */ if (bmp_info.red_mask != 0) while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0) { shift.red++; if (shift.red > 32U) break; } if (bmp_info.green_mask != 0) while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0) { shift.green++; if (shift.green > 32U) break; } if (bmp_info.blue_mask != 0) while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0) { shift.blue++; if (shift.blue > 32U) break; } if (bmp_info.alpha_mask != 0) while (((bmp_info.alpha_mask << shift.opacity) & 0x80000000UL) == 0) { shift.opacity++; if (shift.opacity > 32U) break; } sample=shift.red; while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample > 32U) break; } quantum_bits.red=ClampToQuantum((MagickRealType) sample-shift.red); sample=shift.green; while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample > 32U) break; } quantum_bits.green=ClampToQuantum((MagickRealType) sample-shift.green); sample=shift.blue; while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample > 32U) break; } quantum_bits.blue=ClampToQuantum((MagickRealType) sample-shift.blue); sample=shift.opacity; while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample > 32U) break; } quantum_bits.opacity=ClampToQuantum((MagickRealType) sample- shift.opacity); } switch (bmp_info.bits_per_pixel) { case 1: { /* Convert bitmap scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; 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-7); x+=8) { for (bit=0; bit < 8; bit++) { index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); q++; } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (image->columns % 8); bit++) { index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); break; } case 4: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; 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-1); x+=2) { (void) IsValidColormapIndex(image,(ssize_t) ((*p >> 4) & 0x0f), &index,exception); SetPixelIndex(indexes+x,index); (void) IsValidColormapIndex(image,(ssize_t) (*p & 0x0f),&index, exception); SetPixelIndex(indexes+x+1,index); p++; } if ((image->columns % 2) != 0) { (void) IsValidColormapIndex(image,(ssize_t) ((*p >> 4) & 0xf), &index,exception); SetPixelIndex(indexes+(x++),index); p++; } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); break; } case 8: { /* Convert PseudoColor scanline. */ if ((bmp_info.compression == BI_RLE8) || (bmp_info.compression == BI_RLE4)) bytes_per_line=image->columns; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=(ssize_t) image->columns; x != 0; --x) { (void) IsValidColormapIndex(image,(ssize_t) *p,&index,exception); SetPixelIndex(indexes,index); indexes++; p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); break; } case 16: { unsigned int alpha, pixel; /* Convert bitfield encoded 16-bit PseudoColor scanline. */ if (bmp_info.compression != BI_RGB && bmp_info.compression != BI_BITFIELDS) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnrecognizedImageCompression"); } bytes_per_line=2*(image->columns+image->columns % 2); image->storage_class=DirectClass; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(unsigned int) (*p++); pixel|=(*p++) << 8; red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 5) red|=((red & 0xe000) >> 5); if (quantum_bits.red <= 8) red|=((red & 0xff00) >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 5) green|=((green & 0xe000) >> 5); if (quantum_bits.green == 6) green|=((green & 0xc000) >> 6); if (quantum_bits.green <= 8) green|=((green & 0xff00) >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 5) blue|=((blue & 0xe000) >> 5); if (quantum_bits.blue <= 8) blue|=((blue & 0xff00) >> 8); SetPixelRed(q,ScaleShortToQuantum((unsigned short) red)); SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green)); SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16; if (quantum_bits.opacity <= 8) alpha|=((alpha & 0xff00) >> 8); SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha)); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 24: { /* Convert DirectColor scanline. */ bytes_per_line=4*((image->columns*24+31)/32); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelOpacity(q,OpaqueOpacity); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 32: { /* Convert bitfield encoded DirectColor scanline. */ if ((bmp_info.compression != BI_RGB) && (bmp_info.compression != BI_BITFIELDS)) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnrecognizedImageCompression"); } bytes_per_line=4*(image->columns); for (y=(ssize_t) image->rows-1; y >= 0; y--) { unsigned int alpha, pixel; p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(unsigned int) (*p++); pixel|=((unsigned int) *p++ << 8); pixel|=((unsigned int) *p++ << 16); pixel|=((unsigned int) *p++ << 24); red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 8) red|=(red >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 8) green|=(green >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 8) blue|=(blue >> 8); SetPixelRed(q,ScaleShortToQuantum((unsigned short) red)); SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green)); SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue)); SetPixelAlpha(q,OpaqueOpacity); if (image->matte != MagickFalse) { alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16; if (quantum_bits.opacity == 8) alpha|=(alpha >> 8); SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha)); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } default: { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } } pixel_info=RelinquishVirtualMemory(pixel_info); if (y > 0) break; if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if (bmp_info.height < 0) { Image *flipped_image; /* Correct image orientation. */ flipped_image=FlipImage(image,exception); if (flipped_image != (Image *) NULL) { DuplicateBlob(flipped_image,image); ReplaceImageInList(&image, flipped_image); image=flipped_image; } } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; *magick='\0'; if (bmp_info.ba_offset != 0) { offset=SeekBlob(image,(MagickOffsetType) bmp_info.ba_offset,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } count=ReadBlob(image,2,magick); if ((count == 2) && (IsBMP(magick,2) != MagickFalse)) { /* Acquire 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; } } while (IsBMP(magick,2) != MagickFalse); (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-835'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1337'</s>
<s>[INST] Given the following code containing errors, provide 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 link_stop_clients(Link *link) { int r = 0, k; assert(link); assert(link->manager); assert(link->manager->event); if (!link->network) return 0; if (link->dhcp_client) { k = sd_dhcp_client_stop(link->dhcp_client); if (k < 0) r = log_link_warning_errno(link, r, "Could not stop DHCPv4 client: %m"); } if (link->ipv4ll) { k = sd_ipv4ll_stop(link->ipv4ll); if (k < 0) r = log_link_warning_errno(link, r, "Could not stop IPv4 link-local: %m"); } if(link->ndisc_router_discovery) { if (link->dhcp6_client) { k = sd_dhcp6_client_stop(link->dhcp6_client); if (k < 0) r = log_link_warning_errno(link, r, "Could not stop DHCPv6 client: %m"); } k = sd_ndisc_stop(link->ndisc_router_discovery); if (k < 0) r = log_link_warning_errno(link, r, "Could not stop IPv6 Router Discovery: %m"); } if (link->lldp) { k = sd_lldp_stop(link->lldp); if (k < 0) r = log_link_warning_errno(link, r, "Could not stop LLDP: %m"); } return r; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'networkd: IPv6 router discovery - follow IPv6AcceptRouterAdvertisemnt= The previous behavior: When DHCPv6 was enabled, router discover was performed first, and then DHCPv6 was enabled only if the relevant flags were passed in the Router Advertisement message. Moreover, router discovery was performed even if AcceptRouterAdvertisements=false, moreover, even if router advertisements were accepted (by the kernel) the flags indicating that DHCPv6 should be performed were ignored. New behavior: If RouterAdvertisements are accepted, and either no routers are found, or an advertisement is received indicating DHCPv6 should be performed, the DHCPv6 client is started. Moreover, the DHCP option now truly enables the DHCPv6 client regardless of router discovery (though it will probably not be very useful to get a lease withotu any routes, this seems the more consistent approach). The recommended default setting should be to set DHCP=ipv4 and to leave IPv6AcceptRouterAdvertisements unset.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: do_execstack(i_ctx_t *i_ctx_p, bool include_marks, os_ptr op1) { os_ptr op = osp; ref *arefs = op1->value.refs; uint asize = r_size(op1); uint i; ref *rq; /* * Copy elements from the stack to the array, * optionally skipping executable nulls. * Clear the executable bit in any internal operators, and * convert t_structs and t_astructs (which can only appear * in connection with stack marks, which means that they will * probably be freed when unwinding) to something harmless. */ for (i = 0, rq = arefs + asize; rq != arefs; ++i) { const ref *rp = ref_stack_index(&e_stack, (long)i); if (r_has_type_attrs(rp, t_null, a_executable) && !include_marks) continue; --rq; ref_assign_old(op1, rq, rp, "execstack"); switch (r_type(rq)) { case t_operator: { uint opidx = op_index(rq); if (opidx == 0 || op_def_is_internal(op_index_def(opidx))) r_clear_attrs(rq, a_executable); break; } case t_struct: case t_astruct: { const char *tname = rq->value.pstruct ? gs_struct_type_name_string( gs_object_type(imemory, rq->value.pstruct)) : "NULL"; make_const_string(rq, a_readonly | avm_foreign, strlen(tname), (const byte *)tname); break; } default: ; } } pop(op - op1); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Bug 699927: don't include operator arrays in execstack output When we transfer the contents of the execution stack into the array, take the extra step of replacing any operator arrays on the stack with the operator that reference them. This prevents the contents of Postscript defined, internal only operators (those created with .makeoperator) being exposed via execstack (and thus, via error handling). This necessitates a change in the resource remapping 'resource', which contains a procedure which relies on the contents of the operators arrays being present. As we already had internal-only variants of countexecstack and execstack (.countexecstack and .execstack) - using those, and leaving thier operation including the operator arrays means the procedure continues to work correctly. Both .countexecstack and .execstack are undefined after initialization. Also, when we store the execstack (or part thereof) for an execstackoverflow error, make the same oparray/operator substitution as above for execstack.'</s>
<s>[INST] Given the following code containing errors, provide 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 voutf(struct GlobalConfig *config, const char *prefix, const char *fmt, va_list ap) { size_t width = (79 - strlen(prefix)); if(!config->mute) { size_t len; char *ptr; char *print_buffer; print_buffer = curlx_mvaprintf(fmt, ap); if(!print_buffer) return; len = strlen(print_buffer); ptr = print_buffer; while(len > 0) { fputs(prefix, config->errors); if(len > width) { size_t cut = width-1; while(!ISSPACE(ptr[cut]) && cut) { cut--; } if(0 == cut) /* not a single cutting position was found, just cut it at the max text width then! */ cut = width-1; (void)fwrite(ptr, cut + 1, 1, config->errors); fputs("\n", config->errors); ptr += cut + 1; /* skip the space too */ len -= cut; } else { fputs(ptr, config->errors); len = 0; } } curl_free(print_buffer); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-125'], 'message': 'voutf: fix bad arethmetic when outputting warnings to stderr CVE-2018-16842 Reported-by: Brian Carpenter Bug: https://curl.haxx.se/docs/CVE-2018-16842.html'</s>
<s>[INST] Given the following code containing errors, provide 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 RGWListMultipart_ObjStore::get_params() { upload_id = s->info.args.get("uploadId"); if (upload_id.empty()) { op_ret = -ENOTSUP; } string marker_str = s->info.args.get("part-number-marker"); if (!marker_str.empty()) { string err; marker = strict_strtol(marker_str.c_str(), 10, &err); if (!err.empty()) { ldout(s->cct, 20) << "bad marker: " << marker << dendl; op_ret = -EINVAL; return op_ret; } } string str = s->info.args.get("max-parts"); op_ret = parse_value_and_bound(str, &max_parts, 0, g_conf()->rgw_max_listing_results, max_parts); return op_ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-770'], 'message': 'rgw: fix issues with 'enforce bounds' patch The patch to enforce bounds on max-keys/max-uploads/max-parts had a few issues that would prevent us from compiling it. Instead of changing the code provided by the submitter, we're addressing them in a separate commit to maintain the DCO. Signed-off-by: Joao Eduardo Luis <joao@suse.de> Signed-off-by: Abhishek Lekshmanan <abhishek@suse.com> (cherry picked from commit 29bc434a6a81a2e5c5b8cfc4c8d5c82ca5bf538a) mimic specific fixes: As the largeish change from master g_conf() isn't in mimic yet, use the g_conf global structure, also make rgw_op use the value from req_info ceph context as we do for all the requests'</s>
<s>[INST] Given the following code containing errors, provide 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 Image::printIFDStructure(BasicIo& io, std::ostream& out, Exiv2::PrintStructureOption option,uint32_t start,bool bSwap,char c,int depth) { depth++; bool bFirst = true ; // buffer const size_t dirSize = 32; DataBuf dir(dirSize); bool bPrint = option == kpsBasic || option == kpsRecursive; do { // Read top of directory io.seek(start,BasicIo::beg); io.read(dir.pData_, 2); uint16_t dirLength = byteSwap2(dir,0,bSwap); bool tooBig = dirLength > 500; if ( tooBig ) throw Error(kerTiffDirectoryTooLarge); if ( bFirst && bPrint ) { out << Internal::indent(depth) << Internal::stringFormat("STRUCTURE OF TIFF FILE (%c%c): ",c,c) << io.path() << std::endl; if ( tooBig ) out << Internal::indent(depth) << "dirLength = " << dirLength << std::endl; } // Read the dictionary for ( int i = 0 ; i < dirLength ; i ++ ) { if ( bFirst && bPrint ) { out << Internal::indent(depth) << " address | tag | " << " type | count | offset | value\n"; } bFirst = false; io.read(dir.pData_, 12); uint16_t tag = byteSwap2(dir,0,bSwap); uint16_t type = byteSwap2(dir,2,bSwap); uint32_t count = byteSwap4(dir,4,bSwap); uint32_t offset = byteSwap4(dir,8,bSwap); // Break for unknown tag types else we may segfault. if ( !typeValid(type) ) { std::cerr << "invalid type value detected in Image::printIFDStructure: " << type << std::endl; start = 0; // break from do loop throw Error(kerInvalidTypeValue); } std::string sp = "" ; // output spacer //prepare to print the value uint32_t kount = isPrintXMP(tag,option) ? count // haul in all the data : isPrintICC(tag,option) ? count // ditto : isStringType(type) ? (count > 32 ? 32 : count) // restrict long arrays : count > 5 ? 5 : count ; uint32_t pad = isStringType(type) ? 1 : 0; uint32_t size = isStringType(type) ? 1 : is2ByteType(type) ? 2 : is4ByteType(type) ? 4 : is8ByteType(type) ? 8 : 1 ; // if ( offset > io.size() ) offset = 0; // Denial of service? // #55 and #56 memory allocation crash test/data/POC8 long long allocate = (long long) size*count + pad+20; if ( allocate > (long long) io.size() ) { throw Error(kerInvalidMalloc); } DataBuf buf((long)allocate); // allocate a buffer std::memset(buf.pData_, 0, buf.size_); std::memcpy(buf.pData_,dir.pData_+8,4); // copy dir[8:11] into buffer (short strings) const bool bOffsetIsPointer = count*size > 4; if ( bOffsetIsPointer ) { // read into buffer size_t restore = io.tell(); // save io.seek(offset,BasicIo::beg); // position io.read(buf.pData_,count*size);// read io.seek(restore,BasicIo::beg); // restore } if ( bPrint ) { const uint32_t address = start + 2 + i*12 ; const std::string offsetString = bOffsetIsPointer? Internal::stringFormat("%10u", offset): ""; out << Internal::indent(depth) << Internal::stringFormat("%8u | %#06x %-28s |%10s |%9u |%10s | " ,address,tag,tagName(tag).c_str(),typeName(type),count,offsetString.c_str()); if ( isShortType(type) ){ for ( size_t k = 0 ; k < kount ; k++ ) { out << sp << byteSwap2(buf,k*size,bSwap); sp = " "; } } else if ( isLongType(type) ){ for ( size_t k = 0 ; k < kount ; k++ ) { out << sp << byteSwap4(buf,k*size,bSwap); sp = " "; } } else if ( isRationalType(type) ){ for ( size_t k = 0 ; k < kount ; k++ ) { uint32_t a = byteSwap4(buf,k*size+0,bSwap); uint32_t b = byteSwap4(buf,k*size+4,bSwap); out << sp << a << "/" << b; sp = " "; } } else if ( isStringType(type) ) { out << sp << Internal::binaryToString(makeSlice(buf, 0, kount)); } sp = kount == count ? "" : " ..."; out << sp << std::endl; if ( option == kpsRecursive && (tag == 0x8769 /* ExifTag */ || tag == 0x014a/*SubIFDs*/ || type == tiffIfd) ) { for ( size_t k = 0 ; k < count ; k++ ) { size_t restore = io.tell(); uint32_t offset = byteSwap4(buf,k*size,bSwap); printIFDStructure(io,out,option,offset,bSwap,c,depth); io.seek(restore,BasicIo::beg); } } else if ( option == kpsRecursive && tag == 0x83bb /* IPTCNAA */ ) { if (static_cast<size_t>(Safe::add(count, offset)) > io.size()) { throw Error(kerCorruptedMetadata); } const size_t restore = io.tell(); io.seek(offset, BasicIo::beg); // position std::vector<byte> bytes(count) ; // allocate memory // TODO: once we have C++11 use bytes.data() const long read_bytes = io.read(&bytes[0], count); io.seek(restore, BasicIo::beg); // TODO: once we have C++11 use bytes.data() IptcData::printStructure(out, makeSliceUntil(&bytes[0], read_bytes), depth); } else if ( option == kpsRecursive && tag == 0x927c /* MakerNote */ && count > 10) { size_t restore = io.tell(); // save uint32_t jump= 10 ; byte bytes[20] ; const char* chars = (const char*) &bytes[0] ; io.seek(offset,BasicIo::beg); // position io.read(bytes,jump ) ; // read bytes[jump]=0 ; if ( ::strcmp("Nikon",chars) == 0 ) { // tag is an embedded tiff byte* bytes=new byte[count-jump] ; // allocate memory io.read(bytes,count-jump) ; // read MemIo memIo(bytes,count-jump) ; // create a file printTiffStructure(memIo,out,option,depth); delete[] bytes ; // free } else { // tag is an IFD io.seek(0,BasicIo::beg); // position printIFDStructure(io,out,option,offset,bSwap,c,depth); } io.seek(restore,BasicIo::beg); // restore } } if ( isPrintXMP(tag,option) ) { buf.pData_[count]=0; out << (char*) buf.pData_; } if ( isPrintICC(tag,option) ) { out.write((const char*)buf.pData_,count); } } if ( start ) { io.read(dir.pData_, 4); start = tooBig ? 0 : byteSwap4(dir,0,bSwap); } } while (start) ; if ( bPrint ) { out << Internal::indent(depth) << "END " << io.path() << std::endl; } out.flush(); depth--; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': 'Check in Image::printIFDStructure if seek and reads are OK'</s>
<s>[INST] Given the following code containing errors, provide 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 size_t handle_returned_header (void *ptr, size_t size, size_t nmemb, void *stream) { auth_client *auth_user = stream; size_t bytes = size * nmemb; client_t *client = auth_user->client; if (client) { auth_t *auth = client->auth; auth_url *url = auth->state; if (strncasecmp (ptr, url->auth_header, url->auth_header_len) == 0) client->authenticated = 1; if (strncasecmp (ptr, url->timelimit_header, url->timelimit_header_len) == 0) { unsigned int limit = 0; sscanf ((char *)ptr+url->timelimit_header_len, "%u\r\n", &limit); client->con->discon_time = time(NULL) + limit; } if (strncasecmp (ptr, "icecast-auth-message: ", 22) == 0) { char *eol; snprintf (url->errormsg, sizeof (url->errormsg), "%s", (char*)ptr+22); eol = strchr (url->errormsg, '\r'); if (eol == NULL) eol = strchr (url->errormsg, '\n'); if (eol) *eol = '\0'; } } return bytes; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix: Worked around buffer overflows in URL auth's cURL interface This is only a workaround that keeps compatibility with 2.4.x mainline. A real fix has been implemented in 2.5.x (master).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ambsdtar_estimate( application_argument_t *argument) { char *incrname = NULL; GPtrArray *argv_ptr; char *cmd = NULL; int nullfd = -1; int pipefd = -1; FILE *dumpout = NULL; off_t size = -1; char line[32768]; char *errmsg = NULL; char *qerrmsg = NULL; char *qdisk = NULL; amwait_t wait_status; int tarpid; amregex_t *rp; times_t start_time; int level; GSList *levels; char *file_exclude = NULL; char *file_include = NULL; GString *strbuf; if (!argument->level) { fprintf(stderr, "ERROR No level argument\n"); error(_("No level argument")); } if (!argument->dle.disk) { fprintf(stderr, "ERROR No disk argument\n"); error(_("No disk argument")); } if (!argument->dle.device) { fprintf(stderr, "ERROR No device argument\n"); error(_("No device argument")); } if (argument->calcsize) { char *dirname; int nb_exclude; int nb_include; char *calcsize = g_strjoin(NULL, amlibexecdir, "/", "calcsize", NULL); if (!check_exec_for_suid(calcsize, FALSE)) { errmsg = g_strdup_printf("'%s' binary is not secure", calcsize); goto common_error; return; } if (bsdtar_directory) { dirname = bsdtar_directory; } else { dirname = argument->dle.device; } ambsdtar_build_exinclude(&argument->dle, 1, &nb_exclude, &file_exclude, &nb_include, &file_include); run_calcsize(argument->config, "BSDTAR", argument->dle.disk, dirname, argument->level, file_exclude, file_include); if (argument->verbose == 0) { if (file_exclude) unlink(file_exclude); if (file_include) unlink(file_include); } amfree(file_exclude); amfree(file_include); amfree(qdisk); return; } if (!bsdtar_path) { errmsg = g_strdup(_("BSDTAR-PATH not defined")); goto common_error; } if (!check_exec_for_suid(bsdtar_path, FALSE)) { errmsg = g_strdup_printf("'%s' binary is not secure", bsdtar_path); goto common_error; } if (!state_dir) { errmsg = g_strdup(_("STATE-DIR not defined")); goto common_error; } qdisk = quote_string(argument->dle.disk); for (levels = argument->level; levels != NULL; levels = levels->next) { char *timestamps; level = GPOINTER_TO_INT(levels->data); timestamps = ambsdtar_get_timestamps(argument, level, stdout, CMD_ESTIMATE); cmd = g_strdup(bsdtar_path); argv_ptr = ambsdtar_build_argv(argument, timestamps, &file_exclude, &file_include, CMD_ESTIMATE); amfree(timestamps); start_time = curclock(); if ((nullfd = open("/dev/null", O_RDWR)) == -1) { errmsg = g_strdup_printf(_("Cannot access /dev/null : %s"), strerror(errno)); goto common_exit; } tarpid = pipespawnv(cmd, STDERR_PIPE, 1, &nullfd, &nullfd, &pipefd, (char **)argv_ptr->pdata); dumpout = fdopen(pipefd,"r"); if (!dumpout) { error(_("Can't fdopen: %s"), strerror(errno)); /*NOTREACHED*/ } size = (off_t)-1; while (size < 0 && (fgets(line, sizeof(line), dumpout) != NULL)) { if (strlen(line) > 0 && line[strlen(line)-1] == '\n') { /* remove trailling \n */ line[strlen(line)-1] = '\0'; } if (line[0] == '\0') continue; g_debug("%s", line); /* check for size match */ /*@ignore@*/ for(rp = re_table; rp->regex != NULL; rp++) { if(match(rp->regex, line)) { if (rp->typ == DMP_SIZE) { off_t blocksize = gblocksize; size = ((the_num(line, rp->field)*rp->scale+1023.0)/1024.0); if(size < 0.0) size = 1.0; /* found on NeXT -- sigh */ if (!blocksize) { blocksize = 20; } blocksize /= 2; size = (size+blocksize-1) / blocksize; size *= blocksize; } break; } } /*@end@*/ } while (fgets(line, sizeof(line), dumpout) != NULL) { g_debug("%s", line); } g_debug("....."); g_debug(_("estimate time for %s level %d: %s"), qdisk, level, walltime_str(timessub(curclock(), start_time))); if(size == (off_t)-1) { errmsg = g_strdup_printf(_("no size line match in %s output"), cmd); g_debug(_("%s for %s"), errmsg, qdisk); g_debug("....."); } else if(size == (off_t)0 && argument->level == 0) { g_debug(_("possible %s problem -- is \"%s\" really empty?"), cmd, argument->dle.disk); g_debug("....."); } g_debug(_("estimate size for %s level %d: %lld KB"), qdisk, level, (long long)size); (void)kill(-tarpid, SIGTERM); g_debug(_("waiting for %s \"%s\" child"), cmd, qdisk); waitpid(tarpid, &wait_status, 0); if (WIFSIGNALED(wait_status)) { strbuf = g_string_new(errmsg); g_string_append_printf(strbuf, "%s terminated with signal %d: see %s", cmd, WTERMSIG(wait_status), dbfn()); g_free(errmsg); errmsg = g_string_free(strbuf, FALSE); exit_status = 1; } else if (WIFEXITED(wait_status)) { if (exit_value[WEXITSTATUS(wait_status)] == 1) { strbuf = g_string_new(errmsg); g_string_append_printf(strbuf, "%s exited with status %d: see %s", cmd, WEXITSTATUS(wait_status), dbfn()); g_free(errmsg); errmsg = g_string_free(strbuf, FALSE); exit_status = 1; } else { /* Normal exit */ } } else { errmsg = g_strdup_printf(_("%s got bad exit: see %s"), cmd, dbfn()); exit_status = 1; } g_debug(_("after %s %s wait"), cmd, qdisk); common_exit: if (errmsg) { g_debug("%s", errmsg); fprintf(stdout, "ERROR %s\n", errmsg); amfree(errmsg); } if (argument->verbose == 0) { if (file_exclude) unlink(file_exclude); if (file_include) unlink(file_include); } g_ptr_array_free_full(argv_ptr); amfree(cmd); amfree(incrname); aclose(nullfd); afclose(dumpout); fprintf(stdout, "%d %lld 1\n", level, (long long)size); } amfree(qdisk); amfree(file_exclude); amfree(file_include); amfree(errmsg); amfree(qerrmsg); amfree(incrname); return; common_error: qerrmsg = quote_string(errmsg); amfree(qdisk); g_debug("%s", errmsg); fprintf(stdout, "ERROR %s\n", qerrmsg); exit_status = 1; amfree(file_exclude); amfree(file_include); amfree(errmsg); amfree(qerrmsg); amfree(incrname); return; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-77'], 'message': '* application-src/ambsdtar.c, application-src/amgtar.c, application-src/amstar.c: Filter option from COMMAND-OPTIONS * common-src/ammessage.c: Add message. git-svn-id: https://svn.code.sf.net/p/amanda/code/amanda/trunk@6483 a8d146d6-cc15-0410-8900-af154a0219e0'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: amgtar_restore( application_argument_t *argument) { char *cmd; GPtrArray *argv_ptr = g_ptr_array_new(); char **env; int j; char *e; char *include_filename = NULL; char *exclude_filename = NULL; if (!gnutar_path) { error(_("GNUTAR-PATH not defined")); } if (!check_exec_for_suid(gnutar_path, FALSE)) { error("'%s' binary is not secure", gnutar_path); } cmd = stralloc(gnutar_path); g_ptr_array_add(argv_ptr, stralloc(gnutar_path)); g_ptr_array_add(argv_ptr, stralloc("--numeric-owner")); if (gnutar_no_unquote) g_ptr_array_add(argv_ptr, stralloc("--no-unquote")); if (gnutar_acls) g_ptr_array_add(argv_ptr, stralloc("--acls")); if (gnutar_selinux) g_ptr_array_add(argv_ptr, stralloc("--selinux")); if (gnutar_xattrs) g_ptr_array_add(argv_ptr, stralloc("--xattrs")); /* ignore trailing zero blocks on input (this was the default until tar-1.21) */ if (argument->ignore_zeros) { g_ptr_array_add(argv_ptr, stralloc("--ignore-zeros")); } if (argument->tar_blocksize) { g_ptr_array_add(argv_ptr, stralloc("--blocking-factor")); g_ptr_array_add(argv_ptr, stralloc(argument->tar_blocksize)); } g_ptr_array_add(argv_ptr, stralloc("-xpGvf")); g_ptr_array_add(argv_ptr, stralloc("-")); if (gnutar_directory) { struct stat stat_buf; if(stat(gnutar_directory, &stat_buf) != 0) { fprintf(stderr,"can not stat directory %s: %s\n", gnutar_directory, strerror(errno)); exit(1); } if (!S_ISDIR(stat_buf.st_mode)) { fprintf(stderr,"%s is not a directory\n", gnutar_directory); exit(1); } if (access(gnutar_directory, W_OK) != 0) { fprintf(stderr, "Can't write to %s: %s\n", gnutar_directory, strerror(errno)); exit(1); } g_ptr_array_add(argv_ptr, stralloc("--directory")); g_ptr_array_add(argv_ptr, stralloc(gnutar_directory)); } g_ptr_array_add(argv_ptr, stralloc("--wildcards")); if (argument->dle.exclude_list && argument->dle.exclude_list->nb_element == 1) { FILE *exclude; char *sdisk; int in_argv; int entry_in_exclude = 0; char line[2*PATH_MAX]; FILE *exclude_list; if (argument->dle.disk) { sdisk = sanitise_filename(argument->dle.disk); } else { sdisk = g_strdup_printf("no_dle-%d", (int)getpid()); } exclude_filename= vstralloc(AMANDA_TMPDIR, "/", "exclude-", sdisk, NULL); exclude_list = fopen(argument->dle.exclude_list->first->name, "r"); exclude = fopen(exclude_filename, "w"); while (fgets(line, 2*PATH_MAX, exclude_list)) { char *escaped; line[strlen(line)-1] = '\0'; /* remove '\n' */ escaped = escape_tar_glob(line, &in_argv); if (in_argv) { g_ptr_array_add(argv_ptr, "--exclude"); g_ptr_array_add(argv_ptr, escaped); } else { fprintf(exclude,"%s\n", escaped); entry_in_exclude++; amfree(escaped); } } fclose(exclude); g_ptr_array_add(argv_ptr, stralloc("--exclude-from")); g_ptr_array_add(argv_ptr, exclude_filename); } if (argument->exclude_list_glob) { g_ptr_array_add(argv_ptr, stralloc("--exclude-from")); g_ptr_array_add(argv_ptr, stralloc(argument->exclude_list_glob)); } { GPtrArray *argv_include = g_ptr_array_new(); FILE *include; char *sdisk; int in_argv; guint i; int entry_in_include = 0; if (argument->dle.disk) { sdisk = sanitise_filename(argument->dle.disk); } else { sdisk = g_strdup_printf("no_dle-%d", (int)getpid()); } include_filename = vstralloc(AMANDA_TMPDIR, "/", "include-", sdisk, NULL); include = fopen(include_filename, "w"); if (argument->dle.include_list && argument->dle.include_list->nb_element == 1) { char line[2*PATH_MAX]; FILE *include_list = fopen(argument->dle.include_list->first->name, "r"); while (fgets(line, 2*PATH_MAX, include_list)) { char *escaped; line[strlen(line)-1] = '\0'; /* remove '\n' */ escaped = escape_tar_glob(line, &in_argv); if (in_argv) { g_ptr_array_add(argv_include, escaped); } else { fprintf(include,"%s\n", escaped); entry_in_include++; amfree(escaped); } } } for (j=1; j< argument->argc; j++) { char *escaped = escape_tar_glob(argument->argv[j], &in_argv); if (in_argv) { g_ptr_array_add(argv_include, escaped); } else { fprintf(include,"%s\n", escaped); entry_in_include++; amfree(escaped); } } fclose(include); if (entry_in_include) { g_ptr_array_add(argv_ptr, stralloc("--files-from")); g_ptr_array_add(argv_ptr, include_filename); } if (argument->include_list_glob) { g_ptr_array_add(argv_ptr, stralloc("--files-from")); g_ptr_array_add(argv_ptr, stralloc(argument->include_list_glob)); } for (i = 0; i < argv_include->len; i++) { g_ptr_array_add(argv_ptr, (char *)g_ptr_array_index(argv_include,i)); } } g_ptr_array_add(argv_ptr, NULL); debug_executing(argv_ptr); env = safe_env(); become_root(); execve(cmd, (char **)argv_ptr->pdata, env); e = strerror(errno); error(_("error [exec %s: %s]"), cmd, e); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': '* Add a /etc/amanda-security.conf file git-svn-id: https://svn.code.sf.net/p/amanda/code/amanda/branches/3_3@6486 a8d146d6-cc15-0410-8900-af154a0219e0'</s>
<s>[INST] Given the following code containing errors, provide 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) { #ifdef GNUTAR int i; char *e; char *dbf; char *cmdline; #endif int good_option; if (argc > 1 && argv && argv[1] && g_str_equal(argv[1], "--version")) { printf("runtar-%s\n", VERSION); return (0); } /* * Configure program for internationalization: * 1) Only set the message locale for now. * 2) Set textdomain for all amanda related programs to "amanda" * We don't want to be forced to support dozens of message catalogs. */ setlocale(LC_MESSAGES, "C"); textdomain("amanda"); safe_fd(-1, 0); safe_cd(); set_pname("runtar"); /* Don't die when child closes pipe */ signal(SIGPIPE, SIG_IGN); dbopen(DBG_SUBDIR_CLIENT); config_init(CONFIG_INIT_CLIENT, NULL); if (argc < 3) { error(_("Need at least 3 arguments\n")); /*NOTREACHED*/ } dbprintf(_("version %s\n"), VERSION); if (strcmp(argv[3], "--create") != 0) { error(_("Can only be used to create tar archives\n")); /*NOTREACHED*/ } #ifndef GNUTAR g_fprintf(stderr,_("gnutar not available on this system.\n")); dbprintf(_("%s: gnutar not available on this system.\n"), argv[0]); dbclose(); return 1; #else /* * Print out version information for tar. */ do { FILE * version_file; char version_buf[80]; if ((version_file = popen(GNUTAR " --version 2>&1", "r")) != NULL) { if (fgets(version_buf, (int)sizeof(version_buf), version_file) != NULL) { dbprintf(_(GNUTAR " version: %s\n"), version_buf); } else { if (ferror(version_file)) { dbprintf(_(GNUTAR " version: Read failure: %s\n"), strerror(errno)); } else { dbprintf(_(GNUTAR " version: Read failure; EOF\n")); } } } else { dbprintf(_(GNUTAR " version: unavailable: %s\n"), strerror(errno)); } } while(0); #ifdef WANT_SETUID_CLIENT check_running_as(RUNNING_AS_CLIENT_LOGIN | RUNNING_AS_UID_ONLY); if (!become_root()) { error(_("error [%s could not become root (is the setuid bit set?)]\n"), get_pname()); /*NOTREACHED*/ } #else check_running_as(RUNNING_AS_CLIENT_LOGIN); #endif /* skip argv[0] */ argc--; argv++; dbprintf(_("config: %s\n"), argv[0]); if (strcmp(argv[0], "NOCONFIG") != 0) dbrename(argv[0], DBG_SUBDIR_CLIENT); argc--; argv++; if (!check_exec_for_suid(GNUTAR, TRUE)) { dbclose(); exit(1); } cmdline = stralloc(GNUTAR); good_option = 0; for (i = 1; argv[i]; i++) { char *quoted; if (good_option <= 0) { if (g_str_has_prefix(argv[i],"--rsh-command") || g_str_has_prefix(argv[i],"--to-command") || g_str_has_prefix(argv[i],"--info-script") || g_str_has_prefix(argv[i],"--new-volume-script") || g_str_has_prefix(argv[i],"--rmt-command") || g_str_has_prefix(argv[i],"--use-compress-program")) { /* Filter potential malicious option */ good_option = 0; } else if (g_str_has_prefix(argv[i],"--create") || g_str_has_prefix(argv[i],"--totals") || g_str_has_prefix(argv[i],"--dereference") || g_str_has_prefix(argv[i],"--no-recursion") || g_str_has_prefix(argv[i],"--one-file-system") || g_str_has_prefix(argv[i],"--incremental") || g_str_has_prefix(argv[i],"--atime-preserve") || g_str_has_prefix(argv[i],"--sparse") || g_str_has_prefix(argv[i],"--ignore-failed-read") || g_str_has_prefix(argv[i],"--numeric-owner")) { /* Accept theses options */ good_option++; } else if (g_str_has_prefix(argv[i],"--blocking-factor") || g_str_has_prefix(argv[i],"--file") || g_str_has_prefix(argv[i],"--directory") || g_str_has_prefix(argv[i],"--exclude") || g_str_has_prefix(argv[i],"--transform") || g_str_has_prefix(argv[i],"--listed-incremental") || g_str_has_prefix(argv[i],"--newer") || g_str_has_prefix(argv[i],"--exclude-from") || g_str_has_prefix(argv[i],"--files-from")) { /* Accept theses options with the following argument */ good_option += 2; } else if (argv[i][0] != '-') { good_option++; } } if (good_option <= 0) { error("error [%s invalid option: %s]", get_pname(), argv[i]); } good_option--; quoted = quote_string(argv[i]); cmdline = vstrextend(&cmdline, " ", quoted, NULL); amfree(quoted); } dbprintf(_("running: %s\n"), cmdline); amfree(cmdline); dbf = dbfn(); if (dbf) { dbf = stralloc(dbf); } dbclose(); execve(GNUTAR, argv, safe_env()); e = strerror(errno); dbreopen(dbf, "more"); amfree(dbf); dbprintf(_("execve of %s failed (%s)\n"), GNUTAR, e); dbclose(); g_fprintf(stderr, _("runtar: could not exec %s: %s\n"), GNUTAR, e); return 1; #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': '* Add a /etc/amanda-security.conf file git-svn-id: https://svn.code.sf.net/p/amanda/code/amanda/branches/3_3@6486 a8d146d6-cc15-0410-8900-af154a0219e0'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int main(int argc, char *argv[]) { GooString *fileName; UnicodeMap *uMap; GooString *ownerPW, *userPW; PDFDoc *doc; char uBuf[8]; char path[1024]; char *p; bool ok; int exitCode; GooList *embeddedFiles = nullptr; int nFiles, nPages, n, i, j; FileSpec *fileSpec; Page *page; Annots *annots; Annot *annot; const GooString *s1; Unicode u; bool isUnicode; Win32Console win32Console(&argc, &argv); exitCode = 99; // parse args ok = parseArgs(argDesc, &argc, argv); if ((doList ? 1 : 0) + ((saveNum != 0) ? 1 : 0) + (saveAll ? 1 : 0) != 1) { ok = false; } if (!ok || argc != 2 || printVersion || printHelp) { fprintf(stderr, "pdfdetach version %s\n", PACKAGE_VERSION); fprintf(stderr, "%s\n", popplerCopyright); fprintf(stderr, "%s\n", xpdfCopyright); if (!printVersion) { printUsage("pdfdetach", "<PDF-file>", argDesc); } goto err0; } fileName = new GooString(argv[1]); // read config file globalParams = new GlobalParams(); if (textEncName[0]) { globalParams->setTextEncoding(textEncName); } // get mapping to output encoding if (!(uMap = globalParams->getTextEncoding())) { error(errConfig, -1, "Couldn't get text encoding"); delete fileName; goto err1; } // open PDF file if (ownerPassword[0] != '\001') { ownerPW = new GooString(ownerPassword); } else { ownerPW = nullptr; } if (userPassword[0] != '\001') { userPW = new GooString(userPassword); } else { userPW = nullptr; } doc = PDFDocFactory().createPDFDoc(*fileName, ownerPW, userPW); if (userPW) { delete userPW; } if (ownerPW) { delete ownerPW; } if (!doc->isOk()) { exitCode = 1; goto err2; } embeddedFiles = new GooList(); for (i = 0; i < doc->getCatalog()->numEmbeddedFiles(); ++i) embeddedFiles->push_back(doc->getCatalog()->embeddedFile(i)); nPages = doc->getCatalog()->getNumPages(); for (i = 0; i < nPages; ++i) { page = doc->getCatalog()->getPage(i + 1); if (!page) continue; annots = page->getAnnots(); if (!annots) break; for (j = 0; j < annots->getNumAnnots(); ++j) { annot = annots->getAnnot(j); if (annot->getType() != Annot::typeFileAttachment) continue; embeddedFiles->push_back(new FileSpec(static_cast<AnnotFileAttachment *>(annot)->getFile())); } } nFiles = embeddedFiles->getLength(); // list embedded files if (doList) { printf("%d embedded files\n", nFiles); for (i = 0; i < nFiles; ++i) { fileSpec = static_cast<FileSpec *>(embeddedFiles->get(i)); printf("%d: ", i+1); s1 = fileSpec->getFileName(); if ((s1->getChar(0) & 0xff) == 0xfe && (s1->getChar(1) & 0xff) == 0xff) { isUnicode = true; j = 2; } else { isUnicode = false; j = 0; } while (j < fileSpec->getFileName()->getLength()) { if (isUnicode) { u = ((s1->getChar(j) & 0xff) << 8) | (s1->getChar(j+1) & 0xff); j += 2; } else { u = pdfDocEncoding[s1->getChar(j) & 0xff]; ++j; } n = uMap->mapUnicode(u, uBuf, sizeof(uBuf)); fwrite(uBuf, 1, n, stdout); } fputc('\n', stdout); } // save all embedded files } else if (saveAll) { for (i = 0; i < nFiles; ++i) { fileSpec = static_cast<FileSpec *>(embeddedFiles->get(i)); if (savePath[0]) { n = strlen(savePath); if (n > (int)sizeof(path) - 2) { n = sizeof(path) - 2; } memcpy(path, savePath, n); path[n] = '/'; p = path + n + 1; } else { p = path; } s1 = fileSpec->getFileName(); if ((s1->getChar(0) & 0xff) == 0xfe && (s1->getChar(1) & 0xff) == 0xff) { isUnicode = true; j = 2; } else { isUnicode = false; j = 0; } while (j < fileSpec->getFileName()->getLength()) { if (isUnicode) { u = ((s1->getChar(j) & 0xff) << 8) | (s1->getChar(j+1) & 0xff); j += 2; } else { u = pdfDocEncoding[s1->getChar(j) & 0xff]; ++j; } n = uMap->mapUnicode(u, uBuf, sizeof(uBuf)); if (p + n >= path + sizeof(path)) break; memcpy(p, uBuf, n); p += n; } *p = '\0'; auto *embFile = fileSpec->getEmbeddedFile(); if (!embFile || !embFile->isOk()) { exitCode = 3; goto err2; } if (!embFile->save(path)) { error(errIO, -1, "Error saving embedded file as '{0:s}'", p); exitCode = 2; goto err2; } } // save an embedded file } else { if (saveNum < 1 || saveNum > nFiles) { error(errCommandLine, -1, "Invalid file number"); goto err2; } fileSpec = static_cast<FileSpec *>(embeddedFiles->get(saveNum - 1)); if (savePath[0]) { p = savePath; } else { p = path; s1 = fileSpec->getFileName(); if ((s1->getChar(0) & 0xff) == 0xfe && (s1->getChar(1) & 0xff) == 0xff) { isUnicode = true; j = 2; } else { isUnicode = false; j = 0; } while (j < fileSpec->getFileName()->getLength()) { if (isUnicode) { u = ((s1->getChar(j) & 0xff) << 8) | (s1->getChar(j+1) & 0xff); j += 2; } else { u = pdfDocEncoding[s1->getChar(j) & 0xff]; ++j; } n = uMap->mapUnicode(u, uBuf, sizeof(uBuf)); if (p + n >= path + sizeof(path)) break; memcpy(p, uBuf, n); p += n; } *p = '\0'; p = path; } auto *embFile = fileSpec->getEmbeddedFile(); if (!embFile || !embFile->isOk()) { exitCode = 3; goto err2; } if (!embFile->save(p)) { error(errIO, -1, "Error saving embedded file as '{0:s}'", p); exitCode = 2; goto err2; } } exitCode = 0; // clean up err2: if (embeddedFiles) deleteGooList<FileSpec>(embeddedFiles); uMap->decRefCnt(); delete doc; err1: delete globalParams; err0: return exitCode; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'pdfdetach: Check for valid file name of embedded file before using it to determine save path. Closes #660'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: vrrp_print_json(void) { FILE *file; element e; struct json_object *array; if (LIST_ISEMPTY(vrrp_data->vrrp)) return; file = fopen ("/tmp/keepalived.json","w"); if (!file) { log_message(LOG_INFO, "Can't open /tmp/keepalived.json (%d: %s)", errno, strerror(errno)); return; } array = json_object_new_array(); for (e = LIST_HEAD(vrrp_data->vrrp); e; ELEMENT_NEXT(e)) { struct json_object *instance_json, *json_stats, *json_data, *vips, *evips, *track_ifp, *track_script; #ifdef _HAVE_FIB_ROUTING_ struct json_object *vroutes, *vrules; #endif element f; vrrp_t *vrrp = ELEMENT_DATA(e); instance_json = json_object_new_object(); json_stats = json_object_new_object(); json_data = json_object_new_object(); vips = json_object_new_array(); evips = json_object_new_array(); track_ifp = json_object_new_array(); track_script = json_object_new_array(); #ifdef _HAVE_FIB_ROUTING_ vroutes = json_object_new_array(); vrules = json_object_new_array(); #endif // Dump data to json json_object_object_add(json_data, "iname", json_object_new_string(vrrp->iname)); json_object_object_add(json_data, "dont_track_primary", json_object_new_int(vrrp->dont_track_primary)); json_object_object_add(json_data, "skip_check_adv_addr", json_object_new_int(vrrp->skip_check_adv_addr)); json_object_object_add(json_data, "strict_mode", json_object_new_int((int)vrrp->strict_mode)); #ifdef _HAVE_VRRP_VMAC_ json_object_object_add(json_data, "vmac_ifname", json_object_new_string(vrrp->vmac_ifname)); #endif // Tracked interfaces are stored in a list if (!LIST_ISEMPTY(vrrp->track_ifp)) { for (f = LIST_HEAD(vrrp->track_ifp); f; ELEMENT_NEXT(f)) { interface_t *ifp = ELEMENT_DATA(f); json_object_array_add(track_ifp, json_object_new_string(ifp->ifname)); } } json_object_object_add(json_data, "track_ifp", track_ifp); // Tracked scripts also if (!LIST_ISEMPTY(vrrp->track_script)) { for (f = LIST_HEAD(vrrp->track_script); f; ELEMENT_NEXT(f)) { tracked_sc_t *tsc = ELEMENT_DATA(f); vrrp_script_t *vscript = tsc->scr; json_object_array_add(track_script, json_object_new_string(cmd_str(&vscript->script))); } } json_object_object_add(json_data, "track_script", track_script); json_object_object_add(json_data, "ifp_ifname", json_object_new_string(vrrp->ifp->ifname)); json_object_object_add(json_data, "master_priority", json_object_new_int(vrrp->master_priority)); json_object_object_add(json_data, "last_transition", json_object_new_double(timeval_to_double(&vrrp->last_transition))); json_object_object_add(json_data, "garp_delay", json_object_new_double(vrrp->garp_delay / TIMER_HZ_FLOAT)); json_object_object_add(json_data, "garp_refresh", json_object_new_int((int)vrrp->garp_refresh.tv_sec)); json_object_object_add(json_data, "garp_rep", json_object_new_int((int)vrrp->garp_rep)); json_object_object_add(json_data, "garp_refresh_rep", json_object_new_int((int)vrrp->garp_refresh_rep)); json_object_object_add(json_data, "garp_lower_prio_delay", json_object_new_int((int)(vrrp->garp_lower_prio_delay / TIMER_HZ))); json_object_object_add(json_data, "garp_lower_prio_rep", json_object_new_int((int)vrrp->garp_lower_prio_rep)); json_object_object_add(json_data, "lower_prio_no_advert", json_object_new_int((int)vrrp->lower_prio_no_advert)); json_object_object_add(json_data, "higher_prio_send_advert", json_object_new_int((int)vrrp->higher_prio_send_advert)); json_object_object_add(json_data, "vrid", json_object_new_int(vrrp->vrid)); json_object_object_add(json_data, "base_priority", json_object_new_int(vrrp->base_priority)); json_object_object_add(json_data, "effective_priority", json_object_new_int(vrrp->effective_priority)); json_object_object_add(json_data, "vipset", json_object_new_boolean(vrrp->vipset)); //Virtual IPs are stored in a list if (!LIST_ISEMPTY(vrrp->vip)) { for (f = LIST_HEAD(vrrp->vip); f; ELEMENT_NEXT(f)) { ip_address_t *vip = ELEMENT_DATA(f); char ipaddr[INET6_ADDRSTRLEN]; inet_ntop(vrrp->family, &(vip->u.sin.sin_addr.s_addr), ipaddr, INET6_ADDRSTRLEN); json_object_array_add(vips, json_object_new_string(ipaddr)); } } json_object_object_add(json_data, "vips", vips); //External VIPs are also stored in a list if (!LIST_ISEMPTY(vrrp->evip)) { for (f = LIST_HEAD(vrrp->evip); f; ELEMENT_NEXT(f)) { ip_address_t *evip = ELEMENT_DATA(f); char ipaddr[INET6_ADDRSTRLEN]; inet_ntop(vrrp->family, &(evip->u.sin.sin_addr.s_addr), ipaddr, INET6_ADDRSTRLEN); json_object_array_add(evips, json_object_new_string(ipaddr)); } } json_object_object_add(json_data, "evips", evips); json_object_object_add(json_data, "promote_secondaries", json_object_new_boolean(vrrp->promote_secondaries)); #ifdef _HAVE_FIB_ROUTING_ // Dump vroutes if (!LIST_ISEMPTY(vrrp->vroutes)) { for (f = LIST_HEAD(vrrp->vroutes); f; ELEMENT_NEXT(f)) { ip_route_t *route = ELEMENT_DATA(f); char *buf = MALLOC(ROUTE_BUF_SIZE); format_iproute(route, buf, ROUTE_BUF_SIZE); json_object_array_add(vroutes, json_object_new_string(buf)); } } json_object_object_add(json_data, "vroutes", vroutes); // Dump vrules if (!LIST_ISEMPTY(vrrp->vrules)) { for (f = LIST_HEAD(vrrp->vrules); f; ELEMENT_NEXT(f)) { ip_rule_t *rule = ELEMENT_DATA(f); char *buf = MALLOC(RULE_BUF_SIZE); format_iprule(rule, buf, RULE_BUF_SIZE); json_object_array_add(vrules, json_object_new_string(buf)); } } json_object_object_add(json_data, "vrules", vrules); #endif json_object_object_add(json_data, "adver_int", json_object_new_double(vrrp->adver_int / TIMER_HZ_FLOAT)); json_object_object_add(json_data, "master_adver_int", json_object_new_double(vrrp->master_adver_int / TIMER_HZ_FLOAT)); json_object_object_add(json_data, "accept", json_object_new_int((int)vrrp->accept)); json_object_object_add(json_data, "nopreempt", json_object_new_boolean(vrrp->nopreempt)); json_object_object_add(json_data, "preempt_delay", json_object_new_int((int)(vrrp->preempt_delay / TIMER_HZ))); json_object_object_add(json_data, "state", json_object_new_int(vrrp->state)); json_object_object_add(json_data, "wantstate", json_object_new_int(vrrp->wantstate)); json_object_object_add(json_data, "version", json_object_new_int(vrrp->version)); if (vrrp->script_backup) json_object_object_add(json_data, "script_backup", json_object_new_string(cmd_str(vrrp->script_backup))); if (vrrp->script_master) json_object_object_add(json_data, "script_master", json_object_new_string(cmd_str(vrrp->script_master))); if (vrrp->script_fault) json_object_object_add(json_data, "script_fault", json_object_new_string(cmd_str(vrrp->script_fault))); if (vrrp->script_stop) json_object_object_add(json_data, "script_stop", json_object_new_string(cmd_str(vrrp->script_stop))); if (vrrp->script) json_object_object_add(json_data, "script", json_object_new_string(cmd_str(vrrp->script))); if (vrrp->script_master_rx_lower_pri) json_object_object_add(json_data, "script_master_rx_lower_pri", json_object_new_string(cmd_str(vrrp->script_master_rx_lower_pri))); json_object_object_add(json_data, "smtp_alert", json_object_new_boolean(vrrp->smtp_alert)); #ifdef _WITH_VRRP_AUTH_ if (vrrp->auth_type) { json_object_object_add(json_data, "auth_type", json_object_new_int(vrrp->auth_type)); if (vrrp->auth_type != VRRP_AUTH_AH) { char auth_data[sizeof(vrrp->auth_data) + 1]; memcpy(auth_data, vrrp->auth_data, sizeof(vrrp->auth_data)); auth_data[sizeof(vrrp->auth_data)] = '\0'; json_object_object_add(json_data, "auth_data", json_object_new_string(auth_data)); } } else json_object_object_add(json_data, "auth_type", json_object_new_int(0)); #endif // Dump stats to json json_object_object_add(json_stats, "advert_rcvd", json_object_new_int64((int64_t)vrrp->stats->advert_rcvd)); json_object_object_add(json_stats, "advert_sent", json_object_new_int64(vrrp->stats->advert_sent)); json_object_object_add(json_stats, "become_master", json_object_new_int64(vrrp->stats->become_master)); json_object_object_add(json_stats, "release_master", json_object_new_int64(vrrp->stats->release_master)); json_object_object_add(json_stats, "packet_len_err", json_object_new_int64((int64_t)vrrp->stats->packet_len_err)); json_object_object_add(json_stats, "advert_interval_err", json_object_new_int64((int64_t)vrrp->stats->advert_interval_err)); json_object_object_add(json_stats, "ip_ttl_err", json_object_new_int64((int64_t)vrrp->stats->ip_ttl_err)); json_object_object_add(json_stats, "invalid_type_rcvd", json_object_new_int64((int64_t)vrrp->stats->invalid_type_rcvd)); json_object_object_add(json_stats, "addr_list_err", json_object_new_int64((int64_t)vrrp->stats->addr_list_err)); json_object_object_add(json_stats, "invalid_authtype", json_object_new_int64(vrrp->stats->invalid_authtype)); #ifdef _WITH_VRRP_AUTH_ json_object_object_add(json_stats, "authtype_mismatch", json_object_new_int64(vrrp->stats->authtype_mismatch)); json_object_object_add(json_stats, "auth_failure", json_object_new_int64(vrrp->stats->auth_failure)); #endif json_object_object_add(json_stats, "pri_zero_rcvd", json_object_new_int64((int64_t)vrrp->stats->pri_zero_rcvd)); json_object_object_add(json_stats, "pri_zero_sent", json_object_new_int64((int64_t)vrrp->stats->pri_zero_sent)); // Add both json_data and json_stats to main instance_json json_object_object_add(instance_json, "data", json_data); json_object_object_add(instance_json, "stats", json_stats); // Add instance_json to main array json_object_array_add(array, instance_json); } fprintf(file, "%s", json_object_to_json_string(array)); fclose(file); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'When opening files for write, ensure they aren't symbolic links Issue #1048 identified that if, for example, a non privileged user created a symbolic link from /etc/keepalvied.data to /etc/passwd, writing to /etc/keepalived.data (which could be invoked via DBus) would cause /etc/passwd to be overwritten. This commit stops keepalived writing to pathnames where the ultimate component is a symbolic link, by setting O_NOFOLLOW whenever opening a file for writing. This might break some setups, where, for example, /etc/keepalived.data was a symbolic link to /home/fred/keepalived.data. If this was the case, instead create a symbolic link from /home/fred/keepalived.data to /tmp/keepalived.data, so that the file is still accessible via /home/fred/keepalived.data. There doesn't appear to be a way around this backward incompatibility, since even checking if the pathname is a symbolic link prior to opening for writing would create a race condition. Signed-off-by: Quentin Armitage <quentin@armitage.org.uk>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: set_umask(const char *optarg) { long umask_long; mode_t umask_val; char *endptr; umask_long = strtoll(optarg, &endptr, 0); if (*endptr || umask_long < 0 || umask_long & ~0777L) { fprintf(stderr, "Invalid --umask option %s", optarg); return; } umask_val = umask_long & 0777; umask(umask_val); umask_cmdline = true; return umask_val; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Fix compile warning introduced in commit c6247a9 Commit c6247a9 - "Add command line and configuration option to set umask" introduced a compile warning, although the code would have worked OK. Signed-off-by: Quentin Armitage <quentin@armitage.org.uk>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: keepalived_main(int argc, char **argv) { bool report_stopped = true; struct utsname uname_buf; char *end; int exit_code = KEEPALIVED_EXIT_OK; /* Ensure time_now is set. We then don't have to check anywhere * else if it is set. */ set_time_now(); /* Save command line options in case need to log them later */ save_cmd_line_options(argc, argv); /* Init debugging level */ debug = 0; /* We are the parent process */ #ifndef _DEBUG_ prog_type = PROG_TYPE_PARENT; #endif /* Initialise daemon_mode */ #ifdef _WITH_VRRP_ __set_bit(DAEMON_VRRP, &daemon_mode); #endif #ifdef _WITH_LVS_ __set_bit(DAEMON_CHECKERS, &daemon_mode); #endif #ifdef _WITH_BFD_ __set_bit(DAEMON_BFD, &daemon_mode); #endif /* Set default file creation mask */ umask(022); /* Open log with default settings so we can log initially */ openlog(PACKAGE_NAME, LOG_PID, log_facility); #ifdef _MEM_CHECK_ mem_log_init(PACKAGE_NAME, "Parent process"); #endif /* Some functionality depends on kernel version, so get the version here */ if (uname(&uname_buf)) log_message(LOG_INFO, "Unable to get uname() information - error %d", errno); else { os_major = (unsigned)strtoul(uname_buf.release, &end, 10); if (*end != '.') os_major = 0; else { os_minor = (unsigned)strtoul(end + 1, &end, 10); if (*end != '.') os_major = 0; else { if (!isdigit(end[1])) os_major = 0; else os_release = (unsigned)strtoul(end + 1, &end, 10); } } if (!os_major) log_message(LOG_INFO, "Unable to parse kernel version %s", uname_buf.release); /* config_id defaults to hostname */ if (!config_id) { end = strchrnul(uname_buf.nodename, '.'); config_id = MALLOC((size_t)(end - uname_buf.nodename) + 1); strncpy(config_id, uname_buf.nodename, (size_t)(end - uname_buf.nodename)); config_id[end - uname_buf.nodename] = '\0'; } } /* * Parse command line and set debug level. * bits 0..7 reserved by main.c */ if (parse_cmdline(argc, argv)) { closelog(); if (!__test_bit(NO_SYSLOG_BIT, &debug)) openlog(PACKAGE_NAME, LOG_PID | ((__test_bit(LOG_CONSOLE_BIT, &debug)) ? LOG_CONS : 0) , log_facility); } if (__test_bit(LOG_CONSOLE_BIT, &debug)) enable_console_log(); #ifdef GIT_COMMIT log_message(LOG_INFO, "Starting %s, git commit %s", version_string, GIT_COMMIT); #else log_message(LOG_INFO, "Starting %s", version_string); #endif /* Handle any core file requirements */ core_dump_init(); if (os_major) { if (KERNEL_VERSION(os_major, os_minor, os_release) < LINUX_VERSION_CODE) { /* keepalived was build for a later kernel version */ log_message(LOG_INFO, "WARNING - keepalived was build for newer Linux %d.%d.%d, running on %s %s %s", (LINUX_VERSION_CODE >> 16) & 0xff, (LINUX_VERSION_CODE >> 8) & 0xff, (LINUX_VERSION_CODE ) & 0xff, uname_buf.sysname, uname_buf.release, uname_buf.version); } else { /* keepalived was build for a later kernel version */ log_message(LOG_INFO, "Running on %s %s %s (built for Linux %d.%d.%d)", uname_buf.sysname, uname_buf.release, uname_buf.version, (LINUX_VERSION_CODE >> 16) & 0xff, (LINUX_VERSION_CODE >> 8) & 0xff, (LINUX_VERSION_CODE ) & 0xff); } } #ifndef _DEBUG_ log_command_line(0); #endif /* Check we can read the configuration file(s). NOTE: the working directory will be / if we forked, but will be the current working directory when keepalived was run if we haven't forked. This means that if any config file names are not absolute file names, the behaviour will be different depending on whether we forked or not. */ if (!check_conf_file(conf_file)) { if (__test_bit(CONFIG_TEST_BIT, &debug)) config_test_exit(); exit_code = KEEPALIVED_EXIT_NO_CONFIG; goto end; } global_data = alloc_global_data(); global_data->umask = umask_val; read_config_file(); init_global_data(global_data, NULL); #if HAVE_DECL_CLONE_NEWNET if (override_namespace) { if (global_data->network_namespace) { log_message(LOG_INFO, "Overriding config net_namespace '%s' with command line namespace '%s'", global_data->network_namespace, override_namespace); FREE(global_data->network_namespace); } global_data->network_namespace = override_namespace; override_namespace = NULL; } #endif if (!__test_bit(CONFIG_TEST_BIT, &debug) && (global_data->instance_name #if HAVE_DECL_CLONE_NEWNET || global_data->network_namespace #endif )) { if ((syslog_ident = make_syslog_ident(PACKAGE_NAME))) { log_message(LOG_INFO, "Changing syslog ident to %s", syslog_ident); closelog(); openlog(syslog_ident, LOG_PID | ((__test_bit(LOG_CONSOLE_BIT, &debug)) ? LOG_CONS : 0), log_facility); } else log_message(LOG_INFO, "Unable to change syslog ident"); use_pid_dir = true; open_log_file(log_file_name, NULL, #if HAVE_DECL_CLONE_NEWNET global_data->network_namespace, #else NULL, #endif global_data->instance_name); } /* Initialise pointer to child finding function */ set_child_finder_name(find_keepalived_child_name); if (!__test_bit(CONFIG_TEST_BIT, &debug)) { if (use_pid_dir) { /* Create the directory for pid files */ create_pid_dir(); } } #if HAVE_DECL_CLONE_NEWNET if (global_data->network_namespace) { if (global_data->network_namespace && !set_namespaces(global_data->network_namespace)) { log_message(LOG_ERR, "Unable to set network namespace %s - exiting", global_data->network_namespace); goto end; } } #endif if (!__test_bit(CONFIG_TEST_BIT, &debug)) { if (global_data->instance_name) { if (!main_pidfile && (main_pidfile = make_pidfile_name(KEEPALIVED_PID_DIR KEEPALIVED_PID_FILE, global_data->instance_name, PID_EXTENSION))) free_main_pidfile = true; #ifdef _WITH_LVS_ if (!checkers_pidfile && (checkers_pidfile = make_pidfile_name(KEEPALIVED_PID_DIR CHECKERS_PID_FILE, global_data->instance_name, PID_EXTENSION))) free_checkers_pidfile = true; #endif #ifdef _WITH_VRRP_ if (!vrrp_pidfile && (vrrp_pidfile = make_pidfile_name(KEEPALIVED_PID_DIR VRRP_PID_FILE, global_data->instance_name, PID_EXTENSION))) free_vrrp_pidfile = true; #endif #ifdef _WITH_BFD_ if (!bfd_pidfile && (bfd_pidfile = make_pidfile_name(KEEPALIVED_PID_DIR VRRP_PID_FILE, global_data->instance_name, PID_EXTENSION))) free_bfd_pidfile = true; #endif } if (use_pid_dir) { if (!main_pidfile) main_pidfile = KEEPALIVED_PID_DIR KEEPALIVED_PID_FILE PID_EXTENSION; #ifdef _WITH_LVS_ if (!checkers_pidfile) checkers_pidfile = KEEPALIVED_PID_DIR CHECKERS_PID_FILE PID_EXTENSION; #endif #ifdef _WITH_VRRP_ if (!vrrp_pidfile) vrrp_pidfile = KEEPALIVED_PID_DIR VRRP_PID_FILE PID_EXTENSION; #endif #ifdef _WITH_BFD_ if (!bfd_pidfile) bfd_pidfile = KEEPALIVED_PID_DIR BFD_PID_FILE PID_EXTENSION; #endif } else { if (!main_pidfile) main_pidfile = PID_DIR KEEPALIVED_PID_FILE PID_EXTENSION; #ifdef _WITH_LVS_ if (!checkers_pidfile) checkers_pidfile = PID_DIR CHECKERS_PID_FILE PID_EXTENSION; #endif #ifdef _WITH_VRRP_ if (!vrrp_pidfile) vrrp_pidfile = PID_DIR VRRP_PID_FILE PID_EXTENSION; #endif #ifdef _WITH_BFD_ if (!bfd_pidfile) bfd_pidfile = PID_DIR BFD_PID_FILE PID_EXTENSION; #endif } /* Check if keepalived is already running */ if (keepalived_running(daemon_mode)) { log_message(LOG_INFO, "daemon is already running"); report_stopped = false; goto end; } } /* daemonize process */ if (!__test_bit(DONT_FORK_BIT, &debug) && xdaemon(false, false, true) > 0) { closelog(); FREE_PTR(config_id); FREE_PTR(orig_core_dump_pattern); close_std_fd(); exit(0); } #ifdef _MEM_CHECK_ enable_mem_log_termination(); #endif if (__test_bit(CONFIG_TEST_BIT, &debug)) { validate_config(); config_test_exit(); } /* write the father's pidfile */ if (!pidfile_write(main_pidfile, getpid())) goto end; /* Create the master thread */ master = thread_make_master(); /* Signal handling initialization */ signal_init(); /* Init daemon */ if (!start_keepalived()) log_message(LOG_INFO, "Warning - keepalived has no configuration to run"); initialise_debug_options(); #ifdef THREAD_DUMP register_parent_thread_addresses(); #endif /* Launch the scheduling I/O multiplexer */ launch_thread_scheduler(master); /* Finish daemon process */ stop_keepalived(); #ifdef THREAD_DUMP deregister_thread_addresses(); #endif /* * Reached when terminate signal catched. * finally return from system */ end: if (report_stopped) { #ifdef GIT_COMMIT log_message(LOG_INFO, "Stopped %s, git commit %s", version_string, GIT_COMMIT); #else log_message(LOG_INFO, "Stopped %s", version_string); #endif } #if HAVE_DECL_CLONE_NEWNET if (global_data && global_data->network_namespace) clear_namespaces(); #endif if (use_pid_dir) remove_pid_dir(); /* Restore original core_pattern if necessary */ if (orig_core_dump_pattern) update_core_dump_pattern(orig_core_dump_pattern); free_parent_mallocs_startup(false); free_parent_mallocs_exit(); free_global_data(global_data); closelog(); #ifndef _MEM_CHECK_LOG_ FREE_PTR(syslog_ident); #else if (syslog_ident) free(syslog_ident); #endif close_std_fd(); exit(exit_code); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Disable fopen_safe() append mode by default If a non privileged user creates /tmp/keepalived.log and has it open for read (e.g. tail -f), then even though keepalived will change the owner to root and remove all read/write permissions from non owners, the application which already has the file open will be able to read the added log entries. Accordingly, opening a file in append mode is disabled by default, and only enabled if --enable-smtp-alert-debug or --enable-log-file (which are debugging options and unset by default) are enabled. This should further alleviate security concerns related to CVE-2018-19046. Signed-off-by: Quentin Armitage <quentin@armitage.org.uk>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: start_bfd_child(void) { #ifndef _DEBUG_ pid_t pid; int ret; char *syslog_ident; /* Initialize child process */ if (log_file_name) flush_log_file(); pid = fork(); if (pid < 0) { log_message(LOG_INFO, "BFD child process: fork error(%m)"); return -1; } else if (pid) { bfd_child = pid; log_message(LOG_INFO, "Starting BFD child process, pid=%d", pid); /* Start respawning thread */ thread_add_child(master, bfd_respawn_thread, NULL, pid, TIMER_NEVER); return 0; } prctl(PR_SET_PDEATHSIG, SIGTERM); prog_type = PROG_TYPE_BFD; /* Close the read end of the event notification pipes */ #ifdef _WITH_VRRP_ close(bfd_vrrp_event_pipe[0]); #endif #ifdef _WITH_LVS_ close(bfd_checker_event_pipe[0]); #endif initialise_debug_options(); if ((global_data->instance_name #if HAVE_DECL_CLONE_NEWNET || global_data->network_namespace #endif ) && (bfd_syslog_ident = make_syslog_ident(PROG_BFD))) syslog_ident = bfd_syslog_ident; else syslog_ident = PROG_BFD; /* Opening local BFD syslog channel */ if (!__test_bit(NO_SYSLOG_BIT, &debug)) openlog(syslog_ident, LOG_PID | ((__test_bit(LOG_CONSOLE_BIT, &debug)) ? LOG_CONS : 0) , (log_facility==LOG_DAEMON) ? LOG_LOCAL2 : log_facility); if (log_file_name) open_log_file(log_file_name, "bfd", #if HAVE_DECL_CLONE_NEWNET global_data->network_namespace, #else NULL, #endif global_data->instance_name); #ifdef _MEM_CHECK_ mem_log_init(PROG_BFD, "BFD child process"); #endif free_parent_mallocs_startup(true); /* Clear any child finder functions set in parent */ set_child_finder_name(NULL); /* Child process part, write pidfile */ if (!pidfile_write(bfd_pidfile, getpid())) { /* Fatal error */ log_message(LOG_INFO, "BFD child process: cannot write pidfile"); exit(0); } /* Create the new master thread */ thread_destroy_master(master); master = thread_make_master(); /* change to / dir */ ret = chdir("/"); if (ret < 0) { log_message(LOG_INFO, "BFD child process: error chdir"); } /* Set mask */ umask(0); #endif /* If last process died during a reload, we can get there and we * don't want to loop again, because we're not reloading anymore. */ UNSET_RELOAD; #ifndef _DEBUG_ /* Signal handling initialization */ bfd_signal_init(); #endif /* Start BFD daemon */ start_bfd(NULL); #ifdef _DEBUG_ return 0; #else #ifdef THREAD_DUMP register_bfd_thread_addresses(); #endif /* Launch the scheduling I/O multiplexer */ launch_thread_scheduler(master); #ifdef THREAD_DUMP deregister_thread_addresses(); #endif /* Finish BFD daemon process */ stop_bfd(EXIT_SUCCESS); /* unreachable */ exit(EXIT_SUCCESS); #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Disable fopen_safe() append mode by default If a non privileged user creates /tmp/keepalived.log and has it open for read (e.g. tail -f), then even though keepalived will change the owner to root and remove all read/write permissions from non owners, the application which already has the file open will be able to read the added log entries. Accordingly, opening a file in append mode is disabled by default, and only enabled if --enable-smtp-alert-debug or --enable-log-file (which are debugging options and unset by default) are enabled. This should further alleviate security concerns related to CVE-2018-19046. Signed-off-by: Quentin Armitage <quentin@armitage.org.uk>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: rf64_read_header (SF_PRIVATE *psf, int *blockalign, int *framesperblock) { WAVLIKE_PRIVATE *wpriv ; WAV_FMT *wav_fmt ; sf_count_t riff_size = 0, frame_count = 0, ds64_datalength = 0 ; uint32_t marks [2], marker, chunk_size, parsestage = 0 ; int error, done = 0, format = 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, "pmmm", 0, &marker, marks, marks + 1) ; if (marker != RF64_MARKER || marks [1] != WAVE_MARKER) return SFE_RF64_NOT_RF64 ; if (marks [0] == FFFF_MARKER) psf_log_printf (psf, "%M\n %M\n", RF64_MARKER, WAVE_MARKER) ; else psf_log_printf (psf, "%M : 0x%x (should be 0xFFFFFFFF)\n %M\n", RF64_MARKER, WAVE_MARKER) ; while (NOT (done)) { marker = chunk_size = 0 ; psf_binheader_readf (psf, "em4", &marker, &chunk_size) ; if (marker == 0) { sf_count_t pos = psf_ftell (psf) ; psf_log_printf (psf, "Have 0 marker at position %D (0x%x).\n", pos, pos) ; break ; } ; psf_store_read_chunk_u32 (&psf->rchunks, marker, psf_ftell (psf), chunk_size) ; switch (marker) { case ds64_MARKER : if (parsestage & HAVE_ds64) { psf_log_printf (psf, "*** Second 'ds64' chunk?\n") ; break ; } ; { unsigned int table_len, bytesread ; /* Read ds64 sizes (3 8-byte words). */ bytesread = psf_binheader_readf (psf, "888", &riff_size, &ds64_datalength, &frame_count) ; /* Read table length. */ bytesread += psf_binheader_readf (psf, "4", &table_len) ; /* Skip table for now. (this was "table_len + 4", why?) */ bytesread += psf_binheader_readf (psf, "j", table_len) ; if (chunk_size == bytesread) psf_log_printf (psf, "%M : %u\n", marker, chunk_size) ; else if (chunk_size >= bytesread + 4) { unsigned int next ; psf_binheader_readf (psf, "m", &next) ; if (next == fmt_MARKER) { psf_log_printf (psf, "%M : %u (should be %u)\n", marker, chunk_size, bytesread) ; psf_binheader_readf (psf, "j", -4) ; } else { psf_log_printf (psf, "%M : %u\n", marker, chunk_size) ; psf_binheader_readf (psf, "j", chunk_size - bytesread - 4) ; } ; } ; if (psf->filelength != riff_size + 8) psf_log_printf (psf, " Riff size : %D (should be %D)\n", riff_size, psf->filelength - 8) ; else psf_log_printf (psf, " Riff size : %D\n", riff_size) ; psf_log_printf (psf, " Data size : %D\n", ds64_datalength) ; psf_log_printf (psf, " Frames : %D\n", frame_count) ; psf_log_printf (psf, " Table length : %u\n", table_len) ; } ; parsestage |= HAVE_ds64 ; break ; case fmt_MARKER: psf_log_printf (psf, "%M : %u\n", marker, chunk_size) ; if ((error = wavlike_read_fmt_chunk (psf, chunk_size)) != 0) return error ; format = wav_fmt->format ; parsestage |= HAVE_fmt ; break ; case bext_MARKER : if ((error = wavlike_read_bext_chunk (psf, chunk_size)) != 0) return error ; parsestage |= HAVE_bext ; break ; case cart_MARKER : if ((error = wavlike_read_cart_chunk (psf, chunk_size)) != 0) return error ; parsestage |= HAVE_cart ; break ; case INFO_MARKER : case LIST_MARKER : if ((error = wavlike_subchunk_parse (psf, marker, chunk_size)) != 0) return error ; parsestage |= HAVE_other ; break ; case PEAK_MARKER : if ((parsestage & (HAVE_ds64 | HAVE_fmt)) != (HAVE_ds64 | HAVE_fmt)) return SFE_RF64_PEAK_B4_FMT ; parsestage |= HAVE_PEAK ; psf_log_printf (psf, "%M : %u\n", marker, chunk_size) ; if ((error = wavlike_read_peak_chunk (psf, chunk_size)) != 0) return error ; psf->peak_info->peak_loc = ((parsestage & HAVE_data) == 0) ? SF_PEAK_START : SF_PEAK_END ; break ; case data_MARKER : /* see wav for more sophisticated parsing -> implement state machine with parsestage */ if (HAVE_CHUNK (HAVE_ds64)) { if (chunk_size == 0xffffffff) psf_log_printf (psf, "%M : 0x%x\n", marker, chunk_size) ; else psf_log_printf (psf, "%M : 0x%x (should be 0xffffffff\n", marker, chunk_size) ; psf->datalength = ds64_datalength ; } else { if (chunk_size == 0xffffffff) { psf_log_printf (psf, "%M : 0x%x\n", marker, chunk_size) ; psf_log_printf (psf, " *** Data length not specified no 'ds64' chunk.\n") ; } else { psf_log_printf (psf, "%M : 0x%x\n**** Weird, RF64 file without a 'ds64' chunk and no valid 'data' size.\n", marker, chunk_size) ; psf->datalength = chunk_size ; } ; } ; psf->dataoffset = psf_ftell (psf) ; if (psf->dataoffset > 0) { if (chunk_size == 0 && riff_size == 8 && psf->filelength > 44) { psf_log_printf (psf, " *** Looks like a WAV file which wasn't closed properly. Fixing it.\n") ; psf->datalength = psf->filelength - psf->dataoffset ; } ; /* Only set dataend if there really is data at the end. */ if (psf->datalength + psf->dataoffset < psf->filelength) psf->dataend = psf->datalength + psf->dataoffset ; if (NOT (psf->sf.seekable) || psf->dataoffset < 0) break ; /* Seek past data and continue reading header. */ psf_fseek (psf, psf->datalength, SEEK_CUR) ; if (psf_ftell (psf) != psf->datalength + psf->dataoffset) psf_log_printf (psf, " *** psf_fseek past end error ***\n") ; } ; break ; case JUNK_MARKER : case PAD_MARKER : psf_log_printf (psf, "%M : %d\n", marker, chunk_size) ; psf_binheader_readf (psf, "j", chunk_size) ; break ; default : if (chunk_size >= 0xffff0000) { psf_log_printf (psf, "*** Unknown chunk marker (%X) at position %D with length %u. Exiting parser.\n", marker, psf_ftell (psf) - 8, chunk_size) ; done = SF_TRUE ; break ; } ; if (isprint ((marker >> 24) & 0xFF) && isprint ((marker >> 16) & 0xFF) && isprint ((marker >> 8) & 0xFF) && isprint (marker & 0xFF)) { psf_log_printf (psf, "*** %M : %d (unknown marker)\n", marker, chunk_size) ; psf_binheader_readf (psf, "j", chunk_size) ; break ; } ; if (psf_ftell (psf) & 0x03) { psf_log_printf (psf, " Unknown chunk marker at position 0x%x. Resynching.\n", chunk_size - 4) ; psf_binheader_readf (psf, "j", -3) ; break ; } ; psf_log_printf (psf, "*** Unknown chunk marker (0x%X) at position 0x%X. Exiting parser.\n", marker, psf_ftell (psf) - 4) ; done = SF_TRUE ; break ; } ; /* switch (marker) */ /* The 'data' chunk, a chunk size of 0xffffffff means that the 'data' chunk size ** is actually given by the ds64_datalength field. */ if (marker != data_MARKER && chunk_size >= psf->filelength) { psf_log_printf (psf, "*** Chunk size %u > file length %D. Exiting parser.\n", chunk_size, psf->filelength) ; break ; } ; if (psf_ftell (psf) >= psf->filelength - SIGNED_SIZEOF (marker)) { psf_log_printf (psf, "End\n") ; break ; } ; } ; if (psf->dataoffset <= 0) return SFE_RF64_NO_DATA ; if (psf->sf.channels < 1) return SFE_CHANNEL_COUNT_ZERO ; if (psf->sf.channels >= SF_MAX_CHANNELS) return SFE_CHANNEL_COUNT ; /* WAVs can be little or big endian */ psf->endian = psf->rwf_endian ; psf_fseek (psf, psf->dataoffset, SEEK_SET) ; if (psf->is_pipe == 0) { /* ** Check for 'wvpk' at the start of the DATA section. Not able to ** handle this. */ psf_binheader_readf (psf, "4", &marker) ; if (marker == wvpk_MARKER || marker == OggS_MARKER) return SFE_WAV_WVPK_DATA ; } ; /* Seek to start of DATA section. */ 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 ; } ; if (frame_count != psf->sf.frames) psf_log_printf (psf, "*** Calculated frame count %d does not match value from 'ds64' chunk of %d.\n", psf->sf.frames, frame_count) ; switch (format) { case WAVE_FORMAT_EXTENSIBLE : /* with WAVE_FORMAT_EXTENSIBLE the psf->sf.format field is already set. We just have to set the major to rf64 */ psf->sf.format = (psf->sf.format & ~SF_FORMAT_TYPEMASK) | SF_FORMAT_RF64 ; if (psf->sf.format == (SF_FORMAT_WAVEX | SF_FORMAT_MS_ADPCM)) { *blockalign = wav_fmt->msadpcm.blockalign ; *framesperblock = wav_fmt->msadpcm.samplesperblock ; } ; break ; case WAVE_FORMAT_PCM : psf->sf.format = SF_FORMAT_RF64 | u_bitwidth_to_subformat (psf->bytewidth * 8) ; break ; case WAVE_FORMAT_MULAW : case IBM_FORMAT_MULAW : psf->sf.format = (SF_FORMAT_RF64 | SF_FORMAT_ULAW) ; break ; case WAVE_FORMAT_ALAW : case IBM_FORMAT_ALAW : psf->sf.format = (SF_FORMAT_RF64 | SF_FORMAT_ALAW) ; break ; case WAVE_FORMAT_MS_ADPCM : psf->sf.format = (SF_FORMAT_RF64 | 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_RF64 | SF_FORMAT_IMA_ADPCM) ; *blockalign = wav_fmt->ima.blockalign ; *framesperblock = wav_fmt->ima.samplesperblock ; break ; case WAVE_FORMAT_GSM610 : psf->sf.format = (SF_FORMAT_RF64 | SF_FORMAT_GSM610) ; break ; case WAVE_FORMAT_IEEE_FLOAT : psf->sf.format = SF_FORMAT_RF64 ; psf->sf.format |= (psf->bytewidth == 8) ? SF_FORMAT_DOUBLE : SF_FORMAT_FLOAT ; break ; case WAVE_FORMAT_G721_ADPCM : psf->sf.format = SF_FORMAT_RF64 | SF_FORMAT_G721_32 ; break ; default : return SFE_UNIMPLEMENTED ; } ; if (wpriv->fmt_is_broken) wavlike_analyze (psf) ; /* Only set the format endian-ness if its non-standard big-endian. */ if (psf->endian == SF_ENDIAN_BIG) psf->sf.format |= SF_ENDIAN_BIG ; return 0 ; } /* rf64_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>