text
stringlengths
478
483k
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int snd_timer_user_open(struct inode *inode, struct file *file) { struct snd_timer_user *tu; int err; err = nonseekable_open(inode, file); if (err < 0) return err; tu = kzalloc(sizeof(*tu), GFP_KERNEL); if (tu == NULL) return -ENOMEM; spin_lock_init(&tu->qlock); init_waitqueue_head(&tu->qchange_sleep); mutex_init(&tu->tread_sem); tu->ticks = 1; tu->queue_size = 128; tu->queue = kmalloc(tu->queue_size * sizeof(struct snd_timer_read), GFP_KERNEL); if (tu->queue == NULL) { kfree(tu); return -ENOMEM; } file->private_data = tu; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'ALSA: timer: Fix race among timer ioctls ALSA timer ioctls have an open race and this may lead to a use-after-free of timer instance object. A simplistic fix is to make each ioctl exclusive. We have already tread_sem for controlling the tread, and extend this as a global mutex to be applied to each ioctl. The downside is, of course, the worse concurrency. But these ioctls aren't to be parallel accessible, in anyway, so it should be fine to serialize there. Reported-by: Dmitry Vyukov <[email protected]> Tested-by: Dmitry Vyukov <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static long snd_timer_user_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct snd_timer_user *tu; void __user *argp = (void __user *)arg; int __user *p = argp; tu = file->private_data; switch (cmd) { case SNDRV_TIMER_IOCTL_PVERSION: return put_user(SNDRV_TIMER_VERSION, p) ? -EFAULT : 0; case SNDRV_TIMER_IOCTL_NEXT_DEVICE: return snd_timer_user_next_device(argp); case SNDRV_TIMER_IOCTL_TREAD: { int xarg; mutex_lock(&tu->tread_sem); if (tu->timeri) { /* too late */ mutex_unlock(&tu->tread_sem); return -EBUSY; } if (get_user(xarg, p)) { mutex_unlock(&tu->tread_sem); return -EFAULT; } tu->tread = xarg ? 1 : 0; mutex_unlock(&tu->tread_sem); return 0; } case SNDRV_TIMER_IOCTL_GINFO: return snd_timer_user_ginfo(file, argp); case SNDRV_TIMER_IOCTL_GPARAMS: return snd_timer_user_gparams(file, argp); case SNDRV_TIMER_IOCTL_GSTATUS: return snd_timer_user_gstatus(file, argp); case SNDRV_TIMER_IOCTL_SELECT: return snd_timer_user_tselect(file, argp); case SNDRV_TIMER_IOCTL_INFO: return snd_timer_user_info(file, argp); case SNDRV_TIMER_IOCTL_PARAMS: return snd_timer_user_params(file, argp); case SNDRV_TIMER_IOCTL_STATUS: return snd_timer_user_status(file, argp); case SNDRV_TIMER_IOCTL_START: case SNDRV_TIMER_IOCTL_START_OLD: return snd_timer_user_start(file); case SNDRV_TIMER_IOCTL_STOP: case SNDRV_TIMER_IOCTL_STOP_OLD: return snd_timer_user_stop(file); case SNDRV_TIMER_IOCTL_CONTINUE: case SNDRV_TIMER_IOCTL_CONTINUE_OLD: return snd_timer_user_continue(file); case SNDRV_TIMER_IOCTL_PAUSE: case SNDRV_TIMER_IOCTL_PAUSE_OLD: return snd_timer_user_pause(file); } return -ENOTTY; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'ALSA: timer: Fix race among timer ioctls ALSA timer ioctls have an open race and this may lead to a use-after-free of timer instance object. A simplistic fix is to make each ioctl exclusive. We have already tread_sem for controlling the tread, and extend this as a global mutex to be applied to each ioctl. The downside is, of course, the worse concurrency. But these ioctls aren't to be parallel accessible, in anyway, so it should be fine to serialize there. Reported-by: Dmitry Vyukov <[email protected]> Tested-by: Dmitry Vyukov <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int snd_timer_close(struct snd_timer_instance *timeri) { struct snd_timer *timer = NULL; struct snd_timer_instance *slave, *tmp; if (snd_BUG_ON(!timeri)) return -ENXIO; /* force to stop the timer */ snd_timer_stop(timeri); if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE) { /* wait, until the active callback is finished */ spin_lock_irq(&slave_active_lock); while (timeri->flags & SNDRV_TIMER_IFLG_CALLBACK) { spin_unlock_irq(&slave_active_lock); udelay(10); spin_lock_irq(&slave_active_lock); } spin_unlock_irq(&slave_active_lock); mutex_lock(&register_mutex); list_del(&timeri->open_list); mutex_unlock(&register_mutex); } else { timer = timeri->timer; if (snd_BUG_ON(!timer)) goto out; /* wait, until the active callback is finished */ spin_lock_irq(&timer->lock); while (timeri->flags & SNDRV_TIMER_IFLG_CALLBACK) { spin_unlock_irq(&timer->lock); udelay(10); spin_lock_irq(&timer->lock); } spin_unlock_irq(&timer->lock); mutex_lock(&register_mutex); list_del(&timeri->open_list); if (timer && list_empty(&timer->open_list_head) && timer->hw.close) timer->hw.close(timer); /* remove slave links */ list_for_each_entry_safe(slave, tmp, &timeri->slave_list_head, open_list) { spin_lock_irq(&slave_active_lock); _snd_timer_stop(slave, 1, SNDRV_TIMER_EVENT_RESOLUTION); list_move_tail(&slave->open_list, &snd_timer_slave_list); slave->master = NULL; slave->timer = NULL; spin_unlock_irq(&slave_active_lock); } mutex_unlock(&register_mutex); } out: if (timeri->private_free) timeri->private_free(timeri); kfree(timeri->owner); kfree(timeri); if (timer) module_put(timer->module); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-200', 'CWE-362'], 'message': 'ALSA: timer: Harden slave timer list handling A slave timer instance might be still accessible in a racy way while operating the master instance as it lacks of locking. Since the master operation is mostly protected with timer->lock, we should cope with it while changing the slave instance, too. Also, some linked lists (active_list and ack_list) of slave instances aren't unlinked immediately at stopping or closing, and this may lead to unexpected accesses. This patch tries to address these issues. It adds spin lock of timer->lock (either from master or slave, which is equivalent) in a few places. For avoiding a deadlock, we ensure that the global slave_active_lock is always locked at first before each timer lock. Also, ack and active_list of slave instances are properly unlinked at snd_timer_stop() and snd_timer_close(). Last but not least, remove the superfluous call of _snd_timer_stop() at removing slave links. This is a noop, and calling it may confuse readers wrt locking. Further cleanup will follow in a later patch. Actually we've got reports of use-after-free by syzkaller fuzzer, and this hopefully fixes these issues. Reported-by: Dmitry Vyukov <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void snd_timer_check_master(struct snd_timer_instance *master) { struct snd_timer_instance *slave, *tmp; /* check all pending slaves */ list_for_each_entry_safe(slave, tmp, &snd_timer_slave_list, open_list) { if (slave->slave_class == master->slave_class && slave->slave_id == master->slave_id) { list_move_tail(&slave->open_list, &master->slave_list_head); spin_lock_irq(&slave_active_lock); slave->master = master; slave->timer = master->timer; if (slave->flags & SNDRV_TIMER_IFLG_RUNNING) list_add_tail(&slave->active_list, &master->slave_active_head); spin_unlock_irq(&slave_active_lock); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-200', 'CWE-362'], 'message': 'ALSA: timer: Harden slave timer list handling A slave timer instance might be still accessible in a racy way while operating the master instance as it lacks of locking. Since the master operation is mostly protected with timer->lock, we should cope with it while changing the slave instance, too. Also, some linked lists (active_list and ack_list) of slave instances aren't unlinked immediately at stopping or closing, and this may lead to unexpected accesses. This patch tries to address these issues. It adds spin lock of timer->lock (either from master or slave, which is equivalent) in a few places. For avoiding a deadlock, we ensure that the global slave_active_lock is always locked at first before each timer lock. Also, ack and active_list of slave instances are properly unlinked at snd_timer_stop() and snd_timer_close(). Last but not least, remove the superfluous call of _snd_timer_stop() at removing slave links. This is a noop, and calling it may confuse readers wrt locking. Further cleanup will follow in a later patch. Actually we've got reports of use-after-free by syzkaller fuzzer, and this hopefully fixes these issues. Reported-by: Dmitry Vyukov <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int snd_hrtimer_start(struct snd_timer *t) { struct snd_hrtimer *stime = t->private_data; atomic_set(&stime->running, 0); hrtimer_cancel(&stime->hrt); hrtimer_start(&stime->hrt, ns_to_ktime(t->sticks * resolution), HRTIMER_MODE_REL); atomic_set(&stime->running, 1); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'ALSA: hrtimer: Fix stall by hrtimer_cancel() hrtimer_cancel() waits for the completion from the callback, thus it must not be called inside the callback itself. This was already a problem in the past with ALSA hrtimer driver, and the early commit [fcfdebe70759: ALSA: hrtimer - Fix lock-up] tried to address it. However, the previous fix is still insufficient: it may still cause a lockup when the ALSA timer instance reprograms itself in its callback. Then it invokes the start function even in snd_timer_interrupt() that is called in hrtimer callback itself, results in a CPU stall. This is no hypothetical problem but actually triggered by syzkaller fuzzer. This patch tries to fix the issue again. Now we call hrtimer_try_to_cancel() at both start and stop functions so that it won't fall into a deadlock, yet giving some chance to cancel the queue if the functions have been called outside the callback. The proper hrtimer_cancel() is called in anyway at closing, so this should be enough. Reported-and-tested-by: Dmitry Vyukov <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void hub_activate(struct usb_hub *hub, enum hub_activation_type type) { struct usb_device *hdev = hub->hdev; struct usb_hcd *hcd; int ret; int port1; int status; bool need_debounce_delay = false; unsigned delay; /* Continue a partial initialization */ if (type == HUB_INIT2) goto init2; if (type == HUB_INIT3) goto init3; /* The superspeed hub except for root hub has to use Hub Depth * value as an offset into the route string to locate the bits * it uses to determine the downstream port number. So hub driver * should send a set hub depth request to superspeed hub after * the superspeed hub is set configuration in initialization or * reset procedure. * * After a resume, port power should still be on. * For any other type of activation, turn it on. */ if (type != HUB_RESUME) { if (hdev->parent && hub_is_superspeed(hdev)) { ret = usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0), HUB_SET_DEPTH, USB_RT_HUB, hdev->level - 1, 0, NULL, 0, USB_CTRL_SET_TIMEOUT); if (ret < 0) dev_err(hub->intfdev, "set hub depth failed\n"); } /* Speed up system boot by using a delayed_work for the * hub's initial power-up delays. This is pretty awkward * and the implementation looks like a home-brewed sort of * setjmp/longjmp, but it saves at least 100 ms for each * root hub (assuming usbcore is compiled into the kernel * rather than as a module). It adds up. * * This can't be done for HUB_RESUME or HUB_RESET_RESUME * because for those activation types the ports have to be * operational when we return. In theory this could be done * for HUB_POST_RESET, but it's easier not to. */ if (type == HUB_INIT) { delay = hub_power_on_good_delay(hub); hub_power_on(hub, false); INIT_DELAYED_WORK(&hub->init_work, hub_init_func2); queue_delayed_work(system_power_efficient_wq, &hub->init_work, msecs_to_jiffies(delay)); /* Suppress autosuspend until init is done */ usb_autopm_get_interface_no_resume( to_usb_interface(hub->intfdev)); return; /* Continues at init2: below */ } else if (type == HUB_RESET_RESUME) { /* The internal host controller state for the hub device * may be gone after a host power loss on system resume. * Update the device's info so the HW knows it's a hub. */ hcd = bus_to_hcd(hdev->bus); if (hcd->driver->update_hub_device) { ret = hcd->driver->update_hub_device(hcd, hdev, &hub->tt, GFP_NOIO); if (ret < 0) { dev_err(hub->intfdev, "Host not " "accepting hub info " "update.\n"); dev_err(hub->intfdev, "LS/FS devices " "and hubs may not work " "under this hub\n."); } } hub_power_on(hub, true); } else { hub_power_on(hub, true); } } init2: /* * Check each port and set hub->change_bits to let hub_wq know * which ports need attention. */ for (port1 = 1; port1 <= hdev->maxchild; ++port1) { struct usb_port *port_dev = hub->ports[port1 - 1]; struct usb_device *udev = port_dev->child; u16 portstatus, portchange; portstatus = portchange = 0; status = hub_port_status(hub, port1, &portstatus, &portchange); if (udev || (portstatus & USB_PORT_STAT_CONNECTION)) dev_dbg(&port_dev->dev, "status %04x change %04x\n", portstatus, portchange); /* * After anything other than HUB_RESUME (i.e., initialization * or any sort of reset), every port should be disabled. * Unconnected ports should likewise be disabled (paranoia), * and so should ports for which we have no usb_device. */ if ((portstatus & USB_PORT_STAT_ENABLE) && ( type != HUB_RESUME || !(portstatus & USB_PORT_STAT_CONNECTION) || !udev || udev->state == USB_STATE_NOTATTACHED)) { /* * USB3 protocol ports will automatically transition * to Enabled state when detect an USB3.0 device attach. * Do not disable USB3 protocol ports, just pretend * power was lost */ portstatus &= ~USB_PORT_STAT_ENABLE; if (!hub_is_superspeed(hdev)) usb_clear_port_feature(hdev, port1, USB_PORT_FEAT_ENABLE); } /* Clear status-change flags; we'll debounce later */ if (portchange & USB_PORT_STAT_C_CONNECTION) { need_debounce_delay = true; usb_clear_port_feature(hub->hdev, port1, USB_PORT_FEAT_C_CONNECTION); } if (portchange & USB_PORT_STAT_C_ENABLE) { need_debounce_delay = true; usb_clear_port_feature(hub->hdev, port1, USB_PORT_FEAT_C_ENABLE); } if (portchange & USB_PORT_STAT_C_RESET) { need_debounce_delay = true; usb_clear_port_feature(hub->hdev, port1, USB_PORT_FEAT_C_RESET); } if ((portchange & USB_PORT_STAT_C_BH_RESET) && hub_is_superspeed(hub->hdev)) { need_debounce_delay = true; usb_clear_port_feature(hub->hdev, port1, USB_PORT_FEAT_C_BH_PORT_RESET); } /* We can forget about a "removed" device when there's a * physical disconnect or the connect status changes. */ if (!(portstatus & USB_PORT_STAT_CONNECTION) || (portchange & USB_PORT_STAT_C_CONNECTION)) clear_bit(port1, hub->removed_bits); if (!udev || udev->state == USB_STATE_NOTATTACHED) { /* Tell hub_wq to disconnect the device or * check for a new connection */ if (udev || (portstatus & USB_PORT_STAT_CONNECTION) || (portstatus & USB_PORT_STAT_OVERCURRENT)) set_bit(port1, hub->change_bits); } else if (portstatus & USB_PORT_STAT_ENABLE) { bool port_resumed = (portstatus & USB_PORT_STAT_LINK_STATE) == USB_SS_PORT_LS_U0; /* The power session apparently survived the resume. * If there was an overcurrent or suspend change * (i.e., remote wakeup request), have hub_wq * take care of it. Look at the port link state * for USB 3.0 hubs, since they don't have a suspend * change bit, and they don't set the port link change * bit on device-initiated resume. */ if (portchange || (hub_is_superspeed(hub->hdev) && port_resumed)) set_bit(port1, hub->change_bits); } else if (udev->persist_enabled) { #ifdef CONFIG_PM udev->reset_resume = 1; #endif /* Don't set the change_bits when the device * was powered off. */ if (test_bit(port1, hub->power_bits)) set_bit(port1, hub->change_bits); } else { /* The power session is gone; tell hub_wq */ usb_set_device_state(udev, USB_STATE_NOTATTACHED); set_bit(port1, hub->change_bits); } } /* If no port-status-change flags were set, we don't need any * debouncing. If flags were set we can try to debounce the * ports all at once right now, instead of letting hub_wq do them * one at a time later on. * * If any port-status changes do occur during this delay, hub_wq * will see them later and handle them normally. */ if (need_debounce_delay) { delay = HUB_DEBOUNCE_STABLE; /* Don't do a long sleep inside a workqueue routine */ if (type == HUB_INIT2) { INIT_DELAYED_WORK(&hub->init_work, hub_init_func3); queue_delayed_work(system_power_efficient_wq, &hub->init_work, msecs_to_jiffies(delay)); return; /* Continues at init3: below */ } else { msleep(delay); } } init3: hub->quiescing = 0; status = usb_submit_urb(hub->urb, GFP_NOIO); if (status < 0) dev_err(hub->intfdev, "activate --> %d\n", status); if (hub->has_indicators && blinkenlights) queue_delayed_work(system_power_efficient_wq, &hub->leds, LED_CYCLE_PERIOD); /* Scan all ports that need attention */ kick_hub_wq(hub); /* Allow autosuspend if it was suppressed */ if (type <= HUB_INIT3) usb_autopm_put_interface_async(to_usb_interface(hub->intfdev)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'USB: fix invalid memory access in hub_activate() Commit 8520f38099cc ("USB: change hub initialization sleeps to delayed_work") changed the hub_activate() routine to make part of it run in a workqueue. However, the commit failed to take a reference to the usb_hub structure or to lock the hub interface while doing so. As a result, if a hub is plugged in and quickly unplugged before the work routine can run, the routine will try to access memory that has been deallocated. Or, if the hub is unplugged while the routine is running, the memory may be deallocated while it is in active use. This patch fixes the problem by taking a reference to the usb_hub at the start of hub_activate() and releasing it at the end (when the work is finished), and by locking the hub interface while the work routine is running. It also adds a check at the start of the routine to see if the hub has already been disconnected, in which nothing should be done. Signed-off-by: Alan Stern <[email protected]> Reported-by: Alexandru Cornea <[email protected]> Tested-by: Alexandru Cornea <[email protected]> Fixes: 8520f38099cc ("USB: change hub initialization sleeps to delayed_work") CC: <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int Lua::handle_script_request(struct mg_connection *conn, const struct mg_request_info *request_info, char *script_path) { char buf[64], key[64], ifname[MAX_INTERFACE_NAME_LEN]; char *_cookies, user[64] = { '\0' }, outbuf[FILENAME_MAX]; patricia_tree_t *ptree = NULL; int rc; if(!L) return(-1); luaL_openlibs(L); /* Load base libraries */ lua_register_classes(L, true); /* Load custom classes */ lua_pushlightuserdata(L, (char*)conn); lua_setglobal(L, CONST_HTTP_CONN); /* Put the GET params into the environment */ lua_newtable(L); if(request_info->query_string != NULL) { char *query_string = strdup(request_info->query_string); if(query_string) { char *where; char *tok; // ntop->getTrace()->traceEvent(TRACE_WARNING, "[HTTP] %s", query_string); tok = strtok_r(query_string, "&", &where); while(tok != NULL) { /* key=val */ char *_equal = strchr(tok, '='); if(_equal) { char *equal; int len; _equal[0] = '\0'; _equal = &_equal[1]; len = strlen(_equal); purifyHTTPParameter(tok), purifyHTTPParameter(_equal); if((equal = (char*)malloc(len+1)) != NULL) { char *decoded_buf; Utils::urlDecode(_equal, equal, len+1); if((decoded_buf = http_decode(equal)) != NULL) { FILE *fd; Utils::purifyHTTPparam(tok, true); Utils::purifyHTTPparam(decoded_buf, false); /* Now make sure that decoded_buf is not a file path */ if((decoded_buf[0] == '.') && ((fd = fopen(decoded_buf, "r")) || (fd = fopen(realpath(decoded_buf, outbuf), "r")))) { ntop->getTrace()->traceEvent(TRACE_WARNING, "Discarded '%s'='%s' as argument is a valid file path", tok, decoded_buf); decoded_buf[0] = '\0'; fclose(fd); } /* ntop->getTrace()->traceEvent(TRACE_WARNING, "'%s'='%s'", tok, decoded_buf); */ if(strcmp(tok, "csrf") == 0) { char rsp[32]; if(ntop->getRedis()->get(decoded_buf, rsp, sizeof(rsp)) == -1) { ntop->getTrace()->traceEvent(TRACE_WARNING, "Invalid CSRF parameter specified [%s]", decoded_buf); free(equal); return(send_error(conn, 500 /* Internal server error */, "Internal server error: CSRF attack?", PAGE_ERROR, tok, rsp)); } } lua_push_str_table_entry(L, tok, decoded_buf); free(decoded_buf); } free(equal); } else ntop->getTrace()->traceEvent(TRACE_WARNING, "Not enough memory"); } tok = strtok_r(NULL, "&", &where); } /* while */ free(query_string); } else ntop->getTrace()->traceEvent(TRACE_WARNING, "Not enough memory"); } lua_setglobal(L, "_GET"); /* Like in php */ /* _SERVER */ lua_newtable(L); lua_push_str_table_entry(L, "HTTP_REFERER", (char*)mg_get_header(conn, "Referer")); lua_push_str_table_entry(L, "HTTP_USER_AGENT", (char*)mg_get_header(conn, "User-Agent")); lua_push_str_table_entry(L, "SERVER_NAME", (char*)mg_get_header(conn, "Host")); lua_setglobal(L, "_SERVER"); /* Like in php */ /* Cookies */ lua_newtable(L); if((_cookies = (char*)mg_get_header(conn, "Cookie")) != NULL) { char *cookies = strdup(_cookies); char *tok, *where; // ntop->getTrace()->traceEvent(TRACE_WARNING, "=> '%s'", cookies); tok = strtok_r(cookies, "=", &where); while(tok != NULL) { char *val; while(tok[0] == ' ') tok++; if((val = strtok_r(NULL, ";", &where)) != NULL) { lua_push_str_table_entry(L, tok, val); // ntop->getTrace()->traceEvent(TRACE_WARNING, "'%s'='%s'", tok, val); } else break; tok = strtok_r(NULL, "=", &where); } free(cookies); } lua_setglobal(L, "_COOKIE"); /* Like in php */ /* Put the _SESSION params into the environment */ lua_newtable(L); mg_get_cookie(conn, "user", user, sizeof(user)); lua_push_str_table_entry(L, "user", user); mg_get_cookie(conn, "session", buf, sizeof(buf)); lua_push_str_table_entry(L, "session", buf); if(user[0] != '\0') { snprintf(key, sizeof(key), "ntopng.prefs.%s.ifname", user); if(ntop->getRedis()->get(key, ifname, sizeof(ifname)) < 0) { set_default_if_name_in_session: snprintf(ifname, sizeof(ifname), "%s", ntop->getInterfaceAtId(0)->get_name()); lua_push_str_table_entry(L, "ifname", ifname); ntop->getRedis()->set(key, ifname, 3600 /* 1h */); } else { goto set_preferred_interface; } } else { // We need to check if ntopng is running with the option --disable-login snprintf(key, sizeof(key), "ntopng.prefs.ifname"); if(ntop->getRedis()->get(key, ifname, sizeof(ifname)) < 0) { goto set_preferred_interface; } set_preferred_interface: NetworkInterfaceView *iface; if((iface = ntop->getInterfaceView(ifname)) != NULL) { /* The specified interface still exists */ lua_push_str_table_entry(L, "ifname", iface->get_name()); } else { goto set_default_if_name_in_session; } } lua_setglobal(L, "_SESSION"); /* Like in php */ if(user[0] != '\0') { char val[255]; lua_pushlightuserdata(L, user); lua_setglobal(L, "user"); snprintf(key, sizeof(key), "ntopng.user.%s.allowed_nets", user); if((ntop->getRedis()->get(key, val, sizeof(val)) != -1) && (val[0] != '\0')) { char *what, *net; // ntop->getTrace()->traceEvent(TRACE_WARNING, "%s", val); ptree = New_Patricia(128); net = strtok_r(val, ",", &what); while(net != NULL) { // ntop->getTrace()->traceEvent(TRACE_ERROR, "%s", net); ptree_add_rule(ptree, net); net = strtok_r(NULL, ",", &what); } lua_pushlightuserdata(L, ptree); lua_setglobal(L, CONST_ALLOWED_NETS); } } #ifndef NTOPNG_PRO rc = luaL_dofile(L, script_path); #else if(ntop->getPro()->has_valid_license()) rc = __ntop_lua_handlefile(L, script_path, true); else rc = luaL_dofile(L, script_path); #endif if(rc != 0) { const char *err = lua_tostring(L, -1); if(ptree) Destroy_Patricia(ptree, free_ptree_data); ntop->getTrace()->traceEvent(TRACE_WARNING, "Script failure [%s][%s]", script_path, err); return(send_error(conn, 500 /* Internal server error */, "Internal server error", PAGE_ERROR, script_path, err)); } if(ptree) Destroy_Patricia(ptree, free_ptree_data); return(CONST_LUA_OK); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-254'], 'message': 'Added security fix to avoid escalating privileges to non-privileged users Many thanks to Dolev Farhi 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: long pipe_fcntl(struct file *file, unsigned int cmd, unsigned long arg) { struct pipe_inode_info *pipe; long ret; pipe = get_pipe_info(file); if (!pipe) return -EBADF; __pipe_lock(pipe); switch (cmd) { case F_SETPIPE_SZ: { unsigned int size, nr_pages; size = round_pipe_size(arg); nr_pages = size >> PAGE_SHIFT; ret = -EINVAL; if (!nr_pages) goto out; if (!capable(CAP_SYS_RESOURCE) && size > pipe_max_size) { ret = -EPERM; goto out; } ret = pipe_set_size(pipe, nr_pages); break; } case F_GETPIPE_SZ: ret = pipe->buffers * PAGE_SIZE; break; default: ret = -EINVAL; break; } out: __pipe_unlock(pipe); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'pipe: limit the per-user amount of pages allocated in pipes On no-so-small systems, it is possible for a single process to cause an OOM condition by filling large pipes with data that are never read. A typical process filling 4000 pipes with 1 MB of data will use 4 GB of memory. On small systems it may be tricky to set the pipe max size to prevent this from happening. This patch makes it possible to enforce a per-user soft limit above which new pipes will be limited to a single page, effectively limiting them to 4 kB each, as well as a hard limit above which no new pipes may be created for this user. This has the effect of protecting the system against memory abuse without hurting other users, and still allowing pipes to work correctly though with less data at once. The limit are controlled by two new sysctls : pipe-user-pages-soft, and pipe-user-pages-hard. Both may be disabled by setting them to zero. The default soft limit allows the default number of FDs per process (1024) to create pipes of the default size (64kB), thus reaching a limit of 64MB before starting to create only smaller pipes. With 256 processes limited to 1024 FDs each, this results in 1024*64kB + (256*1024 - 1024) * 4kB = 1084 MB of memory allocated for a user. The hard limit is disabled by default to avoid breaking existing applications that make intensive use of pipes (eg: for splicing). Reported-by: [email protected] Reported-by: Tetsuo Handa <[email protected]> Mitigates: CVE-2013-4312 (Linux 2.0+) Suggested-by: Linus Torvalds <[email protected]> Signed-off-by: Willy Tarreau <[email protected]> Signed-off-by: Al Viro <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: struct pipe_inode_info *alloc_pipe_info(void) { struct pipe_inode_info *pipe; pipe = kzalloc(sizeof(struct pipe_inode_info), GFP_KERNEL); if (pipe) { pipe->bufs = kzalloc(sizeof(struct pipe_buffer) * PIPE_DEF_BUFFERS, GFP_KERNEL); if (pipe->bufs) { init_waitqueue_head(&pipe->wait); pipe->r_counter = pipe->w_counter = 1; pipe->buffers = PIPE_DEF_BUFFERS; mutex_init(&pipe->mutex); return pipe; } kfree(pipe); } return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'pipe: limit the per-user amount of pages allocated in pipes On no-so-small systems, it is possible for a single process to cause an OOM condition by filling large pipes with data that are never read. A typical process filling 4000 pipes with 1 MB of data will use 4 GB of memory. On small systems it may be tricky to set the pipe max size to prevent this from happening. This patch makes it possible to enforce a per-user soft limit above which new pipes will be limited to a single page, effectively limiting them to 4 kB each, as well as a hard limit above which no new pipes may be created for this user. This has the effect of protecting the system against memory abuse without hurting other users, and still allowing pipes to work correctly though with less data at once. The limit are controlled by two new sysctls : pipe-user-pages-soft, and pipe-user-pages-hard. Both may be disabled by setting them to zero. The default soft limit allows the default number of FDs per process (1024) to create pipes of the default size (64kB), thus reaching a limit of 64MB before starting to create only smaller pipes. With 256 processes limited to 1024 FDs each, this results in 1024*64kB + (256*1024 - 1024) * 4kB = 1084 MB of memory allocated for a user. The hard limit is disabled by default to avoid breaking existing applications that make intensive use of pipes (eg: for splicing). Reported-by: [email protected] Reported-by: Tetsuo Handa <[email protected]> Mitigates: CVE-2013-4312 (Linux 2.0+) Suggested-by: Linus Torvalds <[email protected]> Signed-off-by: Willy Tarreau <[email protected]> Signed-off-by: Al Viro <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: readconf_main(void) { int sep = 0; struct stat statbuf; uschar *s, *filename; const uschar *list = config_main_filelist; /* Loop through the possible file names */ while((filename = string_nextinlist(&list, &sep, big_buffer, big_buffer_size)) != NULL) { /* Cut out all the fancy processing unless specifically wanted */ #if defined(CONFIGURE_FILE_USE_NODE) || defined(CONFIGURE_FILE_USE_EUID) uschar *suffix = filename + Ustrlen(filename); /* Try for the node-specific file if a node name exists */ #ifdef CONFIGURE_FILE_USE_NODE struct utsname uts; if (uname(&uts) >= 0) { #ifdef CONFIGURE_FILE_USE_EUID sprintf(CS suffix, ".%ld.%.256s", (long int)original_euid, uts.nodename); config_file = Ufopen(filename, "rb"); if (config_file == NULL) #endif /* CONFIGURE_FILE_USE_EUID */ { sprintf(CS suffix, ".%.256s", uts.nodename); config_file = Ufopen(filename, "rb"); } } #endif /* CONFIGURE_FILE_USE_NODE */ /* Otherwise, try the generic name, possibly with the euid added */ #ifdef CONFIGURE_FILE_USE_EUID if (config_file == NULL) { sprintf(CS suffix, ".%ld", (long int)original_euid); config_file = Ufopen(filename, "rb"); } #endif /* CONFIGURE_FILE_USE_EUID */ /* Finally, try the unadorned name */ if (config_file == NULL) { *suffix = 0; config_file = Ufopen(filename, "rb"); } #else /* if neither defined */ /* This is the common case when the fancy processing is not included. */ config_file = Ufopen(filename, "rb"); #endif /* If the file does not exist, continue to try any others. For any other error, break out (and die). */ if (config_file != NULL || errno != ENOENT) break; } /* On success, save the name for verification; config_filename is used when logging configuration errors (it changes for .included files) whereas config_main_filename is the name shown by -bP. Failure to open a configuration file is a serious disaster. */ if (config_file != NULL) { uschar *p; config_filename = config_main_filename = string_copy(filename); p = Ustrrchr(filename, '/'); config_main_directory = p ? string_copyn(filename, p - filename) : string_copy(US"."); } else { if (filename == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "non-existent configuration file(s): " "%s", config_main_filelist); else log_write(0, LOG_MAIN|LOG_PANIC_DIE, "%s", string_open_failed(errno, "configuration file %s", filename)); } /* Check the status of the file we have opened, if we have retained root privileges and the file isn't /dev/null (which *should* be 0666). */ if (trusted_config && Ustrcmp(filename, US"/dev/null")) { if (fstat(fileno(config_file), &statbuf) != 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to stat configuration file %s", big_buffer); if ((statbuf.st_uid != root_uid /* owner not root */ #ifdef CONFIGURE_OWNER && statbuf.st_uid != config_uid /* owner not the special one */ #endif ) || /* or */ (statbuf.st_gid != root_gid /* group not root & */ #ifdef CONFIGURE_GROUP && statbuf.st_gid != config_gid /* group not the special one */ #endif && (statbuf.st_mode & 020) != 0) || /* group writeable */ /* or */ ((statbuf.st_mode & 2) != 0)) /* world writeable */ log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Exim configuration file %s has the " "wrong owner, group, or mode", big_buffer); } /* Process the main configuration settings. They all begin with a lower case letter. If we see something starting with an upper case letter, it is taken as a macro definition. */ while ((s = get_config_line()) != NULL) { if (isupper(s[0])) read_macro_assignment(s); else if (Ustrncmp(s, "domainlist", 10) == 0) read_named_list(&domainlist_anchor, &domainlist_count, MAX_NAMED_LIST, s+10, US"domain list"); else if (Ustrncmp(s, "hostlist", 8) == 0) read_named_list(&hostlist_anchor, &hostlist_count, MAX_NAMED_LIST, s+8, US"host list"); else if (Ustrncmp(s, US"addresslist", 11) == 0) read_named_list(&addresslist_anchor, &addresslist_count, MAX_NAMED_LIST, s+11, US"address list"); else if (Ustrncmp(s, US"localpartlist", 13) == 0) read_named_list(&localpartlist_anchor, &localpartlist_count, MAX_NAMED_LIST, s+13, US"local part list"); else (void) readconf_handle_option(s, optionlist_config, optionlist_config_size, NULL, US"main option \"%s\" unknown"); } /* If local_sender_retain is set, local_from_check must be unset. */ if (local_sender_retain && local_from_check) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "both local_from_check and " "local_sender_retain are set; this combination is not allowed"); /* If the timezone string is empty, set it to NULL, implying no TZ variable wanted. */ if (timezone_string != NULL && *timezone_string == 0) timezone_string = NULL; /* The max retry interval must not be greater than 24 hours. */ if (retry_interval_max > 24*60*60) retry_interval_max = 24*60*60; /* remote_max_parallel must be > 0 */ if (remote_max_parallel <= 0) remote_max_parallel = 1; /* Save the configured setting of freeze_tell, so we can re-instate it at the start of a new SMTP message. */ freeze_tell_config = freeze_tell; /* The primary host name may be required for expansion of spool_directory and log_file_path, so make sure it is set asap. It is obtained from uname(), but if that yields an unqualified value, make a FQDN by using gethostbyname to canonize it. Some people like upper case letters in their host names, so we don't force the case. */ if (primary_hostname == NULL) { const uschar *hostname; struct utsname uts; if (uname(&uts) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "uname() failed to yield host name"); hostname = US uts.nodename; if (Ustrchr(hostname, '.') == NULL) { int af = AF_INET; struct hostent *hostdata; #if HAVE_IPV6 if (!disable_ipv6 && (dns_ipv4_lookup == NULL || match_isinlist(hostname, CUSS &dns_ipv4_lookup, 0, NULL, NULL, MCL_DOMAIN, TRUE, NULL) != OK)) af = AF_INET6; #else af = AF_INET; #endif for (;;) { #if HAVE_IPV6 #if HAVE_GETIPNODEBYNAME int error_num; hostdata = getipnodebyname(CS hostname, af, 0, &error_num); #else hostdata = gethostbyname2(CS hostname, af); #endif #else hostdata = gethostbyname(CS hostname); #endif if (hostdata != NULL) { hostname = US hostdata->h_name; break; } if (af == AF_INET) break; af = AF_INET; } } primary_hostname = string_copy(hostname); } /* Set up default value for smtp_active_hostname */ smtp_active_hostname = primary_hostname; /* If spool_directory wasn't set in the build-time configuration, it must have got set above. Of course, writing to the log may not work if log_file_path is not set, but it will at least get to syslog or somewhere, with any luck. */ if (*spool_directory == 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "spool_directory undefined: cannot " "proceed"); /* Expand the spool directory name; it may, for example, contain the primary host name. Same comment about failure. */ s = expand_string(spool_directory); if (s == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to expand spool_directory " "\"%s\": %s", spool_directory, expand_string_message); spool_directory = s; /* Expand log_file_path, which must contain "%s" in any component that isn't the null string or "syslog". It is also allowed to contain one instance of %D or %M. However, it must NOT contain % followed by anything else. */ if (*log_file_path != 0) { const uschar *ss, *sss; int sep = ':'; /* Fixed for log file path */ s = expand_string(log_file_path); if (s == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to expand log_file_path " "\"%s\": %s", log_file_path, expand_string_message); ss = s; while ((sss = string_nextinlist(&ss,&sep,big_buffer,big_buffer_size)) != NULL) { uschar *t; if (sss[0] == 0 || Ustrcmp(sss, "syslog") == 0) continue; t = Ustrstr(sss, "%s"); if (t == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "log_file_path \"%s\" does not " "contain \"%%s\"", sss); *t = 'X'; t = Ustrchr(sss, '%'); if (t != NULL) { if ((t[1] != 'D' && t[1] != 'M') || Ustrchr(t+2, '%') != NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "log_file_path \"%s\" contains " "unexpected \"%%\" character", s); } } log_file_path = s; } /* Interpret syslog_facility into an integer argument for 'ident' param to openlog(). Default is LOG_MAIL set in globals.c. Allow the user to omit the leading "log_". */ if (syslog_facility_str != NULL) { int i; uschar *s = syslog_facility_str; if ((Ustrlen(syslog_facility_str) >= 4) && (strncmpic(syslog_facility_str, US"log_", 4) == 0)) s += 4; for (i = 0; i < syslog_list_size; i++) { if (strcmpic(s, syslog_list[i].name) == 0) { syslog_facility = syslog_list[i].value; break; } } if (i >= syslog_list_size) { log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "failed to interpret syslog_facility \"%s\"", syslog_facility_str); } } /* Expand pid_file_path */ if (*pid_file_path != 0) { s = expand_string(pid_file_path); if (s == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to expand pid_file_path " "\"%s\": %s", pid_file_path, expand_string_message); pid_file_path = s; } /* Set default value of process_log_path */ if (process_log_path == NULL || *process_log_path =='\0') process_log_path = string_sprintf("%s/exim-process.info", spool_directory); /* Compile the regex for matching a UUCP-style "From_" line in an incoming message. */ regex_From = regex_must_compile(uucp_from_pattern, FALSE, TRUE); /* Unpick the SMTP rate limiting options, if set */ if (smtp_ratelimit_mail != NULL) { unpick_ratelimit(smtp_ratelimit_mail, &smtp_rlm_threshold, &smtp_rlm_base, &smtp_rlm_factor, &smtp_rlm_limit); } if (smtp_ratelimit_rcpt != NULL) { unpick_ratelimit(smtp_ratelimit_rcpt, &smtp_rlr_threshold, &smtp_rlr_base, &smtp_rlr_factor, &smtp_rlr_limit); } /* The qualify domains default to the primary host name */ if (qualify_domain_sender == NULL) qualify_domain_sender = primary_hostname; if (qualify_domain_recipient == NULL) qualify_domain_recipient = qualify_domain_sender; /* Setting system_filter_user in the configuration sets the gid as well if a name is given, but a numerical value does not. */ if (system_filter_uid_set && !system_filter_gid_set) { struct passwd *pw = getpwuid(system_filter_uid); if (pw == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Failed to look up uid %ld", (long int)system_filter_uid); system_filter_gid = pw->pw_gid; system_filter_gid_set = TRUE; } /* If the errors_reply_to field is set, check that it is syntactically valid and ensure it contains a domain. */ if (errors_reply_to != NULL) { uschar *errmess; int start, end, domain; uschar *recipient = parse_extract_address(errors_reply_to, &errmess, &start, &end, &domain, FALSE); if (recipient == NULL) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "error in errors_reply_to (%s): %s", errors_reply_to, errmess); if (domain == 0) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "errors_reply_to (%s) does not contain a domain", errors_reply_to); } /* If smtp_accept_queue or smtp_accept_max_per_host is set, then smtp_accept_max must also be set. */ if (smtp_accept_max == 0 && (smtp_accept_queue > 0 || smtp_accept_max_per_host != NULL)) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "smtp_accept_max must be set if smtp_accept_queue or " "smtp_accept_max_per_host is set"); /* Set up the host number if anything is specified. It is an expanded string so that it can be computed from the host name, for example. We do this last so as to ensure that everything else is set up before the expansion. */ if (host_number_string != NULL) { long int n; uschar *end; uschar *s = expand_string(host_number_string); if (s == NULL) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to expand localhost_number \"%s\": %s", host_number_string, expand_string_message); n = Ustrtol(s, &end, 0); while (isspace(*end)) end++; if (*end != 0) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "localhost_number value is not a number: %s", s); if (n > LOCALHOST_MAX) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "localhost_number is greater than the maximum allowed value (%d)", LOCALHOST_MAX); host_number = n; } #ifdef SUPPORT_TLS /* If tls_verify_hosts is set, tls_verify_certificates must also be set */ if ((tls_verify_hosts != NULL || tls_try_verify_hosts != NULL) && tls_verify_certificates == NULL) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "tls_%sverify_hosts is set, but tls_verify_certificates is not set", (tls_verify_hosts != NULL)? "" : "try_"); /* This also checks that the library linkage is working and we can call routines in it, so call even if tls_require_ciphers is unset */ if (!tls_dropprivs_validate_require_cipher()) exit(1); /* Magic number: at time of writing, 1024 has been the long-standing value used by so many clients, and what Exim used to use always, that it makes sense to just min-clamp this max-clamp at that. */ if (tls_dh_max_bits < 1024) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "tls_dh_max_bits is too small, must be at least 1024 for interop"); /* If openssl_options is set, validate it */ if (openssl_options != NULL) { # ifdef USE_GNUTLS log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "openssl_options is set but we're using GnuTLS"); # else long dummy; if (!(tls_openssl_options_parse(openssl_options, &dummy))) log_write(0, LOG_PANIC_DIE|LOG_CONFIG, "openssl_options parse error: %s", openssl_options); # endif } if (gnutls_require_kx || gnutls_require_mac || gnutls_require_proto) log_write(0, LOG_MAIN, "WARNING: main options" " gnutls_require_kx, gnutls_require_mac and gnutls_require_protocols" " are obsolete\n"); #endif /*SUPPORT_TLS*/ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Fix CVE-2016-1531 Add keep_environment, add_environment. Change the working directory to "/" during the early startup phase. (cherry picked from commit bc3c7bb7d4aba3e563434e5627fe1f2176aa18c0) (cherry picked from commit 2b92b67bfc33efe05e6ff2ea3852731ac2273832) (cherry picked from commit 14b82c8b736c8ed24eda144f57703cb9feac6323) (cherry picked from commit 9ca92d0c6e9c6f161bd8111366c6952d3a9315e2) (cherry picked from commit 0020c6d9ecfd98ed7b2b337ed4f898fdc409784b) (cherry picked from commit e8f96966360ea8867ad6a8b5affda6c37fa4958c) (cherry picked from commit ef6fb807c1e1a665f444f644c60c77269f7c5209)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ocsp_load_response(SSL_CTX *sctx, tls_ext_ctx_cb *cbinfo, const uschar *expanded) { BIO *bio; OCSP_RESPONSE *resp; OCSP_BASICRESP *basic_response; OCSP_SINGLERESP *single_response; ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd; X509_STORE *store; unsigned long verify_flags; int status, reason, i; cbinfo->u_ocsp.server.file_expanded = string_copy(expanded); if (cbinfo->u_ocsp.server.response) { OCSP_RESPONSE_free(cbinfo->u_ocsp.server.response); cbinfo->u_ocsp.server.response = NULL; } bio = BIO_new_file(CS cbinfo->u_ocsp.server.file_expanded, "rb"); if (!bio) { DEBUG(D_tls) debug_printf("Failed to open OCSP response file \"%s\"\n", cbinfo->u_ocsp.server.file_expanded); return; } resp = d2i_OCSP_RESPONSE_bio(bio, NULL); BIO_free(bio); if (!resp) { DEBUG(D_tls) debug_printf("Error reading OCSP response.\n"); return; } status = OCSP_response_status(resp); if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL) { DEBUG(D_tls) debug_printf("OCSP response not valid: %s (%d)\n", OCSP_response_status_str(status), status); goto bad; } basic_response = OCSP_response_get1_basic(resp); if (!basic_response) { DEBUG(D_tls) debug_printf("OCSP response parse error: unable to extract basic response.\n"); goto bad; } store = SSL_CTX_get_cert_store(sctx); verify_flags = OCSP_NOVERIFY; /* check sigs, but not purpose */ /* May need to expose ability to adjust those flags? OCSP_NOSIGS OCSP_NOVERIFY OCSP_NOCHAIN OCSP_NOCHECKS OCSP_NOEXPLICIT OCSP_TRUSTOTHER OCSP_NOINTERN */ i = OCSP_basic_verify(basic_response, NULL, store, verify_flags); if (i <= 0) { DEBUG(D_tls) { ERR_error_string(ERR_get_error(), ssl_errstring); debug_printf("OCSP response verify failure: %s\n", US ssl_errstring); } goto bad; } /* Here's the simplifying assumption: there's only one response, for the one certificate we use, and nothing for anything else in a chain. If this proves false, we need to extract a cert id from our issued cert (tls_certificate) and use that for OCSP_resp_find_status() (which finds the right cert in the stack and then calls OCSP_single_get0_status()). I'm hoping to avoid reworking a bunch more of how we handle state here. */ single_response = OCSP_resp_get0(basic_response, 0); if (!single_response) { DEBUG(D_tls) debug_printf("Unable to get first response from OCSP basic response.\n"); goto bad; } status = OCSP_single_get0_status(single_response, &reason, &rev, &thisupd, &nextupd); if (status != V_OCSP_CERTSTATUS_GOOD) { DEBUG(D_tls) debug_printf("OCSP response bad cert status: %s (%d) %s (%d)\n", OCSP_cert_status_str(status), status, OCSP_crl_reason_str(reason), reason); goto bad; } if (!OCSP_check_validity(thisupd, nextupd, EXIM_OCSP_SKEW_SECONDS, EXIM_OCSP_MAX_AGE)) { DEBUG(D_tls) debug_printf("OCSP status invalid times.\n"); goto bad; } supply_response: cbinfo->u_ocsp.server.response = resp; return; bad: if (running_in_test_harness) { extern char ** environ; uschar ** p; for (p = USS environ; *p != NULL; p++) if (Ustrncmp(*p, "EXIM_TESTHARNESS_DISABLE_OCSPVALIDITYCHECK", 42) == 0) { DEBUG(D_tls) debug_printf("Supplying known bad OCSP response\n"); goto supply_response; } } return; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Fix CVE-2016-1531 Add keep_environment, add_environment. Change the working directory to "/" during the early startup phase. (cherry picked from commit bc3c7bb7d4aba3e563434e5627fe1f2176aa18c0) (cherry picked from commit 2b92b67bfc33efe05e6ff2ea3852731ac2273832) (cherry picked from commit 14b82c8b736c8ed24eda144f57703cb9feac6323) (cherry picked from commit 9ca92d0c6e9c6f161bd8111366c6952d3a9315e2) (cherry picked from commit 0020c6d9ecfd98ed7b2b337ed4f898fdc409784b) (cherry picked from commit e8f96966360ea8867ad6a8b5affda6c37fa4958c) (cherry picked from commit ef6fb807c1e1a665f444f644c60c77269f7c5209)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: cleanup_environment() { if (!keep_environment || *keep_environment == '\0') clearenv(); else if (Ustrcmp(keep_environment, "*") != 0) { uschar **p; if (environ) for (p = USS environ; *p; /* see below */) { uschar *name = string_copyn(*p, US Ustrchr(*p, '=') - *p); if (OK != match_isinlist(name, CUSS &keep_environment, 0, NULL, NULL, MCL_NOEXPAND, FALSE, NULL)) if (unsetenv(CS name) < 0) return FALSE; else /* nothing */; else p++; store_reset(name); } } if (add_environment) { uschar *p; int sep = 0; const uschar* envlist = add_environment; while ((p = string_nextinlist(&envlist, &sep, NULL, 0))) putenv(CS p); } return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Fix portability issues on *BSD and MacOS (cherry picked from commit 2478dbdfba7cf729ddee43a5a77bde8c25ccdede) (cherry picked from commit 84bbb4d8164aae21a8e5418250359637d8aabc29) (cherry picked from commit cdbe36e825ffdeb88da83148a866db0c9c2806e7) (cherry picked from commit de5ba17561e686e5a05c9cc88288c82b563987de) (cherry picked from commit 35a5627dc1afa9c40adc64d215821750d4932a52)'</s>
<s>[INST] Given the following code containing errors, provide 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 rng_egd_request_entropy(RngBackend *b, size_t size, EntropyReceiveFunc *receive_entropy, void *opaque) { RngEgd *s = RNG_EGD(b); RngRequest *req; req = g_malloc(sizeof(*req)); req->offset = 0; req->size = size; req->receive_entropy = receive_entropy; req->opaque = opaque; req->data = g_malloc(req->size); while (size > 0) { uint8_t header[2]; uint8_t len = MIN(size, 255); /* synchronous entropy request */ header[0] = 0x02; header[1] = len; qemu_chr_fe_write(s->chr, header, sizeof(header)); size -= len; } s->parent.requests = g_slist_append(s->parent.requests, req); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'rng: add request queue support to rng-random Requests are now created in the RngBackend parent class and the code path is shared by both rng-egd and rng-random. This commit fixes the rng-random implementation which processed only one request at a time and simply discarded all but the most recent one. In the guest this manifested as delayed completion of reads from virtio-rng, i.e. a read was completed only after another read was issued. By switching rng-random to use the same request queue as rng-egd, the unsafe stack-based allocation of the entropy buffer is eliminated and replaced with g_malloc. Signed-off-by: Ladi Prosek <[email protected]> Reviewed-by: Amit Shah <[email protected]> Message-Id: <[email protected]> Signed-off-by: Amit Shah <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void rng_random_request_entropy(RngBackend *b, size_t size, EntropyReceiveFunc *receive_entropy, void *opaque) { RndRandom *s = RNG_RANDOM(b); if (s->receive_func) { s->receive_func(s->opaque, NULL, 0); } s->receive_func = receive_entropy; s->opaque = opaque; s->size = size; qemu_set_fd_handler(s->fd, entropy_available, NULL, s); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'rng: add request queue support to rng-random Requests are now created in the RngBackend parent class and the code path is shared by both rng-egd and rng-random. This commit fixes the rng-random implementation which processed only one request at a time and simply discarded all but the most recent one. In the guest this manifested as delayed completion of reads from virtio-rng, i.e. a read was completed only after another read was issued. By switching rng-random to use the same request queue as rng-egd, the unsafe stack-based allocation of the entropy buffer is eliminated and replaced with g_malloc. Signed-off-by: Ladi Prosek <[email protected]> Reviewed-by: Amit Shah <[email protected]> Message-Id: <[email protected]> Signed-off-by: Amit Shah <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int phar_parse_zipfile(php_stream *fp, char *fname, int fname_len, char *alias, int alias_len, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */ { phar_zip_dir_end locator; char buf[sizeof(locator) + 65536]; long size; php_uint16 i; phar_archive_data *mydata = NULL; phar_entry_info entry = {0}; char *p = buf, *ext, *actual_alias = NULL; char *metadata = NULL; size = php_stream_tell(fp); if (size > sizeof(locator) + 65536) { /* seek to max comment length + end of central directory record */ size = sizeof(locator) + 65536; if (FAILURE == php_stream_seek(fp, -size, SEEK_END)) { php_stream_close(fp); if (error) { spprintf(error, 4096, "phar error: unable to search for end of central directory in zip-based phar \"%s\"", fname); } return FAILURE; } } else { php_stream_seek(fp, 0, SEEK_SET); } if (!php_stream_read(fp, buf, size)) { php_stream_close(fp); if (error) { spprintf(error, 4096, "phar error: unable to read in data to search for end of central directory in zip-based phar \"%s\"", fname); } return FAILURE; } while ((p=(char *) memchr(p + 1, 'P', (size_t) (size - (p + 1 - buf)))) != NULL) { if (!memcmp(p + 1, "K\5\6", 3)) { memcpy((void *)&locator, (void *) p, sizeof(locator)); if (PHAR_GET_16(locator.centraldisk) != 0 || PHAR_GET_16(locator.disknumber) != 0) { /* split archives not handled */ php_stream_close(fp); if (error) { spprintf(error, 4096, "phar error: split archives spanning multiple zips cannot be processed in zip-based phar \"%s\"", fname); } return FAILURE; } if (PHAR_GET_16(locator.counthere) != PHAR_GET_16(locator.count)) { if (error) { spprintf(error, 4096, "phar error: corrupt zip archive, conflicting file count in end of central directory record in zip-based phar \"%s\"", fname); } php_stream_close(fp); return FAILURE; } mydata = pecalloc(1, sizeof(phar_archive_data), PHAR_G(persist)); mydata->is_persistent = PHAR_G(persist); /* read in archive comment, if any */ if (PHAR_GET_16(locator.comment_len)) { metadata = p + sizeof(locator); if (PHAR_GET_16(locator.comment_len) != size - (metadata - buf)) { if (error) { spprintf(error, 4096, "phar error: corrupt zip archive, zip file comment truncated in zip-based phar \"%s\"", fname); } php_stream_close(fp); pefree(mydata, mydata->is_persistent); return FAILURE; } mydata->metadata_len = PHAR_GET_16(locator.comment_len); if (phar_parse_metadata(&metadata, &mydata->metadata, PHAR_GET_16(locator.comment_len) TSRMLS_CC) == FAILURE) { mydata->metadata_len = 0; /* if not valid serialized data, it is a regular string */ if (entry.is_persistent) { ALLOC_PERMANENT_ZVAL(mydata->metadata); } else { ALLOC_ZVAL(mydata->metadata); } INIT_ZVAL(*mydata->metadata); metadata = pestrndup(metadata, PHAR_GET_16(locator.comment_len), mydata->is_persistent); ZVAL_STRINGL(mydata->metadata, metadata, PHAR_GET_16(locator.comment_len), 0); } } else { mydata->metadata = NULL; } goto foundit; } } php_stream_close(fp); if (error) { spprintf(error, 4096, "phar error: end of central directory not found in zip-based phar \"%s\"", fname); } return FAILURE; foundit: mydata->fname = pestrndup(fname, fname_len, mydata->is_persistent); #ifdef PHP_WIN32 phar_unixify_path_separators(mydata->fname, fname_len); #endif mydata->is_zip = 1; mydata->fname_len = fname_len; ext = strrchr(mydata->fname, '/'); if (ext) { mydata->ext = memchr(ext, '.', (mydata->fname + fname_len) - ext); if (mydata->ext == ext) { mydata->ext = memchr(ext + 1, '.', (mydata->fname + fname_len) - ext - 1); } if (mydata->ext) { mydata->ext_len = (mydata->fname + fname_len) - mydata->ext; } } /* clean up on big-endian systems */ /* seek to central directory */ php_stream_seek(fp, PHAR_GET_32(locator.cdir_offset), SEEK_SET); /* read in central directory */ zend_hash_init(&mydata->manifest, PHAR_GET_16(locator.count), zend_get_hash_value, destroy_phar_manifest_entry, (zend_bool)mydata->is_persistent); zend_hash_init(&mydata->mounted_dirs, 5, zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent); zend_hash_init(&mydata->virtual_dirs, PHAR_GET_16(locator.count) * 2, zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent); entry.phar = mydata; entry.is_zip = 1; entry.fp_type = PHAR_FP; entry.is_persistent = mydata->is_persistent; #define PHAR_ZIP_FAIL_FREE(errmsg, save) \ zend_hash_destroy(&mydata->manifest); \ mydata->manifest.arBuckets = 0; \ zend_hash_destroy(&mydata->mounted_dirs); \ mydata->mounted_dirs.arBuckets = 0; \ zend_hash_destroy(&mydata->virtual_dirs); \ mydata->virtual_dirs.arBuckets = 0; \ php_stream_close(fp); \ if (mydata->metadata) { \ zval_dtor(mydata->metadata); \ } \ if (mydata->signature) { \ efree(mydata->signature); \ } \ if (error) { \ spprintf(error, 4096, "phar error: %s in zip-based phar \"%s\"", errmsg, mydata->fname); \ } \ pefree(mydata->fname, mydata->is_persistent); \ if (mydata->alias) { \ pefree(mydata->alias, mydata->is_persistent); \ } \ pefree(mydata, mydata->is_persistent); \ efree(save); \ return FAILURE; #define PHAR_ZIP_FAIL(errmsg) \ zend_hash_destroy(&mydata->manifest); \ mydata->manifest.arBuckets = 0; \ zend_hash_destroy(&mydata->mounted_dirs); \ mydata->mounted_dirs.arBuckets = 0; \ zend_hash_destroy(&mydata->virtual_dirs); \ mydata->virtual_dirs.arBuckets = 0; \ php_stream_close(fp); \ if (mydata->metadata) { \ zval_dtor(mydata->metadata); \ } \ if (mydata->signature) { \ efree(mydata->signature); \ } \ if (error) { \ spprintf(error, 4096, "phar error: %s in zip-based phar \"%s\"", errmsg, mydata->fname); \ } \ pefree(mydata->fname, mydata->is_persistent); \ if (mydata->alias) { \ pefree(mydata->alias, mydata->is_persistent); \ } \ pefree(mydata, mydata->is_persistent); \ return FAILURE; /* add each central directory item to the manifest */ for (i = 0; i < PHAR_GET_16(locator.count); ++i) { phar_zip_central_dir_file zipentry; off_t beforeus = php_stream_tell(fp); if (sizeof(zipentry) != php_stream_read(fp, (char *) &zipentry, sizeof(zipentry))) { PHAR_ZIP_FAIL("unable to read central directory entry, truncated"); } /* clean up for bigendian systems */ if (memcmp("PK\1\2", zipentry.signature, 4)) { /* corrupted entry */ PHAR_ZIP_FAIL("corrupted central directory entry, no magic signature"); } if (entry.is_persistent) { entry.manifest_pos = i; } entry.compressed_filesize = PHAR_GET_32(zipentry.compsize); entry.uncompressed_filesize = PHAR_GET_32(zipentry.uncompsize); entry.crc32 = PHAR_GET_32(zipentry.crc32); /* do not PHAR_GET_16 either on the next line */ entry.timestamp = phar_zip_d2u_time(zipentry.timestamp, zipentry.datestamp); entry.flags = PHAR_ENT_PERM_DEF_FILE; entry.header_offset = PHAR_GET_32(zipentry.offset); entry.offset = entry.offset_abs = PHAR_GET_32(zipentry.offset) + sizeof(phar_zip_file_header) + PHAR_GET_16(zipentry.filename_len) + PHAR_GET_16(zipentry.extra_len); if (PHAR_GET_16(zipentry.flags) & PHAR_ZIP_FLAG_ENCRYPTED) { PHAR_ZIP_FAIL("Cannot process encrypted zip files"); } if (!PHAR_GET_16(zipentry.filename_len)) { PHAR_ZIP_FAIL("Cannot process zips created from stdin (zero-length filename)"); } entry.filename_len = PHAR_GET_16(zipentry.filename_len); entry.filename = (char *) pemalloc(entry.filename_len + 1, entry.is_persistent); if (entry.filename_len != php_stream_read(fp, entry.filename, entry.filename_len)) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to read in filename from central directory, truncated"); } entry.filename[entry.filename_len] = '\0'; if (entry.filename[entry.filename_len - 1] == '/') { entry.is_dir = 1; if(entry.filename_len > 1) { entry.filename_len--; } entry.flags |= PHAR_ENT_PERM_DEF_DIR; } else { entry.is_dir = 0; } if (entry.filename_len == sizeof(".phar/signature.bin")-1 && !strncmp(entry.filename, ".phar/signature.bin", sizeof(".phar/signature.bin")-1)) { size_t read; php_stream *sigfile; off_t now; char *sig; now = php_stream_tell(fp); pefree(entry.filename, entry.is_persistent); sigfile = php_stream_fopen_tmpfile(); if (!sigfile) { PHAR_ZIP_FAIL("couldn't open temporary file"); } php_stream_seek(fp, 0, SEEK_SET); /* copy file contents + local headers and zip comment, if any, to be hashed for signature */ phar_stream_copy_to_stream(fp, sigfile, entry.header_offset, NULL); /* seek to central directory */ php_stream_seek(fp, PHAR_GET_32(locator.cdir_offset), SEEK_SET); /* copy central directory header */ phar_stream_copy_to_stream(fp, sigfile, beforeus - PHAR_GET_32(locator.cdir_offset), NULL); if (metadata) { php_stream_write(sigfile, metadata, PHAR_GET_16(locator.comment_len)); } php_stream_seek(fp, sizeof(phar_zip_file_header) + entry.header_offset + entry.filename_len + PHAR_GET_16(zipentry.extra_len), SEEK_SET); sig = (char *) emalloc(entry.uncompressed_filesize); read = php_stream_read(fp, sig, entry.uncompressed_filesize); if (read != entry.uncompressed_filesize) { php_stream_close(sigfile); efree(sig); PHAR_ZIP_FAIL("signature cannot be read"); } mydata->sig_flags = PHAR_GET_32(sig); if (FAILURE == phar_verify_signature(sigfile, php_stream_tell(sigfile), mydata->sig_flags, sig + 8, entry.uncompressed_filesize - 8, fname, &mydata->signature, &mydata->sig_len, error TSRMLS_CC)) { efree(sig); if (error) { char *save; php_stream_close(sigfile); spprintf(&save, 4096, "signature cannot be verified: %s", *error); efree(*error); PHAR_ZIP_FAIL_FREE(save, save); } else { php_stream_close(sigfile); PHAR_ZIP_FAIL("signature cannot be verified"); } } php_stream_close(sigfile); efree(sig); /* signature checked out, let's ensure this is the last file in the phar */ if (i != PHAR_GET_16(locator.count) - 1) { PHAR_ZIP_FAIL("entries exist after signature, invalid phar"); } continue; } phar_add_virtual_dirs(mydata, entry.filename, entry.filename_len TSRMLS_CC); if (PHAR_GET_16(zipentry.extra_len)) { off_t loc = php_stream_tell(fp); if (FAILURE == phar_zip_process_extra(fp, &entry, PHAR_GET_16(zipentry.extra_len) TSRMLS_CC)) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("Unable to process extra field header for file in central directory"); } php_stream_seek(fp, loc + PHAR_GET_16(zipentry.extra_len), SEEK_SET); } switch (PHAR_GET_16(zipentry.compressed)) { case PHAR_ZIP_COMP_NONE : /* compression flag already set */ break; case PHAR_ZIP_COMP_DEFLATE : entry.flags |= PHAR_ENT_COMPRESSED_GZ; if (!PHAR_G(has_zlib)) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("zlib extension is required"); } break; case PHAR_ZIP_COMP_BZIP2 : entry.flags |= PHAR_ENT_COMPRESSED_BZ2; if (!PHAR_G(has_bz2)) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("bzip2 extension is required"); } break; case 1 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (Shrunk) used in this zip"); case 2 : case 3 : case 4 : case 5 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (Reduce) used in this zip"); case 6 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (Implode) used in this zip"); case 7 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (Tokenize) used in this zip"); case 9 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (Deflate64) used in this zip"); case 10 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (PKWare Implode/old IBM TERSE) used in this zip"); case 14 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (LZMA) used in this zip"); case 18 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (IBM TERSE) used in this zip"); case 19 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (IBM LZ77) used in this zip"); case 97 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (WavPack) used in this zip"); case 98 : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (PPMd) used in this zip"); default : pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unsupported compression method (unknown) used in this zip"); } /* get file metadata */ if (PHAR_GET_16(zipentry.comment_len)) { if (PHAR_GET_16(zipentry.comment_len) != php_stream_read(fp, buf, PHAR_GET_16(zipentry.comment_len))) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to read in file comment, truncated"); } p = buf; entry.metadata_len = PHAR_GET_16(zipentry.comment_len); if (phar_parse_metadata(&p, &(entry.metadata), PHAR_GET_16(zipentry.comment_len) TSRMLS_CC) == FAILURE) { entry.metadata_len = 0; /* if not valid serialized data, it is a regular string */ if (entry.is_persistent) { ALLOC_PERMANENT_ZVAL(entry.metadata); } else { ALLOC_ZVAL(entry.metadata); } INIT_ZVAL(*entry.metadata); ZVAL_STRINGL(entry.metadata, pestrndup(buf, PHAR_GET_16(zipentry.comment_len), entry.is_persistent), PHAR_GET_16(zipentry.comment_len), 0); } } else { entry.metadata = NULL; } if (!actual_alias && entry.filename_len == sizeof(".phar/alias.txt")-1 && !strncmp(entry.filename, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) { php_stream_filter *filter; off_t saveloc; /* verify local file header */ phar_zip_file_header local; /* archive alias found */ saveloc = php_stream_tell(fp); php_stream_seek(fp, PHAR_GET_32(zipentry.offset), SEEK_SET); if (sizeof(local) != php_stream_read(fp, (char *) &local, sizeof(local))) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("phar error: internal corruption of zip-based phar (cannot read local file header for alias)"); } /* verify local header */ if (entry.filename_len != PHAR_GET_16(local.filename_len) || entry.crc32 != PHAR_GET_32(local.crc32) || entry.uncompressed_filesize != PHAR_GET_32(local.uncompsize) || entry.compressed_filesize != PHAR_GET_32(local.compsize)) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("phar error: internal corruption of zip-based phar (local header of alias does not match central directory)"); } /* construct actual offset to file start - local extra_len can be different from central extra_len */ entry.offset = entry.offset_abs = sizeof(local) + entry.header_offset + PHAR_GET_16(local.filename_len) + PHAR_GET_16(local.extra_len); php_stream_seek(fp, entry.offset, SEEK_SET); /* these next lines should be for php < 5.2.6 after 5.3 filters are fixed */ fp->writepos = 0; fp->readpos = 0; php_stream_seek(fp, entry.offset, SEEK_SET); fp->writepos = 0; fp->readpos = 0; /* the above lines should be for php < 5.2.6 after 5.3 filters are fixed */ mydata->alias_len = entry.uncompressed_filesize; if (entry.flags & PHAR_ENT_COMPRESSED_GZ) { filter = php_stream_filter_create("zlib.inflate", NULL, php_stream_is_persistent(fp) TSRMLS_CC); if (!filter) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to decompress alias, zlib filter creation failed"); } php_stream_filter_append(&fp->readfilters, filter); if (!(entry.uncompressed_filesize = php_stream_copy_to_mem(fp, &actual_alias, entry.uncompressed_filesize, 0)) || !actual_alias) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to read in alias, truncated"); } php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); } else if (entry.flags & PHAR_ENT_COMPRESSED_BZ2) { filter = php_stream_filter_create("bzip2.decompress", NULL, php_stream_is_persistent(fp) TSRMLS_CC); if (!filter) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to read in alias, bzip2 filter creation failed"); } php_stream_filter_append(&fp->readfilters, filter); if (!(entry.uncompressed_filesize = php_stream_copy_to_mem(fp, &actual_alias, entry.uncompressed_filesize, 0)) || !actual_alias) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to read in alias, truncated"); } php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); } else { if (!(entry.uncompressed_filesize = php_stream_copy_to_mem(fp, &actual_alias, entry.uncompressed_filesize, 0)) || !actual_alias) { pefree(entry.filename, entry.is_persistent); PHAR_ZIP_FAIL("unable to read in alias, truncated"); } } /* return to central directory parsing */ php_stream_seek(fp, saveloc, SEEK_SET); } phar_set_inode(&entry TSRMLS_CC); zend_hash_add(&mydata->manifest, entry.filename, entry.filename_len, (void *)&entry,sizeof(phar_entry_info), NULL); } mydata->fp = fp; if (zend_hash_exists(&(mydata->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1)) { mydata->is_data = 0; } else { mydata->is_data = 1; } zend_hash_add(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len, (void*)&mydata, sizeof(phar_archive_data*), NULL); if (actual_alias) { phar_archive_data **fd_ptr; if (!phar_validate_alias(actual_alias, mydata->alias_len)) { if (error) { spprintf(error, 4096, "phar error: invalid alias \"%s\" in zip-based phar \"%s\"", actual_alias, fname); } efree(actual_alias); zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len); return FAILURE; } mydata->is_temporary_alias = 0; if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), actual_alias, mydata->alias_len, (void **)&fd_ptr)) { if (SUCCESS != phar_free_alias(*fd_ptr, actual_alias, mydata->alias_len TSRMLS_CC)) { if (error) { spprintf(error, 4096, "phar error: Unable to add zip-based phar \"%s\" with implicit alias, alias is already in use", fname); } efree(actual_alias); zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len); return FAILURE; } } mydata->alias = entry.is_persistent ? pestrndup(actual_alias, mydata->alias_len, 1) : actual_alias; if (entry.is_persistent) { efree(actual_alias); } zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), actual_alias, mydata->alias_len, (void*)&mydata, sizeof(phar_archive_data*), NULL); } else { phar_archive_data **fd_ptr; if (alias_len) { if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void **)&fd_ptr)) { if (SUCCESS != phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) { if (error) { spprintf(error, 4096, "phar error: Unable to add zip-based phar \"%s\" with explicit alias, alias is already in use", fname); } zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len); return FAILURE; } } zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), actual_alias, mydata->alias_len, (void*)&mydata, sizeof(phar_archive_data*), NULL); mydata->alias = pestrndup(alias, alias_len, mydata->is_persistent); mydata->alias_len = alias_len; } else { mydata->alias = pestrndup(mydata->fname, fname_len, mydata->is_persistent); mydata->alias_len = fname_len; } mydata->is_temporary_alias = 1; } if (pphar) { *pphar = mydata; } return SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix bug #71498: Out-of-Bound Read in phar_parse_zipfile()'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: */ static void php_wddx_process_data(void *user_data, const XML_Char *s, int len) { st_entry *ent; wddx_stack *stack = (wddx_stack *)user_data; TSRMLS_FETCH(); if (!wddx_stack_is_empty(stack) && !stack->done) { wddx_stack_top(stack, (void**)&ent); switch (Z_TYPE_P(ent)) { case ST_STRING: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len); Z_STRLEN_P(ent->data) = len; } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; } break; case ST_BINARY: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len + 1); } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); } Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; break; case ST_NUMBER: Z_TYPE_P(ent->data) = IS_STRING; Z_STRLEN_P(ent->data) = len; Z_STRVAL_P(ent->data) = estrndup(s, len); convert_scalar_to_number(ent->data TSRMLS_CC); break; case ST_BOOLEAN: if (!strcmp(s, "true")) { Z_LVAL_P(ent->data) = 1; } else if (!strcmp(s, "false")) { Z_LVAL_P(ent->data) = 0; } else { stack->top--; zval_ptr_dtor(&ent->data); if (ent->varname) efree(ent->varname); efree(ent); } break; case ST_DATETIME: { char *tmp; tmp = emalloc(len + 1); memcpy(tmp, s, len); tmp[len] = '\0'; Z_LVAL_P(ent->data) = php_parse_date(tmp, NULL); /* date out of range < 1969 or > 2038 */ if (Z_LVAL_P(ent->data) == -1) { Z_TYPE_P(ent->data) = IS_STRING; Z_STRLEN_P(ent->data) = len; Z_STRVAL_P(ent->data) = estrndup(s, len); } efree(tmp); } break; default: break; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fixed bug #71587 - Use-After-Free / Double-Free in WDDX Deserialize'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_XML_API zend_string *xml_utf8_encode(const char *s, size_t len, const XML_Char *encoding) { size_t pos = len; zend_string *str; unsigned int c; unsigned short (*encoder)(unsigned char) = NULL; xml_encoding *enc = xml_get_encoding(encoding); if (enc) { encoder = enc->encoding_function; } else { /* If the target encoding was unknown, fail */ return NULL; } if (encoder == NULL) { /* If no encoder function was specified, return the data as-is. */ str = zend_string_init(s, len, 0); return str; } /* This is the theoretical max (will never get beyond len * 2 as long * as we are converting from single-byte characters, though) */ str = zend_string_alloc(len * 4, 0); ZSTR_LEN(str) = 0; while (pos > 0) { c = encoder ? encoder((unsigned char)(*s)) : (unsigned short)(*s); if (c < 0x80) { ZSTR_VAL(str)[ZSTR_LEN(str)++] = (char) c; } else if (c < 0x800) { ZSTR_VAL(str)[ZSTR_LEN(str)++] = (0xc0 | (c >> 6)); ZSTR_VAL(str)[ZSTR_LEN(str)++] = (0x80 | (c & 0x3f)); } else if (c < 0x10000) { ZSTR_VAL(str)[ZSTR_LEN(str)++] = (0xe0 | (c >> 12)); ZSTR_VAL(str)[ZSTR_LEN(str)++] = (0xc0 | ((c >> 6) & 0x3f)); ZSTR_VAL(str)[ZSTR_LEN(str)++] = (0x80 | (c & 0x3f)); } else if (c < 0x200000) { ZSTR_VAL(str)[ZSTR_LEN(str)++] = (0xf0 | (c >> 18)); ZSTR_VAL(str)[ZSTR_LEN(str)++] = (0xe0 | ((c >> 12) & 0x3f)); ZSTR_VAL(str)[ZSTR_LEN(str)++] = (0xc0 | ((c >> 6) & 0x3f)); ZSTR_VAL(str)[ZSTR_LEN(str)++] = (0x80 | (c & 0x3f)); } pos--; s++; } ZSTR_VAL(str)[ZSTR_LEN(str)] = '\0'; str = zend_string_truncate(str, ZSTR_LEN(str), 0); return str; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #71637: Multiple Heap Overflow due to integer overflows'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static NOINLINE char *xmalloc_optname_optval(uint8_t *option, const struct dhcp_optflag *optflag, const char *opt_name) { unsigned upper_length; int len, type, optlen; char *dest, *ret; /* option points to OPT_DATA, need to go back to get OPT_LEN */ len = option[-OPT_DATA + OPT_LEN]; type = optflag->flags & OPTION_TYPE_MASK; optlen = dhcp_option_lengths[type]; upper_length = len_of_option_as_string[type] * ((unsigned)(len + optlen - 1) / (unsigned)optlen); dest = ret = xmalloc(upper_length + strlen(opt_name) + 2); dest += sprintf(ret, "%s=", opt_name); while (len >= optlen) { switch (type) { case OPTION_IP: case OPTION_IP_PAIR: dest += sprint_nip(dest, "", option); if (type == OPTION_IP) break; dest += sprint_nip(dest, "/", option + 4); break; // case OPTION_BOOLEAN: // dest += sprintf(dest, *option ? "yes" : "no"); // break; case OPTION_U8: dest += sprintf(dest, "%u", *option); break; // case OPTION_S16: case OPTION_U16: { uint16_t val_u16; move_from_unaligned16(val_u16, option); dest += sprintf(dest, "%u", ntohs(val_u16)); break; } case OPTION_S32: case OPTION_U32: { uint32_t val_u32; move_from_unaligned32(val_u32, option); dest += sprintf(dest, type == OPTION_U32 ? "%lu" : "%ld", (unsigned long) ntohl(val_u32)); break; } /* Note: options which use 'return' instead of 'break' * (for example, OPTION_STRING) skip the code which handles * the case of list of options. */ case OPTION_STRING: case OPTION_STRING_HOST: memcpy(dest, option, len); dest[len] = '\0'; if (type == OPTION_STRING_HOST && !good_hostname(dest)) safe_strncpy(dest, "bad", len); return ret; case OPTION_STATIC_ROUTES: { /* Option binary format: * mask [one byte, 0..32] * ip [big endian, 0..4 bytes depending on mask] * router [big endian, 4 bytes] * may be repeated * * We convert it to a string "IP/MASK ROUTER IP2/MASK2 ROUTER2" */ const char *pfx = ""; while (len >= 1 + 4) { /* mask + 0-byte ip + router */ uint32_t nip; uint8_t *p; unsigned mask; int bytes; mask = *option++; if (mask > 32) break; len--; nip = 0; p = (void*) &nip; bytes = (mask + 7) / 8; /* 0 -> 0, 1..8 -> 1, 9..16 -> 2 etc */ while (--bytes >= 0) { *p++ = *option++; len--; } if (len < 4) break; /* print ip/mask */ dest += sprint_nip(dest, pfx, (void*) &nip); pfx = " "; dest += sprintf(dest, "/%u ", mask); /* print router */ dest += sprint_nip(dest, "", option); option += 4; len -= 4; } return ret; } case OPTION_6RD: /* Option binary format (see RFC 5969): * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | OPTION_6RD | option-length | IPv4MaskLen | 6rdPrefixLen | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | 6rdPrefix | * ... (16 octets) ... * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * ... 6rdBRIPv4Address(es) ... * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * We convert it to a string * "IPv4MaskLen 6rdPrefixLen 6rdPrefix 6rdBRIPv4Address..." * * Sanity check: ensure that our length is at least 22 bytes, that * IPv4MaskLen <= 32, * 6rdPrefixLen <= 128, * 6rdPrefixLen + (32 - IPv4MaskLen) <= 128 * (2nd condition need no check - it follows from 1st and 3rd). * Else, return envvar with empty value ("optname=") */ if (len >= (1 + 1 + 16 + 4) && option[0] <= 32 && (option[1] + 32 - option[0]) <= 128 ) { /* IPv4MaskLen */ dest += sprintf(dest, "%u ", *option++); /* 6rdPrefixLen */ dest += sprintf(dest, "%u ", *option++); /* 6rdPrefix */ dest += sprint_nip6(dest, /* "", */ option); option += 16; len -= 1 + 1 + 16 + 4; /* "+ 4" above corresponds to the length of IPv4 addr * we consume in the loop below */ while (1) { /* 6rdBRIPv4Address(es) */ dest += sprint_nip(dest, " ", option); option += 4; len -= 4; /* do we have yet another 4+ bytes? */ if (len < 0) break; /* no */ } } return ret; #if ENABLE_FEATURE_UDHCP_RFC3397 case OPTION_DNS_STRING: /* unpack option into dest; use ret for prefix (i.e., "optname=") */ dest = dname_dec(option, len, ret); if (dest) { free(ret); return dest; } /* error. return "optname=" string */ return ret; case OPTION_SIP_SERVERS: /* Option binary format: * type: byte * type=0: domain names, dns-compressed * type=1: IP addrs */ option++; len--; if (option[-1] == 0) { dest = dname_dec(option, len, ret); if (dest) { free(ret); return dest; } } else if (option[-1] == 1) { const char *pfx = ""; while (1) { len -= 4; if (len < 0) break; dest += sprint_nip(dest, pfx, option); pfx = " "; option += 4; } } return ret; #endif } /* switch */ /* If we are here, try to format any remaining data * in the option as another, similarly-formatted option */ option += optlen; len -= optlen; // TODO: it can be a list only if (optflag->flags & OPTION_LIST). // Should we bail out/warn if we see multi-ip option which is // not allowed to be such (for example, DHCP_BROADCAST)? - if (len < optlen /* || !(optflag->flags & OPTION_LIST) */) break; *dest++ = ' '; *dest = '\0'; } /* while */ return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'udhcpc: fix OPTION_6RD parsing (could overflow its malloced buffer) Signed-off-by: Denys Vlasenko <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int digi_startup(struct usb_serial *serial) { struct digi_serial *serial_priv; int ret; serial_priv = kzalloc(sizeof(*serial_priv), GFP_KERNEL); if (!serial_priv) return -ENOMEM; spin_lock_init(&serial_priv->ds_serial_lock); serial_priv->ds_oob_port_num = serial->type->num_ports; serial_priv->ds_oob_port = serial->port[serial_priv->ds_oob_port_num]; ret = digi_port_init(serial_priv->ds_oob_port, serial_priv->ds_oob_port_num); if (ret) { kfree(serial_priv); return ret; } usb_set_serial_data(serial, serial_priv); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'USB: digi_acceleport: do sanity checking for the number of ports The driver can be crashed with devices that expose crafted descriptors with too few endpoints. See: http://seclists.org/bugtraq/2016/Mar/61 Signed-off-by: Oliver Neukum <[email protected]> [johan: fix OOB endpoint check and add error messages ] Cc: stable <[email protected]> Signed-off-by: Johan Hovold <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int cypress_generic_port_probe(struct usb_serial_port *port) { struct usb_serial *serial = port->serial; struct cypress_private *priv; priv = kzalloc(sizeof(struct cypress_private), GFP_KERNEL); if (!priv) return -ENOMEM; priv->comm_is_ok = !0; spin_lock_init(&priv->lock); if (kfifo_alloc(&priv->write_fifo, CYPRESS_BUF_SIZE, GFP_KERNEL)) { kfree(priv); return -ENOMEM; } /* Skip reset for FRWD device. It is a workaound: device hangs if it receives SET_CONFIGURE in Configured state. */ if (!is_frwd(serial->dev)) usb_reset_configuration(serial->dev); priv->cmd_ctrl = 0; priv->line_control = 0; priv->termios_initialized = 0; priv->rx_flags = 0; /* Default packet format setting is determined by packet size. Anything with a size larger then 9 must have a separate count field since the 3 bit count field is otherwise too small. Otherwise we can use the slightly more compact format. This is in accordance with the cypress_m8 serial converter app note. */ if (port->interrupt_out_size > 9) priv->pkt_fmt = packet_format_1; else priv->pkt_fmt = packet_format_2; if (interval > 0) { priv->write_urb_interval = interval; priv->read_urb_interval = interval; dev_dbg(&port->dev, "%s - read & write intervals forced to %d\n", __func__, interval); } else { priv->write_urb_interval = port->interrupt_out_urb->interval; priv->read_urb_interval = port->interrupt_in_urb->interval; dev_dbg(&port->dev, "%s - intervals: read=%d write=%d\n", __func__, priv->read_urb_interval, priv->write_urb_interval); } usb_set_serial_port_data(port, priv); port->port.drain_delay = 256; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'USB: cypress_m8: add endpoint sanity check An attack using missing endpoints exists. CVE-2016-3137 Signed-off-by: Oliver Neukum <[email protected]> CC: [email protected] Signed-off-by: Johan Hovold <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int powermate_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct usb_device *udev = interface_to_usbdev (intf); struct usb_host_interface *interface; struct usb_endpoint_descriptor *endpoint; struct powermate_device *pm; struct input_dev *input_dev; int pipe, maxp; int error = -ENOMEM; interface = intf->cur_altsetting; endpoint = &interface->endpoint[0].desc; if (!usb_endpoint_is_int_in(endpoint)) return -EIO; usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x0a, USB_TYPE_CLASS | USB_RECIP_INTERFACE, 0, interface->desc.bInterfaceNumber, NULL, 0, USB_CTRL_SET_TIMEOUT); pm = kzalloc(sizeof(struct powermate_device), GFP_KERNEL); input_dev = input_allocate_device(); if (!pm || !input_dev) goto fail1; if (powermate_alloc_buffers(udev, pm)) goto fail2; pm->irq = usb_alloc_urb(0, GFP_KERNEL); if (!pm->irq) goto fail2; pm->config = usb_alloc_urb(0, GFP_KERNEL); if (!pm->config) goto fail3; pm->udev = udev; pm->intf = intf; pm->input = input_dev; usb_make_path(udev, pm->phys, sizeof(pm->phys)); strlcat(pm->phys, "/input0", sizeof(pm->phys)); spin_lock_init(&pm->lock); switch (le16_to_cpu(udev->descriptor.idProduct)) { case POWERMATE_PRODUCT_NEW: input_dev->name = pm_name_powermate; break; case POWERMATE_PRODUCT_OLD: input_dev->name = pm_name_soundknob; break; default: input_dev->name = pm_name_soundknob; printk(KERN_WARNING "powermate: unknown product id %04x\n", le16_to_cpu(udev->descriptor.idProduct)); } input_dev->phys = pm->phys; usb_to_input_id(udev, &input_dev->id); input_dev->dev.parent = &intf->dev; input_set_drvdata(input_dev, pm); input_dev->event = powermate_input_event; input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REL) | BIT_MASK(EV_MSC); input_dev->keybit[BIT_WORD(BTN_0)] = BIT_MASK(BTN_0); input_dev->relbit[BIT_WORD(REL_DIAL)] = BIT_MASK(REL_DIAL); input_dev->mscbit[BIT_WORD(MSC_PULSELED)] = BIT_MASK(MSC_PULSELED); /* get a handle to the interrupt data pipe */ pipe = usb_rcvintpipe(udev, endpoint->bEndpointAddress); maxp = usb_maxpacket(udev, pipe, usb_pipeout(pipe)); if (maxp < POWERMATE_PAYLOAD_SIZE_MIN || maxp > POWERMATE_PAYLOAD_SIZE_MAX) { printk(KERN_WARNING "powermate: Expected payload of %d--%d bytes, found %d bytes!\n", POWERMATE_PAYLOAD_SIZE_MIN, POWERMATE_PAYLOAD_SIZE_MAX, maxp); maxp = POWERMATE_PAYLOAD_SIZE_MAX; } usb_fill_int_urb(pm->irq, udev, pipe, pm->data, maxp, powermate_irq, pm, endpoint->bInterval); pm->irq->transfer_dma = pm->data_dma; pm->irq->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; /* register our interrupt URB with the USB system */ if (usb_submit_urb(pm->irq, GFP_KERNEL)) { error = -EIO; goto fail4; } error = input_register_device(pm->input); if (error) goto fail5; /* force an update of everything */ pm->requires_update = UPDATE_PULSE_ASLEEP | UPDATE_PULSE_AWAKE | UPDATE_PULSE_MODE | UPDATE_STATIC_BRIGHTNESS; powermate_pulse_led(pm, 0x80, 255, 0, 1, 0); // set default pulse parameters usb_set_intfdata(intf, pm); return 0; fail5: usb_kill_urb(pm->irq); fail4: usb_free_urb(pm->config); fail3: usb_free_urb(pm->irq); fail2: powermate_free_buffers(udev, pm); fail1: input_free_device(input_dev); kfree(pm); return error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'Input: powermate - fix oops with malicious USB descriptors The powermate driver expects at least one valid USB endpoint in its probe function. If given malicious descriptors that specify 0 for the number of endpoints, it will crash. Validate the number of endpoints on the interface before using them. The full report for this issue can be found here: http://seclists.org/bugtraq/2016/Mar/85 Reported-by: Ralf Spenneberg <[email protected]> Cc: stable <[email protected]> Signed-off-by: Josh Boyer <[email protected]> Signed-off-by: Dmitry Torokhov <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int iowarrior_probe(struct usb_interface *interface, const struct usb_device_id *id) { struct usb_device *udev = interface_to_usbdev(interface); struct iowarrior *dev = NULL; struct usb_host_interface *iface_desc; struct usb_endpoint_descriptor *endpoint; int i; int retval = -ENOMEM; /* allocate memory for our device state and initialize it */ dev = kzalloc(sizeof(struct iowarrior), GFP_KERNEL); if (dev == NULL) { dev_err(&interface->dev, "Out of memory\n"); return retval; } mutex_init(&dev->mutex); atomic_set(&dev->intr_idx, 0); atomic_set(&dev->read_idx, 0); spin_lock_init(&dev->intr_idx_lock); atomic_set(&dev->overflow_flag, 0); init_waitqueue_head(&dev->read_wait); atomic_set(&dev->write_busy, 0); init_waitqueue_head(&dev->write_wait); dev->udev = udev; dev->interface = interface; iface_desc = interface->cur_altsetting; dev->product_id = le16_to_cpu(udev->descriptor.idProduct); /* set up the endpoint information */ for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) { endpoint = &iface_desc->endpoint[i].desc; if (usb_endpoint_is_int_in(endpoint)) dev->int_in_endpoint = endpoint; if (usb_endpoint_is_int_out(endpoint)) /* this one will match for the IOWarrior56 only */ dev->int_out_endpoint = endpoint; } /* we have to check the report_size often, so remember it in the endianness suitable for our machine */ dev->report_size = usb_endpoint_maxp(dev->int_in_endpoint); if ((dev->interface->cur_altsetting->desc.bInterfaceNumber == 0) && (dev->product_id == USB_DEVICE_ID_CODEMERCS_IOW56)) /* IOWarrior56 has wMaxPacketSize different from report size */ dev->report_size = 7; /* create the urb and buffer for reading */ dev->int_in_urb = usb_alloc_urb(0, GFP_KERNEL); if (!dev->int_in_urb) { dev_err(&interface->dev, "Couldn't allocate interrupt_in_urb\n"); goto error; } dev->int_in_buffer = kmalloc(dev->report_size, GFP_KERNEL); if (!dev->int_in_buffer) { dev_err(&interface->dev, "Couldn't allocate int_in_buffer\n"); goto error; } usb_fill_int_urb(dev->int_in_urb, dev->udev, usb_rcvintpipe(dev->udev, dev->int_in_endpoint->bEndpointAddress), dev->int_in_buffer, dev->report_size, iowarrior_callback, dev, dev->int_in_endpoint->bInterval); /* create an internal buffer for interrupt data from the device */ dev->read_queue = kmalloc(((dev->report_size + 1) * MAX_INTERRUPT_BUFFER), GFP_KERNEL); if (!dev->read_queue) { dev_err(&interface->dev, "Couldn't allocate read_queue\n"); goto error; } /* Get the serial-number of the chip */ memset(dev->chip_serial, 0x00, sizeof(dev->chip_serial)); usb_string(udev, udev->descriptor.iSerialNumber, dev->chip_serial, sizeof(dev->chip_serial)); if (strlen(dev->chip_serial) != 8) memset(dev->chip_serial, 0x00, sizeof(dev->chip_serial)); /* Set the idle timeout to 0, if this is interface 0 */ if (dev->interface->cur_altsetting->desc.bInterfaceNumber == 0) { usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x0A, USB_TYPE_CLASS | USB_RECIP_INTERFACE, 0, 0, NULL, 0, USB_CTRL_SET_TIMEOUT); } /* allow device read and ioctl */ dev->present = 1; /* we can register the device now, as it is ready */ usb_set_intfdata(interface, dev); retval = usb_register_dev(interface, &iowarrior_class); if (retval) { /* something prevented us from registering this driver */ dev_err(&interface->dev, "Not able to get a minor for this device.\n"); usb_set_intfdata(interface, NULL); goto error; } dev->minor = interface->minor; /* let the user know what node this device is now attached to */ dev_info(&interface->dev, "IOWarrior product=0x%x, serial=%s interface=%d " "now attached to iowarrior%d\n", dev->product_id, dev->chip_serial, iface_desc->desc.bInterfaceNumber, dev->minor - IOWARRIOR_MINOR_BASE); return retval; error: iowarrior_delete(dev); return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'USB: iowarrior: fix oops with malicious USB descriptors The iowarrior driver expects at least one valid endpoint. If given malicious descriptors that specify 0 for the number of endpoints, it will crash in the probe function. Ensure there is at least one endpoint on the interface before using it. The full report of this issue can be found here: http://seclists.org/bugtraq/2016/Mar/87 Reported-by: Ralf Spenneberg <[email protected]> Cc: stable <[email protected]> Signed-off-by: Josh Boyer <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int do_add_counters(struct net *net, const void __user *user, unsigned int len, int compat) { unsigned int i; struct xt_counters_info tmp; struct xt_counters *paddc; unsigned int num_counters; const char *name; int size; void *ptmp; struct xt_table *t; const struct xt_table_info *private; int ret = 0; struct arpt_entry *iter; unsigned int addend; #ifdef CONFIG_COMPAT struct compat_xt_counters_info compat_tmp; if (compat) { ptmp = &compat_tmp; size = sizeof(struct compat_xt_counters_info); } else #endif { ptmp = &tmp; size = sizeof(struct xt_counters_info); } if (copy_from_user(ptmp, user, size) != 0) return -EFAULT; #ifdef CONFIG_COMPAT if (compat) { num_counters = compat_tmp.num_counters; name = compat_tmp.name; } else #endif { num_counters = tmp.num_counters; name = tmp.name; } if (len != size + num_counters * sizeof(struct xt_counters)) return -EINVAL; paddc = vmalloc(len - size); if (!paddc) return -ENOMEM; if (copy_from_user(paddc, user + size, len - size) != 0) { ret = -EFAULT; goto free; } t = xt_find_table_lock(net, NFPROTO_ARP, name); if (IS_ERR_OR_NULL(t)) { ret = t ? PTR_ERR(t) : -ENOENT; goto free; } local_bh_disable(); private = t->private; if (private->number != num_counters) { ret = -EINVAL; goto unlock_up_free; } i = 0; addend = xt_write_recseq_begin(); xt_entry_foreach(iter, private->entries, private->size) { struct xt_counters *tmp; tmp = xt_get_this_cpu_counter(&iter->counters); ADD_COUNTER(*tmp, paddc[i].bcnt, paddc[i].pcnt); ++i; } xt_write_recseq_end(addend); unlock_up_free: local_bh_enable(); xt_table_unlock(t); module_put(t->me); free: vfree(paddc); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'netfilter: x_tables: introduce and use xt_copy_counters_from_user The three variants use same copy&pasted code, condense this into a helper and use that. Make sure info.name is 0-terminated. Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int pagemap_open(struct inode *inode, struct file *file) { pr_warn_once("Bits 55-60 of /proc/PID/pagemap entries are about " "to stop being page-shift some time soon. See the " "linux/Documentation/vm/pagemap.txt for details.\n"); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'pagemap: do not leak physical addresses to non-privileged userspace As pointed by recent post[1] on exploiting DRAM physical imperfection, /proc/PID/pagemap exposes sensitive information which can be used to do attacks. This disallows anybody without CAP_SYS_ADMIN to read the pagemap. [1] http://googleprojectzero.blogspot.com/2015/03/exploiting-dram-rowhammer-bug-to-gain.html [ Eventually we might want to do anything more finegrained, but for now this is the simple model. - Linus ] Signed-off-by: Kirill A. Shutemov <[email protected]> Acked-by: Konstantin Khlebnikov <[email protected]> Acked-by: Andy Lutomirski <[email protected]> Cc: Pavel Emelyanov <[email protected]> Cc: Andrew Morton <[email protected]> Cc: Mark Seaborn <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void sycc444_to_rgb(opj_image_t *img) { int *d0, *d1, *d2, *r, *g, *b; const int *y, *cb, *cr; unsigned int maxw, maxh, max, i; int offset, upb; upb = (int)img->comps[0].prec; offset = 1<<(upb - 1); upb = (1<<upb)-1; maxw = (unsigned int)img->comps[0].w; maxh = (unsigned int)img->comps[0].h; max = maxw * maxh; y = img->comps[0].data; cb = img->comps[1].data; cr = img->comps[2].data; d0 = r = (int*)malloc(sizeof(int) * (size_t)max); d1 = g = (int*)malloc(sizeof(int) * (size_t)max); d2 = b = (int*)malloc(sizeof(int) * (size_t)max); if(r == NULL || g == NULL || b == NULL) goto fails; for(i = 0U; i < max; ++i) { sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b); ++y; ++cb; ++cr; ++r; ++g; ++b; } free(img->comps[0].data); img->comps[0].data = d0; free(img->comps[1].data); img->comps[1].data = d1; free(img->comps[2].data); img->comps[2].data = d2; return; fails: if(r) free(r); if(g) free(g); if(b) free(b); }/* sycc444_to_rgb() */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-125'], 'message': 'Fix Out-Of-Bounds Read in sycc42x_to_rgb function (#745) 42x Images with an odd x0/y0 lead to subsampled component starting at the 2nd column/line. That is offset = comp->dx * comp->x0 - image->x0 = 1 Fix #726'</s>
<s>[INST] Given the following code containing errors, provide 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 imagetobmp(opj_image_t * image, const char *outfile) { int w, h; int i, pad; FILE *fdest = NULL; int adjustR, adjustG, adjustB; if (image->comps[0].prec < 8) { fprintf(stderr, "Unsupported number of components: %d\n", image->comps[0].prec); return 1; } if (image->numcomps >= 3 && image->comps[0].dx == image->comps[1].dx && image->comps[1].dx == image->comps[2].dx && image->comps[0].dy == image->comps[1].dy && image->comps[1].dy == image->comps[2].dy && image->comps[0].prec == image->comps[1].prec && image->comps[1].prec == image->comps[2].prec) { /* -->> -->> -->> -->> 24 bits color <<-- <<-- <<-- <<-- */ fdest = fopen(outfile, "wb"); if (!fdest) { fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile); return 1; } w = (int)image->comps[0].w; h = (int)image->comps[0].h; fprintf(fdest, "BM"); /* FILE HEADER */ /* ------------- */ fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) (h * w * 3 + 3 * h * (w % 2) + 54) & 0xff, (OPJ_UINT8) ((h * w * 3 + 3 * h * (w % 2) + 54) >> 8) & 0xff, (OPJ_UINT8) ((h * w * 3 + 3 * h * (w % 2) + 54) >> 16) & 0xff, (OPJ_UINT8) ((h * w * 3 + 3 * h * (w % 2) + 54) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (54) & 0xff, ((54) >> 8) & 0xff,((54) >> 16) & 0xff, ((54) >> 24) & 0xff); /* INFO HEADER */ /* ------------- */ fprintf(fdest, "%c%c%c%c", (40) & 0xff, ((40) >> 8) & 0xff, ((40) >> 16) & 0xff, ((40) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) ((w) & 0xff), (OPJ_UINT8) ((w) >> 8) & 0xff, (OPJ_UINT8) ((w) >> 16) & 0xff, (OPJ_UINT8) ((w) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) ((h) & 0xff), (OPJ_UINT8) ((h) >> 8) & 0xff, (OPJ_UINT8) ((h) >> 16) & 0xff, (OPJ_UINT8) ((h) >> 24) & 0xff); fprintf(fdest, "%c%c", (1) & 0xff, ((1) >> 8) & 0xff); fprintf(fdest, "%c%c", (24) & 0xff, ((24) >> 8) & 0xff); fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) (3 * h * w + 3 * h * (w % 2)) & 0xff, (OPJ_UINT8) ((h * w * 3 + 3 * h * (w % 2)) >> 8) & 0xff, (OPJ_UINT8) ((h * w * 3 + 3 * h * (w % 2)) >> 16) & 0xff, (OPJ_UINT8) ((h * w * 3 + 3 * h * (w % 2)) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff); if (image->comps[0].prec > 8) { adjustR = (int)image->comps[0].prec - 8; printf("BMP CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec); } else adjustR = 0; if (image->comps[1].prec > 8) { adjustG = (int)image->comps[1].prec - 8; printf("BMP CONVERSION: Truncating component 1 from %d bits to 8 bits\n", image->comps[1].prec); } else adjustG = 0; if (image->comps[2].prec > 8) { adjustB = (int)image->comps[2].prec - 8; printf("BMP CONVERSION: Truncating component 2 from %d bits to 8 bits\n", image->comps[2].prec); } else adjustB = 0; for (i = 0; i < w * h; i++) { OPJ_UINT8 rc, gc, bc; int r, g, b; r = image->comps[0].data[w * h - ((i) / (w) + 1) * w + (i) % (w)]; r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0); r = ((r >> adjustR)+((r >> (adjustR-1))%2)); if(r > 255) r = 255; else if(r < 0) r = 0; rc = (OPJ_UINT8)r; g = image->comps[1].data[w * h - ((i) / (w) + 1) * w + (i) % (w)]; g += (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0); g = ((g >> adjustG)+((g >> (adjustG-1))%2)); if(g > 255) g = 255; else if(g < 0) g = 0; gc = (OPJ_UINT8)g; b = image->comps[2].data[w * h - ((i) / (w) + 1) * w + (i) % (w)]; b += (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0); b = ((b >> adjustB)+((b >> (adjustB-1))%2)); if(b > 255) b = 255; else if(b < 0) b = 0; bc = (OPJ_UINT8)b; fprintf(fdest, "%c%c%c", bc, gc, rc); if ((i + 1) % w == 0) { for (pad = ((3 * w) % 4) ? (4 - (3 * w) % 4) : 0; pad > 0; pad--) /* ADD */ fprintf(fdest, "%c", 0); } } fclose(fdest); } else { /* Gray-scale */ /* -->> -->> -->> -->> 8 bits non code (Gray scale) <<-- <<-- <<-- <<-- */ fdest = fopen(outfile, "wb"); if (!fdest) { fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile); return 1; } w = (int)image->comps[0].w; h = (int)image->comps[0].h; fprintf(fdest, "BM"); /* FILE HEADER */ /* ------------- */ fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) (h * w + 54 + 1024 + h * (w % 2)) & 0xff, (OPJ_UINT8) ((h * w + 54 + 1024 + h * (w % 2)) >> 8) & 0xff, (OPJ_UINT8) ((h * w + 54 + 1024 + h * (w % 2)) >> 16) & 0xff, (OPJ_UINT8) ((h * w + 54 + 1024 + w * (w % 2)) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (54 + 1024) & 0xff, ((54 + 1024) >> 8) & 0xff, ((54 + 1024) >> 16) & 0xff, ((54 + 1024) >> 24) & 0xff); /* INFO HEADER */ /* ------------- */ fprintf(fdest, "%c%c%c%c", (40) & 0xff, ((40) >> 8) & 0xff, ((40) >> 16) & 0xff, ((40) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) ((w) & 0xff), (OPJ_UINT8) ((w) >> 8) & 0xff, (OPJ_UINT8) ((w) >> 16) & 0xff, (OPJ_UINT8) ((w) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) ((h) & 0xff), (OPJ_UINT8) ((h) >> 8) & 0xff, (OPJ_UINT8) ((h) >> 16) & 0xff, (OPJ_UINT8) ((h) >> 24) & 0xff); fprintf(fdest, "%c%c", (1) & 0xff, ((1) >> 8) & 0xff); fprintf(fdest, "%c%c", (8) & 0xff, ((8) >> 8) & 0xff); fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) (h * w + h * (w % 2)) & 0xff, (OPJ_UINT8) ((h * w + h * (w % 2)) >> 8) & 0xff, (OPJ_UINT8) ((h * w + h * (w % 2)) >> 16) & 0xff, (OPJ_UINT8) ((h * w + h * (w % 2)) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (256) & 0xff, ((256) >> 8) & 0xff, ((256) >> 16) & 0xff, ((256) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (256) & 0xff, ((256) >> 8) & 0xff, ((256) >> 16) & 0xff, ((256) >> 24) & 0xff); if (image->comps[0].prec > 8) { adjustR = (int)image->comps[0].prec - 8; printf("BMP CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec); }else adjustR = 0; for (i = 0; i < 256; i++) { fprintf(fdest, "%c%c%c%c", i, i, i, 0); } for (i = 0; i < w * h; i++) { int r; r = image->comps[0].data[w * h - ((i) / (w) + 1) * w + (i) % (w)]; r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0); r = ((r >> adjustR)+((r >> (adjustR-1))%2)); if(r > 255) r = 255; else if(r < 0) r = 0; fprintf(fdest, "%c", (OPJ_UINT8)r); if ((i + 1) % w == 0) { for ((pad = w % 4) ? (4 - w % 4) : 0; pad > 0; pad--) /* ADD */ fprintf(fdest, "%c", 0); } } fclose(fdest); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-125'], 'message': 'Fix Out-Of-Bounds Read in sycc42x_to_rgb function (#745) 42x Images with an odd x0/y0 lead to subsampled component starting at the 2nd column/line. That is offset = comp->dx * comp->x0 - image->x0 = 1 Fix #726'</s>
<s>[INST] Given the following code containing errors, provide 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 color_esycc_to_rgb(opj_image_t *image) { int y, cb, cr, sign1, sign2, val; unsigned int w, h, max, i; int flip_value = (1 << (image->comps[0].prec-1)); int max_value = (1 << image->comps[0].prec) - 1; if(image->numcomps < 3) return; w = image->comps[0].w; h = image->comps[0].h; sign1 = (int)image->comps[1].sgnd; sign2 = (int)image->comps[2].sgnd; max = w * h; for(i = 0; i < max; ++i) { y = image->comps[0].data[i]; cb = image->comps[1].data[i]; cr = image->comps[2].data[i]; if( !sign1) cb -= flip_value; if( !sign2) cr -= flip_value; val = (int) ((float)y - (float)0.0000368 * (float)cb + (float)1.40199 * (float)cr + (float)0.5); if(val > max_value) val = max_value; else if(val < 0) val = 0; image->comps[0].data[i] = val; val = (int) ((float)1.0003 * (float)y - (float)0.344125 * (float)cb - (float)0.7141128 * (float)cr + (float)0.5); if(val > max_value) val = max_value; else if(val < 0) val = 0; image->comps[1].data[i] = val; val = (int) ((float)0.999823 * (float)y + (float)1.77204 * (float)cb - (float)0.000008 *(float)cr + (float)0.5); if(val > max_value) val = max_value; else if(val < 0) val = 0; image->comps[2].data[i] = val; } image->color_space = OPJ_CLRSPC_SRGB; }/* color_esycc_to_rgb() */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix heap-buffer-overflow in color_esycc_to_rgb (#748) When all components do not have the same dx/dy, components buffer are read beyond their end. Do not convert in this case. Update uclouvain/openjpeg#725'</s>
<s>[INST] Given the following code containing errors, provide 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 fib_del_ifaddr(struct in_ifaddr *ifa, struct in_ifaddr *iprim) { struct in_device *in_dev = ifa->ifa_dev; struct net_device *dev = in_dev->dev; struct in_ifaddr *ifa1; struct in_ifaddr *prim = ifa, *prim1 = NULL; __be32 brd = ifa->ifa_address | ~ifa->ifa_mask; __be32 any = ifa->ifa_address & ifa->ifa_mask; #define LOCAL_OK 1 #define BRD_OK 2 #define BRD0_OK 4 #define BRD1_OK 8 unsigned int ok = 0; int subnet = 0; /* Primary network */ int gone = 1; /* Address is missing */ int same_prefsrc = 0; /* Another primary with same IP */ if (ifa->ifa_flags & IFA_F_SECONDARY) { prim = inet_ifa_byprefix(in_dev, any, ifa->ifa_mask); if (!prim) { pr_warn("%s: bug: prim == NULL\n", __func__); return; } if (iprim && iprim != prim) { pr_warn("%s: bug: iprim != prim\n", __func__); return; } } else if (!ipv4_is_zeronet(any) && (any != ifa->ifa_local || ifa->ifa_prefixlen < 32)) { if (!(ifa->ifa_flags & IFA_F_NOPREFIXROUTE)) fib_magic(RTM_DELROUTE, dev->flags & IFF_LOOPBACK ? RTN_LOCAL : RTN_UNICAST, any, ifa->ifa_prefixlen, prim); subnet = 1; } /* Deletion is more complicated than add. * We should take care of not to delete too much :-) * * Scan address list to be sure that addresses are really gone. */ for (ifa1 = in_dev->ifa_list; ifa1; ifa1 = ifa1->ifa_next) { if (ifa1 == ifa) { /* promotion, keep the IP */ gone = 0; continue; } /* Ignore IFAs from our subnet */ if (iprim && ifa1->ifa_mask == iprim->ifa_mask && inet_ifa_match(ifa1->ifa_address, iprim)) continue; /* Ignore ifa1 if it uses different primary IP (prefsrc) */ if (ifa1->ifa_flags & IFA_F_SECONDARY) { /* Another address from our subnet? */ if (ifa1->ifa_mask == prim->ifa_mask && inet_ifa_match(ifa1->ifa_address, prim)) prim1 = prim; else { /* We reached the secondaries, so * same_prefsrc should be determined. */ if (!same_prefsrc) continue; /* Search new prim1 if ifa1 is not * using the current prim1 */ if (!prim1 || ifa1->ifa_mask != prim1->ifa_mask || !inet_ifa_match(ifa1->ifa_address, prim1)) prim1 = inet_ifa_byprefix(in_dev, ifa1->ifa_address, ifa1->ifa_mask); if (!prim1) continue; if (prim1->ifa_local != prim->ifa_local) continue; } } else { if (prim->ifa_local != ifa1->ifa_local) continue; prim1 = ifa1; if (prim != prim1) same_prefsrc = 1; } if (ifa->ifa_local == ifa1->ifa_local) ok |= LOCAL_OK; if (ifa->ifa_broadcast == ifa1->ifa_broadcast) ok |= BRD_OK; if (brd == ifa1->ifa_broadcast) ok |= BRD1_OK; if (any == ifa1->ifa_broadcast) ok |= BRD0_OK; /* primary has network specific broadcasts */ if (prim1 == ifa1 && ifa1->ifa_prefixlen < 31) { __be32 brd1 = ifa1->ifa_address | ~ifa1->ifa_mask; __be32 any1 = ifa1->ifa_address & ifa1->ifa_mask; if (!ipv4_is_zeronet(any1)) { if (ifa->ifa_broadcast == brd1 || ifa->ifa_broadcast == any1) ok |= BRD_OK; if (brd == brd1 || brd == any1) ok |= BRD1_OK; if (any == brd1 || any == any1) ok |= BRD0_OK; } } } if (!(ok & BRD_OK)) fib_magic(RTM_DELROUTE, RTN_BROADCAST, ifa->ifa_broadcast, 32, prim); if (subnet && ifa->ifa_prefixlen < 31) { if (!(ok & BRD1_OK)) fib_magic(RTM_DELROUTE, RTN_BROADCAST, brd, 32, prim); if (!(ok & BRD0_OK)) fib_magic(RTM_DELROUTE, RTN_BROADCAST, any, 32, prim); } if (!(ok & LOCAL_OK)) { unsigned int addr_type; fib_magic(RTM_DELROUTE, RTN_LOCAL, ifa->ifa_local, 32, prim); /* Check, that this local address finally disappeared. */ addr_type = inet_addr_type_dev_table(dev_net(dev), dev, ifa->ifa_local); if (gone && addr_type != RTN_LOCAL) { /* And the last, but not the least thing. * We must flush stray FIB entries. * * First of all, we scan fib_info list searching * for stray nexthop entries, then ignite fib_flush. */ if (fib_sync_down_addr(dev_net(dev), ifa->ifa_local)) fib_flush(dev_net(dev)); } } #undef LOCAL_OK #undef BRD_OK #undef BRD0_OK #undef BRD1_OK } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'ipv4: Don't do expensive useless work during inetdev destroy. When an inetdev is destroyed, every address assigned to the interface is removed. And in this scenerio we do two pointless things which can be very expensive if the number of assigned interfaces is large: 1) Address promotion. We are deleting all addresses, so there is no point in doing this. 2) A full nf conntrack table purge for every address. We only need to do this once, as is already caught by the existing masq_dev_notifier so masq_inet_event() can skip this. Reported-by: Solar Designer <[email protected]> Signed-off-by: David S. Miller <[email protected]> Tested-by: Cyrill Gorcunov <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: process_db_args(krb5_context context, char **db_args, xargs_t *xargs, OPERATION optype) { int i=0; krb5_error_code st=0; char *arg=NULL, *arg_val=NULL; char **dptr=NULL; unsigned int arg_val_len=0; if (db_args) { for (i=0; db_args[i]; ++i) { arg = strtok_r(db_args[i], "=", &arg_val); if (strcmp(arg, TKTPOLICY_ARG) == 0) { dptr = &xargs->tktpolicydn; } else { if (strcmp(arg, USERDN_ARG) == 0) { if (optype == MODIFY_PRINCIPAL || xargs->dn != NULL || xargs->containerdn != NULL || xargs->linkdn != NULL) { st = EINVAL; k5_setmsg(context, st, _("%s option not supported"), arg); goto cleanup; } dptr = &xargs->dn; } else if (strcmp(arg, CONTAINERDN_ARG) == 0) { if (optype == MODIFY_PRINCIPAL || xargs->dn != NULL || xargs->containerdn != NULL) { st = EINVAL; k5_setmsg(context, st, _("%s option not supported"), arg); goto cleanup; } dptr = &xargs->containerdn; } else if (strcmp(arg, LINKDN_ARG) == 0) { if (xargs->dn != NULL || xargs->linkdn != NULL) { st = EINVAL; k5_setmsg(context, st, _("%s option not supported"), arg); goto cleanup; } dptr = &xargs->linkdn; } else { st = EINVAL; k5_setmsg(context, st, _("unknown option: %s"), arg); goto cleanup; } xargs->dn_from_kbd = TRUE; if (arg_val == NULL || strlen(arg_val) == 0) { st = EINVAL; k5_setmsg(context, st, _("%s option value missing"), arg); goto cleanup; } } if (arg_val == NULL) { st = EINVAL; k5_setmsg(context, st, _("%s option value missing"), arg); goto cleanup; } arg_val_len = strlen(arg_val) + 1; if (strcmp(arg, TKTPOLICY_ARG) == 0) { if ((st = krb5_ldap_name_to_policydn (context, arg_val, dptr)) != 0) goto cleanup; } else { *dptr = k5memdup(arg_val, arg_val_len, &st); if (*dptr == NULL) goto cleanup; } } } cleanup: return st; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'Fix LDAP null deref on empty arg [CVE-2016-3119] In the LDAP KDB module's process_db_args(), strtok_r() may return NULL if there is an empty string in the db_args array. Check for this case and avoid dereferencing a null pointer. CVE-2016-3119: In MIT krb5 1.6 and later, an authenticated attacker with permission to modify a principal entry can cause kadmind to dereference a null pointer by supplying an empty DB argument to the modify_principal command, if kadmind is configured to use the LDAP KDB module. CVSSv2 Vector: AV:N/AC:H/Au:S/C:N/I:N/A:C/E:H/RL:OF/RC:ND ticket: 8383 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlParserEntityCheck(xmlParserCtxtPtr ctxt, size_t size, xmlEntityPtr ent, size_t replacement) { size_t consumed = 0; if ((ctxt == NULL) || (ctxt->options & XML_PARSE_HUGE)) return (0); if (ctxt->lastError.code == XML_ERR_ENTITY_LOOP) return (1); /* * This may look absurd but is needed to detect * entities problems */ if ((ent != NULL) && (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) && (ent->content != NULL) && (ent->checked == 0)) { unsigned long oldnbent = ctxt->nbentities; xmlChar *rep; ent->checked = 1; ++ctxt->depth; rep = xmlStringDecodeEntities(ctxt, ent->content, XML_SUBSTITUTE_REF, 0, 0, 0); --ctxt->depth; ent->checked = (ctxt->nbentities - oldnbent + 1) * 2; if (rep != NULL) { if (xmlStrchr(rep, '<')) ent->checked |= 1; xmlFree(rep); rep = NULL; } } if (replacement != 0) { if (replacement < XML_MAX_TEXT_LENGTH) return(0); /* * If the volume of entity copy reaches 10 times the * amount of parsed data and over the large text threshold * then that's very likely to be an abuse. */ if (ctxt->input != NULL) { consumed = ctxt->input->consumed + (ctxt->input->cur - ctxt->input->base); } consumed += ctxt->sizeentities; if (replacement < XML_PARSER_NON_LINEAR * consumed) return(0); } else if (size != 0) { /* * Do the check based on the replacement size of the entity */ if (size < XML_PARSER_BIG_ENTITY) return(0); /* * A limit on the amount of text data reasonably used */ if (ctxt->input != NULL) { consumed = ctxt->input->consumed + (ctxt->input->cur - ctxt->input->base); } consumed += ctxt->sizeentities; if ((size < XML_PARSER_NON_LINEAR * consumed) && (ctxt->nbentities * 3 < XML_PARSER_NON_LINEAR * consumed)) return (0); } else if (ent != NULL) { /* * use the number of parsed entities in the replacement */ size = ent->checked / 2; /* * The amount of data parsed counting entities size only once */ if (ctxt->input != NULL) { consumed = ctxt->input->consumed + (ctxt->input->cur - ctxt->input->base); } consumed += ctxt->sizeentities; /* * Check the density of entities for the amount of data * knowing an entity reference will take at least 3 bytes */ if (size * 3 < consumed * XML_PARSER_NON_LINEAR) return (0); } else { /* * strange we got no data for checking */ if (((ctxt->lastError.code != XML_ERR_UNDECLARED_ENTITY) && (ctxt->lastError.code != XML_WAR_UNDECLARED_ENTITY)) || (ctxt->nbentities <= 10000)) return (0); } xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL); return (1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Avoid building recursive entities For https://bugzilla.gnome.org/show_bug.cgi?id=762100 When we detect a recusive entity we should really not build the associated data, moreover if someone bypass libxml2 fatal errors and still tries to serialize a broken entity make sure we don't risk to get ito a recursion * parser.c: xmlParserEntityCheck() don't build if entity loop were found and remove the associated text content * tree.c: xmlStringGetNodeList() avoid a potential 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: _gd2GetHeader (gdIOCtxPtr in, int *sx, int *sy, int *cs, int *vers, int *fmt, int *ncx, int *ncy, t_chunk_info ** chunkIdx) { int i; int ch; char id[5]; t_chunk_info *cidx; int sidx; int nc; GD2_DBG (printf ("Reading gd2 header info\n")); for (i = 0; i < 4; i++) { ch = gdGetC (in); if (ch == EOF) { goto fail1; }; id[i] = ch; }; id[4] = 0; GD2_DBG (printf ("Got file code: %s\n", id)); /* Equiv. of 'magick'. */ if (strcmp (id, GD2_ID) != 0) { GD2_DBG (printf ("Not a valid gd2 file\n")); goto fail1; }; /* Version */ if (gdGetWord (vers, in) != 1) { goto fail1; }; GD2_DBG (printf ("Version: %d\n", *vers)); if ((*vers != 1) && (*vers != 2)) { GD2_DBG (printf ("Bad version: %d\n", *vers)); goto fail1; }; /* Image Size */ if (!gdGetWord (sx, in)) { GD2_DBG (printf ("Could not get x-size\n")); goto fail1; } if (!gdGetWord (sy, in)) { GD2_DBG (printf ("Could not get y-size\n")); goto fail1; } GD2_DBG (printf ("Image is %dx%d\n", *sx, *sy)); /* Chunk Size (pixels, not bytes!) */ if (gdGetWord (cs, in) != 1) { goto fail1; }; GD2_DBG (printf ("ChunkSize: %d\n", *cs)); if ((*cs < GD2_CHUNKSIZE_MIN) || (*cs > GD2_CHUNKSIZE_MAX)) { GD2_DBG (printf ("Bad chunk size: %d\n", *cs)); goto fail1; }; /* Data Format */ if (gdGetWord (fmt, in) != 1) { goto fail1; }; GD2_DBG (printf ("Format: %d\n", *fmt)); if ((*fmt != GD2_FMT_RAW) && (*fmt != GD2_FMT_COMPRESSED) && (*fmt != GD2_FMT_TRUECOLOR_RAW) && (*fmt != GD2_FMT_TRUECOLOR_COMPRESSED)) { GD2_DBG (printf ("Bad data format: %d\n", *fmt)); goto fail1; }; /* # of chunks wide */ if (gdGetWord (ncx, in) != 1) { goto fail1; }; GD2_DBG (printf ("%d Chunks Wide\n", *ncx)); /* # of chunks high */ if (gdGetWord (ncy, in) != 1) { goto fail1; }; GD2_DBG (printf ("%d Chunks vertically\n", *ncy)); if (gd2_compressed (*fmt)) { nc = (*ncx) * (*ncy); GD2_DBG (printf ("Reading %d chunk index entries\n", nc)); sidx = sizeof (t_chunk_info) * nc; cidx = gdCalloc (sidx, 1); if (!cidx) { goto fail1; } for (i = 0; i < nc; i++) { if (gdGetInt (&cidx[i].offset, in) != 1) { goto fail2; }; if (gdGetInt (&cidx[i].size, in) != 1) { goto fail2; }; }; *chunkIdx = cidx; }; GD2_DBG (printf ("gd2 header complete\n")); return 1; fail2: gdFree(cidx); fail1: return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189', 'CWE-681'], 'message': 'gd2: handle corrupt images better (CVE-2016-3074) Make sure we do some range checking on corrupted chunks. Thanks to Hans Jerry Illikainen <[email protected]> for indepth report and reproducer information. Made for easy test case writing :).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: mbfl_identify_encoding2(mbfl_string *string, const mbfl_encoding **elist, int elistsz, int strict) { int i, n, num, bad; unsigned char *p; mbfl_identify_filter *flist, *filter; const mbfl_encoding *encoding; /* flist is an array of mbfl_identify_filter instances */ flist = (mbfl_identify_filter *)mbfl_calloc(elistsz, sizeof(mbfl_identify_filter)); if (flist == NULL) { return NULL; } num = 0; if (elist != NULL) { for (i = 0; i < elistsz; i++) { if (!mbfl_identify_filter_init2(&flist[num], elist[i])) { num++; } } } /* feed data */ n = string->len; p = string->val; if (p != NULL) { bad = 0; while (n > 0) { for (i = 0; i < num; i++) { filter = &flist[i]; if (!filter->flag) { (*filter->filter_function)(*p, filter); if (filter->flag) { bad++; } } } if ((num - 1) <= bad && !strict) { break; } p++; n--; } } /* judge */ encoding = NULL; for (i = 0; i < num; i++) { filter = &flist[i]; if (!filter->flag) { if (strict && filter->status) { continue; } encoding = filter->encoding; break; } } /* fall-back judge */ if (!encoding) { for (i = 0; i < num; i++) { filter = &flist[i]; if (!filter->flag && (!strict || !filter->status)) { encoding = filter->encoding; break; } } } /* cleanup */ /* dtors should be called in reverse order */ i = num; while (--i >= 0) { mbfl_identify_filter_cleanup(&flist[i]); } mbfl_free((void *)flist); return encoding; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fixed bug #71906: AddressSanitizer: negative-size-param (-1) in mbfl_strcut'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: mbfl_identify_encoding(mbfl_string *string, enum mbfl_no_encoding *elist, int elistsz, int strict) { int i, n, num, bad; unsigned char *p; mbfl_identify_filter *flist, *filter; const mbfl_encoding *encoding; /* flist is an array of mbfl_identify_filter instances */ flist = (mbfl_identify_filter *)mbfl_calloc(elistsz, sizeof(mbfl_identify_filter)); if (flist == NULL) { return NULL; } num = 0; if (elist != NULL) { for (i = 0; i < elistsz; i++) { if (!mbfl_identify_filter_init(&flist[num], elist[i])) { num++; } } } /* feed data */ n = string->len; p = string->val; if (p != NULL) { bad = 0; while (n > 0) { for (i = 0; i < num; i++) { filter = &flist[i]; if (!filter->flag) { (*filter->filter_function)(*p, filter); if (filter->flag) { bad++; } } } if ((num - 1) <= bad && !strict) { break; } p++; n--; } } /* judge */ encoding = NULL; for (i = 0; i < num; i++) { filter = &flist[i]; if (!filter->flag) { if (strict && filter->status) { continue; } encoding = filter->encoding; break; } } /* fall-back judge */ if (!encoding) { for (i = 0; i < num; i++) { filter = &flist[i]; if (!filter->flag && (!strict || !filter->status)) { encoding = filter->encoding; break; } } } /* cleanup */ /* dtors should be called in reverse order */ i = num; while (--i >= 0) { mbfl_identify_filter_cleanup(&flist[i]); } mbfl_free((void *)flist); return encoding; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fixed bug #71906: AddressSanitizer: negative-size-param (-1) in mbfl_strcut'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: mbfl_strpos( mbfl_string *haystack, mbfl_string *needle, int offset, int reverse) { int result; mbfl_string _haystack_u8, _needle_u8; const mbfl_string *haystack_u8, *needle_u8 = NULL; const unsigned char *u8_tbl; if (haystack == NULL || haystack->val == NULL || needle == NULL || needle->val == NULL) { return -8; } { const mbfl_encoding *u8_enc; u8_enc = mbfl_no2encoding(mbfl_no_encoding_utf8); if (u8_enc == NULL || u8_enc->mblen_table == NULL) { return -8; } u8_tbl = u8_enc->mblen_table; } if (haystack->no_encoding != mbfl_no_encoding_utf8) { mbfl_string_init(&_haystack_u8); haystack_u8 = mbfl_convert_encoding(haystack, &_haystack_u8, mbfl_no_encoding_utf8); if (haystack_u8 == NULL) { result = -4; goto out; } } else { haystack_u8 = haystack; } if (needle->no_encoding != mbfl_no_encoding_utf8) { mbfl_string_init(&_needle_u8); needle_u8 = mbfl_convert_encoding(needle, &_needle_u8, mbfl_no_encoding_utf8); if (needle_u8 == NULL) { result = -4; goto out; } } else { needle_u8 = needle; } if (needle_u8->len < 1) { result = -8; goto out; } result = -1; if (haystack_u8->len < needle_u8->len) { goto out; } if (!reverse) { unsigned int jtbl[1 << (sizeof(unsigned char) * 8)]; unsigned int needle_u8_len = needle_u8->len; unsigned int i; const unsigned char *p, *q, *e; const unsigned char *haystack_u8_val = haystack_u8->val, *needle_u8_val = needle_u8->val; for (i = 0; i < sizeof(jtbl) / sizeof(*jtbl); ++i) { jtbl[i] = needle_u8_len + 1; } for (i = 0; i < needle_u8_len - 1; ++i) { jtbl[needle_u8_val[i]] = needle_u8_len - i; } e = haystack_u8_val + haystack_u8->len; p = haystack_u8_val; while (--offset >= 0) { if (p >= e) { result = -16; goto out; } p += u8_tbl[*p]; } p += needle_u8_len; if (p > e) { goto out; } while (p <= e) { const unsigned char *pv = p; q = needle_u8_val + needle_u8_len; for (;;) { if (q == needle_u8_val) { result = 0; while (p > haystack_u8_val) { unsigned char c = *--p; if (c < 0x80) { ++result; } else if ((c & 0xc0) != 0x80) { ++result; } } goto out; } if (*--q != *--p) { break; } } p += jtbl[*p]; if (p <= pv) { p = pv + 1; } } } else { unsigned int jtbl[1 << (sizeof(unsigned char) * 8)]; unsigned int needle_u8_len = needle_u8->len, needle_len = 0; unsigned int i; const unsigned char *p, *e, *q, *qe; const unsigned char *haystack_u8_val = haystack_u8->val, *needle_u8_val = needle_u8->val; for (i = 0; i < sizeof(jtbl) / sizeof(*jtbl); ++i) { jtbl[i] = needle_u8_len; } for (i = needle_u8_len - 1; i > 0; --i) { unsigned char c = needle_u8_val[i]; jtbl[c] = i; if (c < 0x80) { ++needle_len; } else if ((c & 0xc0) != 0x80) { ++needle_len; } } { unsigned char c = needle_u8_val[0]; if (c < 0x80) { ++needle_len; } else if ((c & 0xc0) != 0x80) { ++needle_len; } } e = haystack_u8_val; p = e + haystack_u8->len; qe = needle_u8_val + needle_u8_len; if (offset < 0) { if (-offset > needle_len) { offset += needle_len; while (offset < 0) { unsigned char c; if (p <= e) { result = -16; goto out; } c = *(--p); if (c < 0x80) { ++offset; } else if ((c & 0xc0) != 0x80) { ++offset; } } } } else { const unsigned char *ee = haystack_u8_val + haystack_u8->len; while (--offset >= 0) { if (e >= ee) { result = -16; goto out; } e += u8_tbl[*e]; } } if (p < e + needle_u8_len) { goto out; } p -= needle_u8_len; while (p >= e) { const unsigned char *pv = p; q = needle_u8_val; for (;;) { if (q == qe) { result = 0; p -= needle_u8_len; while (p > haystack_u8_val) { unsigned char c = *--p; if (c < 0x80) { ++result; } else if ((c & 0xc0) != 0x80) { ++result; } } goto out; } if (*q != *p) { break; } ++p, ++q; } p -= jtbl[*p]; if (p >= pv) { p = pv - 1; } } } out: if (haystack_u8 == &_haystack_u8) { mbfl_string_clear(&_haystack_u8); } if (needle_u8 == &_needle_u8) { mbfl_string_clear(&_needle_u8); } return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fixed bug #71906: AddressSanitizer: negative-size-param (-1) in mbfl_strcut'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: mbfl_ja_jp_hantozen( mbfl_string *string, mbfl_string *result, int mode) { int n; unsigned char *p; const mbfl_encoding *encoding; mbfl_memory_device device; mbfl_convert_filter *decoder = NULL; mbfl_convert_filter *encoder = NULL; mbfl_convert_filter *tl_filter = NULL; mbfl_convert_filter *next_filter = NULL; mbfl_filt_tl_jisx0201_jisx0208_param *param = NULL; /* validate parameters */ if (string == NULL || result == NULL) { return NULL; } encoding = mbfl_no2encoding(string->no_encoding); if (encoding == NULL) { return NULL; } mbfl_memory_device_init(&device, string->len, 0); mbfl_string_init(result); result->no_language = string->no_language; result->no_encoding = string->no_encoding; decoder = mbfl_convert_filter_new( mbfl_no_encoding_wchar, string->no_encoding, mbfl_memory_device_output, 0, &device); if (decoder == NULL) { goto out; } next_filter = decoder; param = (mbfl_filt_tl_jisx0201_jisx0208_param *)mbfl_malloc(sizeof(mbfl_filt_tl_jisx0201_jisx0208_param)); if (param == NULL) { goto out; } param->mode = mode; tl_filter = mbfl_convert_filter_new2( &vtbl_tl_jisx0201_jisx0208, (int(*)(int, void*))next_filter->filter_function, (int(*)(void*))next_filter->filter_flush, next_filter); if (tl_filter == NULL) { mbfl_free(param); goto out; } tl_filter->opaque = param; next_filter = tl_filter; encoder = mbfl_convert_filter_new( string->no_encoding, mbfl_no_encoding_wchar, (int(*)(int, void*))next_filter->filter_function, (int(*)(void*))next_filter->filter_flush, next_filter); if (encoder == NULL) { goto out; } /* feed data */ p = string->val; n = string->len; if (p != NULL) { while (n > 0) { if ((*encoder->filter_function)(*p++, encoder) < 0) { break; } n--; } } mbfl_convert_filter_flush(encoder); result = mbfl_memory_device_result(&device, result); out: if (tl_filter != NULL) { if (tl_filter->opaque != NULL) { mbfl_free(tl_filter->opaque); } mbfl_convert_filter_delete(tl_filter); } if (decoder != NULL) { mbfl_convert_filter_delete(decoder); } if (encoder != NULL) { mbfl_convert_filter_delete(encoder); } return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fixed bug #71906: AddressSanitizer: negative-size-param (-1) in mbfl_strcut'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_METHOD(Phar, offsetSet) { char *fname, *cont_str = NULL; size_t fname_len, cont_len; zval *zresource; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly"); return; } if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "sr", &fname, &fname_len, &zresource) == FAILURE && zend_parse_parameters(ZEND_NUM_ARGS(), "ss", &fname, &fname_len, &cont_str, &cont_len) == FAILURE) { return; } if (fname_len == sizeof(".phar/stub.php")-1 && !memcmp(fname, ".phar/stub.php", sizeof(".phar/stub.php")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set stub \".phar/stub.php\" directly in phar \"%s\", use setStub", phar_obj->archive->fname); return; } if (fname_len == sizeof(".phar/alias.txt")-1 && !memcmp(fname, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set alias \".phar/alias.txt\" directly in phar \"%s\", use setAlias", phar_obj->archive->fname); return; } if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set any files or directories in magic \".phar\" directory", phar_obj->archive->fname); return; } phar_add_file(&(phar_obj->archive), fname, fname_len, cont_str, cont_len, zresource); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #71860: Require valid paths for phar filenames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_METHOD(Phar, extractTo) { char *error = NULL; php_stream *fp; php_stream_statbuf ssb; phar_entry_info *entry; char *pathto, *filename; size_t pathto_len, filename_len; int ret, i; int nelems; zval *zval_files = NULL; zend_bool overwrite = 0; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|z!b", &pathto, &pathto_len, &zval_files, &overwrite) == FAILURE) { return; } fp = php_stream_open_wrapper(phar_obj->archive->fname, "rb", IGNORE_URL|STREAM_MUST_SEEK, NULL); if (!fp) { zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "Invalid argument, %s cannot be found", phar_obj->archive->fname); return; } php_stream_close(fp); if (pathto_len < 1) { zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "Invalid argument, extraction path must be non-zero length"); return; } if (pathto_len >= MAXPATHLEN) { char *tmp = estrndup(pathto, 50); /* truncate for error message */ zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "Cannot extract to \"%s...\", destination directory is too long for filesystem", tmp); efree(tmp); return; } if (php_stream_stat_path(pathto, &ssb) < 0) { ret = php_stream_mkdir(pathto, 0777, PHP_STREAM_MKDIR_RECURSIVE, NULL); if (!ret) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Unable to create path \"%s\" for extraction", pathto); return; } } else if (!(ssb.sb.st_mode & S_IFDIR)) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Unable to use path \"%s\" for extraction, it is a file, must be a directory", pathto); return; } if (zval_files) { switch (Z_TYPE_P(zval_files)) { case IS_NULL: goto all_files; case IS_STRING: filename = Z_STRVAL_P(zval_files); filename_len = Z_STRLEN_P(zval_files); break; case IS_ARRAY: nelems = zend_hash_num_elements(Z_ARRVAL_P(zval_files)); if (nelems == 0 ) { RETURN_FALSE; } for (i = 0; i < nelems; i++) { zval *zval_file; if ((zval_file = zend_hash_index_find(Z_ARRVAL_P(zval_files), i)) != NULL) { switch (Z_TYPE_P(zval_file)) { case IS_STRING: break; default: zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "Invalid argument, array of filenames to extract contains non-string value"); return; } if (NULL == (entry = zend_hash_find_ptr(&phar_obj->archive->manifest, Z_STR_P(zval_file)))) { zend_throw_exception_ex(phar_ce_PharException, 0, "Phar Error: attempted to extract non-existent file \"%s\" from phar \"%s\"", Z_STRVAL_P(zval_file), phar_obj->archive->fname); } if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, &error)) { zend_throw_exception_ex(phar_ce_PharException, 0, "Extraction from phar \"%s\" failed: %s", phar_obj->archive->fname, error); efree(error); return; } } } RETURN_TRUE; default: zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "Invalid argument, expected a filename (string) or array of filenames"); return; } if (NULL == (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, filename, filename_len))) { zend_throw_exception_ex(phar_ce_PharException, 0, "Phar Error: attempted to extract non-existent file \"%s\" from phar \"%s\"", filename, phar_obj->archive->fname); return; } if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, &error)) { zend_throw_exception_ex(phar_ce_PharException, 0, "Extraction from phar \"%s\" failed: %s", phar_obj->archive->fname, error); efree(error); return; } } else { phar_archive_data *phar; all_files: phar = phar_obj->archive; /* Extract all files */ if (!zend_hash_num_elements(&(phar->manifest))) { RETURN_TRUE; } ZEND_HASH_FOREACH_PTR(&phar->manifest, entry) { if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, &error)) { zend_throw_exception_ex(phar_ce_PharException, 0, "Extraction from phar \"%s\" failed: %s", phar->fname, error); efree(error); return; } } ZEND_HASH_FOREACH_END(); } RETURN_TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #71860: Require valid paths for phar filenames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_METHOD(PharFileInfo, __construct) { char *fname, *arch, *entry, *error; size_t fname_len; int arch_len, entry_len; phar_entry_object *entry_obj; phar_entry_info *entry_info; phar_archive_data *phar_data; zval *zobj = getThis(), arg1; if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) { return; } entry_obj = (phar_entry_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset); if (entry_obj->entry) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot call constructor twice"); return; } if (fname_len < 7 || memcmp(fname, "phar://", 7) || phar_split_fname(fname, (int)fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0) == FAILURE) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "'%s' is not a valid phar archive URL (must have at least phar://filename.phar)", fname); return; } if (phar_open_from_filename(arch, arch_len, NULL, 0, REPORT_ERRORS, &phar_data, &error) == FAILURE) { efree(arch); efree(entry); if (error) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Cannot open phar file '%s': %s", fname, error); efree(error); } else { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Cannot open phar file '%s'", fname); } return; } if ((entry_info = phar_get_entry_info_dir(phar_data, entry, entry_len, 1, &error, 1)) == NULL) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Cannot access phar file entry '%s' in archive '%s'%s%s", entry, arch, error ? ", " : "", error ? error : ""); efree(arch); efree(entry); return; } efree(arch); efree(entry); entry_obj->entry = entry_info; ZVAL_STRINGL(&arg1, fname, fname_len); zend_call_method_with_1_params(zobj, Z_OBJCE_P(zobj), &spl_ce_SplFileInfo->constructor, "__construct", NULL, &arg1); zval_ptr_dtor(&arg1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #71860: Require valid paths for phar filenames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_METHOD(Phar, createDefaultStub) { char *index = NULL, *webindex = NULL, *error; zend_string *stub; size_t index_len = 0, webindex_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|ss", &index, &index_len, &webindex, &webindex_len) == FAILURE) { return; } stub = phar_create_default_stub(index, webindex, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); return; } RETURN_NEW_STR(stub); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #71860: Require valid paths for phar filenames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_METHOD(Phar, delete) { char *fname; size_t fname_len; char *error; phar_entry_info *entry; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Cannot write out phar archive, phar is read-only"); return; } if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) { RETURN_FALSE; } if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname); return; } if (zend_hash_str_exists(&phar_obj->archive->manifest, fname, (uint) fname_len)) { if (NULL != (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len))) { if (entry->is_deleted) { /* entry is deleted, but has not been flushed to disk yet */ RETURN_TRUE; } else { entry->is_deleted = 1; entry->is_modified = 1; phar_obj->archive->is_modified = 1; } } } else { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s does not exist and cannot be deleted", fname); RETURN_FALSE; } phar_flush(phar_obj->archive, NULL, 0, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } RETURN_TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #71860: Require valid paths for phar filenames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_METHOD(Phar, copy) { char *oldfile, *newfile, *error; const char *pcr_error; size_t oldfile_len, newfile_len; phar_entry_info *oldentry, newentry = {0}, *temp; int tmp_len = 0; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss", &oldfile, &oldfile_len, &newfile, &newfile_len) == FAILURE) { return; } if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Cannot copy \"%s\" to \"%s\", phar is read-only", oldfile, newfile); RETURN_FALSE; } if (oldfile_len >= sizeof(".phar")-1 && !memcmp(oldfile, ".phar", sizeof(".phar")-1)) { /* can't copy a meta file */ zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "file \"%s\" cannot be copied to file \"%s\", cannot copy Phar meta-file in %s", oldfile, newfile, phar_obj->archive->fname); RETURN_FALSE; } if (newfile_len >= sizeof(".phar")-1 && !memcmp(newfile, ".phar", sizeof(".phar")-1)) { /* can't copy a meta file */ zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "file \"%s\" cannot be copied to file \"%s\", cannot copy to Phar meta-file in %s", oldfile, newfile, phar_obj->archive->fname); RETURN_FALSE; } if (!zend_hash_str_exists(&phar_obj->archive->manifest, oldfile, (uint) oldfile_len) || NULL == (oldentry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, oldfile, (uint) oldfile_len)) || oldentry->is_deleted) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "file \"%s\" cannot be copied to file \"%s\", file does not exist in %s", oldfile, newfile, phar_obj->archive->fname); RETURN_FALSE; } if (zend_hash_str_exists(&phar_obj->archive->manifest, newfile, (uint) newfile_len)) { if (NULL != (temp = zend_hash_str_find_ptr(&phar_obj->archive->manifest, newfile, (uint) newfile_len)) || !temp->is_deleted) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "file \"%s\" cannot be copied to file \"%s\", file must not already exist in phar %s", oldfile, newfile, phar_obj->archive->fname); RETURN_FALSE; } } tmp_len = (int)newfile_len; if (phar_path_check(&newfile, &tmp_len, &pcr_error) > pcr_is_ok) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "file \"%s\" contains invalid characters %s, cannot be copied from \"%s\" in phar %s", newfile, pcr_error, oldfile, phar_obj->archive->fname); RETURN_FALSE; } newfile_len = tmp_len; if (phar_obj->archive->is_persistent) { if (FAILURE == phar_copy_on_write(&(phar_obj->archive))) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname); return; } /* re-populate with copied-on-write entry */ oldentry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, oldfile, (uint) oldfile_len); } memcpy((void *) &newentry, oldentry, sizeof(phar_entry_info)); if (Z_TYPE(newentry.metadata) != IS_UNDEF) { zval_copy_ctor(&newentry.metadata); newentry.metadata_str.s = NULL; } newentry.filename = estrndup(newfile, newfile_len); newentry.filename_len = newfile_len; newentry.fp_refcount = 0; if (oldentry->fp_type != PHAR_FP) { if (FAILURE == phar_copy_entry_fp(oldentry, &newentry, &error)) { efree(newentry.filename); php_stream_close(newentry.fp); zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); return; } } zend_hash_str_add_mem(&oldentry->phar->manifest, newfile, newfile_len, &newentry, sizeof(phar_entry_info)); phar_obj->archive->is_modified = 1; phar_flush(phar_obj->archive, 0, 0, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } RETURN_TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #71860: Require valid paths for phar filenames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_METHOD(Phar, addFile) { char *fname, *localname = NULL; size_t fname_len, localname_len = 0; php_stream *resource; zval zresource; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|s", &fname, &fname_len, &localname, &localname_len) == FAILURE) { return; } #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "phar error: unable to open file \"%s\" to add to phar archive, safe_mode restrictions prevent this", fname); return; } #endif if (!strstr(fname, "://") && php_check_open_basedir(fname)) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "phar error: unable to open file \"%s\" to add to phar archive, open_basedir restrictions prevent this", fname); return; } if (!(resource = php_stream_open_wrapper(fname, "rb", 0, NULL))) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "phar error: unable to open file \"%s\" to add to phar archive", fname); return; } if (localname) { fname = localname; fname_len = localname_len; } php_stream_to_zval(resource, &zresource); phar_add_file(&(phar_obj->archive), fname, fname_len, NULL, 0, &zresource); zval_ptr_dtor(&zresource); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #71860: Require valid paths for phar filenames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_METHOD(Phar, loadPhar) { char *fname, *alias = NULL, *error; size_t fname_len, alias_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|s!", &fname, &fname_len, &alias, &alias_len) == FAILURE) { return; } phar_request_initialize(); RETVAL_BOOL(phar_open_from_filename(fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, &error) == SUCCESS); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } } /* }}} */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #71860: Require valid paths for phar filenames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_METHOD(Phar, isValidPharFilename) { char *fname; const char *ext_str; size_t fname_len; int ext_len, is_executable; zend_bool executable = 1; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|b", &fname, &fname_len, &executable) == FAILURE) { return; } is_executable = executable; RETVAL_BOOL(phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, is_executable, 2, 1) == SUCCESS); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #71860: Require valid paths for phar filenames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void php_snmp_error(zval *object, const char *docref, int type, const char *format, ...) { va_list args; php_snmp_object *snmp_object = NULL; if (object) { snmp_object = Z_SNMP_P(object); if (type == PHP_SNMP_ERRNO_NOERROR) { memset(snmp_object->snmp_errstr, 0, sizeof(snmp_object->snmp_errstr)); } else { va_start(args, format); vsnprintf(snmp_object->snmp_errstr, sizeof(snmp_object->snmp_errstr) - 1, format, args); va_end(args); } snmp_object->snmp_errno = type; } if (type == PHP_SNMP_ERRNO_NOERROR) { return; } if (object && (snmp_object->exceptions_enabled & type)) { zend_throw_exception_ex(php_snmp_exception_ce, type, snmp_object->snmp_errstr); } else { va_start(args, format); php_verror(docref, "", E_WARNING, format, args); va_end(args); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fixed bug #71704 php_snmp_error() Format String Vulnerability'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: file_check_mem(struct magic_set *ms, unsigned int level) { size_t len; if (level >= ms->c.len) { len = (ms->c.len += 20) * sizeof(*ms->c.li); ms->c.li = CAST(struct level_info *, (ms->c.li == NULL) ? emalloc(len) : erealloc(ms->c.li, len)); if (ms->c.li == NULL) { file_oomem(ms, len); return -1; } } ms->c.li[level].got_match = 0; #ifdef ENABLE_CONDITIONALS ms->c.li[level].last_match = 0; ms->c.li[level].last_cond = COND_NONE; #endif /* ENABLE_CONDITIONALS */ return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fixed bug #71527 Buffer over-write in finfo_open with malformed magic file The actual fix is applying the upstream patch from https://github.com/file/file/commit/6713ca45e7757297381f4b4cdb9cf5e624a9ad36'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static long ext4_zero_range(struct file *file, loff_t offset, loff_t len, int mode) { struct inode *inode = file_inode(file); handle_t *handle = NULL; unsigned int max_blocks; loff_t new_size = 0; int ret = 0; int flags; int credits; int partial_begin, partial_end; loff_t start, end; ext4_lblk_t lblk; struct address_space *mapping = inode->i_mapping; unsigned int blkbits = inode->i_blkbits; trace_ext4_zero_range(inode, offset, len, mode); if (!S_ISREG(inode->i_mode)) return -EINVAL; /* Call ext4_force_commit to flush all data in case of data=journal. */ if (ext4_should_journal_data(inode)) { ret = ext4_force_commit(inode->i_sb); if (ret) return ret; } /* * Write out all dirty pages to avoid race conditions * Then release them. */ if (mapping->nrpages && mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) { ret = filemap_write_and_wait_range(mapping, offset, offset + len - 1); if (ret) return ret; } /* * Round up offset. This is not fallocate, we neet to zero out * blocks, so convert interior block aligned part of the range to * unwritten and possibly manually zero out unaligned parts of the * range. */ start = round_up(offset, 1 << blkbits); end = round_down((offset + len), 1 << blkbits); if (start < offset || end > offset + len) return -EINVAL; partial_begin = offset & ((1 << blkbits) - 1); partial_end = (offset + len) & ((1 << blkbits) - 1); lblk = start >> blkbits; max_blocks = (end >> blkbits); if (max_blocks < lblk) max_blocks = 0; else max_blocks -= lblk; mutex_lock(&inode->i_mutex); /* * Indirect files do not support unwritten extnets */ if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) { ret = -EOPNOTSUPP; goto out_mutex; } if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > i_size_read(inode)) { new_size = offset + len; ret = inode_newsize_ok(inode, new_size); if (ret) goto out_mutex; } flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT; if (mode & FALLOC_FL_KEEP_SIZE) flags |= EXT4_GET_BLOCKS_KEEP_SIZE; /* Preallocate the range including the unaligned edges */ if (partial_begin || partial_end) { ret = ext4_alloc_file_blocks(file, round_down(offset, 1 << blkbits) >> blkbits, (round_up((offset + len), 1 << blkbits) - round_down(offset, 1 << blkbits)) >> blkbits, new_size, flags, mode); if (ret) goto out_mutex; } /* Zero range excluding the unaligned edges */ if (max_blocks > 0) { flags |= (EXT4_GET_BLOCKS_CONVERT_UNWRITTEN | EXT4_EX_NOCACHE); /* Now release the pages and zero block aligned part of pages*/ truncate_pagecache_range(inode, start, end - 1); inode->i_mtime = inode->i_ctime = ext4_current_time(inode); /* Wait all existing dio workers, newcomers will block on i_mutex */ ext4_inode_block_unlocked_dio(inode); inode_dio_wait(inode); ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size, flags, mode); if (ret) goto out_dio; } if (!partial_begin && !partial_end) goto out_dio; /* * In worst case we have to writeout two nonadjacent unwritten * blocks and update the inode */ credits = (2 * ext4_ext_index_trans_blocks(inode, 2)) + 1; if (ext4_should_journal_data(inode)) credits += 2; handle = ext4_journal_start(inode, EXT4_HT_MISC, credits); if (IS_ERR(handle)) { ret = PTR_ERR(handle); ext4_std_error(inode->i_sb, ret); goto out_dio; } inode->i_mtime = inode->i_ctime = ext4_current_time(inode); if (new_size) { ext4_update_inode_size(inode, new_size); } else { /* * Mark that we allocate beyond EOF so the subsequent truncate * can proceed even if the new size is the same as i_size. */ if ((offset + len) > i_size_read(inode)) ext4_set_inode_flag(inode, EXT4_INODE_EOFBLOCKS); } ext4_mark_inode_dirty(handle, inode); /* Zero out partial block at the edges of the range */ ret = ext4_zero_partial_blocks(handle, inode, offset, len); if (file->f_flags & O_SYNC) ext4_handle_sync(handle); ext4_journal_stop(handle); out_dio: ext4_inode_resume_unlocked_dio(inode); out_mutex: mutex_unlock(&inode->i_mutex); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'ext4: fix races between page faults and hole punching Currently, page faults and hole punching are completely unsynchronized. This can result in page fault faulting in a page into a range that we are punching after truncate_pagecache_range() has been called and thus we can end up with a page mapped to disk blocks that will be shortly freed. Filesystem corruption will shortly follow. Note that the same race is avoided for truncate by checking page fault offset against i_size but there isn't similar mechanism available for punching holes. Fix the problem by creating new rw semaphore i_mmap_sem in inode and grab it for writing over truncate, hole punching, and other functions removing blocks from extent tree and for read over page faults. We cannot easily use i_data_sem for this since that ranks below transaction start and we need something ranking above it so that it can be held over the whole truncate / hole punching operation. Also remove various workarounds we had in the code to reduce race window when page fault could have created pages with stale mapping information. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ext4_collapse_range(struct inode *inode, loff_t offset, loff_t len) { struct super_block *sb = inode->i_sb; ext4_lblk_t punch_start, punch_stop; handle_t *handle; unsigned int credits; loff_t new_size, ioffset; int ret; /* * We need to test this early because xfstests assumes that a * collapse range of (0, 1) will return EOPNOTSUPP if the file * system does not support collapse range. */ if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) return -EOPNOTSUPP; /* Collapse range works only on fs block size aligned offsets. */ if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) || len & (EXT4_CLUSTER_SIZE(sb) - 1)) return -EINVAL; if (!S_ISREG(inode->i_mode)) return -EINVAL; trace_ext4_collapse_range(inode, offset, len); punch_start = offset >> EXT4_BLOCK_SIZE_BITS(sb); punch_stop = (offset + len) >> EXT4_BLOCK_SIZE_BITS(sb); /* Call ext4_force_commit to flush all data in case of data=journal. */ if (ext4_should_journal_data(inode)) { ret = ext4_force_commit(inode->i_sb); if (ret) return ret; } /* * Need to round down offset to be aligned with page size boundary * for page size > block size. */ ioffset = round_down(offset, PAGE_SIZE); /* Write out all dirty pages */ ret = filemap_write_and_wait_range(inode->i_mapping, ioffset, LLONG_MAX); if (ret) return ret; /* Take mutex lock */ mutex_lock(&inode->i_mutex); /* * There is no need to overlap collapse range with EOF, in which case * it is effectively a truncate operation */ if (offset + len >= i_size_read(inode)) { ret = -EINVAL; goto out_mutex; } /* Currently just for extent based files */ if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) { ret = -EOPNOTSUPP; goto out_mutex; } truncate_pagecache(inode, ioffset); /* Wait for existing dio to complete */ ext4_inode_block_unlocked_dio(inode); inode_dio_wait(inode); credits = ext4_writepage_trans_blocks(inode); handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits); if (IS_ERR(handle)) { ret = PTR_ERR(handle); goto out_dio; } down_write(&EXT4_I(inode)->i_data_sem); ext4_discard_preallocations(inode); ret = ext4_es_remove_extent(inode, punch_start, EXT_MAX_BLOCKS - punch_start); if (ret) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } ret = ext4_ext_remove_space(inode, punch_start, punch_stop - 1); if (ret) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } ext4_discard_preallocations(inode); ret = ext4_ext_shift_extents(inode, handle, punch_stop, punch_stop - punch_start, SHIFT_LEFT); if (ret) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } new_size = i_size_read(inode) - len; i_size_write(inode, new_size); EXT4_I(inode)->i_disksize = new_size; up_write(&EXT4_I(inode)->i_data_sem); if (IS_SYNC(inode)) ext4_handle_sync(handle); inode->i_mtime = inode->i_ctime = ext4_current_time(inode); ext4_mark_inode_dirty(handle, inode); out_stop: ext4_journal_stop(handle); out_dio: ext4_inode_resume_unlocked_dio(inode); out_mutex: mutex_unlock(&inode->i_mutex); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'ext4: fix races between page faults and hole punching Currently, page faults and hole punching are completely unsynchronized. This can result in page fault faulting in a page into a range that we are punching after truncate_pagecache_range() has been called and thus we can end up with a page mapped to disk blocks that will be shortly freed. Filesystem corruption will shortly follow. Note that the same race is avoided for truncate by checking page fault offset against i_size but there isn't similar mechanism available for punching holes. Fix the problem by creating new rw semaphore i_mmap_sem in inode and grab it for writing over truncate, hole punching, and other functions removing blocks from extent tree and for read over page faults. We cannot easily use i_data_sem for this since that ranks below transaction start and we need something ranking above it so that it can be held over the whole truncate / hole punching operation. Also remove various workarounds we had in the code to reduce race window when page fault could have created pages with stale mapping information. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ext4_insert_range(struct inode *inode, loff_t offset, loff_t len) { struct super_block *sb = inode->i_sb; handle_t *handle; struct ext4_ext_path *path; struct ext4_extent *extent; ext4_lblk_t offset_lblk, len_lblk, ee_start_lblk = 0; unsigned int credits, ee_len; int ret = 0, depth, split_flag = 0; loff_t ioffset; /* * We need to test this early because xfstests assumes that an * insert range of (0, 1) will return EOPNOTSUPP if the file * system does not support insert range. */ if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) return -EOPNOTSUPP; /* Insert range works only on fs block size aligned offsets. */ if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) || len & (EXT4_CLUSTER_SIZE(sb) - 1)) return -EINVAL; if (!S_ISREG(inode->i_mode)) return -EOPNOTSUPP; trace_ext4_insert_range(inode, offset, len); offset_lblk = offset >> EXT4_BLOCK_SIZE_BITS(sb); len_lblk = len >> EXT4_BLOCK_SIZE_BITS(sb); /* Call ext4_force_commit to flush all data in case of data=journal */ if (ext4_should_journal_data(inode)) { ret = ext4_force_commit(inode->i_sb); if (ret) return ret; } /* * Need to round down to align start offset to page size boundary * for page size > block size. */ ioffset = round_down(offset, PAGE_SIZE); /* Write out all dirty pages */ ret = filemap_write_and_wait_range(inode->i_mapping, ioffset, LLONG_MAX); if (ret) return ret; /* Take mutex lock */ mutex_lock(&inode->i_mutex); /* Currently just for extent based files */ if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) { ret = -EOPNOTSUPP; goto out_mutex; } /* Check for wrap through zero */ if (inode->i_size + len > inode->i_sb->s_maxbytes) { ret = -EFBIG; goto out_mutex; } /* Offset should be less than i_size */ if (offset >= i_size_read(inode)) { ret = -EINVAL; goto out_mutex; } truncate_pagecache(inode, ioffset); /* Wait for existing dio to complete */ ext4_inode_block_unlocked_dio(inode); inode_dio_wait(inode); credits = ext4_writepage_trans_blocks(inode); handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits); if (IS_ERR(handle)) { ret = PTR_ERR(handle); goto out_dio; } /* Expand file to avoid data loss if there is error while shifting */ inode->i_size += len; EXT4_I(inode)->i_disksize += len; inode->i_mtime = inode->i_ctime = ext4_current_time(inode); ret = ext4_mark_inode_dirty(handle, inode); if (ret) goto out_stop; down_write(&EXT4_I(inode)->i_data_sem); ext4_discard_preallocations(inode); path = ext4_find_extent(inode, offset_lblk, NULL, 0); if (IS_ERR(path)) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } depth = ext_depth(inode); extent = path[depth].p_ext; if (extent) { ee_start_lblk = le32_to_cpu(extent->ee_block); ee_len = ext4_ext_get_actual_len(extent); /* * If offset_lblk is not the starting block of extent, split * the extent @offset_lblk */ if ((offset_lblk > ee_start_lblk) && (offset_lblk < (ee_start_lblk + ee_len))) { if (ext4_ext_is_unwritten(extent)) split_flag = EXT4_EXT_MARK_UNWRIT1 | EXT4_EXT_MARK_UNWRIT2; ret = ext4_split_extent_at(handle, inode, &path, offset_lblk, split_flag, EXT4_EX_NOCACHE | EXT4_GET_BLOCKS_PRE_IO | EXT4_GET_BLOCKS_METADATA_NOFAIL); } ext4_ext_drop_refs(path); kfree(path); if (ret < 0) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } } ret = ext4_es_remove_extent(inode, offset_lblk, EXT_MAX_BLOCKS - offset_lblk); if (ret) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } /* * if offset_lblk lies in a hole which is at start of file, use * ee_start_lblk to shift extents */ ret = ext4_ext_shift_extents(inode, handle, ee_start_lblk > offset_lblk ? ee_start_lblk : offset_lblk, len_lblk, SHIFT_RIGHT); up_write(&EXT4_I(inode)->i_data_sem); if (IS_SYNC(inode)) ext4_handle_sync(handle); out_stop: ext4_journal_stop(handle); out_dio: ext4_inode_resume_unlocked_dio(inode); out_mutex: mutex_unlock(&inode->i_mutex); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'ext4: fix races between page faults and hole punching Currently, page faults and hole punching are completely unsynchronized. This can result in page fault faulting in a page into a range that we are punching after truncate_pagecache_range() has been called and thus we can end up with a page mapped to disk blocks that will be shortly freed. Filesystem corruption will shortly follow. Note that the same race is avoided for truncate by checking page fault offset against i_size but there isn't similar mechanism available for punching holes. Fix the problem by creating new rw semaphore i_mmap_sem in inode and grab it for writing over truncate, hole punching, and other functions removing blocks from extent tree and for read over page faults. We cannot easily use i_data_sem for this since that ranks below transaction start and we need something ranking above it so that it can be held over the whole truncate / hole punching operation. Also remove various workarounds we had in the code to reduce race window when page fault could have created pages with stale mapping information. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int ext4_dax_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf) { return dax_mkwrite(vma, vmf, ext4_get_block_dax, ext4_end_io_unwritten); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'ext4: fix races between page faults and hole punching Currently, page faults and hole punching are completely unsynchronized. This can result in page fault faulting in a page into a range that we are punching after truncate_pagecache_range() has been called and thus we can end up with a page mapped to disk blocks that will be shortly freed. Filesystem corruption will shortly follow. Note that the same race is avoided for truncate by checking page fault offset against i_size but there isn't similar mechanism available for punching holes. Fix the problem by creating new rw semaphore i_mmap_sem in inode and grab it for writing over truncate, hole punching, and other functions removing blocks from extent tree and for read over page faults. We cannot easily use i_data_sem for this since that ranks below transaction start and we need something ranking above it so that it can be held over the whole truncate / hole punching operation. Also remove various workarounds we had in the code to reduce race window when page fault could have created pages with stale mapping information. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ext4_setattr(struct dentry *dentry, struct iattr *attr) { struct inode *inode = d_inode(dentry); int error, rc = 0; int orphan = 0; const unsigned int ia_valid = attr->ia_valid; error = inode_change_ok(inode, attr); if (error) return error; if (is_quota_modification(inode, attr)) { error = dquot_initialize(inode); if (error) return error; } if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) || (ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) { handle_t *handle; /* (user+group)*(old+new) structure, inode write (sb, * inode block, ? - but truncate inode update has it) */ handle = ext4_journal_start(inode, EXT4_HT_QUOTA, (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) + EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3); if (IS_ERR(handle)) { error = PTR_ERR(handle); goto err_out; } error = dquot_transfer(inode, attr); if (error) { ext4_journal_stop(handle); return error; } /* Update corresponding info in inode so that everything is in * one transaction */ if (attr->ia_valid & ATTR_UID) inode->i_uid = attr->ia_uid; if (attr->ia_valid & ATTR_GID) inode->i_gid = attr->ia_gid; error = ext4_mark_inode_dirty(handle, inode); ext4_journal_stop(handle); } if (attr->ia_valid & ATTR_SIZE) { handle_t *handle; loff_t oldsize = inode->i_size; int shrink = (attr->ia_size <= inode->i_size); if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) { struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); if (attr->ia_size > sbi->s_bitmap_maxbytes) return -EFBIG; } if (!S_ISREG(inode->i_mode)) return -EINVAL; if (IS_I_VERSION(inode) && attr->ia_size != inode->i_size) inode_inc_iversion(inode); if (ext4_should_order_data(inode) && (attr->ia_size < inode->i_size)) { error = ext4_begin_ordered_truncate(inode, attr->ia_size); if (error) goto err_out; } if (attr->ia_size != inode->i_size) { handle = ext4_journal_start(inode, EXT4_HT_INODE, 3); if (IS_ERR(handle)) { error = PTR_ERR(handle); goto err_out; } if (ext4_handle_valid(handle) && shrink) { error = ext4_orphan_add(handle, inode); orphan = 1; } /* * Update c/mtime on truncate up, ext4_truncate() will * update c/mtime in shrink case below */ if (!shrink) { inode->i_mtime = ext4_current_time(inode); inode->i_ctime = inode->i_mtime; } down_write(&EXT4_I(inode)->i_data_sem); EXT4_I(inode)->i_disksize = attr->ia_size; rc = ext4_mark_inode_dirty(handle, inode); if (!error) error = rc; /* * We have to update i_size under i_data_sem together * with i_disksize to avoid races with writeback code * running ext4_wb_update_i_disksize(). */ if (!error) i_size_write(inode, attr->ia_size); up_write(&EXT4_I(inode)->i_data_sem); ext4_journal_stop(handle); if (error) { if (orphan) ext4_orphan_del(NULL, inode); goto err_out; } } if (!shrink) pagecache_isize_extended(inode, oldsize, inode->i_size); /* * Blocks are going to be removed from the inode. Wait * for dio in flight. Temporarily disable * dioread_nolock to prevent livelock. */ if (orphan) { if (!ext4_should_journal_data(inode)) { ext4_inode_block_unlocked_dio(inode); inode_dio_wait(inode); ext4_inode_resume_unlocked_dio(inode); } else ext4_wait_for_tail_page_commit(inode); } /* * Truncate pagecache after we've waited for commit * in data=journal mode to make pages freeable. */ truncate_pagecache(inode, inode->i_size); if (shrink) ext4_truncate(inode); } if (!rc) { setattr_copy(inode, attr); mark_inode_dirty(inode); } /* * If the call to ext4_truncate failed to get a transaction handle at * all, we need to clean up the in-core orphan list manually. */ if (orphan && inode->i_nlink) ext4_orphan_del(NULL, inode); if (!rc && (ia_valid & ATTR_MODE)) rc = posix_acl_chmod(inode, inode->i_mode); err_out: ext4_std_error(inode->i_sb, error); if (!error) error = rc; return error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'ext4: fix races between page faults and hole punching Currently, page faults and hole punching are completely unsynchronized. This can result in page fault faulting in a page into a range that we are punching after truncate_pagecache_range() has been called and thus we can end up with a page mapped to disk blocks that will be shortly freed. Filesystem corruption will shortly follow. Note that the same race is avoided for truncate by checking page fault offset against i_size but there isn't similar mechanism available for punching holes. Fix the problem by creating new rw semaphore i_mmap_sem in inode and grab it for writing over truncate, hole punching, and other functions removing blocks from extent tree and for read over page faults. We cannot easily use i_data_sem for this since that ranks below transaction start and we need something ranking above it so that it can be held over the whole truncate / hole punching operation. Also remove various workarounds we had in the code to reduce race window when page fault could have created pages with stale mapping information. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: long ext4_fallocate(struct file *file, int mode, loff_t offset, loff_t len) { struct inode *inode = file_inode(file); loff_t new_size = 0; unsigned int max_blocks; int ret = 0; int flags; ext4_lblk_t lblk; unsigned int blkbits = inode->i_blkbits; /* * Encrypted inodes can't handle collapse range or insert * range since we would need to re-encrypt blocks with a * different IV or XTS tweak (which are based on the logical * block number). * * XXX It's not clear why zero range isn't working, but we'll * leave it disabled for encrypted inodes for now. This is a * bug we should fix.... */ if (ext4_encrypted_inode(inode) && (mode & (FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_INSERT_RANGE | FALLOC_FL_ZERO_RANGE))) return -EOPNOTSUPP; /* Return error if mode is not supported */ if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE | FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_ZERO_RANGE | FALLOC_FL_INSERT_RANGE)) return -EOPNOTSUPP; if (mode & FALLOC_FL_PUNCH_HOLE) return ext4_punch_hole(inode, offset, len); ret = ext4_convert_inline_data(inode); if (ret) return ret; if (mode & FALLOC_FL_COLLAPSE_RANGE) return ext4_collapse_range(inode, offset, len); if (mode & FALLOC_FL_INSERT_RANGE) return ext4_insert_range(inode, offset, len); if (mode & FALLOC_FL_ZERO_RANGE) return ext4_zero_range(file, offset, len, mode); trace_ext4_fallocate_enter(inode, offset, len, mode); lblk = offset >> blkbits; /* * We can't just convert len to max_blocks because * If blocksize = 4096 offset = 3072 and len = 2048 */ max_blocks = (EXT4_BLOCK_ALIGN(len + offset, blkbits) >> blkbits) - lblk; flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT; if (mode & FALLOC_FL_KEEP_SIZE) flags |= EXT4_GET_BLOCKS_KEEP_SIZE; mutex_lock(&inode->i_mutex); /* * We only support preallocation for extent-based files only */ if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) { ret = -EOPNOTSUPP; goto out; } if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > i_size_read(inode)) { new_size = offset + len; ret = inode_newsize_ok(inode, new_size); if (ret) goto out; } ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size, flags, mode); if (ret) goto out; if (file->f_flags & O_SYNC && EXT4_SB(inode->i_sb)->s_journal) { ret = jbd2_complete_transaction(EXT4_SB(inode->i_sb)->s_journal, EXT4_I(inode)->i_sync_tid); } out: mutex_unlock(&inode->i_mutex); trace_ext4_fallocate_exit(inode, offset, max_blocks, ret); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'ext4: move unlocked dio protection from ext4_alloc_file_blocks() Currently ext4_alloc_file_blocks() was handling protection against unlocked DIO. However we now need to sometimes call it under i_mmap_sem and sometimes not and DIO protection ranks above it (although strictly speaking this cannot currently create any deadlocks). Also ext4_zero_range() was actually getting & releasing unlocked DIO protection twice in some cases. Luckily it didn't introduce any real bug but it was a land mine waiting to be stepped on. So move DIO protection out from ext4_alloc_file_blocks() into the two callsites. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int ext4_alloc_file_blocks(struct file *file, ext4_lblk_t offset, ext4_lblk_t len, loff_t new_size, int flags, int mode) { struct inode *inode = file_inode(file); handle_t *handle; int ret = 0; int ret2 = 0; int retries = 0; int depth = 0; struct ext4_map_blocks map; unsigned int credits; loff_t epos; map.m_lblk = offset; map.m_len = len; /* * Don't normalize the request if it can fit in one extent so * that it doesn't get unnecessarily split into multiple * extents. */ if (len <= EXT_UNWRITTEN_MAX_LEN) flags |= EXT4_GET_BLOCKS_NO_NORMALIZE; /* Wait all existing dio workers, newcomers will block on i_mutex */ ext4_inode_block_unlocked_dio(inode); inode_dio_wait(inode); /* * credits to insert 1 extent into extent tree */ credits = ext4_chunk_trans_blocks(inode, len); /* * We can only call ext_depth() on extent based inodes */ if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) depth = ext_depth(inode); else depth = -1; retry: while (ret >= 0 && len) { /* * Recalculate credits when extent tree depth changes. */ if (depth >= 0 && depth != ext_depth(inode)) { credits = ext4_chunk_trans_blocks(inode, len); depth = ext_depth(inode); } handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, credits); if (IS_ERR(handle)) { ret = PTR_ERR(handle); break; } ret = ext4_map_blocks(handle, inode, &map, flags); if (ret <= 0) { ext4_debug("inode #%lu: block %u: len %u: " "ext4_ext_map_blocks returned %d", inode->i_ino, map.m_lblk, map.m_len, ret); ext4_mark_inode_dirty(handle, inode); ret2 = ext4_journal_stop(handle); break; } map.m_lblk += ret; map.m_len = len = len - ret; epos = (loff_t)map.m_lblk << inode->i_blkbits; inode->i_ctime = ext4_current_time(inode); if (new_size) { if (epos > new_size) epos = new_size; if (ext4_update_inode_size(inode, epos) & 0x1) inode->i_mtime = inode->i_ctime; } else { if (epos > inode->i_size) ext4_set_inode_flag(inode, EXT4_INODE_EOFBLOCKS); } ext4_mark_inode_dirty(handle, inode); ret2 = ext4_journal_stop(handle); if (ret2) break; } if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries)) { ret = 0; goto retry; } ext4_inode_resume_unlocked_dio(inode); return ret > 0 ? ret2 : ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'ext4: move unlocked dio protection from ext4_alloc_file_blocks() Currently ext4_alloc_file_blocks() was handling protection against unlocked DIO. However we now need to sometimes call it under i_mmap_sem and sometimes not and DIO protection ranks above it (although strictly speaking this cannot currently create any deadlocks). Also ext4_zero_range() was actually getting & releasing unlocked DIO protection twice in some cases. Luckily it didn't introduce any real bug but it was a land mine waiting to be stepped on. So move DIO protection out from ext4_alloc_file_blocks() into the two callsites. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ext4_collapse_range(struct inode *inode, loff_t offset, loff_t len) { struct super_block *sb = inode->i_sb; ext4_lblk_t punch_start, punch_stop; handle_t *handle; unsigned int credits; loff_t new_size, ioffset; int ret; /* * We need to test this early because xfstests assumes that a * collapse range of (0, 1) will return EOPNOTSUPP if the file * system does not support collapse range. */ if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) return -EOPNOTSUPP; /* Collapse range works only on fs block size aligned offsets. */ if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) || len & (EXT4_CLUSTER_SIZE(sb) - 1)) return -EINVAL; if (!S_ISREG(inode->i_mode)) return -EINVAL; trace_ext4_collapse_range(inode, offset, len); punch_start = offset >> EXT4_BLOCK_SIZE_BITS(sb); punch_stop = (offset + len) >> EXT4_BLOCK_SIZE_BITS(sb); /* Call ext4_force_commit to flush all data in case of data=journal. */ if (ext4_should_journal_data(inode)) { ret = ext4_force_commit(inode->i_sb); if (ret) return ret; } /* * Need to round down offset to be aligned with page size boundary * for page size > block size. */ ioffset = round_down(offset, PAGE_SIZE); /* Write out all dirty pages */ ret = filemap_write_and_wait_range(inode->i_mapping, ioffset, LLONG_MAX); if (ret) return ret; /* Take mutex lock */ mutex_lock(&inode->i_mutex); /* * There is no need to overlap collapse range with EOF, in which case * it is effectively a truncate operation */ if (offset + len >= i_size_read(inode)) { ret = -EINVAL; goto out_mutex; } /* Currently just for extent based files */ if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) { ret = -EOPNOTSUPP; goto out_mutex; } /* Wait for existing dio to complete */ ext4_inode_block_unlocked_dio(inode); inode_dio_wait(inode); /* * Prevent page faults from reinstantiating pages we have released from * page cache. */ down_write(&EXT4_I(inode)->i_mmap_sem); truncate_pagecache(inode, ioffset); credits = ext4_writepage_trans_blocks(inode); handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits); if (IS_ERR(handle)) { ret = PTR_ERR(handle); goto out_mmap; } down_write(&EXT4_I(inode)->i_data_sem); ext4_discard_preallocations(inode); ret = ext4_es_remove_extent(inode, punch_start, EXT_MAX_BLOCKS - punch_start); if (ret) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } ret = ext4_ext_remove_space(inode, punch_start, punch_stop - 1); if (ret) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } ext4_discard_preallocations(inode); ret = ext4_ext_shift_extents(inode, handle, punch_stop, punch_stop - punch_start, SHIFT_LEFT); if (ret) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } new_size = i_size_read(inode) - len; i_size_write(inode, new_size); EXT4_I(inode)->i_disksize = new_size; up_write(&EXT4_I(inode)->i_data_sem); if (IS_SYNC(inode)) ext4_handle_sync(handle); inode->i_mtime = inode->i_ctime = ext4_current_time(inode); ext4_mark_inode_dirty(handle, inode); out_stop: ext4_journal_stop(handle); out_mmap: up_write(&EXT4_I(inode)->i_mmap_sem); ext4_inode_resume_unlocked_dio(inode); out_mutex: mutex_unlock(&inode->i_mutex); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'ext4: fix races between buffered IO and collapse / insert range Current code implementing FALLOC_FL_COLLAPSE_RANGE and FALLOC_FL_INSERT_RANGE is prone to races with buffered writes and page faults. If buffered write or write via mmap manages to squeeze between filemap_write_and_wait_range() and truncate_pagecache() in the fallocate implementations, the written data is simply discarded by truncate_pagecache() although it should have been shifted. Fix the problem by moving filemap_write_and_wait_range() call inside i_mutex and i_mmap_sem. That way we are protected against races with both buffered writes and page faults. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static long ext4_zero_range(struct file *file, loff_t offset, loff_t len, int mode) { struct inode *inode = file_inode(file); handle_t *handle = NULL; unsigned int max_blocks; loff_t new_size = 0; int ret = 0; int flags; int credits; int partial_begin, partial_end; loff_t start, end; ext4_lblk_t lblk; unsigned int blkbits = inode->i_blkbits; trace_ext4_zero_range(inode, offset, len, mode); if (!S_ISREG(inode->i_mode)) return -EINVAL; /* Call ext4_force_commit to flush all data in case of data=journal. */ if (ext4_should_journal_data(inode)) { ret = ext4_force_commit(inode->i_sb); if (ret) return ret; } /* * Round up offset. This is not fallocate, we neet to zero out * blocks, so convert interior block aligned part of the range to * unwritten and possibly manually zero out unaligned parts of the * range. */ start = round_up(offset, 1 << blkbits); end = round_down((offset + len), 1 << blkbits); if (start < offset || end > offset + len) return -EINVAL; partial_begin = offset & ((1 << blkbits) - 1); partial_end = (offset + len) & ((1 << blkbits) - 1); lblk = start >> blkbits; max_blocks = (end >> blkbits); if (max_blocks < lblk) max_blocks = 0; else max_blocks -= lblk; mutex_lock(&inode->i_mutex); /* * Indirect files do not support unwritten extnets */ if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) { ret = -EOPNOTSUPP; goto out_mutex; } if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > i_size_read(inode)) { new_size = offset + len; ret = inode_newsize_ok(inode, new_size); if (ret) goto out_mutex; } flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT; if (mode & FALLOC_FL_KEEP_SIZE) flags |= EXT4_GET_BLOCKS_KEEP_SIZE; /* Wait all existing dio workers, newcomers will block on i_mutex */ ext4_inode_block_unlocked_dio(inode); inode_dio_wait(inode); /* Preallocate the range including the unaligned edges */ if (partial_begin || partial_end) { ret = ext4_alloc_file_blocks(file, round_down(offset, 1 << blkbits) >> blkbits, (round_up((offset + len), 1 << blkbits) - round_down(offset, 1 << blkbits)) >> blkbits, new_size, flags, mode); if (ret) goto out_dio; } /* Zero range excluding the unaligned edges */ if (max_blocks > 0) { flags |= (EXT4_GET_BLOCKS_CONVERT_UNWRITTEN | EXT4_EX_NOCACHE); /* * Prevent page faults from reinstantiating pages we have * released from page cache. */ down_write(&EXT4_I(inode)->i_mmap_sem); /* Now release the pages and zero block aligned part of pages */ truncate_pagecache_range(inode, start, end - 1); inode->i_mtime = inode->i_ctime = ext4_current_time(inode); ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size, flags, mode); up_write(&EXT4_I(inode)->i_mmap_sem); if (ret) goto out_dio; } if (!partial_begin && !partial_end) goto out_dio; /* * In worst case we have to writeout two nonadjacent unwritten * blocks and update the inode */ credits = (2 * ext4_ext_index_trans_blocks(inode, 2)) + 1; if (ext4_should_journal_data(inode)) credits += 2; handle = ext4_journal_start(inode, EXT4_HT_MISC, credits); if (IS_ERR(handle)) { ret = PTR_ERR(handle); ext4_std_error(inode->i_sb, ret); goto out_dio; } inode->i_mtime = inode->i_ctime = ext4_current_time(inode); if (new_size) { ext4_update_inode_size(inode, new_size); } else { /* * Mark that we allocate beyond EOF so the subsequent truncate * can proceed even if the new size is the same as i_size. */ if ((offset + len) > i_size_read(inode)) ext4_set_inode_flag(inode, EXT4_INODE_EOFBLOCKS); } ext4_mark_inode_dirty(handle, inode); /* Zero out partial block at the edges of the range */ ret = ext4_zero_partial_blocks(handle, inode, offset, len); if (file->f_flags & O_SYNC) ext4_handle_sync(handle); ext4_journal_stop(handle); out_dio: ext4_inode_resume_unlocked_dio(inode); out_mutex: mutex_unlock(&inode->i_mutex); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'ext4: fix races of writeback with punch hole and zero range When doing delayed allocation, update of on-disk inode size is postponed until IO submission time. However hole punch or zero range fallocate calls can end up discarding the tail page cache page and thus on-disk inode size would never be properly updated. Make sure the on-disk inode size is updated before truncating page cache. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: srtp_unprotect_aead (srtp_ctx_t *ctx, srtp_stream_ctx_t *stream, int delta, xtd_seq_num_t est, void *srtp_hdr, unsigned int *pkt_octet_len) { srtp_hdr_t *hdr = (srtp_hdr_t*)srtp_hdr; uint32_t *enc_start; /* pointer to start of encrypted portion */ unsigned int enc_octet_len = 0; /* number of octets in encrypted portion */ v128_t iv; err_status_t status; int tag_len; unsigned int aad_len; debug_print(mod_srtp, "function srtp_unprotect_aead", NULL); #ifdef NO_64BIT_MATH debug_print2(mod_srtp, "estimated u_packet index: %08x%08x", high32(est), low32(est)); #else debug_print(mod_srtp, "estimated u_packet index: %016llx", est); #endif /* get tag length from stream */ tag_len = auth_get_tag_length(stream->rtp_auth); /* * AEAD uses a new IV formation method */ srtp_calc_aead_iv(stream, &iv, &est, hdr); status = cipher_set_iv(stream->rtp_cipher, &iv, direction_decrypt); if (status) { return err_status_cipher_fail; } /* * find starting point for decryption and length of data to be * decrypted - the encrypted portion starts after the rtp header * extension, if present; otherwise, it starts after the last csrc, * if any are present */ enc_start = (uint32_t*)hdr + uint32s_in_rtp_header + hdr->cc; if (hdr->x == 1) { srtp_hdr_xtnd_t *xtn_hdr = (srtp_hdr_xtnd_t*)enc_start; enc_start += (ntohs(xtn_hdr->length) + 1); } if (!((uint8_t*)enc_start < (uint8_t*)hdr + *pkt_octet_len)) return err_status_parse_err; /* * We pass the tag down to the cipher when doing GCM mode */ enc_octet_len = (unsigned int)(*pkt_octet_len - ((uint8_t*)enc_start - (uint8_t*)hdr)); /* * Sanity check the encrypted payload length against * the tag size. It must always be at least as large * as the tag length. */ if (enc_octet_len < (unsigned int) tag_len) { return err_status_cipher_fail; } /* * update the key usage limit, and check it to make sure that we * didn't just hit either the soft limit or the hard limit, and call * the event handler if we hit either. */ switch (key_limit_update(stream->limit)) { case key_event_normal: break; case key_event_soft_limit: srtp_handle_event(ctx, stream, event_key_soft_limit); break; case key_event_hard_limit: srtp_handle_event(ctx, stream, event_key_hard_limit); return err_status_key_expired; default: break; } /* * Set the AAD for AES-GCM, which is the RTP header */ aad_len = (uint8_t *)enc_start - (uint8_t *)hdr; status = cipher_set_aad(stream->rtp_cipher, (uint8_t*)hdr, aad_len); if (status) { return ( err_status_cipher_fail); } /* Decrypt the ciphertext. This also checks the auth tag based * on the AAD we just specified above */ status = cipher_decrypt(stream->rtp_cipher, (uint8_t*)enc_start, &enc_octet_len); if (status) { return status; } /* * verify that stream is for received traffic - this check will * detect SSRC collisions, since a stream that appears in both * srtp_protect() and srtp_unprotect() will fail this test in one of * those functions. * * we do this check *after* the authentication check, so that the * latter check will catch any attempts to fool us into thinking * that we've got a collision */ if (stream->direction != dir_srtp_receiver) { if (stream->direction == dir_unknown) { stream->direction = dir_srtp_receiver; } else { srtp_handle_event(ctx, stream, event_ssrc_collision); } } /* * if the stream is a 'provisional' one, in which the template context * is used, then we need to allocate a new stream at this point, since * the authentication passed */ if (stream == ctx->stream_template) { srtp_stream_ctx_t *new_stream; /* * allocate and initialize a new stream * * note that we indicate failure if we can't allocate the new * stream, and some implementations will want to not return * failure here */ status = srtp_stream_clone(ctx->stream_template, hdr->ssrc, &new_stream); if (status) { return status; } /* add new stream to the head of the stream_list */ new_stream->next = ctx->stream_list; ctx->stream_list = new_stream; /* set stream (the pointer used in this function) */ stream = new_stream; } /* * the message authentication function passed, so add the packet * index into the replay database */ rdbx_add_index(&stream->rtp_rdbx, delta); /* decrease the packet length by the length of the auth tag */ *pkt_octet_len -= tag_len; return err_status_ok; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Prevent potential DoS attack due to lack of bounds checking on RTP header CSRC count and extension header length. Credit goes to Randell Jesup and the Firefox team for reporting this issue.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: srtp_protect_aead (srtp_ctx_t *ctx, srtp_stream_ctx_t *stream, void *rtp_hdr, unsigned int *pkt_octet_len) { srtp_hdr_t *hdr = (srtp_hdr_t*)rtp_hdr; uint32_t *enc_start; /* pointer to start of encrypted portion */ unsigned int enc_octet_len = 0; /* number of octets in encrypted portion */ xtd_seq_num_t est; /* estimated xtd_seq_num_t of *hdr */ int delta; /* delta of local pkt idx and that in hdr */ err_status_t status; int tag_len; v128_t iv; unsigned int aad_len; debug_print(mod_srtp, "function srtp_protect_aead", NULL); /* * update the key usage limit, and check it to make sure that we * didn't just hit either the soft limit or the hard limit, and call * the event handler if we hit either. */ switch (key_limit_update(stream->limit)) { case key_event_normal: break; case key_event_hard_limit: srtp_handle_event(ctx, stream, event_key_hard_limit); return err_status_key_expired; case key_event_soft_limit: default: srtp_handle_event(ctx, stream, event_key_soft_limit); break; } /* get tag length from stream */ tag_len = auth_get_tag_length(stream->rtp_auth); /* * find starting point for encryption and length of data to be * encrypted - the encrypted portion starts after the rtp header * extension, if present; otherwise, it starts after the last csrc, * if any are present */ enc_start = (uint32_t*)hdr + uint32s_in_rtp_header + hdr->cc; if (hdr->x == 1) { srtp_hdr_xtnd_t *xtn_hdr = (srtp_hdr_xtnd_t*)enc_start; enc_start += (ntohs(xtn_hdr->length) + 1); } if (!((uint8_t*)enc_start < (uint8_t*)hdr + *pkt_octet_len)) return err_status_parse_err; enc_octet_len = (unsigned int)(*pkt_octet_len - ((uint8_t*)enc_start - (uint8_t*)hdr)); /* * estimate the packet index using the start of the replay window * and the sequence number from the header */ delta = rdbx_estimate_index(&stream->rtp_rdbx, &est, ntohs(hdr->seq)); status = rdbx_check(&stream->rtp_rdbx, delta); if (status) { if (status != err_status_replay_fail || !stream->allow_repeat_tx) { return status; /* we've been asked to reuse an index */ } } else { rdbx_add_index(&stream->rtp_rdbx, delta); } #ifdef NO_64BIT_MATH debug_print2(mod_srtp, "estimated packet index: %08x%08x", high32(est), low32(est)); #else debug_print(mod_srtp, "estimated packet index: %016llx", est); #endif /* * AEAD uses a new IV formation method */ srtp_calc_aead_iv(stream, &iv, &est, hdr); status = cipher_set_iv(stream->rtp_cipher, &iv, direction_encrypt); if (status) { return err_status_cipher_fail; } /* shift est, put into network byte order */ #ifdef NO_64BIT_MATH est = be64_to_cpu(make64((high32(est) << 16) | (low32(est) >> 16), low32(est) << 16)); #else est = be64_to_cpu(est << 16); #endif /* * Set the AAD over the RTP header */ aad_len = (uint8_t *)enc_start - (uint8_t *)hdr; status = cipher_set_aad(stream->rtp_cipher, (uint8_t*)hdr, aad_len); if (status) { return ( err_status_cipher_fail); } /* Encrypt the payload */ status = cipher_encrypt(stream->rtp_cipher, (uint8_t*)enc_start, &enc_octet_len); if (status) { return err_status_cipher_fail; } /* * If we're doing GCM, we need to get the tag * and append that to the output */ status = cipher_get_tag(stream->rtp_cipher, (uint8_t*)enc_start+enc_octet_len, &tag_len); if (status) { return ( err_status_cipher_fail); } enc_octet_len += tag_len; /* increase the packet length by the length of the auth tag */ *pkt_octet_len += tag_len; return err_status_ok; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Prevent potential DoS attack due to lack of bounds checking on RTP header CSRC count and extension header length. Credit goes to Randell Jesup and the Firefox team for reporting this issue.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: srtp_protect_aead (srtp_ctx_t *ctx, srtp_stream_ctx_t *stream, void *rtp_hdr, unsigned int *pkt_octet_len) { srtp_hdr_t *hdr = (srtp_hdr_t*)rtp_hdr; uint32_t *enc_start; /* pointer to start of encrypted portion */ unsigned int enc_octet_len = 0; /* number of octets in encrypted portion */ xtd_seq_num_t est; /* estimated xtd_seq_num_t of *hdr */ int delta; /* delta of local pkt idx and that in hdr */ err_status_t status; int tag_len; v128_t iv; unsigned int aad_len; debug_print(mod_srtp, "function srtp_protect_aead", NULL); /* * update the key usage limit, and check it to make sure that we * didn't just hit either the soft limit or the hard limit, and call * the event handler if we hit either. */ switch (key_limit_update(stream->limit)) { case key_event_normal: break; case key_event_hard_limit: srtp_handle_event(ctx, stream, event_key_hard_limit); return err_status_key_expired; case key_event_soft_limit: default: srtp_handle_event(ctx, stream, event_key_soft_limit); break; } /* get tag length from stream */ tag_len = auth_get_tag_length(stream->rtp_auth); /* * find starting point for encryption and length of data to be * encrypted - the encrypted portion starts after the rtp header * extension, if present; otherwise, it starts after the last csrc, * if any are present */ enc_start = (uint32_t*)hdr + uint32s_in_rtp_header + hdr->cc; if (hdr->x == 1) { srtp_hdr_xtnd_t *xtn_hdr = (srtp_hdr_xtnd_t*)enc_start; enc_start += (ntohs(xtn_hdr->length) + 1); } if (!((uint8_t*)enc_start < (uint8_t*)hdr + (*pkt_octet_len - tag_len))) return err_status_parse_err; enc_octet_len = (unsigned int)(*pkt_octet_len - ((uint8_t*)enc_start - (uint8_t*)hdr)); /* * estimate the packet index using the start of the replay window * and the sequence number from the header */ delta = rdbx_estimate_index(&stream->rtp_rdbx, &est, ntohs(hdr->seq)); status = rdbx_check(&stream->rtp_rdbx, delta); if (status) { if (status != err_status_replay_fail || !stream->allow_repeat_tx) { return status; /* we've been asked to reuse an index */ } } else { rdbx_add_index(&stream->rtp_rdbx, delta); } #ifdef NO_64BIT_MATH debug_print2(mod_srtp, "estimated packet index: %08x%08x", high32(est), low32(est)); #else debug_print(mod_srtp, "estimated packet index: %016llx", est); #endif /* * AEAD uses a new IV formation method */ srtp_calc_aead_iv(stream, &iv, &est, hdr); status = cipher_set_iv(stream->rtp_cipher, &iv, direction_encrypt); if (status) { return err_status_cipher_fail; } /* shift est, put into network byte order */ #ifdef NO_64BIT_MATH est = be64_to_cpu(make64((high32(est) << 16) | (low32(est) >> 16), low32(est) << 16)); #else est = be64_to_cpu(est << 16); #endif /* * Set the AAD over the RTP header */ aad_len = (uint8_t *)enc_start - (uint8_t *)hdr; status = cipher_set_aad(stream->rtp_cipher, (uint8_t*)hdr, aad_len); if (status) { return ( err_status_cipher_fail); } /* Encrypt the payload */ status = cipher_encrypt(stream->rtp_cipher, (uint8_t*)enc_start, &enc_octet_len); if (status) { return err_status_cipher_fail; } /* * If we're doing GCM, we need to get the tag * and append that to the output */ status = cipher_get_tag(stream->rtp_cipher, (uint8_t*)enc_start+enc_octet_len, &tag_len); if (status) { return ( err_status_cipher_fail); } enc_octet_len += tag_len; /* increase the packet length by the length of the auth tag */ *pkt_octet_len += tag_len; return err_status_ok; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Apply a7216c19582827cdbd5cacce5618db0b6be8d851 to 1.5.x throttle'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: srtp_protect_aead (srtp_ctx_t *ctx, srtp_stream_ctx_t *stream, void *rtp_hdr, unsigned int *pkt_octet_len) { srtp_hdr_t *hdr = (srtp_hdr_t*)rtp_hdr; uint32_t *enc_start; /* pointer to start of encrypted portion */ int enc_octet_len = 0; /* number of octets in encrypted portion */ xtd_seq_num_t est; /* estimated xtd_seq_num_t of *hdr */ int delta; /* delta of local pkt idx and that in hdr */ err_status_t status; int tag_len; v128_t iv; unsigned int aad_len; debug_print(mod_srtp, "function srtp_protect_aead", NULL); /* * update the key usage limit, and check it to make sure that we * didn't just hit either the soft limit or the hard limit, and call * the event handler if we hit either. */ switch (key_limit_update(stream->limit)) { case key_event_normal: break; case key_event_hard_limit: srtp_handle_event(ctx, stream, event_key_hard_limit); return err_status_key_expired; case key_event_soft_limit: default: srtp_handle_event(ctx, stream, event_key_soft_limit); break; } /* get tag length from stream */ tag_len = auth_get_tag_length(stream->rtp_auth); /* * find starting point for encryption and length of data to be * encrypted - the encrypted portion starts after the rtp header * extension, if present; otherwise, it starts after the last csrc, * if any are present */ enc_start = (uint32_t*)hdr + uint32s_in_rtp_header + hdr->cc; if (hdr->x == 1) { srtp_hdr_xtnd_t *xtn_hdr = (srtp_hdr_xtnd_t*)enc_start; enc_start += (ntohs(xtn_hdr->length) + 1); } if (!((uint8_t*)enc_start < (uint8_t*)hdr + *pkt_octet_len)) return err_status_parse_err; enc_octet_len = (int)(*pkt_octet_len - ((uint8_t*)enc_start - (uint8_t*)hdr)); if (enc_octet_len < 0) return err_status_parse_err; /* * estimate the packet index using the start of the replay window * and the sequence number from the header */ delta = rdbx_estimate_index(&stream->rtp_rdbx, &est, ntohs(hdr->seq)); status = rdbx_check(&stream->rtp_rdbx, delta); if (status) { if (status != err_status_replay_fail || !stream->allow_repeat_tx) { return status; /* we've been asked to reuse an index */ } } else { rdbx_add_index(&stream->rtp_rdbx, delta); } #ifdef NO_64BIT_MATH debug_print2(mod_srtp, "estimated packet index: %08x%08x", high32(est), low32(est)); #else debug_print(mod_srtp, "estimated packet index: %016llx", est); #endif /* * AEAD uses a new IV formation method */ srtp_calc_aead_iv(stream, &iv, &est, hdr); status = cipher_set_iv(stream->rtp_cipher, &iv, direction_encrypt); if (status) { return err_status_cipher_fail; } /* shift est, put into network byte order */ #ifdef NO_64BIT_MATH est = be64_to_cpu(make64((high32(est) << 16) | (low32(est) >> 16), low32(est) << 16)); #else est = be64_to_cpu(est << 16); #endif /* * Set the AAD over the RTP header */ aad_len = (uint8_t *)enc_start - (uint8_t *)hdr; status = cipher_set_aad(stream->rtp_cipher, (uint8_t*)hdr, aad_len); if (status) { return ( err_status_cipher_fail); } /* Encrypt the payload */ status = cipher_encrypt(stream->rtp_cipher, (uint8_t*)enc_start, (unsigned int *)&enc_octet_len); if (status) { return err_status_cipher_fail; } /* * If we're doing GCM, we need to get the tag * and append that to the output */ status = cipher_get_tag(stream->rtp_cipher, (uint8_t*)enc_start+enc_octet_len, &tag_len); if (status) { return ( err_status_cipher_fail); } /* increase the packet length by the length of the auth tag */ *pkt_octet_len += tag_len; return err_status_ok; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Allow zero payload packets to pass bounds 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 unsigned long mmap_legacy_base(unsigned long rnd) { if (mmap_is_ia32()) return TASK_UNMAPPED_BASE; else return TASK_UNMAPPED_BASE + rnd; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-254'], 'message': 'x86/mm/32: Enable full randomization on i386 and X86_32 Currently on i386 and on X86_64 when emulating X86_32 in legacy mode, only the stack and the executable are randomized but not other mmapped files (libraries, vDSO, etc.). This patch enables randomization for the libraries, vDSO and mmap requests on i386 and in X86_32 in legacy mode. By default on i386 there are 8 bits for the randomization of the libraries, vDSO and mmaps which only uses 1MB of VA. This patch preserves the original randomness, using 1MB of VA out of 3GB or 4GB. We think that 1MB out of 3GB is not a big cost for having the ASLR. The first obvious security benefit is that all objects are randomized (not only the stack and the executable) in legacy mode which highly increases the ASLR effectiveness, otherwise the attackers may use these non-randomized areas. But also sensitive setuid/setgid applications are more secure because currently, attackers can disable the randomization of these applications by setting the ulimit stack to "unlimited". This is a very old and widely known trick to disable the ASLR in i386 which has been allowed for too long. Another trick used to disable the ASLR was to set the ADDR_NO_RANDOMIZE personality flag, but fortunately this doesn't work on setuid/setgid applications because there is security checks which clear Security-relevant flags. This patch always randomizes the mmap_legacy_base address, removing the possibility to disable the ASLR by setting the stack to "unlimited". Signed-off-by: Hector Marco-Gisbert <[email protected]> Acked-by: Ismael Ripoll Ripoll <[email protected]> Acked-by: Kees Cook <[email protected]> Acked-by: Arjan van de Ven <[email protected]> Cc: Linus Torvalds <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: [email protected] Cc: kees Cook <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int cdc_ncm_bind(struct usbnet *dev, struct usb_interface *intf) { int ret; /* MBIM backwards compatible function? */ if (cdc_ncm_select_altsetting(intf) != CDC_NCM_COMM_ALTSETTING_NCM) return -ENODEV; /* The NCM data altsetting is fixed, so we hard-coded it. * Additionally, generic NCM devices are assumed to accept arbitrarily * placed NDP. */ ret = cdc_ncm_bind_common(dev, intf, CDC_NCM_DATA_ALTSETTING_NCM, 0); /* * We should get an event when network connection is "connected" or * "disconnected". Set network connection in "disconnected" state * (carrier is OFF) during attach, so the IP network stack does not * start IPv6 negotiation and more. */ usbnet_link_change(dev, 0, 0); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'cdc_ncm: do not call usbnet_link_change from cdc_ncm_bind usbnet_link_change will call schedule_work and should be avoided if bind is failing. Otherwise we will end up with scheduled work referring to a netdev which has gone away. Instead of making the call conditional, we can just defer it to usbnet_probe, using the driver_info flag made for this purpose. Fixes: 8a34b0ae8778 ("usbnet: cdc_ncm: apply usbnet_link_change") Reported-by: Andrey Konovalov <[email protected]> Suggested-by: Linus Torvalds <[email protected]> Signed-off-by: Bjørn Mork <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static enum integrity_status evm_verify_hmac(struct dentry *dentry, const char *xattr_name, char *xattr_value, size_t xattr_value_len, struct integrity_iint_cache *iint) { struct evm_ima_xattr_data *xattr_data = NULL; struct evm_ima_xattr_data calc; enum integrity_status evm_status = INTEGRITY_PASS; int rc, xattr_len; if (iint && iint->evm_status == INTEGRITY_PASS) return iint->evm_status; /* if status is not PASS, try to check again - against -ENOMEM */ /* first need to know the sig type */ rc = vfs_getxattr_alloc(dentry, XATTR_NAME_EVM, (char **)&xattr_data, 0, GFP_NOFS); if (rc <= 0) { evm_status = INTEGRITY_FAIL; if (rc == -ENODATA) { rc = evm_find_protected_xattrs(dentry); if (rc > 0) evm_status = INTEGRITY_NOLABEL; else if (rc == 0) evm_status = INTEGRITY_NOXATTRS; /* new file */ } else if (rc == -EOPNOTSUPP) { evm_status = INTEGRITY_UNKNOWN; } goto out; } xattr_len = rc; /* check value type */ switch (xattr_data->type) { case EVM_XATTR_HMAC: rc = evm_calc_hmac(dentry, xattr_name, xattr_value, xattr_value_len, calc.digest); if (rc) break; rc = memcmp(xattr_data->digest, calc.digest, sizeof(calc.digest)); if (rc) rc = -EINVAL; break; case EVM_IMA_XATTR_DIGSIG: rc = evm_calc_hash(dentry, xattr_name, xattr_value, xattr_value_len, calc.digest); if (rc) break; rc = integrity_digsig_verify(INTEGRITY_KEYRING_EVM, (const char *)xattr_data, xattr_len, calc.digest, sizeof(calc.digest)); if (!rc) { /* Replace RSA with HMAC if not mounted readonly and * not immutable */ if (!IS_RDONLY(d_backing_inode(dentry)) && !IS_IMMUTABLE(d_backing_inode(dentry))) evm_update_evmxattr(dentry, xattr_name, xattr_value, xattr_value_len); } break; default: rc = -EINVAL; break; } if (rc) evm_status = (rc == -ENODATA) ? INTEGRITY_NOXATTRS : INTEGRITY_FAIL; out: if (iint) iint->evm_status = evm_status; kfree(xattr_data); return evm_status; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-241', 'CWE-19'], 'message': 'EVM: Use crypto_memneq() for digest comparisons This patch fixes vulnerability CVE-2016-2085. The problem exists because the vm_verify_hmac() function includes a use of memcmp(). Unfortunately, this allows timing side channel attacks; specifically a MAC forgery complexity drop from 2^128 to 2^12. This patch changes the memcmp() to the cryptographically safe crypto_memneq(). Reported-by: Xiaofei Rex Guo <[email protected]> Signed-off-by: Ryan Ware <[email protected]> Cc: [email protected] Signed-off-by: Mimi Zohar <[email protected]> Signed-off-by: James Morris <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static long restore_tm_user_regs(struct pt_regs *regs, struct mcontext __user *sr, struct mcontext __user *tm_sr) { long err; unsigned long msr, msr_hi; #ifdef CONFIG_VSX int i; #endif /* * restore general registers but not including MSR or SOFTE. Also * take care of keeping r2 (TLS) intact if not a signal. * See comment in signal_64.c:restore_tm_sigcontexts(); * TFHAR is restored from the checkpointed NIP; TEXASR and TFIAR * were set by the signal delivery. */ err = restore_general_regs(regs, tm_sr); err |= restore_general_regs(&current->thread.ckpt_regs, sr); err |= __get_user(current->thread.tm_tfhar, &sr->mc_gregs[PT_NIP]); err |= __get_user(msr, &sr->mc_gregs[PT_MSR]); if (err) return 1; /* Restore the previous little-endian mode */ regs->msr = (regs->msr & ~MSR_LE) | (msr & MSR_LE); /* * Do this before updating the thread state in * current->thread.fpr/vr/evr. That way, if we get preempted * and another task grabs the FPU/Altivec/SPE, it won't be * tempted to save the current CPU state into the thread_struct * and corrupt what we are writing there. */ discard_lazy_cpu_state(); #ifdef CONFIG_ALTIVEC regs->msr &= ~MSR_VEC; if (msr & MSR_VEC) { /* restore altivec registers from the stack */ if (__copy_from_user(&current->thread.vr_state, &sr->mc_vregs, sizeof(sr->mc_vregs)) || __copy_from_user(&current->thread.transact_vr, &tm_sr->mc_vregs, sizeof(sr->mc_vregs))) return 1; } else if (current->thread.used_vr) { memset(&current->thread.vr_state, 0, ELF_NVRREG * sizeof(vector128)); memset(&current->thread.transact_vr, 0, ELF_NVRREG * sizeof(vector128)); } /* Always get VRSAVE back */ if (__get_user(current->thread.vrsave, (u32 __user *)&sr->mc_vregs[32]) || __get_user(current->thread.transact_vrsave, (u32 __user *)&tm_sr->mc_vregs[32])) return 1; if (cpu_has_feature(CPU_FTR_ALTIVEC)) mtspr(SPRN_VRSAVE, current->thread.vrsave); #endif /* CONFIG_ALTIVEC */ regs->msr &= ~(MSR_FP | MSR_FE0 | MSR_FE1); if (copy_fpr_from_user(current, &sr->mc_fregs) || copy_transact_fpr_from_user(current, &tm_sr->mc_fregs)) return 1; #ifdef CONFIG_VSX regs->msr &= ~MSR_VSX; if (msr & MSR_VSX) { /* * Restore altivec registers from the stack to a local * buffer, then write this out to the thread_struct */ if (copy_vsx_from_user(current, &sr->mc_vsregs) || copy_transact_vsx_from_user(current, &tm_sr->mc_vsregs)) return 1; } else if (current->thread.used_vsr) for (i = 0; i < 32 ; i++) { current->thread.fp_state.fpr[i][TS_VSRLOWOFFSET] = 0; current->thread.transact_fp.fpr[i][TS_VSRLOWOFFSET] = 0; } #endif /* CONFIG_VSX */ #ifdef CONFIG_SPE /* SPE regs are not checkpointed with TM, so this section is * simply the same as in restore_user_regs(). */ regs->msr &= ~MSR_SPE; if (msr & MSR_SPE) { if (__copy_from_user(current->thread.evr, &sr->mc_vregs, ELF_NEVRREG * sizeof(u32))) return 1; } else if (current->thread.used_spe) memset(current->thread.evr, 0, ELF_NEVRREG * sizeof(u32)); /* Always get SPEFSCR back */ if (__get_user(current->thread.spefscr, (u32 __user *)&sr->mc_vregs + ELF_NEVRREG)) return 1; #endif /* CONFIG_SPE */ /* Now, recheckpoint. This loads up all of the checkpointed (older) * registers, including FP and V[S]Rs. After recheckpointing, the * transactional versions should be loaded. */ tm_enable(); /* Make sure the transaction is marked as failed */ current->thread.tm_texasr |= TEXASR_FS; /* This loads the checkpointed FP/VEC state, if used */ tm_recheckpoint(&current->thread, msr); /* Get the top half of the MSR */ if (__get_user(msr_hi, &tm_sr->mc_gregs[PT_MSR])) return 1; /* Pull in MSR TM from user context */ regs->msr = (regs->msr & ~MSR_TS_MASK) | ((msr_hi<<32) & MSR_TS_MASK); /* This loads the speculative FP/VEC state, if used */ if (msr & MSR_FP) { do_load_up_transact_fpu(&current->thread); regs->msr |= (MSR_FP | current->thread.fpexc_mode); } #ifdef CONFIG_ALTIVEC if (msr & MSR_VEC) { do_load_up_transact_altivec(&current->thread); regs->msr |= MSR_VEC; } #endif return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-284', 'CWE-369'], 'message': 'powerpc/tm: Block signal return setting invalid MSR state Currently we allow both the MSR T and S bits to be set by userspace on a signal return. Unfortunately this is a reserved configuration and will cause a TM Bad Thing exception if attempted (via rfid). This patch checks for this case in both the 32 and 64 bit signals code. If both T and S are set, we mark the context as invalid. Found using a syscall fuzzer. Fixes: 2b0a576d15e0 ("powerpc: Add new transactional memory state to the signal context") Cc: [email protected] # v3.9+ Signed-off-by: Michael Neuling <[email protected]> Signed-off-by: Michael Ellerman <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void tm_reclaim_thread(struct thread_struct *thr, struct thread_info *ti, uint8_t cause) { unsigned long msr_diff = 0; /* * If FP/VSX registers have been already saved to the * thread_struct, move them to the transact_fp array. * We clear the TIF_RESTORE_TM bit since after the reclaim * the thread will no longer be transactional. */ if (test_ti_thread_flag(ti, TIF_RESTORE_TM)) { msr_diff = thr->ckpt_regs.msr & ~thr->regs->msr; if (msr_diff & MSR_FP) memcpy(&thr->transact_fp, &thr->fp_state, sizeof(struct thread_fp_state)); if (msr_diff & MSR_VEC) memcpy(&thr->transact_vr, &thr->vr_state, sizeof(struct thread_vr_state)); clear_ti_thread_flag(ti, TIF_RESTORE_TM); msr_diff &= MSR_FP | MSR_VEC | MSR_VSX | MSR_FE0 | MSR_FE1; } tm_reclaim(thr, thr->regs->msr, cause); /* Having done the reclaim, we now have the checkpointed * FP/VSX values in the registers. These might be valid * even if we have previously called enable_kernel_fp() or * flush_fp_to_thread(), so update thr->regs->msr to * indicate their current validity. */ thr->regs->msr |= msr_diff; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284'], 'message': 'powerpc/tm: Check for already reclaimed tasks Currently we can hit a scenario where we'll tm_reclaim() twice. This results in a TM bad thing exception because the second reclaim occurs when not in suspend mode. The scenario in which this can happen is the following. We attempt to deliver a signal to userspace. To do this we need obtain the stack pointer to write the signal context. To get this stack pointer we must tm_reclaim() in case we need to use the checkpointed stack pointer (see get_tm_stackpointer()). Normally we'd then return directly to userspace to deliver the signal without going through __switch_to(). Unfortunatley, if at this point we get an error (such as a bad userspace stack pointer), we need to exit the process. The exit will result in a __switch_to(). __switch_to() will attempt to save the process state which results in another tm_reclaim(). This tm_reclaim() now causes a TM Bad Thing exception as this state has already been saved and the processor is no longer in TM suspend mode. Whee! This patch checks the state of the MSR to ensure we are TM suspended before we attempt the tm_reclaim(). If we've already saved the state away, we should no longer be in TM suspend mode. This has the additional advantage of checking for a potential TM Bad Thing exception. Found using syscall fuzzer. Fixes: fb09692e71f1 ("powerpc: Add reclaim and recheckpoint functions for context switching transactional memory processes") Cc: [email protected] # v3.9+ Signed-off-by: Michael Neuling <[email protected]> Signed-off-by: Michael Ellerman <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ImagingResampleHorizontal(Imaging imIn, int xsize, int filter) { ImagingSectionCookie cookie; Imaging imOut; struct filter *filterp; float support, scale, filterscale; float center, ww, ss, ss0, ss1, ss2, ss3; int xx, yy, x, kmax, xmin, xmax; int *xbounds; float *k, *kk; /* check filter */ switch (filter) { case IMAGING_TRANSFORM_LANCZOS: filterp = &LANCZOS; break; case IMAGING_TRANSFORM_BILINEAR: filterp = &BILINEAR; break; case IMAGING_TRANSFORM_BICUBIC: filterp = &BICUBIC; break; default: return (Imaging) ImagingError_ValueError( "unsupported resampling filter" ); } /* prepare for horizontal stretch */ filterscale = scale = (float) imIn->xsize / xsize; /* determine support size (length of resampling filter) */ support = filterp->support; if (filterscale < 1.0) { filterscale = 1.0; } support = support * filterscale; /* maximum number of coofs */ kmax = (int) ceil(support) * 2 + 1; /* coefficient buffer */ kk = malloc(xsize * kmax * sizeof(float)); if ( ! kk) return (Imaging) ImagingError_MemoryError(); xbounds = malloc(xsize * 2 * sizeof(int)); if ( ! xbounds) { free(kk); return (Imaging) ImagingError_MemoryError(); } for (xx = 0; xx < xsize; xx++) { k = &kk[xx * kmax]; center = (xx + 0.5) * scale; ww = 0.0; ss = 1.0 / filterscale; xmin = (int) floor(center - support); if (xmin < 0) xmin = 0; xmax = (int) ceil(center + support); if (xmax > imIn->xsize) xmax = imIn->xsize; for (x = xmin; x < xmax; x++) { float w = filterp->filter((x - center + 0.5) * ss) * ss; k[x - xmin] = w; ww += w; } for (x = 0; x < xmax - xmin; x++) { if (ww != 0.0) k[x] /= ww; } xbounds[xx * 2 + 0] = xmin; xbounds[xx * 2 + 1] = xmax; } imOut = ImagingNew(imIn->mode, xsize, imIn->ysize); if ( ! imOut) { free(kk); free(xbounds); return NULL; } ImagingSectionEnter(&cookie); /* horizontal stretch */ for (yy = 0; yy < imOut->ysize; yy++) { if (imIn->image8) { /* 8-bit grayscale */ for (xx = 0; xx < xsize; xx++) { xmin = xbounds[xx * 2 + 0]; xmax = xbounds[xx * 2 + 1]; k = &kk[xx * kmax]; ss = 0.5; for (x = xmin; x < xmax; x++) ss += i2f(imIn->image8[yy][x]) * k[x - xmin]; imOut->image8[yy][xx] = clip8(ss); } } else { switch(imIn->type) { case IMAGING_TYPE_UINT8: /* n-bit grayscale */ if (imIn->bands == 2) { for (xx = 0; xx < xsize; xx++) { xmin = xbounds[xx * 2 + 0]; xmax = xbounds[xx * 2 + 1]; k = &kk[xx * kmax]; ss0 = ss1 = 0.5; for (x = xmin; x < xmax; x++) { ss0 += i2f((UINT8) imIn->image[yy][x*4 + 0]) * k[x - xmin]; ss1 += i2f((UINT8) imIn->image[yy][x*4 + 3]) * k[x - xmin]; } imOut->image[yy][xx*4 + 0] = clip8(ss0); imOut->image[yy][xx*4 + 3] = clip8(ss1); } } else if (imIn->bands == 3) { for (xx = 0; xx < xsize; xx++) { xmin = xbounds[xx * 2 + 0]; xmax = xbounds[xx * 2 + 1]; k = &kk[xx * kmax]; ss0 = ss1 = ss2 = 0.5; for (x = xmin; x < xmax; x++) { ss0 += i2f((UINT8) imIn->image[yy][x*4 + 0]) * k[x - xmin]; ss1 += i2f((UINT8) imIn->image[yy][x*4 + 1]) * k[x - xmin]; ss2 += i2f((UINT8) imIn->image[yy][x*4 + 2]) * k[x - xmin]; } imOut->image[yy][xx*4 + 0] = clip8(ss0); imOut->image[yy][xx*4 + 1] = clip8(ss1); imOut->image[yy][xx*4 + 2] = clip8(ss2); } } else { for (xx = 0; xx < xsize; xx++) { xmin = xbounds[xx * 2 + 0]; xmax = xbounds[xx * 2 + 1]; k = &kk[xx * kmax]; ss0 = ss1 = ss2 = ss3 = 0.5; for (x = xmin; x < xmax; x++) { ss0 += i2f((UINT8) imIn->image[yy][x*4 + 0]) * k[x - xmin]; ss1 += i2f((UINT8) imIn->image[yy][x*4 + 1]) * k[x - xmin]; ss2 += i2f((UINT8) imIn->image[yy][x*4 + 2]) * k[x - xmin]; ss3 += i2f((UINT8) imIn->image[yy][x*4 + 3]) * k[x - xmin]; } imOut->image[yy][xx*4 + 0] = clip8(ss0); imOut->image[yy][xx*4 + 1] = clip8(ss1); imOut->image[yy][xx*4 + 2] = clip8(ss2); imOut->image[yy][xx*4 + 3] = clip8(ss3); } } break; case IMAGING_TYPE_INT32: /* 32-bit integer */ for (xx = 0; xx < xsize; xx++) { xmin = xbounds[xx * 2 + 0]; xmax = xbounds[xx * 2 + 1]; k = &kk[xx * kmax]; ss = 0.0; for (x = xmin; x < xmax; x++) ss += i2f(IMAGING_PIXEL_I(imIn, x, yy)) * k[x - xmin]; IMAGING_PIXEL_I(imOut, xx, yy) = (int) ss; } break; case IMAGING_TYPE_FLOAT32: /* 32-bit float */ for (xx = 0; xx < xsize; xx++) { xmin = xbounds[xx * 2 + 0]; xmax = xbounds[xx * 2 + 1]; k = &kk[xx * kmax]; ss = 0.0; for (x = xmin; x < xmax; x++) ss += IMAGING_PIXEL_F(imIn, x, yy) * k[x - xmin]; IMAGING_PIXEL_F(imOut, xx, yy) = ss; } break; } } } ImagingSectionLeave(&cookie); free(kk); free(xbounds); return imOut; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'fix integer overflow in Resample.c'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: http_splitheader(struct http *hp, int req) { char *p, *q, **hh; int n; char buf[20]; CHECK_OBJ_NOTNULL(hp, HTTP_MAGIC); if (req) { memset(hp->req, 0, sizeof hp->req); hh = hp->req; } else { memset(hp->resp, 0, sizeof hp->resp); hh = hp->resp; } n = 0; p = hp->rxbuf; /* REQ/PROTO */ while (vct_islws(*p)) p++; hh[n++] = p; while (!vct_islws(*p)) p++; assert(!vct_iscrlf(*p)); *p++ = '\0'; /* URL/STATUS */ while (vct_issp(*p)) /* XXX: H space only */ p++; assert(!vct_iscrlf(*p)); hh[n++] = p; while (!vct_islws(*p)) p++; if (vct_iscrlf(*p)) { hh[n++] = NULL; q = p; p += vct_skipcrlf(p); *q = '\0'; } else { *p++ = '\0'; /* PROTO/MSG */ while (vct_issp(*p)) /* XXX: H space only */ p++; hh[n++] = p; while (!vct_iscrlf(*p)) p++; q = p; p += vct_skipcrlf(p); *q = '\0'; } assert(n == 3); while (*p != '\0') { assert(n < MAX_HDR); if (vct_iscrlf(*p)) break; hh[n++] = p++; while (*p != '\0' && !vct_iscrlf(*p)) p++; q = p; p += vct_skipcrlf(p); *q = '\0'; } p += vct_skipcrlf(p); assert(*p == '\0'); for (n = 0; n < 3 || hh[n] != NULL; n++) { sprintf(buf, "http[%2d] ", n); vtc_dump(hp->vl, 4, buf, hh[n], -1); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-269'], 'message': 'Do not consider a CR by itself as a valid line terminator Varnish (prior to version 4.0) was not following the standard with regard to line separator. Spotted and analyzed by: Régis Leroy [regilero] [email protected]'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: http_splitline(struct worker *w, int fd, struct http *hp, const struct http_conn *htc, int h1, int h2, int h3) { char *p, *q; CHECK_OBJ_NOTNULL(htc, HTTP_CONN_MAGIC); CHECK_OBJ_NOTNULL(hp, HTTP_MAGIC); /* XXX: Assert a NUL at rx.e ? */ Tcheck(htc->rxbuf); /* Skip leading LWS */ for (p = htc->rxbuf.b ; vct_islws(*p); p++) continue; /* First field cannot contain SP, CRLF or CTL */ q = p; for (; !vct_issp(*p); p++) { if (vct_isctl(*p)) return (400); } hp->hd[h1].b = q; hp->hd[h1].e = p; /* Skip SP */ for (; vct_issp(*p); p++) { if (vct_isctl(*p)) return (400); } /* Second field cannot contain LWS or CTL */ q = p; for (; !vct_islws(*p); p++) { if (vct_isctl(*p)) return (400); } hp->hd[h2].b = q; hp->hd[h2].e = p; if (!Tlen(hp->hd[h2])) return (400); /* Skip SP */ for (; vct_issp(*p); p++) { if (vct_isctl(*p)) return (400); } /* Third field is optional and cannot contain CTL */ q = p; if (!vct_iscrlf(*p)) { for (; !vct_iscrlf(*p); p++) if (!vct_issep(*p) && vct_isctl(*p)) return (400); } hp->hd[h3].b = q; hp->hd[h3].e = p; /* Skip CRLF */ p += vct_skipcrlf(p); *hp->hd[h1].e = '\0'; WSLH(w, fd, hp, h1); *hp->hd[h2].e = '\0'; WSLH(w, fd, hp, h2); if (hp->hd[h3].e != NULL) { *hp->hd[h3].e = '\0'; WSLH(w, fd, hp, h3); } return (http_dissect_hdrs(w, hp, fd, p, htc)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-269'], 'message': 'Do not consider a CR by itself as a valid line terminator Varnish (prior to version 4.0) was not following the standard with regard to line separator. Spotted and analyzed by: Régis Leroy [regilero] [email protected]'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void tokenadd(struct jv_parser* p, char c) { assert(p->tokenpos <= p->tokenlen); if (p->tokenpos == p->tokenlen) { p->tokenlen = p->tokenlen*2 + 256; p->tokenbuf = jv_mem_realloc(p->tokenbuf, p->tokenlen); } assert(p->tokenpos < p->tokenlen); p->tokenbuf[p->tokenpos++] = c; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Heap buffer overflow in tokenadd() (fix #105) This was an off-by one: the NUL terminator byte was not allocated on resize. This was triggered by JSON-encoded numbers longer than 256 bytes.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int ndp_sock_open(struct ndp *ndp) { int sock; //struct icmp6_filter flt; int ret; int err; int val; sock = socket(PF_INET6, SOCK_RAW, IPPROTO_ICMPV6); if (sock == -1) { err(ndp, "Failed to create ICMP6 socket."); return -errno; } val = 1; ret = setsockopt(sock, IPPROTO_IPV6, IPV6_RECVPKTINFO, &val, sizeof(val)); if (ret == -1) { err(ndp, "Failed to setsockopt IPV6_RECVPKTINFO."); err = -errno; goto close_sock; } val = 255; ret = setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &val, sizeof(val)); if (ret == -1) { err(ndp, "Failed to setsockopt IPV6_MULTICAST_HOPS."); err = -errno; goto close_sock; } ndp->sock = sock; return 0; close_sock: close(sock); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284'], 'message': 'libndp: validate the IPv6 hop limit None of the NDP messages should ever come from a non-local network; as stated in RFC4861's 6.1.1 (RS), 6.1.2 (RA), 7.1.1 (NS), 7.1.2 (NA), and 8.1. (redirect): - The IP Hop Limit field has a value of 255, i.e., the packet could not possibly have been forwarded by a router. This fixes CVE-2016-3698. Reported by: Julien BERNARD <[email protected]> Signed-off-by: Lubomir Rintel <[email protected]> Signed-off-by: Jiri Pirko <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int myrecvfrom6(int sockfd, void *buf, size_t *buflen, int flags, struct in6_addr *addr, uint32_t *ifindex) { struct sockaddr_in6 sin6; unsigned char cbuf[CMSG_SPACE(sizeof(struct in6_pktinfo))]; struct iovec iovec; struct msghdr msghdr; struct cmsghdr *cmsghdr; ssize_t len; iovec.iov_len = *buflen; iovec.iov_base = buf; memset(&msghdr, 0, sizeof(msghdr)); msghdr.msg_name = &sin6; msghdr.msg_namelen = sizeof(sin6); msghdr.msg_iov = &iovec; msghdr.msg_iovlen = 1; msghdr.msg_control = cbuf; msghdr.msg_controllen = sizeof(cbuf); len = recvmsg(sockfd, &msghdr, flags); if (len == -1) return -errno; *buflen = len; /* Set ifindex to scope_id now. But since scope_id gets not * set by kernel for linklocal addresses, use pktinfo to obtain that * value right after. */ *ifindex = sin6.sin6_scope_id; for (cmsghdr = CMSG_FIRSTHDR(&msghdr); cmsghdr; cmsghdr = CMSG_NXTHDR(&msghdr, cmsghdr)) { if (cmsghdr->cmsg_level == IPPROTO_IPV6 && cmsghdr->cmsg_type == IPV6_PKTINFO && cmsghdr->cmsg_len == CMSG_LEN(sizeof(struct in6_pktinfo))) { struct in6_pktinfo *pktinfo; pktinfo = (struct in6_pktinfo *) CMSG_DATA(cmsghdr); *ifindex = pktinfo->ipi6_ifindex; } } *addr = sin6.sin6_addr; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284'], 'message': 'libndp: validate the IPv6 hop limit None of the NDP messages should ever come from a non-local network; as stated in RFC4861's 6.1.1 (RS), 6.1.2 (RA), 7.1.1 (NS), 7.1.2 (NA), and 8.1. (redirect): - The IP Hop Limit field has a value of 255, i.e., the packet could not possibly have been forwarded by a router. This fixes CVE-2016-3698. Reported by: Julien BERNARD <[email protected]> Signed-off-by: Lubomir Rintel <[email protected]> Signed-off-by: Jiri Pirko <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(openssl_random_pseudo_bytes) { long buffer_length; unsigned char *buffer = NULL; zval *zstrong_result_returned = NULL; int strong_result = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|z", &buffer_length, &zstrong_result_returned) == FAILURE) { return; } if (buffer_length <= 0) { RETURN_FALSE; } if (zstrong_result_returned) { zval_dtor(zstrong_result_returned); ZVAL_BOOL(zstrong_result_returned, 0); } buffer = emalloc(buffer_length + 1); #ifdef PHP_WIN32 strong_result = 1; /* random/urandom equivalent on Windows */ if (php_win32_get_random_bytes(buffer, (size_t) buffer_length) == FAILURE) { efree(buffer); if (zstrong_result_returned) { ZVAL_BOOL(zstrong_result_returned, 0); } RETURN_FALSE; } #else if ((strong_result = RAND_pseudo_bytes(buffer, buffer_length)) < 0) { efree(buffer); if (zstrong_result_returned) { ZVAL_BOOL(zstrong_result_returned, 0); } RETURN_FALSE; } #endif buffer[buffer_length] = 0; RETVAL_STRINGL((char *)buffer, buffer_length, 0); if (zstrong_result_returned) { ZVAL_BOOL(zstrong_result_returned, strong_result); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Fix bug #70014 - use RAND_bytes instead of deprecated RAND_pseudo_bytes'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SecureVector<byte> EME_PKCS1v15::unpad(const byte in[], size_t inlen, size_t key_len) const { if(inlen != key_len / 8 || inlen < 10 || in[0] != 0x02) throw Decoding_Error("PKCS1::unpad"); size_t seperator = 0; for(size_t j = 0; j != inlen; ++j) if(in[j] == 0) { seperator = j; break; } if(seperator < 9) throw Decoding_Error("PKCS1::unpad"); return SecureVector<byte>(in + seperator + 1, inlen - seperator - 1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Fixes for CVE-2015-7827 and CVE-2016-2849'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlParseEntityValue(xmlParserCtxtPtr ctxt, xmlChar **orig) { xmlChar *buf = NULL; int len = 0; int size = XML_PARSER_BUFFER_SIZE; int c, l; xmlChar stop; xmlChar *ret = NULL; const xmlChar *cur = NULL; xmlParserInputPtr input; if (RAW == '"') stop = '"'; else if (RAW == '\'') stop = '\''; else { xmlFatalErr(ctxt, XML_ERR_ENTITY_NOT_STARTED, NULL); return(NULL); } buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); if (buf == NULL) { xmlErrMemory(ctxt, NULL); return(NULL); } /* * The content of the entity definition is copied in a buffer. */ ctxt->instate = XML_PARSER_ENTITY_VALUE; input = ctxt->input; GROW; if (ctxt->instate == XML_PARSER_EOF) { xmlFree(buf); return(NULL); } NEXT; c = CUR_CHAR(l); /* * NOTE: 4.4.5 Included in Literal * When a parameter entity reference appears in a literal entity * value, ... a single or double quote character in the replacement * text is always treated as a normal data character and will not * terminate the literal. * In practice it means we stop the loop only when back at parsing * the initial entity and the quote is found */ while (((IS_CHAR(c)) && ((c != stop) || /* checked */ (ctxt->input != input))) && (ctxt->instate != XML_PARSER_EOF)) { if (len + 5 >= size) { xmlChar *tmp; size *= 2; tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar)); if (tmp == NULL) { xmlErrMemory(ctxt, NULL); xmlFree(buf); return(NULL); } buf = tmp; } COPY_BUF(l,buf,len,c); NEXTL(l); /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) /* non input consuming */ xmlPopInput(ctxt); GROW; c = CUR_CHAR(l); if (c == 0) { GROW; c = CUR_CHAR(l); } } buf[len] = 0; if (ctxt->instate == XML_PARSER_EOF) { xmlFree(buf); return(NULL); } /* * Raise problem w.r.t. '&' and '%' being used in non-entities * reference constructs. Note Charref will be handled in * xmlStringDecodeEntities() */ cur = buf; while (*cur != 0) { /* non input consuming */ if ((*cur == '%') || ((*cur == '&') && (cur[1] != '#'))) { xmlChar *name; xmlChar tmp = *cur; cur++; name = xmlParseStringName(ctxt, &cur); if ((name == NULL) || (*cur != ';')) { xmlFatalErrMsgInt(ctxt, XML_ERR_ENTITY_CHAR_ERROR, "EntityValue: '%c' forbidden except for entities references\n", tmp); } if ((tmp == '%') && (ctxt->inSubset == 1) && (ctxt->inputNr == 1)) { xmlFatalErr(ctxt, XML_ERR_ENTITY_PE_INTERNAL, NULL); } if (name != NULL) xmlFree(name); if (*cur == 0) break; } cur++; } /* * Then PEReference entities are substituted. */ if (c != stop) { xmlFatalErr(ctxt, XML_ERR_ENTITY_NOT_FINISHED, NULL); xmlFree(buf); } else { NEXT; /* * NOTE: 4.4.7 Bypassed * When a general entity reference appears in the EntityValue in * an entity declaration, it is bypassed and left as is. * so XML_SUBSTITUTE_REF is not set here. */ ret = xmlStringDecodeEntities(ctxt, buf, XML_SUBSTITUTE_PEREF, 0, 0, 0); if (orig != NULL) *orig = buf; else xmlFree(buf); } return(ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Add missing increments of recursion depth counter to XML parser. For https://bugzilla.gnome.org/show_bug.cgi?id=765207 CVE-2016-3705 The functions xmlParserEntityCheck() and xmlParseAttValueComplex() used to call xmlStringDecodeEntities() in a recursive context without incrementing the 'depth' counter in the parser context. Because of that omission, the parser failed to detect attribute recursions in certain documents before running out of stack space.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static php_stream *phar_make_dirstream(char *dir, HashTable *manifest TSRMLS_DC) /* {{{ */ { HashTable *data; int dirlen = strlen(dir); phar_zstr key; char *entry, *found, *save, *str_key; uint keylen; ulong unused; ALLOC_HASHTABLE(data); zend_hash_init(data, 64, zend_get_hash_value, NULL, 0); if ((*dir == '/' && dirlen == 1 && (manifest->nNumOfElements == 0)) || (dirlen >= sizeof(".phar")-1 && !memcmp(dir, ".phar", sizeof(".phar")-1))) { /* make empty root directory for empty phar */ /* make empty directory for .phar magic directory */ efree(dir); return php_stream_alloc(&phar_dir_ops, data, NULL, "r"); } zend_hash_internal_pointer_reset(manifest); while (FAILURE != zend_hash_has_more_elements(manifest)) { if (HASH_KEY_NON_EXISTENT == zend_hash_get_current_key_ex(manifest, &key, &keylen, &unused, 0, NULL)) { break; } PHAR_STR(key, str_key); if (keylen <= (uint)dirlen) { if (keylen < (uint)dirlen || !strncmp(str_key, dir, dirlen)) { PHAR_STR_FREE(str_key); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } } if (*dir == '/') { /* root directory */ if (keylen >= sizeof(".phar")-1 && !memcmp(str_key, ".phar", sizeof(".phar")-1)) { PHAR_STR_FREE(str_key); /* do not add any magic entries to this directory */ if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } if (NULL != (found = (char *) memchr(str_key, '/', keylen))) { /* the entry has a path separator and is a subdirectory */ entry = (char *) safe_emalloc(found - str_key, 1, 1); memcpy(entry, str_key, found - str_key); keylen = found - str_key; entry[keylen] = '\0'; } else { entry = (char *) safe_emalloc(keylen, 1, 1); memcpy(entry, str_key, keylen); entry[keylen] = '\0'; } PHAR_STR_FREE(str_key); goto PHAR_ADD_ENTRY; } else { if (0 != memcmp(str_key, dir, dirlen)) { /* entry in directory not found */ PHAR_STR_FREE(str_key); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } else { if (str_key[dirlen] != '/') { PHAR_STR_FREE(str_key); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } } } save = str_key; save += dirlen + 1; /* seek to just past the path separator */ if (NULL != (found = (char *) memchr(save, '/', keylen - dirlen - 1))) { /* is subdirectory */ save -= dirlen + 1; entry = (char *) safe_emalloc(found - save + dirlen, 1, 1); memcpy(entry, save + dirlen + 1, found - save - dirlen - 1); keylen = found - save - dirlen - 1; entry[keylen] = '\0'; } else { /* is file */ save -= dirlen + 1; entry = (char *) safe_emalloc(keylen - dirlen, 1, 1); memcpy(entry, save + dirlen + 1, keylen - dirlen - 1); entry[keylen - dirlen - 1] = '\0'; keylen = keylen - dirlen - 1; } PHAR_STR_FREE(str_key); PHAR_ADD_ENTRY: if (keylen) { phar_add_empty(data, entry, keylen); } efree(entry); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } } if (FAILURE != zend_hash_has_more_elements(data)) { efree(dir); if (zend_hash_sort(data, zend_qsort, phar_compare_dir_name, 0 TSRMLS_CC) == FAILURE) { FREE_HASHTABLE(data); return NULL; } return php_stream_alloc(&phar_dir_ops, data, NULL, "r"); } else { efree(dir); return php_stream_alloc(&phar_dir_ops, data, NULL, "r"); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-824'], 'message': 'Fixed bug #71331 - Uninitialized pointer in phar_make_dirstream()'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlBufAttrSerializeTxtContent(xmlBufPtr buf, xmlDocPtr doc, xmlAttrPtr attr, const xmlChar * string) { xmlChar *base, *cur; if (string == NULL) return; base = cur = (xmlChar *) string; while (*cur != 0) { if (*cur == '\n') { if (base != cur) xmlBufAdd(buf, base, cur - base); xmlBufAdd(buf, BAD_CAST "&#10;", 5); cur++; base = cur; } else if (*cur == '\r') { if (base != cur) xmlBufAdd(buf, base, cur - base); xmlBufAdd(buf, BAD_CAST "&#13;", 5); cur++; base = cur; } else if (*cur == '\t') { if (base != cur) xmlBufAdd(buf, base, cur - base); xmlBufAdd(buf, BAD_CAST "&#9;", 4); cur++; base = cur; } else if (*cur == '"') { if (base != cur) xmlBufAdd(buf, base, cur - base); xmlBufAdd(buf, BAD_CAST "&quot;", 6); cur++; base = cur; } else if (*cur == '<') { if (base != cur) xmlBufAdd(buf, base, cur - base); xmlBufAdd(buf, BAD_CAST "&lt;", 4); cur++; base = cur; } else if (*cur == '>') { if (base != cur) xmlBufAdd(buf, base, cur - base); xmlBufAdd(buf, BAD_CAST "&gt;", 4); cur++; base = cur; } else if (*cur == '&') { if (base != cur) xmlBufAdd(buf, base, cur - base); xmlBufAdd(buf, BAD_CAST "&amp;", 5); cur++; base = cur; } else if ((*cur >= 0x80) && ((doc == NULL) || (doc->encoding == NULL))) { /* * We assume we have UTF-8 content. */ unsigned char tmp[12]; int val = 0, l = 1; if (base != cur) xmlBufAdd(buf, base, cur - base); if (*cur < 0xC0) { xmlSaveErr(XML_SAVE_NOT_UTF8, (xmlNodePtr) attr, NULL); if (doc != NULL) doc->encoding = xmlStrdup(BAD_CAST "ISO-8859-1"); xmlSerializeHexCharRef(tmp, *cur); xmlBufAdd(buf, (xmlChar *) tmp, -1); cur++; base = cur; continue; } else if (*cur < 0xE0) { val = (cur[0]) & 0x1F; val <<= 6; val |= (cur[1]) & 0x3F; l = 2; } else if (*cur < 0xF0) { val = (cur[0]) & 0x0F; val <<= 6; val |= (cur[1]) & 0x3F; val <<= 6; val |= (cur[2]) & 0x3F; l = 3; } else if (*cur < 0xF8) { val = (cur[0]) & 0x07; val <<= 6; val |= (cur[1]) & 0x3F; val <<= 6; val |= (cur[2]) & 0x3F; val <<= 6; val |= (cur[3]) & 0x3F; l = 4; } if ((l == 1) || (!IS_CHAR(val))) { xmlSaveErr(XML_SAVE_CHAR_INVALID, (xmlNodePtr) attr, NULL); if (doc != NULL) doc->encoding = xmlStrdup(BAD_CAST "ISO-8859-1"); xmlSerializeHexCharRef(tmp, *cur); xmlBufAdd(buf, (xmlChar *) tmp, -1); cur++; base = cur; continue; } /* * We could do multiple things here. Just save * as a char ref */ xmlSerializeHexCharRef(tmp, val); xmlBufAdd(buf, (xmlChar *) tmp, -1); cur += l; base = cur; } else { cur++; } } if (base != cur) xmlBufAdd(buf, base, cur - base); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-502'], 'message': 'Avoid an out of bound access when serializing malformed strings For https://bugzilla.gnome.org/show_bug.cgi?id=766414 * xmlsave.c: xmlBufAttrSerializeTxtContent() if an attribute value is not UTF-8 be more careful when serializing it as we may do an out of bound access as a result.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(bcdiv) { char *left, *right; int left_len, right_len; long scale_param = 0; bc_num first, second, result; int scale = BCG(bc_precision), argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc TSRMLS_CC, "ss|l", &left, &left_len, &right, &right_len, &scale_param) == FAILURE) { return; } if (argc == 3) { scale = (int) ((int)scale_param < 0) ? 0 : scale_param; } bc_init_num(&first TSRMLS_CC); bc_init_num(&second TSRMLS_CC); bc_init_num(&result TSRMLS_CC); php_str2num(&first, left TSRMLS_CC); php_str2num(&second, right TSRMLS_CC); switch (bc_divide(first, second, &result, scale TSRMLS_CC)) { case 0: /* OK */ if (result->n_scale > scale) { result->n_scale = scale; } Z_STRVAL_P(return_value) = bc_num2str(result); Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value)); Z_TYPE_P(return_value) = IS_STRING; break; case -1: /* division by zero */ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Division by zero"); break; } bc_free_num(&first); bc_free_num(&second); bc_free_num(&result); return; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #72093: bcpowmod accepts negative scale and corrupts _one_ definition We can not modify result since it can be copy of _zero_ or _one_, etc. and "copy" in bcmath is just bumping the refcount. Conflicts: main/php_version.h'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(bcmul) { char *left, *right; int left_len, right_len; long scale_param = 0; bc_num first, second, result; int scale = BCG(bc_precision), argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc TSRMLS_CC, "ss|l", &left, &left_len, &right, &right_len, &scale_param) == FAILURE) { return; } if (argc == 3) { scale = (int) ((int)scale_param < 0) ? 0 : scale_param; } bc_init_num(&first TSRMLS_CC); bc_init_num(&second TSRMLS_CC); bc_init_num(&result TSRMLS_CC); php_str2num(&first, left TSRMLS_CC); php_str2num(&second, right TSRMLS_CC); bc_multiply (first, second, &result, scale TSRMLS_CC); if (result->n_scale > scale) { result->n_scale = scale; } Z_STRVAL_P(return_value) = bc_num2str(result); Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value)); Z_TYPE_P(return_value) = IS_STRING; bc_free_num(&first); bc_free_num(&second); bc_free_num(&result); return; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #72093: bcpowmod accepts negative scale and corrupts _one_ definition We can not modify result since it can be copy of _zero_ or _one_, etc. and "copy" in bcmath is just bumping the refcount. Conflicts: main/php_version.h'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(bcpow) { char *left, *right; int left_len, right_len; long scale_param = 0; bc_num first, second, result; int scale = BCG(bc_precision), argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc TSRMLS_CC, "ss|l", &left, &left_len, &right, &right_len, &scale_param) == FAILURE) { return; } if (argc == 3) { scale = (int) ((int)scale_param < 0) ? 0 : scale_param; } bc_init_num(&first TSRMLS_CC); bc_init_num(&second TSRMLS_CC); bc_init_num(&result TSRMLS_CC); php_str2num(&first, left TSRMLS_CC); php_str2num(&second, right TSRMLS_CC); bc_raise (first, second, &result, scale TSRMLS_CC); if (result->n_scale > scale) { result->n_scale = scale; } Z_STRVAL_P(return_value) = bc_num2str(result); Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value)); Z_TYPE_P(return_value) = IS_STRING; bc_free_num(&first); bc_free_num(&second); bc_free_num(&result); return; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #72093: bcpowmod accepts negative scale and corrupts _one_ definition We can not modify result since it can be copy of _zero_ or _one_, etc. and "copy" in bcmath is just bumping the refcount. Conflicts: main/php_version.h'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(bccomp) { char *left, *right; int left_len, right_len; long scale_param = 0; bc_num first, second; int scale = BCG(bc_precision), argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc TSRMLS_CC, "ss|l", &left, &left_len, &right, &right_len, &scale_param) == FAILURE) { return; } if (argc == 3) { scale = (int) ((int)scale_param < 0) ? 0 : scale_param; } bc_init_num(&first TSRMLS_CC); bc_init_num(&second TSRMLS_CC); bc_str2num(&first, left, scale TSRMLS_CC); bc_str2num(&second, right, scale TSRMLS_CC); Z_LVAL_P(return_value) = bc_compare(first, second); Z_TYPE_P(return_value) = IS_LONG; bc_free_num(&first); bc_free_num(&second); return; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #72093: bcpowmod accepts negative scale and corrupts _one_ definition We can not modify result since it can be copy of _zero_ or _one_, etc. and "copy" in bcmath is just bumping the refcount. Conflicts: main/php_version.h'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(bcscale) { long new_scale; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &new_scale) == FAILURE) { return; } BCG(bc_precision) = ((int)new_scale < 0) ? 0 : new_scale; RETURN_TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix bug #72093: bcpowmod accepts negative scale and corrupts _one_ definition We can not modify result since it can be copy of _zero_ or _one_, etc. and "copy" in bcmath is just bumping the refcount. Conflicts: main/php_version.h'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void exif_process_TIFF_in_JPEG(image_info_type *ImageInfo, char *CharBuf, size_t length, size_t displacement TSRMLS_DC) { unsigned exif_value_2a, offset_of_ifd; /* set the thumbnail stuff to nothing so we can test to see if they get set up */ if (memcmp(CharBuf, "II", 2) == 0) { ImageInfo->motorola_intel = 0; } else if (memcmp(CharBuf, "MM", 2) == 0) { ImageInfo->motorola_intel = 1; } else { exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid TIFF alignment marker"); return; } /* Check the next two values for correctness. */ exif_value_2a = php_ifd_get16u(CharBuf+2, ImageInfo->motorola_intel); offset_of_ifd = php_ifd_get32u(CharBuf+4, ImageInfo->motorola_intel); if ( exif_value_2a != 0x2a || offset_of_ifd < 0x08) { exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid TIFF start (1)"); return; } if (offset_of_ifd > length) { exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid IFD start"); return; } ImageInfo->sections_found |= FOUND_IFD0; /* First directory starts at offset 8. Offsets starts at 0. */ exif_process_IFD_in_JPEG(ImageInfo, CharBuf+offset_of_ifd, CharBuf, length/*-14*/, displacement, SECTION_IFD0 TSRMLS_CC); #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process TIFF in JPEG done"); #endif /* Compute the CCD width, in milimeters. */ if (ImageInfo->FocalplaneXRes != 0) { ImageInfo->CCDWidth = (float)(ImageInfo->ExifImageWidth * ImageInfo->FocalplaneUnits / ImageInfo->FocalplaneXRes); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix bug #72094 - Out of bounds heap read access in exif header processing'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_MINIT_FUNCTION(xml) { le_xml_parser = zend_register_list_destructors_ex(xml_parser_dtor, NULL, "xml", module_number); REGISTER_LONG_CONSTANT("XML_ERROR_NONE", XML_ERROR_NONE, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_NO_MEMORY", XML_ERROR_NO_MEMORY, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_SYNTAX", XML_ERROR_SYNTAX, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_NO_ELEMENTS", XML_ERROR_NO_ELEMENTS, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_INVALID_TOKEN", XML_ERROR_INVALID_TOKEN, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_UNCLOSED_TOKEN", XML_ERROR_UNCLOSED_TOKEN, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_PARTIAL_CHAR", XML_ERROR_PARTIAL_CHAR, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_TAG_MISMATCH", XML_ERROR_TAG_MISMATCH, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_DUPLICATE_ATTRIBUTE", XML_ERROR_DUPLICATE_ATTRIBUTE, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_JUNK_AFTER_DOC_ELEMENT", XML_ERROR_JUNK_AFTER_DOC_ELEMENT, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_PARAM_ENTITY_REF", XML_ERROR_PARAM_ENTITY_REF, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_UNDEFINED_ENTITY", XML_ERROR_UNDEFINED_ENTITY, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_RECURSIVE_ENTITY_REF", XML_ERROR_RECURSIVE_ENTITY_REF, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_ASYNC_ENTITY", XML_ERROR_ASYNC_ENTITY, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_BAD_CHAR_REF", XML_ERROR_BAD_CHAR_REF, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_BINARY_ENTITY_REF", XML_ERROR_BINARY_ENTITY_REF, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF", XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_MISPLACED_XML_PI", XML_ERROR_MISPLACED_XML_PI, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_UNKNOWN_ENCODING", XML_ERROR_UNKNOWN_ENCODING, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_INCORRECT_ENCODING", XML_ERROR_INCORRECT_ENCODING, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_UNCLOSED_CDATA_SECTION", XML_ERROR_UNCLOSED_CDATA_SECTION, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_ERROR_EXTERNAL_ENTITY_HANDLING", XML_ERROR_EXTERNAL_ENTITY_HANDLING, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_OPTION_CASE_FOLDING", PHP_XML_OPTION_CASE_FOLDING, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_OPTION_TARGET_ENCODING", PHP_XML_OPTION_TARGET_ENCODING, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_OPTION_SKIP_TAGSTART", PHP_XML_OPTION_SKIP_TAGSTART, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("XML_OPTION_SKIP_WHITE", PHP_XML_OPTION_SKIP_WHITE, CONST_CS|CONST_PERSISTENT); /* this object should not be pre-initialised at compile time, as the order of members may vary */ php_xml_mem_hdlrs.malloc_fcn = php_xml_malloc_wrapper; php_xml_mem_hdlrs.realloc_fcn = php_xml_realloc_wrapper; php_xml_mem_hdlrs.free_fcn = php_xml_free_wrapper; #ifdef LIBXML_EXPAT_COMPAT REGISTER_STRING_CONSTANT("XML_SAX_IMPL", "libxml", CONST_CS|CONST_PERSISTENT); #else REGISTER_STRING_CONSTANT("XML_SAX_IMPL", "expat", CONST_CS|CONST_PERSISTENT); #endif return SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix bug #72099: xml_parse_into_struct segmentation fault'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void _xml_characterDataHandler(void *userData, const XML_Char *s, int len) { xml_parser *parser = (xml_parser *)userData; if (parser) { zval *retval, *args[2]; if (parser->characterDataHandler) { args[0] = _xml_resource_zval(parser->index); args[1] = _xml_xmlchar_zval(s, len, parser->target_encoding); if ((retval = xml_call_handler(parser, parser->characterDataHandler, parser->characterDataPtr, 2, args))) { zval_ptr_dtor(&retval); } } if (parser->data) { int i; int doprint = 0; char *decoded_value; int decoded_len; decoded_value = xml_utf8_decode(s,len,&decoded_len,parser->target_encoding); for (i = 0; i < decoded_len; i++) { switch (decoded_value[i]) { case ' ': case '\t': case '\n': continue; default: doprint = 1; break; } if (doprint) { break; } } if (doprint || (! parser->skipwhite)) { if (parser->lastwasopen) { zval **myval; /* check if the current tag already has a value - if yes append to that! */ if (zend_hash_find(Z_ARRVAL_PP(parser->ctag),"value",sizeof("value"),(void **) &myval) == SUCCESS) { int newlen = Z_STRLEN_PP(myval) + decoded_len; Z_STRVAL_PP(myval) = erealloc(Z_STRVAL_PP(myval),newlen+1); strncpy(Z_STRVAL_PP(myval) + Z_STRLEN_PP(myval), decoded_value, decoded_len + 1); Z_STRLEN_PP(myval) += decoded_len; efree(decoded_value); } else { add_assoc_string(*(parser->ctag),"value",decoded_value,0); } } else { zval *tag; zval **curtag, **mytype, **myval; HashPosition hpos=NULL; zend_hash_internal_pointer_end_ex(Z_ARRVAL_P(parser->data), &hpos); if (hpos && (zend_hash_get_current_data_ex(Z_ARRVAL_P(parser->data), (void **) &curtag, &hpos) == SUCCESS)) { if (zend_hash_find(Z_ARRVAL_PP(curtag),"type",sizeof("type"),(void **) &mytype) == SUCCESS) { if (!strcmp(Z_STRVAL_PP(mytype), "cdata")) { if (zend_hash_find(Z_ARRVAL_PP(curtag),"value",sizeof("value"),(void **) &myval) == SUCCESS) { int newlen = Z_STRLEN_PP(myval) + decoded_len; Z_STRVAL_PP(myval) = erealloc(Z_STRVAL_PP(myval),newlen+1); strncpy(Z_STRVAL_PP(myval) + Z_STRLEN_PP(myval), decoded_value, decoded_len + 1); Z_STRLEN_PP(myval) += decoded_len; efree(decoded_value); return; } } } } if (parser->level <= XML_MAXLEVEL) { MAKE_STD_ZVAL(tag); array_init(tag); _xml_add_to_info(parser,parser->ltags[parser->level-1] + parser->toffset); add_assoc_string(tag,"tag",parser->ltags[parser->level-1] + parser->toffset,1); add_assoc_string(tag,"value",decoded_value,0); add_assoc_string(tag,"type","cdata",1); add_assoc_long(tag,"level",parser->level); zend_hash_next_index_insert(Z_ARRVAL_P(parser->data),&tag,sizeof(zval*),NULL); } else if (parser->level == (XML_MAXLEVEL + 1)) { TSRMLS_FETCH(); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Maximum depth exceeded - Results truncated"); } } } else { efree(decoded_value); } } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix bug #72099: xml_parse_into_struct segmentation fault'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void _xml_endElementHandler(void *userData, const XML_Char *name) { xml_parser *parser = (xml_parser *)userData; char *tag_name; if (parser) { zval *retval, *args[2]; tag_name = _xml_decode_tag(parser, name); if (parser->endElementHandler) { args[0] = _xml_resource_zval(parser->index); args[1] = _xml_string_zval(((char *) tag_name) + parser->toffset); if ((retval = xml_call_handler(parser, parser->endElementHandler, parser->endElementPtr, 2, args))) { zval_ptr_dtor(&retval); } } if (parser->data) { zval *tag; if (parser->lastwasopen) { add_assoc_string(*(parser->ctag),"type","complete",1); } else { MAKE_STD_ZVAL(tag); array_init(tag); _xml_add_to_info(parser,((char *) tag_name) + parser->toffset); add_assoc_string(tag,"tag",((char *) tag_name) + parser->toffset,1); /* cast to avoid gcc-warning */ add_assoc_string(tag,"type","close",1); add_assoc_long(tag,"level",parser->level); zend_hash_next_index_insert(Z_ARRVAL_P(parser->data),&tag,sizeof(zval*),NULL); } parser->lastwasopen = 0; } efree(tag_name); if ((parser->ltags) && (parser->level <= XML_MAXLEVEL)) { efree(parser->ltags[parser->level-1]); } parser->level--; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix bug #72099: xml_parse_into_struct segmentation fault'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(xml_parse_into_struct) { xml_parser *parser; zval *pind, **xdata, **info = NULL; char *data; int data_len, ret; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rsZ|Z", &pind, &data, &data_len, &xdata, &info) == FAILURE) { return; } if (info) { zval_dtor(*info); array_init(*info); } ZEND_FETCH_RESOURCE(parser,xml_parser *, &pind, -1, "XML Parser", le_xml_parser); zval_dtor(*xdata); array_init(*xdata); parser->data = *xdata; if (info) { parser->info = *info; } parser->level = 0; parser->ltags = safe_emalloc(XML_MAXLEVEL, sizeof(char *), 0); XML_SetDefaultHandler(parser->parser, _xml_defaultHandler); XML_SetElementHandler(parser->parser, _xml_startElementHandler, _xml_endElementHandler); XML_SetCharacterDataHandler(parser->parser, _xml_characterDataHandler); parser->isparsing = 1; ret = XML_Parse(parser->parser, data, data_len, 1); parser->isparsing = 0; RETVAL_LONG(ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix bug #72099: xml_parse_into_struct segmentation fault'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void _xml_unparsedEntityDeclHandler(void *userData, const XML_Char *entityName, const XML_Char *base, const XML_Char *systemId, const XML_Char *publicId, const XML_Char *notationName) { xml_parser *parser = (xml_parser *)userData; if (parser && parser->unparsedEntityDeclHandler) { zval *retval, *args[6]; args[0] = _xml_resource_zval(parser->index); args[1] = _xml_xmlchar_zval(entityName, 0, parser->target_encoding); args[2] = _xml_xmlchar_zval(base, 0, parser->target_encoding); args[3] = _xml_xmlchar_zval(systemId, 0, parser->target_encoding); args[4] = _xml_xmlchar_zval(publicId, 0, parser->target_encoding); args[5] = _xml_xmlchar_zval(notationName, 0, parser->target_encoding); if ((retval = xml_call_handler(parser, parser->unparsedEntityDeclHandler, parser->unparsedEntityDeclPtr, 6, args))) { zval_ptr_dtor(&retval); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix bug #72099: xml_parse_into_struct segmentation fault'</s>
<s>[INST] Given the following code containing errors, provide 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 zval *_xml_xmlchar_zval(const XML_Char *s, int len, const XML_Char *encoding) { zval *ret; MAKE_STD_ZVAL(ret); if (s == NULL) { ZVAL_FALSE(ret); return ret; } if (len == 0) { len = _xml_xmlcharlen(s); } Z_TYPE_P(ret) = IS_STRING; Z_STRVAL_P(ret) = xml_utf8_decode(s, len, &Z_STRLEN_P(ret), encoding); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix bug #72099: xml_parse_into_struct segmentation fault'</s>
<s>[INST] Given the following code containing errors, provide 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 zval *xml_call_handler(xml_parser *parser, zval *handler, zend_function *function_ptr, int argc, zval **argv) { int i; TSRMLS_FETCH(); if (parser && handler && !EG(exception)) { zval ***args; zval *retval; int result; zend_fcall_info fci; args = safe_emalloc(sizeof(zval **), argc, 0); for (i = 0; i < argc; i++) { args[i] = &argv[i]; } fci.size = sizeof(fci); fci.function_table = EG(function_table); fci.function_name = handler; fci.symbol_table = NULL; fci.object_ptr = parser->object; fci.retval_ptr_ptr = &retval; fci.param_count = argc; fci.params = args; fci.no_separation = 0; /*fci.function_handler_cache = &function_ptr;*/ result = zend_call_function(&fci, NULL TSRMLS_CC); if (result == FAILURE) { zval **method; zval **obj; if (Z_TYPE_P(handler) == IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call handler %s()", Z_STRVAL_P(handler)); } else if (zend_hash_index_find(Z_ARRVAL_P(handler), 0, (void **) &obj) == SUCCESS && zend_hash_index_find(Z_ARRVAL_P(handler), 1, (void **) &method) == SUCCESS && Z_TYPE_PP(obj) == IS_OBJECT && Z_TYPE_PP(method) == IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call handler %s::%s()", Z_OBJCE_PP(obj)->name, Z_STRVAL_PP(method)); } else php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call handler"); } for (i = 0; i < argc; i++) { zval_ptr_dtor(args[i]); } efree(args); if (result == FAILURE) { return NULL; } else { return EG(exception) ? NULL : retval; } } else { for (i = 0; i < argc; i++) { zval_ptr_dtor(&argv[i]); } return NULL; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix bug #72099: xml_parse_into_struct segmentation fault'</s>
<s>[INST] Given the following code containing errors, provide 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 llc_cmsg_rcv(struct msghdr *msg, struct sk_buff *skb) { struct llc_sock *llc = llc_sk(skb->sk); if (llc->cmsg_flags & LLC_CMSG_PKTINFO) { struct llc_pktinfo info; info.lpi_ifindex = llc_sk(skb->sk)->dev->ifindex; llc_pdu_decode_dsap(skb, &info.lpi_sap); llc_pdu_decode_da(skb, info.lpi_mac); put_cmsg(msg, SOL_LLC, LLC_OPT_PKTINFO, sizeof(info), &info); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'net: fix infoleak in llc The stack object “info” has a total size of 12 bytes. Its last byte is padding which is not initialized and leaked via “put_cmsg”. Signed-off-by: Kangjie Lu <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SPL_METHOD(SplDoublyLinkedList, offsetSet) { zval *zindex, *value; spl_dllist_object *intern; if (zend_parse_parameters(ZEND_NUM_ARGS(), "zz", &zindex, &value) == FAILURE) { return; } intern = Z_SPLDLLIST_P(getThis()); if (Z_TYPE_P(zindex) == IS_NULL) { /* $obj[] = ... */ spl_ptr_llist_push(intern->llist, value); } else { /* $obj[$foo] = ... */ zend_long index; spl_ptr_llist_element *element; index = spl_offset_convert_to_long(zindex); if (index < 0 || index >= intern->llist->count) { zval_ptr_dtor(value); zend_throw_exception(spl_ce_OutOfRangeException, "Offset invalid or out of range", 0); return; } element = spl_ptr_llist_offset(intern->llist, index, intern->flags & SPL_DLLIST_IT_LIFO); if (element != NULL) { /* call dtor on the old element as in spl_ptr_llist_pop */ if (intern->llist->dtor) { intern->llist->dtor(element); } /* the element is replaced, delref the old one as in * SplDoublyLinkedList::pop() */ zval_ptr_dtor(&element->data); ZVAL_COPY_VALUE(&element->data, value); /* new element, call ctor as in spl_ptr_llist_push */ if (intern->llist->ctor) { intern->llist->ctor(element); } } else { zval_ptr_dtor(value); zend_throw_exception(spl_ce_OutOfRangeException, "Offset invalid", 0); return; } } } /* }}} */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Fix bug #71735: Double-free in SplDoublyLinkedList::offsetSet'</s>
<s>[INST] Given the following code containing errors, provide 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 propagate_one(struct mount *m) { struct mount *child; int type; /* skip ones added by this propagate_mnt() */ if (IS_MNT_NEW(m)) return 0; /* skip if mountpoint isn't covered by it */ if (!is_subdir(mp->m_dentry, m->mnt.mnt_root)) return 0; if (peers(m, last_dest)) { type = CL_MAKE_SHARED; } else { struct mount *n, *p; for (n = m; ; n = p) { p = n->mnt_master; if (p == dest_master || IS_MNT_MARKED(p)) { while (last_dest->mnt_master != p) { last_source = last_source->mnt_master; last_dest = last_source->mnt_parent; } if (!peers(n, last_dest)) { last_source = last_source->mnt_master; last_dest = last_source->mnt_parent; } break; } } type = CL_SLAVE; /* beginning of peer group among the slaves? */ if (IS_MNT_SHARED(m)) type |= CL_MAKE_SHARED; } /* Notice when we are propagating across user namespaces */ if (m->mnt_ns->user_ns != user_ns) type |= CL_UNPRIVILEGED; child = copy_tree(last_source, last_source->mnt.mnt_root, type); if (IS_ERR(child)) return PTR_ERR(child); child->mnt.mnt_flags &= ~MNT_LOCKED; mnt_set_mountpoint(m, mp, child); last_dest = m; last_source = child; if (m->mnt_master != dest_master) { read_seqlock_excl(&mount_lock); SET_MNT_MARK(m->mnt_master); read_sequnlock_excl(&mount_lock); } hlist_add_head(&child->mnt_hash, list); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'propogate_mnt: Handle the first propogated copy being a slave When the first propgated copy was a slave the following oops would result: > BUG: unable to handle kernel NULL pointer dereference at 0000000000000010 > IP: [<ffffffff811fba4e>] propagate_one+0xbe/0x1c0 > PGD bacd4067 PUD bac66067 PMD 0 > Oops: 0000 [#1] SMP > Modules linked in: > CPU: 1 PID: 824 Comm: mount Not tainted 4.6.0-rc5userns+ #1523 > Hardware name: Bochs Bochs, BIOS Bochs 01/01/2007 > task: ffff8800bb0a8000 ti: ffff8800bac3c000 task.ti: ffff8800bac3c000 > RIP: 0010:[<ffffffff811fba4e>] [<ffffffff811fba4e>] propagate_one+0xbe/0x1c0 > RSP: 0018:ffff8800bac3fd38 EFLAGS: 00010283 > RAX: 0000000000000000 RBX: ffff8800bb77ec00 RCX: 0000000000000010 > RDX: 0000000000000000 RSI: ffff8800bb58c000 RDI: ffff8800bb58c480 > RBP: ffff8800bac3fd48 R08: 0000000000000001 R09: 0000000000000000 > R10: 0000000000001ca1 R11: 0000000000001c9d R12: 0000000000000000 > R13: ffff8800ba713800 R14: ffff8800bac3fda0 R15: ffff8800bb77ec00 > FS: 00007f3c0cd9b7e0(0000) GS:ffff8800bfb00000(0000) knlGS:0000000000000000 > CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 > CR2: 0000000000000010 CR3: 00000000bb79d000 CR4: 00000000000006e0 > Stack: > ffff8800bb77ec00 0000000000000000 ffff8800bac3fd88 ffffffff811fbf85 > ffff8800bac3fd98 ffff8800bb77f080 ffff8800ba713800 ffff8800bb262b40 > 0000000000000000 0000000000000000 ffff8800bac3fdd8 ffffffff811f1da0 > Call Trace: > [<ffffffff811fbf85>] propagate_mnt+0x105/0x140 > [<ffffffff811f1da0>] attach_recursive_mnt+0x120/0x1e0 > [<ffffffff811f1ec3>] graft_tree+0x63/0x70 > [<ffffffff811f1f6b>] do_add_mount+0x9b/0x100 > [<ffffffff811f2c1a>] do_mount+0x2aa/0xdf0 > [<ffffffff8117efbe>] ? strndup_user+0x4e/0x70 > [<ffffffff811f3a45>] SyS_mount+0x75/0xc0 > [<ffffffff8100242b>] do_syscall_64+0x4b/0xa0 > [<ffffffff81988f3c>] entry_SYSCALL64_slow_path+0x25/0x25 > Code: 00 00 75 ec 48 89 0d 02 22 22 01 8b 89 10 01 00 00 48 89 05 fd 21 22 01 39 8e 10 01 00 00 0f 84 e0 00 00 00 48 8b 80 d8 00 00 00 <48> 8b 50 10 48 89 05 df 21 22 01 48 89 15 d0 21 22 01 8b 53 30 > RIP [<ffffffff811fba4e>] propagate_one+0xbe/0x1c0 > RSP <ffff8800bac3fd38> > CR2: 0000000000000010 > ---[ end trace 2725ecd95164f217 ]--- This oops happens with the namespace_sem held and can be triggered by non-root users. An all around not pleasant experience. To avoid this scenario when finding the appropriate source mount to copy stop the walk up the mnt_master chain when the first source mount is encountered. Further rewrite the walk up the last_source mnt_master chain so that it is clear what is going on. The reason why the first source mount is special is that it it's mnt_parent is not a mount in the dest_mnt propagation tree, and as such termination conditions based up on the dest_mnt mount propgation tree do not make sense. To avoid other kinds of confusion last_dest is not changed when computing last_source. last_dest is only used once in propagate_one and that is above the point of the code being modified, so changing the global variable is meaningless and confusing. Cc: [email protected] fixes: f2ebb3a921c1ca1e2ddd9242e95a1989a50c4c68 ("smarter propagate_mnt()") Reported-by: Tycho Andersen <[email protected]> Reviewed-by: Seth Forshee <[email protected]> Tested-by: Seth Forshee <[email protected]> Signed-off-by: "Eric W. Biederman" <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int do_anonymous_page(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pte_t *page_table, pmd_t *pmd, unsigned int flags) { struct mem_cgroup *memcg; struct page *page; spinlock_t *ptl; pte_t entry; pte_unmap(page_table); /* Check if we need to add a guard page to the stack */ if (check_stack_guard_page(vma, address) < 0) return VM_FAULT_SIGSEGV; /* Use the zero-page for reads */ if (!(flags & FAULT_FLAG_WRITE) && !mm_forbids_zeropage(mm)) { entry = pte_mkspecial(pfn_pte(my_zero_pfn(address), vma->vm_page_prot)); page_table = pte_offset_map_lock(mm, pmd, address, &ptl); if (!pte_none(*page_table)) goto unlock; goto setpte; } /* Allocate our own private page. */ if (unlikely(anon_vma_prepare(vma))) goto oom; page = alloc_zeroed_user_highpage_movable(vma, address); if (!page) goto oom; if (mem_cgroup_try_charge(page, mm, GFP_KERNEL, &memcg)) goto oom_free_page; /* * The memory barrier inside __SetPageUptodate makes sure that * preceeding stores to the page contents become visible before * the set_pte_at() write. */ __SetPageUptodate(page); entry = mk_pte(page, vma->vm_page_prot); if (vma->vm_flags & VM_WRITE) entry = pte_mkwrite(pte_mkdirty(entry)); page_table = pte_offset_map_lock(mm, pmd, address, &ptl); if (!pte_none(*page_table)) goto release; inc_mm_counter_fast(mm, MM_ANONPAGES); page_add_new_anon_rmap(page, vma, address); mem_cgroup_commit_charge(page, memcg, false); lru_cache_add_active_or_unevictable(page, vma); setpte: set_pte_at(mm, address, page_table, entry); /* No need to invalidate - it was non-present before */ update_mmu_cache(vma, address, page_table); unlock: pte_unmap_unlock(page_table, ptl); return 0; release: mem_cgroup_cancel_charge(page, memcg); page_cache_release(page); goto unlock; oom_free_page: page_cache_release(page); oom: return VM_FAULT_OOM; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'mm: avoid setting up anonymous pages into file mapping Reading page fault handler code I've noticed that under right circumstances kernel would map anonymous pages into file mappings: if the VMA doesn't have vm_ops->fault() and the VMA wasn't fully populated on ->mmap(), kernel would handle page fault to not populated pte with do_anonymous_page(). Let's change page fault handler to use do_anonymous_page() only on anonymous VMA (->vm_ops == NULL) and make sure that the VMA is not shared. For file mappings without vm_ops->fault() or shred VMA without vm_ops, page fault on pte_none() entry would lead to SIGBUS. Signed-off-by: Kirill A. Shutemov <[email protected]> Acked-by: Oleg Nesterov <[email protected]> Cc: Andrew Morton <[email protected]> Cc: Willy Tarreau <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: zip_read_mac_metadata(struct archive_read *a, struct archive_entry *entry, struct zip_entry *rsrc) { struct zip *zip = (struct zip *)a->format->data; unsigned char *metadata, *mp; int64_t offset = archive_filter_bytes(&a->archive, 0); size_t remaining_bytes, metadata_bytes; ssize_t hsize; int ret = ARCHIVE_OK, eof; switch(rsrc->compression) { case 0: /* No compression. */ #ifdef HAVE_ZLIB_H case 8: /* Deflate compression. */ #endif break; default: /* Unsupported compression. */ /* Return a warning. */ archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unsupported ZIP compression method (%s)", compression_name(rsrc->compression)); /* We can't decompress this entry, but we will * be able to skip() it and try the next entry. */ return (ARCHIVE_WARN); } if (rsrc->uncompressed_size > (4 * 1024 * 1024)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Mac metadata is too large: %jd > 4M bytes", (intmax_t)rsrc->uncompressed_size); return (ARCHIVE_WARN); } metadata = malloc((size_t)rsrc->uncompressed_size); if (metadata == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Mac metadata"); return (ARCHIVE_FATAL); } if (offset < rsrc->local_header_offset) __archive_read_consume(a, rsrc->local_header_offset - offset); else if (offset != rsrc->local_header_offset) { __archive_read_seek(a, rsrc->local_header_offset, SEEK_SET); } hsize = zip_get_local_file_header_size(a, 0); __archive_read_consume(a, hsize); remaining_bytes = (size_t)rsrc->compressed_size; metadata_bytes = (size_t)rsrc->uncompressed_size; mp = metadata; eof = 0; while (!eof && remaining_bytes) { const unsigned char *p; ssize_t bytes_avail; size_t bytes_used; p = __archive_read_ahead(a, 1, &bytes_avail); if (p == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated ZIP file header"); ret = ARCHIVE_WARN; goto exit_mac_metadata; } if ((size_t)bytes_avail > remaining_bytes) bytes_avail = remaining_bytes; switch(rsrc->compression) { case 0: /* No compression. */ memcpy(mp, p, bytes_avail); bytes_used = (size_t)bytes_avail; metadata_bytes -= bytes_used; mp += bytes_used; if (metadata_bytes == 0) eof = 1; break; #ifdef HAVE_ZLIB_H case 8: /* Deflate compression. */ { int r; ret = zip_deflate_init(a, zip); if (ret != ARCHIVE_OK) goto exit_mac_metadata; zip->stream.next_in = (Bytef *)(uintptr_t)(const void *)p; zip->stream.avail_in = (uInt)bytes_avail; zip->stream.total_in = 0; zip->stream.next_out = mp; zip->stream.avail_out = (uInt)metadata_bytes; zip->stream.total_out = 0; r = inflate(&zip->stream, 0); switch (r) { case Z_OK: break; case Z_STREAM_END: eof = 1; break; case Z_MEM_ERROR: archive_set_error(&a->archive, ENOMEM, "Out of memory for ZIP decompression"); ret = ARCHIVE_FATAL; goto exit_mac_metadata; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "ZIP decompression failed (%d)", r); ret = ARCHIVE_FATAL; goto exit_mac_metadata; } bytes_used = zip->stream.total_in; metadata_bytes -= zip->stream.total_out; mp += zip->stream.total_out; break; } #endif default: bytes_used = 0; break; } __archive_read_consume(a, bytes_used); remaining_bytes -= bytes_used; } archive_entry_copy_mac_metadata(entry, metadata, (size_t)rsrc->uncompressed_size - metadata_bytes); exit_mac_metadata: __archive_read_seek(a, offset, SEEK_SET); zip->decompress_init = 0; free(metadata); return (ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Issue #656: Fix CVE-2016-1541, VU#862384 When reading OS X metadata entries in Zip archives that were stored without compression, libarchive would use the uncompressed entry size to allocate a buffer but would use the compressed entry size to limit the amount of data copied into that buffer. Since the compressed and uncompressed sizes are provided by data in the archive itself, an attacker could manipulate these values to write data beyond the end of the allocated buffer. This fix provides three new checks to guard against such manipulation and to make libarchive generally more robust when handling this type of entry: 1. If an OS X metadata entry is stored without compression, abort the entire archive if the compressed and uncompressed data sizes do not match. 2. When sanity-checking the size of an OS X metadata entry, abort this entry if either the compressed or uncompressed size is larger than 4MB. 3. When copying data into the allocated buffer, check the copy size against both the compressed entry size and uncompressed entry size.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: struct bpf_prog *bpf_prog_get(u32 ufd) { struct fd f = fdget(ufd); struct bpf_prog *prog; prog = __bpf_prog_get(f); if (IS_ERR(prog)) return prog; atomic_inc(&prog->aux->refcnt); fdput(f); return prog; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'bpf: fix refcnt overflow On a system with >32Gbyte of phyiscal memory and infinite RLIMIT_MEMLOCK, the malicious application may overflow 32-bit bpf program refcnt. It's also possible to overflow map refcnt on 1Tb system. Impose 32k hard limit which means that the same bpf program or map cannot be shared by more than 32k processes. Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs") Reported-by: Jann Horn <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> Acked-by: Daniel Borkmann <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void *bpf_any_get(void *raw, enum bpf_type type) { switch (type) { case BPF_TYPE_PROG: atomic_inc(&((struct bpf_prog *)raw)->aux->refcnt); break; case BPF_TYPE_MAP: bpf_map_inc(raw, true); break; default: WARN_ON_ONCE(1); break; } return raw; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'bpf: fix refcnt overflow On a system with >32Gbyte of phyiscal memory and infinite RLIMIT_MEMLOCK, the malicious application may overflow 32-bit bpf program refcnt. It's also possible to overflow map refcnt on 1Tb system. Impose 32k hard limit which means that the same bpf program or map cannot be shared by more than 32k processes. Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs") Reported-by: Jann Horn <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> Acked-by: Daniel Borkmann <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void *bpf_obj_do_get(const struct filename *pathname, enum bpf_type *type) { struct inode *inode; struct path path; void *raw; int ret; ret = kern_path(pathname->name, LOOKUP_FOLLOW, &path); if (ret) return ERR_PTR(ret); inode = d_backing_inode(path.dentry); ret = inode_permission(inode, MAY_WRITE); if (ret) goto out; ret = bpf_inode_type(inode, type); if (ret) goto out; raw = bpf_any_get(inode->i_private, *type); touch_atime(&path); path_put(&path); return raw; out: path_put(&path); return ERR_PTR(ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'bpf: fix refcnt overflow On a system with >32Gbyte of phyiscal memory and infinite RLIMIT_MEMLOCK, the malicious application may overflow 32-bit bpf program refcnt. It's also possible to overflow map refcnt on 1Tb system. Impose 32k hard limit which means that the same bpf program or map cannot be shared by more than 32k processes. Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs") Reported-by: Jann Horn <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> Acked-by: Daniel Borkmann <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int snd_timer_user_params(struct file *file, struct snd_timer_params __user *_params) { struct snd_timer_user *tu; struct snd_timer_params params; struct snd_timer *t; struct snd_timer_read *tr; struct snd_timer_tread *ttr; int err; tu = file->private_data; if (!tu->timeri) return -EBADFD; t = tu->timeri->timer; if (!t) return -EBADFD; if (copy_from_user(&params, _params, sizeof(params))) return -EFAULT; if (!(t->hw.flags & SNDRV_TIMER_HW_SLAVE) && params.ticks < 1) { err = -EINVAL; goto _end; } if (params.queue_size > 0 && (params.queue_size < 32 || params.queue_size > 1024)) { err = -EINVAL; goto _end; } if (params.filter & ~((1<<SNDRV_TIMER_EVENT_RESOLUTION)| (1<<SNDRV_TIMER_EVENT_TICK)| (1<<SNDRV_TIMER_EVENT_START)| (1<<SNDRV_TIMER_EVENT_STOP)| (1<<SNDRV_TIMER_EVENT_CONTINUE)| (1<<SNDRV_TIMER_EVENT_PAUSE)| (1<<SNDRV_TIMER_EVENT_SUSPEND)| (1<<SNDRV_TIMER_EVENT_RESUME)| (1<<SNDRV_TIMER_EVENT_MSTART)| (1<<SNDRV_TIMER_EVENT_MSTOP)| (1<<SNDRV_TIMER_EVENT_MCONTINUE)| (1<<SNDRV_TIMER_EVENT_MPAUSE)| (1<<SNDRV_TIMER_EVENT_MSUSPEND)| (1<<SNDRV_TIMER_EVENT_MRESUME))) { err = -EINVAL; goto _end; } snd_timer_stop(tu->timeri); spin_lock_irq(&t->lock); tu->timeri->flags &= ~(SNDRV_TIMER_IFLG_AUTO| SNDRV_TIMER_IFLG_EXCLUSIVE| SNDRV_TIMER_IFLG_EARLY_EVENT); if (params.flags & SNDRV_TIMER_PSFLG_AUTO) tu->timeri->flags |= SNDRV_TIMER_IFLG_AUTO; if (params.flags & SNDRV_TIMER_PSFLG_EXCLUSIVE) tu->timeri->flags |= SNDRV_TIMER_IFLG_EXCLUSIVE; if (params.flags & SNDRV_TIMER_PSFLG_EARLY_EVENT) tu->timeri->flags |= SNDRV_TIMER_IFLG_EARLY_EVENT; spin_unlock_irq(&t->lock); if (params.queue_size > 0 && (unsigned int)tu->queue_size != params.queue_size) { if (tu->tread) { ttr = kmalloc(params.queue_size * sizeof(*ttr), GFP_KERNEL); if (ttr) { kfree(tu->tqueue); tu->queue_size = params.queue_size; tu->tqueue = ttr; } } else { tr = kmalloc(params.queue_size * sizeof(*tr), GFP_KERNEL); if (tr) { kfree(tu->queue); tu->queue_size = params.queue_size; tu->queue = tr; } } } tu->qhead = tu->qtail = tu->qused = 0; if (tu->timeri->flags & SNDRV_TIMER_IFLG_EARLY_EVENT) { if (tu->tread) { struct snd_timer_tread tread; tread.event = SNDRV_TIMER_EVENT_EARLY; tread.tstamp.tv_sec = 0; tread.tstamp.tv_nsec = 0; tread.val = 0; snd_timer_user_append_to_tqueue(tu, &tread); } else { struct snd_timer_read *r = &tu->queue[0]; r->resolution = 0; r->ticks = 0; tu->qused++; tu->qtail++; } } tu->filter = params.filter; tu->ticks = params.ticks; err = 0; _end: if (copy_to_user(_params, &params, sizeof(params))) return -EFAULT; return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'ALSA: timer: Fix leak in SNDRV_TIMER_IOCTL_PARAMS The stack object “tread” has a total size of 32 bytes. Its field “event” and “val” both contain 4 bytes padding. These 8 bytes padding bytes are sent to user without being initialized. Signed-off-by: Kangjie Lu <[email protected]> Signed-off-by: Takashi Iwai <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void snd_timer_user_tinterrupt(struct snd_timer_instance *timeri, unsigned long resolution, unsigned long ticks) { struct snd_timer_user *tu = timeri->callback_data; struct snd_timer_tread *r, r1; struct timespec tstamp; int prev, append = 0; memset(&tstamp, 0, sizeof(tstamp)); spin_lock(&tu->qlock); if ((tu->filter & ((1 << SNDRV_TIMER_EVENT_RESOLUTION) | (1 << SNDRV_TIMER_EVENT_TICK))) == 0) { spin_unlock(&tu->qlock); return; } if (tu->last_resolution != resolution || ticks > 0) { if (timer_tstamp_monotonic) ktime_get_ts(&tstamp); else getnstimeofday(&tstamp); } if ((tu->filter & (1 << SNDRV_TIMER_EVENT_RESOLUTION)) && tu->last_resolution != resolution) { r1.event = SNDRV_TIMER_EVENT_RESOLUTION; r1.tstamp = tstamp; r1.val = resolution; snd_timer_user_append_to_tqueue(tu, &r1); tu->last_resolution = resolution; append++; } if ((tu->filter & (1 << SNDRV_TIMER_EVENT_TICK)) == 0) goto __wake; if (ticks == 0) goto __wake; if (tu->qused > 0) { prev = tu->qtail == 0 ? tu->queue_size - 1 : tu->qtail - 1; r = &tu->tqueue[prev]; if (r->event == SNDRV_TIMER_EVENT_TICK) { r->tstamp = tstamp; r->val += ticks; append++; goto __wake; } } r1.event = SNDRV_TIMER_EVENT_TICK; r1.tstamp = tstamp; r1.val = ticks; snd_timer_user_append_to_tqueue(tu, &r1); append++; __wake: spin_unlock(&tu->qlock); if (append == 0) return; kill_fasync(&tu->fasync, SIGIO, POLL_IN); wake_up(&tu->qchange_sleep); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'ALSA: timer: Fix leak in events via snd_timer_user_tinterrupt The stack object “r1” has a total size of 32 bytes. Its field “event” and “val” both contain 4 bytes padding. These 8 bytes padding bytes are sent to user without being initialized. Signed-off-by: Kangjie Lu <[email protected]> Signed-off-by: Takashi Iwai <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: polarssl_connect_step1(struct connectdata *conn, int sockindex) { struct SessionHandle *data = conn->data; struct ssl_connect_data* connssl = &conn->ssl[sockindex]; bool sni = TRUE; /* default is SNI enabled */ int ret = -1; #ifdef ENABLE_IPV6 struct in6_addr addr; #else struct in_addr addr; #endif void *old_session = NULL; char errorbuf[128]; errorbuf[0]=0; /* PolarSSL only supports SSLv3 and TLSv1 */ if(data->set.ssl.version == CURL_SSLVERSION_SSLv2) { failf(data, "PolarSSL does not support SSLv2"); return CURLE_SSL_CONNECT_ERROR; } else if(data->set.ssl.version == CURL_SSLVERSION_SSLv3) sni = FALSE; /* SSLv3 has no SNI */ #ifdef THREADING_SUPPORT entropy_init_mutex(&entropy); if((ret = ctr_drbg_init(&connssl->ctr_drbg, entropy_func_mutex, &entropy, NULL, 0)) != 0) { #ifdef POLARSSL_ERROR_C error_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* POLARSSL_ERROR_C */ failf(data, "Failed - PolarSSL: ctr_drbg_init returned (-0x%04X) %s\n", -ret, errorbuf); } #else entropy_init(&connssl->entropy); if((ret = ctr_drbg_init(&connssl->ctr_drbg, entropy_func, &connssl->entropy, NULL, 0)) != 0) { #ifdef POLARSSL_ERROR_C error_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* POLARSSL_ERROR_C */ failf(data, "Failed - PolarSSL: ctr_drbg_init returned (-0x%04X) %s\n", -ret, errorbuf); } #endif /* THREADING_SUPPORT */ /* Load the trusted CA */ memset(&connssl->cacert, 0, sizeof(x509_crt)); if(data->set.str[STRING_SSL_CAFILE]) { ret = x509_crt_parse_file(&connssl->cacert, data->set.str[STRING_SSL_CAFILE]); if(ret<0) { #ifdef POLARSSL_ERROR_C error_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* POLARSSL_ERROR_C */ failf(data, "Error reading ca cert file %s - PolarSSL: (-0x%04X) %s", data->set.str[STRING_SSL_CAFILE], -ret, errorbuf); if(data->set.ssl.verifypeer) return CURLE_SSL_CACERT_BADFILE; } } if(data->set.str[STRING_SSL_CAPATH]) { ret = x509_crt_parse_path(&connssl->cacert, data->set.str[STRING_SSL_CAPATH]); if(ret<0) { #ifdef POLARSSL_ERROR_C error_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* POLARSSL_ERROR_C */ failf(data, "Error reading ca cert path %s - PolarSSL: (-0x%04X) %s", data->set.str[STRING_SSL_CAPATH], -ret, errorbuf); if(data->set.ssl.verifypeer) return CURLE_SSL_CACERT_BADFILE; } } /* Load the client certificate */ memset(&connssl->clicert, 0, sizeof(x509_crt)); if(data->set.str[STRING_CERT]) { ret = x509_crt_parse_file(&connssl->clicert, data->set.str[STRING_CERT]); if(ret) { #ifdef POLARSSL_ERROR_C error_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* POLARSSL_ERROR_C */ failf(data, "Error reading client cert file %s - PolarSSL: (-0x%04X) %s", data->set.str[STRING_CERT], -ret, errorbuf); return CURLE_SSL_CERTPROBLEM; } } /* Load the client private key */ if(data->set.str[STRING_KEY]) { pk_context pk; pk_init(&pk); ret = pk_parse_keyfile(&pk, data->set.str[STRING_KEY], data->set.str[STRING_KEY_PASSWD]); if(ret == 0 && !pk_can_do(&pk, POLARSSL_PK_RSA)) ret = POLARSSL_ERR_PK_TYPE_MISMATCH; if(ret == 0) rsa_copy(&connssl->rsa, pk_rsa(pk)); else rsa_free(&connssl->rsa); pk_free(&pk); if(ret) { #ifdef POLARSSL_ERROR_C error_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* POLARSSL_ERROR_C */ failf(data, "Error reading private key %s - PolarSSL: (-0x%04X) %s", data->set.str[STRING_KEY], -ret, errorbuf); return CURLE_SSL_CERTPROBLEM; } } /* Load the CRL */ memset(&connssl->crl, 0, sizeof(x509_crl)); if(data->set.str[STRING_SSL_CRLFILE]) { ret = x509_crl_parse_file(&connssl->crl, data->set.str[STRING_SSL_CRLFILE]); if(ret) { #ifdef POLARSSL_ERROR_C error_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* POLARSSL_ERROR_C */ failf(data, "Error reading CRL file %s - PolarSSL: (-0x%04X) %s", data->set.str[STRING_SSL_CRLFILE], -ret, errorbuf); return CURLE_SSL_CRL_BADFILE; } } infof(data, "PolarSSL: Connecting to %s:%d\n", conn->host.name, conn->remote_port); if(ssl_init(&connssl->ssl)) { failf(data, "PolarSSL: ssl_init failed"); return CURLE_SSL_CONNECT_ERROR; } switch(data->set.ssl.version) { default: case CURL_SSLVERSION_DEFAULT: case CURL_SSLVERSION_TLSv1: ssl_set_min_version(&connssl->ssl, SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1); break; case CURL_SSLVERSION_SSLv3: ssl_set_min_version(&connssl->ssl, SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0); ssl_set_max_version(&connssl->ssl, SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0); infof(data, "PolarSSL: Forced min. SSL Version to be SSLv3\n"); break; case CURL_SSLVERSION_TLSv1_0: ssl_set_min_version(&connssl->ssl, SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1); ssl_set_max_version(&connssl->ssl, SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1); infof(data, "PolarSSL: Forced min. SSL Version to be TLS 1.0\n"); break; case CURL_SSLVERSION_TLSv1_1: ssl_set_min_version(&connssl->ssl, SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_2); ssl_set_max_version(&connssl->ssl, SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_2); infof(data, "PolarSSL: Forced min. SSL Version to be TLS 1.1\n"); break; case CURL_SSLVERSION_TLSv1_2: ssl_set_min_version(&connssl->ssl, SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3); ssl_set_max_version(&connssl->ssl, SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3); infof(data, "PolarSSL: Forced min. SSL Version to be TLS 1.2\n"); break; } ssl_set_endpoint(&connssl->ssl, SSL_IS_CLIENT); ssl_set_authmode(&connssl->ssl, SSL_VERIFY_OPTIONAL); ssl_set_rng(&connssl->ssl, ctr_drbg_random, &connssl->ctr_drbg); ssl_set_bio(&connssl->ssl, net_recv, &conn->sock[sockindex], net_send, &conn->sock[sockindex]); ssl_set_ciphersuites(&connssl->ssl, ssl_list_ciphersuites()); if(!Curl_ssl_getsessionid(conn, &old_session, NULL)) { ret = ssl_set_session(&connssl->ssl, old_session); if(ret) { failf(data, "ssl_set_session returned -0x%x", -ret); return CURLE_SSL_CONNECT_ERROR; } infof(data, "PolarSSL re-using session\n"); } ssl_set_ca_chain(&connssl->ssl, &connssl->cacert, &connssl->crl, conn->host.name); ssl_set_own_cert_rsa(&connssl->ssl, &connssl->clicert, &connssl->rsa); if(!Curl_inet_pton(AF_INET, conn->host.name, &addr) && #ifdef ENABLE_IPV6 !Curl_inet_pton(AF_INET6, conn->host.name, &addr) && #endif sni && ssl_set_hostname(&connssl->ssl, conn->host.name)) { infof(data, "WARNING: failed to configure " "server name indication (SNI) TLS extension\n"); } #ifdef HAS_ALPN if(conn->bits.tls_enable_alpn) { static const char* protocols[3]; int cur = 0; #ifdef USE_NGHTTP2 if(data->set.httpversion >= CURL_HTTP_VERSION_2) { protocols[cur++] = NGHTTP2_PROTO_VERSION_ID; infof(data, "ALPN, offering %s\n", NGHTTP2_PROTO_VERSION_ID); } #endif protocols[cur++] = ALPN_HTTP_1_1; infof(data, "ALPN, offering %s\n", ALPN_HTTP_1_1); protocols[cur] = NULL; ssl_set_alpn_protocols(&connssl->ssl, protocols); } #endif #ifdef POLARSSL_DEBUG ssl_set_dbg(&connssl->ssl, polarssl_debug, data); #endif connssl->connecting_state = ssl_connect_2; return CURLE_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'mbedtls/polarssl: set "hostname" unconditionally ...as otherwise the TLS libs will skip the CN/SAN check and just allow connection to any server. curl previously skipped this function when SNI wasn't used or when connecting to an IP address specified host. CVE-2016-3739 Bug: https://curl.haxx.se/docs/adv_20160518A.html Reported-by: Moti Avrahami'</s>
<s>[INST] Given the following code containing errors, provide 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 color_cmyk_to_rgb(opj_image_t *image) { float C, M, Y, K; float sC, sM, sY, sK; unsigned int w, h, max, i; w = image->comps[0].w; h = image->comps[0].h; if(image->numcomps < 4) return; max = w * h; sC = 1.0F / (float)((1 << image->comps[0].prec) - 1); sM = 1.0F / (float)((1 << image->comps[1].prec) - 1); sY = 1.0F / (float)((1 << image->comps[2].prec) - 1); sK = 1.0F / (float)((1 << image->comps[3].prec) - 1); for(i = 0; i < max; ++i) { /* CMYK values from 0 to 1 */ C = (float)(image->comps[0].data[i]) * sC; M = (float)(image->comps[1].data[i]) * sM; Y = (float)(image->comps[2].data[i]) * sY; K = (float)(image->comps[3].data[i]) * sK; /* Invert all CMYK values */ C = 1.0F - C; M = 1.0F - M; Y = 1.0F - Y; K = 1.0F - K; /* CMYK -> RGB : RGB results from 0 to 255 */ image->comps[0].data[i] = (int)(255.0F * C * K); /* R */ image->comps[1].data[i] = (int)(255.0F * M * K); /* G */ image->comps[2].data[i] = (int)(255.0F * Y * K); /* B */ } free(image->comps[3].data); image->comps[3].data = NULL; image->comps[0].prec = 8; image->comps[1].prec = 8; image->comps[2].prec = 8; image->numcomps -= 1; image->color_space = OPJ_CLRSPC_SRGB; for (i = 3; i < image->numcomps; ++i) { memcpy(&(image->comps[i]), &(image->comps[i+1]), sizeof(image->comps[i])); } }/* color_cmyk_to_rgb() */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-284'], 'message': 'Fix Heap Buffer Overflow in function color_cmyk_to_rgb Fix uclouvain/openjpeg#774'</s>