text
stringlengths
481
107k
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: read_gif(Gif_Reader *grr, int read_flags, const char* landmark, Gif_ReadErrorHandler handler) { Gif_Stream *gfs; Gif_Image *gfi; Gif_Context gfc; int unknown_block_type = 0; if (gifgetc(grr) != 'G' || gifgetc(grr) != 'I' || gifgetc(grr) != 'F') return 0; (void)gifgetc(grr); (void)gifgetc(grr); (void)gifgetc(grr); gfs = Gif_NewStream(); gfi = Gif_NewImage(); gfc.stream = gfs; gfc.prefix = Gif_NewArray(Gif_Code, GIF_MAX_CODE); gfc.suffix = Gif_NewArray(uint8_t, GIF_MAX_CODE); gfc.length = Gif_NewArray(uint16_t, GIF_MAX_CODE); gfc.handler = handler; gfc.gfi = gfi; gfc.errors[0] = gfc.errors[1] = 0; if (!gfs || !gfi || !gfc.prefix || !gfc.suffix || !gfc.length) goto done; gfs->landmark = landmark; GIF_DEBUG(("\nGIF ")); if (!read_logical_screen_descriptor(gfs, grr)) goto done; GIF_DEBUG(("logscrdesc ")); while (!gifeof(grr)) { uint8_t block = gifgetbyte(grr); switch (block) { case ',': /* image block */ GIF_DEBUG(("imageread %d ", gfs->nimages)); gfi->identifier = last_name; last_name = 0; if (!Gif_AddImage(gfs, gfi)) goto done; else if (!read_image(grr, &gfc, gfi, read_flags)) { Gif_RemoveImage(gfs, gfs->nimages - 1); goto done; } gfc.gfi = gfi = Gif_NewImage(); if (!gfi) goto done; break; case ';': /* terminator */ GIF_DEBUG(("term\n")); goto done; case '!': /* extension */ block = gifgetbyte(grr); GIF_DEBUG(("ext(0x%02X) ", block)); switch (block) { case 0xF9: read_graphic_control_extension(&gfc, gfi, grr); break; case 0xCE: last_name = suck_data(last_name, 0, grr); break; case 0xFE: if (!read_comment_extension(gfi, grr)) goto done; break; case 0xFF: read_application_extension(&gfc, grr); break; default: read_unknown_extension(&gfc, grr, block, 0, 0); break; } break; default: if (!unknown_block_type) { char buf[256]; sprintf(buf, "unknown block type %d at file offset %u", block, grr->pos - 1); gif_read_error(&gfc, 1, buf); unknown_block_type = 1; } break; } } done: /* Move comments and extensions after last image into stream. */ if (gfs && gfi) { Gif_Extension* gfex; gfs->end_comment = gfi->comment; gfi->comment = 0; gfs->end_extension_list = gfi->extension_list; gfi->extension_list = 0; for (gfex = gfs->end_extension_list; gfex; gfex = gfex->next) gfex->image = NULL; } Gif_DeleteImage(gfi); Gif_DeleteArray(last_name); Gif_DeleteArray(gfc.prefix); Gif_DeleteArray(gfc.suffix); Gif_DeleteArray(gfc.length); gfc.gfi = 0; if (gfs) gfs->errors = gfc.errors[1]; if (gfs && gfc.errors[1] == 0 && !(read_flags & GIF_READ_TRAILING_GARBAGE_OK) && !grr->eofer(grr)) gif_read_error(&gfc, 0, "trailing garbage after GIF ignored"); /* finally, export last message */ gif_read_error(&gfc, -1, 0); return gfs; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fix use-after-free problems reported in #114.'</s>
<s>[INST] Given the following code containing errors, provide 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 ZipTest::testCrcAndSizeAfterData() { std::string testFile = getTestFile("data", "data.zip"); std::ifstream inp(testFile.c_str(), std::ios::binary); assert (inp.good()); Decompress dec(inp, Poco::Path()); dec.EError += Poco::Delegate<ZipTest, std::pair<const Poco::Zip::ZipLocalFileHeader, const std::string> >(this, &ZipTest::onDecompressError); dec.decompressAllFiles(); dec.EError -= Poco::Delegate<ZipTest, std::pair<const Poco::Zip::ZipLocalFileHeader, const std::string> >(this, &ZipTest::onDecompressError); assert (_errCnt == 0); assert (!dec.mapping().empty()); } ; 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::testDirectory() { std::ofstream out("pocobin.zip", std::ios::binary); Poco::File aFile("some/"); if (aFile.exists()) aFile.remove(true); Poco::File aDir("some/recursive/dir/"); aDir.createDirectories(); Poco::File aDir2("some/other/recursive/dir/"); aDir2.createDirectories(); Poco::File aF("some/recursive/dir/test.file"); aF.createFile(); Poco::FileOutputStream fos(aF.path()); fos << "just some test data"; fos.close(); Poco::Path theFile(aFile.path()); theFile.makeDirectory(); Compress c(out, true); c.addRecursive(theFile, ZipCommon::CL_MAXIMUM, false, theFile); ZipArchive a(c.close()); } ; 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 void automount_enter_runnning(Automount *a) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; struct stat st; int r; assert(a); /* If the user masked our unit in the meantime, fail */ if (UNIT(a)->load_state != UNIT_LOADED) { log_unit_error(UNIT(a), "Suppressing automount event since unit is no longer loaded."); goto fail; } /* We don't take mount requests anymore if we are supposed to * shut down anyway */ if (unit_stop_pending(UNIT(a))) { log_unit_debug(UNIT(a), "Suppressing automount request since unit stop is scheduled."); automount_send_ready(a, a->tokens, -EHOSTDOWN); automount_send_ready(a, a->expire_tokens, -EHOSTDOWN); return; } mkdir_p_label(a->where, a->directory_mode); /* Before we do anything, let's see if somebody is playing games with us? */ if (lstat(a->where, &st) < 0) { log_unit_warning_errno(UNIT(a), errno, "Failed to stat automount point: %m"); goto fail; } if (!S_ISDIR(st.st_mode) || st.st_dev != a->dev_id) log_unit_info(UNIT(a), "Automount point already active?"); else { Unit *trigger; trigger = UNIT_TRIGGER(UNIT(a)); if (!trigger) { log_unit_error(UNIT(a), "Unit to trigger vanished."); goto fail; } r = manager_add_job(UNIT(a)->manager, JOB_START, trigger, JOB_REPLACE, &error, NULL); if (r < 0) { log_unit_warning(UNIT(a), "Failed to queue mount startup job: %s", bus_error_message(&error, r)); goto fail; } } automount_set_state(a, AUTOMOUNT_RUNNING); return; fail: automount_enter_dead(a, AUTOMOUNT_FAILURE_RESOURCES); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'automount: ack automount requests even when already mounted (#5916) If a process accesses an autofs filesystem while systemd is in the middle of starting the mount unit on top of it, it is possible for the autofs_ptype_missing_direct request from the kernel to be received after the mount unit has been fully started: systemd forks and execs mount ... ... access autofs, blocks mount exits ... systemd receives SIGCHLD ... ... kernel sends request systemd receives request ... systemd needs to respond to this request, otherwise the kernel will continue to block access to the mount point.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: BGD_DECLARE(gdImagePtr) gdImageCreateFromGifCtx(gdIOCtxPtr fd) { int BitPixel; #if 0 int ColorResolution; int Background; int AspectRatio; #endif int Transparent = (-1); unsigned char buf[16]; unsigned char c; unsigned char ColorMap[3][MAXCOLORMAPSIZE]; unsigned char localColorMap[3][MAXCOLORMAPSIZE]; int imw, imh, screen_width, screen_height; int useGlobalColormap; int bitPixel, i; /*1.4//int imageCount = 0; */ /* 2.0.28: threadsafe storage */ int ZeroDataBlock = FALSE; int haveGlobalColormap; gdImagePtr im = 0; memset(ColorMap, 0, 3 * MAXCOLORMAPSIZE); memset(localColorMap, 0, 3 * MAXCOLORMAPSIZE); if(!ReadOK(fd, buf, 6)) { return 0; } if(strncmp((char *)buf, "GIF", 3) != 0) { return 0; } if(memcmp((char *)buf + 3, "87a", 3) == 0) { /* GIF87a */ } else if(memcmp((char *)buf + 3, "89a", 3) == 0) { /* GIF89a */ } else { return 0; } if(!ReadOK(fd, buf, 7)) { return 0; } BitPixel = 2 << (buf[4] & 0x07); #if 0 ColorResolution = (int) (((buf[4]&0x70)>>3)+1); Background = buf[5]; AspectRatio = buf[6]; #endif screen_width = imw = LM_to_uint(buf[0], buf[1]); screen_height = imh = LM_to_uint(buf[2], buf[3]); haveGlobalColormap = BitSet(buf[4], LOCALCOLORMAP); /* Global Colormap */ if(haveGlobalColormap) { if(ReadColorMap(fd, BitPixel, ColorMap)) { return 0; } } for (;;) { int top, left; int width, height; if(!ReadOK(fd, &c, 1)) { return 0; } if (c == ';') { /* GIF terminator */ goto terminated; } if(c == '!') { /* Extension */ if(!ReadOK(fd, &c, 1)) { return 0; } DoExtension(fd, c, &Transparent, &ZeroDataBlock); continue; } if(c != ',') { /* Not a valid start character */ continue; } /*1.4//++imageCount; */ if(!ReadOK(fd, buf, 9)) { return 0; } useGlobalColormap = !BitSet(buf[8], LOCALCOLORMAP); bitPixel = 1 << ((buf[8] & 0x07) + 1); left = LM_to_uint(buf[0], buf[1]); top = LM_to_uint(buf[2], buf[3]); width = LM_to_uint(buf[4], buf[5]); height = LM_to_uint(buf[6], buf[7]); if(((left + width) > screen_width) || ((top + height) > screen_height)) { if(VERBOSE) { printf("Frame is not confined to screen dimension.\n"); } return 0; } if(!(im = gdImageCreate(width, height))) { return 0; } im->interlace = BitSet(buf[8], INTERLACE); if(!useGlobalColormap) { if(ReadColorMap(fd, bitPixel, localColorMap)) { gdImageDestroy(im); return 0; } ReadImage(im, fd, width, height, localColorMap, BitSet(buf[8], INTERLACE), &ZeroDataBlock); } else { if(!haveGlobalColormap) { gdImageDestroy(im); return 0; } ReadImage(im, fd, width, height, ColorMap, BitSet(buf[8], INTERLACE), &ZeroDataBlock); } if(Transparent != (-1)) { gdImageColorTransparent(im, Transparent); } goto terminated; } terminated: /* Terminator before any image was declared! */ if(!im) { return 0; } if(!im->colorsTotal) { gdImageDestroy(im); return 0; } /* Check for open colors at the end, so * we can reduce colorsTotal and ultimately * BitsPerPixel */ for(i = im->colorsTotal - 1; i >= 0; i--) { if(im->open[i]) { im->colorsTotal--; } else { break; } } return im; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-681'], 'message': 'Fix #420: 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. CVE-2018-5711 See also https://bugs.php.net/bug.php?id=75571.'</s>
<s>[INST] Given the following code containing errors, provide 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 pcrypt_free(struct crypto_instance *inst) { struct pcrypt_instance_ctx *ctx = crypto_instance_ctx(inst); crypto_drop_aead(&ctx->spawn); kfree(inst); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-763'], 'message': 'crypto: pcrypt - fix freeing pcrypt instances pcrypt is using the old way of freeing instances, where the ->free() method specified in the 'struct crypto_template' is passed a pointer to the 'struct crypto_instance'. But the crypto_instance is being kfree()'d directly, which is incorrect because the memory was actually allocated as an aead_instance, which contains the crypto_instance at a nonzero offset. Thus, the wrong pointer was being kfree()'d. Fix it by switching to the new way to free aead_instance's where the ->free() method is specified in the aead_instance itself. Reported-by: syzbot <syzkaller@googlegroups.com> Fixes: 0496f56065e0 ("crypto: pcrypt - Add support for new AEAD interface") Cc: <stable@vger.kernel.org> # v4.2+ Signed-off-by: Eric Biggers <ebiggers@google.com> Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static js_Ast *multiplicative(js_State *J) { js_Ast *a = unary(J); loop: if (jsP_accept(J, '*')) { a = EXP2(MUL, a, unary(J)); goto loop; } if (jsP_accept(J, '/')) { a = EXP2(DIV, a, unary(J)); goto loop; } if (jsP_accept(J, '%')) { a = EXP2(MOD, a, unary(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 irqreturn_t i8042_interrupt(int irq, void *dev_id) { struct i8042_port *port; struct serio *serio; unsigned long flags; unsigned char str, data; unsigned int dfl; unsigned int port_no; bool filtered; int ret = 1; spin_lock_irqsave(&i8042_lock, flags); str = i8042_read_status(); if (unlikely(~str & I8042_STR_OBF)) { spin_unlock_irqrestore(&i8042_lock, flags); if (irq) dbg("Interrupt %d, without any data\n", irq); ret = 0; goto out; } data = i8042_read_data(); if (i8042_mux_present && (str & I8042_STR_AUXDATA)) { static unsigned long last_transmit; static unsigned char last_str; dfl = 0; if (str & I8042_STR_MUXERR) { dbg("MUX error, status is %02x, data is %02x\n", str, data); /* * When MUXERR condition is signalled the data register can only contain * 0xfd, 0xfe or 0xff if implementation follows the spec. Unfortunately * it is not always the case. Some KBCs also report 0xfc when there is * nothing connected to the port while others sometimes get confused which * port the data came from and signal error leaving the data intact. They * _do not_ revert to legacy mode (actually I've never seen KBC reverting * to legacy mode yet, when we see one we'll add proper handling). * Anyway, we process 0xfc, 0xfd, 0xfe and 0xff as timeouts, and for the * rest assume that the data came from the same serio last byte * was transmitted (if transmission happened not too long ago). */ switch (data) { default: if (time_before(jiffies, last_transmit + HZ/10)) { str = last_str; break; } /* fall through - report timeout */ case 0xfc: case 0xfd: case 0xfe: dfl = SERIO_TIMEOUT; data = 0xfe; break; case 0xff: dfl = SERIO_PARITY; data = 0xfe; break; } } port_no = I8042_MUX_PORT_NO + ((str >> 6) & 3); last_str = str; last_transmit = jiffies; } else { dfl = ((str & I8042_STR_PARITY) ? SERIO_PARITY : 0) | ((str & I8042_STR_TIMEOUT && !i8042_notimeout) ? SERIO_TIMEOUT : 0); port_no = (str & I8042_STR_AUXDATA) ? I8042_AUX_PORT_NO : I8042_KBD_PORT_NO; } port = &i8042_ports[port_no]; serio = port->exists ? port->serio : NULL; filter_dbg(port->driver_bound, data, "<- i8042 (interrupt, %d, %d%s%s)\n", port_no, irq, dfl & SERIO_PARITY ? ", bad parity" : "", dfl & SERIO_TIMEOUT ? ", timeout" : ""); filtered = i8042_filter(data, str, serio); spin_unlock_irqrestore(&i8042_lock, flags); if (likely(port->exists && !filtered)) serio_interrupt(serio, data, dfl); out: return IRQ_RETVAL(ret); } ; 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: static int parse_status(const char *value) { int ret = 0; char *c; /* skip a header line */ c = strchr(value, '\n'); if (!c) return -1; c++; while (*c != '\0') { int port, status, speed, devid; unsigned long socket; char lbusid[SYSFS_BUS_ID_SIZE]; struct usbip_imported_device *idev; char hub[3]; ret = sscanf(c, "%2s %d %d %d %x %lx %31s\n", hub, &port, &status, &speed, &devid, &socket, lbusid); if (ret < 5) { dbg("sscanf failed: %d", ret); BUG(); } dbg("hub %s port %d status %d speed %d devid %x", hub, port, status, speed, devid); dbg("socket %lx lbusid %s", socket, lbusid); /* if a device is connected, look at it */ idev = &vhci_driver->idev[port]; memset(idev, 0, sizeof(*idev)); if (strncmp("hs", hub, 2) == 0) idev->hub = HUB_SPEED_HIGH; else /* strncmp("ss", hub, 2) == 0 */ idev->hub = HUB_SPEED_SUPER; idev->port = port; idev->status = status; idev->devid = devid; idev->busnum = (devid >> 16); idev->devnum = (devid & 0x0000ffff); if (idev->status != VDEV_ST_NULL && idev->status != VDEV_ST_NOTASSIGNED) { idev = imported_device_init(idev, lbusid); if (!idev) { dbg("imported_device_init failed"); return -1; } } /* go to the next line */ c = strchr(c, '\n'); if (!c) break; c++; } dbg("exit"); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'usbip: prevent vhci_hcd driver from leaking a socket pointer address When a client has a USB device attached over IP, the vhci_hcd driver is locally leaking a socket pointer address via the /sys/devices/platform/vhci_hcd/status file (world-readable) and in debug output when "usbip --debug port" is run. Fix it to not leak. The socket pointer address is not used at the moment and it was made visible as a convenient way to find IP address from socket pointer address by looking up /proc/net/{tcp,tcp6}. As this opens a security hole, the fix replaces socket pointer address with sockfd. Reported-by: Secunia Research <vuln@secunia.com> Cc: stable <stable@vger.kernel.org> Signed-off-by: Shuah Khan <shuahkh@osg.samsung.com> 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: flatpak_proxy_client_finalize (GObject *object) { FlatpakProxyClient *client = FLATPAK_PROXY_CLIENT (object); client->proxy->clients = g_list_remove (client->proxy->clients, client); g_clear_object (&client->proxy); g_hash_table_destroy (client->rewrite_reply); g_hash_table_destroy (client->get_owner_reply); g_hash_table_destroy (client->unique_id_policy); free_side (&client->client_side); free_side (&client->bus_side); G_OBJECT_CLASS (flatpak_proxy_client_parent_class)->finalize (object); } ; 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 futex_requeue(u32 __user *uaddr1, unsigned int flags, u32 __user *uaddr2, int nr_wake, int nr_requeue, u32 *cmpval, int requeue_pi) { union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT; int drop_count = 0, task_count = 0, ret; struct futex_pi_state *pi_state = NULL; struct futex_hash_bucket *hb1, *hb2; struct futex_q *this, *next; DEFINE_WAKE_Q(wake_q); /* * When PI not supported: return -ENOSYS if requeue_pi is true, * consequently the compiler knows requeue_pi is always false past * this point which will optimize away all the conditional code * further down. */ if (!IS_ENABLED(CONFIG_FUTEX_PI) && requeue_pi) return -ENOSYS; if (requeue_pi) { /* * Requeue PI only works on two distinct uaddrs. This * check is only valid for private futexes. See below. */ if (uaddr1 == uaddr2) return -EINVAL; /* * requeue_pi requires a pi_state, try to allocate it now * without any locks in case it fails. */ if (refill_pi_state_cache()) return -ENOMEM; /* * requeue_pi must wake as many tasks as it can, up to nr_wake * + nr_requeue, since it acquires the rt_mutex prior to * returning to userspace, so as to not leave the rt_mutex with * waiters and no owner. However, second and third wake-ups * cannot be predicted as they involve race conditions with the * first wake and a fault while looking up the pi_state. Both * pthread_cond_signal() and pthread_cond_broadcast() should * use nr_wake=1. */ if (nr_wake != 1) return -EINVAL; } retry: ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, VERIFY_READ); if (unlikely(ret != 0)) goto out; ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, requeue_pi ? VERIFY_WRITE : VERIFY_READ); if (unlikely(ret != 0)) goto out_put_key1; /* * The check above which compares uaddrs is not sufficient for * shared futexes. We need to compare the keys: */ if (requeue_pi && match_futex(&key1, &key2)) { ret = -EINVAL; goto out_put_keys; } hb1 = hash_futex(&key1); hb2 = hash_futex(&key2); retry_private: hb_waiters_inc(hb2); double_lock_hb(hb1, hb2); if (likely(cmpval != NULL)) { u32 curval; ret = get_futex_value_locked(&curval, uaddr1); if (unlikely(ret)) { double_unlock_hb(hb1, hb2); hb_waiters_dec(hb2); ret = get_user(curval, uaddr1); if (ret) goto out_put_keys; if (!(flags & FLAGS_SHARED)) goto retry_private; put_futex_key(&key2); put_futex_key(&key1); goto retry; } if (curval != *cmpval) { ret = -EAGAIN; goto out_unlock; } } if (requeue_pi && (task_count - nr_wake < nr_requeue)) { /* * Attempt to acquire uaddr2 and wake the top waiter. If we * intend to requeue waiters, force setting the FUTEX_WAITERS * bit. We force this here where we are able to easily handle * faults rather in the requeue loop below. */ ret = futex_proxy_trylock_atomic(uaddr2, hb1, hb2, &key1, &key2, &pi_state, nr_requeue); /* * At this point the top_waiter has either taken uaddr2 or is * waiting on it. If the former, then the pi_state will not * exist yet, look it up one more time to ensure we have a * reference to it. If the lock was taken, ret contains the * vpid of the top waiter task. * If the lock was not taken, we have pi_state and an initial * refcount on it. In case of an error we have nothing. */ if (ret > 0) { WARN_ON(pi_state); drop_count++; task_count++; /* * If we acquired the lock, then the user space value * of uaddr2 should be vpid. It cannot be changed by * the top waiter as it is blocked on hb2 lock if it * tries to do so. If something fiddled with it behind * our back the pi state lookup might unearth it. So * we rather use the known value than rereading and * handing potential crap to lookup_pi_state. * * If that call succeeds then we have pi_state and an * initial refcount on it. */ ret = lookup_pi_state(uaddr2, ret, hb2, &key2, &pi_state); } switch (ret) { case 0: /* We hold a reference on the pi state. */ break; /* If the above failed, then pi_state is NULL */ case -EFAULT: double_unlock_hb(hb1, hb2); hb_waiters_dec(hb2); put_futex_key(&key2); put_futex_key(&key1); ret = fault_in_user_writeable(uaddr2); if (!ret) goto retry; goto out; case -EAGAIN: /* * Two reasons for this: * - Owner is exiting and we just wait for the * exit to complete. * - The user space value changed. */ double_unlock_hb(hb1, hb2); hb_waiters_dec(hb2); put_futex_key(&key2); put_futex_key(&key1); cond_resched(); goto retry; default: goto out_unlock; } } plist_for_each_entry_safe(this, next, &hb1->chain, list) { if (task_count - nr_wake >= nr_requeue) break; if (!match_futex(&this->key, &key1)) continue; /* * FUTEX_WAIT_REQEUE_PI and FUTEX_CMP_REQUEUE_PI should always * be paired with each other and no other futex ops. * * We should never be requeueing a futex_q with a pi_state, * which is awaiting a futex_unlock_pi(). */ if ((requeue_pi && !this->rt_waiter) || (!requeue_pi && this->rt_waiter) || this->pi_state) { ret = -EINVAL; break; } /* * Wake nr_wake waiters. For requeue_pi, if we acquired the * lock, we already woke the top_waiter. If not, it will be * woken by futex_unlock_pi(). */ if (++task_count <= nr_wake && !requeue_pi) { mark_wake_futex(&wake_q, this); continue; } /* Ensure we requeue to the expected futex for requeue_pi. */ if (requeue_pi && !match_futex(this->requeue_pi_key, &key2)) { ret = -EINVAL; break; } /* * Requeue nr_requeue waiters and possibly one more in the case * of requeue_pi if we couldn't acquire the lock atomically. */ if (requeue_pi) { /* * Prepare the waiter to take the rt_mutex. Take a * refcount on the pi_state and store the pointer in * the futex_q object of the waiter. */ get_pi_state(pi_state); this->pi_state = pi_state; ret = rt_mutex_start_proxy_lock(&pi_state->pi_mutex, this->rt_waiter, this->task); if (ret == 1) { /* * We got the lock. We do neither drop the * refcount on pi_state nor clear * this->pi_state because the waiter needs the * pi_state for cleaning up the user space * value. It will drop the refcount after * doing so. */ requeue_pi_wake_futex(this, &key2, hb2); drop_count++; continue; } else if (ret) { /* * rt_mutex_start_proxy_lock() detected a * potential deadlock when we tried to queue * that waiter. Drop the pi_state reference * which we took above and remove the pointer * to the state from the waiters futex_q * object. */ this->pi_state = NULL; put_pi_state(pi_state); /* * We stop queueing more waiters and let user * space deal with the mess. */ break; } } requeue_futex(this, hb1, hb2, &key2); drop_count++; } /* * We took an extra initial reference to the pi_state either * in futex_proxy_trylock_atomic() or in lookup_pi_state(). We * need to drop it here again. */ put_pi_state(pi_state); out_unlock: double_unlock_hb(hb1, hb2); wake_up_q(&wake_q); hb_waiters_dec(hb2); /* * drop_futex_key_refs() must be called outside the spinlocks. During * the requeue we moved futex_q's from the hash bucket at key1 to the * one at key2 and updated their key pointer. We no longer need to * hold the references to key1. */ while (--drop_count >= 0) drop_futex_key_refs(&key1); out_put_keys: put_futex_key(&key2); out_put_key1: put_futex_key(&key1); out: return ret ? ret : task_count; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'futex: Prevent overflow by strengthen input validation UBSAN reports signed integer overflow in kernel/futex.c: UBSAN: Undefined behaviour in kernel/futex.c:2041:18 signed integer overflow: 0 - -2147483648 cannot be represented in type 'int' Add a sanity check to catch negative values of nr_wake and nr_requeue. Signed-off-by: Li Jinyue <lijinyue@huawei.com> Signed-off-by: Thomas Gleixner <tglx@linutronix.de> Cc: peterz@infradead.org Cc: dvhart@infradead.org Cc: stable@vger.kernel.org Link: https://lkml.kernel.org/r/1513242294-31786-1-git-send-email-lijinyue@huawei.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: Header readHeader(BasicIo& io) { byte header[2]; io.read(header, 2); ByteOrder byteOrder = invalidByteOrder; if (header[0] == 'I' && header[1] == 'I') byteOrder = littleEndian; else if (header[0] == 'M' && header[1] == 'M') byteOrder = bigEndian; if (byteOrder == invalidByteOrder) return Header(); byte version[2]; io.read(version, 2); const uint16_t magic = getUShort(version, byteOrder); if (magic != 0x2A && magic != 0x2B) return Header(); Header result; if (magic == 0x2A) { byte buffer[4]; io.read(buffer, 4); const uint32_t offset = getULong(buffer, byteOrder); result = Header(byteOrder, magic, 4, offset); } else { byte buffer[8]; io.read(buffer, 2); const int size = getUShort(buffer, byteOrder); assert(size == 8); io.read(buffer, 2); // null io.read(buffer, 8); const uint64_t offset = getULongLong(buffer, byteOrder); result = Header(byteOrder, magic, size, offset); } return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-617'], 'message': 'fix for crash in bigtiff (issue #208)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: compute_O_value(std::string const& user_password, std::string const& owner_password, QPDF::EncryptionData const& data) { // Algorithm 3.3 from the PDF 1.7 Reference Manual unsigned char O_key[OU_key_bytes_V4]; compute_O_rc4_key(user_password, owner_password, data, O_key); char upass[key_bytes]; pad_or_truncate_password_V4(user_password, upass); iterate_rc4(QUtil::unsigned_char_pointer(upass), key_bytes, O_key, data.getLengthBytes(), (data.getR() >= 3) ? 20 : 1, false); return std::string(upass, key_bytes); } ; 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: QPDF::parse_xrefEntry(std::string const& line, qpdf_offset_t& f1, int& f2, char& type) { // is_space and is_digit both return false on '\0', so this will // not overrun the null-terminated buffer. char const* p = line.c_str(); // Skip zero or more spaces. There aren't supposed to be any. bool invalid = false; while (QUtil::is_space(*p)) { ++p; QTC::TC("qpdf", "QPDF ignore first space in xref entry"); invalid = true; } // Require digit if (! QUtil::is_digit(*p)) { return false; } // Gather digits std::string f1_str; while (QUtil::is_digit(*p)) { f1_str.append(1, *p++); } // Require space if (! QUtil::is_space(*p)) { return false; } if (QUtil::is_space(*(p+1))) { QTC::TC("qpdf", "QPDF ignore first extra space in xref entry"); invalid = true; } // Skip spaces while (QUtil::is_space(*p)) { ++p; } // Require digit if (! QUtil::is_digit(*p)) { return false; } // Gather digits std::string f2_str; while (QUtil::is_digit(*p)) { f2_str.append(1, *p++); } // Require space if (! QUtil::is_space(*p)) { return false; } if (QUtil::is_space(*(p+1))) { QTC::TC("qpdf", "QPDF ignore second extra space in xref entry"); invalid = true; } // Skip spaces while (QUtil::is_space(*p)) { ++p; } if ((*p == 'f') || (*p == 'n')) { type = *p; } else { return false; } if ((f1_str.length() != 10) || (f2_str.length() != 5)) { QTC::TC("qpdf", "QPDF ignore length error xref entry"); invalid = true; } if (invalid) { warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "xref table", this->m->file->getLastOffset(), "accepting invalid xref table entry")); } f1 = QUtil::string_to_ll(f1_str.c_str()); f2 = atoi(f2_str.c_str()); return true; } ; 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: static int ssl_parse_client_psk_identity( mbedtls_ssl_context *ssl, unsigned char **p, const unsigned char *end ) { int ret = 0; size_t n; if( ssl->conf->f_psk == NULL && ( ssl->conf->psk == NULL || ssl->conf->psk_identity == NULL || ssl->conf->psk_identity_len == 0 || ssl->conf->psk_len == 0 ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no pre-shared key" ) ); return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED ); } /* * Receive client pre-shared key identity name */ if( *p + 2 > end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } n = ( (*p)[0] << 8 ) | (*p)[1]; *p += 2; if( n < 1 || n > 65535 || *p + n > end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } if( ssl->conf->f_psk != NULL ) { if( ssl->conf->f_psk( ssl->conf->p_psk, ssl, *p, n ) != 0 ) ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY; } else { /* Identity is not a big secret since clients send it in the clear, * but treat it carefully anyway, just in case */ if( n != ssl->conf->psk_identity_len || mbedtls_ssl_safer_memcmp( ssl->conf->psk_identity, *p, n ) != 0 ) { ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY; } } if( ret == MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY ) { MBEDTLS_SSL_DEBUG_BUF( 3, "Unknown PSK identity", *p, n ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY ); return( MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY ); } *p += n; return( 0 ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-190'], 'message': 'Prevent bounds check bypass through overflow in PSK identity parsing The check `if( *p + n > end )` in `ssl_parse_client_psk_identity` is unsafe because `*p + n` might overflow, thus bypassing the check. As `n` is a user-specified value up to 65K, this is relevant if the library happens to be located in the last 65K of virtual memory. This commit replaces the check by a safe version.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: gplotMakeOutput(GPLOT *gplot) { char buf[L_BUF_SIZE]; char *cmdname; l_int32 ignore; PROCNAME("gplotMakeOutput"); if (!gplot) return ERROR_INT("gplot not defined", procName, 1); gplotGenCommandFile(gplot); gplotGenDataFiles(gplot); cmdname = genPathname(gplot->cmdname, NULL); #ifndef _WIN32 snprintf(buf, L_BUF_SIZE, "gnuplot %s", cmdname); #else snprintf(buf, L_BUF_SIZE, "wgnuplot %s", cmdname); #endif /* _WIN32 */ #ifndef OS_IOS /* iOS 11 does not support system() */ ignore = system(buf); /* gnuplot || wgnuplot */ #endif /* !OS_IOS */ LEPT_FREE(cmdname); 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 server_init(IRC_SERVER_REC *server) { IRC_SERVER_CONNECT_REC *conn; char *address, *ptr, *username, *cmd; GTimeVal now; g_return_if_fail(server != NULL); conn = server->connrec; if (conn->proxy != NULL && conn->proxy_password != NULL && *conn->proxy_password != '\0') { cmd = g_strdup_printf("PASS %s", conn->proxy_password); irc_send_cmd_now(server, cmd); g_free(cmd); } if (conn->proxy != NULL && conn->proxy_string != NULL) { cmd = g_strdup_printf(conn->proxy_string, conn->address, conn->port); irc_send_cmd_now(server, cmd); g_free(cmd); } irc_send_cmd_now(server, "CAP LS"); if (conn->password != NULL && *conn->password != '\0') { /* send password */ cmd = g_strdup_printf("PASS %s", conn->password); irc_send_cmd_now(server, cmd); g_free(cmd); } /* send nick */ cmd = g_strdup_printf("NICK %s", conn->nick); irc_send_cmd_now(server, cmd); g_free(cmd); /* send user/realname */ address = server->connrec->address; ptr = strrchr(address, ':'); if (ptr != NULL) { /* IPv6 address .. doesn't work here, use the string after the last : char */ address = ptr+1; if (*address == '\0') address = "x"; } username = g_strdup(conn->username); ptr = strchr(username, ' '); if (ptr != NULL) *ptr = '\0'; cmd = g_strdup_printf("USER %s %s %s :%s", username, username, address, conn->realname); irc_send_cmd_now(server, cmd); g_free(cmd); g_free(username); if (conn->proxy != NULL && conn->proxy_string_after != NULL) { cmd = g_strdup_printf(conn->proxy_string_after, conn->address, conn->port); irc_send_cmd_now(server, cmd); g_free(cmd); } server->isupport = g_hash_table_new((GHashFunc) g_istr_hash, (GCompareFunc) g_istr_equal); /* set the standards */ g_hash_table_insert(server->isupport, g_strdup("CHANMODES"), g_strdup("beI,k,l,imnpst")); g_hash_table_insert(server->isupport, g_strdup("PREFIX"), g_strdup("(ohv)@%+")); server->cmdcount = 0; /* prevent the queue from sending too early, we have a max cut off of 120 secs */ /* this will reset to 1 sec after we get the 001 event */ g_get_current_time(&now); memcpy(&((IRC_SERVER_REC *)server)->wait_cmd, &now, sizeof(GTimeVal)); ((IRC_SERVER_REC *)server)->wait_cmd.tv_sec += 120; } ; 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_step_fail(IRC_SERVER_REC *server) { irc_send_cmd_now(server, "AUTHENTICATE *"); cap_finish_negotiation(server); server->sasl_timeout = 0; signal_emit("server sasl failure", 2, server, "The server sent an invalid payload"); } ; 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: pixHtmlViewer(const char *dirin, const char *dirout, const char *rootname, l_int32 thumbwidth, l_int32 viewwidth) { char *fname, *fullname, *outname; char *mainname, *linkname, *linknameshort; char *viewfile, *thumbfile; char *shtml, *slink; char charbuf[512]; char htmlstring[] = "<html>"; char framestring[] = "</frameset></html>"; l_int32 i, nfiles, index, w, d, nimages, ret; l_float32 factor; PIX *pix, *pixthumb, *pixview; SARRAY *safiles, *sathumbs, *saviews, *sahtml, *salink; PROCNAME("pixHtmlViewer"); if (!dirin) return ERROR_INT("dirin not defined", procName, 1); if (!dirout) return ERROR_INT("dirout not defined", procName, 1); if (!rootname) return ERROR_INT("rootname not defined", procName, 1); if (thumbwidth == 0) thumbwidth = DEFAULT_THUMB_WIDTH; if (thumbwidth < MIN_THUMB_WIDTH) { L_WARNING("thumbwidth too small; using min value\n", procName); thumbwidth = MIN_THUMB_WIDTH; } if (viewwidth == 0) viewwidth = DEFAULT_VIEW_WIDTH; if (viewwidth < MIN_VIEW_WIDTH) { L_WARNING("viewwidth too small; using min value\n", procName); viewwidth = MIN_VIEW_WIDTH; } /* Make the output directory if it doesn't already exist */ #ifndef _WIN32 snprintf(charbuf, sizeof(charbuf), "mkdir -p %s", dirout); ret = system(charbuf); #else ret = CreateDirectory(dirout, NULL) ? 0 : 1; #endif /* !_WIN32 */ if (ret) { L_ERROR("output directory %s not made\n", procName, dirout); return 1; } /* Capture the filenames in the input directory */ if ((safiles = getFilenamesInDirectory(dirin)) == NULL) return ERROR_INT("safiles not made", procName, 1); /* Generate output text file names */ sprintf(charbuf, "%s/%s.html", dirout, rootname); mainname = stringNew(charbuf); sprintf(charbuf, "%s/%s-links.html", dirout, rootname); linkname = stringNew(charbuf); linknameshort = stringJoin(rootname, "-links.html"); /* Generate the thumbs and views */ sathumbs = sarrayCreate(0); saviews = sarrayCreate(0); nfiles = sarrayGetCount(safiles); index = 0; for (i = 0; i < nfiles; i++) { fname = sarrayGetString(safiles, i, L_NOCOPY); fullname = genPathname(dirin, fname); fprintf(stderr, "name: %s\n", fullname); if ((pix = pixRead(fullname)) == NULL) { fprintf(stderr, "file %s not a readable image\n", fullname); lept_free(fullname); continue; } lept_free(fullname); /* Make and store the thumbnail images */ pixGetDimensions(pix, &w, NULL, &d); factor = (l_float32)thumbwidth / (l_float32)w; pixthumb = pixScale(pix, factor, factor); sprintf(charbuf, "%s_thumb_%03d", rootname, index); sarrayAddString(sathumbs, charbuf, L_COPY); outname = genPathname(dirout, charbuf); WriteFormattedPix(outname, pixthumb); lept_free(outname); pixDestroy(&pixthumb); /* Make and store the view images */ factor = (l_float32)viewwidth / (l_float32)w; if (factor >= 1.0) pixview = pixClone(pix); /* no upscaling */ else pixview = pixScale(pix, factor, factor); snprintf(charbuf, sizeof(charbuf), "%s_view_%03d", rootname, index); sarrayAddString(saviews, charbuf, L_COPY); outname = genPathname(dirout, charbuf); WriteFormattedPix(outname, pixview); lept_free(outname); pixDestroy(&pixview); pixDestroy(&pix); index++; } /* Generate the main html file */ sahtml = sarrayCreate(0); sarrayAddString(sahtml, htmlstring, L_COPY); sprintf(charbuf, "<frameset cols=\"%d, *\">", thumbwidth + 30); sarrayAddString(sahtml, charbuf, L_COPY); sprintf(charbuf, "<frame name=\"thumbs\" src=\"%s\">", linknameshort); sarrayAddString(sahtml, charbuf, L_COPY); sprintf(charbuf, "<frame name=\"views\" src=\"%s\">", sarrayGetString(saviews, 0, L_NOCOPY)); sarrayAddString(sahtml, charbuf, L_COPY); sarrayAddString(sahtml, framestring, L_COPY); shtml = sarrayToString(sahtml, 1); l_binaryWrite(mainname, "w", shtml, strlen(shtml)); fprintf(stderr, "******************************************\n" "Writing html file: %s\n" "******************************************\n", mainname); lept_free(shtml); lept_free(mainname); /* Generate the link html file */ nimages = sarrayGetCount(saviews); fprintf(stderr, "num. images = %d\n", nimages); salink = sarrayCreate(0); for (i = 0; i < nimages; i++) { viewfile = sarrayGetString(saviews, i, L_NOCOPY); thumbfile = sarrayGetString(sathumbs, i, L_NOCOPY); sprintf(charbuf, "<a href=\"%s\" TARGET=views><img src=\"%s\"></a>", viewfile, thumbfile); sarrayAddString(salink, charbuf, L_COPY); } slink = sarrayToString(salink, 1); l_binaryWrite(linkname, "w", slink, strlen(slink)); lept_free(slink); lept_free(linkname); lept_free(linknameshort); sarrayDestroy(&safiles); sarrayDestroy(&sathumbs); sarrayDestroy(&saviews); sarrayDestroy(&sahtml); sarrayDestroy(&salink); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'prog/htmlviewer: Catch unbound memory access (CID 1386222) rootname can have any size, so limit the amount of copied bytes. Signed-off-by: Stefan Weil <sw@weilnetz.de>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int get_v4l2_window32(struct v4l2_window *kp, struct v4l2_window32 __user *up) { struct v4l2_clip32 __user *uclips; struct v4l2_clip __user *kclips; compat_caddr_t p; u32 n; if (!access_ok(VERIFY_READ, up, sizeof(*up)) || copy_from_user(&kp->w, &up->w, sizeof(up->w)) || get_user(kp->field, &up->field) || get_user(kp->chromakey, &up->chromakey) || get_user(kp->clipcount, &up->clipcount) || get_user(kp->global_alpha, &up->global_alpha)) return -EFAULT; if (kp->clipcount > 2048) return -EINVAL; if (!kp->clipcount) { kp->clips = NULL; return 0; } n = kp->clipcount; if (get_user(p, &up->clips)) return -EFAULT; uclips = compat_ptr(p); kclips = compat_alloc_user_space(n * sizeof(*kclips)); kp->clips = kclips; while (n--) { if (copy_in_user(&kclips->c, &uclips->c, sizeof(uclips->c))) return -EFAULT; if (put_user(n ? kclips + 1 : NULL, &kclips->next)) return -EFAULT; uclips++; kclips++; } 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 put_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 = (__force struct v4l2_ext_control __user *)kp->controls; int n = kp->count; compat_caddr_t p; if (!access_ok(VERIFY_WRITE, up, sizeof(*up)) || put_user(kp->which, &up->which) || put_user(kp->count, &up->count) || put_user(kp->error_idx, &up->error_idx) || copy_to_user(up->reserved, kp->reserved, sizeof(up->reserved))) return -EFAULT; if (!kp->count) return 0; if (get_user(p, &up->controls)) return -EFAULT; ucontrols = compat_ptr(p); if (!access_ok(VERIFY_WRITE, ucontrols, n * sizeof(*ucontrols))) return -EFAULT; while (--n >= 0) { unsigned size = sizeof(*ucontrols); u32 id; if (get_user(id, &kcontrols->id)) return -EFAULT; /* Do not modify the pointer when copying a pointer control. The contents of the pointer was changed, not the pointer itself. */ if (ctrl_is_pointer(file, id)) size -= sizeof(ucontrols->value64); if (copy_in_user(ucontrols, kcontrols, size)) 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_plane32(struct v4l2_plane __user *up, struct v4l2_plane32 __user *up32, enum v4l2_memory memory) { void __user *up_pln; compat_long_t p; if (copy_in_user(up, up32, 2 * sizeof(__u32)) || copy_in_user(&up->data_offset, &up32->data_offset, sizeof(up->data_offset))) return -EFAULT; switch (memory) { case V4L2_MEMORY_MMAP: case V4L2_MEMORY_OVERLAY: if (copy_in_user(&up->m.mem_offset, &up32->m.mem_offset, sizeof(up32->m.mem_offset))) return -EFAULT; break; case V4L2_MEMORY_USERPTR: if (get_user(p, &up32->m.userptr)) return -EFAULT; up_pln = compat_ptr(p); if (put_user((unsigned long)up_pln, &up->m.userptr)) return -EFAULT; break; case V4L2_MEMORY_DMABUF: if (copy_in_user(&up->m.fd, &up32->m.fd, sizeof(up32->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: int f2fs_trim_fs(struct f2fs_sb_info *sbi, struct fstrim_range *range) { __u64 start = F2FS_BYTES_TO_BLK(range->start); __u64 end = start + F2FS_BYTES_TO_BLK(range->len) - 1; unsigned int start_segno, end_segno; struct cp_control cpc; int err = 0; if (start >= MAX_BLKADDR(sbi) || range->len < sbi->blocksize) return -EINVAL; cpc.trimmed = 0; if (end <= MAIN_BLKADDR(sbi)) goto out; if (is_sbi_flag_set(sbi, SBI_NEED_FSCK)) { f2fs_msg(sbi->sb, KERN_WARNING, "Found FS corruption, run fsck to fix."); goto out; } /* start/end segment number in main_area */ start_segno = (start <= MAIN_BLKADDR(sbi)) ? 0 : GET_SEGNO(sbi, start); end_segno = (end >= MAX_BLKADDR(sbi)) ? MAIN_SEGS(sbi) - 1 : GET_SEGNO(sbi, end); cpc.reason = CP_DISCARD; cpc.trim_minlen = max_t(__u64, 1, F2FS_BYTES_TO_BLK(range->minlen)); /* do checkpoint to issue discard commands safely */ for (; start_segno <= end_segno; start_segno = cpc.trim_end + 1) { cpc.trim_start = start_segno; if (sbi->discard_blks == 0) break; else if (sbi->discard_blks < BATCHED_TRIM_BLOCKS(sbi)) cpc.trim_end = end_segno; else cpc.trim_end = min_t(unsigned int, rounddown(start_segno + BATCHED_TRIM_SEGMENTS(sbi), sbi->segs_per_sec) - 1, end_segno); mutex_lock(&sbi->gc_mutex); err = write_checkpoint(sbi, &cpc); mutex_unlock(&sbi->gc_mutex); if (err) break; schedule(); } /* It's time to issue all the filed discards */ mark_discard_range_all(sbi); f2fs_wait_discard_bios(sbi); out: range->len = F2FS_BLK_TO_BYTES(cpc.trimmed); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'f2fs: fix potential panic during fstrim As Ju Hyung Park reported: "When 'fstrim' is called for manual trim, a BUG() can be triggered randomly with this patch. I'm seeing this issue on both x86 Desktop and arm64 Android phone. On x86 Desktop, this was caused during Ubuntu boot-up. I have a cronjob installed which calls 'fstrim -v /' during boot. On arm64 Android, this was caused during GC looping with 1ms gc_min_sleep_time & gc_max_sleep_time." Root cause of this issue is that f2fs_wait_discard_bios can only be used by f2fs_put_super, because during put_super there must be no other referrers, so it can ignore discard entry's reference count when removing the entry, otherwise in other caller we will hit bug_on in __remove_discard_cmd as there may be other issuer added reference count in discard entry. Thread A Thread B - issue_discard_thread - f2fs_ioc_fitrim - f2fs_trim_fs - f2fs_wait_discard_bios - __issue_discard_cmd - __submit_discard_cmd - __wait_discard_cmd - dc->ref++ - __wait_one_discard_bio - __wait_discard_cmd - __remove_discard_cmd - f2fs_bug_on(sbi, dc->ref) Fixes: 969d1b180d987c2be02de890d0fff0f66a0e80de Reported-by: Ju Hyung Park <qkrwngud825@gmail.com> Signed-off-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: static struct sctp_chunk *_sctp_make_chunk(const struct sctp_association *asoc, __u8 type, __u8 flags, int paylen, gfp_t gfp) { struct sctp_chunkhdr *chunk_hdr; struct sctp_chunk *retval; struct sk_buff *skb; struct sock *sk; /* No need to allocate LL here, as this is only a chunk. */ skb = alloc_skb(SCTP_PAD4(sizeof(*chunk_hdr) + paylen), gfp); if (!skb) goto nodata; /* Make room for the chunk header. */ chunk_hdr = (struct sctp_chunkhdr *)skb_put(skb, sizeof(*chunk_hdr)); chunk_hdr->type = type; chunk_hdr->flags = flags; chunk_hdr->length = htons(sizeof(*chunk_hdr)); sk = asoc ? asoc->base.sk : NULL; retval = sctp_chunkify(skb, asoc, sk, gfp); if (!retval) { kfree_skb(skb); goto nodata; } retval->chunk_hdr = chunk_hdr; retval->chunk_end = ((__u8 *)chunk_hdr) + sizeof(*chunk_hdr); /* Determine if the chunk needs to be authenticated */ if (sctp_auth_send_cid(type, asoc)) retval->auth = 1; return retval; nodata: return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'sctp: verify size of a new chunk in _sctp_make_chunk() When SCTP makes INIT or INIT_ACK packet the total chunk length can exceed SCTP_MAX_CHUNK_LEN which leads to kernel panic when transmitting these packets, e.g. the crash on sending INIT_ACK: [ 597.804948] skbuff: skb_over_panic: text:00000000ffae06e4 len:120168 put:120156 head:000000007aa47635 data:00000000d991c2de tail:0x1d640 end:0xfec0 dev:<NULL> ... [ 597.976970] ------------[ cut here ]------------ [ 598.033408] kernel BUG at net/core/skbuff.c:104! [ 600.314841] Call Trace: [ 600.345829] <IRQ> [ 600.371639] ? sctp_packet_transmit+0x2095/0x26d0 [sctp] [ 600.436934] skb_put+0x16c/0x200 [ 600.477295] sctp_packet_transmit+0x2095/0x26d0 [sctp] [ 600.540630] ? sctp_packet_config+0x890/0x890 [sctp] [ 600.601781] ? __sctp_packet_append_chunk+0x3b4/0xd00 [sctp] [ 600.671356] ? sctp_cmp_addr_exact+0x3f/0x90 [sctp] [ 600.731482] sctp_outq_flush+0x663/0x30d0 [sctp] [ 600.788565] ? sctp_make_init+0xbf0/0xbf0 [sctp] [ 600.845555] ? sctp_check_transmitted+0x18f0/0x18f0 [sctp] [ 600.912945] ? sctp_outq_tail+0x631/0x9d0 [sctp] [ 600.969936] sctp_cmd_interpreter.isra.22+0x3be1/0x5cb0 [sctp] [ 601.041593] ? sctp_sf_do_5_1B_init+0x85f/0xc30 [sctp] [ 601.104837] ? sctp_generate_t1_cookie_event+0x20/0x20 [sctp] [ 601.175436] ? sctp_eat_data+0x1710/0x1710 [sctp] [ 601.233575] sctp_do_sm+0x182/0x560 [sctp] [ 601.284328] ? sctp_has_association+0x70/0x70 [sctp] [ 601.345586] ? sctp_rcv+0xef4/0x32f0 [sctp] [ 601.397478] ? sctp6_rcv+0xa/0x20 [sctp] ... Here the chunk size for INIT_ACK packet becomes too big, mostly because of the state cookie (INIT packet has large size with many address parameters), plus additional server parameters. Later this chunk causes the panic in skb_put_data(): skb_packet_transmit() sctp_packet_pack() skb_put_data(nskb, chunk->skb->data, chunk->skb->len); 'nskb' (head skb) was previously allocated with packet->size from u16 'chunk->chunk_hdr->length'. As suggested by Marcelo we should check the chunk's length in _sctp_make_chunk() before trying to allocate skb for it and discard a chunk if its size bigger than SCTP_MAX_CHUNK_LEN. Signed-off-by: Alexey Kodanev <alexey.kodanev@oracle.com> Acked-by: Marcelo Ricardo Leitner <marcelo.leinter@gmail.com> Acked-by: Neil Horman <nhorman@tuxdriver.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static ssize_t o2nm_node_local_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; ssize_t ret; tmp = simple_strtoul(p, &p, 0); if (!p || (*p && (*p != '\n'))) return -EINVAL; tmp = !!tmp; /* boolean of whether this node wants to be local */ /* setting local turns on networking rx for now so we require having * set everything else first */ if (!test_bit(O2NM_NODE_ATTR_ADDRESS, &node->nd_set_attributes) || !test_bit(O2NM_NODE_ATTR_NUM, &node->nd_set_attributes) || !test_bit(O2NM_NODE_ATTR_PORT, &node->nd_set_attributes)) return -EINVAL; /* XXX */ /* the only failure case is trying to set a new local node * when a different one is already set */ if (tmp && tmp == cluster->cl_has_local && cluster->cl_local_node != node->nd_num) return -EBUSY; /* bring up the rx thread if we're setting the new local node. */ if (tmp && !cluster->cl_has_local) { ret = o2net_start_listening(node); if (ret) return ret; } if (!tmp && cluster->cl_has_local && cluster->cl_local_node == node->nd_num) { o2net_stop_listening(node); cluster->cl_local_node = O2NM_INVALID_NODE_NUM; } node->nd_local = tmp; if (node->nd_local) { cluster->cl_has_local = tmp; cluster->cl_local_node = node->nd_num; } 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: int sas_smp_get_phy_events(struct sas_phy *phy) { int res; u8 *req; u8 *resp; struct sas_rphy *rphy = dev_to_rphy(phy->dev.parent); struct domain_device *dev = sas_find_dev_by_rphy(rphy); req = alloc_smp_req(RPEL_REQ_SIZE); if (!req) return -ENOMEM; resp = alloc_smp_resp(RPEL_RESP_SIZE); if (!resp) { kfree(req); return -ENOMEM; } req[1] = SMP_REPORT_PHY_ERR_LOG; req[9] = phy->number; res = smp_execute_task(dev, req, RPEL_REQ_SIZE, resp, RPEL_RESP_SIZE); if (!res) goto out; phy->invalid_dword_count = scsi_to_u32(&resp[12]); phy->running_disparity_error_count = scsi_to_u32(&resp[16]); phy->loss_of_dword_sync_count = scsi_to_u32(&resp[20]); phy->phy_reset_problem_count = scsi_to_u32(&resp[24]); out: kfree(resp); return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-772'], 'message': 'scsi: libsas: fix memory leak in sas_smp_get_phy_events() We've got a memory leak with the following producer: while true; do cat /sys/class/sas_phy/phy-1:0:12/invalid_dword_count >/dev/null; done The buffer req is allocated and not freed after we return. Fix it. Fixes: 2908d778ab3e ("[SCSI] aic94xx: new driver") Signed-off-by: Jason Yan <yanaijie@huawei.com> CC: John Garry <john.garry@huawei.com> CC: chenqilin <chenqilin2@huawei.com> CC: chenxiang <chenxiang66@hisilicon.com> Reviewed-by: Christoph Hellwig <hch@lst.de> 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: 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; size_t strip_len = git_decode_varint((const unsigned char *)path_ptr, &varint_len); size_t last_len = strlen(last); size_t prefix_len = last_len - strip_len; size_t suffix_len = strlen(path_ptr + varint_len); size_t path_len; if (varint_len == 0) return index_error_invalid("incorrect prefix length"); 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: fix out-of-bounds read with invalid index entry prefix length The index format in version 4 has prefix-compressed entries, where every index entry can compress its path by using a path prefix of the previous entry. Since implmenting support for this index format version in commit 5625d86b9 (index: support index v4, 2016-05-17), though, we do not correctly verify that the prefix length that we want to reuse is actually smaller or equal to the amount of characters than the length of the previous index entry's path. This can lead to a an integer underflow and subsequently to an out-of-bounds read. Fix this by verifying that the prefix is actually smaller than the previous entry's path length. 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_mem_entry_fopen(ZZIP_MEM_DISK * dir, ZZIP_MEM_ENTRY * entry) { /* keep this in sync with zzip_disk_entry_fopen */ ZZIP_DISK_FILE *file = malloc(sizeof(ZZIP_MEM_DISK_FILE)); if (! file) return file; file->buffer = dir->disk->buffer; file->endbuf = dir->disk->endbuf; file->avail = zzip_mem_entry_usize(entry); if (! file->avail || zzip_mem_entry_data_stored(entry)) { file->stored = zzip_mem_entry_to_data (entry); return file; } file->stored = 0; file->zlib.opaque = 0; file->zlib.zalloc = Z_NULL; file->zlib.zfree = Z_NULL; file->zlib.avail_in = zzip_mem_entry_csize(entry); file->zlib.next_in = zzip_mem_entry_to_data(entry); if (! zzip_mem_entry_data_deflated(entry) || inflateInit2(&file->zlib, -MAX_WBITS) != Z_OK) { free (file); return 0; } return file; } ; 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_findfile(ZZIP_MEM_DISK* dir, char* filename, ZZIP_DISK_ENTRY* after, zzip_strcmp_fn_t compare) { return zzip_disk_findfile(dir->disk, filename, after, compare); } ; 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_parse_root_directory(int fd, struct _disk_trailer *trailer, struct zzip_dir_hdr **hdr_return, zzip_plugin_io_t io) { auto struct zzip_disk_entry dirent; struct zzip_dir_hdr *hdr; struct zzip_dir_hdr *hdr0; uint16_t *p_reclen = 0; zzip_off64_t entries; zzip_off64_t zz_offset; /* offset from start of root directory */ char *fd_map = 0; zzip_off64_t zz_fd_gap = 0; zzip_off64_t zz_entries = _disk_trailer_localentries(trailer); zzip_off64_t zz_rootsize = _disk_trailer_rootsize(trailer); zzip_off64_t zz_rootseek = _disk_trailer_rootseek(trailer); __correct_rootseek(zz_rootseek, zz_rootsize, trailer); hdr0 = (struct zzip_dir_hdr *) malloc(zz_rootsize); if (! hdr0) return ZZIP_DIRSIZE; hdr = hdr0; __debug_dir_hdr(hdr); if (USE_MMAP && io->fd.sys) { zz_fd_gap = zz_rootseek & (_zzip_getpagesize(io->fd.sys) - 1); HINT4(" fd_gap=%ld, mapseek=0x%lx, maplen=%ld", (long) (zz_fd_gap), (long) (zz_rootseek - zz_fd_gap), (long) (zz_rootsize + zz_fd_gap)); fd_map = _zzip_mmap(io->fd.sys, fd, zz_rootseek - zz_fd_gap, zz_rootsize + zz_fd_gap); /* if mmap failed we will fallback to seek/read mode */ if (fd_map == MAP_FAILED) { NOTE2("map failed: %s", strerror(errno)); fd_map = 0; } else { HINT3("mapped *%p len=%li", fd_map, (long) (zz_rootsize + zz_fd_gap)); } } for (entries=0, zz_offset=0; ; entries++) { register struct zzip_disk_entry *d; uint16_t u_extras, u_comment, u_namlen; # ifndef ZZIP_ALLOW_MODULO_ENTRIES if (entries >= zz_entries) { if (zz_offset + 256 < zz_rootsize) { FAIL4("%li's entry is long before the end of directory - enable modulo_entries? (O:%li R:%li)", (long) entries, (long) (zz_offset), (long) zz_rootsize); } break; } # endif if (fd_map) { d = (void*)(fd_map+zz_fd_gap+zz_offset); } /* fd_map+fd_gap==u_rootseek */ else { if (io->fd.seeks(fd, zz_rootseek + zz_offset, SEEK_SET) < 0) return ZZIP_DIR_SEEK; if (io->fd.read(fd, &dirent, sizeof(dirent)) < __sizeof(dirent)) return ZZIP_DIR_READ; d = &dirent; } if ((zzip_off64_t) (zz_offset + sizeof(*d)) > zz_rootsize || (zzip_off64_t) (zz_offset + sizeof(*d)) < 0) { FAIL4("%li's entry stretches beyond root directory (O:%li R:%li)", (long) entries, (long) (zz_offset), (long) zz_rootsize); break; } if (! zzip_disk_entry_check_magic(d)) { # ifndef ZZIP_ALLOW_MODULO_ENTRIES FAIL4("%li's entry has no disk_entry magic indicator (O:%li R:%li)", (long) entries, (long) (zz_offset), (long) zz_rootsize); # endif break; } # if 0 && defined DEBUG zzip_debug_xbuf((unsigned char *) d, sizeof(*d) + 8); # endif u_extras = zzip_disk_entry_get_extras(d); u_comment = zzip_disk_entry_get_comment(d); u_namlen = zzip_disk_entry_get_namlen(d); HINT5("offset=0x%lx, size %ld, dirent *%p, hdr %p\n", (long) (zz_offset + zz_rootseek), (long) zz_rootsize, d, hdr); /* writes over the read buffer, Since the structure where data is copied is smaller than the data in buffer this can be done. It is important that the order of setting the fields is considered when filling the structure, so that some data is not trashed in first structure read. at the end the whole copied list of structures is copied into newly allocated buffer */ hdr->d_crc32 = zzip_disk_entry_get_crc32(d); hdr->d_csize = zzip_disk_entry_get_csize(d); hdr->d_usize = zzip_disk_entry_get_usize(d); hdr->d_off = zzip_disk_entry_get_offset(d); hdr->d_compr = zzip_disk_entry_get_compr(d); if (hdr->d_compr > _255) hdr->d_compr = 255; if ((zzip_off64_t) (zz_offset + sizeof(*d) + u_namlen) > zz_rootsize || (zzip_off64_t) (zz_offset + sizeof(*d) + u_namlen) < 0) { FAIL4("%li's name stretches beyond root directory (O:%li N:%li)", (long) entries, (long) (zz_offset), (long) (u_namlen)); break; } if (fd_map) { memcpy(hdr->d_name, fd_map+zz_fd_gap + zz_offset+sizeof(*d), u_namlen); } else { io->fd.read(fd, hdr->d_name, u_namlen); } hdr->d_name[u_namlen] = '\0'; hdr->d_namlen = u_namlen; /* update offset by the total length of this entry -> next entry */ zz_offset += sizeof(*d) + u_namlen + u_extras + u_comment; if (zz_offset > zz_rootsize) { FAIL3("%li's entry stretches beyond root directory (O:%li)", (long) entries, (long) (zz_offset)); entries ++; break; } HINT5("file %ld { compr=%d crc32=$%x offset=%d", (long) entries, hdr->d_compr, hdr->d_crc32, hdr->d_off); HINT5("csize=%d usize=%d namlen=%d extras=%d", hdr->d_csize, hdr->d_usize, u_namlen, u_extras); HINT5("comment=%d name='%s' %s <sizeof %d> } ", u_comment, hdr->d_name, "", (int) sizeof(*d)); p_reclen = &hdr->d_reclen; { register char *p = (char *) hdr; register char *q = aligned4(p + sizeof(*hdr) + u_namlen + 1); *p_reclen = (uint16_t) (q - p); hdr = (struct zzip_dir_hdr *) q; } } /*for */ if (USE_MMAP && fd_map) { HINT3("unmap *%p len=%li", fd_map, (long) (zz_rootsize + zz_fd_gap)); _zzip_munmap(io->fd.sys, fd_map, zz_rootsize + zz_fd_gap); } if (p_reclen) { *p_reclen = 0; /* mark end of list */ if (hdr_return) *hdr_return = hdr0; } /* else zero (sane) entries */ # ifndef ZZIP_ALLOW_MODULO_ENTRIES return (entries != zz_entries ? ZZIP_CORRUPTED : 0); # else return ((entries & (unsigned)0xFFFF) != zz_entries ? ZZIP_CORRUPTED : 0); # endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'check rootseek after correction #41'</s>
<s>[INST] Given the following code containing errors, provide 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 ocfs2_direct_IO(struct kiocb *iocb, struct iov_iter *iter) { struct file *file = iocb->ki_filp; struct inode *inode = file->f_mapping->host; struct ocfs2_super *osb = OCFS2_SB(inode->i_sb); get_block_t *get_block; /* * Fallback to buffered I/O if we see an inode without * extents. */ if (OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL) return 0; /* Fallback to buffered I/O if we do not support append dio. */ if (iocb->ki_pos + iter->count > i_size_read(inode) && !ocfs2_supports_append_dio(osb)) return 0; if (iov_iter_rw(iter) == READ) get_block = ocfs2_get_block; else get_block = ocfs2_dio_get_block; return __blockdev_direct_IO(iocb, inode, inode->i_sb->s_bdev, iter, get_block, ocfs2_dio_end_io, NULL, 0); } ; 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_revalidate_domain(struct work_struct *work) { int res = 0; struct sas_discovery_event *ev = to_sas_discovery_event(work); struct asd_sas_port *port = ev->port; struct sas_ha_struct *ha = port->ha; struct domain_device *ddev = port->port_dev; /* prevent revalidation from finding sata links in recovery */ mutex_lock(&ha->disco_mutex); if (test_bit(SAS_HA_ATA_EH_ACTIVE, &ha->state)) { SAS_DPRINTK("REVALIDATION DEFERRED on port %d, pid:%d\n", port->id, task_pid_nr(current)); goto out; } clear_bit(DISCE_REVALIDATE_DOMAIN, &port->disc.pending); SAS_DPRINTK("REVALIDATING DOMAIN on port %d, pid:%d\n", port->id, task_pid_nr(current)); if (ddev && (ddev->dev_type == SAS_FANOUT_EXPANDER_DEVICE || ddev->dev_type == SAS_EDGE_EXPANDER_DEVICE)) res = sas_ex_revalidate_domain(ddev); SAS_DPRINTK("done REVALIDATING DOMAIN on port %d, pid:%d, res 0x%x\n", port->id, task_pid_nr(current), res); out: mutex_unlock(&ha->disco_mutex); } ; 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: static Token *tokenize(char *line) { char c, *p = line; enum pp_token_type type; Token *list = NULL; Token *t, **tail = &list; while (*line) { p = line; if (*p == '%') { p++; if (*p == '+' && !nasm_isdigit(p[1])) { p++; type = TOK_PASTE; } else if (nasm_isdigit(*p) || ((*p == '-' || *p == '+') && nasm_isdigit(p[1]))) { do { p++; } while (nasm_isdigit(*p)); type = TOK_PREPROC_ID; } else if (*p == '{') { p++; while (*p) { if (*p == '}') break; p[-1] = *p; p++; } if (*p != '}') nasm_error(ERR_WARNING | ERR_PASS1, "unterminated %%{ construct"); p[-1] = '\0'; if (*p) p++; type = TOK_PREPROC_ID; } else if (*p == '[') { int lvl = 1; line += 2; /* Skip the leading %[ */ p++; while (lvl && (c = *p++)) { switch (c) { case ']': lvl--; break; case '%': if (*p == '[') lvl++; break; case '\'': case '\"': case '`': p = nasm_skip_string(p - 1) + 1; break; default: break; } } p--; if (*p) *p++ = '\0'; if (lvl) nasm_error(ERR_NONFATAL|ERR_PASS1, "unterminated %%[ construct"); type = TOK_INDIRECT; } else if (*p == '?') { type = TOK_PREPROC_Q; /* %? */ p++; if (*p == '?') { type = TOK_PREPROC_QQ; /* %?? */ p++; } } else if (*p == '!') { type = TOK_PREPROC_ID; p++; if (isidchar(*p)) { do { p++; } while (isidchar(*p)); } else if (*p == '\'' || *p == '\"' || *p == '`') { p = nasm_skip_string(p); if (*p) p++; else nasm_error(ERR_NONFATAL|ERR_PASS1, "unterminated %%! string"); } else { /* %! without string or identifier */ type = TOK_OTHER; /* Legacy behavior... */ } } else if (isidchar(*p) || ((*p == '!' || *p == '%' || *p == '$') && isidchar(p[1]))) { do { p++; } while (isidchar(*p)); type = TOK_PREPROC_ID; } else { type = TOK_OTHER; if (*p == '%') p++; } } else if (isidstart(*p) || (*p == '$' && isidstart(p[1]))) { type = TOK_ID; p++; while (*p && isidchar(*p)) p++; } else if (*p == '\'' || *p == '"' || *p == '`') { /* * A string token. */ type = TOK_STRING; p = nasm_skip_string(p); if (*p) { p++; } else { nasm_error(ERR_WARNING|ERR_PASS1, "unterminated string"); /* Handling unterminated strings by UNV */ /* type = -1; */ } } else if (p[0] == '$' && p[1] == '$') { type = TOK_OTHER; /* TOKEN_BASE */ p += 2; } else if (isnumstart(*p)) { bool is_hex = false; bool is_float = false; bool has_e = false; char c, *r; /* * A numeric token. */ if (*p == '$') { p++; is_hex = true; } for (;;) { c = *p++; if (!is_hex && (c == 'e' || c == 'E')) { has_e = true; if (*p == '+' || *p == '-') { /* * e can only be followed by +/- if it is either a * prefixed hex number or a floating-point number */ p++; is_float = true; } } else if (c == 'H' || c == 'h' || c == 'X' || c == 'x') { is_hex = true; } else if (c == 'P' || c == 'p') { is_float = true; if (*p == '+' || *p == '-') p++; } else if (isnumchar(c)) ; /* just advance */ else if (c == '.') { /* * we need to deal with consequences of the legacy * parser, like "1.nolist" being two tokens * (TOK_NUMBER, TOK_ID) here; at least give it * a shot for now. In the future, we probably need * a flex-based scanner with proper pattern matching * to do it as well as it can be done. Nothing in * the world is going to help the person who wants * 0x123.p16 interpreted as two tokens, though. */ r = p; while (*r == '_') r++; if (nasm_isdigit(*r) || (is_hex && nasm_isxdigit(*r)) || (!is_hex && (*r == 'e' || *r == 'E')) || (*r == 'p' || *r == 'P')) { p = r; is_float = true; } else break; /* Terminate the token */ } else break; } p--; /* Point to first character beyond number */ if (p == line+1 && *line == '$') { type = TOK_OTHER; /* TOKEN_HERE */ } else { if (has_e && !is_hex) { /* 1e13 is floating-point, but 1e13h is not */ is_float = true; } type = is_float ? TOK_FLOAT : TOK_NUMBER; } } else if (nasm_isspace(*p)) { type = TOK_WHITESPACE; p = nasm_skip_spaces(p); /* * Whitespace just before end-of-line is discarded by * pretending it's a comment; whitespace just before a * comment gets lumped into the comment. */ if (!*p || *p == ';') { type = TOK_COMMENT; while (*p) p++; } } else if (*p == ';') { type = TOK_COMMENT; while (*p) p++; } else { /* * Anything else is an operator of some kind. We check * for all the double-character operators (>>, <<, //, * %%, <=, >=, ==, !=, <>, &&, ||, ^^), but anything * else is a single-character operator. */ type = TOK_OTHER; if ((p[0] == '>' && p[1] == '>') || (p[0] == '<' && p[1] == '<') || (p[0] == '/' && p[1] == '/') || (p[0] == '<' && p[1] == '=') || (p[0] == '>' && p[1] == '=') || (p[0] == '=' && p[1] == '=') || (p[0] == '!' && p[1] == '=') || (p[0] == '<' && p[1] == '>') || (p[0] == '&' && p[1] == '&') || (p[0] == '|' && p[1] == '|') || (p[0] == '^' && p[1] == '^')) { p++; } p++; } /* Handling unterminated string by UNV */ /*if (type == -1) { *tail = t = new_Token(NULL, TOK_STRING, line, p-line+1); t->text[p-line] = *line; tail = &t->next; } else */ if (type != TOK_COMMENT) { *tail = t = new_Token(NULL, type, line, p - line); tail = &t->next; } line = p; } return list; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'preproc: Don't access offsting byte on unterminated strings https://bugzilla.nasm.us/show_bug.cgi?id=3392446 Signed-off-by: Cyrill Gorcunov <gorcunov@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 void LogOpenCLBuildFailure(MagickCLDevice device,const char *kernel, ExceptionInfo *exception) { char filename[MagickPathExtent], *log; size_t log_size; (void) FormatLocaleString(filename,MagickPathExtent,"%s%s%s", GetOpenCLCacheDirectory(),DirectorySeparator,"magick_badcl.cl"); (void) remove_utf8(filename); (void) BlobToFile(filename,kernel,strlen(kernel),exception); openCL_library->clGetProgramBuildInfo(device->program,device->deviceID, CL_PROGRAM_BUILD_LOG,0,NULL,&log_size); log=(char*)AcquireMagickMemory(log_size); openCL_library->clGetProgramBuildInfo(device->program,device->deviceID, CL_PROGRAM_BUILD_LOG,log_size,log,&log_size); (void) FormatLocaleString(filename,MagickPathExtent,"%s%s%s", GetOpenCLCacheDirectory(),DirectorySeparator,"magick_badcl.log"); (void) remove_utf8(filename); (void) BlobToFile(filename,log,log_size,exception); log=(char*)RelinquishMagickMemory(log); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/793'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: dir_initialize(int argc, VALUE *argv, VALUE dir) { struct dir_data *dp; rb_encoding *fsenc; VALUE dirname, opt, orig; static ID keyword_ids[1]; const char *path; if (!keyword_ids[0]) { keyword_ids[0] = rb_id_encoding(); } fsenc = rb_filesystem_encoding(); rb_scan_args(argc, argv, "1:", &dirname, &opt); if (!NIL_P(opt)) { VALUE enc; rb_get_kwargs(opt, keyword_ids, 0, 1, &enc); if (enc != Qundef && !NIL_P(enc)) { fsenc = rb_to_encoding(enc); } } GlobPathValue(dirname, FALSE); orig = rb_str_dup_frozen(dirname); dirname = rb_str_encode_ospath(dirname); dirname = rb_str_dup_frozen(dirname); TypedData_Get_Struct(dir, struct dir_data, &dir_data_type, dp); if (dp->dir) closedir(dp->dir); dp->dir = NULL; RB_OBJ_WRITE(dir, &dp->path, Qnil); dp->enc = fsenc; path = RSTRING_PTR(dirname); dp->dir = opendir_without_gvl(path); if (dp->dir == NULL) { int e = errno; if (rb_gc_for_fd(e)) { dp->dir = opendir_without_gvl(path); } #ifdef HAVE_GETATTRLIST else if (e == EIO) { u_int32_t attrbuf[1]; struct attrlist al = {ATTR_BIT_MAP_COUNT, 0}; if (getattrlist(path, &al, attrbuf, sizeof(attrbuf), FSOPT_NOFOLLOW) == 0) { dp->dir = opendir_without_gvl(path); } } #endif if (dp->dir == NULL) { RB_GC_GUARD(dirname); rb_syserr_fail_path(e, orig); } } RB_OBJ_WRITE(dir, &dp->path, orig); return dir; } ; 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: do_ed_script (char const *inname, char const *outname, bool *outname_needs_removal, FILE *ofp) { static char const editor_program[] = EDITOR_PROGRAM; file_offset beginning_of_this_line; FILE *pipefp = 0; size_t chars_read; if (! dry_run && ! skip_rest_of_patch) { int exclusive = *outname_needs_removal ? 0 : O_EXCL; if (inerrno != ENOENT) { *outname_needs_removal = true; copy_file (inname, outname, 0, exclusive, instat.st_mode, true); } sprintf (buf, "%s %s%s", editor_program, verbosity == VERBOSE ? "" : "- ", outname); fflush (stdout); pipefp = popen(buf, binary_transput ? "wb" : "w"); if (!pipefp) pfatal ("Can't open pipe to %s", quotearg (buf)); } for (;;) { char ed_command_letter; beginning_of_this_line = file_tell (pfp); chars_read = get_line (); if (! chars_read) { next_intuit_at(beginning_of_this_line,p_input_line); break; } ed_command_letter = get_ed_command_letter (buf); if (ed_command_letter) { if (pipefp) if (! fwrite (buf, sizeof *buf, chars_read, pipefp)) write_fatal (); if (ed_command_letter != 'd' && ed_command_letter != 's') { p_pass_comments_through = true; while ((chars_read = get_line ()) != 0) { if (pipefp) if (! fwrite (buf, sizeof *buf, chars_read, pipefp)) write_fatal (); if (chars_read == 2 && strEQ (buf, ".\n")) break; } p_pass_comments_through = false; } } else { next_intuit_at(beginning_of_this_line,p_input_line); break; } } if (!pipefp) return; if (fwrite ("w\nq\n", sizeof (char), (size_t) 4, pipefp) == 0 || fflush (pipefp) != 0) write_fatal (); if (pclose (pipefp) != 0) fatal ("%s FAILED", editor_program); if (ofp) { FILE *ifp = fopen (outname, binary_transput ? "rb" : "r"); int c; if (!ifp) pfatal ("can't open '%s'", outname); while ((c = getc (ifp)) != EOF) if (putc (c, ofp) == EOF) write_fatal (); if (ferror (ifp) || fclose (ifp) != 0) read_fatal (); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix arbitrary command execution in ed-style patches (CVE-2018-1000156) * src/pch.c (do_ed_script): Write ed script to a temporary file instead of piping it to ed: this will cause ed to abort on invalid commands instead of rejecting them and carrying on. * tests/ed-style: New test case. * tests/Makefile.am (TESTS): Add test case.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: pk_transaction_authorize_actions_finished_cb (GObject *source_object, GAsyncResult *res, struct AuthorizeActionsData *data) { const gchar *action_id = NULL; PkTransactionPrivate *priv = data->transaction->priv; g_autoptr(GError) error = NULL; g_autoptr(PolkitAuthorizationResult) result = NULL; g_assert (data->actions && data->actions->len > 0); /* get the first action */ action_id = g_ptr_array_index (data->actions, 0); /* finish the call */ result = polkit_authority_check_authorization_finish (priv->authority, res, &error); /* failed because the request was cancelled */ if (g_cancellable_is_cancelled (priv->cancellable)) { /* emit an ::StatusChanged, ::ErrorCode() and then ::Finished() */ priv->waiting_for_auth = FALSE; pk_transaction_status_changed_emit (data->transaction, PK_STATUS_ENUM_FINISHED); pk_transaction_error_code_emit (data->transaction, PK_ERROR_ENUM_NOT_AUTHORIZED, "The authentication was cancelled due to a timeout."); pk_transaction_finished_emit (data->transaction, PK_EXIT_ENUM_FAILED, 0); goto out; } /* failed, maybe polkit is messed up? */ if (result == NULL) { g_autofree gchar *message = NULL; priv->waiting_for_auth = FALSE; g_warning ("failed to check for auth: %s", error->message); /* emit an ::StatusChanged, ::ErrorCode() and then ::Finished() */ pk_transaction_status_changed_emit (data->transaction, PK_STATUS_ENUM_FINISHED); message = g_strdup_printf ("Failed to check for authentication: %s", error->message); pk_transaction_error_code_emit (data->transaction, PK_ERROR_ENUM_NOT_AUTHORIZED, message); pk_transaction_finished_emit (data->transaction, PK_EXIT_ENUM_FAILED, 0); goto out; } /* did not auth */ if (!polkit_authorization_result_get_is_authorized (result)) { if (g_strcmp0 (action_id, "org.freedesktop.packagekit.package-install") == 0 && pk_bitfield_contain (priv->cached_transaction_flags, PK_TRANSACTION_FLAG_ENUM_ALLOW_REINSTALL)) { g_debug ("allowing just reinstallation"); pk_bitfield_add (priv->cached_transaction_flags, PK_TRANSACTION_FLAG_ENUM_JUST_REINSTALL); } else { priv->waiting_for_auth = FALSE; /* emit an ::StatusChanged, ::ErrorCode() and then ::Finished() */ pk_transaction_status_changed_emit (data->transaction, PK_STATUS_ENUM_FINISHED); pk_transaction_error_code_emit (data->transaction, PK_ERROR_ENUM_NOT_AUTHORIZED, "Failed to obtain authentication."); pk_transaction_finished_emit (data->transaction, PK_EXIT_ENUM_FAILED, 0); syslog (LOG_AUTH | LOG_NOTICE, "uid %i failed to obtain auth", priv->uid); goto out; } } if (data->actions->len <= 1) { /* authentication finished successfully */ priv->waiting_for_auth = FALSE; pk_transaction_set_state (data->transaction, PK_TRANSACTION_STATE_READY); /* log success too */ syslog (LOG_AUTH | LOG_INFO, "uid %i obtained auth for %s", priv->uid, action_id); } else { /* process the rest of actions */ g_ptr_array_remove_index (data->actions, 0); pk_transaction_authorize_actions (data->transaction, data->role, data->actions); } out: g_ptr_array_unref (data->actions); g_free (data); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-287'], 'message': 'Do not set JUST_REINSTALL on any kind of auth failure If we try to continue the auth queue when it has been cancelled (or failed) then we fall upon the obscure JUST_REINSTALL transaction flag which only the DNF backend actually verifies. Many thanks to Matthias Gerstner <mgerstner@suse.de> for spotting the problem.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QPDFObjectHandle::parseInternal(PointerHolder<InputSource> input, std::string const& object_description, QPDFTokenizer& tokenizer, bool& empty, StringDecrypter* decrypter, QPDF* context, bool content_stream) { // This method must take care not to resolve any objects. Don't // check the type of any object without first ensuring that it is // a direct object. Otherwise, doing so may have the side effect // of reading the object and changing the file pointer. empty = false; QPDFObjectHandle object; std::vector<std::vector<QPDFObjectHandle> > olist_stack; olist_stack.push_back(std::vector<QPDFObjectHandle>()); std::vector<parser_state_e> state_stack; state_stack.push_back(st_top); std::vector<qpdf_offset_t> offset_stack; qpdf_offset_t offset = input->tell(); offset_stack.push_back(offset); bool done = false; while (! done) { std::vector<QPDFObjectHandle>& olist = olist_stack.back(); parser_state_e state = state_stack.back(); offset = offset_stack.back(); object = QPDFObjectHandle(); QPDFTokenizer::Token token = tokenizer.readToken(input, object_description, true); switch (token.getType()) { case QPDFTokenizer::tt_eof: if (! content_stream) { QTC::TC("qpdf", "QPDFObjectHandle eof in parseInternal"); warn(context, QPDFExc(qpdf_e_damaged_pdf, input->getName(), object_description, input->getLastOffset(), "unexpected EOF")); } state = st_eof; break; case QPDFTokenizer::tt_bad: QTC::TC("qpdf", "QPDFObjectHandle bad token in parse"); warn(context, QPDFExc(qpdf_e_damaged_pdf, input->getName(), object_description, input->getLastOffset(), token.getErrorMessage())); object = newNull(); break; case QPDFTokenizer::tt_brace_open: case QPDFTokenizer::tt_brace_close: QTC::TC("qpdf", "QPDFObjectHandle bad brace"); warn(context, QPDFExc(qpdf_e_damaged_pdf, input->getName(), object_description, input->getLastOffset(), "treating unexpected brace token as null")); object = newNull(); break; case QPDFTokenizer::tt_array_close: if (state == st_array) { state = st_stop; } else { QTC::TC("qpdf", "QPDFObjectHandle bad array close"); warn(context, QPDFExc(qpdf_e_damaged_pdf, input->getName(), object_description, input->getLastOffset(), "treating unexpected array close token as null")); object = newNull(); } break; case QPDFTokenizer::tt_dict_close: if (state == st_dictionary) { state = st_stop; } else { QTC::TC("qpdf", "QPDFObjectHandle bad dictionary close"); warn(context, QPDFExc(qpdf_e_damaged_pdf, input->getName(), object_description, input->getLastOffset(), "unexpected dictionary close token")); object = newNull(); } break; case QPDFTokenizer::tt_array_open: case QPDFTokenizer::tt_dict_open: olist_stack.push_back(std::vector<QPDFObjectHandle>()); state = st_start; offset_stack.push_back(input->tell()); state_stack.push_back( (token.getType() == QPDFTokenizer::tt_array_open) ? st_array : st_dictionary); break; case QPDFTokenizer::tt_bool: object = newBool((token.getValue() == "true")); break; case QPDFTokenizer::tt_null: object = newNull(); break; case QPDFTokenizer::tt_integer: object = newInteger(QUtil::string_to_ll(token.getValue().c_str())); break; case QPDFTokenizer::tt_real: object = newReal(token.getValue()); break; case QPDFTokenizer::tt_name: object = newName(token.getValue()); break; case QPDFTokenizer::tt_word: { std::string const& value = token.getValue(); if (content_stream) { object = QPDFObjectHandle::newOperator(value); } else if ((value == "R") && (state != st_top) && (olist.size() >= 2) && (! olist.at(olist.size() - 1).isIndirect()) && (olist.at(olist.size() - 1).isInteger()) && (! olist.at(olist.size() - 2).isIndirect()) && (olist.at(olist.size() - 2).isInteger())) { if (context == 0) { QTC::TC("qpdf", "QPDFObjectHandle indirect without context"); throw std::logic_error( "QPDFObjectHandle::parse called without context" " on an object with indirect references"); } // Try to resolve indirect objects object = newIndirect( context, olist.at(olist.size() - 2).getIntValue(), olist.at(olist.size() - 1).getIntValue()); olist.pop_back(); olist.pop_back(); } else if ((value == "endobj") && (state == st_top)) { // We just saw endobj without having read // anything. Treat this as a null and do not move // the input source's offset. object = newNull(); input->seek(input->getLastOffset(), SEEK_SET); empty = true; } else { QTC::TC("qpdf", "QPDFObjectHandle treat word as string"); warn(context, QPDFExc(qpdf_e_damaged_pdf, input->getName(), object_description, input->getLastOffset(), "unknown token while reading object;" " treating as string")); object = newString(value); } } break; case QPDFTokenizer::tt_string: { std::string val = token.getValue(); if (decrypter) { decrypter->decryptString(val); } object = QPDFObjectHandle::newString(val); } break; default: warn(context, QPDFExc(qpdf_e_damaged_pdf, input->getName(), object_description, input->getLastOffset(), "treating unknown token type as null while " "reading object")); object = newNull(); break; } if ((! object.isInitialized()) && (! ((state == st_start) || (state == st_stop) || (state == st_eof)))) { throw std::logic_error( "QPDFObjectHandle::parseInternal: " "unexpected uninitialized object"); object = newNull(); } switch (state) { case st_eof: if (state_stack.size() > 1) { warn(context, QPDFExc(qpdf_e_damaged_pdf, input->getName(), object_description, input->getLastOffset(), "parse error while reading object")); } done = true; // In content stream mode, leave object uninitialized to // indicate EOF if (! content_stream) { object = newNull(); } break; case st_dictionary: case st_array: setObjectDescriptionFromInput( object, context, object_description, input, input->getLastOffset()); olist.push_back(object); break; case st_top: done = true; break; case st_start: break; case st_stop: if ((state_stack.size() < 2) || (olist_stack.size() < 2)) { throw std::logic_error( "QPDFObjectHandle::parseInternal: st_stop encountered" " with insufficient elements in stack"); } parser_state_e old_state = state_stack.back(); state_stack.pop_back(); if (old_state == st_array) { object = newArray(olist); setObjectDescriptionFromInput( object, context, object_description, input, offset); } else if (old_state == st_dictionary) { // Convert list to map. Alternating elements are keys. // Attempt to recover more or less gracefully from // invalid dictionaries. std::set<std::string> names; for (std::vector<QPDFObjectHandle>::iterator iter = olist.begin(); iter != olist.end(); ++iter) { if ((! (*iter).isIndirect()) && (*iter).isName()) { names.insert((*iter).getName()); } } std::map<std::string, QPDFObjectHandle> dict; int next_fake_key = 1; for (unsigned int i = 0; i < olist.size(); ++i) { QPDFObjectHandle key_obj = olist.at(i); QPDFObjectHandle val; if (key_obj.isIndirect() || (! key_obj.isName())) { bool found_fake = false; std::string candidate; while (! found_fake) { candidate = "/QPDFFake" + QUtil::int_to_string(next_fake_key++); found_fake = (names.count(candidate) == 0); QTC::TC("qpdf", "QPDFObjectHandle found fake", (found_fake ? 0 : 1)); } warn(context, QPDFExc( qpdf_e_damaged_pdf, input->getName(), object_description, offset, "expected dictionary key but found" " non-name object; inserting key " + candidate)); val = key_obj; key_obj = newName(candidate); } else if (i + 1 >= olist.size()) { QTC::TC("qpdf", "QPDFObjectHandle no val for last key"); warn(context, QPDFExc( qpdf_e_damaged_pdf, input->getName(), object_description, offset, "dictionary ended prematurely; " "using null as value for last key")); val = newNull(); setObjectDescriptionFromInput( val, context, object_description, input, offset); } else { val = olist.at(++i); } dict[key_obj.getName()] = val; } object = newDictionary(dict); setObjectDescriptionFromInput( object, context, object_description, input, offset); } olist_stack.pop_back(); offset_stack.pop_back(); if (state_stack.back() == st_top) { done = true; } else { olist_stack.back().push_back(object); } } } setObjectDescriptionFromInput( object, context, object_description, input, offset); return object; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-674'], 'message': 'Limit depth of nesting in direct objects (fixes #202) This fixes CVE-2018-9918.'</s>
<s>[INST] Given the following code containing errors, provide 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 *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MaxTextExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelPacket mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; /* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second */ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneMNGImage()"); image=mng_info->image; if (LocaleCompare(image_info->magick,"MNG") == 0) { char magic_number[MaxTextExtent]; /* Verify MNG signature. */ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (memcmp(magic_number,"\212MNG\r\n\032\n",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize some nonzero members of the MngInfo structure. */ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; /* should be False when converting or mogrifying */ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MaxTextExtent]; if (LocaleCompare(image_info->magick,"MNG") == 0) { unsigned char *chunk; /* Read a new chunk. */ type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MaxTextExtent); length=(size_t) ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading MNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX) { status=MagickFalse; break; } if (count == 0) ThrowReaderException(CorruptImageError,"CorruptImage"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); 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) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"JNGCompressNotSupported","`%s'",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"DeltaPNGNotSupported","`%s'",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); break; } if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skip to IEND."); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"CorruptImage"); } mng_info->mng_width=(unsigned long)mng_get_long(p); mng_info->mng_height=(unsigned long)mng_get_long(&p[4]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG width: %.20g",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG height: %.20g",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; /* Skip nominal layer count, frame count, and play time */ p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; /* Full MNG */ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; /* LC */ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; /* VLC */ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit"); } (void) FormatLocaleString(page_geometry,MaxTextExtent, "%.20gx%.20g+0+0",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3 && length > 8) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " repeat=%d, final_delay=%.20g, iterations=%.20g", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) { (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"DEFI chunk found in MNG-VLC datastream","`%s'", image->filename); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (length < 2) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"CorruptImage"); } object_id=((unsigned int) p[0] << 8) | (unsigned int) p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError,"Nonzero object_id in MNG-LC datastream", "`%s'", image->filename); if (object_id > MNG_MAX_OBJECTS) { /* Instead of using a warning we should allocate a larger MngInfo structure and continue. */ (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError, "object id too large","`%s'",image->filename); object_id=MNG_MAX_OBJECTS; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "DEFI cannot redefine a frozen MNG object","`%s'", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; /* Extract object offset info. */ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) mng_get_long(&p[4]); mng_info->y_off[object_id]=(ssize_t) mng_get_long(&p[8]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " x_off[%d]: %.20g, y_off[%d]: %.20g", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } /* Extract object clipping info. */ if (length > 27) mng_info->object_clip[object_id]= mng_read_box(mng_info->frame,0, &p[12]); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.opacity=OpaqueOpacity; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { /* Read global PLTE. */ if (length && (length < 769)) { if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); if (mng_info->global_plte == (png_colorp) NULL) { mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); mng_info=MngInfoFreeStruct(mng_info); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } for (i=0; i < (ssize_t) (length/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { /* read global tRNS */ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { /* Read global cHRM */ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { /* Read global sRGB. */ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ /* Read global iCCP. */ chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"FRAM chunk found in MNG-VLC datastream","`%s'", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length > 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_mode=%d",mng_info->framing_mode); if (length > 6) { /* Note the delay and frame clipping boundaries. */ p++; /* framing mode */ while (((p-chunk) < (long) length) && *p) p++; /* frame name */ p++; /* frame name terminator */ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; /* change_sync */ if (change_delay && ((p-chunk) < (ssize_t) (length-4))) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_delay=%.20g",(double) frame_delay); } if (change_timeout && ((p-chunk) < (ssize_t) (length-4))) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_timeout=%.20g",(double) frame_timeout); } if (change_clipping && ((p-chunk) < (ssize_t) (length-16))) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=16; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); /* Insert a background layer behind the frame if framing_mode is 4. */ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " subframe_width=%.20g, subframe_height=%.20g",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { /* Allocate next image structure. */ if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; image->delay=0; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; /* Read CLIP. */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { /* Read DISC or SEEK. */ if ((length == 0) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; /* read MOVE */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; /* mark loop active */ /* Record starting point. */ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " LOOP level %.20g has %.20g iterations ", (double) loop_level, (double) loop_iters); if (loop_iters == 0) skipping_loop=loop_level; else { mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { /* Found end of zero-iteration loop. */ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ENDL: LOOP level %.20g has %.20g remaining iters ", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset=SeekBlob(image, mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, "ImproperImageHeader"); } } else { short last_level; /* Finished loop. */ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"CLON is not implemented yet","`%s'", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "MAGN is not implemented yet for nonzero objects", "`%s'",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "Unknown MAGN method in MNG datastream","`%s'", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS /* Magnify existing objects in the range magn_first to magn_last */ #endif if (magn_first == 0 || magn_last == 0) { /* Save the magnification factors for object 0 */ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"PAST is not implemented yet","`%s'", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"SHOW is not implemented yet","`%s'", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"pHYg is not implemented.","`%s'",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"BASI is not implemented yet","`%s'", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED if (length > 11) { basi_width=(unsigned long) mng_get_long(p); basi_width=(unsigned long) mng_get_long(&p[4]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; } if (length > 13) basi_red=(png_uint_32) p[12] << 8) & png_uint_32) p[13]; else basi_red=0; if (length > 15) basi_green=(png_uint_32) p[14] << 8) & png_uint_32) p[15]; else basi_green=0; if (length > 17) basi_blue=(png_uint_32) p[16] << 8) & png_uint_32) p[17]; else basi_blue=0; if (length > 19) basi_alpha=(png_uint_32) p[18] << 8) & png_uint_32) p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 20) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { /* Not an IHDR or JHDR chunk */ chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } /* Process IHDR */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing %c%c%c%c chunk",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping invisible object"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); /* Insert a transparent background layer behind the entire animation if it is not full screen. */ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; /* Make a background rectangle. */ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Inserted transparent background layer, W=%.20g, H=%.20g", (double) mng_info->mng_width,(double) mng_info->mng_height); } } /* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. */ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif /* MNG_INSERT_LAYERS */ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; /* Seek back to the beginning of the IHDR or JHDR chunk's length field. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Seeking back to beginning of %c%c%c%c chunk",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing MNG MAGN chunk"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; ssize_t m, y; register ssize_t x; register PixelPacket *n, *q; PixelPacket *next, *prev; png_uint_16 magn_methx, magn_methy; /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocate magnified image"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { /* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleQuantumToShort( GetPixelRed(q))); SetPixelGreen(q,ScaleQuantumToShort( GetPixelGreen(q))); SetPixelBlue(q,ScaleQuantumToShort( GetPixelBlue(q))); SetPixelOpacity(q,ScaleQuantumToShort( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->matte != MagickFalse) (void) SetImageBackgroundColor(large_image); else { large_image->background_color.opacity=OpaqueOpacity; (void) SetImageBackgroundColor(large_image); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } /* magnify the rows into the right side of the large image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the rows to %.20g",(double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) image->columns; next=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*next)); prev=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (PixelPacket *) NULL) || (next == (PixelPacket *) NULL)) { if (prev != (PixelPacket *) NULL) prev=(PixelPacket *) RelinquishMagickMemory(prev); if (next != (PixelPacket *) NULL) next=(PixelPacket *) RelinquishMagickMemory(next); image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) memcpy(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) memcpy(next,n,length); } for (i=0; i < m; i++, yy++) { register PixelPacket *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); if (q == (PixelPacket *) NULL) break; q+=(large_image->columns-image->columns); for (x=(ssize_t) image->columns-1; x >= 0; x--) { /* To do: get color as function of indexes[x] */ /* if (image->storage_class == PseudoClass) { } */ if (magn_methy <= 1) { /* replicate previous */ SetPixelRGBO(q,(pixels)); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } else { /* Interpolate */ SetPixelRed(q, ((QM) (((ssize_t) (2*i*(GetPixelRed(n) -GetPixelRed(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelRed(pixels))))); SetPixelGreen(q, ((QM) (((ssize_t) (2*i*(GetPixelGreen(n) -GetPixelGreen(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelGreen(pixels))))); SetPixelBlue(q, ((QM) (((ssize_t) (2*i*(GetPixelBlue(n) -GetPixelBlue(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelBlue(pixels))))); if (image->matte != MagickFalse) SetPixelOpacity(q, ((QM) (((ssize_t) (2*i*(GetPixelOpacity(n) -GetPixelOpacity(pixels)+m)) /((ssize_t) (m*2))+ GetPixelOpacity(pixels))))); } if (magn_methy == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) SetPixelOpacity(q, (*pixels).opacity+0); else SetPixelOpacity(q, (*n).opacity+0); } } else /* if (magn_methy == 3 || magn_methy == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methy == 5) { SetPixelOpacity(q, (QM) (((ssize_t) (2*i* (GetPixelOpacity(n) -GetPixelOpacity(pixels)) +m))/((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } n++; q++; pixels++; } /* x */ if (SyncAuthenticPixels(large_image,exception) == 0) break; } /* i */ } /* y */ prev=(PixelPacket *) RelinquishMagickMemory(prev); next=(PixelPacket *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Delete original image"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; /* magnify the columns */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the columns to %.20g",(double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; pixels=q+(image->columns-length); n=pixels+1; for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { /* To do: Rewrite using Get/Set***PixelComponent() */ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { /* replicate previous */ SetPixelRGBO(q,(pixels)); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } /* To do: Rewrite using Get/Set***PixelComponent() */ else { /* Interpolate */ SetPixelRed(q, (QM) ((2*i*( GetPixelRed(n) -GetPixelRed(pixels))+m) /((ssize_t) (m*2))+ GetPixelRed(pixels))); SetPixelGreen(q, (QM) ((2*i*( GetPixelGreen(n) -GetPixelGreen(pixels))+m) /((ssize_t) (m*2))+ GetPixelGreen(pixels))); SetPixelBlue(q, (QM) ((2*i*( GetPixelBlue(n) -GetPixelBlue(pixels))+m) /((ssize_t) (m*2))+ GetPixelBlue(pixels))); if (image->matte != MagickFalse) SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m) /((ssize_t) (m*2))+ GetPixelOpacity(pixels))); } if (magn_methx == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelOpacity(q, GetPixelOpacity(pixels)+0); } else { SetPixelOpacity(q, GetPixelOpacity(n)+0); } } } else /* if (magn_methx == 3 || magn_methx == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methx == 5) { /* Interpolate */ SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m)/ ((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } q++; } n++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { /* Rescale pixels to Quantum */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleShortToQuantum( GetPixelRed(q))); SetPixelGreen(q,ScaleShortToQuantum( GetPixelGreen(q))); SetPixelBlue(q,ScaleShortToQuantum( GetPixelBlue(q))); SetPixelOpacity(q,ScaleShortToQuantum( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished MAGN processing"); } } /* Crop_box is with respect to the upper left corner of the MNG. */ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Crop the PNG image"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; /* Crop_info is with respect to the upper left corner of the image. */ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { /* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. */ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy, and promote any depths > 8 to 16. */ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (LosslessReduceDepthOK(image) != MagickFalse) image->depth = 8; #endif GetImageException(image,exception); if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading image datastream."); } while (LocaleCompare(image_info->magick,"MNG") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading all image datastreams."); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { /* Insert a background layer if nothing else was found. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No images found. Inserting a background layer."); if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocation failed, returning NULL."); return(DestroyImageList(image)); } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->matte=MagickFalse; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," No beginning"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"Linked list is corrupted, beginning of list not found", "`%s'",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Corrupt list"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"Linked list is corrupted; next_image is NULL","`%s'", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " First image null"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"image->next for first image is NULL but shouldn't be.", "`%s'",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No visible images found."); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"No visible images in file","`%s'",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay/mng_info->ticks_per_second; else image->start_loop=MagickTrue; /* Find final nonzero image delay */ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->delay=%.20g, final_delay=%.20g",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Before coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g",(double) scene++,(double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Coalesce Images"); scene=image->scene; next_image=CoalesceImages(image,&image->exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " After coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g dispose=%.20g",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g dispose=%.20g",(double) scene++, (double) image->delay,(double) image->dispose); } } 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-835'], 'message': 'Fixed infinite loop (#1095).'</s>
<s>[INST] Given the following code containing errors, provide 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 ParseRiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int is_rf64 = !strncmp (fourcc, "RF64", 4), got_ds64 = 0; int64_t total_samples = 0, infilesize; RiffChunkHeader riff_chunk_header; ChunkHeader chunk_header; WaveHeader WaveHeader; DS64Chunk ds64_chunk; uint32_t bcount; CLEAR (WaveHeader); CLEAR (ds64_chunk); infilesize = DoGetFileSize (infile); if (!is_rf64 && infilesize >= 4294967296LL && !(config->qmode & QMODE_IGNORE_LENGTH)) { error_line ("can't handle .WAV files larger than 4 GB (non-standard)!"); return WAVPACK_SOFT_ERROR; } memcpy (&riff_chunk_header, fourcc, 4); if ((!DoReadFile (infile, ((char *) &riff_chunk_header) + 4, sizeof (RiffChunkHeader) - 4, &bcount) || bcount != sizeof (RiffChunkHeader) - 4 || strncmp (riff_chunk_header.formType, "WAVE", 4))) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &riff_chunk_header, sizeof (RiffChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } // loop through all elements of the RIFF wav header // (until the data chuck) and copy them to the output file while (1) { if (!DoReadFile (infile, &chunk_header, sizeof (ChunkHeader), &bcount) || bcount != sizeof (ChunkHeader)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &chunk_header, sizeof (ChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&chunk_header, ChunkHeaderFormat); if (!strncmp (chunk_header.ckID, "ds64", 4)) { if (chunk_header.ckSize < sizeof (DS64Chunk) || !DoReadFile (infile, &ds64_chunk, sizeof (DS64Chunk), &bcount) || bcount != sizeof (DS64Chunk)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &ds64_chunk, sizeof (DS64Chunk))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } got_ds64 = 1; WavpackLittleEndianToNative (&ds64_chunk, DS64ChunkFormat); if (debug_logging_mode) error_line ("DS64: riffSize = %lld, dataSize = %lld, sampleCount = %lld, table_length = %d", (long long) ds64_chunk.riffSize64, (long long) ds64_chunk.dataSize64, (long long) ds64_chunk.sampleCount64, ds64_chunk.tableLength); if (ds64_chunk.tableLength * sizeof (CS64Chunk) != chunk_header.ckSize - sizeof (DS64Chunk)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } while (ds64_chunk.tableLength--) { CS64Chunk cs64_chunk; if (!DoReadFile (infile, &cs64_chunk, sizeof (CS64Chunk), &bcount) || bcount != sizeof (CS64Chunk) || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &cs64_chunk, sizeof (CS64Chunk)))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } } } else if (!strncmp (chunk_header.ckID, "fmt ", 4)) { // if it's the format chunk, we want to get some info out of there and int supported = TRUE, format; // make sure it's a .wav file we can handle if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) || !DoReadFile (infile, &WaveHeader, chunk_header.ckSize, &bcount) || bcount != chunk_header.ckSize) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &WaveHeader, 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 .WAV 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 WAV 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 if (config->float_norm_exp) error_line ("data format: 32-bit floating point (Audition %d:%d float type 1)", config->float_norm_exp - 126, 150 - config->float_norm_exp); else error_line ("data format: %d-bit integers stored in %d byte(s)", config->bits_per_sample, WaveHeader.BlockAlign / WaveHeader.NumChannels); } } else if (!strncmp (chunk_header.ckID, "data", 4)) { // on the data chunk, get size and exit loop int64_t data_chunk_size = (got_ds64 && chunk_header.ckSize == (uint32_t) -1) ? ds64_chunk.dataSize64 : chunk_header.ckSize; if (!WaveHeader.NumChannels || (is_rf64 && !got_ds64)) { // make sure we saw "fmt" and "ds64" chunks (if required) error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && infilesize - data_chunk_size > 16777216) { error_line ("this .WAV file has over 16 MB of extra RIFF data, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (config->qmode & QMODE_IGNORE_LENGTH) { if (infilesize && DoGetFilePosition (infile) != -1) total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign; else total_samples = -1; } else { total_samples = data_chunk_size / WaveHeader.BlockAlign; if (got_ds64 && total_samples != ds64_chunk.sampleCount64) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } if (!total_samples) { error_line ("this .WAV 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 + 1) & ~1L; 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: int CephxServiceHandler::handle_request(bufferlist::iterator& indata, bufferlist& result_bl, uint64_t& global_id, AuthCapsInfo& caps, uint64_t *auid) { int ret = 0; struct CephXRequestHeader cephx_header; ::decode(cephx_header, indata); switch (cephx_header.request_type) { case CEPHX_GET_AUTH_SESSION_KEY: { ldout(cct, 10) << "handle_request get_auth_session_key for " << entity_name << dendl; CephXAuthenticate req; ::decode(req, indata); CryptoKey secret; if (!key_server->get_secret(entity_name, secret)) { ldout(cct, 0) << "couldn't find entity name: " << entity_name << dendl; ret = -EPERM; break; } if (!server_challenge) { ret = -EPERM; break; } uint64_t expected_key; std::string error; cephx_calc_client_server_challenge(cct, secret, server_challenge, req.client_challenge, &expected_key, error); if (!error.empty()) { ldout(cct, 0) << " cephx_calc_client_server_challenge error: " << error << dendl; ret = -EPERM; break; } ldout(cct, 20) << " checking key: req.key=" << hex << req.key << " expected_key=" << expected_key << dec << dendl; if (req.key != expected_key) { ldout(cct, 0) << " unexpected key: req.key=" << hex << req.key << " expected_key=" << expected_key << dec << dendl; ret = -EPERM; break; } CryptoKey session_key; CephXSessionAuthInfo info; bool should_enc_ticket = false; EntityAuth eauth; if (! key_server->get_auth(entity_name, eauth)) { ret = -EPERM; break; } CephXServiceTicketInfo old_ticket_info; if (cephx_decode_ticket(cct, key_server, CEPH_ENTITY_TYPE_AUTH, req.old_ticket, old_ticket_info)) { global_id = old_ticket_info.ticket.global_id; ldout(cct, 10) << "decoded old_ticket with global_id=" << global_id << dendl; should_enc_ticket = true; } info.ticket.init_timestamps(ceph_clock_now(), cct->_conf->auth_mon_ticket_ttl); info.ticket.name = entity_name; info.ticket.global_id = global_id; info.ticket.auid = eauth.auid; info.validity += cct->_conf->auth_mon_ticket_ttl; if (auid) *auid = eauth.auid; key_server->generate_secret(session_key); info.session_key = session_key; info.service_id = CEPH_ENTITY_TYPE_AUTH; if (!key_server->get_service_secret(CEPH_ENTITY_TYPE_AUTH, info.service_secret, info.secret_id)) { ldout(cct, 0) << " could not get service secret for auth subsystem" << dendl; ret = -EIO; break; } vector<CephXSessionAuthInfo> info_vec; info_vec.push_back(info); build_cephx_response_header(cephx_header.request_type, 0, result_bl); if (!cephx_build_service_ticket_reply(cct, eauth.key, info_vec, should_enc_ticket, old_ticket_info.session_key, result_bl)) { ret = -EIO; } if (!key_server->get_service_caps(entity_name, CEPH_ENTITY_TYPE_MON, caps)) { ldout(cct, 0) << " could not get mon caps for " << entity_name << dendl; ret = -EACCES; } else { char *caps_str = caps.caps.c_str(); if (!caps_str || !caps_str[0]) { ldout(cct,0) << "mon caps null for " << entity_name << dendl; ret = -EACCES; } } } break; case CEPHX_GET_PRINCIPAL_SESSION_KEY: { ldout(cct, 10) << "handle_request get_principal_session_key" << dendl; bufferlist tmp_bl; CephXServiceTicketInfo auth_ticket_info; if (!cephx_verify_authorizer(cct, key_server, indata, auth_ticket_info, tmp_bl)) { ret = -EPERM; break; } CephXServiceTicketRequest ticket_req; ::decode(ticket_req, indata); ldout(cct, 10) << " ticket_req.keys = " << ticket_req.keys << dendl; ret = 0; vector<CephXSessionAuthInfo> info_vec; int found_services = 0; int service_err = 0; for (uint32_t service_id = 1; service_id <= ticket_req.keys; service_id <<= 1) { if (ticket_req.keys & service_id) { ldout(cct, 10) << " adding key for service " << ceph_entity_type_name(service_id) << dendl; CephXSessionAuthInfo info; int r = key_server->build_session_auth_info(service_id, auth_ticket_info, info); // tolerate missing MGR rotating key for the purposes of upgrades. if (r < 0) { ldout(cct, 10) << " missing key for service " << ceph_entity_type_name(service_id) << dendl; service_err = r; continue; } info.validity += cct->_conf->auth_service_ticket_ttl; info_vec.push_back(info); ++found_services; } } if (!found_services && service_err) { ldout(cct, 10) << __func__ << " did not find any service keys" << dendl; ret = service_err; } CryptoKey no_key; build_cephx_response_header(cephx_header.request_type, ret, result_bl); cephx_build_service_ticket_reply(cct, auth_ticket_info.session_key, info_vec, false, no_key, result_bl); } break; case CEPHX_GET_ROTATING_KEY: { ldout(cct, 10) << "handle_request getting rotating secret for " << entity_name << dendl; build_cephx_response_header(cephx_header.request_type, 0, result_bl); if (!key_server->get_rotating_encrypted(entity_name, result_bl)) { ret = -EPERM; break; } } break; default: ldout(cct, 10) << "handle_request unknown op " << cephx_header.request_type << dendl; return -EINVAL; } return ret; } ; 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 CephxAuthorizeHandler::verify_authorizer(CephContext *cct, KeyStore *keys, bufferlist& authorizer_data, bufferlist& authorizer_reply, EntityName& entity_name, uint64_t& global_id, AuthCapsInfo& caps_info, CryptoKey& session_key, uint64_t *auid) { bufferlist::iterator iter = authorizer_data.begin(); if (!authorizer_data.length()) { ldout(cct, 1) << "verify authorizer, authorizer_data.length()=0" << dendl; return false; } CephXServiceTicketInfo auth_ticket_info; bool isvalid = cephx_verify_authorizer(cct, keys, iter, auth_ticket_info, authorizer_reply); if (isvalid) { caps_info = auth_ticket_info.ticket.caps; entity_name = auth_ticket_info.ticket.name; global_id = auth_ticket_info.ticket.global_id; session_key = auth_ticket_info.session_key; if (auid) *auid = auth_ticket_info.ticket.auid; } return isvalid; } ; 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: int Pipe::accept() { ldout(msgr->cct,10) << "accept" << dendl; assert(pipe_lock.is_locked()); assert(state == STATE_ACCEPTING); pipe_lock.Unlock(); // vars bufferlist addrs; entity_addr_t socket_addr; socklen_t len; int r; char banner[strlen(CEPH_BANNER)+1]; bufferlist addrbl; ceph_msg_connect connect; ceph_msg_connect_reply reply; Pipe *existing = 0; bufferptr bp; bufferlist authorizer, authorizer_reply; bool authorizer_valid; uint64_t feat_missing; bool replaced = false; // this variable denotes if the connection attempt from peer is a hard // reset or not, it is true if there is an existing connection and the // connection sequence from peer is equal to zero bool is_reset_from_peer = false; CryptoKey session_key; int removed; // single-use down below // this should roughly mirror pseudocode at // http://ceph.com/wiki/Messaging_protocol int reply_tag = 0; uint64_t existing_seq = -1; // used for reading in the remote acked seq on connect uint64_t newly_acked_seq = 0; recv_reset(); set_socket_options(); // announce myself. r = tcp_write(CEPH_BANNER, strlen(CEPH_BANNER)); if (r < 0) { ldout(msgr->cct,10) << "accept couldn't write banner" << dendl; goto fail_unlocked; } // and my addr ::encode(msgr->my_inst.addr, addrs, 0); // legacy port = msgr->my_inst.addr.get_port(); // and peer's socket addr (they might not know their ip) sockaddr_storage ss; len = sizeof(ss); r = ::getpeername(sd, (sockaddr*)&ss, &len); if (r < 0) { ldout(msgr->cct,0) << "accept failed to getpeername " << cpp_strerror(errno) << dendl; goto fail_unlocked; } socket_addr.set_sockaddr((sockaddr*)&ss); ::encode(socket_addr, addrs, 0); // legacy r = tcp_write(addrs.c_str(), addrs.length()); if (r < 0) { ldout(msgr->cct,10) << "accept couldn't write my+peer addr" << dendl; goto fail_unlocked; } ldout(msgr->cct,1) << "accept sd=" << sd << " " << socket_addr << dendl; // identify peer if (tcp_read(banner, strlen(CEPH_BANNER)) < 0) { ldout(msgr->cct,10) << "accept couldn't read banner" << dendl; goto fail_unlocked; } if (memcmp(banner, CEPH_BANNER, strlen(CEPH_BANNER))) { banner[strlen(CEPH_BANNER)] = 0; ldout(msgr->cct,1) << "accept peer sent bad banner '" << banner << "' (should be '" << CEPH_BANNER << "')" << dendl; goto fail_unlocked; } { bufferptr tp(sizeof(ceph_entity_addr)); addrbl.push_back(std::move(tp)); } if (tcp_read(addrbl.c_str(), addrbl.length()) < 0) { ldout(msgr->cct,10) << "accept couldn't read peer_addr" << dendl; goto fail_unlocked; } { bufferlist::iterator ti = addrbl.begin(); ::decode(peer_addr, ti); } ldout(msgr->cct,10) << "accept peer addr is " << peer_addr << dendl; if (peer_addr.is_blank_ip()) { // peer apparently doesn't know what ip they have; figure it out for them. int port = peer_addr.get_port(); peer_addr.u = socket_addr.u; peer_addr.set_port(port); ldout(msgr->cct,0) << "accept peer addr is really " << peer_addr << " (socket is " << socket_addr << ")" << dendl; } set_peer_addr(peer_addr); // so that connection_state gets set up while (1) { if (tcp_read((char*)&connect, sizeof(connect)) < 0) { ldout(msgr->cct,10) << "accept couldn't read connect" << dendl; goto fail_unlocked; } authorizer.clear(); if (connect.authorizer_len) { bp = buffer::create(connect.authorizer_len); if (tcp_read(bp.c_str(), connect.authorizer_len) < 0) { ldout(msgr->cct,10) << "accept couldn't read connect authorizer" << dendl; goto fail_unlocked; } authorizer.push_back(std::move(bp)); authorizer_reply.clear(); } ldout(msgr->cct,20) << "accept got peer connect_seq " << connect.connect_seq << " global_seq " << connect.global_seq << dendl; msgr->lock.Lock(); // FIXME pipe_lock.Lock(); if (msgr->dispatch_queue.stop) goto shutting_down; if (state != STATE_ACCEPTING) { goto shutting_down; } // note peer's type, flags set_peer_type(connect.host_type); policy = msgr->get_policy(connect.host_type); ldout(msgr->cct,10) << "accept of host_type " << connect.host_type << ", policy.lossy=" << policy.lossy << " policy.server=" << policy.server << " policy.standby=" << policy.standby << " policy.resetcheck=" << policy.resetcheck << dendl; memset(&reply, 0, sizeof(reply)); reply.protocol_version = msgr->get_proto_version(peer_type, false); msgr->lock.Unlock(); // mismatch? ldout(msgr->cct,10) << "accept my proto " << reply.protocol_version << ", their proto " << connect.protocol_version << dendl; if (connect.protocol_version != reply.protocol_version) { reply.tag = CEPH_MSGR_TAG_BADPROTOVER; goto reply; } // require signatures for cephx? if (connect.authorizer_protocol == CEPH_AUTH_CEPHX) { if (peer_type == CEPH_ENTITY_TYPE_OSD || peer_type == CEPH_ENTITY_TYPE_MDS || peer_type == CEPH_ENTITY_TYPE_MGR) { if (msgr->cct->_conf->cephx_require_signatures || msgr->cct->_conf->cephx_cluster_require_signatures) { ldout(msgr->cct,10) << "using cephx, requiring MSG_AUTH feature bit for cluster" << dendl; policy.features_required |= CEPH_FEATURE_MSG_AUTH; } if (msgr->cct->_conf->cephx_require_version >= 2 || msgr->cct->_conf->cephx_cluster_require_version >= 2) { ldout(msgr->cct,10) << "using cephx, requiring cephx v2 feature bit for cluster" << dendl; policy.features_required |= CEPH_FEATUREMASK_CEPHX_V2; } } else { if (msgr->cct->_conf->cephx_require_signatures || msgr->cct->_conf->cephx_service_require_signatures) { ldout(msgr->cct,10) << "using cephx, requiring MSG_AUTH feature bit for service" << dendl; policy.features_required |= CEPH_FEATURE_MSG_AUTH; } if (msgr->cct->_conf->cephx_require_version >= 2 || msgr->cct->_conf->cephx_service_require_version >= 2) { ldout(msgr->cct,10) << "using cephx, requiring cephx v2 feature bit for cluster" << dendl; policy.features_required |= CEPH_FEATUREMASK_CEPHX_V2; } } } feat_missing = policy.features_required & ~(uint64_t)connect.features; if (feat_missing) { ldout(msgr->cct,1) << "peer missing required features " << std::hex << feat_missing << std::dec << dendl; reply.tag = CEPH_MSGR_TAG_FEATURES; goto reply; } // Check the authorizer. If not good, bail out. pipe_lock.Unlock(); if (!msgr->verify_authorizer(connection_state.get(), peer_type, connect.authorizer_protocol, authorizer, authorizer_reply, authorizer_valid, session_key) || !authorizer_valid) { ldout(msgr->cct,0) << "accept: got bad authorizer" << dendl; pipe_lock.Lock(); if (state != STATE_ACCEPTING) goto shutting_down_msgr_unlocked; reply.tag = CEPH_MSGR_TAG_BADAUTHORIZER; session_security.reset(); goto reply; } // We've verified the authorizer for this pipe, so set up the session security structure. PLR ldout(msgr->cct,10) << "accept: setting up session_security." << dendl; retry_existing_lookup: msgr->lock.Lock(); pipe_lock.Lock(); if (msgr->dispatch_queue.stop) goto shutting_down; if (state != STATE_ACCEPTING) goto shutting_down; // existing? existing = msgr->_lookup_pipe(peer_addr); if (existing) { existing->pipe_lock.Lock(true); // skip lockdep check (we are locking a second Pipe here) if (existing->reader_dispatching) { /** we need to wait, or we can deadlock if downstream * fast_dispatchers are (naughtily!) waiting on resources * held by somebody trying to make use of the SimpleMessenger lock. * So drop locks, wait, and retry. It just looks like a slow network * to everybody else. * * We take a ref to existing here since it might get reaped before we * wake up (see bug #15870). We can be confident that it lived until * locked it since we held the msgr lock from _lookup_pipe through to * locking existing->lock and checking reader_dispatching. */ existing->get(); pipe_lock.Unlock(); msgr->lock.Unlock(); existing->notify_on_dispatch_done = true; while (existing->reader_dispatching) existing->cond.Wait(existing->pipe_lock); existing->pipe_lock.Unlock(); existing->put(); existing = nullptr; goto retry_existing_lookup; } if (connect.global_seq < existing->peer_global_seq) { ldout(msgr->cct,10) << "accept existing " << existing << ".gseq " << existing->peer_global_seq << " > " << connect.global_seq << ", RETRY_GLOBAL" << dendl; reply.tag = CEPH_MSGR_TAG_RETRY_GLOBAL; reply.global_seq = existing->peer_global_seq; // so we can send it below.. existing->pipe_lock.Unlock(); msgr->lock.Unlock(); goto reply; } else { ldout(msgr->cct,10) << "accept existing " << existing << ".gseq " << existing->peer_global_seq << " <= " << connect.global_seq << ", looks ok" << dendl; } if (existing->policy.lossy) { ldout(msgr->cct,0) << "accept replacing existing (lossy) channel (new one lossy=" << policy.lossy << ")" << dendl; existing->was_session_reset(); goto replace; } ldout(msgr->cct,0) << "accept connect_seq " << connect.connect_seq << " vs existing " << existing->connect_seq << " state " << existing->get_state_name() << dendl; if (connect.connect_seq == 0 && existing->connect_seq > 0) { ldout(msgr->cct,0) << "accept peer reset, then tried to connect to us, replacing" << dendl; // this is a hard reset from peer is_reset_from_peer = true; if (policy.resetcheck) existing->was_session_reset(); // this resets out_queue, msg_ and connect_seq #'s goto replace; } if (connect.connect_seq < existing->connect_seq) { // old attempt, or we sent READY but they didn't get it. ldout(msgr->cct,10) << "accept existing " << existing << ".cseq " << existing->connect_seq << " > " << connect.connect_seq << ", RETRY_SESSION" << dendl; goto retry_session; } if (connect.connect_seq == existing->connect_seq) { // if the existing connection successfully opened, and/or // subsequently went to standby, then the peer should bump // their connect_seq and retry: this is not a connection race // we need to resolve here. if (existing->state == STATE_OPEN || existing->state == STATE_STANDBY) { ldout(msgr->cct,10) << "accept connection race, existing " << existing << ".cseq " << existing->connect_seq << " == " << connect.connect_seq << ", OPEN|STANDBY, RETRY_SESSION" << dendl; goto retry_session; } // connection race? if (peer_addr < msgr->my_inst.addr || existing->policy.server) { // incoming wins ldout(msgr->cct,10) << "accept connection race, existing " << existing << ".cseq " << existing->connect_seq << " == " << connect.connect_seq << ", or we are server, replacing my attempt" << dendl; if (!(existing->state == STATE_CONNECTING || existing->state == STATE_WAIT)) lderr(msgr->cct) << "accept race bad state, would replace, existing=" << existing->get_state_name() << " " << existing << ".cseq=" << existing->connect_seq << " == " << connect.connect_seq << dendl; assert(existing->state == STATE_CONNECTING || existing->state == STATE_WAIT); goto replace; } else { // our existing outgoing wins ldout(msgr->cct,10) << "accept connection race, existing " << existing << ".cseq " << existing->connect_seq << " == " << connect.connect_seq << ", sending WAIT" << dendl; assert(peer_addr > msgr->my_inst.addr); if (!(existing->state == STATE_CONNECTING)) lderr(msgr->cct) << "accept race bad state, would send wait, existing=" << existing->get_state_name() << " " << existing << ".cseq=" << existing->connect_seq << " == " << connect.connect_seq << dendl; assert(existing->state == STATE_CONNECTING); // make sure our outgoing connection will follow through existing->_send_keepalive(); reply.tag = CEPH_MSGR_TAG_WAIT; existing->pipe_lock.Unlock(); msgr->lock.Unlock(); goto reply; } } assert(connect.connect_seq > existing->connect_seq); assert(connect.global_seq >= existing->peer_global_seq); if (policy.resetcheck && // RESETSESSION only used by servers; peers do not reset each other existing->connect_seq == 0) { ldout(msgr->cct,0) << "accept we reset (peer sent cseq " << connect.connect_seq << ", " << existing << ".cseq = " << existing->connect_seq << "), sending RESETSESSION" << dendl; reply.tag = CEPH_MSGR_TAG_RESETSESSION; msgr->lock.Unlock(); existing->pipe_lock.Unlock(); goto reply; } // reconnect ldout(msgr->cct,10) << "accept peer sent cseq " << connect.connect_seq << " > " << existing->connect_seq << dendl; goto replace; } // existing else if (connect.connect_seq > 0) { // we reset, and they are opening a new session ldout(msgr->cct,0) << "accept we reset (peer sent cseq " << connect.connect_seq << "), sending RESETSESSION" << dendl; msgr->lock.Unlock(); reply.tag = CEPH_MSGR_TAG_RESETSESSION; goto reply; } else { // new session ldout(msgr->cct,10) << "accept new session" << dendl; existing = NULL; goto open; } ceph_abort(); retry_session: assert(existing->pipe_lock.is_locked()); assert(pipe_lock.is_locked()); reply.tag = CEPH_MSGR_TAG_RETRY_SESSION; reply.connect_seq = existing->connect_seq + 1; existing->pipe_lock.Unlock(); msgr->lock.Unlock(); goto reply; reply: assert(pipe_lock.is_locked()); reply.features = ((uint64_t)connect.features & policy.features_supported) | policy.features_required; reply.authorizer_len = authorizer_reply.length(); pipe_lock.Unlock(); r = tcp_write((char*)&reply, sizeof(reply)); if (r < 0) goto fail_unlocked; if (reply.authorizer_len) { r = tcp_write(authorizer_reply.c_str(), authorizer_reply.length()); if (r < 0) goto fail_unlocked; } } replace: assert(existing->pipe_lock.is_locked()); assert(pipe_lock.is_locked()); // if it is a hard reset from peer, we don't need a round-trip to negotiate in/out sequence if ((connect.features & CEPH_FEATURE_RECONNECT_SEQ) && !is_reset_from_peer) { reply_tag = CEPH_MSGR_TAG_SEQ; existing_seq = existing->in_seq; } ldout(msgr->cct,10) << "accept replacing " << existing << dendl; existing->stop(); existing->unregister_pipe(); replaced = true; if (existing->policy.lossy) { // disconnect from the Connection assert(existing->connection_state); if (existing->connection_state->clear_pipe(existing)) msgr->dispatch_queue.queue_reset(existing->connection_state.get()); } else { // queue a reset on the new connection, which we're dumping for the old msgr->dispatch_queue.queue_reset(connection_state.get()); // drop my Connection, and take a ref to the existing one. do not // clear existing->connection_state, since read_message and // write_message both dereference it without pipe_lock. connection_state = existing->connection_state; // make existing Connection reference us connection_state->reset_pipe(this); if (existing->delay_thread) { existing->delay_thread->steal_for_pipe(this); delay_thread = existing->delay_thread; existing->delay_thread = NULL; delay_thread->flush(); } // steal incoming queue uint64_t replaced_conn_id = conn_id; conn_id = existing->conn_id; existing->conn_id = replaced_conn_id; // reset the in_seq if this is a hard reset from peer, // otherwise we respect our original connection's value in_seq = is_reset_from_peer ? 0 : existing->in_seq; in_seq_acked = in_seq; // steal outgoing queue and out_seq existing->requeue_sent(); out_seq = existing->out_seq; ldout(msgr->cct,10) << "accept re-queuing on out_seq " << out_seq << " in_seq " << in_seq << dendl; for (map<int, list<Message*> >::iterator p = existing->out_q.begin(); p != existing->out_q.end(); ++p) out_q[p->first].splice(out_q[p->first].begin(), p->second); } existing->stop_and_wait(); existing->pipe_lock.Unlock(); open: // open assert(pipe_lock.is_locked()); connect_seq = connect.connect_seq + 1; peer_global_seq = connect.global_seq; assert(state == STATE_ACCEPTING); state = STATE_OPEN; ldout(msgr->cct,10) << "accept success, connect_seq = " << connect_seq << ", sending READY" << dendl; // send READY reply reply.tag = (reply_tag ? reply_tag : CEPH_MSGR_TAG_READY); reply.features = policy.features_supported; reply.global_seq = msgr->get_global_seq(); reply.connect_seq = connect_seq; reply.flags = 0; reply.authorizer_len = authorizer_reply.length(); if (policy.lossy) reply.flags = reply.flags | CEPH_MSG_CONNECT_LOSSY; connection_state->set_features((uint64_t)reply.features & (uint64_t)connect.features); ldout(msgr->cct,10) << "accept features " << connection_state->get_features() << dendl; session_security.reset( get_auth_session_handler(msgr->cct, connect.authorizer_protocol, session_key, connection_state->get_features())); // notify msgr->dispatch_queue.queue_accept(connection_state.get()); msgr->ms_deliver_handle_fast_accept(connection_state.get()); // ok! if (msgr->dispatch_queue.stop) goto shutting_down; removed = msgr->accepting_pipes.erase(this); assert(removed == 1); register_pipe(); msgr->lock.Unlock(); pipe_lock.Unlock(); r = tcp_write((char*)&reply, sizeof(reply)); if (r < 0) { goto fail_registered; } if (reply.authorizer_len) { r = tcp_write(authorizer_reply.c_str(), authorizer_reply.length()); if (r < 0) { goto fail_registered; } } if (reply_tag == CEPH_MSGR_TAG_SEQ) { if (tcp_write((char*)&existing_seq, sizeof(existing_seq)) < 0) { ldout(msgr->cct,2) << "accept write error on in_seq" << dendl; goto fail_registered; } if (tcp_read((char*)&newly_acked_seq, sizeof(newly_acked_seq)) < 0) { ldout(msgr->cct,2) << "accept read error on newly_acked_seq" << dendl; goto fail_registered; } } pipe_lock.Lock(); discard_requeued_up_to(newly_acked_seq); if (state != STATE_CLOSED) { ldout(msgr->cct,10) << "accept starting writer, state " << get_state_name() << dendl; start_writer(); } ldout(msgr->cct,20) << "accept done" << dendl; maybe_start_delay_thread(); return 0; // success. fail_registered: ldout(msgr->cct, 10) << "accept fault after register" << dendl; if (msgr->cct->_conf->ms_inject_internal_delays) { ldout(msgr->cct, 10) << " sleep for " << msgr->cct->_conf->ms_inject_internal_delays << dendl; utime_t t; t.set_from_double(msgr->cct->_conf->ms_inject_internal_delays); t.sleep(); } fail_unlocked: pipe_lock.Lock(); if (state != STATE_CLOSED) { bool queued = is_queued(); ldout(msgr->cct, 10) << " queued = " << (int)queued << dendl; if (queued) { state = policy.server ? STATE_STANDBY : STATE_CONNECTING; } else if (replaced) { state = STATE_STANDBY; } else { state = STATE_CLOSED; state_closed = true; } fault(); if (queued || replaced) start_writer(); } return -1; shutting_down: msgr->lock.Unlock(); shutting_down_msgr_unlocked: assert(pipe_lock.is_locked()); if (msgr->cct->_conf->ms_inject_internal_delays) { ldout(msgr->cct, 10) << " sleep for " << msgr->cct->_conf->ms_inject_internal_delays << dendl; utime_t t; t.set_from_double(msgr->cct->_conf->ms_inject_internal_delays); t.sleep(); } state = STATE_CLOSED; state_closed = true; fault(); return -1; } ; 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: static void addECSOption(char* packet, const size_t& packetSize, uint16_t* len, const ComboAddress& remote, int stamp) { string EDNSRR; struct dnsheader* dh = (struct dnsheader*) packet; EDNSSubnetOpts eso; if(stamp < 0) eso.source = Netmask(remote); else { ComboAddress stamped(remote); *((char*)&stamped.sin4.sin_addr.s_addr)=stamp; eso.source = Netmask(stamped); } string optRData=makeEDNSSubnetOptsString(eso); string record; generateEDNSOption(EDNSOptionCode::ECS, optRData, record); generateOptRR(record, EDNSRR); uint16_t arcount = ntohs(dh->arcount); /* does it fit in the existing buffer? */ if (packetSize - *len > EDNSRR.size()) { arcount++; dh->arcount = htons(arcount); memcpy(packet + *len, EDNSRR.c_str(), EDNSRR.size()); *len += EDNSRR.size(); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'dnsreplay: Bail out on a too small outgoing 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: int ldb_kv_search(struct ldb_kv_context *ctx) { struct ldb_context *ldb; struct ldb_module *module = ctx->module; struct ldb_request *req = ctx->req; void *data = ldb_module_get_private(module); struct ldb_kv_private *ldb_kv = talloc_get_type(data, struct ldb_kv_private); int ret; ldb = ldb_module_get_ctx(module); ldb_request_set_state(req, LDB_ASYNC_PENDING); if (ldb_kv->kv_ops->lock_read(module) != 0) { return LDB_ERR_OPERATIONS_ERROR; } if (ldb_kv_cache_load(module) != 0) { ldb_kv->kv_ops->unlock_read(module); return LDB_ERR_OPERATIONS_ERROR; } if (req->op.search.tree == NULL) { ldb_kv->kv_ops->unlock_read(module); return LDB_ERR_OPERATIONS_ERROR; } ctx->tree = req->op.search.tree; ctx->scope = req->op.search.scope; ctx->base = req->op.search.base; ctx->attrs = req->op.search.attrs; if ((req->op.search.base == NULL) || (ldb_dn_is_null(req->op.search.base) == true)) { /* Check what we should do with a NULL dn */ switch (req->op.search.scope) { case LDB_SCOPE_BASE: ldb_asprintf_errstring(ldb, "NULL Base DN invalid for a base search"); ret = LDB_ERR_INVALID_DN_SYNTAX; break; case LDB_SCOPE_ONELEVEL: ldb_asprintf_errstring(ldb, "NULL Base DN invalid for a one-level search"); ret = LDB_ERR_INVALID_DN_SYNTAX; break; case LDB_SCOPE_SUBTREE: default: /* We accept subtree searches from a NULL base DN, ie over the whole DB */ ret = LDB_SUCCESS; } } else if (ldb_dn_is_valid(req->op.search.base) == false) { /* We don't want invalid base DNs here */ ldb_asprintf_errstring(ldb, "Invalid Base DN: %s", ldb_dn_get_linearized(req->op.search.base)); ret = LDB_ERR_INVALID_DN_SYNTAX; } else if (req->op.search.scope == LDB_SCOPE_BASE) { /* * If we are LDB_SCOPE_BASE, do just one search and * return early. This is critical to ensure we do not * go into the index code for special DNs, as that * will try to look up an index record for a special * record (which doesn't exist). */ ret = ldb_kv_search_and_return_base(ldb_kv, ctx); ldb_kv->kv_ops->unlock_read(module); return ret; } else if (ldb_kv->check_base) { /* * This database has been marked as * 'checkBaseOnSearch', so do a spot check of the base * dn. Also optimise the subsequent filter by filling * in the ctx->base to be exactly case correct */ ret = ldb_kv_search_base( module, ctx, req->op.search.base, &ctx->base); if (ret == LDB_ERR_NO_SUCH_OBJECT) { ldb_asprintf_errstring(ldb, "No such Base DN: %s", ldb_dn_get_linearized(req->op.search.base)); } } else { /* If we are not checking the base DN life is easy */ ret = LDB_SUCCESS; } if (ret == LDB_SUCCESS) { uint32_t match_count = 0; ret = ldb_kv_search_indexed(ctx, &match_count); if (ret == LDB_ERR_NO_SUCH_OBJECT) { /* Not in the index, therefore OK! */ ret = LDB_SUCCESS; } /* Check if we got just a normal error. * In that case proceed to a full search unless we got a * callback error */ if (!ctx->request_terminated && ret != LDB_SUCCESS) { /* Not indexed, so we need to do a full scan */ if (ldb_kv->warn_unindexed || ldb_kv->disable_full_db_scan) { /* useful for debugging when slow performance * is caused by unindexed searches */ char *expression = ldb_filter_from_tree(ctx, ctx->tree); ldb_debug(ldb, LDB_DEBUG_ERROR, "ldb FULL SEARCH: %s SCOPE: %s DN: %s", expression, req->op.search.scope==LDB_SCOPE_BASE?"base": req->op.search.scope==LDB_SCOPE_ONELEVEL?"one": req->op.search.scope==LDB_SCOPE_SUBTREE?"sub":"UNKNOWN", ldb_dn_get_linearized(req->op.search.base)); talloc_free(expression); } if (match_count != 0) { /* the indexing code gave an error * after having returned at least one * entry. This means the indexes are * corrupt or a database record is * corrupt. We cannot continue with a * full search or we may return * duplicate entries */ ldb_kv->kv_ops->unlock_read(module); return LDB_ERR_OPERATIONS_ERROR; } if (ldb_kv->disable_full_db_scan) { ldb_set_errstring(ldb, "ldb FULL SEARCH disabled"); ldb_kv->kv_ops->unlock_read(module); return LDB_ERR_INAPPROPRIATE_MATCHING; } ret = ldb_kv_search_full(ctx); if (ret != LDB_SUCCESS) { ldb_set_errstring(ldb, "Indexed and full searches both failed!\n"); } } } ldb_kv->kv_ops->unlock_read(module); 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::canPack() { union { unsigned char buf[sizeof(Elf32_Ehdr) + 14*sizeof(Elf32_Phdr)]; //struct { Elf32_Ehdr ehdr; Elf32_Phdr phdr; } e; } u; COMPILE_TIME_ASSERT(sizeof(u.buf) <= 512) fi->seek(0, SEEK_SET); fi->readx(u.buf, sizeof(u.buf)); fi->seek(0, SEEK_SET); Elf32_Ehdr const *const ehdr = (Elf32_Ehdr *) u.buf; // now check the ELF header if (checkEhdr(ehdr) != 0) return false; // additional requirements for linux/elf386 if (get_te16(&ehdr->e_ehsize) != sizeof(*ehdr)) { throwCantPack("invalid Ehdr e_ehsize; try '--force-execve'"); return false; } if (e_phoff != sizeof(*ehdr)) {// Phdrs not contiguous with Ehdr throwCantPack("non-contiguous Ehdr/Phdr; try '--force-execve'"); return false; } unsigned char osabi0 = u.buf[Elf32_Ehdr::EI_OSABI]; // The first PT_LOAD32 must cover the beginning of the file (0==p_offset). Elf32_Phdr const *phdr = phdri; note_size = 0; for (unsigned j=0; j < e_phnum; ++phdr, ++j) { if (j >= 14) { throwCantPack("too many ElfXX_Phdr; try '--force-execve'"); return false; } unsigned const p_type = get_te32(&phdr->p_type); unsigned const p_offset = get_te32(&phdr->p_offset); if (1!=exetype && PT_LOAD32 == p_type) { // 1st PT_LOAD exetype = 1; load_va = get_te32(&phdr->p_vaddr); // class data member // Cast on next line is to avoid a compiler bug (incorrect complaint) in // Microsoft (R) C/C++ Optimizing Compiler Version 19.00.24215.1 for x64 // error C4319: '~': zero extending 'unsigned int' to 'upx_uint64_t' of greater size unsigned const off = ~page_mask & (unsigned)load_va; if (off && off == p_offset) { // specific hint throwCantPack("Go-language PT_LOAD: try hemfix.c, or try '--force-execve'"); // Fixing it inside upx fails because packExtent() reads original file. return false; } if (0 != p_offset) { // 1st PT_LOAD must cover Ehdr and Phdr throwCantPack("first PT_LOAD.p_offset != 0; try '--force-execve'"); return false; } hatch_off = ~3u & (3+ get_te32(&phdr->p_memsz)); } if (PT_NOTE32 == p_type) { unsigned const x = get_te32(&phdr->p_memsz); if ( sizeof(elfout.notes) < x // beware overflow of note_size || (sizeof(elfout.notes) < (note_size += x)) ) { throwCantPack("PT_NOTEs too big; try '--force-execve'"); return false; } if (osabi_note && Elf32_Ehdr::ELFOSABI_NONE==osabi0) { // Still seems to be generic. struct { struct Elf32_Nhdr nhdr; char name[8]; unsigned body; } note; memset(&note, 0, sizeof(note)); fi->seek(p_offset, SEEK_SET); fi->readx(&note, sizeof(note)); fi->seek(0, SEEK_SET); if (4==get_te32(&note.nhdr.descsz) && 1==get_te32(&note.nhdr.type) // && 0==note.end && (1+ strlen(osabi_note))==get_te32(&note.nhdr.namesz) && 0==strcmp(osabi_note, (char const *)&note.name[0]) ) { osabi0 = ei_osabi; // Specified by PT_NOTE. } } } } if (Elf32_Ehdr::ELFOSABI_NONE ==osabi0 || Elf32_Ehdr::ELFOSABI_LINUX==osabi0) { // No EI_OSBAI, no PT_NOTE. unsigned const arm_eabi = 0xff000000u & get_te32(&ehdr->e_flags); if (Elf32_Ehdr::EM_ARM==e_machine && (EF_ARM_EABI_VER5==arm_eabi || EF_ARM_EABI_VER4==arm_eabi ) ) { // armel-eabi armeb-eabi ARM Linux EABI version 4 is a mess. ei_osabi = osabi0 = Elf32_Ehdr::ELFOSABI_LINUX; } else { osabi0 = opt->o_unix.osabi0; // Possibly specified by command-line. } } if (osabi0!=ei_osabi) { return false; } // We want to compress position-independent executable (gcc -pie) // main programs, but compressing a shared library must be avoided // because the result is no longer usable. In theory, there is no way // to tell them apart: both are just ET_DYN. Also in theory, // neither the presence nor the absence of any particular symbol name // can be used to tell them apart; there are counterexamples. // However, we will use the following heuristic suggested by // Peter S. Mazinger <ps.m@gmx.net> September 2005: // If a ET_DYN has __libc_start_main as a global undefined symbol, // then the file is a position-independent executable main program // (that depends on libc.so.6) and is eligible to be compressed. // Otherwise (no __libc_start_main as global undefined): skip it. // Also allow __uClibc_main and __uClibc_start_main . if (Elf32_Ehdr::ET_DYN==get_te16(&ehdr->e_type)) { // The DT_SYMTAB has no designated length. Read the whole file. alloc_file_image(file_image, file_size); fi->seek(0, SEEK_SET); fi->readx(file_image, file_size); memcpy(&ehdri, ehdr, sizeof(Elf32_Ehdr)); phdri= (Elf32_Phdr *)((size_t)e_phoff + file_image); // do not free() !! shdri= (Elf32_Shdr *)((size_t)e_shoff + file_image); // do not free() !! sec_strndx = &shdri[get_te16(&ehdr->e_shstrndx)]; shstrtab = (char const *)(get_te32(&sec_strndx->sh_offset) + file_image); sec_dynsym = elf_find_section_type(Elf32_Shdr::SHT_DYNSYM); if (sec_dynsym) sec_dynstr = get_te32(&sec_dynsym->sh_link) + shdri; if (Elf32_Shdr::SHT_STRTAB != get_te32(&sec_strndx->sh_type) || 0!=strcmp((char const *)".shstrtab", &shstrtab[get_te32(&sec_strndx->sh_name)]) ) { throwCantPack("bad e_shstrndx"); } phdr= phdri; for (int j= e_phnum; --j>=0; ++phdr) if (Elf32_Phdr::PT_DYNAMIC==get_te32(&phdr->p_type)) { dynseg= (Elf32_Dyn const *)(check_pt_dynamic(phdr) + file_image); invert_pt_dynamic(dynseg); break; } // elf_find_dynamic() returns 0 if 0==dynseg. dynstr= (char const *)elf_find_dynamic(Elf32_Dyn::DT_STRTAB); dynsym= (Elf32_Sym const *)elf_find_dynamic(Elf32_Dyn::DT_SYMTAB); if (opt->o_unix.force_pie || Elf32_Dyn::DF_1_PIE & elf_unsigned_dynamic(Elf32_Dyn::DT_FLAGS_1) || calls_crt1((Elf32_Rel const *)elf_find_dynamic(Elf32_Dyn::DT_REL), (int)elf_unsigned_dynamic(Elf32_Dyn::DT_RELSZ)) || calls_crt1((Elf32_Rel const *)elf_find_dynamic(Elf32_Dyn::DT_JMPREL), (int)elf_unsigned_dynamic(Elf32_Dyn::DT_PLTRELSZ))) { is_pie = true; goto proceed; // calls C library init for main program } // Heuristic HACK for shared libraries (compare Darwin (MacOS) Dylib.) // If there is an existing DT_INIT, and if everything that the dynamic // linker ld-linux needs to perform relocations before calling DT_INIT // resides below the first SHT_EXECINSTR Section in one PT_LOAD, then // compress from the first executable Section to the end of that PT_LOAD. // We must not alter anything that ld-linux might touch before it calls // the DT_INIT function. // // Obviously this hack requires that the linker script put pieces // into good positions when building the original shared library, // and also requires ld-linux to behave. // Apparently glibc-2.13.90 insists on 0==e_ident[EI_PAD..15], // so compressing shared libraries may be doomed anyway. // 2011-06-01: stub.shlib-init.S works around by installing hatch // at end of .text. if (/*jni_onload_sym ||*/ elf_find_dynamic(upx_dt_init)) { if (this->e_machine!=Elf32_Ehdr::EM_386 && this->e_machine!=Elf32_Ehdr::EM_MIPS && this->e_machine!=Elf32_Ehdr::EM_ARM) goto abandon; // need stub: EM_PPC if (elf_has_dynamic(Elf32_Dyn::DT_TEXTREL)) { throwCantPack("DT_TEXTREL found; re-compile with -fPIC"); goto abandon; } Elf32_Shdr const *shdr = shdri; xct_va = ~0u; if (e_shnum) { for (int j= e_shnum; --j>=0; ++shdr) { unsigned const sh_type = get_te32(&shdr->sh_type); if (Elf32_Shdr::SHF_EXECINSTR & get_te32(&shdr->sh_flags)) { xct_va = umin(xct_va, get_te32(&shdr->sh_addr)); } // Hook the first slot of DT_PREINIT_ARRAY or DT_INIT_ARRAY. if (( Elf32_Dyn::DT_PREINIT_ARRAY==upx_dt_init && Elf32_Shdr::SHT_PREINIT_ARRAY==sh_type) || ( Elf32_Dyn::DT_INIT_ARRAY ==upx_dt_init && Elf32_Shdr::SHT_INIT_ARRAY ==sh_type) ) { user_init_off = get_te32(&shdr->sh_offset); user_init_va = get_te32(&file_image[user_init_off]); } // By default /usr/bin/ld leaves 4 extra DT_NULL to support pre-linking. // Take one as a last resort. if ((Elf32_Dyn::DT_INIT==upx_dt_init || !upx_dt_init) && Elf32_Shdr::SHT_DYNAMIC == sh_type) { unsigned const n = get_te32(&shdr->sh_size) / sizeof(Elf32_Dyn); Elf32_Dyn *dynp = (Elf32_Dyn *)&file_image[get_te32(&shdr->sh_offset)]; for (; Elf32_Dyn::DT_NULL != dynp->d_tag; ++dynp) { if (upx_dt_init == get_te32(&dynp->d_tag)) { break; // re-found DT_INIT } } if ((1+ dynp) < (n+ dynseg)) { // not the terminator, so take it user_init_va = get_te32(&dynp->d_val); // 0 if (0==upx_dt_init) set_te32(&dynp->d_tag, upx_dt_init = Elf32_Dyn::DT_INIT); user_init_off = (char const *)&dynp->d_val - (char const *)&file_image[0]; } } } } else { // no Sections; use heuristics unsigned const strsz = elf_unsigned_dynamic(Elf32_Dyn::DT_STRSZ); unsigned const strtab = elf_unsigned_dynamic(Elf32_Dyn::DT_STRTAB); unsigned const relsz = elf_unsigned_dynamic(Elf32_Dyn::DT_RELSZ); unsigned const rel = elf_unsigned_dynamic(Elf32_Dyn::DT_REL); unsigned const init = elf_unsigned_dynamic(upx_dt_init); if ((init == (relsz + rel ) && rel == (strsz + strtab)) || (init == (strsz + strtab) && strtab == (relsz + rel )) ) { xct_va = init; user_init_va = init; user_init_off = elf_get_offset_from_address(init); } } // Rely on 0==elf_unsigned_dynamic(tag) if no such tag. unsigned const va_gash = elf_unsigned_dynamic(Elf32_Dyn::DT_GNU_HASH); unsigned const va_hash = elf_unsigned_dynamic(Elf32_Dyn::DT_HASH); if (xct_va < va_gash || (0==va_gash && xct_va < va_hash) || xct_va < elf_unsigned_dynamic(Elf32_Dyn::DT_STRTAB) || xct_va < elf_unsigned_dynamic(Elf32_Dyn::DT_SYMTAB) || xct_va < elf_unsigned_dynamic(Elf32_Dyn::DT_REL) || xct_va < elf_unsigned_dynamic(Elf32_Dyn::DT_RELA) || xct_va < elf_unsigned_dynamic(Elf32_Dyn::DT_JMPREL) || xct_va < elf_unsigned_dynamic(Elf32_Dyn::DT_VERDEF) || xct_va < elf_unsigned_dynamic(Elf32_Dyn::DT_VERSYM) || xct_va < elf_unsigned_dynamic(Elf32_Dyn::DT_VERNEEDED) ) { throwCantPack("DT_ tag above stub"); goto abandon; } if (!opt->o_unix.android_shlib) { phdr = phdri; for (unsigned j= 0; j < e_phnum; ++phdr, ++j) { unsigned const vaddr = get_te32(&phdr->p_vaddr); if (PT_NOTE32 == get_te32(&phdr->p_type) && xct_va < vaddr) { char buf[40]; snprintf(buf, sizeof(buf), "PT_NOTE %#x above stub", vaddr); throwCantPack(buf); goto abandon; } } } xct_off = elf_get_offset_from_address(xct_va); if (opt->debug.debug_level) { fprintf(stderr, "shlib canPack: xct_va=%#lx xct_off=%lx\n", (long)xct_va, (long)xct_off); } goto proceed; // But proper packing depends on checking xct_va. } else throwCantPack("need DT_INIT; try \"void _init(void){}\""); abandon: return false; proceed: ; } // XXX Theoretically the following test should be first, // but PackUnix::canPack() wants 0!=exetype ? if (!super::canPack()) return false; assert(exetype == 1); exetype = 0; // set options opt->o_unix.blocksize = blocksize = file_size; return true; } ; 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 compat_get_timex(struct timex *txc, const struct compat_timex __user *utp) { struct compat_timex tx32; if (copy_from_user(&tx32, utp, sizeof(struct compat_timex))) return -EFAULT; txc->modes = tx32.modes; txc->offset = tx32.offset; txc->freq = tx32.freq; txc->maxerror = tx32.maxerror; txc->esterror = tx32.esterror; txc->status = tx32.status; txc->constant = tx32.constant; txc->precision = tx32.precision; txc->tolerance = tx32.tolerance; txc->time.tv_sec = tx32.time.tv_sec; txc->time.tv_usec = tx32.time.tv_usec; txc->tick = tx32.tick; txc->ppsfreq = tx32.ppsfreq; txc->jitter = tx32.jitter; txc->shift = tx32.shift; txc->stabil = tx32.stabil; txc->jitcnt = tx32.jitcnt; txc->calcnt = tx32.calcnt; txc->errcnt = tx32.errcnt; txc->stbcnt = tx32.stbcnt; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'compat: fix 4-byte infoleak via uninitialized struct field Commit 3a4d44b61625 ("ntp: Move adjtimex related compat syscalls to native counterparts") removed the memset() in compat_get_timex(). Since then, the compat adjtimex syscall can invoke do_adjtimex() with an uninitialized ->tai. If do_adjtimex() doesn't write to ->tai (e.g. because the arguments are invalid), compat_put_timex() then copies the uninitialized ->tai field to userspace. Fix it by adding the memset() back. Fixes: 3a4d44b61625 ("ntp: Move adjtimex related compat syscalls to native counterparts") Signed-off-by: Jann Horn <jannh@google.com> Acked-by: Kees Cook <keescook@chromium.org> Acked-by: Al Viro <viro@zeniv.linux.org.uk> 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: _rpc_batch_job(slurm_msg_t *msg, bool new_msg) { batch_job_launch_msg_t *req = (batch_job_launch_msg_t *)msg->data; bool first_job_run; int rc = SLURM_SUCCESS; bool replied = false, revoked; slurm_addr_t *cli = &msg->orig_addr; if (new_msg) { uid_t req_uid = g_slurm_auth_get_uid(msg->auth_cred, conf->auth_info); if (!_slurm_authorized_user(req_uid)) { error("Security violation, batch launch RPC from uid %d", req_uid); rc = ESLURM_USER_ID_MISSING; /* or bad in this case */ goto done; } } if (_launch_job_test(req->job_id)) { error("Job %u already running, do not launch second copy", req->job_id); rc = ESLURM_DUPLICATE_JOB_ID; /* job already running */ _launch_job_fail(req->job_id, rc); goto done; } slurm_cred_handle_reissue(conf->vctx, req->cred); if (slurm_cred_revoked(conf->vctx, req->cred)) { error("Job %u already killed, do not launch batch job", req->job_id); rc = ESLURMD_CREDENTIAL_REVOKED; /* job already ran */ goto done; } task_g_slurmd_batch_request(req->job_id, req); /* determine task affinity */ slurm_mutex_lock(&prolog_mutex); first_job_run = !slurm_cred_jobid_cached(conf->vctx, req->job_id); /* BlueGene prolog waits for partition boot and is very slow. * On any system we might need to load environment variables * for Moab (see --get-user-env), which could also be slow. * Just reply now and send a separate kill job request if the * prolog or launch fail. */ replied = true; if (new_msg && (slurm_send_rc_msg(msg, rc) < 1)) { /* The slurmctld is no longer waiting for a reply. * This typically indicates that the slurmd was * blocked from memory and/or CPUs and the slurmctld * has requeued the batch job request. */ error("Could not confirm batch launch for job %u, " "aborting request", req->job_id); rc = SLURM_COMMUNICATIONS_SEND_ERROR; slurm_mutex_unlock(&prolog_mutex); goto done; } /* * Insert jobid into credential context to denote that * we've now "seen" an instance of the job */ if (first_job_run) { job_env_t job_env; slurm_cred_insert_jobid(conf->vctx, req->job_id); _add_job_running_prolog(req->job_id); slurm_mutex_unlock(&prolog_mutex); memset(&job_env, 0, sizeof(job_env_t)); job_env.jobid = req->job_id; job_env.step_id = req->step_id; job_env.node_list = req->nodes; job_env.partition = req->partition; job_env.spank_job_env = req->spank_job_env; job_env.spank_job_env_size = req->spank_job_env_size; job_env.uid = req->uid; job_env.user_name = req->user_name; /* * Run job prolog on this node */ #if defined(HAVE_BG) select_g_select_jobinfo_get(req->select_jobinfo, SELECT_JOBDATA_BLOCK_ID, &job_env.resv_id); #elif defined(HAVE_ALPS_CRAY) job_env.resv_id = select_g_select_jobinfo_xstrdup( req->select_jobinfo, SELECT_PRINT_RESV_ID); #endif if (container_g_create(req->job_id)) error("container_g_create(%u): %m", req->job_id); rc = _run_prolog(&job_env, req->cred); xfree(job_env.resv_id); if (rc) { int term_sig, exit_status; if (WIFSIGNALED(rc)) { exit_status = 0; term_sig = WTERMSIG(rc); } else { exit_status = WEXITSTATUS(rc); term_sig = 0; } error("[job %u] prolog failed status=%d:%d", req->job_id, exit_status, term_sig); _prolog_error(req, rc); rc = ESLURMD_PROLOG_FAILED; goto done; } } else { slurm_mutex_unlock(&prolog_mutex); _wait_for_job_running_prolog(req->job_id); } if (_get_user_env(req) < 0) { bool requeue = _requeue_setup_env_fail(); if (requeue) { rc = ESLURMD_SETUP_ENVIRONMENT_ERROR; goto done; } } _set_batch_job_limits(msg); /* Since job could have been killed while the prolog was * running (especially on BlueGene, which can take minutes * for partition booting). Test if the credential has since * been revoked and exit as needed. */ if (slurm_cred_revoked(conf->vctx, req->cred)) { info("Job %u already killed, do not launch batch job", req->job_id); rc = ESLURMD_CREDENTIAL_REVOKED; /* job already ran */ goto done; } slurm_mutex_lock(&launch_mutex); if (req->step_id == SLURM_BATCH_SCRIPT) info("Launching batch job %u for UID %d", req->job_id, req->uid); else info("Launching batch job %u.%u for UID %d", req->job_id, req->step_id, req->uid); debug3("_rpc_batch_job: call to _forkexec_slurmstepd"); rc = _forkexec_slurmstepd(LAUNCH_BATCH_JOB, (void *)req, cli, NULL, (hostset_t)NULL, SLURM_PROTOCOL_VERSION); debug3("_rpc_batch_job: return from _forkexec_slurmstepd: %d", rc); slurm_mutex_unlock(&launch_mutex); _launch_complete_add(req->job_id); /* On a busy system, slurmstepd may take a while to respond, * if the job was cancelled in the interim, run through the * abort logic below. */ revoked = slurm_cred_revoked(conf->vctx, req->cred); if (revoked) _launch_complete_rm(req->job_id); if (revoked && _is_batch_job_finished(req->job_id)) { /* If configured with select/serial and the batch job already * completed, consider the job sucessfully launched and do * not repeat termination logic below, which in the worst case * just slows things down with another message. */ revoked = false; } if (revoked) { info("Job %u killed while launch was in progress", req->job_id); sleep(1); /* give slurmstepd time to create * the communication socket */ _terminate_all_steps(req->job_id, true); rc = ESLURMD_CREDENTIAL_REVOKED; goto done; } done: if (!replied) { if (new_msg && (slurm_send_rc_msg(msg, rc) < 1)) { /* The slurmctld is no longer waiting for a reply. * This typically indicates that the slurmd was * blocked from memory and/or CPUs and the slurmctld * has requeued the batch job request. */ error("Could not confirm batch launch for job %u, " "aborting request", req->job_id); rc = SLURM_COMMUNICATIONS_SEND_ERROR; } else { /* No need to initiate separate reply below */ rc = SLURM_SUCCESS; } } if (rc != SLURM_SUCCESS) { /* prolog or job launch failure, * tell slurmctld that the job failed */ if (req->step_id == SLURM_BATCH_SCRIPT) _launch_job_fail(req->job_id, rc); else _abort_step(req->job_id, req->step_id); } /* * If job prolog failed or we could not reply, * initiate message to slurmctld with current state */ if ((rc == ESLURMD_PROLOG_FAILED) || (rc == SLURM_COMMUNICATIONS_SEND_ERROR) || (rc == ESLURMD_SETUP_ENVIRONMENT_ERROR)) { send_registration_msg(rc, false); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Validate gid and user_name values provided to slurmd up front. Do not defer until later, and do not potentially miss out on proper validation of the user_name field which can lead to improper authentication handling. 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: static ssize_t match_busid_show(struct device_driver *drv, char *buf) { int i; char *out = buf; spin_lock(&busid_table_lock); for (i = 0; i < MAX_BUSID; i++) if (busid_table[i].name[0]) out += sprintf(out, "%s ", busid_table[i].name); spin_unlock(&busid_table_lock); out += sprintf(out, "\n"); return out - buf; } ; 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: void put_busid_priv(struct bus_id_priv *bid) { spin_unlock(&bid->busid_lock); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'usbip: usbip_host: fix bad unlock balance during stub_probe() stub_probe() calls put_busid_priv() in an error path when device isn't found in the busid_table. Fix it by making put_busid_priv() safe to be called with null struct bus_id_priv pointer. This problem happens when "usbip bind" is run without loading usbip_host driver and then running modprobe. The first failed bind attempt unbinds the device from the original driver and when usbip_host is modprobed, stub_probe() runs and doesn't find the device in its busid table and calls put_busid_priv(0 with null bus_id_priv pointer. usbip-host 3-10.2: 3-10.2 is not in match_busid table... skip! [ 367.359679] ===================================== [ 367.359681] WARNING: bad unlock balance detected! [ 367.359683] 4.17.0-rc4+ #5 Not tainted [ 367.359685] ------------------------------------- [ 367.359688] modprobe/2768 is trying to release lock ( [ 367.359689] ================================================================== [ 367.359696] BUG: KASAN: null-ptr-deref in print_unlock_imbalance_bug+0x99/0x110 [ 367.359699] Read of size 8 at addr 0000000000000058 by task modprobe/2768 [ 367.359705] CPU: 4 PID: 2768 Comm: modprobe Not tainted 4.17.0-rc4+ #5 Fixes: 22076557b07c ("usbip: usbip_host: fix NULL-ptr deref and use-after-free errors") in usb-linus 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()(Definition_Ptr d) { Env* env = environment(); Definition_Obj dd = SASS_MEMORY_COPY(d); env->local_frame()[d->name() + (d->type() == Definition::MIXIN ? "[m]" : "[f]")] = dd; if (d->type() == Definition::FUNCTION && ( Prelexer::calc_fn_call(d->name().c_str()) || d->name() == "element" || d->name() == "expression" || d->name() == "url" )) { deprecated( "Naming a function \"" + d->name() + "\" is disallowed and will be an error in future versions of Sass.", "This name conflicts with an existing CSS function with special parse rules.", false, d->pstate() ); } // set the static link so we can have lexical scoping dd->environment(env); return 0; } ; 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 size_t optsize (lua_State *L, char opt, const char **fmt) { switch (opt) { case 'B': case 'b': return sizeof(char); case 'H': case 'h': return sizeof(short); case 'L': case 'l': return sizeof(long); case 'T': return sizeof(size_t); case 'f': return sizeof(float); case 'd': return sizeof(double); case 'x': return 1; case 'c': return getnum(L, fmt, 1); case 'i': case 'I': { int sz = getnum(L, fmt, sizeof(int)); if (sz > MAXINTSIZE) luaL_error(L, "integral size %d is larger than limit of %d", sz, MAXINTSIZE); return sz; } default: return 0; /* other cases do not need alignment */ } } ; 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: void sock_release(struct socket *sock) { if (sock->ops) { struct module *owner = sock->ops->owner; sock->ops->release(sock); sock->ops = NULL; module_put(owner); } if (rcu_dereference_protected(sock->wq, 1)->fasync_list) pr_err("%s: fasync list not empty!\n", __func__); if (!sock->file) { iput(SOCK_INODE(sock)); return; } sock->file = NULL; } ; 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: static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception) { BMPInfo bmp_info; Image *image; MagickBooleanType status; MagickOffsetType offset, start_position; MemoryInfo *pixel_info; Quantum index; register Quantum *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,exception); 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 { PixelInfo quantum_bits; PixelPacket shift; /* 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); 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",MagickPathExtent); 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); 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",MagickPathExtent); 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->alpha_trait=((bmp_info.alpha_mask != 0) && (bmp_info.compression == BI_BITFIELDS)) ? BlendPixelTrait : UndefinedPixelTrait; 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->resolution.x=(double) bmp_info.x_pixels/100.0; image->resolution.y=(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,exception); if (status == MagickFalse) 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,exception) == 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=(MagickRealType) ScaleCharToQuantum(*p++); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(*p++); image->colormap[i].red=(MagickRealType) 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((size_t) 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((size_t) 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->alpha_trait == UndefinedPixelTrait) && (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->alpha_trait=BlendPixelTrait; y=-1; break; } p+=4; } } } bmp_info.alpha_mask=image->alpha_trait != UndefinedPixelTrait ? 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 unsigned int 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.alpha) & 0x80000000UL) == 0) { shift.alpha++; if (shift.alpha >= 32U) break; } sample=shift.red; while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.red=(MagickRealType) (sample-shift.red); sample=shift.green; while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.green=(MagickRealType) (sample-shift.green); sample=shift.blue; while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.blue=(MagickRealType) (sample-shift.blue); sample=shift.alpha; while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.alpha=(MagickRealType) (sample-shift.alpha); } 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 == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (image->columns % 8); bit++) { index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } 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,exception); 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 == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-1); x+=2) { ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0x0f),&index, exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); ValidateColormapValue(image,(ssize_t) (*p & 0x0f),&index,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; } if ((image->columns % 2) != 0) { ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0xf),&index, exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; x++; } 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,exception); 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 == (Quantum *) NULL) break; for (x=(ssize_t) image->columns; x != 0; --x) { ValidateColormapValue(image,(ssize_t) *p++,&index,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } 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,exception); 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 == (Quantum *) 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(image,ScaleShortToQuantum((unsigned short) red),q); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16; if (quantum_bits.alpha <= 8) alpha|=((alpha & 0xff00) >> 8); SetPixelAlpha(image,ScaleShortToQuantum( (unsigned short) alpha),q); } q+=GetPixelChannels(image); } 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 == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } 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 == (Quantum *) 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(image,ScaleShortToQuantum((unsigned short) red),q); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16; if (quantum_bits.alpha == 8) alpha|=(alpha >> 8); SetPixelAlpha(image,ScaleShortToQuantum( (unsigned short) alpha),q); } q+=GetPixelChannels(image); } 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,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (IsBMP(magick,2) != MagickFalse); (void) CloseBlob(image); return(GetFirstImageInList(image)); } ; 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 nested_vmx_check_permission(struct kvm_vcpu *vcpu) { if (!to_vmx(vcpu)->nested.vmxon) { kvm_queue_exception(vcpu, UD_VECTOR); return 0; } return 1; } ; 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::load() { if (RemoteFsDevice::constSambaAvahiProtocol==details.url.scheme()) { // Start Avahi listener... Avahi::self(); QUrlQuery q(details.url); if (q.hasQueryItem(constServiceNameQuery)) { details.serviceName=q.queryItemValue(constServiceNameQuery); } if (!details.serviceName.isEmpty()) { AvahiService *srv=Avahi::self()->getService(details.serviceName); if (!srv || srv->getHost().isEmpty()) { sub=tr("Not Available"); } else { sub=tr("Available"); } } connect(Avahi::self(), SIGNAL(serviceAdded(QString)), SLOT(serviceAdded(QString))); connect(Avahi::self(), SIGNAL(serviceRemoved(QString)), SLOT(serviceRemoved(QString))); } if (isConnected()) { setAudioFolder(); readOpts(settingsFileName(), opts, true); rescan(false); // Read from cache if we have it! } } ; 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: ~Mounter() { } ; 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: void Avahi::addService(int, int, const QString &name, const QString &type, const QString &domain, uint) { if (isLocalDomain(domain) && !services.contains(name)) { AvahiService *srv=new AvahiService(name, type, domain); services.insert(name, srv); connect(srv, SIGNAL(serviceResolved(QString)), this, SIGNAL(serviceAdded(QString))); } } ; 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: void Mounter::startTimer() { if (!timer) { timer=new QTimer(this); connect(timer, SIGNAL(timeout()), SLOT(timeout())); } timer->start(30000); } ; 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: ext4_read_inode_bitmap(struct super_block *sb, ext4_group_t block_group) { struct ext4_group_desc *desc; struct ext4_sb_info *sbi = EXT4_SB(sb); struct buffer_head *bh = NULL; ext4_fsblk_t bitmap_blk; int err; desc = ext4_get_group_desc(sb, block_group, NULL); if (!desc) return ERR_PTR(-EFSCORRUPTED); bitmap_blk = ext4_inode_bitmap(sb, desc); if ((bitmap_blk <= le32_to_cpu(sbi->s_es->s_first_data_block)) || (bitmap_blk >= ext4_blocks_count(sbi->s_es))) { ext4_error(sb, "Invalid inode bitmap blk %llu in " "block_group %u", bitmap_blk, block_group); ext4_mark_group_bitmap_corrupted(sb, block_group, EXT4_GROUP_INFO_IBITMAP_CORRUPT); return ERR_PTR(-EFSCORRUPTED); } bh = sb_getblk(sb, bitmap_blk); if (unlikely(!bh)) { ext4_error(sb, "Cannot read inode bitmap - " "block_group = %u, inode_bitmap = %llu", block_group, bitmap_blk); return ERR_PTR(-ENOMEM); } if (bitmap_uptodate(bh)) goto verify; lock_buffer(bh); if (bitmap_uptodate(bh)) { unlock_buffer(bh); goto verify; } ext4_lock_group(sb, block_group); if (desc->bg_flags & cpu_to_le16(EXT4_BG_INODE_UNINIT)) { memset(bh->b_data, 0, (EXT4_INODES_PER_GROUP(sb) + 7) / 8); ext4_mark_bitmap_end(EXT4_INODES_PER_GROUP(sb), sb->s_blocksize * 8, bh->b_data); set_bitmap_uptodate(bh); set_buffer_uptodate(bh); set_buffer_verified(bh); ext4_unlock_group(sb, block_group); unlock_buffer(bh); return bh; } ext4_unlock_group(sb, block_group); if (buffer_uptodate(bh)) { /* * if not uninit if bh is uptodate, * bitmap is also uptodate */ set_bitmap_uptodate(bh); unlock_buffer(bh); goto verify; } /* * submit the buffer_head for reading */ trace_ext4_load_inode_bitmap(sb, block_group); bh->b_end_io = ext4_end_bitmap_read; get_bh(bh); submit_bh(REQ_OP_READ, REQ_META | REQ_PRIO, bh); wait_on_buffer(bh); if (!buffer_uptodate(bh)) { put_bh(bh); ext4_error(sb, "Cannot read inode bitmap - " "block_group = %u, inode_bitmap = %llu", block_group, bitmap_blk); ext4_mark_group_bitmap_corrupted(sb, block_group, EXT4_GROUP_INFO_IBITMAP_CORRUPT); return ERR_PTR(-EIO); } verify: err = ext4_validate_inode_bitmap(sb, desc, block_group, bh); if (err) goto out; return bh; out: put_bh(bh); return ERR_PTR(err); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'ext4: only look at the bg_flags field if it is valid The bg_flags field in the block group descripts is only valid if the uninit_bg or metadata_csum feature is enabled. We were not consistently looking at this field; fix this. Also block group #0 must never have uninitialized allocation bitmaps, or need to be zeroed, since that's where the root inode, and other special inodes are set up. Check for these conditions and mark the file system as corrupted if they are detected. This addresses CVE-2018-10876. https://bugzilla.kernel.org/show_bug.cgi?id=199403 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: __ext4_xattr_check_block(struct inode *inode, struct buffer_head *bh, const char *function, unsigned int line) { int error = -EFSCORRUPTED; if (buffer_verified(bh)) return 0; if (BHDR(bh)->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC) || BHDR(bh)->h_blocks != cpu_to_le32(1)) goto errout; error = -EFSBADCRC; if (!ext4_xattr_block_csum_verify(inode, bh)) goto errout; error = ext4_xattr_check_entries(BFIRST(bh), bh->b_data + bh->b_size, bh->b_data); errout: if (error) __ext4_error_inode(inode, function, line, 0, "corrupted xattr block %llu", (unsigned long long) bh->b_blocknr); else set_buffer_verified(bh); return error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'ext4: always verify the magic number in xattr blocks If there an inode points to a block which is also some other type of metadata block (such as a block allocation bitmap), the buffer_verified flag can be set when it was validated as that other metadata block type; however, it would make a really terrible external attribute block. The reason why we use the verified flag is to avoid constantly reverifying the block. However, it doesn't take much overhead to make sure the magic number of the xattr block is correct, and this will avoid potential crashes. 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: static int alarm_timer_nsleep(const clockid_t which_clock, int flags, const struct timespec64 *tsreq) { enum alarmtimer_type type = clock2alarm(which_clock); struct restart_block *restart = &current->restart_block; struct alarm alarm; ktime_t exp; int ret = 0; if (!alarmtimer_get_rtcdev()) return -ENOTSUPP; if (flags & ~TIMER_ABSTIME) return -EINVAL; if (!capable(CAP_WAKE_ALARM)) return -EPERM; alarm_init_on_stack(&alarm, type, alarmtimer_nsleep_wakeup); exp = timespec64_to_ktime(*tsreq); /* Convert (if necessary) to absolute time */ if (flags != TIMER_ABSTIME) { ktime_t now = alarm_bases[type].gettime(); exp = ktime_add(now, exp); } ret = alarmtimer_do_nsleep(&alarm, exp, type); if (ret != -ERESTART_RESTARTBLOCK) return ret; /* abs timers don't set remaining time or restart */ if (flags == TIMER_ABSTIME) return -ERESTARTNOHAND; restart->fn = alarm_timer_nsleep_restart; restart->nanosleep.clockid = type; restart->nanosleep.expires = exp; return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'alarmtimer: Prevent overflow for relative nanosleep Air Icy reported: UBSAN: Undefined behaviour in kernel/time/alarmtimer.c:811:7 signed integer overflow: 1529859276030040771 + 9223372036854775807 cannot be represented in type 'long long int' Call Trace: alarm_timer_nsleep+0x44c/0x510 kernel/time/alarmtimer.c:811 __do_sys_clock_nanosleep kernel/time/posix-timers.c:1235 [inline] __se_sys_clock_nanosleep kernel/time/posix-timers.c:1213 [inline] __x64_sys_clock_nanosleep+0x326/0x4e0 kernel/time/posix-timers.c:1213 do_syscall_64+0xb8/0x3a0 arch/x86/entry/common.c:290 alarm_timer_nsleep() uses ktime_add() to add the current time and the relative expiry value. ktime_add() has no sanity checks so the addition can overflow when the relative timeout is large enough. Use ktime_add_safe() which has the necessary sanity checks in place and limits the result to the valid range. Fixes: 9a7adcf5c6de ("timers: Posix interface for alarm-timers") Reported-by: Team OWL337 <icytxw@gmail.com> Signed-off-by: Thomas Gleixner <tglx@linutronix.de> Cc: John Stultz <john.stultz@linaro.org> Link: https://lkml.kernel.org/r/alpine.DEB.2.21.1807020926360.1595@nanos.tec.linutronix.de'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static Image *XMagickCommand(Display *display,XResourceInfo *resource_info, XWindows *windows,const CommandType command_type,Image **image, MagickStatusType *state) { Image *nexus; MagickBooleanType proceed; MagickStatusType status; XTextProperty window_name; /* Process user command. */ nexus=NewImageList(); switch (command_type) { case OpenCommand: { char **filelist; ExceptionInfo *exception; Image *images, *next; ImageInfo *read_info; int number_files; register int i; static char filenames[MaxTextExtent] = "*"; 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); exception=AcquireExceptionInfo(); images=NewImageList(); XSetCursorState(display,windows,MagickTrue); XCheckRefreshWindows(display,windows); for (i=0; i < number_files; i++) { (void) CopyMagickString(read_info->filename,filelist[i],MaxTextExtent); 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); exception=DestroyExceptionInfo(exception); 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[MaxTextExtent]; 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,MaxTextExtent, "%s: %s",MagickPackageName,basename); if (resource_info->title != (char *) NULL) { char *title; title=InterpretImageProperties(resource_info->image_info,*image, resource_info->title); (void) CopyMagickString(windows->image.name,title,MaxTextExtent); 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); if (status == MagickFalse) { char message[MaxTextExtent]; (void) FormatLocaleString(message,MaxTextExtent,"%s:%s", (*image)->exception.reason != (char *) NULL ? (*image)->exception.reason : "", (*image)->exception.description != (char *) NULL ? (*image)->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); 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[MaxTextExtent], *url; /* Display documentation using Netscape remote control. */ url=GetMagickHomeURL(); (void) FormatLocaleString(command,MaxTextExtent, "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,&(*image)->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 SoundTouch::setChannels(uint numChannels) { /*if (numChannels != 1 && numChannels != 2) { //ST_THROW_RT_ERROR("Illegal number of channels"); return; }*/ channels = numChannels; pRateTransposer->setChannels((int)numChannels); pTDStretch->setChannels((int)numChannels); } ; 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_fetch_message (CONTEXT* ctx, MESSAGE* msg, int msgno) { int ret; void *uidl; char buf[LONG_STRING]; char path[_POSIX_PATH_MAX]; progress_t progressbar; POP_DATA *pop_data = (POP_DATA *)ctx->data; POP_CACHE *cache; HEADER *h = ctx->hdrs[msgno]; unsigned short bcache = 1; /* see if we already have the message in body cache */ if ((msg->fp = mutt_bcache_get (pop_data->bcache, h->data))) return 0; /* * see if we already have the message in our cache in * case $message_cachedir is unset */ cache = &pop_data->cache[h->index % POP_CACHE_LEN]; if (cache->path) { if (cache->index == h->index) { /* yes, so just return a pointer to the message */ msg->fp = fopen (cache->path, "r"); if (msg->fp) return 0; mutt_perror (cache->path); mutt_sleep (2); return -1; } else { /* clear the previous entry */ unlink (cache->path); FREE (&cache->path); } } FOREVER { if (pop_reconnect (ctx) < 0) return -1; /* verify that massage index is correct */ if (h->refno < 0) { mutt_error _("The message index is incorrect. Try reopening the mailbox."); mutt_sleep (2); return -1; } mutt_progress_init (&progressbar, _("Fetching message..."), MUTT_PROGRESS_SIZE, NetInc, h->content->length + h->content->offset - 1); /* see if we can put in body cache; use our cache as fallback */ if (!(msg->fp = mutt_bcache_put (pop_data->bcache, h->data, 1))) { /* no */ bcache = 0; mutt_mktemp (path, sizeof (path)); if (!(msg->fp = safe_fopen (path, "w+"))) { mutt_perror (path); mutt_sleep (2); return -1; } } snprintf (buf, sizeof (buf), "RETR %d\r\n", h->refno); ret = pop_fetch_data (pop_data, buf, &progressbar, fetch_message, msg->fp); if (ret == 0) break; safe_fclose (&msg->fp); /* if RETR failed (e.g. connection closed), be sure to remove either * the file in bcache or from POP's own cache since the next iteration * of the loop will re-attempt to put() the message */ if (!bcache) unlink (path); if (ret == -2) { mutt_error ("%s", pop_data->err_msg); mutt_sleep (2); return -1; } if (ret == -3) { mutt_error _("Can't write message to temporary file!"); mutt_sleep (2); return -1; } } /* Update the header information. Previously, we only downloaded a * portion of the headers, those required for the main display. */ if (bcache) mutt_bcache_commit (pop_data->bcache, h->data); else { cache->index = h->index; cache->path = safe_strdup (path); } rewind (msg->fp); uidl = h->data; /* we replace envelop, key in subj_hash has to be updated as well */ if (ctx->subj_hash && h->env->real_subj) hash_delete (ctx->subj_hash, h->env->real_subj, h, NULL); mutt_label_hash_remove (ctx, h); mutt_free_envelope (&h->env); h->env = mutt_read_rfc822_header (msg->fp, h, 0, 0); if (ctx->subj_hash && h->env->real_subj) hash_insert (ctx->subj_hash, h->env->real_subj, h); mutt_label_hash_add (ctx, h); h->data = uidl; h->lines = 0; fgets (buf, sizeof (buf), msg->fp); while (!feof (msg->fp)) { ctx->hdrs[msgno]->lines++; fgets (buf, sizeof (buf), msg->fp); } h->content->length = ftello (msg->fp) - h->content->offset; /* This needs to be done in case this is a multipart message */ if (!WithCrypto) h->security = crypt_query (h->content); mutt_clear_error(); rewind (msg->fp); return 0; } ; 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: void imap_quote_string(char *dest, size_t dlen, const char *src) { static const char quote[] = "\"\\"; char *pt = dest; const char *s = src; *pt++ = '"'; /* save room for trailing quote-char */ dlen -= 2; for (; *s && dlen; s++) { if (strchr(quote, *s)) { dlen -= 2; if (dlen == 0) break; *pt++ = '\\'; *pt++ = *s; } else { *pt++ = *s; dlen--; } } *pt++ = '"'; *pt = '\0'; } ; 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: imap_auth_res_t imap_auth_cram_md5 (IMAP_DATA* idata, const char* method) { char ibuf[LONG_STRING*2], obuf[LONG_STRING]; unsigned char hmac_response[MD5_DIGEST_LEN]; int len; int rc; if (!mutt_bit_isset (idata->capabilities, ACRAM_MD5)) return IMAP_AUTH_UNAVAIL; mutt_message _("Authenticating (CRAM-MD5)..."); /* get auth info */ if (mutt_account_getlogin (&idata->conn->account)) return IMAP_AUTH_FAILURE; if (mutt_account_getpass (&idata->conn->account)) return IMAP_AUTH_FAILURE; imap_cmd_start (idata, "AUTHENTICATE CRAM-MD5"); /* From RFC 2195: * The data encoded in the first ready response contains a presumptively * arbitrary string of random digits, a timestamp, and the fully-qualified * primary host name of the server. The syntax of the unencoded form must * correspond to that of an RFC 822 'msg-id' [RFC822] as described in [POP3]. */ do rc = imap_cmd_step (idata); while (rc == IMAP_CMD_CONTINUE); if (rc != IMAP_CMD_RESPOND) { dprint (1, (debugfile, "Invalid response from server: %s\n", ibuf)); goto bail; } if ((len = mutt_from_base64 (obuf, idata->buf + 2)) == -1) { dprint (1, (debugfile, "Error decoding base64 response.\n")); goto bail; } obuf[len] = '\0'; dprint (2, (debugfile, "CRAM challenge: %s\n", obuf)); /* The client makes note of the data and then responds with a string * consisting of the user name, a space, and a 'digest'. The latter is * computed by applying the keyed MD5 algorithm from [KEYED-MD5] where the * key is a shared secret and the digested text is the timestamp (including * angle-brackets). * * Note: The user name shouldn't be quoted. Since the digest can't contain * spaces, there is no ambiguity. Some servers get this wrong, we'll work * around them when the bug report comes in. Until then, we'll remain * blissfully RFC-compliant. */ hmac_md5 (idata->conn->account.pass, obuf, hmac_response); /* dubious optimisation I saw elsewhere: make the whole string in one call */ snprintf (obuf, sizeof (obuf), "%s %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", idata->conn->account.user, hmac_response[0], hmac_response[1], hmac_response[2], hmac_response[3], hmac_response[4], hmac_response[5], hmac_response[6], hmac_response[7], hmac_response[8], hmac_response[9], hmac_response[10], hmac_response[11], hmac_response[12], hmac_response[13], hmac_response[14], hmac_response[15]); dprint(2, (debugfile, "CRAM response: %s\n", obuf)); /* XXX - ibuf must be long enough to store the base64 encoding of obuf, * plus the additional debris */ mutt_to_base64 ((unsigned char*) ibuf, (unsigned char*) obuf, strlen (obuf), sizeof (ibuf) - 2); safe_strcat (ibuf, sizeof (ibuf), "\r\n"); mutt_socket_write (idata->conn, ibuf); do rc = imap_cmd_step (idata); while (rc == IMAP_CMD_CONTINUE); if (rc != IMAP_CMD_OK) { dprint (1, (debugfile, "Error receiving server response.\n")); goto bail; } if (imap_code (idata->buf)) return IMAP_AUTH_SUCCESS; bail: mutt_error _("CRAM-MD5 authentication failed."); mutt_sleep (2); return IMAP_AUTH_FAILURE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'Check outbuf length in mutt_from_base64() The obuf can be overflowed in auth_cram.c, and possibly auth_gss.c. Thanks to Jeriko One for the bug report.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static apr_status_t run_watchdog(int state, void *baton, apr_pool_t *ptemp) { md_watchdog *wd = baton; apr_status_t rv = APR_SUCCESS; md_job_t *job; apr_time_t next_run, now; int restart = 0; int i; switch (state) { case AP_WATCHDOG_STATE_STARTING: ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, wd->s, APLOGNO(10054) "md watchdog start, auto drive %d mds", wd->jobs->nelts); assert(wd->reg); for (i = 0; i < wd->jobs->nelts; ++i) { job = APR_ARRAY_IDX(wd->jobs, i, md_job_t *); load_job_props(wd->reg, job, ptemp); } break; case AP_WATCHDOG_STATE_RUNNING: wd->next_change = 0; ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, wd->s, APLOGNO(10055) "md watchdog run, auto drive %d mds", wd->jobs->nelts); /* normally, we'd like to run at least twice a day */ next_run = apr_time_now() + apr_time_from_sec(MD_SECS_PER_DAY / 2); /* Check on all the jobs we have */ for (i = 0; i < wd->jobs->nelts; ++i) { job = APR_ARRAY_IDX(wd->jobs, i, md_job_t *); rv = check_job(wd, job, ptemp); if (job->need_restart && !job->restart_processed) { restart = 1; } if (job->next_check && job->next_check < next_run) { next_run = job->next_check; } } now = apr_time_now(); if (APLOGdebug(wd->s)) { ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, wd->s, APLOGNO(10107) "next run in %s", md_print_duration(ptemp, next_run - now)); } wd_set_interval(wd->watchdog, next_run - now, wd, run_watchdog); break; case AP_WATCHDOG_STATE_STOPPING: ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, wd->s, APLOGNO(10058) "md watchdog stopping"); break; } if (restart) { const char *action, *names = ""; int n; for (i = 0, n = 0; i < wd->jobs->nelts; ++i) { job = APR_ARRAY_IDX(wd->jobs, i, md_job_t *); if (job->need_restart && !job->restart_processed) { names = apr_psprintf(ptemp, "%s%s%s", names, n? " " : "", job->md->name); ++n; } } if (n > 0) { int notified = 1; /* Run notify command for ready MDs (if configured) and persist that * we have done so. This process might be reaped after n requests or die * of another cause. The one taking over the watchdog need to notify again. */ if (wd->mc->notify_cmd) { const char * const *argv; const char *cmdline; int exit_code; cmdline = apr_psprintf(ptemp, "%s %s", wd->mc->notify_cmd, names); apr_tokenize_to_argv(cmdline, (char***)&argv, ptemp); if (APR_SUCCESS == (rv = md_util_exec(ptemp, argv[0], argv, &exit_code))) { ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, wd->s, APLOGNO(10108) "notify command '%s' returned %d", wd->mc->notify_cmd, exit_code); } else { ap_log_error(APLOG_MARK, APLOG_ERR, rv, wd->s, APLOGNO(10109) "executing configured MDNotifyCmd %s", wd->mc->notify_cmd); notified = 0; } } if (notified) { /* persist the jobs that were notified */ for (i = 0, n = 0; i < wd->jobs->nelts; ++i) { job = APR_ARRAY_IDX(wd->jobs, i, md_job_t *); if (job->need_restart && !job->restart_processed) { job->restart_processed = 1; save_job_props(wd->reg, job, ptemp); } } } /* FIXME: the server needs to start gracefully to take the new certificate in. * This poses a variety of problems to solve satisfactory for everyone: * - I myself, have no implementation for Windows * - on *NIX, child processes run with less privileges, preventing * the signal based restart trigger to work * - admins want better control of timing windows for restarts, e.g. * during less busy hours/days. */ rv = md_server_graceful(ptemp, wd->s); if (APR_ENOTIMPL == rv) { /* self-graceful restart not supported in this setup */ action = " and changes will be activated on next (graceful) server restart."; } else { action = " and server has been asked to restart now."; } ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, wd->s, APLOGNO(10059) "The Managed Domain%s %s %s been setup%s", (n > 1)? "s" : "", names, (n > 1)? "have" : "has", action); } } return APR_SUCCESS; } ; 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); // verify that header length isn't smaller than expected if (nLen < sizeof(header.format) - 8) return -1; 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; // verify that fact length isn't smaller than expected if (nLen < sizeof(header.fact) - 8) return -1; 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': 'Fixed WavFile header/fact not-too-small 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: static ssize_t parse8BIM(Image *ifile, Image *ofile) { char brkused, quoted, *line, *token, *newstr, *name; int state, next; unsigned char dataset; unsigned int recnum; int inputlen = MaxTextExtent; MagickOffsetType savedpos, currentpos; ssize_t savedolen = 0L, outputlen = 0L; TokenInfo *token_info; dataset = 0; recnum = 0; line = (char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*line)); if (line == (char *) NULL) return(-1); newstr = name = token = (char *) NULL; savedpos = 0; token_info=AcquireTokenInfo(); while (super_fgets(&line,&inputlen,ifile)!=NULL) { state=0; next=0; token=(char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*token)); if (token == (char *) NULL) break; newstr=(char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*newstr)); if (newstr == (char *) NULL) break; while (Tokenizer(token_info,0,token,(size_t) inputlen,line,"","=","\"",0, &brkused,&next,&quoted)==0) { if (state == 0) { int state, next; char brkused, quoted; state=0; next=0; while (Tokenizer(token_info,0,newstr,(size_t) inputlen,token,"","#", "", 0,&brkused,&next,&quoted)==0) { switch (state) { case 0: if (strcmp(newstr,"8BIM")==0) dataset = 255; else dataset = (unsigned char) StringToLong(newstr); break; case 1: recnum = (unsigned int) StringToUnsignedLong(newstr); break; case 2: name=(char *) AcquireQuantumMemory(strlen(newstr)+MaxTextExtent, sizeof(*name)); if (name) (void) strcpy(name,newstr); break; } state++; } } else if (state == 1) { int next; ssize_t len; char brkused, quoted; next=0; len = (ssize_t) strlen(token); while (Tokenizer(token_info,0,newstr,(size_t) inputlen,token,"","&", "",0,&brkused,&next,&quoted)==0) { if (brkused && next > 0) { size_t codes_length; char *s = &token[next-1]; codes_length=convertHTMLcodes(s, strlen(s)); if ((ssize_t) codes_length > len) len=0; else len-=codes_length; } } if (dataset == 255) { unsigned char nlen = 0; int i; if (savedolen > 0) { MagickOffsetType offset; ssize_t diff = outputlen - savedolen; currentpos = TellBlob(ofile); if (currentpos < 0) return(-1); offset=SeekBlob(ofile,savedpos,SEEK_SET); if (offset < 0) return(-1); (void) WriteBlobMSBLong(ofile,(unsigned int) diff); offset=SeekBlob(ofile,currentpos,SEEK_SET); if (offset < 0) return(-1); savedolen = 0L; } if (outputlen & 1) { (void) WriteBlobByte(ofile,0x00); outputlen++; } (void) WriteBlobString(ofile,"8BIM"); (void) WriteBlobMSBShort(ofile,(unsigned short) recnum); outputlen += 6; if (name) nlen = (unsigned char) strlen(name); (void) WriteBlobByte(ofile,nlen); outputlen++; for (i=0; i<nlen; i++) (void) WriteBlobByte(ofile,(unsigned char) name[i]); outputlen += nlen; if ((nlen & 0x01) == 0) { (void) WriteBlobByte(ofile,0x00); outputlen++; } if (recnum != IPTC_ID) { (void) WriteBlobMSBLong(ofile, (unsigned int) len); outputlen += 4; next=0; outputlen += len; while (len-- > 0) (void) WriteBlobByte(ofile,(unsigned char) token[next++]); if (outputlen & 1) { (void) WriteBlobByte(ofile,0x00); outputlen++; } } else { /* patch in a fake length for now and fix it later */ savedpos = TellBlob(ofile); if (savedpos < 0) return(-1); (void) WriteBlobMSBLong(ofile,0xFFFFFFFFU); outputlen += 4; savedolen = outputlen; } } else { if (len <= 0x7FFF) { (void) WriteBlobByte(ofile,0x1c); (void) WriteBlobByte(ofile,(unsigned char) dataset); (void) WriteBlobByte(ofile,(unsigned char) (recnum & 0xff)); (void) WriteBlobMSBShort(ofile,(unsigned short) len); outputlen += 5; next=0; outputlen += len; while (len-- > 0) (void) WriteBlobByte(ofile,(unsigned char) token[next++]); } } } state++; } if (token != (char *) NULL) token=DestroyString(token); if (newstr != (char *) NULL) newstr=DestroyString(newstr); if (name != (char *) NULL) name=DestroyString(name); } token_info=DestroyTokenInfo(token_info); if (token != (char *) NULL) token=DestroyString(token); if (newstr != (char *) NULL) newstr=DestroyString(newstr); if (name != (char *) NULL) name=DestroyString(name); line=DestroyString(line); if (savedolen > 0) { MagickOffsetType offset; ssize_t diff = outputlen - savedolen; currentpos = TellBlob(ofile); if (currentpos < 0) return(-1); offset=SeekBlob(ofile,savedpos,SEEK_SET); if (offset < 0) return(-1); (void) WriteBlobMSBLong(ofile,(unsigned int) diff); offset=SeekBlob(ofile,currentpos,SEEK_SET); if (offset < 0) return(-1); savedolen = 0L; } return(outputlen); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-772'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1190'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static struct pid *good_sigevent(sigevent_t * event) { struct task_struct *rtn = current->group_leader; if ((event->sigev_notify & SIGEV_THREAD_ID ) && (!(rtn = find_task_by_vpid(event->sigev_notify_thread_id)) || !same_thread_group(rtn, current) || (event->sigev_notify & ~SIGEV_THREAD_ID) != SIGEV_SIGNAL)) return NULL; if (((event->sigev_notify & ~SIGEV_THREAD_ID) != SIGEV_NONE) && ((event->sigev_signo <= 0) || (event->sigev_signo > SIGRTMAX))) return NULL; return task_pid(rtn); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'posix-timer: Properly check sigevent->sigev_notify timer_create() specifies via sigevent->sigev_notify the signal delivery for the new timer. The valid modes are SIGEV_NONE, SIGEV_SIGNAL, SIGEV_THREAD and (SIGEV_SIGNAL | SIGEV_THREAD_ID). The sanity check in good_sigevent() is only checking the valid combination for the SIGEV_THREAD_ID bit, i.e. SIGEV_SIGNAL, but if SIGEV_THREAD_ID is not set it accepts any random value. This has no real effects on the posix timer and signal delivery code, but it affects show_timer() which handles the output of /proc/$PID/timers. That function uses a string array to pretty print sigev_notify. The access to that array has no bound checks, so random sigev_notify cause access beyond the array bounds. Add proper checks for the valid notify modes and remove the SIGEV_THREAD_ID masking from various code pathes as SIGEV_NONE can never be set in combination with SIGEV_THREAD_ID. Reported-by: Eric Biggers <ebiggers3@gmail.com> Reported-by: Dmitry Vyukov <dvyukov@google.com> Reported-by: Alexey Dobriyan <adobriyan@gmail.com> Signed-off-by: Thomas Gleixner <tglx@linutronix.de> Cc: John Stultz <john.stultz@linaro.org> Cc: stable@vger.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: kernel_ptr(void) { } ; 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: BGD_DECLARE(void *) gdImageBmpPtr(gdImagePtr im, int *size, int compression) { void *rv; gdIOCtx *out = gdNewDynamicCtx(2048, NULL); if (out == NULL) return NULL; gdImageBmpCtx(im, out, compression); rv = gdDPExtractData(out, size); out->gd_free(out); return rv; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'bmp: check return value in gdImageBmpPtr Closes #447.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: lex(struct scanner *s, union lvalue *val) { skip_more_whitespace_and_comments: /* Skip spaces. */ while (is_space(peek(s))) if (next(s) == '\n') return TOK_END_OF_LINE; /* Skip comments. */ if (chr(s, '#')) { skip_to_eol(s); goto skip_more_whitespace_and_comments; } /* See if we're done. */ if (eof(s)) return TOK_END_OF_FILE; /* New token. */ s->token_line = s->line; s->token_column = s->column; s->buf_pos = 0; /* LHS Keysym. */ if (chr(s, '<')) { while (peek(s) != '>' && !eol(s)) buf_append(s, next(s)); if (!chr(s, '>')) { scanner_err(s, "unterminated keysym literal"); return TOK_ERROR; } if (!buf_append(s, '\0')) { scanner_err(s, "keysym literal is too long"); return TOK_ERROR; } val->string.str = s->buf; val->string.len = s->buf_pos; return TOK_LHS_KEYSYM; } /* Colon. */ if (chr(s, ':')) return TOK_COLON; if (chr(s, '!')) return TOK_BANG; if (chr(s, '~')) return TOK_TILDE; /* String literal. */ if (chr(s, '\"')) { while (!eof(s) && !eol(s) && peek(s) != '\"') { if (chr(s, '\\')) { uint8_t o; if (chr(s, '\\')) { buf_append(s, '\\'); } else if (chr(s, '"')) { buf_append(s, '"'); } else if (chr(s, 'x') || chr(s, 'X')) { if (hex(s, &o)) buf_append(s, (char) o); else scanner_warn(s, "illegal hexadecimal escape sequence in string literal"); } else if (oct(s, &o)) { buf_append(s, (char) o); } else { scanner_warn(s, "unknown escape sequence (%c) in string literal", peek(s)); /* Ignore. */ } } else { buf_append(s, next(s)); } } if (!chr(s, '\"')) { scanner_err(s, "unterminated string literal"); return TOK_ERROR; } if (!buf_append(s, '\0')) { scanner_err(s, "string literal is too long"); return TOK_ERROR; } if (!is_valid_utf8(s->buf, s->buf_pos - 1)) { scanner_err(s, "string literal is not a valid UTF-8 string"); return TOK_ERROR; } val->string.str = s->buf; val->string.len = s->buf_pos; return TOK_STRING; } /* Identifier or include. */ if (is_alpha(peek(s)) || peek(s) == '_') { s->buf_pos = 0; while (is_alnum(peek(s)) || peek(s) == '_') buf_append(s, next(s)); if (!buf_append(s, '\0')) { scanner_err(s, "identifier is too long"); return TOK_ERROR; } if (streq(s->buf, "include")) return TOK_INCLUDE; val->string.str = s->buf; val->string.len = s->buf_pos; return TOK_IDENT; } /* Discard rest of line. */ skip_to_eol(s); scanner_err(s, "unrecognized token"); return TOK_ERROR; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': 'compose: fix infinite loop in parser on some inputs The parser would enter an infinite loop if an unterminated keysym literal occurs at EOF. Found 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 char *InterpretDelegateProperties(ImageInfo *image_info, Image *image,const char *embed_text,ExceptionInfo *exception) { #define ExtendInterpretText(string_length) \ DisableMSCWarning(4127) \ { \ size_t length=(string_length); \ if ((size_t) (q-interpret_text+length+1) >= extent) \ { \ extent+=length; \ interpret_text=(char *) ResizeQuantumMemory(interpret_text,extent+ \ MaxTextExtent,sizeof(*interpret_text)); \ if (interpret_text == (char *) NULL) \ return((char *) NULL); \ q=interpret_text+strlen(interpret_text); \ } \ } \ RestoreMSCWarning #define AppendKeyValue2Text(key,value)\ DisableMSCWarning(4127) \ { \ size_t length=strlen(key)+strlen(value)+2; \ if ((size_t) (q-interpret_text+length+1) >= extent) \ { \ extent+=length; \ interpret_text=(char *) ResizeQuantumMemory(interpret_text,extent+ \ MaxTextExtent,sizeof(*interpret_text)); \ if (interpret_text == (char *) NULL) \ return((char *) NULL); \ q=interpret_text+strlen(interpret_text); \ } \ q+=FormatLocaleString(q,extent,"%s=%s\n",(key),(value)); \ } \ RestoreMSCWarning #define AppendString2Text(string) \ DisableMSCWarning(4127) \ { \ size_t length=strlen((string)); \ if ((size_t) (q-interpret_text+length+1) >= extent) \ { \ extent+=length; \ interpret_text=(char *) ResizeQuantumMemory(interpret_text,extent+ \ MaxTextExtent,sizeof(*interpret_text)); \ if (interpret_text == (char *) NULL) \ return((char *) NULL); \ q=interpret_text+strlen(interpret_text); \ } \ (void) CopyMagickString(q,(string),extent); \ q+=length; \ } \ RestoreMSCWarning char *interpret_text, *string; register char *q; /* current position in interpret_text */ register const char *p; /* position in embed_text string being expanded */ size_t extent; /* allocated length of interpret_text */ MagickBooleanType number; assert(image == NULL || image->signature == MagickCoreSignature); assert(image_info == NULL || image_info->signature == MagickCoreSignature); if ((image != (Image *) NULL) && (image->debug != MagickFalse)) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); else if ((image_info != (ImageInfo *) NULL) && (image_info->debug != MagickFalse)) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s","no-image"); if (embed_text == (const char *) NULL) return(ConstantString("")); p=embed_text; while ((isspace((int) ((unsigned char) *p)) != 0) && (*p != '\0')) p++; if (*p == '\0') return(ConstantString("")); /* Translate any embedded format characters. */ interpret_text=AcquireString(embed_text); /* new string with extra space */ extent=MagickPathExtent; /* allocated space in string */ number=MagickFalse; /* is last char a number? */ for (q=interpret_text; *p!='\0'; number=isdigit((int) ((unsigned char) *p)) ? MagickTrue : MagickFalse,p++) { /* Interpret escape characters (e.g. Filename: %M). */ *q='\0'; ExtendInterpretText(MagickPathExtent); switch (*p) { case '\\': { switch (*(p+1)) { case '\0': continue; case 'r': /* convert to RETURN */ { *q++='\r'; p++; continue; } case 'n': /* convert to NEWLINE */ { *q++='\n'; p++; continue; } case '\n': /* EOL removal UNIX,MacOSX */ { p++; continue; } case '\r': /* EOL removal DOS,Windows */ { p++; if (*p == '\n') /* return-newline EOL */ p++; continue; } default: { p++; *q++=(*p); } } continue; } case '&': { if (LocaleNCompare("&lt;",p,4) == 0) { *q++='<'; p+=3; } else if (LocaleNCompare("&gt;",p,4) == 0) { *q++='>'; p+=3; } else if (LocaleNCompare("&amp;",p,5) == 0) { *q++='&'; p+=4; } else *q++=(*p); continue; } case '%': break; /* continue to next set of handlers */ default: { *q++=(*p); /* any thing else is 'as normal' */ continue; } } p++; /* advance beyond the percent */ /* Doubled Percent - or percent at end of string. */ if ((*p == '\0') || (*p == '\'') || (*p == '"')) p--; if (*p == '%') { *q++='%'; continue; } /* Single letter escapes %c. */ if (number != MagickFalse) { /* But only if not preceeded by a number! */ *q++='%'; /* do NOT substitute the percent */ p--; /* back up one */ continue; } string=GetMagickPropertyLetter(image_info,image,*p, exception); if (string != (char *) NULL) { AppendString2Text(string); string=DestroyString(string); continue; } (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "UnknownImageProperty","\"%%%c\"",*p); } *q='\0'; return(interpret_text); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1225'</s>
<s>[INST] Given the following code containing errors, provide 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; int unique_filenames; 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 PixelPacket *s; register ssize_t i, x; register PixelPacket *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; unique_filenames=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneJNGImage()"); image=mng_info->image; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireNextImage()"); AcquireNextImage(image_info,image); 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[MaxTextExtent]; 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",MaxTextExtent); 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 */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating color_blob."); 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); if (color_image == (Image *) NULL) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } (void) AcquireUniqueFilename(color_image->filename); unique_filenames++; 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); 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); unique_filenames++; status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); 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->x_resolution=(double) mng_get_long(p); image->y_resolution=(double) mng_get_long(&p[4]); if ((int) p[8] == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->x_resolution=image->x_resolution/100.0f; image->y_resolution=image->y_resolution/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 opacity 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=DestroyImage(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,MaxTextExtent,"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); unique_filenames--; 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->columns=jng_width; image->rows=jng_height; length=image->columns*sizeof(PixelPacket); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { jng_image=DestroyImageList(jng_image); DestroyJNG(NULL,&color_image,&color_image_info,&alpha_image, &alpha_image_info); return(DestroyImageList(image)); } if ((image->columns != jng_image->columns) || (image->rows != jng_image->rows)) { jng_image=DestroyImageList(jng_image); DestroyJNG(NULL,&color_image,&color_image_info,&alpha_image, &alpha_image_info); return(DestroyImageList(image)); } 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 PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; (void) memcpy(q,s,length); 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) SeekBlob(alpha_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading opacity from alpha_blob."); (void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent, "%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,&image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if ((s == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; if (image->matte != MagickFalse) for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) SetPixelOpacity(q,QuantumRange-GetPixelRed(s)); else for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) { SetPixelAlpha(q,GetPixelRed(s)); if (GetPixelOpacity(q) != OpaqueOpacity) image->matte=MagickTrue; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } (void) RelinquishUniqueFileResource(alpha_image->filename); unique_filenames--; 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(); unique_filenames=%d",unique_filenames); return(image); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['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 *ReadCALSImage(const ImageInfo *image_info, ExceptionInfo *exception) { char filename[MaxTextExtent], header[129], message[MaxTextExtent]; FILE *file; Image *image; ImageInfo *read_info; int c, unique_file; MagickBooleanType status; register ssize_t i; unsigned long density, direction, height, orientation, pel_path, type, width; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read CALS header. */ (void) memset(header,0,sizeof(header)); density=0; direction=0; orientation=1; pel_path=0; type=1; width=0; height=0; for (i=0; i < 16; i++) { if (ReadBlob(image,128,(unsigned char *) header) != 128) break; switch (*header) { case 'R': case 'r': { if (LocaleNCompare(header,"rdensty:",8) == 0) { (void) sscanf(header+8,"%lu",&density); break; } if (LocaleNCompare(header,"rpelcnt:",8) == 0) { (void) sscanf(header+8,"%lu,%lu",&width,&height); break; } if (LocaleNCompare(header,"rorient:",8) == 0) { (void) sscanf(header+8,"%lu,%lu",&pel_path,&direction); if (pel_path == 90) orientation=5; else if (pel_path == 180) orientation=3; else if (pel_path == 270) orientation=7; if (direction == 90) orientation++; break; } if (LocaleNCompare(header,"rtype:",6) == 0) { (void) sscanf(header+6,"%lu",&type); break; } break; } } } /* Read CALS pixels. */ file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile"); while ((c=ReadBlobByte(image)) != EOF) (void) fputc(c,file); (void) fclose(file); (void) CloseBlob(image); image=DestroyImage(image); read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); (void) FormatLocaleString(read_info->filename,MaxTextExtent,"group4:%s", filename); (void) FormatLocaleString(message,MaxTextExtent,"%lux%lu",width,height); read_info->size=ConstantString(message); (void) FormatLocaleString(message,MaxTextExtent,"%lu",density); read_info->density=ConstantString(message); read_info->orientation=(OrientationType) orientation; image=ReadImage(read_info,exception); if (image != (Image *) NULL) { (void) CopyMagickString(image->filename,image_info->filename, MaxTextExtent); (void) CopyMagickString(image->magick_filename,image_info->filename, MaxTextExtent); (void) CopyMagickString(image->magick,"CALS",MaxTextExtent); } read_info=DestroyImageInfo(read_info); (void) RelinquishUniqueFileResource(filename); return(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: test_bson_validate (void) { char filename[64]; size_t offset; bson_t *b; int i; bson_error_t error; for (i = 1; i <= 38; i++) { bson_snprintf (filename, sizeof filename, "test%u.bson", i); b = get_bson (filename); BSON_ASSERT (bson_validate (b, BSON_VALIDATE_NONE, &offset)); bson_destroy (b); } b = get_bson ("codewscope.bson"); BSON_ASSERT (bson_validate (b, BSON_VALIDATE_NONE, &offset)); bson_destroy (b); b = get_bson ("empty_key.bson"); BSON_ASSERT (bson_validate (b, BSON_VALIDATE_NONE | BSON_VALIDATE_UTF8 | BSON_VALIDATE_DOLLAR_KEYS | BSON_VALIDATE_DOT_KEYS, &offset)); bson_destroy (b); #define VALIDATE_TEST(_filename, _flags, _offset, _flag, _msg) \ b = get_bson (_filename); \ BSON_ASSERT (!bson_validate (b, _flags, &offset)); \ ASSERT_CMPSIZE_T (offset, ==, (size_t) _offset); \ BSON_ASSERT (!bson_validate_with_error (b, _flags, &error)); \ ASSERT_ERROR_CONTAINS (error, BSON_ERROR_INVALID, _flag, _msg); \ bson_destroy (b) VALIDATE_TEST ("overflow2.bson", BSON_VALIDATE_NONE, 9, BSON_VALIDATE_NONE, "corrupt BSON"); VALIDATE_TEST ("trailingnull.bson", BSON_VALIDATE_NONE, 14, BSON_VALIDATE_NONE, "corrupt BSON"); VALIDATE_TEST ("dollarquery.bson", BSON_VALIDATE_DOLLAR_KEYS | BSON_VALIDATE_DOT_KEYS, 4, BSON_VALIDATE_DOLLAR_KEYS, "keys cannot begin with \"$\": \"$query\""); VALIDATE_TEST ("dotquery.bson", BSON_VALIDATE_DOLLAR_KEYS | BSON_VALIDATE_DOT_KEYS, 4, BSON_VALIDATE_DOT_KEYS, "keys cannot contain \".\": \"abc.def\""); VALIDATE_TEST ("overflow3.bson", BSON_VALIDATE_NONE, 9, BSON_VALIDATE_NONE, "corrupt BSON"); /* same outcome as above, despite different flags */ VALIDATE_TEST ("overflow3.bson", BSON_VALIDATE_UTF8, 9, BSON_VALIDATE_NONE, "corrupt BSON"); VALIDATE_TEST ("overflow4.bson", BSON_VALIDATE_NONE, 9, BSON_VALIDATE_NONE, "corrupt BSON"); VALIDATE_TEST ("empty_key.bson", BSON_VALIDATE_EMPTY_KEYS, 4, BSON_VALIDATE_EMPTY_KEYS, "empty key"); VALIDATE_TEST ( "test40.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); VALIDATE_TEST ( "test41.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); VALIDATE_TEST ( "test42.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); VALIDATE_TEST ( "test43.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); VALIDATE_TEST ( "test44.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); VALIDATE_TEST ( "test45.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); VALIDATE_TEST ( "test46.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); VALIDATE_TEST ( "test47.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); VALIDATE_TEST ( "test48.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); VALIDATE_TEST ( "test49.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); VALIDATE_TEST ("test50.bson", BSON_VALIDATE_NONE, 10, BSON_VALIDATE_NONE, "corrupt code-with-scope"); VALIDATE_TEST ("test51.bson", BSON_VALIDATE_NONE, 10, BSON_VALIDATE_NONE, "corrupt code-with-scope"); VALIDATE_TEST ( "test52.bson", BSON_VALIDATE_NONE, 9, BSON_VALIDATE_NONE, "corrupt BSON"); VALIDATE_TEST ( "test53.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); VALIDATE_TEST ("test54.bson", BSON_VALIDATE_NONE, 12, BSON_VALIDATE_NONE, "corrupt BSON"); /* DBRef validation */ b = BCON_NEW ("my_dbref", "{", "$ref", BCON_UTF8 ("collection"), "$id", BCON_INT32 (1), "}"); BSON_ASSERT (bson_validate_with_error (b, BSON_VALIDATE_NONE, &error)); BSON_ASSERT ( bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error)); bson_destroy (b); /* needs "$ref" before "$id" */ b = BCON_NEW ("my_dbref", "{", "$id", BCON_INT32 (1), "}"); BSON_ASSERT (bson_validate_with_error (b, BSON_VALIDATE_NONE, &error)); BSON_ASSERT ( !bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error)); ASSERT_ERROR_CONTAINS (error, BSON_ERROR_INVALID, BSON_VALIDATE_DOLLAR_KEYS, "keys cannot begin with \"$\": \"$id\""); bson_destroy (b); /* two $refs */ b = BCON_NEW ("my_dbref", "{", "$ref", BCON_UTF8 ("collection"), "$ref", BCON_UTF8 ("collection"), "}"); BSON_ASSERT (bson_validate_with_error (b, BSON_VALIDATE_NONE, &error)); BSON_ASSERT ( !bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error)); ASSERT_ERROR_CONTAINS (error, BSON_ERROR_INVALID, BSON_VALIDATE_DOLLAR_KEYS, "keys cannot begin with \"$\": \"$ref\""); bson_destroy (b); /* must not contain invalid key like "extra" */ b = BCON_NEW ("my_dbref", "{", "$ref", BCON_UTF8 ("collection"), "extra", BCON_INT32 (2), "$id", BCON_INT32 (1), "}"); BSON_ASSERT (bson_validate_with_error (b, BSON_VALIDATE_NONE, &error)); BSON_ASSERT ( !bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error)); ASSERT_ERROR_CONTAINS (error, BSON_ERROR_INVALID, BSON_VALIDATE_DOLLAR_KEYS, "invalid key within DBRef subdocument: \"extra\""); bson_destroy (b); #undef VALIDATE_TEST } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix for CVE-2018-16790 -- Verify bounds before binary length read. As reported here: https://jira.mongodb.org/browse/CDRIVER-2819, a heap overread occurs due a failure to correctly verify data bounds. In the original check, len - o returns the data left including the sizeof(l) we just read. Instead, the comparison should check against the data left NOT including the binary int32, i.e. just subtype (byte*) instead of int32 subtype (byte*). Added in test for corrupted BSON example.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: epass2003_sm_unwrap_apdu(struct sc_card *card, struct sc_apdu *sm, struct sc_apdu *plain) { int r; size_t len = 0; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); r = sc_check_sw(card, sm->sw1, sm->sw2); if (r == SC_SUCCESS) { if (exdata->sm) { if (0 != decrypt_response(card, sm->resp, sm->resplen, plain->resp, &len)) return SC_ERROR_CARD_CMD_FAILED; } else { memcpy(plain->resp, sm->resp, sm->resplen); len = sm->resplen; } } plain->resplen = len; plain->sw1 = sm->sw1; plain->sw2 = sm->sw2; sc_log(card->ctx, "unwrapped APDU: resplen %"SC_FORMAT_LEN_SIZE_T"u, SW %02X%02X", plain->resplen, plain->sw1, plain->sw2); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } ; 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 cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL); if (card->serialnr.len) { *serial = card->serialnr; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } if (priv->cac_id_len) { serial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR); memcpy(serial->value, priv->cac_id, priv->cac_id_len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND); } ; 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: void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) { tcp::TCP_ApplicationAnalyzer::DeliverStream(length, line, orig); if ( starttls ) { ForwardStream(length, line, orig); return; } // check line size if ( length > 512 ) { Weird("irc_line_size_exceeded"); return; } string myline = string((const char*) line, length); SkipLeadingWhitespace(myline); if ( myline.length() < 3 ) { Weird("irc_line_too_short"); return; } // Check for prefix. string prefix = ""; if ( myline[0] == ':' ) { // find end of prefix and extract it auto pos = myline.find(' '); if ( pos == string::npos ) { Weird("irc_invalid_line"); return; } prefix = myline.substr(1, pos - 1); myline = myline.substr(pos + 1); // remove prefix from line SkipLeadingWhitespace(myline); } if ( orig ) ProtocolConfirmation(); int code = 0; string command = ""; // Check if line is long enough to include status code or command. // (shortest command with optional params is "WHO") if ( myline.length() < 3 ) { Weird("irc_invalid_line"); ProtocolViolation("line too short"); return; } // Check if this is a server reply. if ( isdigit(myline[0]) ) { if ( isdigit(myline[1]) && isdigit(myline[2]) && myline[3] == ' ') { code = (myline[0] - '0') * 100 + (myline[1] - '0') * 10 + (myline[2] - '0'); myline = myline.substr(4); } else { Weird("irc_invalid_reply_number"); ProtocolViolation("invalid reply number"); return; } } else { // get command auto pos = myline.find(' '); // Not all commands require parameters if ( pos == string::npos ) pos = myline.length(); command = myline.substr(0, pos); for ( unsigned int i = 0; i < command.size(); ++i ) command[i] = toupper(command[i]); // Adjust for the no-parameter case if ( pos == myline.length() ) pos--; myline = myline.substr(pos + 1); SkipLeadingWhitespace(myline); } // Extract parameters. string params = myline; // special case if ( command == "STARTTLS" ) return; // Check for Server2Server - connections with ZIP enabled. if ( orig && orig_status == WAIT_FOR_REGISTRATION ) { if ( command == "PASS" ) { vector<string> p = SplitWords(params,' '); if ( p.size() > 3 && (p[3].find('Z')<=p[3].size() || p[3].find('z')<=p[3].size()) ) orig_zip_status = ACCEPT_ZIP; else orig_zip_status = NO_ZIP; } // We do not check if SERVER command is successful, since // the connection will be terminated by the server if // authentication fails. // // (### This seems not quite prudent to me - VP) if ( command == "SERVER" && prefix == "") { orig_status = REGISTERED; } } if ( ! orig && resp_status == WAIT_FOR_REGISTRATION ) { if ( command == "PASS" ) { vector<string> p = SplitWords(params,' '); if ( p.size() > 3 && (p[3].find('Z')<=p[3].size() || p[3].find('z')<=p[3].size()) ) resp_zip_status = ACCEPT_ZIP; else resp_zip_status = NO_ZIP; } // Again, don't bother checking whether SERVER command // is successful. if ( command == "SERVER" && prefix == "") resp_status = REGISTERED; } // Analyze server reply messages. if ( code > 0 ) { switch ( code ) { /* case 1: // RPL_WELCOME case 2: // RPL_YOURHOST case 3: // RPL_CREATED case 4: // RPL_MYINFO case 5: // RPL_BOUNCE case 252: // number of ops online case 253: // number of unknown connections case 265: // RPL_LOCALUSERS case 312: // whois server reply case 315: // end of who list case 317: // whois idle reply case 318: // end of whois list case 366: // end of names list case 372: // RPL_MOTD case 375: // RPL_MOTDSTART case 376: // RPL_ENDOFMOTD case 331: // RPL_NOTOPIC break; */ // Count of users, services and servers in whole network. case 251: if ( ! irc_network_info ) break; { vector<string> parts = SplitWords(params, ' '); int users = 0; int services = 0; int servers = 0; for ( unsigned int i = 1; i < parts.size(); ++i ) { if ( parts[i] == "users" ) users = atoi(parts[i-1].c_str()); else if ( parts[i] == "services" ) services = atoi(parts[i-1].c_str()); else if ( parts[i] == "servers" ) servers = atoi(parts[i-1].c_str()); // else ### } val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); vl->append(new Val(users, TYPE_INT)); vl->append(new Val(services, TYPE_INT)); vl->append(new Val(servers, TYPE_INT)); ConnectionEvent(irc_network_info, vl); } break; // List of users in a channel (names command). case 353: if ( ! irc_names_info ) break; { vector<string> parts = SplitWords(params, ' '); // Remove nick name. parts.erase(parts.begin()); if ( parts.size() < 2 ) { Weird("irc_invalid_names_line"); return; } string type = parts[0]; string channel = parts[1]; // Remove type and channel. parts.erase(parts.begin()); parts.erase(parts.begin()); if ( parts.size() > 0 && parts[0][0] == ':' ) parts[0] = parts[0].substr(1); val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); vl->append(new StringVal(type.c_str())); vl->append(new StringVal(channel.c_str())); TableVal* set = new TableVal(string_set); for ( unsigned int i = 0; i < parts.size(); ++i ) { if ( parts[i][0] == '@' ) parts[i] = parts[i].substr(1); Val* idx = new StringVal(parts[i].c_str()); set->Assign(idx, 0); Unref(idx); } vl->append(set); ConnectionEvent(irc_names_info, vl); } break; // Count of users and services on this server. case 255: if ( ! irc_server_info ) break; { vector<string> parts = SplitWords(params, ' '); int users = 0; int services = 0; int servers = 0; for ( unsigned int i = 1; i < parts.size(); ++i ) { if ( parts[i] == "users," ) users = atoi(parts[i-1].c_str()); else if ( parts[i] == "clients" ) users = atoi(parts[i-1].c_str()); else if ( parts[i] == "services" ) services = atoi(parts[i-1].c_str()); else if ( parts[i] == "servers" ) servers = atoi(parts[i-1].c_str()); // else ### } val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); vl->append(new Val(users, TYPE_INT)); vl->append(new Val(services, TYPE_INT)); vl->append(new Val(servers, TYPE_INT)); ConnectionEvent(irc_server_info, vl); } break; // Count of channels. case 254: if ( ! irc_channel_info ) break; { vector<string> parts = SplitWords(params, ' '); int channels = 0; for ( unsigned int i = 1; i < parts.size(); ++i ) if ( parts[i] == ":channels" ) channels = atoi(parts[i - 1].c_str()); val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); vl->append(new Val(channels, TYPE_INT)); ConnectionEvent(irc_channel_info, vl); } break; // RPL_GLOBALUSERS case 266: { // FIXME: We should really streamline all this // parsing code ... if ( ! irc_global_users ) break; const char* prefix = params.c_str(); const char* eop = strchr(prefix, ' '); if ( ! eop ) { Weird("invalid_irc_global_users_reply"); break; } const char *msg = strchr(++eop, ':'); if ( ! msg ) { Weird("invalid_irc_global_users_reply"); break; } val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); vl->append(new StringVal(eop - prefix, prefix)); vl->append(new StringVal(++msg)); ConnectionEvent(irc_global_users, vl); break; } // WHOIS user reply line. case 311: if ( ! irc_whois_user_line ) break; { vector<string> parts = SplitWords(params, ' '); if ( parts.size() > 1 ) parts.erase(parts.begin()); if ( parts.size() < 5 ) { Weird("irc_invalid_whois_user_line"); return; } val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); vl->append(new StringVal(parts[0].c_str())); vl->append(new StringVal(parts[1].c_str())); vl->append(new StringVal(parts[2].c_str())); parts.erase(parts.begin(), parts.begin() + 4); string real_name = parts[0]; for ( unsigned int i = 1; i < parts.size(); ++i ) real_name = real_name + " " + parts[i]; if ( real_name[0] == ':' ) real_name = real_name.substr(1); vl->append(new StringVal(real_name.c_str())); ConnectionEvent(irc_whois_user_line, vl); } break; // WHOIS operator reply line. case 313: if ( ! irc_whois_operator_line ) break; { vector<string> parts = SplitWords(params, ' '); if ( parts.size() > 1 ) parts.erase(parts.begin()); if ( parts.size() < 2 ) { Weird("irc_invalid_whois_operator_line"); return; } val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); vl->append(new StringVal(parts[0].c_str())); ConnectionEvent(irc_whois_operator_line, vl); } break; // WHOIS channel reply. case 319: if ( ! irc_whois_channel_line ) break; { vector<string> parts = SplitWords(params, ' '); // Remove nick name. parts.erase(parts.begin()); if ( parts.size() < 2 ) { Weird("irc_invalid_whois_channel_line"); return; } string nick = parts[0]; parts.erase(parts.begin()); if ( parts.size() > 0 && parts[0][0] == ':' ) parts[0] = parts[0].substr(1); val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); vl->append(new StringVal(nick.c_str())); TableVal* set = new TableVal(string_set); for ( unsigned int i = 0; i < parts.size(); ++i ) { Val* idx = new StringVal(parts[i].c_str()); set->Assign(idx, 0); Unref(idx); } vl->append(set); ConnectionEvent(irc_whois_channel_line, vl); } break; // RPL_TOPIC reply. case 332: { if ( ! irc_channel_topic ) break; vector<string> parts = SplitWords(params, ' '); if ( parts.size() < 4 ) { Weird("irc_invalid_topic_reply"); return; } unsigned int pos = params.find(':'); if ( pos < params.size() ) { string topic = params.substr(pos + 1); val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); vl->append(new StringVal(parts[1].c_str())); const char* t = topic.c_str(); if ( *t == ':' ) ++t; vl->append(new StringVal(t)); ConnectionEvent(irc_channel_topic, vl); } else { Weird("irc_invalid_topic_reply"); return; } break; } // WHO reply line. case 352: if ( ! irc_who_line ) break; { vector<string> parts = SplitWords(params, ' '); if ( parts.size() < 9 ) { Weird("irc_invalid_who_line"); return; } val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); vl->append(new StringVal(parts[0].c_str())); vl->append(new StringVal(parts[1].c_str())); if ( parts[2][0] == '~' ) parts[2] = parts[2].substr(1); vl->append(new StringVal(parts[2].c_str())); vl->append(new StringVal(parts[3].c_str())); vl->append(new StringVal(parts[4].c_str())); vl->append(new StringVal(parts[5].c_str())); vl->append(new StringVal(parts[6].c_str())); if ( parts[7][0] == ':' ) parts[7] = parts[7].substr(1); vl->append(new Val(atoi(parts[7].c_str()), TYPE_INT)); vl->append(new StringVal(parts[8].c_str())); ConnectionEvent(irc_who_line, vl); } break; // Invalid nick name. case 431: case 432: case 433: case 436: if ( irc_invalid_nick ) { val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); ConnectionEvent(irc_invalid_nick, vl); } break; // Operator responses. case 381: // User is operator case 491: // user is not operator if ( irc_oper_response ) { val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); vl->append(new Val(code == 381, TYPE_BOOL)); ConnectionEvent(irc_oper_response, vl); } break; case 670: // StartTLS success reply to StartTLS StartTLS(); break; // All other server replies. default: val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); vl->append(new StringVal(prefix.c_str())); vl->append(new Val(code, TYPE_COUNT)); vl->append(new StringVal(params.c_str())); ConnectionEvent(irc_reply, vl); break; } return; } // Check if command is valid. if ( command.size() > 20 ) { Weird("irc_invalid_command"); if ( ++invalid_msg_count > invalid_msg_max_count ) { Weird("irc_too_many_invalid"); ProtocolViolation("too many long lines"); return; } return; } else if ( ( irc_privmsg_message || irc_dcc_message ) && command == "PRIVMSG") { unsigned int pos = params.find(' '); if ( pos >= params.size() ) { Weird("irc_invalid_privmsg_message_format"); return; } string target = params.substr(0, pos); string message = params.substr(pos + 1); SkipLeadingWhitespace(message); if ( message.size() > 0 && message[0] == ':' ) message = message.substr(1); if ( message.size() > 0 && message[0] == 1 ) message = message.substr(1); // DCC // Check for DCC messages. if ( message.size() > 3 && message.substr(0, 3) == "DCC" ) { if ( message.size() > 0 && message[message.size() - 1] == 1 ) message = message.substr(0, message.size() - 1); vector<string> parts = SplitWords(message, ' '); if ( parts.size() < 5 || parts.size() > 6 ) { // Turbo DCC extension appends a "T" at the end of handshake. if ( ! (parts.size() == 7 && parts[6] == "T") ) { Weird("irc_invalid_dcc_message_format"); return; } } // Calculate IP address. uint32 raw_ip = 0; for ( unsigned int i = 0; i < parts[3].size(); ++i ) { string s = parts[3].substr(i, 1); raw_ip = (10 * raw_ip) + atoi(s.c_str()); } val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); vl->append(new StringVal(prefix.c_str())); vl->append(new StringVal(target.c_str())); vl->append(new StringVal(parts[1].c_str())); vl->append(new StringVal(parts[2].c_str())); vl->append(new AddrVal(htonl(raw_ip))); vl->append(new Val(atoi(parts[4].c_str()), TYPE_COUNT)); if ( parts.size() >= 6 ) vl->append(new Val(atoi(parts[5].c_str()), TYPE_COUNT)); else vl->append(new Val(0, TYPE_COUNT)); ConnectionEvent(irc_dcc_message, vl); } else { val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); vl->append(new StringVal(prefix.c_str())); vl->append(new StringVal(target.c_str())); vl->append(new StringVal(message.c_str())); ConnectionEvent(irc_privmsg_message, vl); } } else if ( irc_notice_message && command == "NOTICE" ) { unsigned int pos = params.find(' '); if ( pos >= params.size() ) { Weird("irc_invalid_notice_message_format"); return; } string target = params.substr(0, pos); string message = params.substr(pos + 1); SkipLeadingWhitespace(message); if ( message[0] == ':' ) message = message.substr(1); val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); vl->append(new StringVal(prefix.c_str())); vl->append(new StringVal(target.c_str())); vl->append(new StringVal(message.c_str())); ConnectionEvent(irc_notice_message, vl); } else if ( irc_squery_message && command == "SQUERY" ) { unsigned int pos = params.find(' '); if ( pos >= params.size() ) { Weird("irc_invalid_squery_message_format"); return; } string target = params.substr(0, pos); string message = params.substr(pos + 1); SkipLeadingWhitespace(message); if ( message[0] == ':' ) message = message.substr(1); val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); vl->append(new StringVal(prefix.c_str())); vl->append(new StringVal(target.c_str())); vl->append(new StringVal(message.c_str())); ConnectionEvent(irc_squery_message, vl); } else if ( irc_user_message && command == "USER" ) { // extract username and real name vector<string> parts = SplitWords(params, ' '); val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); if ( parts.size() > 0 ) vl->append(new StringVal(parts[0].c_str())); else vl->append(new StringVal("")); if ( parts.size() > 1 ) vl->append(new StringVal(parts[1].c_str())); else vl->append(new StringVal("")); if ( parts.size() > 2 ) vl->append(new StringVal(parts[2].c_str())); else vl->append(new StringVal("")); string realname; for ( unsigned int i = 3; i < parts.size(); i++ ) { realname += parts[i]; if ( i > 3 ) realname += " "; } const char* name = realname.c_str(); vl->append(new StringVal(*name == ':' ? name + 1 : name)); ConnectionEvent(irc_user_message, vl); } else if ( irc_oper_message && command == "OPER" ) { // extract username and password vector<string> parts = SplitWords(params, ' '); if ( parts.size() == 2 ) { val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); vl->append(new StringVal(parts[0].c_str())); vl->append(new StringVal(parts[1].c_str())); ConnectionEvent(irc_oper_message, vl); } else Weird("irc_invalid_oper_message_format"); } else if ( irc_kick_message && command == "KICK" ) { // Extract channels, users and comment. vector<string> parts = SplitWords(params, ' '); if ( parts.size() <= 1 ) { Weird("irc_invalid_kick_message_format"); return; } val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); vl->append(new StringVal(prefix.c_str())); vl->append(new StringVal(parts[0].c_str())); vl->append(new StringVal(parts[1].c_str())); if ( parts.size() > 2 ) { string comment = parts[2]; for ( unsigned int i = 3; i < parts.size(); ++i ) comment += " " + parts[i]; if ( comment[0] == ':' ) comment = comment.substr(1); vl->append(new StringVal(comment.c_str())); } else vl->append(new StringVal("")); ConnectionEvent(irc_kick_message, vl); } else if ( irc_join_message && command == "JOIN" ) { if ( params[0] == ':' ) params = params.substr(1); vector<string> parts = SplitWords(params, ' '); if ( parts.size() < 1 ) { Weird("irc_invalid_join_line"); return; } string nickname = ""; if ( prefix.size() > 0 ) { unsigned int pos = prefix.find('!'); if ( pos < prefix.size() ) nickname = prefix.substr(0, pos); } val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); TableVal* list = new TableVal(irc_join_list); vector<string> channels = SplitWords(parts[0], ','); vector<string> passwords; if ( parts.size() > 1 ) passwords = SplitWords(parts[1], ','); string empty_string = ""; for ( unsigned int i = 0; i < channels.size(); ++i ) { RecordVal* info = new RecordVal(irc_join_info); info->Assign(0, new StringVal(nickname.c_str())); info->Assign(1, new StringVal(channels[i].c_str())); if ( i < passwords.size() ) info->Assign(2, new StringVal(passwords[i].c_str())); else info->Assign(2, new StringVal(empty_string.c_str())); // User mode. info->Assign(3, new StringVal(empty_string.c_str())); list->Assign(info, 0); Unref(info); } vl->append(list); ConnectionEvent(irc_join_message, vl); } else if ( irc_join_message && command == "NJOIN" ) { vector<string> parts = SplitWords(params, ' '); if ( parts.size() != 2 ) { Weird("irc_invalid_njoin_line"); return; } string channel = parts[0]; if ( parts[1][0] == ':' ) parts[1] = parts[1].substr(1); vector<string> users = SplitWords(parts[1], ','); val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); TableVal* list = new TableVal(irc_join_list); string empty_string = ""; for ( unsigned int i = 0; i < users.size(); ++i ) { RecordVal* info = new RecordVal(irc_join_info); string nick = users[i]; string mode = "none"; if ( nick[0] == '@' ) { if ( nick[1] == '@' ) { nick = nick.substr(2); mode = "creator"; } else { nick = nick.substr(1); mode = "operator"; } } else if ( nick[0] == '+' ) { nick = nick.substr(1); mode = "voice"; } info->Assign(0, new StringVal(nick.c_str())); info->Assign(1, new StringVal(channel.c_str())); // Password: info->Assign(2, new StringVal(empty_string.c_str())); // User mode: info->Assign(3, new StringVal(mode.c_str())); list->Assign(info, 0); Unref(info); } vl->append(list); ConnectionEvent(irc_join_message, vl); } else if ( irc_part_message && command == "PART" ) { string channels = params; string message = ""; unsigned int pos = params.find(' '); if ( pos < params.size() ) { channels = params.substr(0, pos); if ( params.size() > pos + 1 ) { message = params.substr(pos + 1); SkipLeadingWhitespace(message); } if ( message[0] == ':' ) message = message.substr(1); } string nick = prefix; pos = nick.find('!'); if ( pos < nick.size() ) nick = nick.substr(0, pos); vector<string> channelList = SplitWords(channels, ','); TableVal* set = new TableVal(string_set); for ( unsigned int i = 0; i < channelList.size(); ++i ) { Val* idx = new StringVal(channelList[i].c_str()); set->Assign(idx, 0); Unref(idx); } val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); vl->append(new StringVal(nick.c_str())); vl->append(set); vl->append(new StringVal(message.c_str())); ConnectionEvent(irc_part_message, vl); } else if ( irc_quit_message && command == "QUIT" ) { string message = params; if ( message[0] == ':' ) message = message.substr(1); string nickname = ""; if ( prefix.size() > 0 ) { unsigned int pos = prefix.find('!'); if ( pos < prefix.size() ) nickname = prefix.substr(0, pos); } val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); vl->append(new StringVal(nickname.c_str())); vl->append(new StringVal(message.c_str())); ConnectionEvent(irc_quit_message, vl); } else if ( irc_nick_message && command == "NICK" ) { string nick = params; if ( nick[0] == ':' ) nick = nick.substr(1); val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); vl->append(new StringVal(prefix.c_str())); vl->append(new StringVal(nick.c_str())); ConnectionEvent(irc_nick_message, vl); } else if ( irc_who_message && command == "WHO" ) { vector<string> parts = SplitWords(params, ' '); if ( parts.size() > 2 ) { Weird("irc_invalid_who_message_format"); return; } bool oper = false; if ( parts.size() == 2 && parts[1] == "o" ) oper = true; // Remove ":" from mask. if ( parts.size() > 0 && parts[0].size() > 0 && parts[0][0] == ':' ) parts[0] = parts[0].substr(1); val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); if ( parts.size() > 0 ) vl->append(new StringVal(parts[0].c_str())); else vl->append(new StringVal("")); vl->append(new Val(oper, TYPE_BOOL)); ConnectionEvent(irc_who_message, vl); } else if ( irc_whois_message && command == "WHOIS" ) { vector<string> parts = SplitWords(params, ' '); if ( parts.size() < 1 || parts.size() > 2 ) { Weird("irc_invalid_whois_message_format"); return; } string server = ""; string users = ""; if ( parts.size() == 2 ) { server = parts[0]; users = parts[1]; } else users = parts[0]; val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); vl->append(new StringVal(server.c_str())); vl->append(new StringVal(users.c_str())); ConnectionEvent(irc_whois_message, vl); } else if ( irc_error_message && command == "ERROR" ) { val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); vl->append(new StringVal(prefix.c_str())); if ( params[0] == ':' ) params = params.substr(1); vl->append(new StringVal(params.c_str())); ConnectionEvent(irc_error_message, vl); } else if ( irc_invite_message && command == "INVITE" ) { vector<string> parts = SplitWords(params, ' '); if ( parts.size() == 2 ) { // remove ":" from channel if ( parts[1].size() > 0 && parts[1][0] == ':' ) parts[1] = parts[1].substr(1); val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); vl->append(new StringVal(prefix.c_str())); vl->append(new StringVal(parts[0].c_str())); vl->append(new StringVal(parts[1].c_str())); ConnectionEvent(irc_invite_message, vl); } else Weird("irc_invalid_invite_message_format"); } else if ( irc_mode_message && command == "MODE" ) { if ( params.size() > 0 ) { val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); vl->append(new StringVal(prefix.c_str())); vl->append(new StringVal(params.c_str())); ConnectionEvent(irc_mode_message, vl); } else Weird("irc_invalid_mode_message_format"); } else if ( irc_password_message && command == "PASS" ) { val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); vl->append(new StringVal(params.c_str())); ConnectionEvent(irc_password_message, vl); } else if ( irc_squit_message && command == "SQUIT" ) { string server = params; string message = ""; unsigned int pos = params.find(' '); if ( pos < params.size() ) { server = params.substr(0, pos); message = params.substr(pos + 1); SkipLeadingWhitespace(message); if ( message[0] == ':' ) message = message.substr(1); } val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); vl->append(new StringVal(prefix.c_str())); vl->append(new StringVal(server.c_str())); vl->append(new StringVal(message.c_str())); ConnectionEvent(irc_squit_message, vl); } else if ( orig ) { if ( irc_request ) { val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); vl->append(new StringVal(prefix.c_str())); vl->append(new StringVal(command.c_str())); vl->append(new StringVal(params.c_str())); ConnectionEvent(irc_request, vl); } } else { if ( irc_message ) { val_list* vl = new val_list; vl->append(BuildConnVal()); vl->append(new Val(orig, TYPE_BOOL)); vl->append(new StringVal(prefix.c_str())); vl->append(new StringVal(command.c_str())); vl->append(new StringVal(params.c_str())); ConnectionEvent(irc_message, vl); } } if ( orig_status == REGISTERED && resp_status == REGISTERED && orig_zip_status == ACCEPT_ZIP && resp_zip_status == ACCEPT_ZIP ) { orig_zip_status = ZIP_LOADED; resp_zip_status = ZIP_LOADED; AddSupportAnalyzer(new zip::ZIP_Analyzer(Conn(), true)); AddSupportAnalyzer(new zip::ZIP_Analyzer(Conn(), false)); } return; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix IRC names command parsing'</s>
<s>[INST] Given the following code containing errors, provide 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 float *buffer, int numElems) { int numBytes; int bytesPerSample; if (numElems == 0) return; bytesPerSample = header.format.bits_per_sample / 8; numBytes = numElems * bytesPerSample; int confBufBytes = (numBytes + 3) & -4; // round up to nearest multiple of four to avoid overflow with 24bit-value assignment void *temp = getConvBuffer(confBufBytes); switch (bytesPerSample) { case 1: { unsigned char *temp2 = (unsigned char *)temp; for (int i = 0; i < numElems; i ++) { temp2[i] = (unsigned char)saturate(buffer[i] * 128.0f + 128.0f, 0.0f, 255.0f); } break; } case 2: { short *temp2 = (short *)temp; for (int i = 0; i < numElems; i ++) { short value = (short)saturate(buffer[i] * 32768.0f, -32768.0f, 32767.0f); temp2[i] = _swap16(value); } break; } case 3: { char *temp2 = (char *)temp; for (int i = 0; i < numElems; i ++) { int value = saturate(buffer[i] * 8388608.0f, -8388608.0f, 8388607.0f); *((int*)temp2) = _swap32(value); temp2 += 3; } break; } case 4: { int *temp2 = (int *)temp; for (int i = 0; i < numElems; i ++) { int value = saturate(buffer[i] * 2147483648.0f, -2147483648.0f, 2147483647.0f); temp2[i] = _swap32(value); } break; } default: assert(false); } int res = (int)fwrite(temp, 1, numBytes, fptr); if (res != numBytes) { ST_THROW_RT_ERROR("Error while writing to a wav file."); } bytesWritten += numBytes; } ; 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: int ovl_permission(struct inode *inode, int mask) { struct ovl_entry *oe = inode->i_private; bool is_upper; struct dentry *realdentry = ovl_entry_real(oe, &is_upper); struct inode *realinode; int err; if (ovl_is_default_permissions(inode)) { struct kstat stat; struct path realpath = { .dentry = realdentry }; if (mask & MAY_NOT_BLOCK) return -ECHILD; realpath.mnt = ovl_entry_mnt_real(oe, inode, is_upper); err = vfs_getattr(&realpath, &stat); if (err) return err; if ((stat.mode ^ inode->i_mode) & S_IFMT) return -ESTALE; inode->i_mode = stat.mode; inode->i_uid = stat.uid; inode->i_gid = stat.gid; return generic_permission(inode, mask); } /* Careful in RCU walk mode */ realinode = d_inode_rcu(realdentry); if (!realinode) { WARN_ON(!(mask & MAY_NOT_BLOCK)); return -ENOENT; } if (mask & MAY_WRITE) { umode_t mode = realinode->i_mode; /* * Writes will always be redirected to upper layer, so * ignore lower layer being read-only. * * If the overlay itself is read-only then proceed * with the permission check, don't return EROFS. * This will only happen if this is the lower layer of * another overlayfs. * * If upper fs becomes read-only after the overlay was * constructed return EROFS to prevent modification of * upper layer. */ if (is_upper && !IS_RDONLY(inode) && IS_RDONLY(realinode) && (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) return -EROFS; } return __inode_permission(realinode, mask); } ; 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: matchCurrentInput( const InString *input, int pos, const widechar *passInstructions, int passIC) { int k; int kk = pos; for (k = passIC + 2; k < passIC + 2 + passInstructions[passIC + 1]; k++) if (input->chars[kk] == ENDSEGMENT || passInstructions[k] != input->chars[kk++]) return 0; return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix a buffer overflow Fixes #635 Thanks to HongxuChen for reporting it'</s>
<s>[INST] Given the following code containing errors, provide 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 clone_submodule(const char *path, const char *gitdir, const char *url, const char *depth, struct string_list *reference, int quiet, int progress) { struct child_process cp = CHILD_PROCESS_INIT; argv_array_push(&cp.args, "clone"); argv_array_push(&cp.args, "--no-checkout"); if (quiet) argv_array_push(&cp.args, "--quiet"); if (progress) argv_array_push(&cp.args, "--progress"); if (depth && *depth) argv_array_pushl(&cp.args, "--depth", depth, NULL); if (reference->nr) { struct string_list_item *item; for_each_string_list_item(item, reference) argv_array_pushl(&cp.args, "--reference", item->string, NULL); } if (gitdir && *gitdir) argv_array_pushl(&cp.args, "--separate-git-dir", gitdir, NULL); argv_array_push(&cp.args, url); argv_array_push(&cp.args, path); cp.git_cmd = 1; prepare_submodule_repo_env(&cp.env_array); cp.no_stdin = 1; return run_command(&cp); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-88'], 'message': 'submodule--helper: use "--" to signal end of clone options When we clone a submodule, we call "git clone $url $path". But there's nothing to say that those components can't begin with a dash themselves, confusing git-clone into thinking they're options. Let's pass "--" to make it clear what we expect. There's no test here, because it's actually quite hard to make these names work, even with "git clone" parsing them correctly. And we're going to restrict these cases even further in future commits. So we'll leave off testing until then; this is just the minimal fix to prevent us from doing something stupid with a badly formed entry. Reported-by: joernchen <joernchen@phenoelit.de> Signed-off-by: Jeff King <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.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: mon_rwxa_t MonCapGrant::get_allowed(CephContext *cct, int daemon_type, EntityName name, const std::string& s, const std::string& c, const map<string,string>& c_args) const { if (profile.length()) { expand_profile(daemon_type, name); mon_rwxa_t a; for (list<MonCapGrant>::const_iterator p = profile_grants.begin(); p != profile_grants.end(); ++p) a = a | p->get_allowed(cct, daemon_type, name, s, c, c_args); return a; } if (service.length()) { if (service != s) return 0; return allow; } if (command.length()) { if (command != c) return 0; for (map<string,StringConstraint>::const_iterator p = command_args.begin(); p != command_args.end(); ++p) { map<string,string>::const_iterator q = c_args.find(p->first); // argument must be present if a constraint exists if (q == c_args.end()) return 0; switch (p->second.match_type) { case StringConstraint::MATCH_TYPE_EQUAL: if (p->second.value != q->second) return 0; break; case StringConstraint::MATCH_TYPE_PREFIX: if (q->second.find(p->second.value) != 0) return 0; break; case StringConstraint::MATCH_TYPE_REGEX: try { std::regex pattern( p->second.value, std::regex::extended); if (!std::regex_match(q->second, pattern)) return 0; } catch(const std::regex_error&) { return 0; } break; default: break; } } return MON_CAP_ALL; } return allow; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-285'], 'message': 'mon/config-key: limit caps allowed to access the store Henceforth, we'll require explicit `allow` caps for commands, or for the config-key service. Blanket caps are no longer allowed for the config-key service, except for 'allow *'. (for luminous and mimic, we're also ensuring MonCap's parser is able to understand forward slashes '/' when parsing prefixes) Signed-off-by: Joao Eduardo Luis <joao@suse.de> (cherry picked from commit 5fff611041c5afeaf3c8eb09e4de0cc919d69237)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static bool manager_check_idle(void *userdata) { Manager *m = userdata; Link *link; Iterator i; assert(m); HASHMAP_FOREACH(link, m->links, i) { /* we are not woken on udev activity, so let's just wait for the * pending udev event */ if (link->state == LINK_STATE_PENDING) return false; if (!link->network) continue; /* we are not woken on netork activity, so let's stay around */ if (link_lldp_enabled(link) || link_ipv4ll_enabled(link) || link_dhcp4_server_enabled(link) || link_dhcp4_enabled(link) || link_dhcp6_enabled(link)) return false; } return true; } ; 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: execstack2_continue(i_ctx_t *i_ctx_p) { os_ptr op = osp; return do_execstack(i_ctx_p, op->value.boolval, op - 1); } ; 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[256]; len = vsnprintf(print_buffer, sizeof(print_buffer), fmt, ap); 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; } } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'curl: support >256 bytes warning messsages Bug: #2174'</s>
<s>[INST] Given the following code containing errors, provide 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 RGWListBucketMultiparts_ObjStore::get_params() { delimiter = s->info.args.get("delimiter"); prefix = s->info.args.get("prefix"); string str = s->info.args.get("max-uploads"); op_ret = parse_value_and_bound(str, &max_uploads, 0, g_conf()->rgw_max_listing_results, default_max); if (op_ret < 0) { return op_ret; } string key_marker = s->info.args.get("key-marker"); string upload_id_marker = s->info.args.get("upload-id-marker"); if (!key_marker.empty()) marker.init(key_marker, upload_id_marker); return 0; } ; 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: static int ras_putdatastd(jas_stream_t *out, ras_hdr_t *hdr, jas_image_t *image, int numcmpts, int *cmpts) { int rowsize; int pad; unsigned int z; int nz; int c; int x; int y; int v; jas_matrix_t *data[3]; int i; assert(numcmpts <= 3); for (i = 0; i < 3; ++i) { data[i] = 0; } for (i = 0; i < numcmpts; ++i) { if (!(data[i] = jas_matrix_create(jas_image_height(image), jas_image_width(image)))) { goto error; } } rowsize = RAS_ROWSIZE(hdr); pad = rowsize - (hdr->width * hdr->depth + 7) / 8; hdr->length = hdr->height * rowsize; for (y = 0; y < hdr->height; y++) { for (i = 0; i < numcmpts; ++i) { if (jas_image_readcmpt(image, cmpts[i], 0, y, jas_image_width(image), 1, data[i])) { goto error; } } z = 0; nz = 0; for (x = 0; x < hdr->width; x++) { z <<= hdr->depth; if (RAS_ISRGB(hdr)) { v = RAS_RED((jas_matrix_getv(data[0], x))) | RAS_GREEN((jas_matrix_getv(data[1], x))) | RAS_BLUE((jas_matrix_getv(data[2], x))); } else { v = (jas_matrix_getv(data[0], x)); } z |= v & RAS_ONES(hdr->depth); nz += hdr->depth; while (nz >= 8) { c = (z >> (nz - 8)) & 0xff; if (jas_stream_putc(out, c) == EOF) { goto error; } nz -= 8; z &= RAS_ONES(nz); } } if (nz > 0) { c = (z >> (8 - nz)) & RAS_ONES(nz); if (jas_stream_putc(out, c) == EOF) { goto error; } } if (pad % 2) { if (jas_stream_putc(out, 0) == EOF) { goto error; } } } for (i = 0; i < numcmpts; ++i) { jas_matrix_destroy(data[i]); data[i] = 0; } return 0; error: for (i = 0; i < numcmpts; ++i) { if (data[i]) { jas_matrix_destroy(data[i]); } } return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'ras_enc: check components for RGB, fixes NULL pointer dereference Fixes CVE-2018-18873 Closes https://github.com/jasper-maint/jasper/issues/15 Closes https://github.com/mdadams/jasper/issues/184'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Perl_my_setenv(pTHX_ const char *nam, const char *val) { dVAR; #ifdef __amigaos4__ amigaos4_obtain_environ(__FUNCTION__); #endif #ifdef USE_ITHREADS /* only parent thread can modify process environment */ if (PL_curinterp == aTHX) #endif { #ifndef PERL_USE_SAFE_PUTENV if (!PL_use_safe_putenv) { /* most putenv()s leak, so we manipulate environ directly */ I32 i; const I32 len = strlen(nam); int nlen, vlen; /* where does it go? */ for (i = 0; environ[i]; i++) { if (strnEQ(environ[i],nam,len) && environ[i][len] == '=') break; } if (environ == PL_origenviron) { /* need we copy environment? */ I32 j; I32 max; char **tmpenv; max = i; while (environ[max]) max++; tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*)); for (j=0; j<max; j++) { /* copy environment */ const int len = strlen(environ[j]); tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char)); Copy(environ[j], tmpenv[j], len+1, char); } tmpenv[max] = NULL; environ = tmpenv; /* tell exec where it is now */ } if (!val) { safesysfree(environ[i]); while (environ[i]) { environ[i] = environ[i+1]; i++; } #ifdef __amigaos4__ goto my_setenv_out; #else return; #endif } if (!environ[i]) { /* does not exist yet */ environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*)); environ[i+1] = NULL; /* make sure it's null terminated */ } else safesysfree(environ[i]); nlen = strlen(nam); vlen = strlen(val); environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char)); /* all that work just for this */ my_setenv_format(environ[i], nam, nlen, val, vlen); } else { # endif /* This next branch should only be called #if defined(HAS_SETENV), but Configure doesn't test for that yet. For Solaris, setenv() and unsetenv() were introduced in Solaris 9, so testing for HAS UNSETENV is sufficient. */ # if defined(__CYGWIN__)|| defined(__SYMBIAN32__) || defined(__riscos__) || (defined(__sun) && defined(HAS_UNSETENV)) || defined(PERL_DARWIN) # if defined(HAS_UNSETENV) if (val == NULL) { (void)unsetenv(nam); } else { (void)setenv(nam, val, 1); } # else /* ! HAS_UNSETENV */ (void)setenv(nam, val, 1); # endif /* HAS_UNSETENV */ # elif defined(HAS_UNSETENV) if (val == NULL) { if (environ) /* old glibc can crash with null environ */ (void)unsetenv(nam); } else { const int nlen = strlen(nam); const int vlen = strlen(val); char * const new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char)); my_setenv_format(new_env, nam, nlen, val, vlen); (void)putenv(new_env); } # else /* ! HAS_UNSETENV */ char *new_env; const int nlen = strlen(nam); int vlen; if (!val) { val = ""; } vlen = strlen(val); new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char)); /* all that work just for this */ my_setenv_format(new_env, nam, nlen, val, vlen); (void)putenv(new_env); # endif /* __CYGWIN__ */ #ifndef PERL_USE_SAFE_PUTENV } #endif } #ifdef __amigaos4__ my_setenv_out: amigaos4_release_environ(__FUNCTION__); #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-703', 'CWE-787'], 'message': 'Perl_my_setenv(); handle integer wrap RT #133204 Wean this function off int/I32 and onto UV/Size_t. Also, replace all malloc-ish calls with a wrapper that does overflow checks, In particular, it was doing (nlen + vlen + 2) which could wrap when the combined length of the environment variable name and value exceeded around 0x7fffffff. The wrapper check function is probably overkill, but belt and braces... NB this function has several variant parts, #ifdef'ed by platform type; I have blindly changed the parts that aren't compiled under linux.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: amstar_estimate( application_argument_t *argument) { GPtrArray *argv_ptr; char *cmd = NULL; int nullfd; int pipefd; FILE *dumpout = NULL; off_t size = -1; char line[32768]; char *errmsg = NULL; char *qerrmsg; char *qdisk = NULL; amwait_t wait_status; int starpid; amregex_t *rp; times_t start_time; int level = 0; GSList *levels = NULL; 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->dle.include_list && argument->dle.include_list->nb_element >= 0) { fprintf(stderr, "ERROR include-list not supported for backup\n"); } if (check_device(argument) == 0) { return; } if (argument->calcsize) { char *dirname; 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 (star_directory) { dirname = star_directory; } else { dirname = argument->dle.device; } run_calcsize(argument->config, "STAR", argument->dle.disk, dirname, argument->level, NULL, NULL); return; } qdisk = quote_string(argument->dle.disk); if (!star_path) { errmsg = g_strdup(_("STAR-PATH not defined")); goto common_error; } if (!check_exec_for_suid(star_path, FALSE)) { errmsg = g_strdup_printf("'%s' binary is not secure", star_path); goto common_error; } cmd = g_strdup(star_path); start_time = curclock(); qdisk = quote_string(argument->dle.disk); for (levels = argument->level; levels != NULL; levels = levels->next) { level = GPOINTER_TO_INT(levels->data); argv_ptr = amstar_build_argv(argument, level, CMD_ESTIMATE, NULL); if ((nullfd = open("/dev/null", O_RDWR)) == -1) { errmsg = g_strdup_printf(_("Cannot access /dev/null : %s"), strerror(errno)); goto common_error; } starpid = pipespawnv(cmd, STDERR_PIPE, 1, &nullfd, &nullfd, &pipefd, (char **)argv_ptr->pdata); dumpout = fdopen(pipefd,"r"); if (!dumpout) { errmsg = g_strdup_printf(_("Can't fdopen: %s"), strerror(errno)); aclose(nullfd); goto common_error; } 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; dbprintf("%s\n", line); /* check for size match */ /*@ignore@*/ for(rp = re_table; rp->regex != NULL; rp++) { if(match(rp->regex, line)) { if (rp->typ == DMP_SIZE) { size = ((the_num(line, rp->field)*rp->scale+1023.0)/1024.0); if(size < 0.0) size = 1.0; /* found on NeXT -- sigh */ } break; } } /*@end@*/ } while ((fgets(line, sizeof(line), dumpout)) != NULL) { dbprintf("%s", line); } dbprintf(".....\n"); dbprintf(_("estimate time for %s level %d: %s\n"), 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); dbprintf(_("%s for %s\n"), errmsg, qdisk); dbprintf(".....\n"); qerrmsg = quote_string(errmsg); fprintf(stdout, "ERROR %s\n", qerrmsg); amfree(errmsg); amfree(qerrmsg); } else if(size == (off_t)0 && argument->level == 0) { dbprintf(_("possible %s problem -- is \"%s\" really empty?\n"), cmd, argument->dle.disk); dbprintf(".....\n"); } dbprintf(_("estimate size for %s level %d: %lld KB\n"), qdisk, level, (long long)size); (void)kill(-starpid, SIGTERM); dbprintf(_("waiting for %s \"%s\" child\n"), cmd, qdisk); waitpid(starpid, &wait_status, 0); if (WIFSIGNALED(wait_status)) { amfree(errmsg); errmsg = g_strdup_printf(_("%s terminated with signal %d: see %s"), cmd, WTERMSIG(wait_status), dbfn()); dbprintf(_("%s for %s\n"), errmsg, qdisk); dbprintf(".....\n"); qerrmsg = quote_string(errmsg); fprintf(stdout, "ERROR %s\n", qerrmsg); amfree(errmsg); amfree(qerrmsg); } else if (WIFEXITED(wait_status)) { if (WEXITSTATUS(wait_status) != 0) { amfree(errmsg); errmsg = g_strdup_printf(_("%s exited with status %d: see %s"), cmd, WEXITSTATUS(wait_status), dbfn()); dbprintf(_("%s for %s\n"), errmsg, qdisk); dbprintf(".....\n"); qerrmsg = quote_string(errmsg); fprintf(stdout, "ERROR %s\n", qerrmsg); amfree(errmsg); amfree(qerrmsg); } else { /* Normal exit */ } } else { amfree(errmsg); errmsg = g_strdup_printf(_("%s got bad exit: see %s"), cmd, dbfn()); dbprintf(_("%s for %s\n"), errmsg, qdisk); dbprintf(".....\n"); qerrmsg = quote_string(errmsg); fprintf(stdout, "ERROR %s\n", qerrmsg); amfree(errmsg); amfree(qerrmsg); } dbprintf(_("after %s %s wait\n"), cmd, qdisk); g_ptr_array_free_full(argv_ptr); aclose(nullfd); afclose(dumpout); fprintf(stdout, "%d %lld 1\n", level, (long long)size); } amfree(qdisk); amfree(cmd); return; common_error: dbprintf("%s\n", errmsg); qerrmsg = quote_string(errmsg); amfree(qdisk); dbprintf("%s", errmsg); fprintf(stdout, "ERROR %s\n", qerrmsg); amfree(errmsg); amfree(qerrmsg); amfree(cmd); } ; 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: static GPtrArray *amstar_build_argv( application_argument_t *argument, int level, int command, FILE *mesgstream) { char *dirname; char *fsname; char levelstr[NUM_STR_SIZE+7]; GPtrArray *argv_ptr = g_ptr_array_new(); char *s; char *tardumpfile; GSList *copt; if (star_directory) { dirname = star_directory; } else { dirname = argument->dle.device; } fsname = vstralloc("fs-name=", dirname, NULL); for (s = fsname; *s != '\0'; s++) { if (iscntrl((int)*s)) *s = '-'; } snprintf(levelstr, SIZEOF(levelstr), "-level=%d", level); if (star_dle_tardumps) { char *sdisk = sanitise_filename(argument->dle.disk); tardumpfile = vstralloc(star_tardumps, sdisk, NULL); amfree(sdisk); } else { tardumpfile = stralloc(star_tardumps); } g_ptr_array_add(argv_ptr, stralloc(star_path)); g_ptr_array_add(argv_ptr, stralloc("-c")); g_ptr_array_add(argv_ptr, stralloc("-f")); if (command == CMD_ESTIMATE) { g_ptr_array_add(argv_ptr, stralloc("/dev/null")); } else { g_ptr_array_add(argv_ptr, stralloc("-")); } g_ptr_array_add(argv_ptr, stralloc("-C")); #if defined(__CYGWIN__) { char tmppath[PATH_MAX]; cygwin_conv_to_full_posix_path(dirname, tmppath); g_ptr_array_add(argv_ptr, stralloc(tmppath)); } #else g_ptr_array_add(argv_ptr, stralloc(dirname)); #endif g_ptr_array_add(argv_ptr, stralloc(fsname)); if (star_onefilesystem) g_ptr_array_add(argv_ptr, stralloc("-xdev")); g_ptr_array_add(argv_ptr, stralloc("-link-dirs")); g_ptr_array_add(argv_ptr, stralloc(levelstr)); g_ptr_array_add(argv_ptr, stralloc2("tardumps=", tardumpfile)); if (command == CMD_BACKUP) g_ptr_array_add(argv_ptr, stralloc("-wtardumps")); g_ptr_array_add(argv_ptr, stralloc("-xattr")); if (star_acl) g_ptr_array_add(argv_ptr, stralloc("-acl")); g_ptr_array_add(argv_ptr, stralloc("H=exustar")); g_ptr_array_add(argv_ptr, stralloc("errctl=WARN|SAMEFILE|DIFF|GROW|SHRINK|SPECIALFILE|GETXATTR|BADACL *")); if (star_sparse) g_ptr_array_add(argv_ptr, stralloc("-sparse")); g_ptr_array_add(argv_ptr, stralloc("-dodesc")); if (command == CMD_BACKUP && argument->dle.create_index) g_ptr_array_add(argv_ptr, stralloc("-v")); if (((argument->dle.include_file && argument->dle.include_file->nb_element >= 1) || (argument->dle.include_list && argument->dle.include_list->nb_element >= 1)) && ((argument->dle.exclude_file && argument->dle.exclude_file->nb_element >= 1) || (argument->dle.exclude_list && argument->dle.exclude_list->nb_element >= 1))) { if (mesgstream && command == CMD_BACKUP) { fprintf(mesgstream, "? include and exclude specified, disabling exclude\n"); } free_sl(argument->dle.exclude_file); argument->dle.exclude_file = NULL; free_sl(argument->dle.exclude_list); argument->dle.exclude_list = NULL; } if ((argument->dle.exclude_file && argument->dle.exclude_file->nb_element >= 1) || (argument->dle.exclude_list && argument->dle.exclude_list->nb_element >= 1)) { g_ptr_array_add(argv_ptr, stralloc("-match-tree")); g_ptr_array_add(argv_ptr, stralloc("-not")); } if (argument->dle.exclude_file && argument->dle.exclude_file->nb_element >= 1) { sle_t *excl; for (excl = argument->dle.exclude_file->first; excl != NULL; excl = excl->next) { char *ex; if (strcmp(excl->name, "./") == 0) { ex = g_strdup_printf("pat=%s", excl->name+2); } else { ex = g_strdup_printf("pat=%s", excl->name); } g_ptr_array_add(argv_ptr, ex); } } if (argument->dle.exclude_list && argument->dle.exclude_list->nb_element >= 1) { sle_t *excl; for (excl = argument->dle.exclude_list->first; excl != NULL; excl = excl->next) { char *exclname = fixup_relative(excl->name, argument->dle.device); FILE *exclude; char *aexc; if ((exclude = fopen(exclname, "r")) != NULL) { while ((aexc = agets(exclude)) != NULL) { if (aexc[0] != '\0') { char *ex; if (strcmp(aexc, "./") == 0) { ex = g_strdup_printf("pat=%s", aexc+2); } else { ex = g_strdup_printf("pat=%s", aexc); } g_ptr_array_add(argv_ptr, ex); } amfree(aexc); } fclose(exclude); } amfree(exclname); } } if (argument->dle.include_file && argument->dle.include_file->nb_element >= 1) { sle_t *excl; for (excl = argument->dle.include_file->first; excl != NULL; excl = excl->next) { char *ex; if (g_str_equal(excl->name, "./")) { ex = g_strdup_printf("pat=%s", excl->name+2); } else { ex = g_strdup_printf("pat=%s", excl->name); } g_ptr_array_add(argv_ptr, ex); } } if (argument->dle.include_list && argument->dle.include_list->nb_element >= 1) { sle_t *excl; for (excl = argument->dle.include_list->first; excl != NULL; excl = excl->next) { char *exclname = fixup_relative(excl->name, argument->dle.device); FILE *include; char *aexc; if ((include = fopen(exclname, "r")) != NULL) { while ((aexc = agets(include)) != NULL) { if (aexc[0] != '\0') { char *ex; if (g_str_equal(aexc, "./")) { ex = g_strdup_printf("pat=%s", aexc+2); } else { ex = g_strdup_printf("pat=%s", aexc); } g_ptr_array_add(argv_ptr, ex); } amfree(aexc); } fclose(include); } amfree(exclname); } } /* It is best to place command_options at the and of command line. * For example '-find' option requires that it is the last option used. * See: http://cdrecord.berlios.de/private/man/star/star.1.html */ for (copt = argument->command_options; copt != NULL; copt = copt->next) { g_ptr_array_add(argv_ptr, stralloc((char *)copt->data)); } g_ptr_array_add(argv_ptr, stralloc(".")); g_ptr_array_add(argv_ptr, NULL); amfree(tardumpfile); amfree(fsname); return(argv_ptr); } ; 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: amgtar_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; amwait_t wait_status; int tarpid; amregex_t *rp; times_t start_time; int level; GSList *levels; char *file_exclude; char *file_include; char *option; 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")); } qdisk = quote_string(argument->dle.disk); if ((option = validate_command_options(argument))) { fprintf(stderr, "ERROR Invalid '%s' COMMAND-OPTIONS\n", option); error("Invalid '%s' COMMAND-OPTIONS", option); } 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); g_free(calcsize); goto common_error; } g_free(calcsize); if (gnutar_directory) { dirname = gnutar_directory; } else { dirname = argument->dle.device; } amgtar_build_exinclude(&argument->dle, 1, &nb_exclude, &file_exclude, &nb_include, &file_include); run_calcsize(argument->config, "GNUTAR", 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); } return; } if (!gnutar_path) { errmsg = vstrallocf(_("GNUTAR-PATH not defined")); goto common_error; } if (!check_exec_for_suid(gnutar_path, FALSE)) { errmsg = g_strdup_printf("'%s' binary is not secure", gnutar_path); goto common_error; } if (!gnutar_listdir) { errmsg = vstrallocf(_("GNUTAR-LISTDIR not defined")); goto common_error; } for (levels = argument->level; levels != NULL; levels = levels->next) { level = GPOINTER_TO_INT(levels->data); incrname = amgtar_get_incrname(argument, level, stdout, CMD_ESTIMATE); cmd = stralloc(gnutar_path); argv_ptr = amgtar_build_argv(argument, incrname, &file_exclude, &file_include, CMD_ESTIMATE); start_time = curclock(); if ((nullfd = open("/dev/null", O_RDWR)) == -1) { errmsg = vstrallocf(_("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 (line[strlen(line)-1] == '\n') /* remove trailling \n */ line[strlen(line)-1] = '\0'; if (line[0] == '\0') continue; dbprintf("%s\n", line); /* check for size match */ /*@ignore@*/ for(rp = re_table; rp->regex != NULL; rp++) { if(match(rp->regex, line)) { if (rp->typ == DMP_SIZE) { size = ((the_num(line, rp->field)*rp->scale+1023.0)/1024.0); if(size < 0.0) size = 1.0; /* found on NeXT -- sigh */ } break; } } /*@end@*/ } while (fgets(line, sizeof(line), dumpout) != NULL) { dbprintf("%s", line); } dbprintf(".....\n"); dbprintf(_("estimate time for %s level %d: %s\n"), qdisk, level, walltime_str(timessub(curclock(), start_time))); if(size == (off_t)-1) { errmsg = vstrallocf(_("no size line match in %s output"), cmd); dbprintf(_("%s for %s\n"), errmsg, qdisk); dbprintf(".....\n"); } else if(size == (off_t)0 && argument->level == 0) { dbprintf(_("possible %s problem -- is \"%s\" really empty?\n"), cmd, argument->dle.disk); dbprintf(".....\n"); } dbprintf(_("estimate size for %s level %d: %lld KB\n"), qdisk, level, (long long)size); kill(-tarpid, SIGTERM); dbprintf(_("waiting for %s \"%s\" child\n"), cmd, qdisk); waitpid(tarpid, &wait_status, 0); if (WIFSIGNALED(wait_status)) { errmsg = vstrallocf(_("%s terminated with signal %d: see %s"), cmd, WTERMSIG(wait_status), dbfn()); } else if (WIFEXITED(wait_status)) { if (exit_value[WEXITSTATUS(wait_status)] == 1) { errmsg = vstrallocf(_("%s exited with status %d: see %s"), cmd, WEXITSTATUS(wait_status), dbfn()); } else { /* Normal exit */ } } else { errmsg = vstrallocf(_("%s got bad exit: see %s"), cmd, dbfn()); } dbprintf(_("after %s %s wait\n"), cmd, qdisk); common_exit: if (errmsg) { dbprintf("%s", errmsg); fprintf(stdout, "ERROR %s\n", errmsg); } if (incrname) { unlink(incrname); } 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); aclose(nullfd); afclose(dumpout); fprintf(stdout, "%d %lld 1\n", level, (long long)size); } amfree(qdisk); return; common_error: qerrmsg = quote_string(errmsg); amfree(qdisk); dbprintf("%s", errmsg); fprintf(stdout, "ERROR %s\n", qerrmsg); amfree(errmsg); amfree(qerrmsg); return; } ; 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: _poppler_attachment_new (FileSpec *emb_file) { PopplerAttachment *attachment; PopplerAttachmentPrivate *priv; EmbFile *embFile; g_assert (emb_file != nullptr); attachment = (PopplerAttachment *) g_object_new (POPPLER_TYPE_ATTACHMENT, nullptr); priv = POPPLER_ATTACHMENT_GET_PRIVATE (attachment); if (emb_file->getFileName ()) attachment->name = _poppler_goo_string_to_utf8 (emb_file->getFileName ()); if (emb_file->getDescription ()) attachment->description = _poppler_goo_string_to_utf8 (emb_file->getDescription ()); embFile = emb_file->getEmbeddedFile(); attachment->size = embFile->size (); if (embFile->createDate ()) _poppler_convert_pdf_date_to_gtime (embFile->createDate (), (time_t *)&attachment->ctime); if (embFile->modDate ()) _poppler_convert_pdf_date_to_gtime (embFile->modDate (), (time_t *)&attachment->mtime); if (embFile->checksum () && embFile->checksum ()->getLength () > 0) attachment->checksum = g_string_new_len (embFile->checksum ()->getCString (), embFile->checksum ()->getLength ()); priv->obj_stream = embFile->streamObject()->copy(); return attachment; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fix crash on missing embedded file Check whether an embedded file is actually present in the PDF and show warning in that case. https://bugs.freedesktop.org/show_bug.cgi?id=106137 https://gitlab.freedesktop.org/poppler/poppler/issues/236'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: write_stacktrace(const char *file_name, const char *str) { int fd; void *buffer[100]; int nptrs; int i; char **strs; nptrs = backtrace(buffer, 100); if (file_name) { fd = open(file_name, O_WRONLY | O_APPEND | O_CREAT, 0644); if (str) dprintf(fd, "%s\n", str); backtrace_symbols_fd(buffer, nptrs, fd); if (write(fd, "\n", 1) != 1) { /* We don't care, but this stops a warning on Ubuntu */ } close(fd); } else { if (str) log_message(LOG_INFO, "%s", str); strs = backtrace_symbols(buffer, nptrs); if (strs == NULL) { log_message(LOG_INFO, "Unable to get stack backtrace"); return; } /* We don't need the call to this function, or the first two entries on the stack */ for (i = 1; i < nptrs - 2; i++) log_message(LOG_INFO, " %s", strs[i]); free(strs); } } ; 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: keepalived_main(int argc, char **argv) { bool report_stopped = true; struct utsname uname_buf; char *end; /* 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 /* 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(); goto end; } global_data = alloc_global_data(); 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); } /* Set file creation mask */ umask(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(KEEPALIVED_EXIT_OK); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Add command line and configuration option to set umask Issue #1048 identified that files created by keepalived are created with mode 0666. This commit changes the default to 0644, and also allows the umask to be specified in the configuration or as a command line option. 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: vlog_message(const int facility, const char* format, va_list args) { #if !HAVE_VSYSLOG char buf[MAX_LOG_MSG+1]; vsnprintf(buf, sizeof(buf), format, args); #endif /* Don't write syslog if testing configuration */ if (__test_bit(CONFIG_TEST_BIT, &debug)) return; if (log_file || (__test_bit(DONT_FORK_BIT, &debug) && log_console)) { #if HAVE_VSYSLOG va_list args1; char buf[2 * MAX_LOG_MSG + 1]; va_copy(args1, args); vsnprintf(buf, sizeof(buf), format, args1); va_end(args1); #endif /* timestamp setup */ time_t t = time(NULL); struct tm tm; localtime_r(&t, &tm); char timestamp[64]; strftime(timestamp, sizeof(timestamp), "%c", &tm); if (log_console && __test_bit(DONT_FORK_BIT, &debug)) fprintf(stderr, "%s: %s\n", timestamp, buf); if (log_file) { fprintf(log_file, "%s: %s\n", timestamp, buf); if (always_flush_log_file) fflush(log_file); } } if (!__test_bit(NO_SYSLOG_BIT, &debug)) #if HAVE_VSYSLOG vsyslog(facility, format, args); #else syslog(facility, "%s", buf); #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: stop_bfd(int status) { struct rusage usage; if (__test_bit(CONFIG_TEST_BIT, &debug)) return; /* Stop daemon */ pidfile_rm(bfd_pidfile); /* Clean data */ free_global_data(global_data); bfd_dispatcher_release(bfd_data); free_bfd_data(bfd_data); free_bfd_buffer(); thread_destroy_master(master); free_parent_mallocs_exit(); /* * Reached when terminate signal catched. * finally return to parent process. */ if (__test_bit(LOG_DETAIL_BIT, &debug)) { getrusage(RUSAGE_SELF, &usage); log_message(LOG_INFO, "Stopped - used %ld.%6.6ld user time, %ld.%6.6ld system time", usage.ru_utime.tv_sec, usage.ru_utime.tv_usec, usage.ru_stime.tv_sec, usage.ru_stime.tv_usec); } else log_message(LOG_INFO, "Stopped"); if (log_file_name) close_log_file(); closelog(); #ifndef _MEM_CHECK_LOG_ FREE_PTR(bfd_syslog_ident); #else if (bfd_syslog_ident) free(bfd_syslog_ident); #endif close_std_fd(); exit(status); } ; 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>