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 struct sem_undo *find_alloc_undo(struct ipc_namespace *ns, int semid) { struct sem_array *sma; struct sem_undo_list *ulp; struct sem_undo *un, *new; int nsems; int error; error = get_undo_list(&ulp); if (error) return ERR_PTR(error); rcu_read_lock(); spin_lock(&ulp->lock); un = lookup_undo(ulp, semid); spin_unlock(&ulp->lock); if (likely(un!=NULL)) goto out; /* no undo structure around - allocate one. */ /* step 1: figure out the size of the semaphore array */ sma = sem_obtain_object_check(ns, semid); if (IS_ERR(sma)) { rcu_read_unlock(); return ERR_CAST(sma); } nsems = sma->sem_nsems; ipc_rcu_getref(sma); rcu_read_unlock(); /* step 2: allocate new undo structure */ new = kzalloc(sizeof(struct sem_undo) + sizeof(short)*nsems, GFP_KERNEL); if (!new) { sem_putref(sma); return ERR_PTR(-ENOMEM); } /* step 3: Acquire the lock on semaphore array */ sem_lock_and_putref(sma); if (sma->sem_perm.deleted) { sem_unlock(sma); kfree(new); un = ERR_PTR(-EIDRM); goto out; } spin_lock(&ulp->lock); /* * step 4: check for races: did someone else allocate the undo struct? */ un = lookup_undo(ulp, semid); if (un) { kfree(new); goto success; } /* step 5: initialize & link new undo structure */ new->semadj = (short *) &new[1]; new->ulp = ulp; new->semid = semid; assert_spin_locked(&ulp->lock); list_add_rcu(&new->list_proc, &ulp->list_proc); assert_spin_locked(&sma->sem_perm.lock); list_add(&new->list_id, &sma->list_id); un = new; success: spin_unlock(&ulp->lock); rcu_read_lock(); sem_unlock(sma); out: return un; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'ipc,sem: fine grained locking for semtimedop Introduce finer grained locking for semtimedop, to handle the common case of a program wanting to manipulate one semaphore from an array with multiple semaphores. If the call is a semop manipulating just one semaphore in an array with multiple semaphores, only take the lock for that semaphore itself. If the call needs to manipulate multiple semaphores, or another caller is in a transaction that manipulates multiple semaphores, the sem_array lock is taken, as well as all the locks for the individual semaphores. On a 24 CPU system, performance numbers with the semop-multi test with N threads and N semaphores, look like this: vanilla Davidlohr's Davidlohr's + Davidlohr's + threads patches rwlock patches v3 patches 10 610652 726325 1783589 2142206 20 341570 365699 1520453 1977878 30 288102 307037 1498167 2037995 40 290714 305955 1612665 2256484 50 288620 312890 1733453 2650292 60 289987 306043 1649360 2388008 70 291298 306347 1723167 2717486 80 290948 305662 1729545 2763582 90 290996 306680 1736021 2757524 100 292243 306700 1773700 3059159 [[email protected]: do not call sem_lock when bogus sma] [[email protected]: make refcounter atomic] Signed-off-by: Rik van Riel <[email protected]> Suggested-by: Linus Torvalds <[email protected]> Acked-by: Davidlohr Bueso <[email protected]> Cc: Chegu Vinod <[email protected]> Cc: Jason Low <[email protected]> Reviewed-by: Michel Lespinasse <[email protected]> Cc: Peter Hurley <[email protected]> Cc: Stanislav Kinsbursky <[email protected]> Tested-by: Emmanuel Benisty <[email protected]> Tested-by: Sedat Dilek <[email protected]> Signed-off-by: Andrew Morton <[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 freeary(struct ipc_namespace *ns, struct kern_ipc_perm *ipcp) { struct sem_undo *un, *tu; struct sem_queue *q, *tq; struct sem_array *sma = container_of(ipcp, struct sem_array, sem_perm); struct list_head tasks; int i; /* Free the existing undo structures for this semaphore set. */ assert_spin_locked(&sma->sem_perm.lock); list_for_each_entry_safe(un, tu, &sma->list_id, list_id) { list_del(&un->list_id); spin_lock(&un->ulp->lock); un->semid = -1; list_del_rcu(&un->list_proc); spin_unlock(&un->ulp->lock); kfree_rcu(un, rcu); } /* Wake up all pending processes and let them fail with EIDRM. */ INIT_LIST_HEAD(&tasks); list_for_each_entry_safe(q, tq, &sma->sem_pending, list) { unlink_queue(sma, q); wake_up_sem_queue_prepare(&tasks, q, -EIDRM); } for (i = 0; i < sma->sem_nsems; i++) { struct sem *sem = sma->sem_base + i; list_for_each_entry_safe(q, tq, &sem->sem_pending, list) { unlink_queue(sma, q); wake_up_sem_queue_prepare(&tasks, q, -EIDRM); } } /* Remove the semaphore set from the IDR */ sem_rmid(ns, sma); sem_unlock(sma); wake_up_sem_queue_do(&tasks); ns->used_sems -= sma->sem_nsems; security_sem_free(sma); ipc_rcu_putref(sma); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'ipc,sem: fine grained locking for semtimedop Introduce finer grained locking for semtimedop, to handle the common case of a program wanting to manipulate one semaphore from an array with multiple semaphores. If the call is a semop manipulating just one semaphore in an array with multiple semaphores, only take the lock for that semaphore itself. If the call needs to manipulate multiple semaphores, or another caller is in a transaction that manipulates multiple semaphores, the sem_array lock is taken, as well as all the locks for the individual semaphores. On a 24 CPU system, performance numbers with the semop-multi test with N threads and N semaphores, look like this: vanilla Davidlohr's Davidlohr's + Davidlohr's + threads patches rwlock patches v3 patches 10 610652 726325 1783589 2142206 20 341570 365699 1520453 1977878 30 288102 307037 1498167 2037995 40 290714 305955 1612665 2256484 50 288620 312890 1733453 2650292 60 289987 306043 1649360 2388008 70 291298 306347 1723167 2717486 80 290948 305662 1729545 2763582 90 290996 306680 1736021 2757524 100 292243 306700 1773700 3059159 [[email protected]: do not call sem_lock when bogus sma] [[email protected]: make refcounter atomic] Signed-off-by: Rik van Riel <[email protected]> Suggested-by: Linus Torvalds <[email protected]> Acked-by: Davidlohr Bueso <[email protected]> Cc: Chegu Vinod <[email protected]> Cc: Jason Low <[email protected]> Reviewed-by: Michel Lespinasse <[email protected]> Cc: Peter Hurley <[email protected]> Cc: Stanislav Kinsbursky <[email protected]> Tested-by: Emmanuel Benisty <[email protected]> Tested-by: Sedat Dilek <[email protected]> Signed-off-by: Andrew Morton <[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 int newary(struct ipc_namespace *ns, struct ipc_params *params) { int id; int retval; struct sem_array *sma; int size; key_t key = params->key; int nsems = params->u.nsems; int semflg = params->flg; int i; if (!nsems) return -EINVAL; if (ns->used_sems + nsems > ns->sc_semmns) return -ENOSPC; size = sizeof (*sma) + nsems * sizeof (struct sem); sma = ipc_rcu_alloc(size); if (!sma) { return -ENOMEM; } memset (sma, 0, size); sma->sem_perm.mode = (semflg & S_IRWXUGO); sma->sem_perm.key = key; sma->sem_perm.security = NULL; retval = security_sem_alloc(sma); if (retval) { ipc_rcu_putref(sma); return retval; } id = ipc_addid(&sem_ids(ns), &sma->sem_perm, ns->sc_semmni); if (id < 0) { security_sem_free(sma); ipc_rcu_putref(sma); return id; } ns->used_sems += nsems; sma->sem_base = (struct sem *) &sma[1]; for (i = 0; i < nsems; i++) INIT_LIST_HEAD(&sma->sem_base[i].sem_pending); sma->complex_count = 0; INIT_LIST_HEAD(&sma->sem_pending); INIT_LIST_HEAD(&sma->list_id); sma->sem_nsems = nsems; sma->sem_ctime = get_seconds(); sem_unlock(sma); return sma->sem_perm.id; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'ipc,sem: fine grained locking for semtimedop Introduce finer grained locking for semtimedop, to handle the common case of a program wanting to manipulate one semaphore from an array with multiple semaphores. If the call is a semop manipulating just one semaphore in an array with multiple semaphores, only take the lock for that semaphore itself. If the call needs to manipulate multiple semaphores, or another caller is in a transaction that manipulates multiple semaphores, the sem_array lock is taken, as well as all the locks for the individual semaphores. On a 24 CPU system, performance numbers with the semop-multi test with N threads and N semaphores, look like this: vanilla Davidlohr's Davidlohr's + Davidlohr's + threads patches rwlock patches v3 patches 10 610652 726325 1783589 2142206 20 341570 365699 1520453 1977878 30 288102 307037 1498167 2037995 40 290714 305955 1612665 2256484 50 288620 312890 1733453 2650292 60 289987 306043 1649360 2388008 70 291298 306347 1723167 2717486 80 290948 305662 1729545 2763582 90 290996 306680 1736021 2757524 100 292243 306700 1773700 3059159 [[email protected]: do not call sem_lock when bogus sma] [[email protected]: make refcounter atomic] Signed-off-by: Rik van Riel <[email protected]> Suggested-by: Linus Torvalds <[email protected]> Acked-by: Davidlohr Bueso <[email protected]> Cc: Chegu Vinod <[email protected]> Cc: Jason Low <[email protected]> Reviewed-by: Michel Lespinasse <[email protected]> Cc: Peter Hurley <[email protected]> Cc: Stanislav Kinsbursky <[email protected]> Tested-by: Emmanuel Benisty <[email protected]> Tested-by: Sedat Dilek <[email protected]> Signed-off-by: Andrew Morton <[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: long do_msgsnd(int msqid, long mtype, void __user *mtext, size_t msgsz, int msgflg) { struct msg_queue *msq; struct msg_msg *msg; int err; struct ipc_namespace *ns; ns = current->nsproxy->ipc_ns; if (msgsz > ns->msg_ctlmax || (long) msgsz < 0 || msqid < 0) return -EINVAL; if (mtype < 1) return -EINVAL; msg = load_msg(mtext, msgsz); if (IS_ERR(msg)) return PTR_ERR(msg); msg->m_type = mtype; msg->m_ts = msgsz; msq = msg_lock_check(ns, msqid); if (IS_ERR(msq)) { err = PTR_ERR(msq); goto out_free; } for (;;) { struct msg_sender s; err = -EACCES; if (ipcperms(ns, &msq->q_perm, S_IWUGO)) goto out_unlock_free; err = security_msg_queue_msgsnd(msq, msg, msgflg); if (err) goto out_unlock_free; if (msgsz + msq->q_cbytes <= msq->q_qbytes && 1 + msq->q_qnum <= msq->q_qbytes) { break; } /* queue full, wait: */ if (msgflg & IPC_NOWAIT) { err = -EAGAIN; goto out_unlock_free; } ss_add(msq, &s); ipc_rcu_getref(msq); msg_unlock(msq); schedule(); ipc_lock_by_ptr(&msq->q_perm); ipc_rcu_putref(msq); if (msq->q_perm.deleted) { err = -EIDRM; goto out_unlock_free; } ss_del(&s); if (signal_pending(current)) { err = -ERESTARTNOHAND; goto out_unlock_free; } } msq->q_lspid = task_tgid_vnr(current); msq->q_stime = get_seconds(); if (!pipelined_send(msq, msg)) { /* no one is waiting for this message, enqueue it */ list_add_tail(&msg->m_list, &msq->q_messages); msq->q_cbytes += msgsz; msq->q_qnum++; atomic_add(msgsz, &ns->msg_bytes); atomic_inc(&ns->msg_hdrs); } err = 0; msg = NULL; out_unlock_free: msg_unlock(msq); out_free: if (msg != NULL) free_msg(msg); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'ipc,sem: fine grained locking for semtimedop Introduce finer grained locking for semtimedop, to handle the common case of a program wanting to manipulate one semaphore from an array with multiple semaphores. If the call is a semop manipulating just one semaphore in an array with multiple semaphores, only take the lock for that semaphore itself. If the call needs to manipulate multiple semaphores, or another caller is in a transaction that manipulates multiple semaphores, the sem_array lock is taken, as well as all the locks for the individual semaphores. On a 24 CPU system, performance numbers with the semop-multi test with N threads and N semaphores, look like this: vanilla Davidlohr's Davidlohr's + Davidlohr's + threads patches rwlock patches v3 patches 10 610652 726325 1783589 2142206 20 341570 365699 1520453 1977878 30 288102 307037 1498167 2037995 40 290714 305955 1612665 2256484 50 288620 312890 1733453 2650292 60 289987 306043 1649360 2388008 70 291298 306347 1723167 2717486 80 290948 305662 1729545 2763582 90 290996 306680 1736021 2757524 100 292243 306700 1773700 3059159 [[email protected]: do not call sem_lock when bogus sma] [[email protected]: make refcounter atomic] Signed-off-by: Rik van Riel <[email protected]> Suggested-by: Linus Torvalds <[email protected]> Acked-by: Davidlohr Bueso <[email protected]> Cc: Chegu Vinod <[email protected]> Cc: Jason Low <[email protected]> Reviewed-by: Michel Lespinasse <[email protected]> Cc: Peter Hurley <[email protected]> Cc: Stanislav Kinsbursky <[email protected]> Tested-by: Emmanuel Benisty <[email protected]> Tested-by: Sedat Dilek <[email protected]> Signed-off-by: Andrew Morton <[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 inline void sem_getref(struct sem_array *sma) { spin_lock(&(sma)->sem_perm.lock); ipc_rcu_getref(sma); ipc_unlock(&(sma)->sem_perm); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'ipc,sem: fine grained locking for semtimedop Introduce finer grained locking for semtimedop, to handle the common case of a program wanting to manipulate one semaphore from an array with multiple semaphores. If the call is a semop manipulating just one semaphore in an array with multiple semaphores, only take the lock for that semaphore itself. If the call needs to manipulate multiple semaphores, or another caller is in a transaction that manipulates multiple semaphores, the sem_array lock is taken, as well as all the locks for the individual semaphores. On a 24 CPU system, performance numbers with the semop-multi test with N threads and N semaphores, look like this: vanilla Davidlohr's Davidlohr's + Davidlohr's + threads patches rwlock patches v3 patches 10 610652 726325 1783589 2142206 20 341570 365699 1520453 1977878 30 288102 307037 1498167 2037995 40 290714 305955 1612665 2256484 50 288620 312890 1733453 2650292 60 289987 306043 1649360 2388008 70 291298 306347 1723167 2717486 80 290948 305662 1729545 2763582 90 290996 306680 1736021 2757524 100 292243 306700 1773700 3059159 [[email protected]: do not call sem_lock when bogus sma] [[email protected]: make refcounter atomic] Signed-off-by: Rik van Riel <[email protected]> Suggested-by: Linus Torvalds <[email protected]> Acked-by: Davidlohr Bueso <[email protected]> Cc: Chegu Vinod <[email protected]> Cc: Jason Low <[email protected]> Reviewed-by: Michel Lespinasse <[email protected]> Cc: Peter Hurley <[email protected]> Cc: Stanislav Kinsbursky <[email protected]> Tested-by: Emmanuel Benisty <[email protected]> Tested-by: Sedat Dilek <[email protected]> Signed-off-by: Andrew Morton <[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 inline struct sem_array *sem_lock_check(struct ipc_namespace *ns, int id) { struct kern_ipc_perm *ipcp = ipc_lock_check(&sem_ids(ns), id); if (IS_ERR(ipcp)) return ERR_CAST(ipcp); return container_of(ipcp, struct sem_array, sem_perm); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'ipc,sem: fine grained locking for semtimedop Introduce finer grained locking for semtimedop, to handle the common case of a program wanting to manipulate one semaphore from an array with multiple semaphores. If the call is a semop manipulating just one semaphore in an array with multiple semaphores, only take the lock for that semaphore itself. If the call needs to manipulate multiple semaphores, or another caller is in a transaction that manipulates multiple semaphores, the sem_array lock is taken, as well as all the locks for the individual semaphores. On a 24 CPU system, performance numbers with the semop-multi test with N threads and N semaphores, look like this: vanilla Davidlohr's Davidlohr's + Davidlohr's + threads patches rwlock patches v3 patches 10 610652 726325 1783589 2142206 20 341570 365699 1520453 1977878 30 288102 307037 1498167 2037995 40 290714 305955 1612665 2256484 50 288620 312890 1733453 2650292 60 289987 306043 1649360 2388008 70 291298 306347 1723167 2717486 80 290948 305662 1729545 2763582 90 290996 306680 1736021 2757524 100 292243 306700 1773700 3059159 [[email protected]: do not call sem_lock when bogus sma] [[email protected]: make refcounter atomic] Signed-off-by: Rik van Riel <[email protected]> Suggested-by: Linus Torvalds <[email protected]> Acked-by: Davidlohr Bueso <[email protected]> Cc: Chegu Vinod <[email protected]> Cc: Jason Low <[email protected]> Reviewed-by: Michel Lespinasse <[email protected]> Cc: Peter Hurley <[email protected]> Cc: Stanislav Kinsbursky <[email protected]> Tested-by: Emmanuel Benisty <[email protected]> Tested-by: Sedat Dilek <[email protected]> Signed-off-by: Andrew Morton <[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: void ipc_rcu_putref(void *ptr) { if (--container_of(ptr, struct ipc_rcu_hdr, data)->refcount > 0) return; if (container_of(ptr, struct ipc_rcu_hdr, data)->is_vmalloc) { call_rcu(&container_of(ptr, struct ipc_rcu_grace, data)->rcu, ipc_schedule_free); } else { kfree_rcu(container_of(ptr, struct ipc_rcu_grace, data), rcu); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'ipc,sem: fine grained locking for semtimedop Introduce finer grained locking for semtimedop, to handle the common case of a program wanting to manipulate one semaphore from an array with multiple semaphores. If the call is a semop manipulating just one semaphore in an array with multiple semaphores, only take the lock for that semaphore itself. If the call needs to manipulate multiple semaphores, or another caller is in a transaction that manipulates multiple semaphores, the sem_array lock is taken, as well as all the locks for the individual semaphores. On a 24 CPU system, performance numbers with the semop-multi test with N threads and N semaphores, look like this: vanilla Davidlohr's Davidlohr's + Davidlohr's + threads patches rwlock patches v3 patches 10 610652 726325 1783589 2142206 20 341570 365699 1520453 1977878 30 288102 307037 1498167 2037995 40 290714 305955 1612665 2256484 50 288620 312890 1733453 2650292 60 289987 306043 1649360 2388008 70 291298 306347 1723167 2717486 80 290948 305662 1729545 2763582 90 290996 306680 1736021 2757524 100 292243 306700 1773700 3059159 [[email protected]: do not call sem_lock when bogus sma] [[email protected]: make refcounter atomic] Signed-off-by: Rik van Riel <[email protected]> Suggested-by: Linus Torvalds <[email protected]> Acked-by: Davidlohr Bueso <[email protected]> Cc: Chegu Vinod <[email protected]> Cc: Jason Low <[email protected]> Reviewed-by: Michel Lespinasse <[email protected]> Cc: Peter Hurley <[email protected]> Cc: Stanislav Kinsbursky <[email protected]> Tested-by: Emmanuel Benisty <[email protected]> Tested-by: Sedat Dilek <[email protected]> Signed-off-by: Andrew Morton <[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 int semctl_down(struct ipc_namespace *ns, int semid, int cmd, int version, void __user *p) { struct sem_array *sma; int err; struct semid64_ds semid64; struct kern_ipc_perm *ipcp; if(cmd == IPC_SET) { if (copy_semid_from_user(&semid64, p, version)) return -EFAULT; } ipcp = ipcctl_pre_down_nolock(ns, &sem_ids(ns), semid, cmd, &semid64.sem_perm, 0); if (IS_ERR(ipcp)) return PTR_ERR(ipcp); sma = container_of(ipcp, struct sem_array, sem_perm); err = security_sem_semctl(sma, cmd); if (err) { rcu_read_unlock(); goto out_unlock; } switch(cmd){ case IPC_RMID: ipc_lock_object(&sma->sem_perm); freeary(ns, ipcp); goto out_up; case IPC_SET: ipc_lock_object(&sma->sem_perm); err = ipc_update_perm(&semid64.sem_perm, ipcp); if (err) goto out_unlock; sma->sem_ctime = get_seconds(); break; default: rcu_read_unlock(); err = -EINVAL; goto out_up; } out_unlock: sem_unlock(sma); out_up: up_write(&sem_ids(ns).rw_mutex); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'ipc,sem: fine grained locking for semtimedop Introduce finer grained locking for semtimedop, to handle the common case of a program wanting to manipulate one semaphore from an array with multiple semaphores. If the call is a semop manipulating just one semaphore in an array with multiple semaphores, only take the lock for that semaphore itself. If the call needs to manipulate multiple semaphores, or another caller is in a transaction that manipulates multiple semaphores, the sem_array lock is taken, as well as all the locks for the individual semaphores. On a 24 CPU system, performance numbers with the semop-multi test with N threads and N semaphores, look like this: vanilla Davidlohr's Davidlohr's + Davidlohr's + threads patches rwlock patches v3 patches 10 610652 726325 1783589 2142206 20 341570 365699 1520453 1977878 30 288102 307037 1498167 2037995 40 290714 305955 1612665 2256484 50 288620 312890 1733453 2650292 60 289987 306043 1649360 2388008 70 291298 306347 1723167 2717486 80 290948 305662 1729545 2763582 90 290996 306680 1736021 2757524 100 292243 306700 1773700 3059159 [[email protected]: do not call sem_lock when bogus sma] [[email protected]: make refcounter atomic] Signed-off-by: Rik van Riel <[email protected]> Suggested-by: Linus Torvalds <[email protected]> Acked-by: Davidlohr Bueso <[email protected]> Cc: Chegu Vinod <[email protected]> Cc: Jason Low <[email protected]> Reviewed-by: Michel Lespinasse <[email protected]> Cc: Peter Hurley <[email protected]> Cc: Stanislav Kinsbursky <[email protected]> Tested-by: Emmanuel Benisty <[email protected]> Tested-by: Sedat Dilek <[email protected]> Signed-off-by: Andrew Morton <[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 inline void sem_lock_and_putref(struct sem_array *sma) { ipc_lock_by_ptr(&sma->sem_perm); ipc_rcu_putref(sma); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'ipc,sem: fine grained locking for semtimedop Introduce finer grained locking for semtimedop, to handle the common case of a program wanting to manipulate one semaphore from an array with multiple semaphores. If the call is a semop manipulating just one semaphore in an array with multiple semaphores, only take the lock for that semaphore itself. If the call needs to manipulate multiple semaphores, or another caller is in a transaction that manipulates multiple semaphores, the sem_array lock is taken, as well as all the locks for the individual semaphores. On a 24 CPU system, performance numbers with the semop-multi test with N threads and N semaphores, look like this: vanilla Davidlohr's Davidlohr's + Davidlohr's + threads patches rwlock patches v3 patches 10 610652 726325 1783589 2142206 20 341570 365699 1520453 1977878 30 288102 307037 1498167 2037995 40 290714 305955 1612665 2256484 50 288620 312890 1733453 2650292 60 289987 306043 1649360 2388008 70 291298 306347 1723167 2717486 80 290948 305662 1729545 2763582 90 290996 306680 1736021 2757524 100 292243 306700 1773700 3059159 [[email protected]: do not call sem_lock when bogus sma] [[email protected]: make refcounter atomic] Signed-off-by: Rik van Riel <[email protected]> Suggested-by: Linus Torvalds <[email protected]> Acked-by: Davidlohr Bueso <[email protected]> Cc: Chegu Vinod <[email protected]> Cc: Jason Low <[email protected]> Reviewed-by: Michel Lespinasse <[email protected]> Cc: Peter Hurley <[email protected]> Cc: Stanislav Kinsbursky <[email protected]> Tested-by: Emmanuel Benisty <[email protected]> Tested-by: Sedat Dilek <[email protected]> Signed-off-by: Andrew Morton <[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 inline void sem_putref(struct sem_array *sma) { ipc_lock_by_ptr(&sma->sem_perm); ipc_rcu_putref(sma); ipc_unlock(&(sma)->sem_perm); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'ipc,sem: fine grained locking for semtimedop Introduce finer grained locking for semtimedop, to handle the common case of a program wanting to manipulate one semaphore from an array with multiple semaphores. If the call is a semop manipulating just one semaphore in an array with multiple semaphores, only take the lock for that semaphore itself. If the call needs to manipulate multiple semaphores, or another caller is in a transaction that manipulates multiple semaphores, the sem_array lock is taken, as well as all the locks for the individual semaphores. On a 24 CPU system, performance numbers with the semop-multi test with N threads and N semaphores, look like this: vanilla Davidlohr's Davidlohr's + Davidlohr's + threads patches rwlock patches v3 patches 10 610652 726325 1783589 2142206 20 341570 365699 1520453 1977878 30 288102 307037 1498167 2037995 40 290714 305955 1612665 2256484 50 288620 312890 1733453 2650292 60 289987 306043 1649360 2388008 70 291298 306347 1723167 2717486 80 290948 305662 1729545 2763582 90 290996 306680 1736021 2757524 100 292243 306700 1773700 3059159 [[email protected]: do not call sem_lock when bogus sma] [[email protected]: make refcounter atomic] Signed-off-by: Rik van Riel <[email protected]> Suggested-by: Linus Torvalds <[email protected]> Acked-by: Davidlohr Bueso <[email protected]> Cc: Chegu Vinod <[email protected]> Cc: Jason Low <[email protected]> Reviewed-by: Michel Lespinasse <[email protected]> Cc: Peter Hurley <[email protected]> Cc: Stanislav Kinsbursky <[email protected]> Tested-by: Emmanuel Benisty <[email protected]> Tested-by: Sedat Dilek <[email protected]> Signed-off-by: Andrew Morton <[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 gg_action_t gg_handle_tls_negotiation(struct gg_session *sess, struct gg_event *e, enum gg_state_t next_state, enum gg_state_t alt_state, enum gg_state_t alt2_state) { #ifdef GG_CONFIG_HAVE_GNUTLS int res; gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() GG_STATE_TLS_NEGOTIATION\n"); for (;;) { res = gnutls_handshake(GG_SESSION_GNUTLS(sess)); if (res == GNUTLS_E_AGAIN) { gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() TLS handshake GNUTLS_E_AGAIN\n"); if (gnutls_record_get_direction(GG_SESSION_GNUTLS(sess)) == 0) sess->check = GG_CHECK_READ; else sess->check = GG_CHECK_WRITE; sess->timeout = GG_DEFAULT_TIMEOUT; return GG_ACTION_WAIT; } if (res == GNUTLS_E_INTERRUPTED) { gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() TLS handshake GNUTLS_E_INTERRUPTED\n"); continue; } if (res != GNUTLS_E_SUCCESS) { gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() TLS handshake error: %d, %s\n", res, gnutls_strerror(res)); e->event.failure = GG_FAILURE_TLS; return GG_ACTION_FAIL; } break; } gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() TLS negotiation succeded:\n"); gg_debug_session(sess, GG_DEBUG_MISC, "// cipher: VERS-%s:%s:%s:%s:COMP-%s\n", gnutls_protocol_get_name(gnutls_protocol_get_version(GG_SESSION_GNUTLS(sess))), gnutls_cipher_get_name(gnutls_cipher_get(GG_SESSION_GNUTLS(sess))), gnutls_kx_get_name(gnutls_kx_get(GG_SESSION_GNUTLS(sess))), gnutls_mac_get_name(gnutls_mac_get(GG_SESSION_GNUTLS(sess))), gnutls_compression_get_name(gnutls_compression_get(GG_SESSION_GNUTLS(sess)))); if (gnutls_certificate_type_get(GG_SESSION_GNUTLS(sess)) == GNUTLS_CRT_X509) { unsigned int peer_count; const gnutls_datum_t *peers; gnutls_x509_crt_t cert; if (gnutls_x509_crt_init(&cert) == 0) { peers = gnutls_certificate_get_peers(GG_SESSION_GNUTLS(sess), &peer_count); if (peers != NULL) { char buf[256]; size_t size; if (gnutls_x509_crt_import(cert, &peers[0], GNUTLS_X509_FMT_DER) == 0) { size = sizeof(buf); gnutls_x509_crt_get_dn(cert, buf, &size); gg_debug_session(sess, GG_DEBUG_MISC, "// cert subject: %s\n", buf); size = sizeof(buf); gnutls_x509_crt_get_issuer_dn(cert, buf, &size); gg_debug_session(sess, GG_DEBUG_MISC, "// cert issuer: %s\n", buf); } } gnutls_x509_crt_deinit(cert); } } sess->state = next_state; sess->check = GG_CHECK_READ; sess->timeout = GG_DEFAULT_TIMEOUT; return GG_ACTION_WAIT; #elif defined GG_CONFIG_HAVE_OPENSSL X509 *peer; int res; gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() %s\n", gg_debug_state(sess->state)); res = SSL_connect(GG_SESSION_OPENSSL(sess)); if (res <= 0) { int err; err = SSL_get_error(GG_SESSION_OPENSSL(sess), res); if (res == 0) { gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() disconnected during TLS negotiation\n"); e->event.failure = GG_FAILURE_TLS; return GG_ACTION_FAIL; } if (err == SSL_ERROR_WANT_READ) { gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() SSL_connect() wants to read\n"); sess->check = GG_CHECK_READ; sess->timeout = GG_DEFAULT_TIMEOUT; return GG_ACTION_WAIT; } else if (err == SSL_ERROR_WANT_WRITE) { gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() SSL_connect() wants to write\n"); sess->check = GG_CHECK_WRITE; sess->timeout = GG_DEFAULT_TIMEOUT; return GG_ACTION_WAIT; } else { char buf[256]; ERR_error_string_n(ERR_get_error(), buf, sizeof(buf)); gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() SSL_connect() bailed out: %s\n", buf); e->event.failure = GG_FAILURE_TLS; return GG_ACTION_FAIL; } } gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() TLS negotiation succeded:\n// cipher: %s\n", SSL_get_cipher_name(GG_SESSION_OPENSSL(sess))); peer = SSL_get_peer_certificate(GG_SESSION_OPENSSL(sess)); if (peer == NULL) { gg_debug_session(sess, GG_DEBUG_MISC, "// WARNING! unable to get peer certificate!\n"); } else { char buf[256]; X509_NAME_oneline(X509_get_subject_name(peer), buf, sizeof(buf)); gg_debug_session(sess, GG_DEBUG_MISC, "// cert subject: %s\n", buf); X509_NAME_oneline(X509_get_issuer_name(peer), buf, sizeof(buf)); gg_debug_session(sess, GG_DEBUG_MISC, "// cert issuer: %s\n", buf); } sess->state = next_state; sess->check = GG_CHECK_READ; sess->timeout = GG_DEFAULT_TIMEOUT; return GG_ACTION_WAIT; #else gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() no SSL support\n"); e->event.failure = GG_FAILURE_TLS; return GG_ACTION_FAIL; #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Dla GG_SSL_REQUIRED sprawdzamy certyfikat serwera z certyfikatami zainstalowanymi w systemie (Radhesh Krishnan K., Bartosz Brachaczek)'</s>
<s>[INST] Given the following code containing errors, provide 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 gg_action_t gg_handle_tls_negotiation(struct gg_session *sess, struct gg_event *e, enum gg_state_t next_state, enum gg_state_t alt_state, enum gg_state_t alt2_state) { #ifdef GG_CONFIG_HAVE_GNUTLS int res; gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() GG_STATE_TLS_NEGOTIATION\n"); for (;;) { res = gnutls_handshake(GG_SESSION_GNUTLS(sess)); if (res == GNUTLS_E_AGAIN) { gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() TLS handshake GNUTLS_E_AGAIN\n"); if (gnutls_record_get_direction(GG_SESSION_GNUTLS(sess)) == 0) sess->check = GG_CHECK_READ; else sess->check = GG_CHECK_WRITE; sess->timeout = GG_DEFAULT_TIMEOUT; return GG_ACTION_WAIT; } if (res == GNUTLS_E_INTERRUPTED) { gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() TLS handshake GNUTLS_E_INTERRUPTED\n"); continue; } if (res != GNUTLS_E_SUCCESS) { gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() TLS handshake error: %d, %s\n", res, gnutls_strerror(res)); e->event.failure = GG_FAILURE_TLS; return GG_ACTION_FAIL; } break; } gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() TLS negotiation succeded:\n"); gg_debug_session(sess, GG_DEBUG_MISC, "// cipher: VERS-%s:%s:%s:%s:COMP-%s\n", gnutls_protocol_get_name(gnutls_protocol_get_version(GG_SESSION_GNUTLS(sess))), gnutls_cipher_get_name(gnutls_cipher_get(GG_SESSION_GNUTLS(sess))), gnutls_kx_get_name(gnutls_kx_get(GG_SESSION_GNUTLS(sess))), gnutls_mac_get_name(gnutls_mac_get(GG_SESSION_GNUTLS(sess))), gnutls_compression_get_name(gnutls_compression_get(GG_SESSION_GNUTLS(sess)))); if (gnutls_certificate_type_get(GG_SESSION_GNUTLS(sess)) == GNUTLS_CRT_X509) { unsigned int peer_count; const gnutls_datum_t *peers; gnutls_x509_crt_t cert; if (gnutls_x509_crt_init(&cert) == 0) { peers = gnutls_certificate_get_peers(GG_SESSION_GNUTLS(sess), &peer_count); if (peers != NULL) { char buf[256]; size_t size; if (gnutls_x509_crt_import(cert, &peers[0], GNUTLS_X509_FMT_DER) == 0) { size = sizeof(buf); gnutls_x509_crt_get_dn(cert, buf, &size); gg_debug_session(sess, GG_DEBUG_MISC, "// cert subject: %s\n", buf); size = sizeof(buf); gnutls_x509_crt_get_issuer_dn(cert, buf, &size); gg_debug_session(sess, GG_DEBUG_MISC, "// cert issuer: %s\n", buf); } } gnutls_x509_crt_deinit(cert); } } sess->state = next_state; sess->check = GG_CHECK_READ; sess->timeout = GG_DEFAULT_TIMEOUT; return GG_ACTION_WAIT; #elif defined GG_CONFIG_HAVE_OPENSSL X509 *peer; int res; gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() %s\n", gg_debug_state(sess->state)); res = SSL_connect(GG_SESSION_OPENSSL(sess)); if (res <= 0) { int err; err = SSL_get_error(GG_SESSION_OPENSSL(sess), res); if (res == 0) { gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() disconnected during TLS negotiation\n"); e->event.failure = GG_FAILURE_TLS; return GG_ACTION_FAIL; } if (err == SSL_ERROR_WANT_READ) { gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() SSL_connect() wants to read\n"); sess->check = GG_CHECK_READ; sess->timeout = GG_DEFAULT_TIMEOUT; return GG_ACTION_WAIT; } else if (err == SSL_ERROR_WANT_WRITE) { gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() SSL_connect() wants to write\n"); sess->check = GG_CHECK_WRITE; sess->timeout = GG_DEFAULT_TIMEOUT; return GG_ACTION_WAIT; } else { char buf[256]; ERR_error_string_n(ERR_get_error(), buf, sizeof(buf)); gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() SSL_connect() bailed out: %s\n", buf); e->event.failure = GG_FAILURE_TLS; return GG_ACTION_FAIL; } } gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() TLS negotiation succeded:\n// cipher: %s\n", SSL_get_cipher_name(GG_SESSION_OPENSSL(sess))); peer = SSL_get_peer_certificate(GG_SESSION_OPENSSL(sess)); if (peer == NULL) { gg_debug_session(sess, GG_DEBUG_MISC, "// WARNING! unable to get peer certificate!\n"); if (sess->ssl_flag == GG_SSL_REQUIRED) { e->event.failure = GG_FAILURE_TLS; return GG_ACTION_FAIL; } } else { char buf[256]; long res; X509_NAME_oneline(X509_get_subject_name(peer), buf, sizeof(buf)); gg_debug_session(sess, GG_DEBUG_MISC, "// cert subject: %s\n", buf); X509_NAME_oneline(X509_get_issuer_name(peer), buf, sizeof(buf)); gg_debug_session(sess, GG_DEBUG_MISC, "// cert issuer: %s\n", buf); res = SSL_get_verify_result(GG_SESSION_OPENSSL(sess)); if (res != X509_V_OK) { gg_debug_session(sess, GG_DEBUG_MISC, "//   WARNING! unable to verify peer certificate! res=%ld\n", res); if (sess->ssl_flag == GG_SSL_REQUIRED) { e->event.failure = GG_FAILURE_TLS; return GG_ACTION_FAIL; } } else { gg_debug_session(sess, GG_DEBUG_MISC, "// verified peer certificate\n"); } } sess->state = next_state; sess->check = GG_CHECK_READ; sess->timeout = GG_DEFAULT_TIMEOUT; return GG_ACTION_WAIT; #else gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() no SSL support\n"); e->event.failure = GG_FAILURE_TLS; return GG_ACTION_FAIL; #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Weryfikacja certyfikatów SSL.'</s>
<s>[INST] Given the following code containing errors, provide 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 gg_change_status_descr(struct gg_session *sess, int status, const char *descr) { struct gg_new_status80 p; char *gen_descr = NULL; int descr_len = 0; int res; gg_debug_session(sess, GG_DEBUG_FUNCTION, "** gg_change_status_descr(%p, %d, \"%s\");\n", sess, status, descr); if (!sess) { errno = EFAULT; return -1; } if (sess->state != GG_STATE_CONNECTED) { errno = ENOTCONN; return -1; } sess->status = status; if (descr != NULL && sess->encoding != GG_ENCODING_UTF8) { descr = gen_descr = gg_encoding_convert(descr, GG_ENCODING_CP1250, GG_ENCODING_UTF8, -1, -1); if (!gen_descr) return -1; } if (descr) { descr_len = strlen(descr); if (descr_len > GG_STATUS_DESCR_MAXSIZE) descr_len = GG_STATUS_DESCR_MAXSIZE; /* XXX pamiętać o tym, żeby nie ucinać w środku znaku utf-8 */ } else { descr = ""; } p.status = gg_fix32(status); p.flags = gg_fix32(sess->status_flags); p.description_size = gg_fix32(descr_len); if (sess->protocol_version >= GG_PROTOCOL_110) { p.flags = gg_fix32(0x00000014); descr_len++; /* dodaj \0 na końcu */ } res = gg_send_packet(sess, GG_NEW_STATUS80, &p, sizeof(p), descr, descr_len, NULL); free(gen_descr); if (GG_S_NA(status)) { sess->state = GG_STATE_DISCONNECTING; sess->timeout = GG_TIMEOUT_DISCONNECT; } return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Poprawka ograniczania długości opisu.'</s>
<s>[INST] Given the following code containing errors, provide 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 gg_action_t gg_handle_tls_negotiation(struct gg_session *sess, struct gg_event *e, enum gg_state_t next_state, enum gg_state_t alt_state, enum gg_state_t alt2_state) { int valid_hostname = 0; #ifdef GG_CONFIG_HAVE_GNUTLS unsigned int status; int res; gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() GG_STATE_TLS_NEGOTIATION\n"); for (;;) { res = gnutls_handshake(GG_SESSION_GNUTLS(sess)); if (res == GNUTLS_E_AGAIN) { gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() TLS handshake GNUTLS_E_AGAIN\n"); if (gnutls_record_get_direction(GG_SESSION_GNUTLS(sess)) == 0) sess->check = GG_CHECK_READ; else sess->check = GG_CHECK_WRITE; sess->timeout = GG_DEFAULT_TIMEOUT; return GG_ACTION_WAIT; } if (res == GNUTLS_E_INTERRUPTED) { gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() TLS handshake GNUTLS_E_INTERRUPTED\n"); continue; } if (res != GNUTLS_E_SUCCESS) { gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() TLS handshake error: %d, %s\n", res, gnutls_strerror(res)); e->event.failure = GG_FAILURE_TLS; return GG_ACTION_FAIL; } break; } gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() TLS negotiation succeded:\n"); gg_debug_session(sess, GG_DEBUG_MISC, "// cipher: VERS-%s:%s:%s:%s:COMP-%s\n", gnutls_protocol_get_name(gnutls_protocol_get_version(GG_SESSION_GNUTLS(sess))), gnutls_cipher_get_name(gnutls_cipher_get(GG_SESSION_GNUTLS(sess))), gnutls_kx_get_name(gnutls_kx_get(GG_SESSION_GNUTLS(sess))), gnutls_mac_get_name(gnutls_mac_get(GG_SESSION_GNUTLS(sess))), gnutls_compression_get_name(gnutls_compression_get(GG_SESSION_GNUTLS(sess)))); if (gnutls_certificate_type_get(GG_SESSION_GNUTLS(sess)) == GNUTLS_CRT_X509) { unsigned int peer_count; const gnutls_datum_t *peers; gnutls_x509_crt_t cert; if (gnutls_x509_crt_init(&cert) == 0) { peers = gnutls_certificate_get_peers(GG_SESSION_GNUTLS(sess), &peer_count); if (peers != NULL) { char buf[256]; size_t size; if (gnutls_x509_crt_import(cert, &peers[0], GNUTLS_X509_FMT_DER) == 0) { size = sizeof(buf); gnutls_x509_crt_get_dn(cert, buf, &size); gg_debug_session(sess, GG_DEBUG_MISC, "// cert subject: %s\n", buf); size = sizeof(buf); gnutls_x509_crt_get_issuer_dn(cert, buf, &size); gg_debug_session(sess, GG_DEBUG_MISC, "// cert issuer: %s\n", buf); if (gnutls_x509_crt_check_hostname(cert, sess->connect_host) != 0) valid_hostname = 1; } } gnutls_x509_crt_deinit(cert); } } res = gnutls_certificate_verify_peers2(GG_SESSION_GNUTLS(sess), &status); if (res != 0) { gg_debug_session(sess, GG_DEBUG_MISC, "//   WARNING! unable to verify peer certificate: %d, %s\n", res, gnutls_strerror(res)); if (sess->ssl_flag == GG_SSL_REQUIRED) { e->event.failure = GG_FAILURE_TLS; return GG_ACTION_FAIL; } } else { gg_debug_session(sess, GG_DEBUG_MISC, "// verified peer certificate\n"); } #elif defined GG_CONFIG_HAVE_OPENSSL X509 *peer; int res; gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() %s\n", gg_debug_state(sess->state)); res = SSL_connect(GG_SESSION_OPENSSL(sess)); if (res <= 0) { int err; err = SSL_get_error(GG_SESSION_OPENSSL(sess), res); if (res == 0) { gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() disconnected during TLS negotiation\n"); e->event.failure = GG_FAILURE_TLS; return GG_ACTION_FAIL; } if (err == SSL_ERROR_WANT_READ) { gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() SSL_connect() wants to read\n"); sess->check = GG_CHECK_READ; sess->timeout = GG_DEFAULT_TIMEOUT; return GG_ACTION_WAIT; } else if (err == SSL_ERROR_WANT_WRITE) { gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() SSL_connect() wants to write\n"); sess->check = GG_CHECK_WRITE; sess->timeout = GG_DEFAULT_TIMEOUT; return GG_ACTION_WAIT; } else { char buf[256]; ERR_error_string_n(ERR_get_error(), buf, sizeof(buf)); gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() SSL_connect() bailed out: %s\n", buf); e->event.failure = GG_FAILURE_TLS; return GG_ACTION_FAIL; } } gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() TLS negotiation succeded:\n// cipher: %s\n", SSL_get_cipher_name(GG_SESSION_OPENSSL(sess))); peer = SSL_get_peer_certificate(GG_SESSION_OPENSSL(sess)); if (peer == NULL) { gg_debug_session(sess, GG_DEBUG_MISC, "// WARNING! unable to get peer certificate!\n"); if (sess->ssl_flag == GG_SSL_REQUIRED) { e->event.failure = GG_FAILURE_TLS; return GG_ACTION_FAIL; } } else { char buf[256]; long res; X509_NAME_oneline(X509_get_subject_name(peer), buf, sizeof(buf)); gg_debug_session(sess, GG_DEBUG_MISC, "// cert subject: %s\n", buf); X509_NAME_oneline(X509_get_issuer_name(peer), buf, sizeof(buf)); gg_debug_session(sess, GG_DEBUG_MISC, "// cert issuer: %s\n", buf); res = SSL_get_verify_result(GG_SESSION_OPENSSL(sess)); if (res != X509_V_OK) { gg_debug_session(sess, GG_DEBUG_MISC, "//   WARNING! unable to verify peer certificate! res=%ld\n", res); if (sess->ssl_flag == GG_SSL_REQUIRED) { e->event.failure = GG_FAILURE_TLS; return GG_ACTION_FAIL; } } else { gg_debug_session(sess, GG_DEBUG_MISC, "// verified peer certificate\n"); } if (X509_NAME_get_text_by_NID(X509_get_subject_name(peer), NID_commonName, buf, sizeof(buf)) == -1) buf[0] = 0; /* Obsługa certyfikatów z wieloznacznikiem */ if (strchr(buf, '*') == buf && strchr(buf + 1, '*') == NULL) { char *tmp; tmp = strchr(sess->connect_host, '.'); if (tmp != NULL) valid_hostname = (strcasecmp(tmp, buf + 1) == 0); } else { valid_hostname = (strcasecmp(sess->connect_host, buf) == 0); } } #else gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() no SSL support\n"); e->event.failure = GG_FAILURE_TLS; return GG_ACTION_FAIL; #endif if (!valid_hostname) { gg_debug_session(sess, GG_DEBUG_MISC, "//   WARNING! unable to verify hostname\n"); if (sess->ssl_flag == GG_SSL_REQUIRED) { e->event.failure = GG_FAILURE_TLS; return GG_ACTION_FAIL; } } sess->state = next_state; sess->check = GG_CHECK_READ; sess->timeout = GG_DEFAULT_TIMEOUT; return GG_ACTION_WAIT; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Poprawna weryfikacja certyfikatu za pomocą GnuTLS.'</s>
<s>[INST] Given the following code containing errors, provide 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 net_ctl_permissions(struct ctl_table_header *head, struct ctl_table *table) { struct net *net = container_of(head->set, struct net, sysctls); kuid_t root_uid = make_kuid(net->user_ns, 0); kgid_t root_gid = make_kgid(net->user_ns, 0); /* Allow network administrator to have same access as root. */ if (ns_capable(net->user_ns, CAP_NET_ADMIN) || uid_eq(root_uid, current_uid())) { int mode = (table->mode >> 6) & 7; return (mode << 6) | (mode << 3) | mode; } /* Allow netns root group to have the same access as the root group */ if (gid_eq(root_gid, current_gid())) { int mode = (table->mode >> 3) & 7; return (mode << 3) | mode; } return table->mode; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'net: Update the sysctl permissions handler to test effective uid/gid Modify the code to use current_euid(), and in_egroup_p, as in done in fs/proc/proc_sysctl.c:test_perm() Cc: [email protected] Reviewed-by: Eric Sandeen <[email protected]> Reported-by: Eric Sandeen <[email protected]> Signed-off-by: "Eric W. Biederman" <[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 int __ptrace_may_access(struct task_struct *task, unsigned int mode) { const struct cred *cred = current_cred(), *tcred; /* May we inspect the given task? * This check is used both for attaching with ptrace * and for allowing access to sensitive information in /proc. * * ptrace_attach denies several cases that /proc allows * because setting up the necessary parent/child relationship * or halting the specified task is impossible. */ int dumpable = 0; /* Don't let security modules deny introspection */ if (same_thread_group(task, current)) return 0; rcu_read_lock(); tcred = __task_cred(task); if (uid_eq(cred->uid, tcred->euid) && uid_eq(cred->uid, tcred->suid) && uid_eq(cred->uid, tcred->uid) && gid_eq(cred->gid, tcred->egid) && gid_eq(cred->gid, tcred->sgid) && gid_eq(cred->gid, tcred->gid)) goto ok; if (ptrace_has_cap(tcred->user_ns, mode)) goto ok; rcu_read_unlock(); return -EPERM; ok: rcu_read_unlock(); smp_rmb(); if (task->mm) dumpable = get_dumpable(task->mm); rcu_read_lock(); if (!dumpable && !ptrace_has_cap(__task_cred(task)->user_ns, mode)) { rcu_read_unlock(); return -EPERM; } rcu_read_unlock(); return security_ptrace_access_check(task, mode); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'exec/ptrace: fix get_dumpable() incorrect tests The get_dumpable() return value is not boolean. Most users of the function actually want to be testing for non-SUID_DUMP_USER(1) rather than SUID_DUMP_DISABLE(0). The SUID_DUMP_ROOT(2) is also considered a protected state. Almost all places did this correctly, excepting the two places fixed in this patch. Wrong logic: if (dumpable == SUID_DUMP_DISABLE) { /* be protective */ } or if (dumpable == 0) { /* be protective */ } or if (!dumpable) { /* be protective */ } Correct logic: if (dumpable != SUID_DUMP_USER) { /* be protective */ } or if (dumpable != 1) { /* be protective */ } Without this patch, if the system had set the sysctl fs/suid_dumpable=2, a user was able to ptrace attach to processes that had dropped privileges to that user. (This may have been partially mitigated if Yama was enabled.) The macros have been moved into the file that declares get/set_dumpable(), which means things like the ia64 code can see them too. CVE-2013-2929 Reported-by: Vasily Kulikov <[email protected]> Signed-off-by: Kees Cook <[email protected]> Cc: "Luck, Tony" <[email protected]> Cc: Oleg Nesterov <[email protected]> Cc: "Eric W. Biederman" <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[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: find_alternate_tgs(kdc_realm_t *kdc_active_realm, krb5_principal princ, krb5_db_entry **server_ptr, const char **status) { krb5_error_code retval; krb5_principal *plist = NULL, *pl2; krb5_data tmp; krb5_db_entry *server = NULL; *server_ptr = NULL; assert(is_cross_tgs_principal(princ)); if ((retval = krb5_walk_realm_tree(kdc_context, krb5_princ_realm(kdc_context, princ), krb5_princ_component(kdc_context, princ, 1), &plist, KRB5_REALM_BRANCH_CHAR))) { goto cleanup; } /* move to the end */ for (pl2 = plist; *pl2; pl2++); /* the first entry in this array is for krbtgt/local@local, so we ignore it */ while (--pl2 > plist) { tmp = *krb5_princ_realm(kdc_context, *pl2); krb5_princ_set_realm(kdc_context, *pl2, krb5_princ_realm(kdc_context, tgs_server)); retval = db_get_svc_princ(kdc_context, *pl2, 0, &server, status); krb5_princ_set_realm(kdc_context, *pl2, &tmp); if (retval == KRB5_KDB_NOENTRY) continue; else if (retval) goto cleanup; log_tgs_alt_tgt(kdc_context, server->princ); *server_ptr = server; server = NULL; goto cleanup; } cleanup: if (retval != 0) *status = "UNKNOWN_SERVER"; krb5_free_realm_tree(kdc_context, plist); krb5_db_free_principal(kdc_context, server); return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'KDC null deref due to referrals [CVE-2013-1417] An authenticated remote client can cause a KDC to crash by making a valid TGS-REQ to a KDC serving a realm with a single-component name. The process_tgs_req() function dereferences a null pointer because an unusual failure condition causes a helper function to return success. While attempting to provide cross-realm referrals for host-based service principals, the find_referral_tgs() function could return a TGS principal for a zero-length realm name (indicating that the hostname in the service principal has no known realm associated with it). Subsequently, the find_alternate_tgs() function would attempt to construct a path to this empty-string realm, and return success along with a null pointer in its output parameter. This happens because krb5_walk_realm_tree() returns a list of length one when it attempts to construct a transit path between a single-component realm and the empty-string realm. This list causes a loop in find_alternate_tgs() to iterate over zero elements, resulting in the unexpected output of a null pointer, which process_tgs_req() proceeds to dereference because there is no error condition. Add an error condition to find_referral_tgs() when krb5_get_host_realm() returns an empty realm name. Also add an error condition to find_alternate_tgs() to handle the length-one output from krb5_walk_realm_tree(). The vulnerable configuration is not likely to arise in practice. (Realm names that have a single component are likely to be test realms.) Releases prior to krb5-1.11 are not vulnerable. Thanks to Sol Jerome for reporting this problem. CVSSv2: AV:N/AC:M/Au:S/C:N/I:N/A:P/E:H/RL:O/RC:C (cherry picked from commit 3c7f1c21ffaaf6c90f1045f0f5440303c766acc0) ticket: 7668 version_fixed: 1.11.4 status: resolved'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static ssize_t __nfs4_get_acl_uncached(struct inode *inode, void *buf, size_t buflen) { struct page *pages[NFS4ACL_MAXPAGES] = {NULL, }; struct nfs_getaclargs args = { .fh = NFS_FH(inode), .acl_pages = pages, .acl_len = buflen, }; struct nfs_getaclres res = { .acl_len = buflen, }; struct rpc_message msg = { .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_GETACL], .rpc_argp = &args, .rpc_resp = &res, }; unsigned int npages = DIV_ROUND_UP(buflen, PAGE_SIZE); int ret = -ENOMEM, i; /* As long as we're doing a round trip to the server anyway, * let's be prepared for a page of acl data. */ if (npages == 0) npages = 1; if (npages > ARRAY_SIZE(pages)) return -ERANGE; for (i = 0; i < npages; i++) { pages[i] = alloc_page(GFP_KERNEL); if (!pages[i]) goto out_free; } /* for decoding across pages */ res.acl_scratch = alloc_page(GFP_KERNEL); if (!res.acl_scratch) goto out_free; args.acl_len = npages * PAGE_SIZE; args.acl_pgbase = 0; dprintk("%s buf %p buflen %zu npages %d args.acl_len %zu\n", __func__, buf, buflen, npages, args.acl_len); ret = nfs4_call_sync(NFS_SERVER(inode)->client, NFS_SERVER(inode), &msg, &args.seq_args, &res.seq_res, 0); if (ret) goto out_free; /* Handle the case where the passed-in buffer is too short */ if (res.acl_flags & NFS4_ACL_TRUNC) { /* Did the user only issue a request for the acl length? */ if (buf == NULL) goto out_ok; ret = -ERANGE; goto out_free; } nfs4_write_cached_acl(inode, pages, res.acl_data_offset, res.acl_len); if (buf) _copy_from_pages(buf, pages, res.acl_data_offset, res.acl_len); out_ok: ret = res.acl_len; out_free: for (i = 0; i < npages; i++) if (pages[i]) __free_page(pages[i]); if (res.acl_scratch) __free_page(res.acl_scratch); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-401'], 'message': 'NFSv4: Check for buffer length in __nfs4_get_acl_uncached Commit 1f1ea6c "NFSv4: Fix buffer overflow checking in __nfs4_get_acl_uncached" accidently dropped the checking for too small result buffer length. If someone uses getxattr on "system.nfs4_acl" on an NFSv4 mount supporting ACLs, the ACL has not been cached and the buffer suplied is too short, we still copy the complete ACL, resulting in kernel and user space memory corruption. Signed-off-by: Sven Wegener <[email protected]> Cc: [email protected] Signed-off-by: Trond Myklebust <[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 __kvm_set_memory_region(struct kvm *kvm, struct kvm_userspace_memory_region *mem, int user_alloc) { int r; gfn_t base_gfn; unsigned long npages; struct kvm_memory_slot *memslot, *slot; struct kvm_memory_slot old, new; struct kvm_memslots *slots, *old_memslots; r = check_memory_region_flags(mem); if (r) goto out; r = -EINVAL; /* General sanity checks */ if (mem->memory_size & (PAGE_SIZE - 1)) goto out; if (mem->guest_phys_addr & (PAGE_SIZE - 1)) goto out; /* We can read the guest memory with __xxx_user() later on. */ if (user_alloc && ((mem->userspace_addr & (PAGE_SIZE - 1)) || !access_ok(VERIFY_WRITE, (void __user *)(unsigned long)mem->userspace_addr, mem->memory_size))) goto out; if (mem->slot >= KVM_MEM_SLOTS_NUM) goto out; if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr) goto out; memslot = id_to_memslot(kvm->memslots, mem->slot); base_gfn = mem->guest_phys_addr >> PAGE_SHIFT; npages = mem->memory_size >> PAGE_SHIFT; r = -EINVAL; if (npages > KVM_MEM_MAX_NR_PAGES) goto out; if (!npages) mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES; new = old = *memslot; new.id = mem->slot; new.base_gfn = base_gfn; new.npages = npages; new.flags = mem->flags; /* * Disallow changing a memory slot's size or changing anything about * zero sized slots that doesn't involve making them non-zero. */ r = -EINVAL; if (npages && old.npages && npages != old.npages) goto out_free; if (!npages && !old.npages) goto out_free; /* Check for overlaps */ r = -EEXIST; kvm_for_each_memslot(slot, kvm->memslots) { if (slot->id >= KVM_MEMORY_SLOTS || slot == memslot) continue; if (!((base_gfn + npages <= slot->base_gfn) || (base_gfn >= slot->base_gfn + slot->npages))) goto out_free; } /* Free page dirty bitmap if unneeded */ if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES)) new.dirty_bitmap = NULL; r = -ENOMEM; /* * Allocate if a slot is being created. If modifying a slot, * the userspace_addr cannot change. */ if (!old.npages) { new.user_alloc = user_alloc; new.userspace_addr = mem->userspace_addr; if (kvm_arch_create_memslot(&new, npages)) goto out_free; } else if (npages && mem->userspace_addr != old.userspace_addr) { r = -EINVAL; goto out_free; } /* Allocate page dirty bitmap if needed */ if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) { if (kvm_create_dirty_bitmap(&new) < 0) goto out_free; /* destroy any largepage mappings for dirty tracking */ } if (!npages || base_gfn != old.base_gfn) { struct kvm_memory_slot *slot; r = -ENOMEM; slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; slot = id_to_memslot(slots, mem->slot); slot->flags |= KVM_MEMSLOT_INVALID; update_memslots(slots, NULL); old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); /* From this point no new shadow pages pointing to a deleted, * or moved, memslot will be created. * * validation of sp->gfn happens in: * - gfn_to_hva (kvm_read_guest, gfn_to_pfn) * - kvm_is_visible_gfn (mmu_check_roots) */ kvm_arch_flush_shadow_memslot(kvm, slot); kfree(old_memslots); } r = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc); if (r) goto out_free; /* map/unmap the pages in iommu page table */ if (npages) { r = kvm_iommu_map_pages(kvm, &new); if (r) goto out_free; } else kvm_iommu_unmap_pages(kvm, &old); r = -ENOMEM; slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; /* actual memory is freed via old in kvm_free_physmem_slot below */ if (!npages) { new.dirty_bitmap = NULL; memset(&new.arch, 0, sizeof(new.arch)); } update_memslots(slots, &new); old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); kvm_arch_commit_memory_region(kvm, mem, old, user_alloc); kvm_free_physmem_slot(&old, &new); kfree(old_memslots); return 0; out_free: kvm_free_physmem_slot(&new, &old); out: return r; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'KVM: Fix iommu map/unmap to handle memory slot moves The iommu integration into memory slots expects memory slots to be added or removed and doesn't handle the move case. We can unmap slots from the iommu after we mark them invalid and map them before installing the final memslot array. Also re-order the kmemdup vs map so we don't leave iommu mappings if we get ENOMEM. Reviewed-by: Gleb Natapov <[email protected]> Signed-off-by: Alex Williamson <[email protected]> Signed-off-by: Marcelo Tosatti <[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 json_object* json_tokener_parse_ex(struct json_tokener *tok, const char *str, int len) { struct json_object *obj = NULL; char c = '\1'; #ifdef HAVE_SETLOCALE char *oldlocale=NULL, *tmplocale; tmplocale = setlocale(LC_NUMERIC, NULL); if (tmplocale) oldlocale = strdup(tmplocale); setlocale(LC_NUMERIC, "C"); #endif tok->char_offset = 0; tok->err = json_tokener_success; while (PEEK_CHAR(c, tok)) { redo_char: switch(state) { case json_tokener_state_eatws: /* Advance until we change state */ while (isspace((int)c)) { if ((!ADVANCE_CHAR(str, tok)) || (!PEEK_CHAR(c, tok))) goto out; } if(c == '/' && !(tok->flags & JSON_TOKENER_STRICT)) { printbuf_reset(tok->pb); printbuf_memappend_fast(tok->pb, &c, 1); state = json_tokener_state_comment_start; } else { state = saved_state; goto redo_char; } break; case json_tokener_state_start: switch(c) { case '{': state = json_tokener_state_eatws; saved_state = json_tokener_state_object_field_start; current = json_object_new_object(); break; case '[': state = json_tokener_state_eatws; saved_state = json_tokener_state_array; current = json_object_new_array(); break; case 'I': case 'i': state = json_tokener_state_inf; printbuf_reset(tok->pb); tok->st_pos = 0; goto redo_char; case 'N': case 'n': state = json_tokener_state_null; // or NaN printbuf_reset(tok->pb); tok->st_pos = 0; goto redo_char; case '\'': if (tok->flags & JSON_TOKENER_STRICT) { /* in STRICT mode only double-quote are allowed */ tok->err = json_tokener_error_parse_unexpected; goto out; } case '"': state = json_tokener_state_string; printbuf_reset(tok->pb); tok->quote_char = c; break; case 'T': case 't': case 'F': case 'f': state = json_tokener_state_boolean; printbuf_reset(tok->pb); tok->st_pos = 0; goto redo_char; #if defined(__GNUC__) case '0' ... '9': #else case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': #endif case '-': state = json_tokener_state_number; printbuf_reset(tok->pb); tok->is_double = 0; goto redo_char; default: tok->err = json_tokener_error_parse_unexpected; goto out; } break; case json_tokener_state_finish: if(tok->depth == 0) goto out; obj = json_object_get(current); json_tokener_reset_level(tok, tok->depth); tok->depth--; goto redo_char; case json_tokener_state_inf: /* aka starts with 'i' */ { int size; int size_inf; int is_negative = 0; printbuf_memappend_fast(tok->pb, &c, 1); size = json_min(tok->st_pos+1, json_null_str_len); size_inf = json_min(tok->st_pos+1, json_inf_str_len); char *infbuf = tok->pb->buf; if (*infbuf == '-') { infbuf++; is_negative = 1; } if ((!(tok->flags & JSON_TOKENER_STRICT) && strncasecmp(json_inf_str, infbuf, size_inf) == 0) || (strncmp(json_inf_str, infbuf, size_inf) == 0) ) { if (tok->st_pos == json_inf_str_len) { current = json_object_new_double(is_negative ? -INFINITY : INFINITY); saved_state = json_tokener_state_finish; state = json_tokener_state_eatws; goto redo_char; } } else { tok->err = json_tokener_error_parse_unexpected; goto out; } tok->st_pos++; } break; case json_tokener_state_null: /* aka starts with 'n' */ { int size; int size_nan; printbuf_memappend_fast(tok->pb, &c, 1); size = json_min(tok->st_pos+1, json_null_str_len); size_nan = json_min(tok->st_pos+1, json_nan_str_len); if((!(tok->flags & JSON_TOKENER_STRICT) && strncasecmp(json_null_str, tok->pb->buf, size) == 0) || (strncmp(json_null_str, tok->pb->buf, size) == 0) ) { if (tok->st_pos == json_null_str_len) { current = NULL; saved_state = json_tokener_state_finish; state = json_tokener_state_eatws; goto redo_char; } } else if ((!(tok->flags & JSON_TOKENER_STRICT) && strncasecmp(json_nan_str, tok->pb->buf, size_nan) == 0) || (strncmp(json_nan_str, tok->pb->buf, size_nan) == 0) ) { if (tok->st_pos == json_nan_str_len) { current = json_object_new_double(NAN); saved_state = json_tokener_state_finish; state = json_tokener_state_eatws; goto redo_char; } } else { tok->err = json_tokener_error_parse_null; goto out; } tok->st_pos++; } break; case json_tokener_state_comment_start: if(c == '*') { state = json_tokener_state_comment; } else if(c == '/') { state = json_tokener_state_comment_eol; } else { tok->err = json_tokener_error_parse_comment; goto out; } printbuf_memappend_fast(tok->pb, &c, 1); break; case json_tokener_state_comment: { /* Advance until we change state */ const char *case_start = str; while(c != '*') { if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) { printbuf_memappend_fast(tok->pb, case_start, str-case_start); goto out; } } printbuf_memappend_fast(tok->pb, case_start, 1+str-case_start); state = json_tokener_state_comment_end; } break; case json_tokener_state_comment_eol: { /* Advance until we change state */ const char *case_start = str; while(c != '\n') { if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) { printbuf_memappend_fast(tok->pb, case_start, str-case_start); goto out; } } printbuf_memappend_fast(tok->pb, case_start, str-case_start); MC_DEBUG("json_tokener_comment: %s\n", tok->pb->buf); state = json_tokener_state_eatws; } break; case json_tokener_state_comment_end: printbuf_memappend_fast(tok->pb, &c, 1); if(c == '/') { MC_DEBUG("json_tokener_comment: %s\n", tok->pb->buf); state = json_tokener_state_eatws; } else { state = json_tokener_state_comment; } break; case json_tokener_state_string: { /* Advance until we change state */ const char *case_start = str; while(1) { if(c == tok->quote_char) { printbuf_memappend_fast(tok->pb, case_start, str-case_start); current = json_object_new_string_len(tok->pb->buf, tok->pb->bpos); saved_state = json_tokener_state_finish; state = json_tokener_state_eatws; break; } else if(c == '\\') { printbuf_memappend_fast(tok->pb, case_start, str-case_start); saved_state = json_tokener_state_string; state = json_tokener_state_string_escape; break; } if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) { printbuf_memappend_fast(tok->pb, case_start, str-case_start); goto out; } } } break; case json_tokener_state_string_escape: switch(c) { case '"': case '\\': case '/': printbuf_memappend_fast(tok->pb, &c, 1); state = saved_state; break; case 'b': case 'n': case 'r': case 't': case 'f': if(c == 'b') printbuf_memappend_fast(tok->pb, "\b", 1); else if(c == 'n') printbuf_memappend_fast(tok->pb, "\n", 1); else if(c == 'r') printbuf_memappend_fast(tok->pb, "\r", 1); else if(c == 't') printbuf_memappend_fast(tok->pb, "\t", 1); else if(c == 'f') printbuf_memappend_fast(tok->pb, "\f", 1); state = saved_state; break; case 'u': tok->ucs_char = 0; tok->st_pos = 0; state = json_tokener_state_escape_unicode; break; default: tok->err = json_tokener_error_parse_string; goto out; } break; case json_tokener_state_escape_unicode: { unsigned int got_hi_surrogate = 0; /* Handle a 4-byte sequence, or two sequences if a surrogate pair */ while(1) { if(strchr(json_hex_chars, c)) { tok->ucs_char += ((unsigned int)hexdigit(c) << ((3-tok->st_pos++)*4)); if(tok->st_pos == 4) { unsigned char unescaped_utf[4]; if (got_hi_surrogate) { if (IS_LOW_SURROGATE(tok->ucs_char)) { /* Recalculate the ucs_char, then fall thru to process normally */ tok->ucs_char = DECODE_SURROGATE_PAIR(got_hi_surrogate, tok->ucs_char); } else { /* Hi surrogate was not followed by a low surrogate */ /* Replace the hi and process the rest normally */ printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3); } got_hi_surrogate = 0; } if (tok->ucs_char < 0x80) { unescaped_utf[0] = tok->ucs_char; printbuf_memappend_fast(tok->pb, (char*)unescaped_utf, 1); } else if (tok->ucs_char < 0x800) { unescaped_utf[0] = 0xc0 | (tok->ucs_char >> 6); unescaped_utf[1] = 0x80 | (tok->ucs_char & 0x3f); printbuf_memappend_fast(tok->pb, (char*)unescaped_utf, 2); } else if (IS_HIGH_SURROGATE(tok->ucs_char)) { /* Got a high surrogate. Remember it and look for the * the beginning of another sequence, which should be the * low surrogate. */ got_hi_surrogate = tok->ucs_char; /* Not at end, and the next two chars should be "\u" */ if ((tok->char_offset+1 != len) && (tok->char_offset+2 != len) && (str[1] == '\\') && (str[2] == 'u')) { /* Advance through the 16 bit surrogate, and move on to the * next sequence. The next step is to process the following * characters. */ if( !ADVANCE_CHAR(str, tok) || !ADVANCE_CHAR(str, tok) ) { printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3); } /* Advance to the first char of the next sequence and * continue processing with the next sequence. */ if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) { printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3); goto out; } tok->ucs_char = 0; tok->st_pos = 0; continue; /* other json_tokener_state_escape_unicode */ } else { /* Got a high surrogate without another sequence following * it. Put a replacement char in for the hi surrogate * and pretend we finished. */ printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3); } } else if (IS_LOW_SURROGATE(tok->ucs_char)) { /* Got a low surrogate not preceded by a high */ printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3); } else if (tok->ucs_char < 0x10000) { unescaped_utf[0] = 0xe0 | (tok->ucs_char >> 12); unescaped_utf[1] = 0x80 | ((tok->ucs_char >> 6) & 0x3f); unescaped_utf[2] = 0x80 | (tok->ucs_char & 0x3f); printbuf_memappend_fast(tok->pb, (char*)unescaped_utf, 3); } else if (tok->ucs_char < 0x110000) { unescaped_utf[0] = 0xf0 | ((tok->ucs_char >> 18) & 0x07); unescaped_utf[1] = 0x80 | ((tok->ucs_char >> 12) & 0x3f); unescaped_utf[2] = 0x80 | ((tok->ucs_char >> 6) & 0x3f); unescaped_utf[3] = 0x80 | (tok->ucs_char & 0x3f); printbuf_memappend_fast(tok->pb, (char*)unescaped_utf, 4); } else { /* Don't know what we got--insert the replacement char */ printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3); } state = saved_state; break; } } else { tok->err = json_tokener_error_parse_string; goto out; } if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) { if (got_hi_surrogate) /* Clean up any pending chars */ printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3); goto out; } } } break; case json_tokener_state_boolean: { int size1, size2; printbuf_memappend_fast(tok->pb, &c, 1); size1 = json_min(tok->st_pos+1, json_true_str_len); size2 = json_min(tok->st_pos+1, json_false_str_len); if((!(tok->flags & JSON_TOKENER_STRICT) && strncasecmp(json_true_str, tok->pb->buf, size1) == 0) || (strncmp(json_true_str, tok->pb->buf, size1) == 0) ) { if(tok->st_pos == json_true_str_len) { current = json_object_new_boolean(1); saved_state = json_tokener_state_finish; state = json_tokener_state_eatws; goto redo_char; } } else if((!(tok->flags & JSON_TOKENER_STRICT) && strncasecmp(json_false_str, tok->pb->buf, size2) == 0) || (strncmp(json_false_str, tok->pb->buf, size2) == 0)) { if(tok->st_pos == json_false_str_len) { current = json_object_new_boolean(0); saved_state = json_tokener_state_finish; state = json_tokener_state_eatws; goto redo_char; } } else { tok->err = json_tokener_error_parse_boolean; goto out; } tok->st_pos++; } break; case json_tokener_state_number: { /* Advance until we change state */ const char *case_start = str; int case_len=0; while(c && strchr(json_number_chars, c)) { ++case_len; if(c == '.' || c == 'e' || c == 'E') tok->is_double = 1; if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) { printbuf_memappend_fast(tok->pb, case_start, case_len); goto out; } } if (case_len>0) printbuf_memappend_fast(tok->pb, case_start, case_len); // Check for -Infinity if (tok->pb->buf[0] == '-' && case_len == 1 && (c == 'i' || c == 'I')) { state = json_tokener_state_inf; goto redo_char; } } { int64_t num64; double numd; if (!tok->is_double && json_parse_int64(tok->pb->buf, &num64) == 0) { if (num64 && tok->pb->buf[0]=='0' && (tok->flags & JSON_TOKENER_STRICT)) { /* in strict mode, number must not start with 0 */ tok->err = json_tokener_error_parse_number; goto out; } current = json_object_new_int64(num64); } else if(tok->is_double && json_parse_double(tok->pb->buf, &numd) == 0) { current = json_object_new_double_s(numd, tok->pb->buf); } else { tok->err = json_tokener_error_parse_number; goto out; } saved_state = json_tokener_state_finish; state = json_tokener_state_eatws; goto redo_char; } break; case json_tokener_state_array_after_sep: case json_tokener_state_array: if(c == ']') { if (state == json_tokener_state_array_after_sep && (tok->flags & JSON_TOKENER_STRICT)) { tok->err = json_tokener_error_parse_unexpected; goto out; } saved_state = json_tokener_state_finish; state = json_tokener_state_eatws; } else { if(tok->depth >= tok->max_depth-1) { tok->err = json_tokener_error_depth; goto out; } state = json_tokener_state_array_add; tok->depth++; json_tokener_reset_level(tok, tok->depth); goto redo_char; } break; case json_tokener_state_array_add: json_object_array_add(current, obj); saved_state = json_tokener_state_array_sep; state = json_tokener_state_eatws; goto redo_char; case json_tokener_state_array_sep: if(c == ']') { saved_state = json_tokener_state_finish; state = json_tokener_state_eatws; } else if(c == ',') { saved_state = json_tokener_state_array_after_sep; state = json_tokener_state_eatws; } else { tok->err = json_tokener_error_parse_array; goto out; } break; case json_tokener_state_object_field_start: case json_tokener_state_object_field_start_after_sep: if(c == '}') { if (state == json_tokener_state_object_field_start_after_sep && (tok->flags & JSON_TOKENER_STRICT)) { tok->err = json_tokener_error_parse_unexpected; goto out; } saved_state = json_tokener_state_finish; state = json_tokener_state_eatws; } else if (c == '"' || c == '\'') { tok->quote_char = c; printbuf_reset(tok->pb); state = json_tokener_state_object_field; } else { tok->err = json_tokener_error_parse_object_key_name; goto out; } break; case json_tokener_state_object_field: { /* Advance until we change state */ const char *case_start = str; while(1) { if(c == tok->quote_char) { printbuf_memappend_fast(tok->pb, case_start, str-case_start); obj_field_name = strdup(tok->pb->buf); saved_state = json_tokener_state_object_field_end; state = json_tokener_state_eatws; break; } else if(c == '\\') { printbuf_memappend_fast(tok->pb, case_start, str-case_start); saved_state = json_tokener_state_object_field; state = json_tokener_state_string_escape; break; } if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) { printbuf_memappend_fast(tok->pb, case_start, str-case_start); goto out; } } } break; case json_tokener_state_object_field_end: if(c == ':') { saved_state = json_tokener_state_object_value; state = json_tokener_state_eatws; } else { tok->err = json_tokener_error_parse_object_key_sep; goto out; } break; case json_tokener_state_object_value: if(tok->depth >= tok->max_depth-1) { tok->err = json_tokener_error_depth; goto out; } state = json_tokener_state_object_value_add; tok->depth++; json_tokener_reset_level(tok, tok->depth); goto redo_char; case json_tokener_state_object_value_add: json_object_object_add(current, obj_field_name, obj); free(obj_field_name); obj_field_name = NULL; saved_state = json_tokener_state_object_sep; state = json_tokener_state_eatws; goto redo_char; case json_tokener_state_object_sep: if(c == '}') { saved_state = json_tokener_state_finish; state = json_tokener_state_eatws; } else if(c == ',') { saved_state = json_tokener_state_object_field_start_after_sep; state = json_tokener_state_eatws; } else { tok->err = json_tokener_error_parse_object_value_sep; goto out; } break; } if (!ADVANCE_CHAR(str, tok)) goto out; } /* while(POP_CHAR) */ out: if (c && (state == json_tokener_state_finish) && (tok->depth == 0) && (tok->flags & JSON_TOKENER_STRICT)) { /* unexpected char after JSON data */ tok->err = json_tokener_error_parse_unexpected; } if (!c) { /* We hit an eof char (0) */ if(state != json_tokener_state_finish && saved_state != json_tokener_state_finish) tok->err = json_tokener_error_parse_eof; } #ifdef HAVE_SETLOCALE setlocale(LC_NUMERIC, oldlocale); if (oldlocale) free(oldlocale); #endif if (tok->err == json_tokener_success) { json_object *ret = json_object_get(current); int ii; /* Partially reset, so we parse additional objects on subsequent calls. */ for(ii = tok->depth; ii >= 0; ii--) json_tokener_reset_level(tok, ii); return ret; } MC_DEBUG("json_tokener_parse_ex: error %s at offset %d\n", json_tokener_errors[tok->err], tok->char_offset); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-310'], 'message': 'Patch to address the following issues: * CVE-2013-6371: hash collision denial of service * CVE-2013-6370: buffer overflow if size_t is larger than int'</s>
<s>[INST] Given the following code containing errors, provide 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 Bfree(Bigint *v) { if (v) { ACQUIRE_DTOA_LOCK(0); v->next = freelist[v->k]; freelist[v->k] = v; FREE_DTOA_LOCK(0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'util.c: ignore too long fraction part * util.c (ruby_strtod): ignore too long fraction part, which does not affect the result. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@43775 b2dd03c8-39d4-4d8f-98ff-823fe69b080e'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static Bigint * Balloc(int k) { int x; Bigint *rv; #ifndef Omit_Private_Memory size_t len; #endif ACQUIRE_DTOA_LOCK(0); if ((rv = freelist[k]) != 0) { freelist[k] = rv->next; } else { x = 1 << k; #ifdef Omit_Private_Memory rv = (Bigint *)MALLOC(sizeof(Bigint) + (x-1)*sizeof(ULong)); #else len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1) /sizeof(double); if (pmem_next - private_mem + len <= PRIVATE_mem) { rv = (Bigint*)pmem_next; pmem_next += len; } else rv = (Bigint*)MALLOC(len*sizeof(double)); #endif rv->k = k; rv->maxwds = x; } FREE_DTOA_LOCK(0); rv->sign = rv->wds = 0; return rv; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'util.c: ignore too long fraction part * util.c (ruby_strtod): ignore too long fraction part, which does not affect the result. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@43775 b2dd03c8-39d4-4d8f-98ff-823fe69b080e'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void add_bytes_c(uint8_t *dst, uint8_t *src, int w){ long i; for(i=0; i<=w-sizeof(long); i+=sizeof(long)){ long a = *(long*)(src+i); long b = *(long*)(dst+i); *(long*)(dst+i) = ((a&pb_7f) + (b&pb_7f)) ^ ((a^b)&pb_80); } for(; i<w; i++) dst[i+0] += src[i+0]; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'avcodec/dsputil: fix signedness in sizeof() comparissions Signed-off-by: Michael Niedermayer <[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 ff_combine_frame(ParseContext *pc, int next, const uint8_t **buf, int *buf_size) { if(pc->overread){ av_dlog(NULL, "overread %d, state:%X next:%d index:%d o_index:%d\n", pc->overread, pc->state, next, pc->index, pc->overread_index); av_dlog(NULL, "%X %X %X %X\n", (*buf)[0], (*buf)[1], (*buf)[2], (*buf)[3]); } /* Copy overread bytes from last frame into buffer. */ for(; pc->overread>0; pc->overread--){ pc->buffer[pc->index++]= pc->buffer[pc->overread_index++]; } /* flush remaining if EOF */ if(!*buf_size && next == END_NOT_FOUND){ next= 0; } pc->last_index= pc->index; /* copy into buffer end return */ if(next == END_NOT_FOUND){ void* new_buffer = av_fast_realloc(pc->buffer, &pc->buffer_size, (*buf_size) + pc->index + FF_INPUT_BUFFER_PADDING_SIZE); if(!new_buffer) return AVERROR(ENOMEM); pc->buffer = new_buffer; memcpy(&pc->buffer[pc->index], *buf, *buf_size); pc->index += *buf_size; return -1; } *buf_size= pc->overread_index= pc->index + next; /* append to buffer */ if(pc->index){ void* new_buffer = av_fast_realloc(pc->buffer, &pc->buffer_size, next + pc->index + FF_INPUT_BUFFER_PADDING_SIZE); if(!new_buffer) return AVERROR(ENOMEM); pc->buffer = new_buffer; if (next > -FF_INPUT_BUFFER_PADDING_SIZE) memcpy(&pc->buffer[pc->index], *buf, next + FF_INPUT_BUFFER_PADDING_SIZE); pc->index = 0; *buf= pc->buffer; } /* store overread bytes */ for(;next < 0; next++){ pc->state = (pc->state<<8) | pc->buffer[pc->last_index + next]; pc->state64 = (pc->state64<<8) | pc->buffer[pc->last_index + next]; pc->overread++; } if(pc->overread){ av_dlog(NULL, "overread %d, state:%X next:%d index:%d o_index:%d\n", pc->overread, pc->state, next, pc->index, pc->overread_index); av_dlog(NULL, "%X %X %X %X\n", (*buf)[0], (*buf)[1],(*buf)[2],(*buf)[3]); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'avcodec/parser: reset indexes on realloc failure Fixes Ticket2982 Signed-off-by: Michael Niedermayer <[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: json_t *json_object(void) { json_object_t *object = jsonp_malloc(sizeof(json_object_t)); if(!object) return NULL; json_init(&object->json, JSON_OBJECT); if(hashtable_init(&object->hashtable)) { jsonp_free(object); return NULL; } object->serial = 0; object->visited = 0; return &object->json; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'CVE-2013-6401: Change hash function, randomize hashes Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing and testing.'</s>
<s>[INST] Given the following code containing errors, provide 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 JSON_INLINE size_t num_buckets(hashtable_t *hashtable) { return primes[hashtable->num_buckets]; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'CVE-2013-6401: Change hash function, randomize hashes Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing and testing.'</s>
<s>[INST] Given the following code containing errors, provide 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 use_env() { int indent; size_t flags = 0; json_t *json; json_error_t error; #ifdef _WIN32 /* On Windows, set stdout and stderr to binary mode to avoid outputting DOS line terminators */ _setmode(_fileno(stdout), _O_BINARY); _setmode(_fileno(stderr), _O_BINARY); #endif indent = getenv_int("JSON_INDENT"); if(indent < 0 || indent > 255) { fprintf(stderr, "invalid value for JSON_INDENT: %d\n", indent); return 2; } if(indent > 0) flags |= JSON_INDENT(indent); if(getenv_int("JSON_COMPACT") > 0) flags |= JSON_COMPACT; if(getenv_int("JSON_ENSURE_ASCII")) flags |= JSON_ENSURE_ASCII; if(getenv_int("JSON_PRESERVE_ORDER")) flags |= JSON_PRESERVE_ORDER; if(getenv_int("JSON_SORT_KEYS")) flags |= JSON_SORT_KEYS; if(getenv_int("STRIP")) { /* Load to memory, strip leading and trailing whitespace */ size_t size = 0, used = 0; char *buffer = NULL; while(1) { size_t count; size = (size == 0 ? 128 : size * 2); buffer = realloc(buffer, size); if(!buffer) { fprintf(stderr, "Unable to allocate %d bytes\n", (int)size); return 1; } count = fread(buffer + used, 1, size - used, stdin); if(count < size - used) { buffer[used + count] = '\0'; break; } used += count; } json = json_loads(strip(buffer), 0, &error); free(buffer); } else json = json_loadf(stdin, 0, &error); if(!json) { fprintf(stderr, "%d %d %d\n%s\n", error.line, error.column, error.position, error.text); return 1; } json_dumpf(json, stdout, flags); json_decref(json); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'CVE-2013-6401: Change hash function, randomize hashes Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing and testing.'</s>
<s>[INST] Given the following code containing errors, provide 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 *my_malloc(size_t size) { malloc_called += 1; return malloc(size); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'CVE-2013-6401: Change hash function, randomize hashes Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing and testing.'</s>
<s>[INST] Given the following code containing errors, provide 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 *hashtable_iter_at(hashtable_t *hashtable, const char *key) { pair_t *pair; size_t hash; bucket_t *bucket; hash = hash_str(key); bucket = &hashtable->buckets[hash % num_buckets(hashtable)]; pair = hashtable_find_pair(hashtable, bucket, key, hash); if(!pair) return NULL; return &pair->list; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'CVE-2013-6401: Change hash function, randomize hashes Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing and testing.'</s>
<s>[INST] Given the following code containing errors, provide 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 hashtable_do_rehash(hashtable_t *hashtable) { list_t *list, *next; pair_t *pair; size_t i, index, new_size; jsonp_free(hashtable->buckets); hashtable->num_buckets++; new_size = num_buckets(hashtable); hashtable->buckets = jsonp_malloc(new_size * sizeof(bucket_t)); if(!hashtable->buckets) return -1; for(i = 0; i < num_buckets(hashtable); i++) { hashtable->buckets[i].first = hashtable->buckets[i].last = &hashtable->list; } list = hashtable->list.next; list_init(&hashtable->list); for(; list != &hashtable->list; list = next) { next = list->next; pair = list_to_pair(list); index = pair->hash % new_size; insert_to_bucket(hashtable, &hashtable->buckets[index], &pair->list); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'CVE-2013-6401: Change hash function, randomize hashes Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing and testing.'</s>
<s>[INST] Given the following code containing errors, provide 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 test_simple() { json_set_alloc_funcs(my_malloc, my_free); create_and_free_complex_object(); if(malloc_called != 20 || free_called != 20) fail("Custom allocation failed"); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'CVE-2013-6401: Change hash function, randomize hashes Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing and testing.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static size_t hash_str(const void *ptr) { const char *str = (const char *)ptr; size_t hash = 5381; size_t c; while((c = (size_t)*str)) { hash = ((hash << 5) + hash) + c; str++; } return hash; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'CVE-2013-6401: Change hash function, randomize hashes Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing and testing.'</s>
<s>[INST] Given the following code containing errors, provide 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 json_object_seed(size_t seed) { uint32_t new_seed = (uint32_t)seed; if (hashtable_seed == 0) { if (InterlockedIncrement(&seed_initialized) == 1) { /* Do the seeding ourselves */ if (new_seed == 0) new_seed = generate_seed(); hashtable_seed = new_seed; } else { /* Wait for another thread to do the seeding */ do { SwitchToThread(); } while (hashtable_seed == 0); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Oops, ATOMIC_ACQ_REL is not a correct memmodel for __atomic_store_n'</s>
<s>[INST] Given the following code containing errors, provide 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 json_object_seed(size_t seed) { uint32_t new_seed = (uint32_t)seed; if (hashtable_seed == 0) { if (new_seed == 0) new_seed = generate_seed(); hashtable_seed = new_seed; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Oops, ATOMIC_ACQ_REL is not a correct memmodel for __atomic_store_n'</s>
<s>[INST] Given the following code containing errors, provide 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 scan(Scanner *s) { uchar *cursor = s->cur; char *str, *ptr = NULL; std: s->tok = cursor; s->len = 0; #line 311 "ext/date/lib/parse_iso_intervals.re" #line 291 "ext/date/lib/parse_iso_intervals.c" { YYCTYPE yych; unsigned int yyaccept = 0; static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; YYDEBUG(0, *YYCURSOR); if ((YYLIMIT - YYCURSOR) < 20) YYFILL(20); yych = *YYCURSOR; if (yych <= ',') { if (yych <= '\n') { if (yych <= 0x00) goto yy9; if (yych <= 0x08) goto yy11; if (yych <= '\t') goto yy7; goto yy9; } else { if (yych == ' ') goto yy7; if (yych <= '+') goto yy11; goto yy7; } } else { if (yych <= 'O') { if (yych <= '-') goto yy11; if (yych <= '/') goto yy7; if (yych <= '9') goto yy4; goto yy11; } else { if (yych <= 'P') goto yy5; if (yych != 'R') goto yy11; } } YYDEBUG(2, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '/') goto yy3; if (yych <= '9') goto yy98; yy3: YYDEBUG(3, *YYCURSOR); #line 424 "ext/date/lib/parse_iso_intervals.re" { add_error(s, "Unexpected character"); goto std; } #line 366 "ext/date/lib/parse_iso_intervals.c" yy4: YYDEBUG(4, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') goto yy3; if (yych <= '9') goto yy59; goto yy3; yy5: YYDEBUG(5, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') goto yy6; if (yych <= '9') goto yy12; if (yych == 'T') goto yy14; yy6: YYDEBUG(6, *YYCURSOR); #line 351 "ext/date/lib/parse_iso_intervals.re" { timelib_sll nr; int in_time = 0; DEBUG_OUTPUT("period"); TIMELIB_INIT; ptr++; do { if ( *ptr == 'T' ) { in_time = 1; ptr++; } if ( *ptr == '\0' ) { add_error(s, "Missing expected time part"); break; } nr = timelib_get_unsigned_nr((char **) &ptr, 12); switch (*ptr) { case 'Y': s->period->y = nr; break; case 'W': s->period->d = nr * 7; break; case 'D': s->period->d = nr; break; case 'H': s->period->h = nr; break; case 'S': s->period->s = nr; break; case 'M': if (in_time) { s->period->i = nr; } else { s->period->m = nr; } break; default: add_error(s, "Undefined period specifier"); break; } ptr++; } while (*ptr); s->have_period = 1; TIMELIB_DEINIT; return TIMELIB_PERIOD; } #line 424 "ext/date/lib/parse_iso_intervals.c" yy7: YYDEBUG(7, *YYCURSOR); ++YYCURSOR; YYDEBUG(8, *YYCURSOR); #line 413 "ext/date/lib/parse_iso_intervals.re" { goto std; } #line 433 "ext/date/lib/parse_iso_intervals.c" yy9: YYDEBUG(9, *YYCURSOR); ++YYCURSOR; YYDEBUG(10, *YYCURSOR); #line 418 "ext/date/lib/parse_iso_intervals.re" { s->pos = cursor; s->line++; goto std; } #line 443 "ext/date/lib/parse_iso_intervals.c" yy11: YYDEBUG(11, *YYCURSOR); yych = *++YYCURSOR; goto yy3; yy12: YYDEBUG(12, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych <= '9') { if (yych >= '0') goto yy25; } else { if (yych == 'D') goto yy24; } } else { if (yych <= 'W') { if (yych <= 'M') goto yy27; if (yych >= 'W') goto yy26; } else { if (yych == 'Y') goto yy28; } } yy13: YYDEBUG(13, *YYCURSOR); YYCURSOR = YYMARKER; if (yyaccept <= 0) { goto yy3; } else { goto yy6; } yy14: YYDEBUG(14, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 128) { goto yy15; } goto yy6; yy15: YYDEBUG(15, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; YYDEBUG(16, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy15; } if (yych <= 'L') { if (yych == 'H') goto yy19; goto yy13; } else { if (yych <= 'M') goto yy18; if (yych != 'S') goto yy13; } yy17: YYDEBUG(17, *YYCURSOR); yych = *++YYCURSOR; goto yy6; yy18: YYDEBUG(18, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') goto yy6; if (yych <= '9') goto yy22; goto yy6; yy19: YYDEBUG(19, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') goto yy6; if (yych >= ':') goto yy6; yy20: YYDEBUG(20, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; YYDEBUG(21, *YYCURSOR); if (yych <= 'L') { if (yych <= '/') goto yy13; if (yych <= '9') goto yy20; goto yy13; } else { if (yych <= 'M') goto yy18; if (yych == 'S') goto yy17; goto yy13; } yy22: YYDEBUG(22, *YYCURSOR); ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; YYDEBUG(23, *YYCURSOR); if (yych <= '/') goto yy13; if (yych <= '9') goto yy22; if (yych == 'S') goto yy17; goto yy13; yy24: YYDEBUG(24, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy14; goto yy6; yy25: YYDEBUG(25, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych <= '9') { if (yych <= '/') goto yy13; goto yy35; } else { if (yych == 'D') goto yy24; goto yy13; } } else { if (yych <= 'W') { if (yych <= 'M') goto yy27; if (yych <= 'V') goto yy13; } else { if (yych == 'Y') goto yy28; goto yy13; } } yy26: YYDEBUG(26, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') goto yy6; if (yych <= '9') goto yy33; if (yych == 'T') goto yy14; goto yy6; yy27: YYDEBUG(27, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') goto yy6; if (yych <= '9') goto yy31; if (yych == 'T') goto yy14; goto yy6; yy28: YYDEBUG(28, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') goto yy6; if (yych <= '9') goto yy29; if (yych == 'T') goto yy14; goto yy6; yy29: YYDEBUG(29, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 3) YYFILL(3); yych = *YYCURSOR; YYDEBUG(30, *YYCURSOR); if (yych <= 'D') { if (yych <= '/') goto yy13; if (yych <= '9') goto yy29; if (yych <= 'C') goto yy13; goto yy24; } else { if (yych <= 'M') { if (yych <= 'L') goto yy13; goto yy27; } else { if (yych == 'W') goto yy26; goto yy13; } } yy31: YYDEBUG(31, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 3) YYFILL(3); yych = *YYCURSOR; YYDEBUG(32, *YYCURSOR); if (yych <= 'C') { if (yych <= '/') goto yy13; if (yych <= '9') goto yy31; goto yy13; } else { if (yych <= 'D') goto yy24; if (yych == 'W') goto yy26; goto yy13; } yy33: YYDEBUG(33, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 3) YYFILL(3); yych = *YYCURSOR; YYDEBUG(34, *YYCURSOR); if (yych <= '/') goto yy13; if (yych <= '9') goto yy33; if (yych == 'D') goto yy24; goto yy13; yy35: YYDEBUG(35, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych <= '9') { if (yych <= '/') goto yy13; } else { if (yych == 'D') goto yy24; goto yy13; } } else { if (yych <= 'W') { if (yych <= 'M') goto yy27; if (yych <= 'V') goto yy13; goto yy26; } else { if (yych == 'Y') goto yy28; goto yy13; } } YYDEBUG(36, *YYCURSOR); yych = *++YYCURSOR; if (yych != '-') goto yy39; YYDEBUG(37, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '0') goto yy40; if (yych <= '1') goto yy41; goto yy13; yy38: YYDEBUG(38, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 3) YYFILL(3); yych = *YYCURSOR; yy39: YYDEBUG(39, *YYCURSOR); if (yych <= 'L') { if (yych <= '9') { if (yych <= '/') goto yy13; goto yy38; } else { if (yych == 'D') goto yy24; goto yy13; } } else { if (yych <= 'W') { if (yych <= 'M') goto yy27; if (yych <= 'V') goto yy13; goto yy26; } else { if (yych == 'Y') goto yy28; goto yy13; } } yy40: YYDEBUG(40, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '9') goto yy42; goto yy13; yy41: YYDEBUG(41, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= '3') goto yy13; yy42: YYDEBUG(42, *YYCURSOR); yych = *++YYCURSOR; if (yych != '-') goto yy13; YYDEBUG(43, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '0') goto yy44; if (yych <= '2') goto yy45; if (yych <= '3') goto yy46; goto yy13; yy44: YYDEBUG(44, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '9') goto yy47; goto yy13; yy45: YYDEBUG(45, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '9') goto yy47; goto yy13; yy46: YYDEBUG(46, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= '2') goto yy13; yy47: YYDEBUG(47, *YYCURSOR); yych = *++YYCURSOR; if (yych != 'T') goto yy13; YYDEBUG(48, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '1') goto yy49; if (yych <= '2') goto yy50; goto yy13; yy49: YYDEBUG(49, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '9') goto yy51; goto yy13; yy50: YYDEBUG(50, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= '5') goto yy13; yy51: YYDEBUG(51, *YYCURSOR); yych = *++YYCURSOR; if (yych != ':') goto yy13; YYDEBUG(52, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= '6') goto yy13; YYDEBUG(53, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= ':') goto yy13; YYDEBUG(54, *YYCURSOR); yych = *++YYCURSOR; if (yych != ':') goto yy13; YYDEBUG(55, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= '6') goto yy13; YYDEBUG(56, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= ':') goto yy13; YYDEBUG(57, *YYCURSOR); ++YYCURSOR; YYDEBUG(58, *YYCURSOR); #line 393 "ext/date/lib/parse_iso_intervals.re" { DEBUG_OUTPUT("combinedrep"); TIMELIB_INIT; s->period->y = timelib_get_unsigned_nr((char **) &ptr, 4); ptr++; s->period->m = timelib_get_unsigned_nr((char **) &ptr, 2); ptr++; s->period->d = timelib_get_unsigned_nr((char **) &ptr, 2); ptr++; s->period->h = timelib_get_unsigned_nr((char **) &ptr, 2); ptr++; s->period->i = timelib_get_unsigned_nr((char **) &ptr, 2); ptr++; s->period->s = timelib_get_unsigned_nr((char **) &ptr, 2); s->have_period = 1; TIMELIB_DEINIT; return TIMELIB_PERIOD; } #line 792 "ext/date/lib/parse_iso_intervals.c" yy59: YYDEBUG(59, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= ':') goto yy13; YYDEBUG(60, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= ':') goto yy13; YYDEBUG(61, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '-') goto yy64; goto yy13; } else { if (yych <= '0') goto yy62; if (yych <= '1') goto yy63; goto yy13; } yy62: YYDEBUG(62, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '0') goto yy13; if (yych <= '9') goto yy85; goto yy13; yy63: YYDEBUG(63, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '2') goto yy85; goto yy13; yy64: YYDEBUG(64, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '0') goto yy65; if (yych <= '1') goto yy66; goto yy13; yy65: YYDEBUG(65, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '0') goto yy13; if (yych <= '9') goto yy67; goto yy13; yy66: YYDEBUG(66, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= '3') goto yy13; yy67: YYDEBUG(67, *YYCURSOR); yych = *++YYCURSOR; if (yych != '-') goto yy13; YYDEBUG(68, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '0') goto yy69; if (yych <= '2') goto yy70; if (yych <= '3') goto yy71; goto yy13; yy69: YYDEBUG(69, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '0') goto yy13; if (yych <= '9') goto yy72; goto yy13; yy70: YYDEBUG(70, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '9') goto yy72; goto yy13; yy71: YYDEBUG(71, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= '2') goto yy13; yy72: YYDEBUG(72, *YYCURSOR); yych = *++YYCURSOR; if (yych != 'T') goto yy13; YYDEBUG(73, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '1') goto yy74; if (yych <= '2') goto yy75; goto yy13; yy74: YYDEBUG(74, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '9') goto yy76; goto yy13; yy75: YYDEBUG(75, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= '5') goto yy13; yy76: YYDEBUG(76, *YYCURSOR); yych = *++YYCURSOR; if (yych != ':') goto yy13; YYDEBUG(77, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= '6') goto yy13; YYDEBUG(78, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= ':') goto yy13; YYDEBUG(79, *YYCURSOR); yych = *++YYCURSOR; if (yych != ':') goto yy13; YYDEBUG(80, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= '6') goto yy13; YYDEBUG(81, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= ':') goto yy13; YYDEBUG(82, *YYCURSOR); yych = *++YYCURSOR; if (yych != 'Z') goto yy13; yy83: YYDEBUG(83, *YYCURSOR); ++YYCURSOR; YYDEBUG(84, *YYCURSOR); #line 327 "ext/date/lib/parse_iso_intervals.re" { timelib_time *current; if (s->have_date || s->have_period) { current = s->end; s->have_end_date = 1; } else { current = s->begin; s->have_begin_date = 1; } DEBUG_OUTPUT("datetimebasic | datetimeextended"); TIMELIB_INIT; current->y = timelib_get_nr((char **) &ptr, 4); current->m = timelib_get_nr((char **) &ptr, 2); current->d = timelib_get_nr((char **) &ptr, 2); current->h = timelib_get_nr((char **) &ptr, 2); current->i = timelib_get_nr((char **) &ptr, 2); current->s = timelib_get_nr((char **) &ptr, 2); s->have_date = 1; TIMELIB_DEINIT; return TIMELIB_ISO_DATE; } #line 944 "ext/date/lib/parse_iso_intervals.c" yy85: YYDEBUG(85, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '0') goto yy86; if (yych <= '2') goto yy87; if (yych <= '3') goto yy88; goto yy13; yy86: YYDEBUG(86, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '0') goto yy13; if (yych <= '9') goto yy89; goto yy13; yy87: YYDEBUG(87, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '9') goto yy89; goto yy13; yy88: YYDEBUG(88, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= '2') goto yy13; yy89: YYDEBUG(89, *YYCURSOR); yych = *++YYCURSOR; if (yych != 'T') goto yy13; YYDEBUG(90, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '1') goto yy91; if (yych <= '2') goto yy92; goto yy13; yy91: YYDEBUG(91, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych <= '9') goto yy93; goto yy13; yy92: YYDEBUG(92, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= '5') goto yy13; yy93: YYDEBUG(93, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= '6') goto yy13; YYDEBUG(94, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= ':') goto yy13; YYDEBUG(95, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= '6') goto yy13; YYDEBUG(96, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy13; if (yych >= ':') goto yy13; YYDEBUG(97, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Z') goto yy83; goto yy13; yy98: YYDEBUG(98, *YYCURSOR); ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; YYDEBUG(99, *YYCURSOR); if (yych <= '/') goto yy100; if (yych <= '9') goto yy98; yy100: YYDEBUG(100, *YYCURSOR); #line 316 "ext/date/lib/parse_iso_intervals.re" { DEBUG_OUTPUT("recurrences"); TIMELIB_INIT; ptr++; s->recurrences = timelib_get_unsigned_nr((char **) &ptr, 9); TIMELIB_DEINIT; s->have_recurrences = 1; return TIMELIB_PERIOD; } #line 1032 "ext/date/lib/parse_iso_intervals.c" } #line 428 "ext/date/lib/parse_iso_intervals.re" } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fixed bug #66060 (Heap buffer over-read in DateInterval)'</s>
<s>[INST] Given the following code containing errors, provide 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 pn_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct sk_buff *skb = NULL; struct sockaddr_pn sa; int rval = -EOPNOTSUPP; int copylen; if (flags & ~(MSG_PEEK|MSG_TRUNC|MSG_DONTWAIT|MSG_NOSIGNAL| MSG_CMSG_COMPAT)) goto out_nofree; if (addr_len) *addr_len = sizeof(sa); skb = skb_recv_datagram(sk, flags, noblock, &rval); if (skb == NULL) goto out_nofree; pn_skb_get_src_sockaddr(skb, &sa); copylen = skb->len; if (len < copylen) { msg->msg_flags |= MSG_TRUNC; copylen = len; } rval = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copylen); if (rval) { rval = -EFAULT; goto out; } rval = (flags & MSG_TRUNC) ? skb->len : copylen; if (msg->msg_name != NULL) memcpy(msg->msg_name, &sa, sizeof(struct sockaddr_pn)); out: skb_free_datagram(sk, skb); out_nofree: return rval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'inet: prevent leakage of uninitialized memory to user in recv syscalls Only update *addr_len when we actually fill in sockaddr, otherwise we can return uninitialized memory from the stack to the caller in the recvfrom, recvmmsg and recvmsg syscalls. Drop the the (addr_len == NULL) checks because we only get called with a valid addr_len pointer either from sock_common_recvmsg or inet_recvmsg. If a blocking read waits on a socket which is concurrently shut down we now return zero and set msg_msgnamelen to 0. Reported-by: mpb <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int rawv6_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct ipv6_pinfo *np = inet6_sk(sk); struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)msg->msg_name; struct sk_buff *skb; size_t copied; int err; if (flags & MSG_OOB) return -EOPNOTSUPP; if (addr_len) *addr_len=sizeof(*sin6); if (flags & MSG_ERRQUEUE) return ipv6_recv_error(sk, msg, len); if (np->rxpmtu && np->rxopt.bits.rxpmtu) return ipv6_recv_rxpmtu(sk, msg, len); skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) goto out; copied = skb->len; if (copied > len) { copied = len; msg->msg_flags |= MSG_TRUNC; } if (skb_csum_unnecessary(skb)) { err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); } else if (msg->msg_flags&MSG_TRUNC) { if (__skb_checksum_complete(skb)) goto csum_copy_err; err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); } else { err = skb_copy_and_csum_datagram_iovec(skb, 0, msg->msg_iov); if (err == -EINVAL) goto csum_copy_err; } if (err) goto out_free; /* Copy the address. */ if (sin6) { sin6->sin6_family = AF_INET6; sin6->sin6_port = 0; sin6->sin6_addr = ipv6_hdr(skb)->saddr; sin6->sin6_flowinfo = 0; sin6->sin6_scope_id = ipv6_iface_scope_id(&sin6->sin6_addr, IP6CB(skb)->iif); } sock_recv_ts_and_drops(msg, sk, skb); if (np->rxopt.all) ip6_datagram_recv_ctl(sk, msg, skb); err = copied; if (flags & MSG_TRUNC) err = skb->len; out_free: skb_free_datagram(sk, skb); out: return err; csum_copy_err: skb_kill_datagram(sk, skb, flags); /* Error for blocking case is chosen to masquerade as some normal condition. */ err = (flags&MSG_DONTWAIT) ? -EAGAIN : -EHOSTUNREACH; goto out; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'inet: prevent leakage of uninitialized memory to user in recv syscalls Only update *addr_len when we actually fill in sockaddr, otherwise we can return uninitialized memory from the stack to the caller in the recvfrom, recvmmsg and recvmsg syscalls. Drop the the (addr_len == NULL) checks because we only get called with a valid addr_len pointer either from sock_common_recvmsg or inet_recvmsg. If a blocking read waits on a socket which is concurrently shut down we now return zero and set msg_msgnamelen to 0. Reported-by: mpb <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int udp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct inet_sock *inet = inet_sk(sk); struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name; struct sk_buff *skb; unsigned int ulen, copied; int peeked, off = 0; int err; int is_udplite = IS_UDPLITE(sk); bool slow; /* * Check any passed addresses */ if (addr_len) *addr_len = sizeof(*sin); if (flags & MSG_ERRQUEUE) return ip_recv_error(sk, msg, len); try_again: skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0), &peeked, &off, &err); if (!skb) goto out; ulen = skb->len - sizeof(struct udphdr); copied = len; if (copied > ulen) copied = ulen; else if (copied < ulen) msg->msg_flags |= MSG_TRUNC; /* * If checksum is needed at all, try to do it while copying the * data. If the data is truncated, or if we only want a partial * coverage checksum (UDP-Lite), do it before the copy. */ if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) { if (udp_lib_checksum_complete(skb)) goto csum_copy_err; } if (skb_csum_unnecessary(skb)) err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov, copied); else { err = skb_copy_and_csum_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov); if (err == -EINVAL) goto csum_copy_err; } if (unlikely(err)) { trace_kfree_skb(skb, udp_recvmsg); if (!peeked) { atomic_inc(&sk->sk_drops); UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } goto out_free; } if (!peeked) UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INDATAGRAMS, is_udplite); sock_recv_ts_and_drops(msg, sk, skb); /* Copy the address. */ if (sin) { sin->sin_family = AF_INET; sin->sin_port = udp_hdr(skb)->source; sin->sin_addr.s_addr = ip_hdr(skb)->saddr; memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); } if (inet->cmsg_flags) ip_cmsg_recv(msg, skb); err = copied; if (flags & MSG_TRUNC) err = ulen; out_free: skb_free_datagram_locked(sk, skb); out: return err; csum_copy_err: slow = lock_sock_fast(sk); if (!skb_kill_datagram(sk, skb, flags)) { UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite); UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } unlock_sock_fast(sk, slow); if (noblock) return -EAGAIN; /* starting over for a new packet */ msg->msg_flags &= ~MSG_TRUNC; goto try_again; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'inet: prevent leakage of uninitialized memory to user in recv syscalls Only update *addr_len when we actually fill in sockaddr, otherwise we can return uninitialized memory from the stack to the caller in the recvfrom, recvmmsg and recvmsg syscalls. Drop the the (addr_len == NULL) checks because we only get called with a valid addr_len pointer either from sock_common_recvmsg or inet_recvmsg. If a blocking read waits on a socket which is concurrently shut down we now return zero and set msg_msgnamelen to 0. Reported-by: mpb <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int l2tp_ip_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct inet_sock *inet = inet_sk(sk); size_t copied = 0; int err = -EOPNOTSUPP; struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name; struct sk_buff *skb; if (flags & MSG_OOB) goto out; if (addr_len) *addr_len = sizeof(*sin); skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) goto out; copied = skb->len; if (len < copied) { msg->msg_flags |= MSG_TRUNC; copied = len; } err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto done; sock_recv_timestamp(msg, sk, skb); /* Copy the address. */ if (sin) { sin->sin_family = AF_INET; sin->sin_addr.s_addr = ip_hdr(skb)->saddr; sin->sin_port = 0; memset(&sin->sin_zero, 0, sizeof(sin->sin_zero)); } if (inet->cmsg_flags) ip_cmsg_recv(msg, skb); if (flags & MSG_TRUNC) copied = skb->len; done: skb_free_datagram(sk, skb); out: return err ? err : copied; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'inet: prevent leakage of uninitialized memory to user in recv syscalls Only update *addr_len when we actually fill in sockaddr, otherwise we can return uninitialized memory from the stack to the caller in the recvfrom, recvmmsg and recvmsg syscalls. Drop the the (addr_len == NULL) checks because we only get called with a valid addr_len pointer either from sock_common_recvmsg or inet_recvmsg. If a blocking read waits on a socket which is concurrently shut down we now return zero and set msg_msgnamelen to 0. Reported-by: mpb <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int udpv6_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct ipv6_pinfo *np = inet6_sk(sk); struct inet_sock *inet = inet_sk(sk); struct sk_buff *skb; unsigned int ulen, copied; int peeked, off = 0; int err; int is_udplite = IS_UDPLITE(sk); int is_udp4; bool slow; if (flags & MSG_ERRQUEUE) return ipv6_recv_error(sk, msg, len); if (np->rxpmtu && np->rxopt.bits.rxpmtu) return ipv6_recv_rxpmtu(sk, msg, len); try_again: skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0), &peeked, &off, &err); if (!skb) goto out; ulen = skb->len - sizeof(struct udphdr); copied = len; if (copied > ulen) copied = ulen; else if (copied < ulen) msg->msg_flags |= MSG_TRUNC; is_udp4 = (skb->protocol == htons(ETH_P_IP)); /* * If checksum is needed at all, try to do it while copying the * data. If the data is truncated, or if we only want a partial * coverage checksum (UDP-Lite), do it before the copy. */ if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) { if (udp_lib_checksum_complete(skb)) goto csum_copy_err; } if (skb_csum_unnecessary(skb)) err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov, copied); else { err = skb_copy_and_csum_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov); if (err == -EINVAL) goto csum_copy_err; } if (unlikely(err)) { trace_kfree_skb(skb, udpv6_recvmsg); if (!peeked) { atomic_inc(&sk->sk_drops); if (is_udp4) UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); else UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } goto out_free; } if (!peeked) { if (is_udp4) UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INDATAGRAMS, is_udplite); else UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_INDATAGRAMS, is_udplite); } sock_recv_ts_and_drops(msg, sk, skb); /* Copy the address. */ if (msg->msg_name) { struct sockaddr_in6 *sin6; sin6 = (struct sockaddr_in6 *) msg->msg_name; sin6->sin6_family = AF_INET6; sin6->sin6_port = udp_hdr(skb)->source; sin6->sin6_flowinfo = 0; if (is_udp4) { ipv6_addr_set_v4mapped(ip_hdr(skb)->saddr, &sin6->sin6_addr); sin6->sin6_scope_id = 0; } else { sin6->sin6_addr = ipv6_hdr(skb)->saddr; sin6->sin6_scope_id = ipv6_iface_scope_id(&sin6->sin6_addr, IP6CB(skb)->iif); } *addr_len = sizeof(*sin6); } if (is_udp4) { if (inet->cmsg_flags) ip_cmsg_recv(msg, skb); } else { if (np->rxopt.all) ip6_datagram_recv_ctl(sk, msg, skb); } err = copied; if (flags & MSG_TRUNC) err = ulen; out_free: skb_free_datagram_locked(sk, skb); out: return err; csum_copy_err: slow = lock_sock_fast(sk); if (!skb_kill_datagram(sk, skb, flags)) { if (is_udp4) { UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite); UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } else { UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite); UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } } unlock_sock_fast(sk, slow); if (noblock) return -EAGAIN; /* starting over for a new packet */ msg->msg_flags &= ~MSG_TRUNC; goto try_again; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'inet: fix addr_len/msg->msg_namelen assignment in recv_error and rxpmtu functions Commit bceaa90240b6019ed73b49965eac7d167610be69 ("inet: prevent leakage of uninitialized memory to user in recv syscalls") conditionally updated addr_len if the msg_name is written to. The recv_error and rxpmtu functions relied on the recvmsg functions to set up addr_len before. As this does not happen any more we have to pass addr_len to those functions as well and set it to the size of the corresponding sockaddr length. This broke traceroute and such. Fixes: bceaa90240b6 ("inet: prevent leakage of uninitialized memory to user in recv syscalls") Reported-by: Brad Spengler <[email protected]> Reported-by: Tom Labanowski Cc: mpb <[email protected]> Cc: David S. Miller <[email protected]> Cc: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ipv6_recv_rxpmtu(struct sock *sk, struct msghdr *msg, int len) { struct ipv6_pinfo *np = inet6_sk(sk); struct sk_buff *skb; struct sockaddr_in6 *sin; struct ip6_mtuinfo mtu_info; int err; int copied; err = -EAGAIN; skb = xchg(&np->rxpmtu, NULL); if (skb == NULL) goto out; copied = skb->len; if (copied > len) { msg->msg_flags |= MSG_TRUNC; copied = len; } err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto out_free_skb; sock_recv_timestamp(msg, sk, skb); memcpy(&mtu_info, IP6CBMTU(skb), sizeof(mtu_info)); sin = (struct sockaddr_in6 *)msg->msg_name; if (sin) { sin->sin6_family = AF_INET6; sin->sin6_flowinfo = 0; sin->sin6_port = 0; sin->sin6_scope_id = mtu_info.ip6m_addr.sin6_scope_id; sin->sin6_addr = mtu_info.ip6m_addr.sin6_addr; } put_cmsg(msg, SOL_IPV6, IPV6_PATHMTU, sizeof(mtu_info), &mtu_info); err = copied; out_free_skb: kfree_skb(skb); out: return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'inet: fix addr_len/msg->msg_namelen assignment in recv_error and rxpmtu functions Commit bceaa90240b6019ed73b49965eac7d167610be69 ("inet: prevent leakage of uninitialized memory to user in recv syscalls") conditionally updated addr_len if the msg_name is written to. The recv_error and rxpmtu functions relied on the recvmsg functions to set up addr_len before. As this does not happen any more we have to pass addr_len to those functions as well and set it to the size of the corresponding sockaddr length. This broke traceroute and such. Fixes: bceaa90240b6 ("inet: prevent leakage of uninitialized memory to user in recv syscalls") Reported-by: Brad Spengler <[email protected]> Reported-by: Tom Labanowski Cc: mpb <[email protected]> Cc: David S. Miller <[email protected]> Cc: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int l2tp_ip6_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct ipv6_pinfo *np = inet6_sk(sk); struct sockaddr_l2tpip6 *lsa = (struct sockaddr_l2tpip6 *)msg->msg_name; size_t copied = 0; int err = -EOPNOTSUPP; struct sk_buff *skb; if (flags & MSG_OOB) goto out; if (addr_len) *addr_len = sizeof(*lsa); if (flags & MSG_ERRQUEUE) return ipv6_recv_error(sk, msg, len); skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) goto out; copied = skb->len; if (len < copied) { msg->msg_flags |= MSG_TRUNC; copied = len; } err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto done; sock_recv_timestamp(msg, sk, skb); /* Copy the address. */ if (lsa) { lsa->l2tp_family = AF_INET6; lsa->l2tp_unused = 0; lsa->l2tp_addr = ipv6_hdr(skb)->saddr; lsa->l2tp_flowinfo = 0; lsa->l2tp_scope_id = 0; lsa->l2tp_conn_id = 0; if (ipv6_addr_type(&lsa->l2tp_addr) & IPV6_ADDR_LINKLOCAL) lsa->l2tp_scope_id = IP6CB(skb)->iif; } if (np->rxopt.all) ip6_datagram_recv_ctl(sk, msg, skb); if (flags & MSG_TRUNC) copied = skb->len; done: skb_free_datagram(sk, skb); out: return err ? err : copied; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'inet: fix addr_len/msg->msg_namelen assignment in recv_error and rxpmtu functions Commit bceaa90240b6019ed73b49965eac7d167610be69 ("inet: prevent leakage of uninitialized memory to user in recv syscalls") conditionally updated addr_len if the msg_name is written to. The recv_error and rxpmtu functions relied on the recvmsg functions to set up addr_len before. As this does not happen any more we have to pass addr_len to those functions as well and set it to the size of the corresponding sockaddr length. This broke traceroute and such. Fixes: bceaa90240b6 ("inet: prevent leakage of uninitialized memory to user in recv syscalls") Reported-by: Brad Spengler <[email protected]> Reported-by: Tom Labanowski Cc: mpb <[email protected]> Cc: David S. Miller <[email protected]> Cc: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ipv6_recv_error(struct sock *sk, struct msghdr *msg, int len) { struct ipv6_pinfo *np = inet6_sk(sk); struct sock_exterr_skb *serr; struct sk_buff *skb, *skb2; struct sockaddr_in6 *sin; struct { struct sock_extended_err ee; struct sockaddr_in6 offender; } errhdr; int err; int copied; err = -EAGAIN; skb = skb_dequeue(&sk->sk_error_queue); if (skb == NULL) goto out; copied = skb->len; if (copied > len) { msg->msg_flags |= MSG_TRUNC; copied = len; } err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto out_free_skb; sock_recv_timestamp(msg, sk, skb); serr = SKB_EXT_ERR(skb); sin = (struct sockaddr_in6 *)msg->msg_name; if (sin) { const unsigned char *nh = skb_network_header(skb); sin->sin6_family = AF_INET6; sin->sin6_flowinfo = 0; sin->sin6_port = serr->port; if (skb->protocol == htons(ETH_P_IPV6)) { const struct ipv6hdr *ip6h = container_of((struct in6_addr *)(nh + serr->addr_offset), struct ipv6hdr, daddr); sin->sin6_addr = ip6h->daddr; if (np->sndflow) sin->sin6_flowinfo = ip6_flowinfo(ip6h); sin->sin6_scope_id = ipv6_iface_scope_id(&sin->sin6_addr, IP6CB(skb)->iif); } else { ipv6_addr_set_v4mapped(*(__be32 *)(nh + serr->addr_offset), &sin->sin6_addr); sin->sin6_scope_id = 0; } } memcpy(&errhdr.ee, &serr->ee, sizeof(struct sock_extended_err)); sin = &errhdr.offender; sin->sin6_family = AF_UNSPEC; if (serr->ee.ee_origin != SO_EE_ORIGIN_LOCAL) { sin->sin6_family = AF_INET6; sin->sin6_flowinfo = 0; if (skb->protocol == htons(ETH_P_IPV6)) { sin->sin6_addr = ipv6_hdr(skb)->saddr; if (np->rxopt.all) ip6_datagram_recv_ctl(sk, msg, skb); sin->sin6_scope_id = ipv6_iface_scope_id(&sin->sin6_addr, IP6CB(skb)->iif); } else { struct inet_sock *inet = inet_sk(sk); ipv6_addr_set_v4mapped(ip_hdr(skb)->saddr, &sin->sin6_addr); sin->sin6_scope_id = 0; if (inet->cmsg_flags) ip_cmsg_recv(msg, skb); } } put_cmsg(msg, SOL_IPV6, IPV6_RECVERR, sizeof(errhdr), &errhdr); /* Now we could try to dump offended packet options */ msg->msg_flags |= MSG_ERRQUEUE; err = copied; /* Reset and regenerate socket error */ spin_lock_bh(&sk->sk_error_queue.lock); sk->sk_err = 0; if ((skb2 = skb_peek(&sk->sk_error_queue)) != NULL) { sk->sk_err = SKB_EXT_ERR(skb2)->ee.ee_errno; spin_unlock_bh(&sk->sk_error_queue.lock); sk->sk_error_report(sk); } else { spin_unlock_bh(&sk->sk_error_queue.lock); } out_free_skb: kfree_skb(skb); out: return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'inet: fix addr_len/msg->msg_namelen assignment in recv_error and rxpmtu functions Commit bceaa90240b6019ed73b49965eac7d167610be69 ("inet: prevent leakage of uninitialized memory to user in recv syscalls") conditionally updated addr_len if the msg_name is written to. The recv_error and rxpmtu functions relied on the recvmsg functions to set up addr_len before. As this does not happen any more we have to pass addr_len to those functions as well and set it to the size of the corresponding sockaddr length. This broke traceroute and such. Fixes: bceaa90240b6 ("inet: prevent leakage of uninitialized memory to user in recv syscalls") Reported-by: Brad Spengler <[email protected]> Reported-by: Tom Labanowski Cc: mpb <[email protected]> Cc: David S. Miller <[email protected]> Cc: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int udp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct inet_sock *inet = inet_sk(sk); struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name; struct sk_buff *skb; unsigned int ulen, copied; int peeked, off = 0; int err; int is_udplite = IS_UDPLITE(sk); bool slow; if (flags & MSG_ERRQUEUE) return ip_recv_error(sk, msg, len); try_again: skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0), &peeked, &off, &err); if (!skb) goto out; ulen = skb->len - sizeof(struct udphdr); copied = len; if (copied > ulen) copied = ulen; else if (copied < ulen) msg->msg_flags |= MSG_TRUNC; /* * If checksum is needed at all, try to do it while copying the * data. If the data is truncated, or if we only want a partial * coverage checksum (UDP-Lite), do it before the copy. */ if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) { if (udp_lib_checksum_complete(skb)) goto csum_copy_err; } if (skb_csum_unnecessary(skb)) err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov, copied); else { err = skb_copy_and_csum_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov); if (err == -EINVAL) goto csum_copy_err; } if (unlikely(err)) { trace_kfree_skb(skb, udp_recvmsg); if (!peeked) { atomic_inc(&sk->sk_drops); UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } goto out_free; } if (!peeked) UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INDATAGRAMS, is_udplite); sock_recv_ts_and_drops(msg, sk, skb); /* Copy the address. */ if (sin) { sin->sin_family = AF_INET; sin->sin_port = udp_hdr(skb)->source; sin->sin_addr.s_addr = ip_hdr(skb)->saddr; memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); *addr_len = sizeof(*sin); } if (inet->cmsg_flags) ip_cmsg_recv(msg, skb); err = copied; if (flags & MSG_TRUNC) err = ulen; out_free: skb_free_datagram_locked(sk, skb); out: return err; csum_copy_err: slow = lock_sock_fast(sk); if (!skb_kill_datagram(sk, skb, flags)) { UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite); UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } unlock_sock_fast(sk, slow); if (noblock) return -EAGAIN; /* starting over for a new packet */ msg->msg_flags &= ~MSG_TRUNC; goto try_again; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'inet: fix addr_len/msg->msg_namelen assignment in recv_error and rxpmtu functions Commit bceaa90240b6019ed73b49965eac7d167610be69 ("inet: prevent leakage of uninitialized memory to user in recv syscalls") conditionally updated addr_len if the msg_name is written to. The recv_error and rxpmtu functions relied on the recvmsg functions to set up addr_len before. As this does not happen any more we have to pass addr_len to those functions as well and set it to the size of the corresponding sockaddr length. This broke traceroute and such. Fixes: bceaa90240b6 ("inet: prevent leakage of uninitialized memory to user in recv syscalls") Reported-by: Brad Spengler <[email protected]> Reported-by: Tom Labanowski Cc: mpb <[email protected]> Cc: David S. Miller <[email protected]> Cc: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static time_t asn1_time_to_time_t(ASN1_UTCTIME * timestr TSRMLS_DC) /* {{{ */ { /* This is how the time string is formatted: snprintf(p, sizeof(p), "%02d%02d%02d%02d%02d%02dZ",ts->tm_year%100, ts->tm_mon+1,ts->tm_mday,ts->tm_hour,ts->tm_min,ts->tm_sec); */ time_t ret; struct tm thetime; char * strbuf; char * thestr; long gmadjust = 0; if (timestr->length < 13) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "extension author too lazy to parse %s correctly", timestr->data); return (time_t)-1; } strbuf = estrdup((char *)timestr->data); memset(&thetime, 0, sizeof(thetime)); /* we work backwards so that we can use atoi more easily */ thestr = strbuf + timestr->length - 3; thetime.tm_sec = atoi(thestr); *thestr = '\0'; thestr -= 2; thetime.tm_min = atoi(thestr); *thestr = '\0'; thestr -= 2; thetime.tm_hour = atoi(thestr); *thestr = '\0'; thestr -= 2; thetime.tm_mday = atoi(thestr); *thestr = '\0'; thestr -= 2; thetime.tm_mon = atoi(thestr)-1; *thestr = '\0'; thestr -= 2; thetime.tm_year = atoi(thestr); if (thetime.tm_year < 68) { thetime.tm_year += 100; } thetime.tm_isdst = -1; ret = mktime(&thetime); #if HAVE_TM_GMTOFF gmadjust = thetime.tm_gmtoff; #else /* ** If correcting for daylight savings time, we set the adjustment to ** the value of timezone - 3600 seconds. Otherwise, we need to overcorrect and ** set the adjustment to the main timezone + 3600 seconds. */ gmadjust = -(thetime.tm_isdst ? (long)timezone - 3600 : (long)timezone + 3600); #endif ret += gmadjust; efree(strbuf); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix CVE-2013-6420 - memory corruption in openssl_x509_parse'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: conn *conn_new(const int sfd, enum conn_states init_state, const int event_flags, const int read_buffer_size, enum network_transport transport, struct event_base *base) { conn *c = conn_from_freelist(); if (NULL == c) { if (!(c = (conn *)calloc(1, sizeof(conn)))) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); fprintf(stderr, "Failed to allocate connection object\n"); return NULL; } MEMCACHED_CONN_CREATE(c); c->rbuf = c->wbuf = 0; c->ilist = 0; c->suffixlist = 0; c->iov = 0; c->msglist = 0; c->hdrbuf = 0; c->rsize = read_buffer_size; c->wsize = DATA_BUFFER_SIZE; c->isize = ITEM_LIST_INITIAL; c->suffixsize = SUFFIX_LIST_INITIAL; c->iovsize = IOV_LIST_INITIAL; c->msgsize = MSG_LIST_INITIAL; c->hdrsize = 0; c->rbuf = (char *)malloc((size_t)c->rsize); c->wbuf = (char *)malloc((size_t)c->wsize); c->ilist = (item **)malloc(sizeof(item *) * c->isize); c->suffixlist = (char **)malloc(sizeof(char *) * c->suffixsize); c->iov = (struct iovec *)malloc(sizeof(struct iovec) * c->iovsize); c->msglist = (struct msghdr *)malloc(sizeof(struct msghdr) * c->msgsize); if (c->rbuf == 0 || c->wbuf == 0 || c->ilist == 0 || c->iov == 0 || c->msglist == 0 || c->suffixlist == 0) { conn_free(c); STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); fprintf(stderr, "Failed to allocate buffers for connection\n"); return NULL; } STATS_LOCK(); stats.conn_structs++; STATS_UNLOCK(); } c->transport = transport; c->protocol = settings.binding_protocol; /* unix socket mode doesn't need this, so zeroed out. but why * is this done for every command? presumably for UDP * mode. */ if (!settings.socketpath) { c->request_addr_size = sizeof(c->request_addr); } else { c->request_addr_size = 0; } if (settings.verbose > 1) { if (init_state == conn_listening) { fprintf(stderr, "<%d server listening (%s)\n", sfd, prot_text(c->protocol)); } else if (IS_UDP(transport)) { fprintf(stderr, "<%d server listening (udp)\n", sfd); } else if (c->protocol == negotiating_prot) { fprintf(stderr, "<%d new auto-negotiating client connection\n", sfd); } else if (c->protocol == ascii_prot) { fprintf(stderr, "<%d new ascii client connection.\n", sfd); } else if (c->protocol == binary_prot) { fprintf(stderr, "<%d new binary client connection.\n", sfd); } else { fprintf(stderr, "<%d new unknown (%d) client connection\n", sfd, c->protocol); assert(false); } } c->sfd = sfd; c->state = init_state; c->rlbytes = 0; c->cmd = -1; c->rbytes = c->wbytes = 0; c->wcurr = c->wbuf; c->rcurr = c->rbuf; c->ritem = 0; c->icurr = c->ilist; c->suffixcurr = c->suffixlist; c->ileft = 0; c->suffixleft = 0; c->iovused = 0; c->msgcurr = 0; c->msgused = 0; c->write_and_go = init_state; c->write_and_free = 0; c->item = 0; c->noreply = false; event_set(&c->event, sfd, event_flags, event_handler, (void *)c); event_base_set(base, &c->event); c->ev_flags = event_flags; if (event_add(&c->event, 0) == -1) { if (conn_add_to_freelist(c)) { conn_free(c); } perror("event_add"); return NULL; } STATS_LOCK(); stats.curr_conns++; stats.total_conns++; STATS_UNLOCK(); MEMCACHED_CONN_ALLOCATE(c->sfd); return c; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-287'], 'message': 'explicitly record sasl auth states It was previously possible to bypass authentication due to implicit state management. Now we explicitly consider ourselves unauthenticated on any new connections and authentication attempts. bug316 Signed-off-by: Dustin Sallings <[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 bool authenticated(conn *c) { assert(settings.sasl); bool rv = false; switch (c->cmd) { case PROTOCOL_BINARY_CMD_SASL_LIST_MECHS: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_SASL_AUTH: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_SASL_STEP: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_VERSION: /* FALLTHROUGH */ rv = true; break; default: if (c->sasl_conn) { const void *uname = NULL; sasl_getprop(c->sasl_conn, SASL_USERNAME, &uname); rv = uname != NULL; } } if (settings.verbose > 1) { fprintf(stderr, "authenticated() in cmd 0x%02x is %s\n", c->cmd, rv ? "true" : "false"); } return rv; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-287'], 'message': 'explicitly record sasl auth states It was previously possible to bypass authentication due to implicit state management. Now we explicitly consider ourselves unauthenticated on any new connections and authentication attempts. bug316 Signed-off-by: Dustin Sallings <[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 msPostGISLayerSetTimeFilter(layerObj *lp, const char *timestring, const char *timefield) { char **atimes, **aranges = NULL; int numtimes=0,i=0,numranges=0; size_t buffer_size = 512; char buffer[512], bufferTmp[512]; buffer[0] = '\0'; bufferTmp[0] = '\0'; if (!lp || !timestring || !timefield) return MS_FALSE; /* discrete time */ if (strstr(timestring, ",") == NULL && strstr(timestring, "/") == NULL) { /* discrete time */ createPostgresTimeCompareSimple(timefield, timestring, buffer, buffer_size); } else { /* multiple times, or ranges */ atimes = msStringSplit (timestring, ',', &numtimes); if (atimes == NULL || numtimes < 1) return MS_FALSE; strlcat(buffer, "(", buffer_size); for(i=0; i<numtimes; i++) { if(i!=0) { strlcat(buffer, " OR ", buffer_size); } strlcat(buffer, "(", buffer_size); aranges = msStringSplit(atimes[i], '/', &numranges); if(!aranges) return MS_FALSE; if(numranges == 1) { /* we don't have range, just a simple time */ createPostgresTimeCompareSimple(timefield, atimes[i], bufferTmp, buffer_size); strlcat(buffer, bufferTmp, buffer_size); } else if(numranges == 2) { /* we have a range */ createPostgresTimeCompareRange(timefield, aranges[0], aranges[1], bufferTmp, buffer_size); strlcat(buffer, bufferTmp, buffer_size); } else { return MS_FALSE; } msFreeCharArray(aranges, numranges); strlcat(buffer, ")", buffer_size); } strlcat(buffer, ")", buffer_size); msFreeCharArray(atimes, numtimes); } if(!*buffer) { return MS_FALSE; } if(lp->filteritem) free(lp->filteritem); lp->filteritem = msStrdup(timefield); if (&lp->filter) { /* if the filter is set and it's a string type, concatenate it with the time. If not just free it */ if (lp->filter.type == MS_EXPRESSION) { snprintf(bufferTmp, buffer_size, "(%s) and %s", lp->filter.string, buffer); loadExpressionString(&lp->filter, bufferTmp); } else { freeExpression(&lp->filter); loadExpressionString(&lp->filter, buffer); } } return MS_TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-89'], 'message': 'Fix potential SQL Injection with postgis TIME filters (#4834)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TEST(BSONValidate, MuckingData1) { BSONObj theObject; { BSONObjBuilder b; b.append( "name" , "eliot was here" ); b.append( "yippee" , "asd" ); BSONArrayBuilder a( b.subarrayStart( "arr" ) ); for ( int i=0; i<100; i++ ) { a.append( BSON( "x" << i << "who" << "me" << "asd" << "asd" ) ); } a.done(); b.done(); theObject = b.obj(); } int numValid = 0; int numToRun = 1000; long long jsonSize = 0; for ( int i=4; i<theObject.objsize()-1; i++ ) { BSONObj mine = theObject.copy(); char* data = const_cast<char*>(mine.objdata()); data[ i ] = 200; numToRun++; if ( mine.valid() ) { numValid++; jsonSize += mine.jsonString().size(); } } log() << "MuckingData1: didn't crash valid/total: " << numValid << "/" << numToRun << " (want few valid ones) " << " jsonSize: " << jsonSize << endl; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'SERVER-7769 - fast bson validate'</s>
<s>[INST] Given the following code containing errors, provide 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 CmdLine::addGlobalOptions( boost::program_options::options_description& general , boost::program_options::options_description& hidden , boost::program_options::options_description& ssl_options ) { /* support for -vv -vvvv etc. */ for (string s = "vv"; s.length() <= 12; s.append("v")) { hidden.add_options()(s.c_str(), "verbose"); } StringBuilder portInfoBuilder; StringBuilder maxConnInfoBuilder; portInfoBuilder << "specify port number - " << DefaultDBPort << " by default"; maxConnInfoBuilder << "max number of simultaneous connections - " << DEFAULT_MAX_CONN << " by default"; general.add_options() ("help,h", "show this usage information") ("version", "show version information") ("config,f", po::value<string>(), "configuration file specifying additional options") ("verbose,v", "be more verbose (include multiple times for more verbosity e.g. -vvvvv)") ("quiet", "quieter output") ("port", po::value<int>(&cmdLine.port), portInfoBuilder.str().c_str()) ("bind_ip", po::value<string>(&cmdLine.bind_ip), "comma separated list of ip addresses to listen on - all local ips by default") ("maxConns",po::value<int>(), maxConnInfoBuilder.str().c_str()) ("objcheck", "inspect client data for validity on receipt") ("logpath", po::value<string>() , "log file to send write to instead of stdout - has to be a file, not directory" ) ("logappend" , "append to logpath instead of over-writing" ) ("pidfilepath", po::value<string>(), "full path to pidfile (if not set, no pidfile is created)") ("keyFile", po::value<string>(), "private key for cluster authentication") ("setParameter", po::value< std::vector<std::string> >()->composing(), "Set a configurable parameter") #ifndef _WIN32 ("nounixsocket", "disable listening on unix sockets") ("unixSocketPrefix", po::value<string>(), "alternative directory for UNIX domain sockets (defaults to /tmp)") ("fork" , "fork server process" ) ("syslog" , "log to system's syslog facility instead of file or stdout" ) #endif ; #ifdef MONGO_SSL ssl_options.add_options() ("sslOnNormalPorts" , "use ssl on configured ports" ) ("sslPEMKeyFile" , po::value<string>(&cmdLine.sslPEMKeyFile), "PEM file for ssl" ) ("sslPEMKeyPassword" , new PasswordValue(&cmdLine.sslPEMKeyPassword) , "PEM file password" ) ("sslCAFile", po::value<std::string>(&cmdLine.sslCAFile), "Certificate Authority file for SSL") ("sslCRLFile", po::value<std::string>(&cmdLine.sslCRLFile), "Certificate Revocation List file for SSL") ("sslForceCertificateValidation", "require each client to present a valid certificate") #endif ; // Extra hidden options hidden.add_options() ("traceExceptions", "log stack traces for every exception") ("enableExperimentalIndexStatsCmd", po::bool_switch(&cmdLine.experimental.indexStatsCmdEnabled), "EXPERIMENTAL (UNSUPPORTED). Enable command computing aggregate statistics on indexes.") ("enableExperimentalStorageDetailsCmd", po::bool_switch(&cmdLine.experimental.storageDetailsCmdEnabled), "EXPERIMENTAL (UNSUPPORTED). Enable command computing aggregate statistics on storage.") ; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'SERVER-7769 - turn objcheck on by default and use new fast bson validate'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: inline CmdLine::CmdLine() : port(DefaultDBPort), rest(false), jsonp(false), indexBuildRetry(true), quiet(false), noTableScan(false), prealloc(true), preallocj(true), smallfiles(sizeof(int*) == 4), configsvr(false), quota(false), quotaFiles(8), cpu(false), durOptions(0), objcheck(false), oplogSize(0), defaultProfile(0), slowMS(100), defaultLocalThresholdMillis(15), pretouch(0), moveParanoia( true ), syncdelay(60), noUnixSocket(false), doFork(0), socket("/tmp"), maxConns(DEFAULT_MAX_CONN), logAppend(false), logWithSyslog(false) { started = time(0); journalCommitInterval = 0; // 0 means use default dur = false; #if defined(_DURABLEDEFAULTON) dur = true; #endif if( sizeof(void*) == 8 ) dur = true; #if defined(_DURABLEDEFAULTOFF) dur = false; #endif #ifdef MONGO_SSL sslOnNormalPorts = false; #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'SERVER-7769 - turn objcheck on by default and use new fast bson validate'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: BSONTool::BSONTool( const char * name, DBAccess access , bool objcheck ) : Tool( name , access , "" , "" , false ) , _objcheck( objcheck ) { add_options() ("objcheck" , "validate object before inserting" ) ("filter" , po::value<string>() , "filter to apply before inserting" ) ; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'SERVER-7769 - turn objcheck on by default and use new fast bson validate'</s>
<s>[INST] Given the following code containing errors, provide 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 BSONTool::run() { _objcheck = hasParam( "objcheck" ); if ( hasParam( "filter" ) ) _matcher.reset( new Matcher( fromjson( getParam( "filter" ) ) ) ); return doRun(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'SERVER-7769 - turn objcheck on by default and use new fast bson validate'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: item *do_item_get(const char *key, const size_t nkey, const uint32_t hv) { //mutex_lock(&cache_lock); item *it = assoc_find(key, nkey, hv); if (it != NULL) { refcount_incr(&it->refcount); /* Optimization for slab reassignment. prevents popular items from * jamming in busy wait. Can only do this here to satisfy lock order * of item_lock, cache_lock, slabs_lock. */ if (slab_rebalance_signal && ((void *)it >= slab_rebal.slab_start && (void *)it < slab_rebal.slab_end)) { do_item_unlink_nolock(it, hv); do_item_remove(it); it = NULL; } } //mutex_unlock(&cache_lock); int was_found = 0; if (settings.verbose > 2) { if (it == NULL) { fprintf(stderr, "> NOT FOUND %s", key); } else { fprintf(stderr, "> FOUND KEY %s", ITEM_key(it)); was_found++; } } if (it != NULL) { if (settings.oldest_live != 0 && settings.oldest_live <= current_time && it->time <= settings.oldest_live) { do_item_unlink(it, hv); do_item_remove(it); it = NULL; if (was_found) { fprintf(stderr, " -nuked by flush"); } } else if (it->exptime != 0 && it->exptime <= current_time) { do_item_unlink(it, hv); do_item_remove(it); it = NULL; if (was_found) { fprintf(stderr, " -nuked by expire"); } } else { it->it_flags |= ITEM_FETCHED; DEBUG_REFCNT(it, '+'); } } if (settings.verbose > 2) fprintf(stderr, "\n"); return it; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'fix potential unbounded key prints item key isn't necessarily null terminated. user submitted a patch for one, this clears two more.'</s>
<s>[INST] Given the following code containing errors, provide 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 ikev2_parent_inI1outR1_continue(struct pluto_crypto_req_cont *pcrc, struct pluto_crypto_req *r, err_t ugh) { struct ke_continuation *ke = (struct ke_continuation *)pcrc; struct msg_digest *md = ke->md; struct state *const st = md->st; stf_status e; DBG(DBG_CONTROLMORE, DBG_log("ikev2 parent inI1outR1: calculated ke+nonce, sending R1")); if (st == NULL) { loglog(RC_LOG_SERIOUS, "%s: Request was disconnected from state", __FUNCTION__); if (ke->md) release_md(ke->md); return; } /* XXX should check out ugh */ passert(ugh == NULL); passert(cur_state == NULL); passert(st != NULL); passert(st->st_suspended_md == ke->md); set_suspended(st, NULL); /* no longer connected or suspended */ set_cur_state(st); st->st_calculating = FALSE; e = ikev2_parent_inI1outR1_tail(pcrc, r); if (ke->md != NULL) { complete_v2_state_transition(&ke->md, e); if (ke->md) release_md(ke->md); } reset_globals(); passert(GLOBALS_ARE_RESET()); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'SECURITY: Properly handle IKEv2 I1 notification packet without KE payload'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: stf_status ikev2parent_inI1outR1(struct msg_digest *md) { struct state *st = md->st; lset_t policy = POLICY_IKEV2_ALLOW; struct connection *c = find_host_connection(&md->iface->ip_addr, md->iface->port, &md->sender, md->sender_port, POLICY_IKEV2_ALLOW); /* retrieve st->st_gi */ #if 0 if (c == NULL) { /* * make up a policy from the thing that was proposed, and see * if we can find a connection with that policy. */ pb_stream pre_sa_pbs = sa_pd->pbs; policy = preparse_isakmp_sa_body(&pre_sa_pbs); c = find_host_connection(&md->iface->ip_addr, pluto_port, (ip_address*)NULL, md->sender_port, policy); } #endif if (c == NULL) { /* See if a wildcarded connection can be found. * We cannot pick the right connection, so we're making a guess. * All Road Warrior connections are fair game: * we pick the first we come across (if any). * If we don't find any, we pick the first opportunistic * with the smallest subnet that includes the peer. * There is, of course, no necessary relationship between * an Initiator's address and that of its client, * but Food Groups kind of assumes one. */ { struct connection *d; d = find_host_connection(&md->iface->ip_addr, pluto_port, (ip_address*)NULL, md->sender_port, policy); for (; d != NULL; d = d->hp_next) { if (d->kind == CK_GROUP) { /* ignore */ } else { if (d->kind == CK_TEMPLATE && !(d->policy & POLICY_OPPO)) { /* must be Road Warrior: we have a winner */ c = d; break; } /* Opportunistic or Shunt: pick tightest match */ if (addrinsubnet(&md->sender, &d->spd.that.client) && (c == NULL || !subnetinsubnet(&c->spd.that. client, &d->spd.that. client))) c = d; } } } if (c == NULL) { loglog(RC_LOG_SERIOUS, "initial parent SA message received on %s:%u" " but no connection has been authorized%s%s", ip_str( &md->iface->ip_addr), ntohs(portof(&md->iface->ip_addr)), (policy != LEMPTY) ? " with policy=" : "", (policy != LEMPTY) ? bitnamesof(sa_policy_bit_names, policy) : ""); return STF_FAIL + v2N_NO_PROPOSAL_CHOSEN; } if (c->kind != CK_TEMPLATE) { loglog(RC_LOG_SERIOUS, "initial parent SA message received on %s:%u" " but \"%s\" forbids connection", ip_str( &md->iface->ip_addr), pluto_port, c->name); return STF_FAIL + v2N_NO_PROPOSAL_CHOSEN; } c = rw_instantiate(c, &md->sender, NULL, NULL); } else { /* we found a non-wildcard conn. double check if it needs instantiation anyway (eg vnet=) */ /* vnet=/vhost= should have set CK_TEMPLATE on connection loading */ if ((c->kind == CK_TEMPLATE) && c->spd.that.virt) { DBG(DBG_CONTROL, DBG_log( "local endpoint has virt (vnet/vhost) set without wildcards - needs instantiation")); c = rw_instantiate(c, &md->sender, NULL, NULL); } else if ((c->kind == CK_TEMPLATE) && (c->policy & POLICY_IKEV2_ALLOW_NARROWING)) { DBG(DBG_CONTROL, DBG_log( "local endpoint has narrowing=yes - needs instantiation")); c = rw_instantiate(c, &md->sender, NULL, NULL); } } DBG_log("found connection: %s\n", c ? c->name : "<none>"); if (!st) { st = new_state(); /* set up new state */ memcpy(st->st_icookie, md->hdr.isa_icookie, COOKIE_SIZE); /* initialize_new_state expects valid icookie/rcookie values, so create it now */ get_cookie(FALSE, st->st_rcookie, COOKIE_SIZE, &md->sender); initialize_new_state(st, c, policy, 0, NULL_FD, pcim_stranger_crypto); st->st_ikev2 = TRUE; change_state(st, STATE_PARENT_R1); st->st_msgid_lastack = INVALID_MSGID; st->st_msgid_nextuse = 0; md->st = st; md->from_state = STATE_IKEv2_BASE; } /* check,as a responder, are we under dos attack or not * if yes go to 6 message exchange mode. it is a config option for now. * TBD set force_busy dynamically * Paul: Can we check for STF_TOOMUCHCRYPTO ? */ if (force_busy == TRUE) { u_char dcookie[SHA1_DIGEST_SIZE]; chunk_t dc; ikev2_get_dcookie( dcookie, st->st_ni, &md->sender, st->st_icookie); dc.ptr = dcookie; dc.len = SHA1_DIGEST_SIZE; /* check if I1 packet contian KE and a v2N payload with type COOKIE */ if ( md->chain[ISAKMP_NEXT_v2KE] && md->chain[ISAKMP_NEXT_v2N] && (md->chain[ISAKMP_NEXT_v2N]->payload.v2n.isan_type == v2N_COOKIE)) { u_int8_t spisize; const pb_stream *dc_pbs; chunk_t blob; DBG(DBG_CONTROLMORE, DBG_log("received a DOS cookie in I1 verify it")); /* we received dcookie we send earlier verify it */ spisize = md->chain[ISAKMP_NEXT_v2N]->payload.v2n. isan_spisize; dc_pbs = &md->chain[ISAKMP_NEXT_v2N]->pbs; blob.ptr = dc_pbs->cur + spisize; blob.len = pbs_left(dc_pbs) - spisize; DBG(DBG_CONTROLMORE, DBG_dump_chunk("dcookie received in I1 Packet", blob); DBG_dump("dcookie computed", dcookie, SHA1_DIGEST_SIZE)); if (memcmp(blob.ptr, dcookie, SHA1_DIGEST_SIZE) != 0) { libreswan_log( "mismatch in DOS v2N_COOKIE,send a new one"); SEND_NOTIFICATION_AA(v2N_COOKIE, &dc); return STF_FAIL + v2N_INVALID_IKE_SPI; } DBG(DBG_CONTROLMORE, DBG_log("dcookie received match with computed one")); } else { /* we are under DOS attack I1 contains no DOS COOKIE */ DBG(DBG_CONTROLMORE, DBG_log( "busy mode on. receieved I1 without a valid dcookie"); DBG_log("send a dcookie and forget this state")); SEND_NOTIFICATION_AA(v2N_COOKIE, &dc); return STF_FAIL; } } else { DBG(DBG_CONTROLMORE, DBG_log("will not send/process a dcookie")); } /* * We have to agree to the DH group before we actually know who * we are talking to. If we support the group, we use it. * * It is really too hard here to go through all the possible policies * that might permit this group. If we think we are being DOS'ed * then we should demand a cookie. */ { struct ikev2_ke *ke; ke = &md->chain[ISAKMP_NEXT_v2KE]->payload.v2ke; st->st_oakley.group = lookup_group(ke->isak_group); if (st->st_oakley.group == NULL) { char fromname[ADDRTOT_BUF]; addrtot(&md->sender, 0, fromname, ADDRTOT_BUF); libreswan_log( "rejecting I1 from %s:%u, invalid DH group=%u", fromname, md->sender_port, ke->isak_group); return v2N_INVALID_KE_PAYLOAD; } } /* now. we need to go calculate the nonce, and the KE */ { struct ke_continuation *ke = alloc_thing( struct ke_continuation, "ikev2_inI1outR1 KE"); stf_status e; ke->md = md; set_suspended(st, ke->md); if (!st->st_sec_in_use) { pcrc_init(&ke->ke_pcrc); ke->ke_pcrc.pcrc_func = ikev2_parent_inI1outR1_continue; e = build_ke(&ke->ke_pcrc, st, st->st_oakley.group, pcim_stranger_crypto); if (e != STF_SUSPEND && e != STF_INLINE) { loglog(RC_CRYPTOFAILED, "system too busy"); delete_state(st); } } else { e = ikev2_parent_inI1outR1_tail((struct pluto_crypto_req_cont *)ke, NULL); } reset_globals(); return e; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'SECURITY: Properly handle IKEv2 I1 notification packet without KE payload'</s>
<s>[INST] Given the following code containing errors, provide 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 ikev2_parent_outI1_continue(struct pluto_crypto_req_cont *pcrc, struct pluto_crypto_req *r, err_t ugh) { struct ke_continuation *ke = (struct ke_continuation *)pcrc; struct msg_digest *md = ke->md; struct state *const st = md->st; stf_status e; DBG(DBG_CONTROLMORE, DBG_log("ikev2 parent outI1: calculated ke+nonce, sending I1")); if (st == NULL) { loglog(RC_LOG_SERIOUS, "%s: Request was disconnected from state", __FUNCTION__); if (ke->md) release_md(ke->md); return; } /* XXX should check out ugh */ passert(ugh == NULL); passert(cur_state == NULL); passert(st != NULL); passert(st->st_suspended_md == ke->md); set_suspended(st, NULL); /* no longer connected or suspended */ set_cur_state(st); st->st_calculating = FALSE; e = ikev2_parent_outI1_tail(pcrc, r); if (ke->md != NULL) { complete_v2_state_transition(&ke->md, e); if (ke->md) release_md(ke->md); } reset_cur_state(); reset_globals(); passert(GLOBALS_ARE_RESET()); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'SECURITY: Properly handle IKEv2 I1 notification packet without KE payload'</s>
<s>[INST] Given the following code containing errors, provide 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 UrlParser::parse(char ch) { switch(_state) { case state_0: if (ch == '=') _state = state_value; else if (ch == '&') ; else if (ch == '%') _state = state_keyesc; else { _key = ch; _state = state_key; } break; case state_key: if (ch == '=') _state = state_value; else if (ch == '&') { _q.add(_key); _key.clear(); _state = state_0; } else if (ch == '%') _state = state_keyesc; else _key += ch; break; case state_value: if (ch == '%') _state = state_valueesc; else if (ch == '&') { _q.add(_key, _value); _key.clear(); _value.clear(); _state = state_0; } else if (ch == '+') _value += ' '; else _value += ch; break; case state_keyesc: case state_valueesc: if (ch >= '0' && ch <= '9') { ++_cnt; _v = (_v << 4) + (ch - '0'); } else if (ch >= 'a' && ch <= 'f') { ++_cnt; _v = (_v << 4) + (ch - 'a' + 10); } else if (ch >= 'A' && ch <= 'F') { ++_cnt; _v = (_v << 4) + (ch - 'A' + 10); } else { if (_cnt == 0) { if (_state == state_keyesc) _state = state_key; else _state = state_value; parse('%'); } else { if (_state == state_keyesc) { _key += static_cast<char>(_v); _state = state_key; } else { _value += static_cast<char>(_v); _state = state_value; } _cnt = 0; _v = 0; } parse(ch); break; } if (_cnt >= 2) { if (_state == state_keyesc) { _key += static_cast<char>(_v); _state = state_key; } else { _value += static_cast<char>(_v); _state = state_value; } _cnt = 0; _v = 0; } break; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'fix parsing double % in query parameters'</s>
<s>[INST] Given the following code containing errors, provide 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 Messageheader::Parser::checkHeaderspace(unsigned chars) const { if (headerdataPtr + chars >= header.rawdata + sizeof(header.rawdata)) throw HttpError(HTTP_REQUEST_ENTITY_TOO_LARGE, "header too large"); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'fix possible information leak'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xps_parse_color(xps_document *doc, char *base_uri, char *string, fz_colorspace **csp, float *samples) { char *p; int i, n; char buf[1024]; char *profile; *csp = fz_device_rgb(doc->ctx); samples[0] = 1; samples[1] = 0; samples[2] = 0; samples[3] = 0; if (string[0] == '#') { if (strlen(string) == 9) { samples[0] = unhex(string[1]) * 16 + unhex(string[2]); samples[1] = unhex(string[3]) * 16 + unhex(string[4]); samples[2] = unhex(string[5]) * 16 + unhex(string[6]); samples[3] = unhex(string[7]) * 16 + unhex(string[8]); } else { samples[0] = 255; samples[1] = unhex(string[1]) * 16 + unhex(string[2]); samples[2] = unhex(string[3]) * 16 + unhex(string[4]); samples[3] = unhex(string[5]) * 16 + unhex(string[6]); } samples[0] /= 255; samples[1] /= 255; samples[2] /= 255; samples[3] /= 255; } else if (string[0] == 's' && string[1] == 'c' && string[2] == '#') { if (count_commas(string) == 2) sscanf(string, "sc#%g,%g,%g", samples + 1, samples + 2, samples + 3); if (count_commas(string) == 3) sscanf(string, "sc#%g,%g,%g,%g", samples, samples + 1, samples + 2, samples + 3); } else if (strstr(string, "ContextColor ") == string) { /* Crack the string for profile name and sample values */ fz_strlcpy(buf, string, sizeof buf); profile = strchr(buf, ' '); if (!profile) { fz_warn(doc->ctx, "cannot find icc profile uri in '%s'", string); return; } *profile++ = 0; p = strchr(profile, ' '); if (!p) { fz_warn(doc->ctx, "cannot find component values in '%s'", profile); return; } *p++ = 0; n = count_commas(p) + 1; i = 0; while (i < n) { samples[i++] = fz_atof(p); p = strchr(p, ','); if (!p) break; p ++; if (*p == ' ') p ++; } while (i < n) { samples[i++] = 0; } /* TODO: load ICC profile */ switch (n) { case 2: *csp = fz_device_gray(doc->ctx); break; case 4: *csp = fz_device_rgb(doc->ctx); break; case 5: *csp = fz_device_cmyk(doc->ctx); break; default: *csp = fz_device_gray(doc->ctx); break; } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Bug 694957: fix stack buffer overflow in xps_parse_color xps_parse_color happily reads more than FZ_MAX_COLORS values out of a ContextColor array which overflows the passed in samples array. Limiting the number of allowed samples to FZ_MAX_COLORS and make sure to use that constant for all callers fixes the problem. Thanks to Jean-Jamil Khalifé for reporting and investigating the issue and providing a sample exploit file.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xps_parse_path(xps_document *doc, const fz_matrix *ctm, char *base_uri, xps_resource *dict, fz_xml *root) { fz_xml *node; char *fill_uri; char *stroke_uri; char *opacity_mask_uri; char *transform_att; char *clip_att; char *data_att; char *fill_att; char *stroke_att; char *opacity_att; char *opacity_mask_att; fz_xml *transform_tag = NULL; fz_xml *clip_tag = NULL; fz_xml *data_tag = NULL; fz_xml *fill_tag = NULL; fz_xml *stroke_tag = NULL; fz_xml *opacity_mask_tag = NULL; char *fill_opacity_att = NULL; char *stroke_opacity_att = NULL; char *stroke_dash_array_att; char *stroke_dash_cap_att; char *stroke_dash_offset_att; char *stroke_end_line_cap_att; char *stroke_start_line_cap_att; char *stroke_line_join_att; char *stroke_miter_limit_att; char *stroke_thickness_att; char *navigate_uri_att; fz_stroke_state *stroke = NULL; fz_matrix transform; float samples[32]; fz_colorspace *colorspace; fz_path *path = NULL; fz_path *stroke_path = NULL; fz_rect area; int fill_rule; int dash_len = 0; fz_matrix local_ctm; /* * Extract attributes and extended attributes. */ transform_att = fz_xml_att(root, "RenderTransform"); clip_att = fz_xml_att(root, "Clip"); data_att = fz_xml_att(root, "Data"); fill_att = fz_xml_att(root, "Fill"); stroke_att = fz_xml_att(root, "Stroke"); opacity_att = fz_xml_att(root, "Opacity"); opacity_mask_att = fz_xml_att(root, "OpacityMask"); stroke_dash_array_att = fz_xml_att(root, "StrokeDashArray"); stroke_dash_cap_att = fz_xml_att(root, "StrokeDashCap"); stroke_dash_offset_att = fz_xml_att(root, "StrokeDashOffset"); stroke_end_line_cap_att = fz_xml_att(root, "StrokeEndLineCap"); stroke_start_line_cap_att = fz_xml_att(root, "StrokeStartLineCap"); stroke_line_join_att = fz_xml_att(root, "StrokeLineJoin"); stroke_miter_limit_att = fz_xml_att(root, "StrokeMiterLimit"); stroke_thickness_att = fz_xml_att(root, "StrokeThickness"); navigate_uri_att = fz_xml_att(root, "FixedPage.NavigateUri"); for (node = fz_xml_down(root); node; node = fz_xml_next(node)) { if (!strcmp(fz_xml_tag(node), "Path.RenderTransform")) transform_tag = fz_xml_down(node); if (!strcmp(fz_xml_tag(node), "Path.OpacityMask")) opacity_mask_tag = fz_xml_down(node); if (!strcmp(fz_xml_tag(node), "Path.Clip")) clip_tag = fz_xml_down(node); if (!strcmp(fz_xml_tag(node), "Path.Fill")) fill_tag = fz_xml_down(node); if (!strcmp(fz_xml_tag(node), "Path.Stroke")) stroke_tag = fz_xml_down(node); if (!strcmp(fz_xml_tag(node), "Path.Data")) data_tag = fz_xml_down(node); } fill_uri = base_uri; stroke_uri = base_uri; opacity_mask_uri = base_uri; xps_resolve_resource_reference(doc, dict, &data_att, &data_tag, NULL); xps_resolve_resource_reference(doc, dict, &clip_att, &clip_tag, NULL); xps_resolve_resource_reference(doc, dict, &transform_att, &transform_tag, NULL); xps_resolve_resource_reference(doc, dict, &fill_att, &fill_tag, &fill_uri); xps_resolve_resource_reference(doc, dict, &stroke_att, &stroke_tag, &stroke_uri); xps_resolve_resource_reference(doc, dict, &opacity_mask_att, &opacity_mask_tag, &opacity_mask_uri); /* * Act on the information we have gathered: */ if (!data_att && !data_tag) return; if (fill_tag && !strcmp(fz_xml_tag(fill_tag), "SolidColorBrush")) { fill_opacity_att = fz_xml_att(fill_tag, "Opacity"); fill_att = fz_xml_att(fill_tag, "Color"); fill_tag = NULL; } if (stroke_tag && !strcmp(fz_xml_tag(stroke_tag), "SolidColorBrush")) { stroke_opacity_att = fz_xml_att(stroke_tag, "Opacity"); stroke_att = fz_xml_att(stroke_tag, "Color"); stroke_tag = NULL; } if (stroke_att || stroke_tag) { if (stroke_dash_array_att) { char *s = stroke_dash_array_att; while (*s) { while (*s == ' ') s++; if (*s) /* needed in case of a space before the last quote */ dash_len++; while (*s && *s != ' ') s++; } } stroke = fz_new_stroke_state_with_dash_len(doc->ctx, dash_len); stroke->start_cap = xps_parse_line_cap(stroke_start_line_cap_att); stroke->dash_cap = xps_parse_line_cap(stroke_dash_cap_att); stroke->end_cap = xps_parse_line_cap(stroke_end_line_cap_att); stroke->linejoin = FZ_LINEJOIN_MITER_XPS; if (stroke_line_join_att) { if (!strcmp(stroke_line_join_att, "Miter")) stroke->linejoin = FZ_LINEJOIN_MITER_XPS; if (!strcmp(stroke_line_join_att, "Round")) stroke->linejoin = FZ_LINEJOIN_ROUND; if (!strcmp(stroke_line_join_att, "Bevel")) stroke->linejoin = FZ_LINEJOIN_BEVEL; } stroke->miterlimit = 10; if (stroke_miter_limit_att) stroke->miterlimit = fz_atof(stroke_miter_limit_att); stroke->linewidth = 1; if (stroke_thickness_att) stroke->linewidth = fz_atof(stroke_thickness_att); stroke->dash_phase = 0; stroke->dash_len = 0; if (stroke_dash_array_att) { char *s = stroke_dash_array_att; if (stroke_dash_offset_att) stroke->dash_phase = fz_atof(stroke_dash_offset_att) * stroke->linewidth; while (*s) { while (*s == ' ') s++; if (*s) /* needed in case of a space before the last quote */ stroke->dash_list[stroke->dash_len++] = fz_atof(s) * stroke->linewidth; while (*s && *s != ' ') s++; } stroke->dash_len = dash_len; } } transform = fz_identity; if (transform_att) xps_parse_render_transform(doc, transform_att, &transform); if (transform_tag) xps_parse_matrix_transform(doc, transform_tag, &transform); fz_concat(&local_ctm, &transform, ctm); if (clip_att || clip_tag) xps_clip(doc, &local_ctm, dict, clip_att, clip_tag); fill_rule = 0; if (data_att) path = xps_parse_abbreviated_geometry(doc, data_att, &fill_rule); else if (data_tag) { path = xps_parse_path_geometry(doc, dict, data_tag, 0, &fill_rule); if (stroke_att || stroke_tag) stroke_path = xps_parse_path_geometry(doc, dict, data_tag, 1, &fill_rule); } if (!stroke_path) stroke_path = path; if (stroke_att || stroke_tag) { fz_bound_path(doc->ctx, stroke_path, stroke, &local_ctm, &area); if (stroke_path != path && (fill_att || fill_tag)) { fz_rect bounds; fz_bound_path(doc->ctx, path, NULL, &local_ctm, &bounds); fz_union_rect(&area, &bounds); } } else fz_bound_path(doc->ctx, path, NULL, &local_ctm, &area); if (navigate_uri_att) xps_add_link(doc, &area, base_uri, navigate_uri_att); xps_begin_opacity(doc, &local_ctm, &area, opacity_mask_uri, dict, opacity_att, opacity_mask_tag); if (fill_att) { xps_parse_color(doc, base_uri, fill_att, &colorspace, samples); if (fill_opacity_att) samples[0] *= fz_atof(fill_opacity_att); xps_set_color(doc, colorspace, samples); fz_fill_path(doc->dev, path, fill_rule == 0, &local_ctm, doc->colorspace, doc->color, doc->alpha); } if (fill_tag) { fz_clip_path(doc->dev, path, &area, fill_rule == 0, &local_ctm); xps_parse_brush(doc, &local_ctm, &area, fill_uri, dict, fill_tag); fz_pop_clip(doc->dev); } if (stroke_att) { xps_parse_color(doc, base_uri, stroke_att, &colorspace, samples); if (stroke_opacity_att) samples[0] *= fz_atof(stroke_opacity_att); xps_set_color(doc, colorspace, samples); fz_stroke_path(doc->dev, stroke_path, stroke, &local_ctm, doc->colorspace, doc->color, doc->alpha); } if (stroke_tag) { fz_clip_stroke_path(doc->dev, stroke_path, &area, stroke, &local_ctm); xps_parse_brush(doc, &local_ctm, &area, stroke_uri, dict, stroke_tag); fz_pop_clip(doc->dev); } xps_end_opacity(doc, opacity_mask_uri, dict, opacity_att, opacity_mask_tag); if (stroke_path != path) fz_free_path(doc->ctx, stroke_path); fz_free_path(doc->ctx, path); path = NULL; fz_drop_stroke_state(doc->ctx, stroke); if (clip_att || clip_tag) fz_pop_clip(doc->dev); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Bug 694957: fix stack buffer overflow in xps_parse_color xps_parse_color happily reads more than FZ_MAX_COLORS values out of a ContextColor array which overflows the passed in samples array. Limiting the number of allowed samples to FZ_MAX_COLORS and make sure to use that constant for all callers fixes the problem. Thanks to Jean-Jamil Khalifé for reporting and investigating the issue and providing a sample exploit file.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xps_parse_glyphs(xps_document *doc, const fz_matrix *ctm, char *base_uri, xps_resource *dict, fz_xml *root) { fz_xml *node; char *fill_uri; char *opacity_mask_uri; char *bidi_level_att; char *fill_att; char *font_size_att; char *font_uri_att; char *origin_x_att; char *origin_y_att; char *is_sideways_att; char *indices_att; char *unicode_att; char *style_att; char *transform_att; char *clip_att; char *opacity_att; char *opacity_mask_att; char *navigate_uri_att; fz_xml *transform_tag = NULL; fz_xml *clip_tag = NULL; fz_xml *fill_tag = NULL; fz_xml *opacity_mask_tag = NULL; char *fill_opacity_att = NULL; xps_part *part; fz_font *font; char partname[1024]; char fakename[1024]; char *subfont; float font_size = 10; int subfontid = 0; int is_sideways = 0; int bidi_level = 0; fz_text *text; fz_rect area; fz_matrix local_ctm = *ctm; /* * Extract attributes and extended attributes. */ bidi_level_att = fz_xml_att(root, "BidiLevel"); fill_att = fz_xml_att(root, "Fill"); font_size_att = fz_xml_att(root, "FontRenderingEmSize"); font_uri_att = fz_xml_att(root, "FontUri"); origin_x_att = fz_xml_att(root, "OriginX"); origin_y_att = fz_xml_att(root, "OriginY"); is_sideways_att = fz_xml_att(root, "IsSideways"); indices_att = fz_xml_att(root, "Indices"); unicode_att = fz_xml_att(root, "UnicodeString"); style_att = fz_xml_att(root, "StyleSimulations"); transform_att = fz_xml_att(root, "RenderTransform"); clip_att = fz_xml_att(root, "Clip"); opacity_att = fz_xml_att(root, "Opacity"); opacity_mask_att = fz_xml_att(root, "OpacityMask"); navigate_uri_att = fz_xml_att(root, "FixedPage.NavigateUri"); for (node = fz_xml_down(root); node; node = fz_xml_next(node)) { if (!strcmp(fz_xml_tag(node), "Glyphs.RenderTransform")) transform_tag = fz_xml_down(node); if (!strcmp(fz_xml_tag(node), "Glyphs.OpacityMask")) opacity_mask_tag = fz_xml_down(node); if (!strcmp(fz_xml_tag(node), "Glyphs.Clip")) clip_tag = fz_xml_down(node); if (!strcmp(fz_xml_tag(node), "Glyphs.Fill")) fill_tag = fz_xml_down(node); } fill_uri = base_uri; opacity_mask_uri = base_uri; xps_resolve_resource_reference(doc, dict, &transform_att, &transform_tag, NULL); xps_resolve_resource_reference(doc, dict, &clip_att, &clip_tag, NULL); xps_resolve_resource_reference(doc, dict, &fill_att, &fill_tag, &fill_uri); xps_resolve_resource_reference(doc, dict, &opacity_mask_att, &opacity_mask_tag, &opacity_mask_uri); /* * Check that we have all the necessary information. */ if (!font_size_att || !font_uri_att || !origin_x_att || !origin_y_att) { fz_warn(doc->ctx, "missing attributes in glyphs element"); return; } if (!indices_att && !unicode_att) return; /* nothing to draw */ if (is_sideways_att) is_sideways = !strcmp(is_sideways_att, "true"); if (bidi_level_att) bidi_level = atoi(bidi_level_att); /* * Find and load the font resource */ xps_resolve_url(partname, base_uri, font_uri_att, sizeof partname); subfont = strrchr(partname, '#'); if (subfont) { subfontid = atoi(subfont + 1); *subfont = 0; } /* Make a new part name for font with style simulation applied */ fz_strlcpy(fakename, partname, sizeof fakename); if (style_att) { if (!strcmp(style_att, "BoldSimulation")) fz_strlcat(fakename, "#Bold", sizeof fakename); else if (!strcmp(style_att, "ItalicSimulation")) fz_strlcat(fakename, "#Italic", sizeof fakename); else if (!strcmp(style_att, "BoldItalicSimulation")) fz_strlcat(fakename, "#BoldItalic", sizeof fakename); } font = xps_lookup_font(doc, fakename); if (!font) { fz_try(doc->ctx) { part = xps_read_part(doc, partname); } fz_catch(doc->ctx) { fz_rethrow_if(doc->ctx, FZ_ERROR_TRYLATER); fz_warn(doc->ctx, "cannot find font resource part '%s'", partname); return; } /* deobfuscate if necessary */ if (strstr(part->name, ".odttf")) xps_deobfuscate_font_resource(doc, part); if (strstr(part->name, ".ODTTF")) xps_deobfuscate_font_resource(doc, part); fz_try(doc->ctx) { fz_buffer *buf = fz_new_buffer_from_data(doc->ctx, part->data, part->size); font = fz_new_font_from_buffer(doc->ctx, NULL, buf, subfontid, 1); fz_drop_buffer(doc->ctx, buf); } fz_catch(doc->ctx) { fz_rethrow_if(doc->ctx, FZ_ERROR_TRYLATER); fz_warn(doc->ctx, "cannot load font resource '%s'", partname); xps_free_part(doc, part); return; } if (style_att) { font->ft_bold = !!strstr(style_att, "Bold"); font->ft_italic = !!strstr(style_att, "Italic"); } xps_select_best_font_encoding(doc, font); xps_insert_font(doc, fakename, font); /* NOTE: we already saved part->data in the buffer in the font */ fz_free(doc->ctx, part->name); fz_free(doc->ctx, part); } /* * Set up graphics state. */ if (transform_att || transform_tag) { fz_matrix transform; if (transform_att) xps_parse_render_transform(doc, transform_att, &transform); if (transform_tag) xps_parse_matrix_transform(doc, transform_tag, &transform); fz_concat(&local_ctm, &transform, &local_ctm); } if (clip_att || clip_tag) xps_clip(doc, &local_ctm, dict, clip_att, clip_tag); font_size = fz_atof(font_size_att); text = xps_parse_glyphs_imp(doc, &local_ctm, font, font_size, fz_atof(origin_x_att), fz_atof(origin_y_att), is_sideways, bidi_level, indices_att, unicode_att); fz_bound_text(doc->ctx, text, NULL, &local_ctm, &area); if (navigate_uri_att) xps_add_link(doc, &area, base_uri, navigate_uri_att); xps_begin_opacity(doc, &local_ctm, &area, opacity_mask_uri, dict, opacity_att, opacity_mask_tag); /* If it's a solid color brush fill/stroke do a simple fill */ if (fill_tag && !strcmp(fz_xml_tag(fill_tag), "SolidColorBrush")) { fill_opacity_att = fz_xml_att(fill_tag, "Opacity"); fill_att = fz_xml_att(fill_tag, "Color"); fill_tag = NULL; } if (fill_att) { float samples[32]; fz_colorspace *colorspace; xps_parse_color(doc, base_uri, fill_att, &colorspace, samples); if (fill_opacity_att) samples[0] *= fz_atof(fill_opacity_att); xps_set_color(doc, colorspace, samples); fz_fill_text(doc->dev, text, &local_ctm, doc->colorspace, doc->color, doc->alpha); } /* If it's a complex brush, use the charpath as a clip mask */ if (fill_tag) { fz_clip_text(doc->dev, text, &local_ctm, 0); xps_parse_brush(doc, &local_ctm, &area, fill_uri, dict, fill_tag); fz_pop_clip(doc->dev); } xps_end_opacity(doc, opacity_mask_uri, dict, opacity_att, opacity_mask_tag); fz_free_text(doc->ctx, text); if (clip_att || clip_tag) fz_pop_clip(doc->dev); fz_drop_font(doc->ctx, font); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Bug 694957: fix stack buffer overflow in xps_parse_color xps_parse_color happily reads more than FZ_MAX_COLORS values out of a ContextColor array which overflows the passed in samples array. Limiting the number of allowed samples to FZ_MAX_COLORS and make sure to use that constant for all callers fixes the problem. Thanks to Jean-Jamil Khalifé for reporting and investigating the issue and providing a sample exploit file.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void verifyDirectoryPermissions(const string &path) { TRACE_POINT(); struct stat buf; if (stat(path.c_str(), &buf) == -1) { int e = errno; throw FileSystemException("Cannot stat() " + path, e, path); } else if (buf.st_mode != (S_IFDIR | parseModeString("u=rwx,g=rx,o=rx"))) { throw RuntimeException("Tried to reuse existing server instance directory " + path + ", but it has wrong permissions"); } else if (buf.st_uid != geteuid() || buf.st_gid != getegid()) { /* The server instance directory is always created by the Watchdog. Its UID/GID never * changes because: * 1. Disabling user switching only lowers the privilege of the HelperAgent. * 2. For the UID/GID to change, the web server must be completely restarted * (not just graceful reload) so that the control process can change its UID/GID. * This causes the PID to change, so that an entirely new server instance * directory is created. */ throw RuntimeException("Tried to reuse existing server instance directory " + path + ", but it has wrong owner and group"); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'Fix a symlink-related security vulnerability. The fix in commit 34b10878 and contained a small attack time window in between two filesystem operations. This has been fixed.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void initialize(const string &path, bool owner) { TRACE_POINT(); this->path = path; this->owner = owner; /* Create the server instance directory. We only need to write to this * directory for these reasons: * 1. Initial population of structure files (structure_version.txt, instance.pid). * 2. Creating/removing a generation directory. * 3. Removing the entire server instance directory (after all * generations are removed). * * 1 and 2 are done by the helper server during initialization and before lowering * privilege. 3 is done during helper server shutdown by a cleanup process that's * running as the same user the helper server was running as before privilege * lowering. * Therefore, we make the directory only writable by the user the helper server * was running as before privilege is lowered. Everybody else has read and execute * rights though, because we want admin tools to be able to list the available * generations no matter what user they're running as. */ if (owner) { switch (getFileTypeNoFollowSymlinks(path)) { case FT_NONEXISTANT: createDirectory(path); break; case FT_DIRECTORY: verifyDirectoryPermissions(path); break; default: throw RuntimeException("'" + path + "' already exists, and is not a directory"); } } else if (getFileType(path) != FT_DIRECTORY) { throw RuntimeException("Server instance directory '" + path + "' does not exist"); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'Fix a symlink-related security vulnerability. The fix in commit 34b10878 and contained a small attack time window in between two filesystem operations. This has been fixed.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bool AudioOutputSpeech::needSamples(unsigned int snum) { for (unsigned int i=iLastConsume;i<iBufferFilled;++i) pfBuffer[i-iLastConsume]=pfBuffer[i]; iBufferFilled -= iLastConsume; iLastConsume = snum; if (iBufferFilled >= snum) return bLastAlive; float *pOut; bool nextalive = bLastAlive; while (iBufferFilled < snum) { int decodedSamples = iFrameSize; resizeBuffer(iBufferFilled + iOutputSize); pOut = (srs) ? fResamplerBuffer : (pfBuffer + iBufferFilled); if (! bLastAlive) { memset(pOut, 0, iFrameSize * sizeof(float)); } else { if (p == &LoopUser::lpLoopy) { LoopUser::lpLoopy.fetchFrames(); } int avail = 0; int ts = jitter_buffer_get_pointer_timestamp(jbJitter); jitter_buffer_ctl(jbJitter, JITTER_BUFFER_GET_AVAILABLE_COUNT, &avail); if (p && (ts == 0)) { int want = iroundf(p->fAverageAvailable); if (avail < want) { ++iMissCount; if (iMissCount < 20) { memset(pOut, 0, iFrameSize * sizeof(float)); goto nextframe; } } } if (qlFrames.isEmpty()) { QMutexLocker lock(&qmJitter); char data[4096]; JitterBufferPacket jbp; jbp.data = data; jbp.len = 4096; spx_int32_t startofs = 0; if (jitter_buffer_get(jbJitter, &jbp, iFrameSize, &startofs) == JITTER_BUFFER_OK) { PacketDataStream pds(jbp.data, jbp.len); iMissCount = 0; ucFlags = static_cast<unsigned char>(pds.next()); bHasTerminator = false; if (umtType == MessageHandler::UDPVoiceOpus) { int size; pds >> size; bHasTerminator = size & 0x2000; qlFrames << pds.dataBlock(size & 0x1fff); } else { unsigned int header = 0; do { header = static_cast<unsigned int>(pds.next()); if (header) qlFrames << pds.dataBlock(header & 0x7f); else bHasTerminator = true; } while ((header & 0x80) && pds.isValid()); } if (pds.left()) { pds >> fPos[0]; pds >> fPos[1]; pds >> fPos[2]; } else { fPos[0] = fPos[1] = fPos[2] = 0.0f; } if (p) { float a = static_cast<float>(avail); if (avail >= p->fAverageAvailable) p->fAverageAvailable = a; else p->fAverageAvailable *= 0.99f; } } else { jitter_buffer_update_delay(jbJitter, &jbp, NULL); iMissCount++; if (iMissCount > 10) nextalive = false; } } if (! qlFrames.isEmpty()) { QByteArray qba = qlFrames.takeFirst(); if (umtType == MessageHandler::UDPVoiceCELTAlpha || umtType == MessageHandler::UDPVoiceCELTBeta) { int wantversion = (umtType == MessageHandler::UDPVoiceCELTAlpha) ? g.iCodecAlpha : g.iCodecBeta; if ((p == &LoopUser::lpLoopy) && (! g.qmCodecs.isEmpty())) { QMap<int, CELTCodec *>::const_iterator i = g.qmCodecs.constEnd(); --i; wantversion = i.key(); } if (cCodec && (cCodec->bitstreamVersion() != wantversion)) { cCodec->celt_decoder_destroy(cdDecoder); cdDecoder = NULL; } if (! cCodec) { cCodec = g.qmCodecs.value(wantversion); if (cCodec) { cdDecoder = cCodec->decoderCreate(); } } if (cdDecoder) cCodec->decode_float(cdDecoder, qba.isEmpty() ? NULL : reinterpret_cast<const unsigned char *>(qba.constData()), qba.size(), pOut); else memset(pOut, 0, sizeof(float) * iFrameSize); } else if (umtType == MessageHandler::UDPVoiceOpus) { #ifdef USE_OPUS decodedSamples = opus_decode_float(opusState, qba.isEmpty() ? NULL : reinterpret_cast<const unsigned char *>(qba.constData()), qba.size(), pOut, iAudioBufferSize, 0); #endif } else { if (qba.isEmpty()) { speex_decode(dsSpeex, NULL, pOut); } else { speex_bits_read_from(&sbBits, qba.data(), qba.size()); speex_decode(dsSpeex, &sbBits, pOut); } for (unsigned int i=0;i<iFrameSize;++i) pOut[i] *= (1.0f / 32767.f); } bool update = true; if (p) { float &fPowerMax = p->fPowerMax; float &fPowerMin = p->fPowerMin; float pow = 0.0f; for (int i = 0; i < decodedSamples; ++i) pow += pOut[i] * pOut[i]; pow = sqrtf(pow / static_cast<float>(decodedSamples)); if (pow >= fPowerMax) { fPowerMax = pow; } else { if (pow <= fPowerMin) { fPowerMin = pow; } else { fPowerMax = 0.99f * fPowerMax; fPowerMin += 0.0001f * pow; } } update = (pow < (fPowerMin + 0.01f * (fPowerMax - fPowerMin))); } if (qlFrames.isEmpty() && update) jitter_buffer_update_delay(jbJitter, NULL, NULL); if (qlFrames.isEmpty() && bHasTerminator) nextalive = false; } else { if (umtType == MessageHandler::UDPVoiceCELTAlpha || umtType == MessageHandler::UDPVoiceCELTBeta) { if (cdDecoder) cCodec->decode_float(cdDecoder, NULL, 0, pOut); else memset(pOut, 0, sizeof(float) * iFrameSize); } else if (umtType == MessageHandler::UDPVoiceOpus) { #ifdef USE_OPUS decodedSamples = opus_decode_float(opusState, NULL, 0, pOut, iFrameSize, 0); #endif } else { speex_decode(dsSpeex, NULL, pOut); for (unsigned int i=0;i<iFrameSize;++i) pOut[i] *= (1.0f / 32767.f); } } if (! nextalive) { for (unsigned int i=0;i<iFrameSize;++i) pOut[i] *= fFadeOut[i]; } else if (ts == 0) { for (unsigned int i=0;i<iFrameSize;++i) pOut[i] *= fFadeIn[i]; } for (int i = decodedSamples / iFrameSize; i > 0; --i) { jitter_buffer_tick(jbJitter); } } nextframe: spx_uint32_t inlen = decodedSamples; spx_uint32_t outlen = static_cast<unsigned int>(ceilf(static_cast<float>(decodedSamples * iMixerFreq) / static_cast<float>(iSampleRate))); if (srs && bLastAlive) speex_resampler_process_float(srs, 0, fResamplerBuffer, &inlen, pfBuffer + iBufferFilled, &outlen); iBufferFilled += outlen; } if (p) { Settings::TalkState ts; if (! nextalive) ucFlags = 0xFF; switch (ucFlags) { case 0: ts = Settings::Talking; break; case 1: ts = Settings::Shouting; break; case 0xFF: ts = Settings::Passive; break; default: ts = Settings::Whispering; break; } p->setTalking(ts); } bool tmp = bLastAlive; bLastAlive = nextalive; return tmp; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'mumble: fix Mumble-SA-2014-002 (CVE-2014-0045).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: gs_window_class_init (GSWindowClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass); object_class->finalize = gs_window_finalize; object_class->get_property = gs_window_get_property; object_class->set_property = gs_window_set_property; widget_class->show = gs_window_real_show; widget_class->hide = gs_window_real_hide; widget_class->realize = gs_window_real_realize; widget_class->unrealize = gs_window_real_unrealize; widget_class->key_press_event = gs_window_real_key_press_event; widget_class->motion_notify_event = gs_window_real_motion_notify_event; widget_class->button_press_event = gs_window_real_button_press_event; widget_class->scroll_event = gs_window_real_scroll_event; widget_class->get_preferred_width = gs_window_real_get_preferred_width; widget_class->get_preferred_height = gs_window_real_get_preferred_height; widget_class->grab_broken_event = gs_window_real_grab_broken; widget_class->visibility_notify_event = gs_window_real_visibility_notify_event; g_type_class_add_private (klass, sizeof (GSWindowPrivate)); signals [ACTIVITY] = g_signal_new ("activity", G_TYPE_FROM_CLASS (object_class), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GSWindowClass, activity), NULL, NULL, gs_marshal_BOOLEAN__VOID, G_TYPE_BOOLEAN, 0); signals [DEACTIVATED] = g_signal_new ("deactivated", G_TYPE_FROM_CLASS (object_class), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GSWindowClass, deactivated), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); g_object_class_install_property (object_class, PROP_OBSCURED, g_param_spec_boolean ("obscured", NULL, NULL, FALSE, G_PARAM_READABLE)); g_object_class_install_property (object_class, PROP_DIALOG_UP, g_param_spec_boolean ("dialog-up", NULL, NULL, FALSE, G_PARAM_READABLE)); g_object_class_install_property (object_class, PROP_LOCK_ENABLED, g_param_spec_boolean ("lock-enabled", NULL, NULL, FALSE, G_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_LOGOUT_ENABLED, g_param_spec_boolean ("logout-enabled", NULL, NULL, FALSE, G_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_LOGOUT_TIMEOUT, g_param_spec_long ("logout-timeout", NULL, NULL, -1, G_MAXLONG, 0, G_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_LOGOUT_COMMAND, g_param_spec_string ("logout-command", NULL, NULL, NULL, G_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_KEYBOARD_ENABLED, g_param_spec_boolean ("keyboard-enabled", NULL, NULL, FALSE, G_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_KEYBOARD_COMMAND, g_param_spec_string ("keyboard-command", NULL, NULL, NULL, G_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_MONITOR, g_param_spec_int ("monitor", "Xinerama monitor", "The monitor (in terms of Xinerama) which the window is on", 0, G_MAXINT, 0, G_PARAM_READWRITE | G_PARAM_CONSTRUCT)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284'], 'message': 'Workaround gtk3 bug, don't allow GtkWindow to handle popup_menu.'</s>
<s>[INST] Given the following code containing errors, provide 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(imagesetstyle) { zval *IM, *styles; gdImagePtr im; int * stylearr; int index; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra", &IM, &styles) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); /* copy the style values in the stylearr */ stylearr = safe_emalloc(sizeof(int), zend_hash_num_elements(HASH_OF(styles)), 0); zend_hash_internal_pointer_reset_ex(HASH_OF(styles), &pos); for (index = 0;; zend_hash_move_forward_ex(HASH_OF(styles), &pos)) { zval ** item; if (zend_hash_get_current_data_ex(HASH_OF(styles), (void **) &item, &pos) == FAILURE) { break; } convert_to_long_ex(item); stylearr[index++] = Z_LVAL_PP(item); } gdImageSetStyle(im, stylearr, index); efree(stylearr); RETURN_TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Fixed bug #66356 (Heap Overflow Vulnerability in imagecrop()) And also fixed the bug: arguments are altered after some calls'</s>
<s>[INST] Given the following code containing errors, provide 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_imagepolygon(INTERNAL_FUNCTION_PARAMETERS, int filled) { zval *IM, *POINTS; long NPOINTS, COL; zval **var = NULL; gdImagePtr im; gdPointPtr points; int npoints, col, nelem, i; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rall", &IM, &POINTS, &NPOINTS, &COL) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); npoints = NPOINTS; col = COL; nelem = zend_hash_num_elements(Z_ARRVAL_P(POINTS)); if (nelem < 6) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have at least 3 points in your array"); RETURN_FALSE; } if (npoints <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must give a positive number of points"); RETURN_FALSE; } if (nelem < npoints * 2) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Trying to use %d points in array with only %d points", npoints, nelem/2); RETURN_FALSE; } points = (gdPointPtr) safe_emalloc(npoints, sizeof(gdPoint), 0); for (i = 0; i < npoints; i++) { if (zend_hash_index_find(Z_ARRVAL_P(POINTS), (i * 2), (void **) &var) == SUCCESS) { SEPARATE_ZVAL((var)); convert_to_long(*var); points[i].x = Z_LVAL_PP(var); } if (zend_hash_index_find(Z_ARRVAL_P(POINTS), (i * 2) + 1, (void **) &var) == SUCCESS) { SEPARATE_ZVAL(var); convert_to_long(*var); points[i].y = Z_LVAL_PP(var); } } if (filled) { gdImageFilledPolygon(im, points, npoints, col); } else { gdImagePolygon(im, points, npoints, col); } efree(points); RETURN_TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Fixed bug #66356 (Heap Overflow Vulnerability in imagecrop()) And also fixed the bug: arguments are altered after some calls'</s>
<s>[INST] Given the following code containing errors, provide 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(imageaffinematrixconcat) { double m1[6]; double m2[6]; double mr[6]; zval **tmp; zval *z_m1; zval *z_m2; int i, nelems; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "aa", &z_m1, &z_m2) == FAILURE) { return; } if (((nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m1))) != 6) || (nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m2))) != 6) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Affine arrays must have six elements"); RETURN_FALSE; } for (i = 0; i < 6; i++) { if (zend_hash_index_find(Z_ARRVAL_P(z_m1), i, (void **) &tmp) == SUCCESS) { switch (Z_TYPE_PP(tmp)) { case IS_LONG: m1[i] = Z_LVAL_PP(tmp); break; case IS_DOUBLE: m1[i] = Z_DVAL_PP(tmp); break; case IS_STRING: convert_to_double_ex(tmp); m1[i] = Z_DVAL_PP(tmp); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i); RETURN_FALSE; } } if (zend_hash_index_find(Z_ARRVAL_P(z_m2), i, (void **) &tmp) == SUCCESS) { switch (Z_TYPE_PP(tmp)) { case IS_LONG: m2[i] = Z_LVAL_PP(tmp); break; case IS_DOUBLE: m2[i] = Z_DVAL_PP(tmp); break; case IS_STRING: convert_to_double_ex(tmp); m2[i] = Z_DVAL_PP(tmp); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i); RETURN_FALSE; } } } if (gdAffineConcat (mr, m1, m2) != GD_TRUE) { RETURN_FALSE; } array_init(return_value); for (i = 0; i < 6; i++) { add_index_double(return_value, i, mr[i]); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Fixed bug #66356 (Heap Overflow Vulnerability in imagecrop()) And also fixed the bug: arguments are altered after some calls'</s>
<s>[INST] Given the following code containing errors, provide 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(imagecrop) { zval *IM; gdImagePtr im; gdImagePtr im_crop; gdRect rect; zval *z_rect; zval **tmp; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra", &IM, &z_rect) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (zend_hash_find(HASH_OF(z_rect), "x", sizeof("x"), (void **)&tmp) != FAILURE) { rect.x = Z_LVAL_PP(tmp); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), "y", sizeof("x"), (void **)&tmp) != FAILURE) { rect.y = Z_LVAL_PP(tmp); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), "width", sizeof("width"), (void **)&tmp) != FAILURE) { rect.width = Z_LVAL_PP(tmp); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing width"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), "height", sizeof("height"), (void **)&tmp) != FAILURE) { rect.height = Z_LVAL_PP(tmp); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing height"); RETURN_FALSE; } im_crop = gdImageCrop(im, &rect); if (im_crop == NULL) { RETURN_FALSE; } else { ZEND_REGISTER_RESOURCE(return_value, im_crop, le_gd); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Fixed bug #66356 (Heap Overflow Vulnerability in imagecrop()) And also fixed the bug: arguments are altered after some calls'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: AddRoleMems(const char *rolename, Oid roleid, List *memberNames, List *memberIds, Oid grantorId, bool admin_opt) { Relation pg_authmem_rel; TupleDesc pg_authmem_dsc; ListCell *nameitem; ListCell *iditem; Assert(list_length(memberNames) == list_length(memberIds)); /* Skip permission check if nothing to do */ if (!memberIds) return; /* * Check permissions: must have createrole or admin option on the role to * be changed. To mess with a superuser role, you gotta be superuser. */ if (superuser_arg(roleid)) { if (!superuser()) ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), errmsg("must be superuser to alter superusers"))); } else { if (!have_createrole_privilege() && !is_admin_of_role(grantorId, roleid)) ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), errmsg("must have admin option on role \"%s\"", rolename))); } /* XXX not sure about this check */ if (grantorId != GetUserId() && !superuser()) ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), errmsg("must be superuser to set grantor"))); pg_authmem_rel = heap_open(AuthMemRelationId, RowExclusiveLock); pg_authmem_dsc = RelationGetDescr(pg_authmem_rel); forboth(nameitem, memberNames, iditem, memberIds) { const char *membername = strVal(lfirst(nameitem)); Oid memberid = lfirst_oid(iditem); HeapTuple authmem_tuple; HeapTuple tuple; Datum new_record[Natts_pg_auth_members]; bool new_record_nulls[Natts_pg_auth_members]; bool new_record_repl[Natts_pg_auth_members]; /* * Refuse creation of membership loops, including the trivial case * where a role is made a member of itself. We do this by checking to * see if the target role is already a member of the proposed member * role. We have to ignore possible superuserness, however, else we * could never grant membership in a superuser-privileged role. */ if (is_member_of_role_nosuper(roleid, memberid)) ereport(ERROR, (errcode(ERRCODE_INVALID_GRANT_OPERATION), (errmsg("role \"%s\" is a member of role \"%s\"", rolename, membername)))); /* * Check if entry for this role/member already exists; if so, give * warning unless we are adding admin option. */ authmem_tuple = SearchSysCache2(AUTHMEMROLEMEM, ObjectIdGetDatum(roleid), ObjectIdGetDatum(memberid)); if (HeapTupleIsValid(authmem_tuple) && (!admin_opt || ((Form_pg_auth_members) GETSTRUCT(authmem_tuple))->admin_option)) { ereport(NOTICE, (errmsg("role \"%s\" is already a member of role \"%s\"", membername, rolename))); ReleaseSysCache(authmem_tuple); continue; } /* Build a tuple to insert or update */ MemSet(new_record, 0, sizeof(new_record)); MemSet(new_record_nulls, false, sizeof(new_record_nulls)); MemSet(new_record_repl, false, sizeof(new_record_repl)); new_record[Anum_pg_auth_members_roleid - 1] = ObjectIdGetDatum(roleid); new_record[Anum_pg_auth_members_member - 1] = ObjectIdGetDatum(memberid); new_record[Anum_pg_auth_members_grantor - 1] = ObjectIdGetDatum(grantorId); new_record[Anum_pg_auth_members_admin_option - 1] = BoolGetDatum(admin_opt); if (HeapTupleIsValid(authmem_tuple)) { new_record_repl[Anum_pg_auth_members_grantor - 1] = true; new_record_repl[Anum_pg_auth_members_admin_option - 1] = true; tuple = heap_modify_tuple(authmem_tuple, pg_authmem_dsc, new_record, new_record_nulls, new_record_repl); simple_heap_update(pg_authmem_rel, &tuple->t_self, tuple); CatalogUpdateIndexes(pg_authmem_rel, tuple); ReleaseSysCache(authmem_tuple); } else { tuple = heap_form_tuple(pg_authmem_dsc, new_record, new_record_nulls); simple_heap_insert(pg_authmem_rel, tuple); CatalogUpdateIndexes(pg_authmem_rel, tuple); } /* CCI after each change, in case there are duplicates in list */ CommandCounterIncrement(); } /* * Close pg_authmem, but keep lock till commit. */ heap_close(pg_authmem_rel, NoLock); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Shore up ADMIN OPTION restrictions. Granting a role without ADMIN OPTION is supposed to prevent the grantee from adding or removing members from the granted role. Issuing SET ROLE before the GRANT bypassed that, because the role itself had an implicit right to add or remove members. Plug that hole by recognizing that implicit right only when the session user matches the current role. Additionally, do not recognize it during a security-restricted operation or during execution of a SECURITY DEFINER function. The restriction on SECURITY DEFINER is not security-critical. However, it seems best for a user testing his own SECURITY DEFINER function to see the same behavior others will see. Back-patch to 8.4 (all supported versions). The SQL standards do not conflate roles and users as PostgreSQL does; only SQL roles have members, and only SQL users initiate sessions. An application using PostgreSQL users and roles as SQL users and roles will never attempt to grant membership in the role that is the session user, so the implicit right to add or remove members will never arise. The security impact was mostly that a role member could revoke access from others, contrary to the wishes of his own grantor. Unapproved role member additions are less notable, because the member can still largely achieve that by creating a view or a SECURITY DEFINER function. Reviewed by Andres Freund and Tom Lane. Reported, independently, by Jonas Sundman and Noah Misch. Security: CVE-2014-0060'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: is_admin_of_role(Oid member, Oid role) { bool result = false; List *roles_list; ListCell *l; /* Fast path for simple case */ if (member == role) return true; /* Superusers have every privilege, so are part of every role */ if (superuser_arg(member)) return true; /* * Find all the roles that member is a member of, including multi-level * recursion. We build a list in the same way that is_member_of_role does * to track visited and unvisited roles. */ roles_list = list_make1_oid(member); foreach(l, roles_list) { Oid memberid = lfirst_oid(l); CatCList *memlist; int i; /* Find roles that memberid is directly a member of */ memlist = SearchSysCacheList1(AUTHMEMMEMROLE, ObjectIdGetDatum(memberid)); for (i = 0; i < memlist->n_members; i++) { HeapTuple tup = &memlist->members[i]->tuple; Oid otherid = ((Form_pg_auth_members) GETSTRUCT(tup))->roleid; if (otherid == role && ((Form_pg_auth_members) GETSTRUCT(tup))->admin_option) { /* Found what we came for, so can stop searching */ result = true; break; } roles_list = list_append_unique_oid(roles_list, otherid); } ReleaseSysCacheList(memlist); if (result) break; } list_free(roles_list); return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Shore up ADMIN OPTION restrictions. Granting a role without ADMIN OPTION is supposed to prevent the grantee from adding or removing members from the granted role. Issuing SET ROLE before the GRANT bypassed that, because the role itself had an implicit right to add or remove members. Plug that hole by recognizing that implicit right only when the session user matches the current role. Additionally, do not recognize it during a security-restricted operation or during execution of a SECURITY DEFINER function. The restriction on SECURITY DEFINER is not security-critical. However, it seems best for a user testing his own SECURITY DEFINER function to see the same behavior others will see. Back-patch to 8.4 (all supported versions). The SQL standards do not conflate roles and users as PostgreSQL does; only SQL roles have members, and only SQL users initiate sessions. An application using PostgreSQL users and roles as SQL users and roles will never attempt to grant membership in the role that is the session user, so the implicit right to add or remove members will never arise. The security impact was mostly that a role member could revoke access from others, contrary to the wishes of his own grantor. Unapproved role member additions are less notable, because the member can still largely achieve that by creating a view or a SECURITY DEFINER function. Reviewed by Andres Freund and Tom Lane. Reported, independently, by Jonas Sundman and Noah Misch. Security: CVE-2014-0060'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: plpgsql_validator(PG_FUNCTION_ARGS) { Oid funcoid = PG_GETARG_OID(0); HeapTuple tuple; Form_pg_proc proc; char functyptype; int numargs; Oid *argtypes; char **argnames; char *argmodes; bool is_dml_trigger = false; bool is_event_trigger = false; int i; /* Get the new function's pg_proc entry */ tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid)); if (!HeapTupleIsValid(tuple)) elog(ERROR, "cache lookup failed for function %u", funcoid); proc = (Form_pg_proc) GETSTRUCT(tuple); functyptype = get_typtype(proc->prorettype); /* Disallow pseudotype result */ /* except for TRIGGER, RECORD, VOID, or polymorphic */ if (functyptype == TYPTYPE_PSEUDO) { /* we assume OPAQUE with no arguments means a trigger */ if (proc->prorettype == TRIGGEROID || (proc->prorettype == OPAQUEOID && proc->pronargs == 0)) is_dml_trigger = true; else if (proc->prorettype == EVTTRIGGEROID) is_event_trigger = true; else if (proc->prorettype != RECORDOID && proc->prorettype != VOIDOID && !IsPolymorphicType(proc->prorettype)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("PL/pgSQL functions cannot return type %s", format_type_be(proc->prorettype)))); } /* Disallow pseudotypes in arguments (either IN or OUT) */ /* except for polymorphic */ numargs = get_func_arg_info(tuple, &argtypes, &argnames, &argmodes); for (i = 0; i < numargs; i++) { if (get_typtype(argtypes[i]) == TYPTYPE_PSEUDO) { if (!IsPolymorphicType(argtypes[i])) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("PL/pgSQL functions cannot accept type %s", format_type_be(argtypes[i])))); } } /* Postpone body checks if !check_function_bodies */ if (check_function_bodies) { FunctionCallInfoData fake_fcinfo; FmgrInfo flinfo; int rc; TriggerData trigdata; EventTriggerData etrigdata; /* * Connect to SPI manager (is this needed for compilation?) */ if ((rc = SPI_connect()) != SPI_OK_CONNECT) elog(ERROR, "SPI_connect failed: %s", SPI_result_code_string(rc)); /* * Set up a fake fcinfo with just enough info to satisfy * plpgsql_compile(). */ MemSet(&fake_fcinfo, 0, sizeof(fake_fcinfo)); MemSet(&flinfo, 0, sizeof(flinfo)); fake_fcinfo.flinfo = &flinfo; flinfo.fn_oid = funcoid; flinfo.fn_mcxt = CurrentMemoryContext; if (is_dml_trigger) { MemSet(&trigdata, 0, sizeof(trigdata)); trigdata.type = T_TriggerData; fake_fcinfo.context = (Node *) &trigdata; } else if (is_event_trigger) { MemSet(&etrigdata, 0, sizeof(etrigdata)); etrigdata.type = T_EventTriggerData; fake_fcinfo.context = (Node *) &etrigdata; } /* Test-compile the function */ plpgsql_compile(&fake_fcinfo, true); /* * Disconnect from SPI manager */ if ((rc = SPI_finish()) != SPI_OK_FINISH) elog(ERROR, "SPI_finish failed: %s", SPI_result_code_string(rc)); } ReleaseSysCache(tuple); PG_RETURN_VOID(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Prevent privilege escalation in explicit calls to PL validators. The primary role of PL validators is to be called implicitly during CREATE FUNCTION, but they are also normal functions that a user can call explicitly. Add a permissions check to each validator to ensure that a user cannot use explicit validator calls to achieve things he could not otherwise achieve. Back-patch to 8.4 (all supported versions). Non-core procedural language extensions ought to make the same two-line change to their own validators. Andres Freund, reviewed by Tom Lane and Noah Misch. Security: CVE-2014-0061'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: fmgr_sql_validator(PG_FUNCTION_ARGS) { Oid funcoid = PG_GETARG_OID(0); HeapTuple tuple; Form_pg_proc proc; List *raw_parsetree_list; List *querytree_list; ListCell *lc; bool isnull; Datum tmp; char *prosrc; parse_error_callback_arg callback_arg; ErrorContextCallback sqlerrcontext; bool haspolyarg; int i; tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid)); if (!HeapTupleIsValid(tuple)) elog(ERROR, "cache lookup failed for function %u", funcoid); proc = (Form_pg_proc) GETSTRUCT(tuple); /* Disallow pseudotype result */ /* except for RECORD, VOID, or polymorphic */ if (get_typtype(proc->prorettype) == TYPTYPE_PSEUDO && proc->prorettype != RECORDOID && proc->prorettype != VOIDOID && !IsPolymorphicType(proc->prorettype)) ereport(ERROR, (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION), errmsg("SQL functions cannot return type %s", format_type_be(proc->prorettype)))); /* Disallow pseudotypes in arguments */ /* except for polymorphic */ haspolyarg = false; for (i = 0; i < proc->pronargs; i++) { if (get_typtype(proc->proargtypes.values[i]) == TYPTYPE_PSEUDO) { if (IsPolymorphicType(proc->proargtypes.values[i])) haspolyarg = true; else ereport(ERROR, (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION), errmsg("SQL functions cannot have arguments of type %s", format_type_be(proc->proargtypes.values[i])))); } } /* Postpone body checks if !check_function_bodies */ if (check_function_bodies) { tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull); if (isnull) elog(ERROR, "null prosrc"); prosrc = TextDatumGetCString(tmp); /* * Setup error traceback support for ereport(). */ callback_arg.proname = NameStr(proc->proname); callback_arg.prosrc = prosrc; sqlerrcontext.callback = sql_function_parse_error_callback; sqlerrcontext.arg = (void *) &callback_arg; sqlerrcontext.previous = error_context_stack; error_context_stack = &sqlerrcontext; /* * We can't do full prechecking of the function definition if there * are any polymorphic input types, because actual datatypes of * expression results will be unresolvable. The check will be done at * runtime instead. * * We can run the text through the raw parser though; this will at * least catch silly syntactic errors. */ raw_parsetree_list = pg_parse_query(prosrc); if (!haspolyarg) { /* * OK to do full precheck: analyze and rewrite the queries, then * verify the result type. */ SQLFunctionParseInfoPtr pinfo; /* But first, set up parameter information */ pinfo = prepare_sql_fn_parse_info(tuple, NULL, InvalidOid); querytree_list = NIL; foreach(lc, raw_parsetree_list) { Node *parsetree = (Node *) lfirst(lc); List *querytree_sublist; querytree_sublist = pg_analyze_and_rewrite_params(parsetree, prosrc, (ParserSetupHook) sql_fn_parser_setup, pinfo); querytree_list = list_concat(querytree_list, querytree_sublist); } (void) check_sql_fn_retval(funcoid, proc->prorettype, querytree_list, NULL, NULL); } error_context_stack = sqlerrcontext.previous; } ReleaseSysCache(tuple); PG_RETURN_VOID(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Prevent privilege escalation in explicit calls to PL validators. The primary role of PL validators is to be called implicitly during CREATE FUNCTION, but they are also normal functions that a user can call explicitly. Add a permissions check to each validator to ensure that a user cannot use explicit validator calls to achieve things he could not otherwise achieve. Back-patch to 8.4 (all supported versions). Non-core procedural language extensions ought to make the same two-line change to their own validators. Andres Freund, reviewed by Tom Lane and Noah Misch. Security: CVE-2014-0061'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: plperlu_validator(PG_FUNCTION_ARGS) { return plperl_validator(fcinfo); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Prevent privilege escalation in explicit calls to PL validators. The primary role of PL validators is to be called implicitly during CREATE FUNCTION, but they are also normal functions that a user can call explicitly. Add a permissions check to each validator to ensure that a user cannot use explicit validator calls to achieve things he could not otherwise achieve. Back-patch to 8.4 (all supported versions). Non-core procedural language extensions ought to make the same two-line change to their own validators. Andres Freund, reviewed by Tom Lane and Noah Misch. Security: CVE-2014-0061'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: fmgr_c_validator(PG_FUNCTION_ARGS) { Oid funcoid = PG_GETARG_OID(0); void *libraryhandle; HeapTuple tuple; bool isnull; Datum tmp; char *prosrc; char *probin; /* * It'd be most consistent to skip the check if !check_function_bodies, * but the purpose of that switch is to be helpful for pg_dump loading, * and for pg_dump loading it's much better if we *do* check. */ tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid)); if (!HeapTupleIsValid(tuple)) elog(ERROR, "cache lookup failed for function %u", funcoid); tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull); if (isnull) elog(ERROR, "null prosrc for C function %u", funcoid); prosrc = TextDatumGetCString(tmp); tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_probin, &isnull); if (isnull) elog(ERROR, "null probin for C function %u", funcoid); probin = TextDatumGetCString(tmp); (void) load_external_function(probin, prosrc, true, &libraryhandle); (void) fetch_finfo_record(libraryhandle, prosrc); ReleaseSysCache(tuple); PG_RETURN_VOID(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Prevent privilege escalation in explicit calls to PL validators. The primary role of PL validators is to be called implicitly during CREATE FUNCTION, but they are also normal functions that a user can call explicitly. Add a permissions check to each validator to ensure that a user cannot use explicit validator calls to achieve things he could not otherwise achieve. Back-patch to 8.4 (all supported versions). Non-core procedural language extensions ought to make the same two-line change to their own validators. Andres Freund, reviewed by Tom Lane and Noah Misch. Security: CVE-2014-0061'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: DefineIndex(IndexStmt *stmt, Oid indexRelationId, bool is_alter_table, bool check_rights, bool skip_build, bool quiet) { char *indexRelationName; char *accessMethodName; Oid *typeObjectId; Oid *collationObjectId; Oid *classObjectId; Oid accessMethodId; Oid relationId; Oid namespaceId; Oid tablespaceId; List *indexColNames; Relation rel; Relation indexRelation; HeapTuple tuple; Form_pg_am accessMethodForm; bool amcanorder; RegProcedure amoptions; Datum reloptions; int16 *coloptions; IndexInfo *indexInfo; int numberOfAttributes; TransactionId limitXmin; VirtualTransactionId *old_snapshots; int n_old_snapshots; LockRelId heaprelid; LOCKTAG heaplocktag; Snapshot snapshot; int i; /* * count attributes in index */ numberOfAttributes = list_length(stmt->indexParams); if (numberOfAttributes <= 0) ereport(ERROR, (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), errmsg("must specify at least one column"))); if (numberOfAttributes > INDEX_MAX_KEYS) ereport(ERROR, (errcode(ERRCODE_TOO_MANY_COLUMNS), errmsg("cannot use more than %d columns in an index", INDEX_MAX_KEYS))); /* * Open heap relation, acquire a suitable lock on it, remember its OID * * Only SELECT ... FOR UPDATE/SHARE are allowed while doing a standard * index build; but for concurrent builds we allow INSERT/UPDATE/DELETE * (but not VACUUM). */ rel = heap_openrv(stmt->relation, (stmt->concurrent ? ShareUpdateExclusiveLock : ShareLock)); relationId = RelationGetRelid(rel); namespaceId = RelationGetNamespace(rel); if (rel->rd_rel->relkind != RELKIND_RELATION && rel->rd_rel->relkind != RELKIND_MATVIEW) { if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE) /* * Custom error message for FOREIGN TABLE since the term is close * to a regular table and can confuse the user. */ ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("cannot create index on foreign table \"%s\"", RelationGetRelationName(rel)))); else ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("\"%s\" is not a table or materialized view", RelationGetRelationName(rel)))); } /* * Don't try to CREATE INDEX on temp tables of other backends. */ if (RELATION_IS_OTHER_TEMP(rel)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("cannot create indexes on temporary tables of other sessions"))); /* * Verify we (still) have CREATE rights in the rel's namespace. * (Presumably we did when the rel was created, but maybe not anymore.) * Skip check if caller doesn't want it. Also skip check if * bootstrapping, since permissions machinery may not be working yet. */ if (check_rights && !IsBootstrapProcessingMode()) { AclResult aclresult; aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_CREATE); if (aclresult != ACLCHECK_OK) aclcheck_error(aclresult, ACL_KIND_NAMESPACE, get_namespace_name(namespaceId)); } /* * Select tablespace to use. If not specified, use default tablespace * (which may in turn default to database's default). */ if (stmt->tableSpace) { tablespaceId = get_tablespace_oid(stmt->tableSpace, false); } else { tablespaceId = GetDefaultTablespace(rel->rd_rel->relpersistence); /* note InvalidOid is OK in this case */ } /* Check permissions except when using database's default */ if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace) { AclResult aclresult; aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(), ACL_CREATE); if (aclresult != ACLCHECK_OK) aclcheck_error(aclresult, ACL_KIND_TABLESPACE, get_tablespace_name(tablespaceId)); } /* * Force shared indexes into the pg_global tablespace. This is a bit of a * hack but seems simpler than marking them in the BKI commands. On the * other hand, if it's not shared, don't allow it to be placed there. */ if (rel->rd_rel->relisshared) tablespaceId = GLOBALTABLESPACE_OID; else if (tablespaceId == GLOBALTABLESPACE_OID) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("only shared relations can be placed in pg_global tablespace"))); /* * Choose the index column names. */ indexColNames = ChooseIndexColumnNames(stmt->indexParams); /* * Select name for index if caller didn't specify */ indexRelationName = stmt->idxname; if (indexRelationName == NULL) indexRelationName = ChooseIndexName(RelationGetRelationName(rel), namespaceId, indexColNames, stmt->excludeOpNames, stmt->primary, stmt->isconstraint); /* * look up the access method, verify it can handle the requested features */ accessMethodName = stmt->accessMethod; tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName)); if (!HeapTupleIsValid(tuple)) { /* * Hack to provide more-or-less-transparent updating of old RTREE * indexes to GiST: if RTREE is requested and not found, use GIST. */ if (strcmp(accessMethodName, "rtree") == 0) { ereport(NOTICE, (errmsg("substituting access method \"gist\" for obsolete method \"rtree\""))); accessMethodName = "gist"; tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName)); } if (!HeapTupleIsValid(tuple)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("access method \"%s\" does not exist", accessMethodName))); } accessMethodId = HeapTupleGetOid(tuple); accessMethodForm = (Form_pg_am) GETSTRUCT(tuple); if (stmt->unique && !accessMethodForm->amcanunique) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("access method \"%s\" does not support unique indexes", accessMethodName))); if (numberOfAttributes > 1 && !accessMethodForm->amcanmulticol) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("access method \"%s\" does not support multicolumn indexes", accessMethodName))); if (stmt->excludeOpNames && !OidIsValid(accessMethodForm->amgettuple)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("access method \"%s\" does not support exclusion constraints", accessMethodName))); amcanorder = accessMethodForm->amcanorder; amoptions = accessMethodForm->amoptions; ReleaseSysCache(tuple); /* * Validate predicate, if given */ if (stmt->whereClause) CheckPredicate((Expr *) stmt->whereClause); /* * Parse AM-specific options, convert to text array form, validate. */ reloptions = transformRelOptions((Datum) 0, stmt->options, NULL, NULL, false, false); (void) index_reloptions(amoptions, reloptions, true); /* * Prepare arguments for index_create, primarily an IndexInfo structure. * Note that ii_Predicate must be in implicit-AND format. */ indexInfo = makeNode(IndexInfo); indexInfo->ii_NumIndexAttrs = numberOfAttributes; indexInfo->ii_Expressions = NIL; /* for now */ indexInfo->ii_ExpressionsState = NIL; indexInfo->ii_Predicate = make_ands_implicit((Expr *) stmt->whereClause); indexInfo->ii_PredicateState = NIL; indexInfo->ii_ExclusionOps = NULL; indexInfo->ii_ExclusionProcs = NULL; indexInfo->ii_ExclusionStrats = NULL; indexInfo->ii_Unique = stmt->unique; /* In a concurrent build, mark it not-ready-for-inserts */ indexInfo->ii_ReadyForInserts = !stmt->concurrent; indexInfo->ii_Concurrent = stmt->concurrent; indexInfo->ii_BrokenHotChain = false; typeObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid)); collationObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid)); classObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid)); coloptions = (int16 *) palloc(numberOfAttributes * sizeof(int16)); ComputeIndexAttrs(indexInfo, typeObjectId, collationObjectId, classObjectId, coloptions, stmt->indexParams, stmt->excludeOpNames, relationId, accessMethodName, accessMethodId, amcanorder, stmt->isconstraint); /* * Extra checks when creating a PRIMARY KEY index. */ if (stmt->primary) index_check_primary_key(rel, indexInfo, is_alter_table); /* * Report index creation if appropriate (delay this till after most of the * error checks) */ if (stmt->isconstraint && !quiet) { const char *constraint_type; if (stmt->primary) constraint_type = "PRIMARY KEY"; else if (stmt->unique) constraint_type = "UNIQUE"; else if (stmt->excludeOpNames != NIL) constraint_type = "EXCLUDE"; else { elog(ERROR, "unknown constraint type"); constraint_type = NULL; /* keep compiler quiet */ } ereport(DEBUG1, (errmsg("%s %s will create implicit index \"%s\" for table \"%s\"", is_alter_table ? "ALTER TABLE / ADD" : "CREATE TABLE /", constraint_type, indexRelationName, RelationGetRelationName(rel)))); } /* * A valid stmt->oldNode implies that we already have a built form of the * index. The caller should also decline any index build. */ Assert(!OidIsValid(stmt->oldNode) || (skip_build && !stmt->concurrent)); /* * Make the catalog entries for the index, including constraints. Then, if * not skip_build || concurrent, actually build the index. */ indexRelationId = index_create(rel, indexRelationName, indexRelationId, stmt->oldNode, indexInfo, indexColNames, accessMethodId, tablespaceId, collationObjectId, classObjectId, coloptions, reloptions, stmt->primary, stmt->isconstraint, stmt->deferrable, stmt->initdeferred, allowSystemTableMods, skip_build || stmt->concurrent, stmt->concurrent, !check_rights); /* Add any requested comment */ if (stmt->idxcomment != NULL) CreateComments(indexRelationId, RelationRelationId, 0, stmt->idxcomment); if (!stmt->concurrent) { /* Close the heap and we're done, in the non-concurrent case */ heap_close(rel, NoLock); return indexRelationId; } /* save lockrelid and locktag for below, then close rel */ heaprelid = rel->rd_lockInfo.lockRelId; SET_LOCKTAG_RELATION(heaplocktag, heaprelid.dbId, heaprelid.relId); heap_close(rel, NoLock); /* * For a concurrent build, it's important to make the catalog entries * visible to other transactions before we start to build the index. That * will prevent them from making incompatible HOT updates. The new index * will be marked not indisready and not indisvalid, so that no one else * tries to either insert into it or use it for queries. * * We must commit our current transaction so that the index becomes * visible; then start another. Note that all the data structures we just * built are lost in the commit. The only data we keep past here are the * relation IDs. * * Before committing, get a session-level lock on the table, to ensure * that neither it nor the index can be dropped before we finish. This * cannot block, even if someone else is waiting for access, because we * already have the same lock within our transaction. * * Note: we don't currently bother with a session lock on the index, * because there are no operations that could change its state while we * hold lock on the parent table. This might need to change later. */ LockRelationIdForSession(&heaprelid, ShareUpdateExclusiveLock); PopActiveSnapshot(); CommitTransactionCommand(); StartTransactionCommand(); /* * Phase 2 of concurrent index build (see comments for validate_index() * for an overview of how this works) * * Now we must wait until no running transaction could have the table open * with the old list of indexes. Use ShareLock to consider running * transactions that hold locks that permit writing to the table. Note we * do not need to worry about xacts that open the table for writing after * this point; they will see the new index when they open it. * * Note: the reason we use actual lock acquisition here, rather than just * checking the ProcArray and sleeping, is that deadlock is possible if * one of the transactions in question is blocked trying to acquire an * exclusive lock on our table. The lock code will detect deadlock and * error out properly. */ WaitForLockers(heaplocktag, ShareLock); /* * At this moment we are sure that there are no transactions with the * table open for write that don't have this new index in their list of * indexes. We have waited out all the existing transactions and any new * transaction will have the new index in its list, but the index is still * marked as "not-ready-for-inserts". The index is consulted while * deciding HOT-safety though. This arrangement ensures that no new HOT * chains can be created where the new tuple and the old tuple in the * chain have different index keys. * * We now take a new snapshot, and build the index using all tuples that * are visible in this snapshot. We can be sure that any HOT updates to * these tuples will be compatible with the index, since any updates made * by transactions that didn't know about the index are now committed or * rolled back. Thus, each visible tuple is either the end of its * HOT-chain or the extension of the chain is HOT-safe for this index. */ /* Open and lock the parent heap relation */ rel = heap_openrv(stmt->relation, ShareUpdateExclusiveLock); /* And the target index relation */ indexRelation = index_open(indexRelationId, RowExclusiveLock); /* Set ActiveSnapshot since functions in the indexes may need it */ PushActiveSnapshot(GetTransactionSnapshot()); /* We have to re-build the IndexInfo struct, since it was lost in commit */ indexInfo = BuildIndexInfo(indexRelation); Assert(!indexInfo->ii_ReadyForInserts); indexInfo->ii_Concurrent = true; indexInfo->ii_BrokenHotChain = false; /* Now build the index */ index_build(rel, indexRelation, indexInfo, stmt->primary, false); /* Close both the relations, but keep the locks */ heap_close(rel, NoLock); index_close(indexRelation, NoLock); /* * Update the pg_index row to mark the index as ready for inserts. Once we * commit this transaction, any new transactions that open the table must * insert new entries into the index for insertions and non-HOT updates. */ index_set_state_flags(indexRelationId, INDEX_CREATE_SET_READY); /* we can do away with our snapshot */ PopActiveSnapshot(); /* * Commit this transaction to make the indisready update visible. */ CommitTransactionCommand(); StartTransactionCommand(); /* * Phase 3 of concurrent index build * * We once again wait until no transaction can have the table open with * the index marked as read-only for updates. */ WaitForLockers(heaplocktag, ShareLock); /* * Now take the "reference snapshot" that will be used by validate_index() * to filter candidate tuples. Beware! There might still be snapshots in * use that treat some transaction as in-progress that our reference * snapshot treats as committed. If such a recently-committed transaction * deleted tuples in the table, we will not include them in the index; yet * those transactions which see the deleting one as still-in-progress will * expect such tuples to be there once we mark the index as valid. * * We solve this by waiting for all endangered transactions to exit before * we mark the index as valid. * * We also set ActiveSnapshot to this snap, since functions in indexes may * need a snapshot. */ snapshot = RegisterSnapshot(GetTransactionSnapshot()); PushActiveSnapshot(snapshot); /* * Scan the index and the heap, insert any missing index entries. */ validate_index(relationId, indexRelationId, snapshot); /* * Drop the reference snapshot. We must do this before waiting out other * snapshot holders, else we will deadlock against other processes also * doing CREATE INDEX CONCURRENTLY, which would see our snapshot as one * they must wait for. But first, save the snapshot's xmin to use as * limitXmin for GetCurrentVirtualXIDs(). */ limitXmin = snapshot->xmin; PopActiveSnapshot(); UnregisterSnapshot(snapshot); /* * The index is now valid in the sense that it contains all currently * interesting tuples. But since it might not contain tuples deleted just * before the reference snap was taken, we have to wait out any * transactions that might have older snapshots. Obtain a list of VXIDs * of such transactions, and wait for them individually. * * We can exclude any running transactions that have xmin > the xmin of * our reference snapshot; their oldest snapshot must be newer than ours. * We can also exclude any transactions that have xmin = zero, since they * evidently have no live snapshot at all (and any one they might be in * process of taking is certainly newer than ours). Transactions in other * DBs can be ignored too, since they'll never even be able to see this * index. * * We can also exclude autovacuum processes and processes running manual * lazy VACUUMs, because they won't be fazed by missing index entries * either. (Manual ANALYZEs, however, can't be excluded because they * might be within transactions that are going to do arbitrary operations * later.) * * Also, GetCurrentVirtualXIDs never reports our own vxid, so we need not * check for that. * * If a process goes idle-in-transaction with xmin zero, we do not need to * wait for it anymore, per the above argument. We do not have the * infrastructure right now to stop waiting if that happens, but we can at * least avoid the folly of waiting when it is idle at the time we would * begin to wait. We do this by repeatedly rechecking the output of * GetCurrentVirtualXIDs. If, during any iteration, a particular vxid * doesn't show up in the output, we know we can forget about it. */ old_snapshots = GetCurrentVirtualXIDs(limitXmin, true, false, PROC_IS_AUTOVACUUM | PROC_IN_VACUUM, &n_old_snapshots); for (i = 0; i < n_old_snapshots; i++) { if (!VirtualTransactionIdIsValid(old_snapshots[i])) continue; /* found uninteresting in previous cycle */ if (i > 0) { /* see if anything's changed ... */ VirtualTransactionId *newer_snapshots; int n_newer_snapshots; int j; int k; newer_snapshots = GetCurrentVirtualXIDs(limitXmin, true, false, PROC_IS_AUTOVACUUM | PROC_IN_VACUUM, &n_newer_snapshots); for (j = i; j < n_old_snapshots; j++) { if (!VirtualTransactionIdIsValid(old_snapshots[j])) continue; /* found uninteresting in previous cycle */ for (k = 0; k < n_newer_snapshots; k++) { if (VirtualTransactionIdEquals(old_snapshots[j], newer_snapshots[k])) break; } if (k >= n_newer_snapshots) /* not there anymore */ SetInvalidVirtualTransactionId(old_snapshots[j]); } pfree(newer_snapshots); } if (VirtualTransactionIdIsValid(old_snapshots[i])) VirtualXactLock(old_snapshots[i], true); } /* * Index can now be marked valid -- update its pg_index entry */ index_set_state_flags(indexRelationId, INDEX_CREATE_SET_VALID); /* * The pg_index update will cause backends (including this one) to update * relcache entries for the index itself, but we should also send a * relcache inval on the parent table to force replanning of cached plans. * Otherwise existing sessions might fail to use the new index where it * would be useful. (Note that our earlier commits did not create reasons * to replan; so relcache flush on the index itself was sufficient.) */ CacheInvalidateRelcacheByRelid(heaprelid.relId); /* * Last thing to do is release the session-level lock on the parent table. */ UnlockRelationIdForSession(&heaprelid, ShareUpdateExclusiveLock); return indexRelationId; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'Avoid repeated name lookups during table and index DDL. If the name lookups come to different conclusions due to concurrent activity, we might perform some parts of the DDL on a different table than other parts. At least in the case of CREATE INDEX, this can be used to cause the permissions checks to be performed against a different table than the index creation, allowing for a privilege escalation attack. This changes the calling convention for DefineIndex, CreateTrigger, transformIndexStmt, transformAlterTableStmt, CheckIndexCompatible (in 9.2 and newer), and AlterTable (in 9.1 and older). In addition, CheckRelationOwnership is removed in 9.2 and newer and the calling convention is changed in older branches. A field has also been added to the Constraint node (FkConstraint in 8.4). Third-party code calling these functions or using the Constraint node will require updating. Report by Andres Freund. Patch by Robert Haas and Andres Freund, reviewed by Tom Lane. Security: CVE-2014-0062'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: index_constraint_create(Relation heapRelation, Oid indexRelationId, IndexInfo *indexInfo, const char *constraintName, char constraintType, bool deferrable, bool initdeferred, bool mark_as_primary, bool update_pgindex, bool remove_old_dependencies, bool allow_system_table_mods, bool is_internal) { Oid namespaceId = RelationGetNamespace(heapRelation); ObjectAddress myself, referenced; Oid conOid; /* constraint creation support doesn't work while bootstrapping */ Assert(!IsBootstrapProcessingMode()); /* enforce system-table restriction */ if (!allow_system_table_mods && IsSystemRelation(heapRelation) && IsNormalProcessingMode()) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("user-defined indexes on system catalog tables are not supported"))); /* primary/unique constraints shouldn't have any expressions */ if (indexInfo->ii_Expressions && constraintType != CONSTRAINT_EXCLUSION) elog(ERROR, "constraints cannot have index expressions"); /* * If we're manufacturing a constraint for a pre-existing index, we need * to get rid of the existing auto dependencies for the index (the ones * that index_create() would have made instead of calling this function). * * Note: this code would not necessarily do the right thing if the index * has any expressions or predicate, but we'd never be turning such an * index into a UNIQUE or PRIMARY KEY constraint. */ if (remove_old_dependencies) deleteDependencyRecordsForClass(RelationRelationId, indexRelationId, RelationRelationId, DEPENDENCY_AUTO); /* * Construct a pg_constraint entry. */ conOid = CreateConstraintEntry(constraintName, namespaceId, constraintType, deferrable, initdeferred, true, RelationGetRelid(heapRelation), indexInfo->ii_KeyAttrNumbers, indexInfo->ii_NumIndexAttrs, InvalidOid, /* no domain */ indexRelationId, /* index OID */ InvalidOid, /* no foreign key */ NULL, NULL, NULL, NULL, 0, ' ', ' ', ' ', indexInfo->ii_ExclusionOps, NULL, /* no check constraint */ NULL, NULL, true, /* islocal */ 0, /* inhcount */ true, /* noinherit */ is_internal); /* * Register the index as internally dependent on the constraint. * * Note that the constraint has a dependency on the table, so we don't * need (or want) any direct dependency from the index to the table. */ myself.classId = RelationRelationId; myself.objectId = indexRelationId; myself.objectSubId = 0; referenced.classId = ConstraintRelationId; referenced.objectId = conOid; referenced.objectSubId = 0; recordDependencyOn(&myself, &referenced, DEPENDENCY_INTERNAL); /* * If the constraint is deferrable, create the deferred uniqueness * checking trigger. (The trigger will be given an internal dependency on * the constraint by CreateTrigger.) */ if (deferrable) { RangeVar *heapRel; CreateTrigStmt *trigger; heapRel = makeRangeVar(get_namespace_name(namespaceId), pstrdup(RelationGetRelationName(heapRelation)), -1); trigger = makeNode(CreateTrigStmt); trigger->trigname = (constraintType == CONSTRAINT_PRIMARY) ? "PK_ConstraintTrigger" : "Unique_ConstraintTrigger"; trigger->relation = heapRel; trigger->funcname = SystemFuncName("unique_key_recheck"); trigger->args = NIL; trigger->row = true; trigger->timing = TRIGGER_TYPE_AFTER; trigger->events = TRIGGER_TYPE_INSERT | TRIGGER_TYPE_UPDATE; trigger->columns = NIL; trigger->whenClause = NULL; trigger->isconstraint = true; trigger->deferrable = true; trigger->initdeferred = initdeferred; trigger->constrrel = NULL; (void) CreateTrigger(trigger, NULL, conOid, indexRelationId, true); } /* * If needed, mark the table as having a primary key. We assume it can't * have been so marked already, so no need to clear the flag in the other * case. * * Note: this might better be done by callers. We do it here to avoid * exposing index_update_stats() globally, but that wouldn't be necessary * if relhaspkey went away. */ if (mark_as_primary) index_update_stats(heapRelation, true, true, -1.0); /* * If needed, mark the index as primary and/or deferred in pg_index. * * Note: When making an existing index into a constraint, caller must * have a table lock that prevents concurrent table updates; otherwise, * there is a risk that concurrent readers of the table will miss seeing * this index at all. */ if (update_pgindex && (mark_as_primary || deferrable)) { Relation pg_index; HeapTuple indexTuple; Form_pg_index indexForm; bool dirty = false; pg_index = heap_open(IndexRelationId, RowExclusiveLock); indexTuple = SearchSysCacheCopy1(INDEXRELID, ObjectIdGetDatum(indexRelationId)); if (!HeapTupleIsValid(indexTuple)) elog(ERROR, "cache lookup failed for index %u", indexRelationId); indexForm = (Form_pg_index) GETSTRUCT(indexTuple); if (mark_as_primary && !indexForm->indisprimary) { indexForm->indisprimary = true; dirty = true; } if (deferrable && indexForm->indimmediate) { indexForm->indimmediate = false; dirty = true; } if (dirty) { simple_heap_update(pg_index, &indexTuple->t_self, indexTuple); CatalogUpdateIndexes(pg_index, indexTuple); InvokeObjectPostAlterHookArg(IndexRelationId, indexRelationId, 0, InvalidOid, is_internal); } heap_freetuple(indexTuple); heap_close(pg_index, RowExclusiveLock); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'Avoid repeated name lookups during table and index DDL. If the name lookups come to different conclusions due to concurrent activity, we might perform some parts of the DDL on a different table than other parts. At least in the case of CREATE INDEX, this can be used to cause the permissions checks to be performed against a different table than the index creation, allowing for a privilege escalation attack. This changes the calling convention for DefineIndex, CreateTrigger, transformIndexStmt, transformAlterTableStmt, CheckIndexCompatible (in 9.2 and newer), and AlterTable (in 9.1 and older). In addition, CheckRelationOwnership is removed in 9.2 and newer and the calling convention is changed in older branches. A field has also been added to the Constraint node (FkConstraint in 8.4). Third-party code calling these functions or using the Constraint node will require updating. Report by Andres Freund. Patch by Robert Haas and Andres Freund, reviewed by Tom Lane. Security: CVE-2014-0062'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString) { Relation rel; ParseState *pstate; CreateStmtContext cxt; List *result; List *save_alist; ListCell *lcmd, *l; List *newcmds = NIL; bool skipValidation = true; AlterTableCmd *newcmd; LOCKMODE lockmode; /* * We must not scribble on the passed-in AlterTableStmt, so copy it. (This * is overkill, but easy.) */ stmt = (AlterTableStmt *) copyObject(stmt); /* * Determine the appropriate lock level for this list of subcommands. */ lockmode = AlterTableGetLockLevel(stmt->cmds); /* * Acquire appropriate lock on the target relation, which will be held * until end of transaction. This ensures any decisions we make here * based on the state of the relation will still be good at execution. We * must get lock now because execution will later require it; taking a * lower grade lock now and trying to upgrade later risks deadlock. Any * new commands we add after this must not upgrade the lock level * requested here. */ rel = relation_openrv_extended(stmt->relation, lockmode, stmt->missing_ok); if (rel == NULL) { /* this message is consistent with relation_openrv */ ereport(NOTICE, (errmsg("relation \"%s\" does not exist, skipping", stmt->relation->relname))); return NIL; } /* Set up pstate and CreateStmtContext */ pstate = make_parsestate(NULL); pstate->p_sourcetext = queryString; cxt.pstate = pstate; if (stmt->relkind == OBJECT_FOREIGN_TABLE) { cxt.stmtType = "ALTER FOREIGN TABLE"; cxt.isforeign = true; } else { cxt.stmtType = "ALTER TABLE"; cxt.isforeign = false; } cxt.relation = stmt->relation; cxt.rel = rel; cxt.inhRelations = NIL; cxt.isalter = true; cxt.hasoids = false; /* need not be right */ cxt.columns = NIL; cxt.ckconstraints = NIL; cxt.fkconstraints = NIL; cxt.ixconstraints = NIL; cxt.inh_indexes = NIL; cxt.blist = NIL; cxt.alist = NIL; cxt.pkey = NULL; /* * The only subtypes that currently require parse transformation handling * are ADD COLUMN and ADD CONSTRAINT. These largely re-use code from * CREATE TABLE. */ foreach(lcmd, stmt->cmds) { AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd); switch (cmd->subtype) { case AT_AddColumn: case AT_AddColumnToView: { ColumnDef *def = (ColumnDef *) cmd->def; Assert(IsA(def, ColumnDef)); transformColumnDefinition(&cxt, def); /* * If the column has a non-null default, we can't skip * validation of foreign keys. */ if (def->raw_default != NULL) skipValidation = false; /* * All constraints are processed in other ways. Remove the * original list */ def->constraints = NIL; newcmds = lappend(newcmds, cmd); break; } case AT_AddConstraint: /* * The original AddConstraint cmd node doesn't go to newcmds */ if (IsA(cmd->def, Constraint)) { transformTableConstraint(&cxt, (Constraint *) cmd->def); if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN) skipValidation = false; } else elog(ERROR, "unrecognized node type: %d", (int) nodeTag(cmd->def)); break; case AT_ProcessedConstraint: /* * Already-transformed ADD CONSTRAINT, so just make it look * like the standard case. */ cmd->subtype = AT_AddConstraint; newcmds = lappend(newcmds, cmd); break; default: newcmds = lappend(newcmds, cmd); break; } } /* * transformIndexConstraints wants cxt.alist to contain only index * statements, so transfer anything we already have into save_alist * immediately. */ save_alist = cxt.alist; cxt.alist = NIL; /* Postprocess index and FK constraints */ transformIndexConstraints(&cxt); transformFKConstraints(&cxt, skipValidation, true); /* * Push any index-creation commands into the ALTER, so that they can be * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint * subcommand has already been through transformIndexStmt. */ foreach(l, cxt.alist) { IndexStmt *idxstmt = (IndexStmt *) lfirst(l); Assert(IsA(idxstmt, IndexStmt)); idxstmt = transformIndexStmt(idxstmt, queryString); newcmd = makeNode(AlterTableCmd); newcmd->subtype = OidIsValid(idxstmt->indexOid) ? AT_AddIndexConstraint : AT_AddIndex; newcmd->def = (Node *) idxstmt; newcmds = lappend(newcmds, newcmd); } cxt.alist = NIL; /* Append any CHECK or FK constraints to the commands list */ foreach(l, cxt.ckconstraints) { newcmd = makeNode(AlterTableCmd); newcmd->subtype = AT_AddConstraint; newcmd->def = (Node *) lfirst(l); newcmds = lappend(newcmds, newcmd); } foreach(l, cxt.fkconstraints) { newcmd = makeNode(AlterTableCmd); newcmd->subtype = AT_AddConstraint; newcmd->def = (Node *) lfirst(l); newcmds = lappend(newcmds, newcmd); } /* Close rel but keep lock */ relation_close(rel, NoLock); /* * Output results. */ stmt->cmds = newcmds; result = lappend(cxt.blist, stmt); result = list_concat(result, cxt.alist); result = list_concat(result, save_alist); return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'Avoid repeated name lookups during table and index DDL. If the name lookups come to different conclusions due to concurrent activity, we might perform some parts of the DDL on a different table than other parts. At least in the case of CREATE INDEX, this can be used to cause the permissions checks to be performed against a different table than the index creation, allowing for a privilege escalation attack. This changes the calling convention for DefineIndex, CreateTrigger, transformIndexStmt, transformAlterTableStmt, CheckIndexCompatible (in 9.2 and newer), and AlterTable (in 9.1 and older). In addition, CheckRelationOwnership is removed in 9.2 and newer and the calling convention is changed in older branches. A field has also been added to the Constraint node (FkConstraint in 8.4). Third-party code calling these functions or using the Constraint node will require updating. Report by Andres Freund. Patch by Robert Haas and Andres Freund, reviewed by Tom Lane. Security: CVE-2014-0062'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: CheckRelationOwnership(RangeVar *rel, bool noCatalogs) { Oid relOid; HeapTuple tuple; /* * XXX: This is unsafe in the presence of concurrent DDL, since it is * called before acquiring any lock on the target relation. However, * locking the target relation (especially using something like * AccessExclusiveLock) before verifying that the user has permissions is * not appealing either. */ relOid = RangeVarGetRelid(rel, NoLock, false); tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid)); if (!HeapTupleIsValid(tuple)) /* should not happen */ elog(ERROR, "cache lookup failed for relation %u", relOid); if (!pg_class_ownercheck(relOid, GetUserId())) aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS, rel->relname); if (noCatalogs) { if (!allowSystemTableMods && IsSystemClass(relOid, (Form_pg_class) GETSTRUCT(tuple))) ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), errmsg("permission denied: \"%s\" is a system catalog", rel->relname))); } ReleaseSysCache(tuple); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'Avoid repeated name lookups during table and index DDL. If the name lookups come to different conclusions due to concurrent activity, we might perform some parts of the DDL on a different table than other parts. At least in the case of CREATE INDEX, this can be used to cause the permissions checks to be performed against a different table than the index creation, allowing for a privilege escalation attack. This changes the calling convention for DefineIndex, CreateTrigger, transformIndexStmt, transformAlterTableStmt, CheckIndexCompatible (in 9.2 and newer), and AlterTable (in 9.1 and older). In addition, CheckRelationOwnership is removed in 9.2 and newer and the calling convention is changed in older branches. A field has also been added to the Constraint node (FkConstraint in 8.4). Third-party code calling these functions or using the Constraint node will require updating. Report by Andres Freund. Patch by Robert Haas and Andres Freund, reviewed by Tom Lane. Security: CVE-2014-0062'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TryReuseIndex(Oid oldId, IndexStmt *stmt) { if (CheckIndexCompatible(oldId, stmt->relation, stmt->accessMethod, stmt->indexParams, stmt->excludeOpNames)) { Relation irel = index_open(oldId, NoLock); stmt->oldNode = irel->rd_node.relNode; index_close(irel, NoLock); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'Avoid repeated name lookups during table and index DDL. If the name lookups come to different conclusions due to concurrent activity, we might perform some parts of the DDL on a different table than other parts. At least in the case of CREATE INDEX, this can be used to cause the permissions checks to be performed against a different table than the index creation, allowing for a privilege escalation attack. This changes the calling convention for DefineIndex, CreateTrigger, transformIndexStmt, transformAlterTableStmt, CheckIndexCompatible (in 9.2 and newer), and AlterTable (in 9.1 and older). In addition, CheckRelationOwnership is removed in 9.2 and newer and the calling convention is changed in older branches. A field has also been added to the Constraint node (FkConstraint in 8.4). Third-party code calling these functions or using the Constraint node will require updating. Report by Andres Freund. Patch by Robert Haas and Andres Freund, reviewed by Tom Lane. Security: CVE-2014-0062'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: CreateTrigger(CreateTrigStmt *stmt, const char *queryString, Oid constraintOid, Oid indexOid, bool isInternal) { int16 tgtype; int ncolumns; int16 *columns; int2vector *tgattr; Node *whenClause; List *whenRtable; char *qual; Datum values[Natts_pg_trigger]; bool nulls[Natts_pg_trigger]; Relation rel; AclResult aclresult; Relation tgrel; SysScanDesc tgscan; ScanKeyData key; Relation pgrel; HeapTuple tuple; Oid fargtypes[1]; /* dummy */ Oid funcoid; Oid funcrettype; Oid trigoid; char internaltrigname[NAMEDATALEN]; char *trigname; Oid constrrelid = InvalidOid; ObjectAddress myself, referenced; rel = heap_openrv(stmt->relation, AccessExclusiveLock); /* * Triggers must be on tables or views, and there are additional * relation-type-specific restrictions. */ if (rel->rd_rel->relkind == RELKIND_RELATION) { /* Tables can't have INSTEAD OF triggers */ if (stmt->timing != TRIGGER_TYPE_BEFORE && stmt->timing != TRIGGER_TYPE_AFTER) ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("\"%s\" is a table", RelationGetRelationName(rel)), errdetail("Tables cannot have INSTEAD OF triggers."))); } else if (rel->rd_rel->relkind == RELKIND_VIEW) { /* * Views can have INSTEAD OF triggers (which we check below are * row-level), or statement-level BEFORE/AFTER triggers. */ if (stmt->timing != TRIGGER_TYPE_INSTEAD && stmt->row) ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("\"%s\" is a view", RelationGetRelationName(rel)), errdetail("Views cannot have row-level BEFORE or AFTER triggers."))); /* Disallow TRUNCATE triggers on VIEWs */ if (TRIGGER_FOR_TRUNCATE(stmt->events)) ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("\"%s\" is a view", RelationGetRelationName(rel)), errdetail("Views cannot have TRUNCATE triggers."))); } else ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("\"%s\" is not a table or view", RelationGetRelationName(rel)))); if (!allowSystemTableMods && IsSystemRelation(rel)) ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), errmsg("permission denied: \"%s\" is a system catalog", RelationGetRelationName(rel)))); if (stmt->isconstraint && stmt->constrrel != NULL) { /* * We must take a lock on the target relation to protect against * concurrent drop. It's not clear that AccessShareLock is strong * enough, but we certainly need at least that much... otherwise, we * might end up creating a pg_constraint entry referencing a * nonexistent table. */ constrrelid = RangeVarGetRelid(stmt->constrrel, AccessShareLock, false); } /* permission checks */ if (!isInternal) { aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(), ACL_TRIGGER); if (aclresult != ACLCHECK_OK) aclcheck_error(aclresult, ACL_KIND_CLASS, RelationGetRelationName(rel)); if (OidIsValid(constrrelid)) { aclresult = pg_class_aclcheck(constrrelid, GetUserId(), ACL_TRIGGER); if (aclresult != ACLCHECK_OK) aclcheck_error(aclresult, ACL_KIND_CLASS, get_rel_name(constrrelid)); } } /* Compute tgtype */ TRIGGER_CLEAR_TYPE(tgtype); if (stmt->row) TRIGGER_SETT_ROW(tgtype); tgtype |= stmt->timing; tgtype |= stmt->events; /* Disallow ROW-level TRUNCATE triggers */ if (TRIGGER_FOR_ROW(tgtype) && TRIGGER_FOR_TRUNCATE(tgtype)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("TRUNCATE FOR EACH ROW triggers are not supported"))); /* INSTEAD triggers must be row-level, and can't have WHEN or columns */ if (TRIGGER_FOR_INSTEAD(tgtype)) { if (!TRIGGER_FOR_ROW(tgtype)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("INSTEAD OF triggers must be FOR EACH ROW"))); if (stmt->whenClause) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("INSTEAD OF triggers cannot have WHEN conditions"))); if (stmt->columns != NIL) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("INSTEAD OF triggers cannot have column lists"))); } /* * Parse the WHEN clause, if any */ if (stmt->whenClause) { ParseState *pstate; RangeTblEntry *rte; List *varList; ListCell *lc; /* Set up a pstate to parse with */ pstate = make_parsestate(NULL); pstate->p_sourcetext = queryString; /* * Set up RTEs for OLD and NEW references. * * 'OLD' must always have varno equal to 1 and 'NEW' equal to 2. */ rte = addRangeTableEntryForRelation(pstate, rel, makeAlias("old", NIL), false, false); addRTEtoQuery(pstate, rte, false, true, true); rte = addRangeTableEntryForRelation(pstate, rel, makeAlias("new", NIL), false, false); addRTEtoQuery(pstate, rte, false, true, true); /* Transform expression. Copy to be sure we don't modify original */ whenClause = transformWhereClause(pstate, copyObject(stmt->whenClause), EXPR_KIND_TRIGGER_WHEN, "WHEN"); /* we have to fix its collations too */ assign_expr_collations(pstate, whenClause); /* * Check for disallowed references to OLD/NEW. * * NB: pull_var_clause is okay here only because we don't allow * subselects in WHEN clauses; it would fail to examine the contents * of subselects. */ varList = pull_var_clause(whenClause, PVC_REJECT_AGGREGATES, PVC_REJECT_PLACEHOLDERS); foreach(lc, varList) { Var *var = (Var *) lfirst(lc); switch (var->varno) { case PRS2_OLD_VARNO: if (!TRIGGER_FOR_ROW(tgtype)) ereport(ERROR, (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), errmsg("statement trigger's WHEN condition cannot reference column values"), parser_errposition(pstate, var->location))); if (TRIGGER_FOR_INSERT(tgtype)) ereport(ERROR, (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), errmsg("INSERT trigger's WHEN condition cannot reference OLD values"), parser_errposition(pstate, var->location))); /* system columns are okay here */ break; case PRS2_NEW_VARNO: if (!TRIGGER_FOR_ROW(tgtype)) ereport(ERROR, (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), errmsg("statement trigger's WHEN condition cannot reference column values"), parser_errposition(pstate, var->location))); if (TRIGGER_FOR_DELETE(tgtype)) ereport(ERROR, (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), errmsg("DELETE trigger's WHEN condition cannot reference NEW values"), parser_errposition(pstate, var->location))); if (var->varattno < 0 && TRIGGER_FOR_BEFORE(tgtype)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("BEFORE trigger's WHEN condition cannot reference NEW system columns"), parser_errposition(pstate, var->location))); break; default: /* can't happen without add_missing_from, so just elog */ elog(ERROR, "trigger WHEN condition cannot contain references to other relations"); break; } } /* we'll need the rtable for recordDependencyOnExpr */ whenRtable = pstate->p_rtable; qual = nodeToString(whenClause); free_parsestate(pstate); } else { whenClause = NULL; whenRtable = NIL; qual = NULL; } /* * Find and validate the trigger function. */ funcoid = LookupFuncName(stmt->funcname, 0, fargtypes, false); if (!isInternal) { aclresult = pg_proc_aclcheck(funcoid, GetUserId(), ACL_EXECUTE); if (aclresult != ACLCHECK_OK) aclcheck_error(aclresult, ACL_KIND_PROC, NameListToString(stmt->funcname)); } funcrettype = get_func_rettype(funcoid); if (funcrettype != TRIGGEROID) { /* * We allow OPAQUE just so we can load old dump files. When we see a * trigger function declared OPAQUE, change it to TRIGGER. */ if (funcrettype == OPAQUEOID) { ereport(WARNING, (errmsg("changing return type of function %s from \"opaque\" to \"trigger\"", NameListToString(stmt->funcname)))); SetFunctionReturnType(funcoid, TRIGGEROID); } else ereport(ERROR, (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), errmsg("function %s must return type \"trigger\"", NameListToString(stmt->funcname)))); } /* * If the command is a user-entered CREATE CONSTRAINT TRIGGER command that * references one of the built-in RI_FKey trigger functions, assume it is * from a dump of a pre-7.3 foreign key constraint, and take steps to * convert this legacy representation into a regular foreign key * constraint. Ugly, but necessary for loading old dump files. */ if (stmt->isconstraint && !isInternal && list_length(stmt->args) >= 6 && (list_length(stmt->args) % 2) == 0 && RI_FKey_trigger_type(funcoid) != RI_TRIGGER_NONE) { /* Keep lock on target rel until end of xact */ heap_close(rel, NoLock); ConvertTriggerToFK(stmt, funcoid); return InvalidOid; } /* * If it's a user-entered CREATE CONSTRAINT TRIGGER command, make a * corresponding pg_constraint entry. */ if (stmt->isconstraint && !OidIsValid(constraintOid)) { /* Internal callers should have made their own constraints */ Assert(!isInternal); constraintOid = CreateConstraintEntry(stmt->trigname, RelationGetNamespace(rel), CONSTRAINT_TRIGGER, stmt->deferrable, stmt->initdeferred, true, RelationGetRelid(rel), NULL, /* no conkey */ 0, InvalidOid, /* no domain */ InvalidOid, /* no index */ InvalidOid, /* no foreign key */ NULL, NULL, NULL, NULL, 0, ' ', ' ', ' ', NULL, /* no exclusion */ NULL, /* no check constraint */ NULL, NULL, true, /* islocal */ 0, /* inhcount */ true, /* isnoinherit */ isInternal); /* is_internal */ } /* * Generate the trigger's OID now, so that we can use it in the name if * needed. */ tgrel = heap_open(TriggerRelationId, RowExclusiveLock); trigoid = GetNewOid(tgrel); /* * If trigger is internally generated, modify the provided trigger name to * ensure uniqueness by appending the trigger OID. (Callers will usually * supply a simple constant trigger name in these cases.) */ if (isInternal) { snprintf(internaltrigname, sizeof(internaltrigname), "%s_%u", stmt->trigname, trigoid); trigname = internaltrigname; } else { /* user-defined trigger; use the specified trigger name as-is */ trigname = stmt->trigname; } /* * Scan pg_trigger for existing triggers on relation. We do this only to * give a nice error message if there's already a trigger of the same * name. (The unique index on tgrelid/tgname would complain anyway.) We * can skip this for internally generated triggers, since the name * modification above should be sufficient. * * NOTE that this is cool only because we have AccessExclusiveLock on the * relation, so the trigger set won't be changing underneath us. */ if (!isInternal) { ScanKeyInit(&key, Anum_pg_trigger_tgrelid, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(rel))); tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true, NULL, 1, &key); while (HeapTupleIsValid(tuple = systable_getnext(tgscan))) { Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(tuple); if (namestrcmp(&(pg_trigger->tgname), trigname) == 0) ereport(ERROR, (errcode(ERRCODE_DUPLICATE_OBJECT), errmsg("trigger \"%s\" for relation \"%s\" already exists", trigname, stmt->relation->relname))); } systable_endscan(tgscan); } /* * Build the new pg_trigger tuple. */ memset(nulls, false, sizeof(nulls)); values[Anum_pg_trigger_tgrelid - 1] = ObjectIdGetDatum(RelationGetRelid(rel)); values[Anum_pg_trigger_tgname - 1] = DirectFunctionCall1(namein, CStringGetDatum(trigname)); values[Anum_pg_trigger_tgfoid - 1] = ObjectIdGetDatum(funcoid); values[Anum_pg_trigger_tgtype - 1] = Int16GetDatum(tgtype); values[Anum_pg_trigger_tgenabled - 1] = CharGetDatum(TRIGGER_FIRES_ON_ORIGIN); values[Anum_pg_trigger_tgisinternal - 1] = BoolGetDatum(isInternal); values[Anum_pg_trigger_tgconstrrelid - 1] = ObjectIdGetDatum(constrrelid); values[Anum_pg_trigger_tgconstrindid - 1] = ObjectIdGetDatum(indexOid); values[Anum_pg_trigger_tgconstraint - 1] = ObjectIdGetDatum(constraintOid); values[Anum_pg_trigger_tgdeferrable - 1] = BoolGetDatum(stmt->deferrable); values[Anum_pg_trigger_tginitdeferred - 1] = BoolGetDatum(stmt->initdeferred); if (stmt->args) { ListCell *le; char *args; int16 nargs = list_length(stmt->args); int len = 0; foreach(le, stmt->args) { char *ar = strVal(lfirst(le)); len += strlen(ar) + 4; for (; *ar; ar++) { if (*ar == '\\') len++; } } args = (char *) palloc(len + 1); args[0] = '\0'; foreach(le, stmt->args) { char *s = strVal(lfirst(le)); char *d = args + strlen(args); while (*s) { if (*s == '\\') *d++ = '\\'; *d++ = *s++; } strcpy(d, "\\000"); } values[Anum_pg_trigger_tgnargs - 1] = Int16GetDatum(nargs); values[Anum_pg_trigger_tgargs - 1] = DirectFunctionCall1(byteain, CStringGetDatum(args)); } else { values[Anum_pg_trigger_tgnargs - 1] = Int16GetDatum(0); values[Anum_pg_trigger_tgargs - 1] = DirectFunctionCall1(byteain, CStringGetDatum("")); } /* build column number array if it's a column-specific trigger */ ncolumns = list_length(stmt->columns); if (ncolumns == 0) columns = NULL; else { ListCell *cell; int i = 0; columns = (int16 *) palloc(ncolumns * sizeof(int16)); foreach(cell, stmt->columns) { char *name = strVal(lfirst(cell)); int16 attnum; int j; /* Lookup column name. System columns are not allowed */ attnum = attnameAttNum(rel, name, false); if (attnum == InvalidAttrNumber) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_COLUMN), errmsg("column \"%s\" of relation \"%s\" does not exist", name, RelationGetRelationName(rel)))); /* Check for duplicates */ for (j = i - 1; j >= 0; j--) { if (columns[j] == attnum) ereport(ERROR, (errcode(ERRCODE_DUPLICATE_COLUMN), errmsg("column \"%s\" specified more than once", name))); } columns[i++] = attnum; } } tgattr = buildint2vector(columns, ncolumns); values[Anum_pg_trigger_tgattr - 1] = PointerGetDatum(tgattr); /* set tgqual if trigger has WHEN clause */ if (qual) values[Anum_pg_trigger_tgqual - 1] = CStringGetTextDatum(qual); else nulls[Anum_pg_trigger_tgqual - 1] = true; tuple = heap_form_tuple(tgrel->rd_att, values, nulls); /* force tuple to have the desired OID */ HeapTupleSetOid(tuple, trigoid); /* * Insert tuple into pg_trigger. */ simple_heap_insert(tgrel, tuple); CatalogUpdateIndexes(tgrel, tuple); heap_freetuple(tuple); heap_close(tgrel, RowExclusiveLock); pfree(DatumGetPointer(values[Anum_pg_trigger_tgname - 1])); pfree(DatumGetPointer(values[Anum_pg_trigger_tgargs - 1])); pfree(DatumGetPointer(values[Anum_pg_trigger_tgattr - 1])); /* * Update relation's pg_class entry. Crucial side-effect: other backends * (and this one too!) are sent SI message to make them rebuild relcache * entries. */ pgrel = heap_open(RelationRelationId, RowExclusiveLock); tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(RelationGetRelid(rel))); if (!HeapTupleIsValid(tuple)) elog(ERROR, "cache lookup failed for relation %u", RelationGetRelid(rel)); ((Form_pg_class) GETSTRUCT(tuple))->relhastriggers = true; simple_heap_update(pgrel, &tuple->t_self, tuple); CatalogUpdateIndexes(pgrel, tuple); heap_freetuple(tuple); heap_close(pgrel, RowExclusiveLock); /* * We used to try to update the rel's relcache entry here, but that's * fairly pointless since it will happen as a byproduct of the upcoming * CommandCounterIncrement... */ /* * Record dependencies for trigger. Always place a normal dependency on * the function. */ myself.classId = TriggerRelationId; myself.objectId = trigoid; myself.objectSubId = 0; referenced.classId = ProcedureRelationId; referenced.objectId = funcoid; referenced.objectSubId = 0; recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL); if (isInternal && OidIsValid(constraintOid)) { /* * Internally-generated trigger for a constraint, so make it an * internal dependency of the constraint. We can skip depending on * the relation(s), as there'll be an indirect dependency via the * constraint. */ referenced.classId = ConstraintRelationId; referenced.objectId = constraintOid; referenced.objectSubId = 0; recordDependencyOn(&myself, &referenced, DEPENDENCY_INTERNAL); } else { /* * User CREATE TRIGGER, so place dependencies. We make trigger be * auto-dropped if its relation is dropped or if the FK relation is * dropped. (Auto drop is compatible with our pre-7.3 behavior.) */ referenced.classId = RelationRelationId; referenced.objectId = RelationGetRelid(rel); referenced.objectSubId = 0; recordDependencyOn(&myself, &referenced, DEPENDENCY_AUTO); if (OidIsValid(constrrelid)) { referenced.classId = RelationRelationId; referenced.objectId = constrrelid; referenced.objectSubId = 0; recordDependencyOn(&myself, &referenced, DEPENDENCY_AUTO); } /* Not possible to have an index dependency in this case */ Assert(!OidIsValid(indexOid)); /* * If it's a user-specified constraint trigger, make the constraint * internally dependent on the trigger instead of vice versa. */ if (OidIsValid(constraintOid)) { referenced.classId = ConstraintRelationId; referenced.objectId = constraintOid; referenced.objectSubId = 0; recordDependencyOn(&referenced, &myself, DEPENDENCY_INTERNAL); } } /* If column-specific trigger, add normal dependencies on columns */ if (columns != NULL) { int i; referenced.classId = RelationRelationId; referenced.objectId = RelationGetRelid(rel); for (i = 0; i < ncolumns; i++) { referenced.objectSubId = columns[i]; recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL); } } /* * If it has a WHEN clause, add dependencies on objects mentioned in the * expression (eg, functions, as well as any columns used). */ if (whenClause != NULL) recordDependencyOnExpr(&myself, whenClause, whenRtable, DEPENDENCY_NORMAL); /* Post creation hook for new trigger */ InvokeObjectPostCreateHookArg(TriggerRelationId, trigoid, 0, isInternal); /* Keep lock on target rel until end of xact */ heap_close(rel, NoLock); return trigoid; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'Avoid repeated name lookups during table and index DDL. If the name lookups come to different conclusions due to concurrent activity, we might perform some parts of the DDL on a different table than other parts. At least in the case of CREATE INDEX, this can be used to cause the permissions checks to be performed against a different table than the index creation, allowing for a privilege escalation attack. This changes the calling convention for DefineIndex, CreateTrigger, transformIndexStmt, transformAlterTableStmt, CheckIndexCompatible (in 9.2 and newer), and AlterTable (in 9.1 and older). In addition, CheckRelationOwnership is removed in 9.2 and newer and the calling convention is changed in older branches. A field has also been added to the Constraint node (FkConstraint in 8.4). Third-party code calling these functions or using the Constraint node will require updating. Report by Andres Freund. Patch by Robert Haas and Andres Freund, reviewed by Tom Lane. Security: CVE-2014-0062'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: createForeignKeyTriggers(Relation rel, Constraint *fkconstraint, Oid constraintOid, Oid indexOid) { RangeVar *myRel; CreateTrigStmt *fk_trigger; /* * Reconstruct a RangeVar for my relation (not passed in, unfortunately). */ myRel = makeRangeVar(get_namespace_name(RelationGetNamespace(rel)), pstrdup(RelationGetRelationName(rel)), -1); /* Make changes-so-far visible */ CommandCounterIncrement(); /* * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON * DELETE action on the referenced table. */ fk_trigger = makeNode(CreateTrigStmt); fk_trigger->trigname = "RI_ConstraintTrigger_a"; fk_trigger->relation = fkconstraint->pktable; fk_trigger->row = true; fk_trigger->timing = TRIGGER_TYPE_AFTER; fk_trigger->events = TRIGGER_TYPE_DELETE; fk_trigger->columns = NIL; fk_trigger->whenClause = NULL; fk_trigger->isconstraint = true; fk_trigger->constrrel = myRel; switch (fkconstraint->fk_del_action) { case FKCONSTR_ACTION_NOACTION: fk_trigger->deferrable = fkconstraint->deferrable; fk_trigger->initdeferred = fkconstraint->initdeferred; fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del"); break; case FKCONSTR_ACTION_RESTRICT: fk_trigger->deferrable = false; fk_trigger->initdeferred = false; fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del"); break; case FKCONSTR_ACTION_CASCADE: fk_trigger->deferrable = false; fk_trigger->initdeferred = false; fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del"); break; case FKCONSTR_ACTION_SETNULL: fk_trigger->deferrable = false; fk_trigger->initdeferred = false; fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del"); break; case FKCONSTR_ACTION_SETDEFAULT: fk_trigger->deferrable = false; fk_trigger->initdeferred = false; fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del"); break; default: elog(ERROR, "unrecognized FK action type: %d", (int) fkconstraint->fk_del_action); break; } fk_trigger->args = NIL; (void) CreateTrigger(fk_trigger, NULL, constraintOid, indexOid, true); /* Make changes-so-far visible */ CommandCounterIncrement(); /* * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON * UPDATE action on the referenced table. */ fk_trigger = makeNode(CreateTrigStmt); fk_trigger->trigname = "RI_ConstraintTrigger_a"; fk_trigger->relation = fkconstraint->pktable; fk_trigger->row = true; fk_trigger->timing = TRIGGER_TYPE_AFTER; fk_trigger->events = TRIGGER_TYPE_UPDATE; fk_trigger->columns = NIL; fk_trigger->whenClause = NULL; fk_trigger->isconstraint = true; fk_trigger->constrrel = myRel; switch (fkconstraint->fk_upd_action) { case FKCONSTR_ACTION_NOACTION: fk_trigger->deferrable = fkconstraint->deferrable; fk_trigger->initdeferred = fkconstraint->initdeferred; fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd"); break; case FKCONSTR_ACTION_RESTRICT: fk_trigger->deferrable = false; fk_trigger->initdeferred = false; fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd"); break; case FKCONSTR_ACTION_CASCADE: fk_trigger->deferrable = false; fk_trigger->initdeferred = false; fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd"); break; case FKCONSTR_ACTION_SETNULL: fk_trigger->deferrable = false; fk_trigger->initdeferred = false; fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd"); break; case FKCONSTR_ACTION_SETDEFAULT: fk_trigger->deferrable = false; fk_trigger->initdeferred = false; fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd"); break; default: elog(ERROR, "unrecognized FK action type: %d", (int) fkconstraint->fk_upd_action); break; } fk_trigger->args = NIL; (void) CreateTrigger(fk_trigger, NULL, constraintOid, indexOid, true); /* Make changes-so-far visible */ CommandCounterIncrement(); /* * Build and execute CREATE CONSTRAINT TRIGGER statements for the CHECK * action for both INSERTs and UPDATEs on the referencing table. */ CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, indexOid, true); CreateFKCheckTrigger(myRel, fkconstraint, constraintOid, indexOid, false); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'Avoid repeated name lookups during table and index DDL. If the name lookups come to different conclusions due to concurrent activity, we might perform some parts of the DDL on a different table than other parts. At least in the case of CREATE INDEX, this can be used to cause the permissions checks to be performed against a different table than the index creation, allowing for a privilege escalation attack. This changes the calling convention for DefineIndex, CreateTrigger, transformIndexStmt, transformAlterTableStmt, CheckIndexCompatible (in 9.2 and newer), and AlterTable (in 9.1 and older). In addition, CheckRelationOwnership is removed in 9.2 and newer and the calling convention is changed in older branches. A field has also been added to the Constraint node (FkConstraint in 8.4). Third-party code calling these functions or using the Constraint node will require updating. Report by Andres Freund. Patch by Robert Haas and Andres Freund, reviewed by Tom Lane. Security: CVE-2014-0062'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: _copyConstraint(const Constraint *from) { Constraint *newnode = makeNode(Constraint); COPY_SCALAR_FIELD(contype); COPY_STRING_FIELD(conname); COPY_SCALAR_FIELD(deferrable); COPY_SCALAR_FIELD(initdeferred); COPY_LOCATION_FIELD(location); COPY_SCALAR_FIELD(is_no_inherit); COPY_NODE_FIELD(raw_expr); COPY_STRING_FIELD(cooked_expr); COPY_NODE_FIELD(keys); COPY_NODE_FIELD(exclusions); COPY_NODE_FIELD(options); COPY_STRING_FIELD(indexname); COPY_STRING_FIELD(indexspace); COPY_STRING_FIELD(access_method); COPY_NODE_FIELD(where_clause); COPY_NODE_FIELD(pktable); COPY_NODE_FIELD(fk_attrs); COPY_NODE_FIELD(pk_attrs); COPY_SCALAR_FIELD(fk_matchtype); COPY_SCALAR_FIELD(fk_upd_action); COPY_SCALAR_FIELD(fk_del_action); COPY_NODE_FIELD(old_conpfeqop); COPY_SCALAR_FIELD(skip_validation); COPY_SCALAR_FIELD(initially_valid); return newnode; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'Avoid repeated name lookups during table and index DDL. If the name lookups come to different conclusions due to concurrent activity, we might perform some parts of the DDL on a different table than other parts. At least in the case of CREATE INDEX, this can be used to cause the permissions checks to be performed against a different table than the index creation, allowing for a privilege escalation attack. This changes the calling convention for DefineIndex, CreateTrigger, transformIndexStmt, transformAlterTableStmt, CheckIndexCompatible (in 9.2 and newer), and AlterTable (in 9.1 and older). In addition, CheckRelationOwnership is removed in 9.2 and newer and the calling convention is changed in older branches. A field has also been added to the Constraint node (FkConstraint in 8.4). Third-party code calling these functions or using the Constraint node will require updating. Report by Andres Freund. Patch by Robert Haas and Andres Freund, reviewed by Tom Lane. Security: CVE-2014-0062'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: _equalConstraint(const Constraint *a, const Constraint *b) { COMPARE_SCALAR_FIELD(contype); COMPARE_STRING_FIELD(conname); COMPARE_SCALAR_FIELD(deferrable); COMPARE_SCALAR_FIELD(initdeferred); COMPARE_LOCATION_FIELD(location); COMPARE_SCALAR_FIELD(is_no_inherit); COMPARE_NODE_FIELD(raw_expr); COMPARE_STRING_FIELD(cooked_expr); COMPARE_NODE_FIELD(keys); COMPARE_NODE_FIELD(exclusions); COMPARE_NODE_FIELD(options); COMPARE_STRING_FIELD(indexname); COMPARE_STRING_FIELD(indexspace); COMPARE_STRING_FIELD(access_method); COMPARE_NODE_FIELD(where_clause); COMPARE_NODE_FIELD(pktable); COMPARE_NODE_FIELD(fk_attrs); COMPARE_NODE_FIELD(pk_attrs); COMPARE_SCALAR_FIELD(fk_matchtype); COMPARE_SCALAR_FIELD(fk_upd_action); COMPARE_SCALAR_FIELD(fk_del_action); COMPARE_NODE_FIELD(old_conpfeqop); COMPARE_SCALAR_FIELD(skip_validation); COMPARE_SCALAR_FIELD(initially_valid); return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'Avoid repeated name lookups during table and index DDL. If the name lookups come to different conclusions due to concurrent activity, we might perform some parts of the DDL on a different table than other parts. At least in the case of CREATE INDEX, this can be used to cause the permissions checks to be performed against a different table than the index creation, allowing for a privilege escalation attack. This changes the calling convention for DefineIndex, CreateTrigger, transformIndexStmt, transformAlterTableStmt, CheckIndexCompatible (in 9.2 and newer), and AlterTable (in 9.1 and older). In addition, CheckRelationOwnership is removed in 9.2 and newer and the calling convention is changed in older branches. A field has also been added to the Constraint node (FkConstraint in 8.4). Third-party code calling these functions or using the Constraint node will require updating. Report by Andres Freund. Patch by Robert Haas and Andres Freund, reviewed by Tom Lane. Security: CVE-2014-0062'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PGTYPESdate_from_asc(char *str, char **endptr) { date dDate; fsec_t fsec; struct tm tt, *tm = &tt; int dtype; int nf; char *field[MAXDATEFIELDS]; int ftype[MAXDATEFIELDS]; char lowstr[MAXDATELEN + 1]; char *realptr; char **ptr = (endptr != NULL) ? endptr : &realptr; bool EuroDates = FALSE; errno = 0; if (strlen(str) >= sizeof(lowstr)) { errno = PGTYPES_DATE_BAD_DATE; return INT_MIN; } if (ParseDateTime(str, lowstr, field, ftype, &nf, ptr) != 0 || DecodeDateTime(field, ftype, nf, &dtype, tm, &fsec, EuroDates) != 0) { errno = PGTYPES_DATE_BAD_DATE; return INT_MIN; } switch (dtype) { case DTK_DATE: break; case DTK_EPOCH: if (GetEpochTime(tm) < 0) { errno = PGTYPES_DATE_BAD_DATE; return INT_MIN; } break; default: errno = PGTYPES_DATE_BAD_DATE; return INT_MIN; } dDate = (date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - date2j(2000, 1, 1)); return dDate; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-119'], 'message': 'Fix handling of wide datetime input/output. Many server functions use the MAXDATELEN constant to size a buffer for parsing or displaying a datetime value. It was much too small for the longest possible interval output and slightly too small for certain valid timestamp input, particularly input with a long timezone name. The long input was rejected needlessly; the long output caused interval_out() to overrun its buffer. ECPG's pgtypes library has a copy of the vulnerable functions, which bore the same vulnerabilities along with some of its own. In contrast to the server, certain long inputs caused stack overflow rather than failing cleanly. Back-patch to 8.4 (all supported versions). Reported by Daniel Schüssler, reviewed by Tom Lane. Security: CVE-2014-0063'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PGTYPESinterval_from_asc(char *str, char **endptr) { interval *result = NULL; fsec_t fsec; struct tm tt, *tm = &tt; int dtype; int nf; char *field[MAXDATEFIELDS]; int ftype[MAXDATEFIELDS]; char lowstr[MAXDATELEN + MAXDATEFIELDS]; char *realptr; char **ptr = (endptr != NULL) ? endptr : &realptr; tm->tm_year = 0; tm->tm_mon = 0; tm->tm_mday = 0; tm->tm_hour = 0; tm->tm_min = 0; tm->tm_sec = 0; fsec = 0; if (strlen(str) >= sizeof(lowstr)) { errno = PGTYPES_INTVL_BAD_INTERVAL; return NULL; } if (ParseDateTime(str, lowstr, field, ftype, &nf, ptr) != 0 || (DecodeInterval(field, ftype, nf, &dtype, tm, &fsec) != 0 && DecodeISO8601Interval(str, &dtype, tm, &fsec) != 0)) { errno = PGTYPES_INTVL_BAD_INTERVAL; return NULL; } result = (interval *) pgtypes_alloc(sizeof(interval)); if (!result) return NULL; if (dtype != DTK_DELTA) { errno = PGTYPES_INTVL_BAD_INTERVAL; free(result); return NULL; } if (tm2interval(tm, fsec, result) != 0) { errno = PGTYPES_INTVL_BAD_INTERVAL; free(result); return NULL; } errno = 0; return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-119'], 'message': 'Fix handling of wide datetime input/output. Many server functions use the MAXDATELEN constant to size a buffer for parsing or displaying a datetime value. It was much too small for the longest possible interval output and slightly too small for certain valid timestamp input, particularly input with a long timezone name. The long input was rejected needlessly; the long output caused interval_out() to overrun its buffer. ECPG's pgtypes library has a copy of the vulnerable functions, which bore the same vulnerabilities along with some of its own. In contrast to the server, certain long inputs caused stack overflow rather than failing cleanly. Back-patch to 8.4 (all supported versions). Reported by Daniel Schüssler, reviewed by Tom Lane. Security: CVE-2014-0063'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: poly_path(PG_FUNCTION_ARGS) { POLYGON *poly = PG_GETARG_POLYGON_P(0); PATH *path; int size; int i; size = offsetof(PATH, p[0]) +sizeof(path->p[0]) * poly->npts; path = (PATH *) palloc(size); SET_VARSIZE(path, size); path->npts = poly->npts; path->closed = TRUE; /* prevent instability in unused pad bytes */ path->dummy = 0; for (i = 0; i < poly->npts; i++) { path->p[i].x = poly->p[i].x; path->p[i].y = poly->p[i].y; } PG_RETURN_PATH_P(path); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Predict integer overflow to avoid buffer overruns. Several functions, mostly type input functions, calculated an allocation size such that the calculation wrapped to a small positive value when arguments implied a sufficiently-large requirement. Writes past the end of the inadvertent small allocation followed shortly thereafter. Coverity identified the path_in() vulnerability; code inspection led to the rest. In passing, add check_stack_depth() to prevent stack overflow in related functions. Back-patch to 8.4 (all supported versions). The non-comment hstore changes touch code that did not exist in 8.4, so that part stops at 9.0. Noah Misch and Heikki Linnakangas, reviewed by Tom Lane. Security: CVE-2014-0064'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: makepol(QPRS_STATE *state) { int32 val = 0, type; int32 lenval = 0; char *strval = NULL; int32 stack[STACKDEPTH]; int32 lenstack = 0; uint16 flag = 0; while ((type = gettoken_query(state, &val, &lenval, &strval, &flag)) != END) { switch (type) { case VAL: pushval_asis(state, VAL, strval, lenval, flag); while (lenstack && (stack[lenstack - 1] == (int32) '&' || stack[lenstack - 1] == (int32) '!')) { lenstack--; pushquery(state, OPR, stack[lenstack], 0, 0, 0); } break; case OPR: if (lenstack && val == (int32) '|') pushquery(state, OPR, val, 0, 0, 0); else { if (lenstack == STACKDEPTH) /* internal error */ elog(ERROR, "stack too short"); stack[lenstack] = val; lenstack++; } break; case OPEN: if (makepol(state) == ERR) return ERR; while (lenstack && (stack[lenstack - 1] == (int32) '&' || stack[lenstack - 1] == (int32) '!')) { lenstack--; pushquery(state, OPR, stack[lenstack], 0, 0, 0); } break; case CLOSE: while (lenstack) { lenstack--; pushquery(state, OPR, stack[lenstack], 0, 0, 0); }; return END; break; case ERR: default: ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("syntax error"))); return ERR; } } while (lenstack) { lenstack--; pushquery(state, OPR, stack[lenstack], 0, 0, 0); }; return END; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Predict integer overflow to avoid buffer overruns. Several functions, mostly type input functions, calculated an allocation size such that the calculation wrapped to a small positive value when arguments implied a sufficiently-large requirement. Writes past the end of the inadvertent small allocation followed shortly thereafter. Coverity identified the path_in() vulnerability; code inspection led to the rest. In passing, add check_stack_depth() to prevent stack overflow in related functions. Back-patch to 8.4 (all supported versions). The non-comment hstore changes touch code that did not exist in 8.4, so that part stops at 9.0. Noah Misch and Heikki Linnakangas, reviewed by Tom Lane. Security: CVE-2014-0064'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: hstoreArrayToPairs(ArrayType *a, int *npairs) { Datum *key_datums; bool *key_nulls; int key_count; Pairs *key_pairs; int bufsiz; int i, j; deconstruct_array(a, TEXTOID, -1, false, 'i', &key_datums, &key_nulls, &key_count); if (key_count == 0) { *npairs = 0; return NULL; } key_pairs = palloc(sizeof(Pairs) * key_count); for (i = 0, j = 0; i < key_count; i++) { if (!key_nulls[i]) { key_pairs[j].key = VARDATA(key_datums[i]); key_pairs[j].keylen = VARSIZE(key_datums[i]) - VARHDRSZ; key_pairs[j].val = NULL; key_pairs[j].vallen = 0; key_pairs[j].needfree = 0; key_pairs[j].isnull = 1; j++; } } *npairs = hstoreUniquePairs(key_pairs, j, &bufsiz); return key_pairs; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Predict integer overflow to avoid buffer overruns. Several functions, mostly type input functions, calculated an allocation size such that the calculation wrapped to a small positive value when arguments implied a sufficiently-large requirement. Writes past the end of the inadvertent small allocation followed shortly thereafter. Coverity identified the path_in() vulnerability; code inspection led to the rest. In passing, add check_stack_depth() to prevent stack overflow in related functions. Back-patch to 8.4 (all supported versions). The non-comment hstore changes touch code that did not exist in 8.4, so that part stops at 9.0. Noah Misch and Heikki Linnakangas, reviewed by Tom Lane. Security: CVE-2014-0064'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: poly_in(PG_FUNCTION_ARGS) { char *str = PG_GETARG_CSTRING(0); POLYGON *poly; int npts; int size; int isopen; char *s; if ((npts = pair_count(str, ',')) <= 0) ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("invalid input syntax for type polygon: \"%s\"", str))); size = offsetof(POLYGON, p[0]) +sizeof(poly->p[0]) * npts; poly = (POLYGON *) palloc0(size); /* zero any holes */ SET_VARSIZE(poly, size); poly->npts = npts; if ((!path_decode(FALSE, npts, str, &isopen, &s, &(poly->p[0]))) || (*s != '\0')) ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("invalid input syntax for type polygon: \"%s\"", str))); make_bound_box(poly); PG_RETURN_POLYGON_P(poly); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Predict integer overflow to avoid buffer overruns. Several functions, mostly type input functions, calculated an allocation size such that the calculation wrapped to a small positive value when arguments implied a sufficiently-large requirement. Writes past the end of the inadvertent small allocation followed shortly thereafter. Coverity identified the path_in() vulnerability; code inspection led to the rest. In passing, add check_stack_depth() to prevent stack overflow in related functions. Back-patch to 8.4 (all supported versions). The non-comment hstore changes touch code that did not exist in 8.4, so that part stops at 9.0. Noah Misch and Heikki Linnakangas, reviewed by Tom Lane. Security: CVE-2014-0064'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: lquery_in(PG_FUNCTION_ARGS) { char *buf = (char *) PG_GETARG_POINTER(0); char *ptr; int num = 0, totallen = 0, numOR = 0; int state = LQPRS_WAITLEVEL; lquery *result; nodeitem *lptr = NULL; lquery_level *cur, *curqlevel, *tmpql; lquery_variant *lrptr = NULL; bool hasnot = false; bool wasbad = false; int charlen; int pos = 0; ptr = buf; while (*ptr) { charlen = pg_mblen(ptr); if (charlen == 1) { if (t_iseq(ptr, '.')) num++; else if (t_iseq(ptr, '|')) numOR++; } ptr += charlen; } num++; curqlevel = tmpql = (lquery_level *) palloc0(ITEMSIZE * num); ptr = buf; while (*ptr) { charlen = pg_mblen(ptr); if (state == LQPRS_WAITLEVEL) { if (ISALNUM(ptr)) { GETVAR(curqlevel) = lptr = (nodeitem *) palloc0(sizeof(nodeitem) * (numOR + 1)); lptr->start = ptr; state = LQPRS_WAITDELIM; curqlevel->numvar = 1; } else if (charlen == 1 && t_iseq(ptr, '!')) { GETVAR(curqlevel) = lptr = (nodeitem *) palloc0(sizeof(nodeitem) * (numOR + 1)); lptr->start = ptr + 1; state = LQPRS_WAITDELIM; curqlevel->numvar = 1; curqlevel->flag |= LQL_NOT; hasnot = true; } else if (charlen == 1 && t_iseq(ptr, '*')) state = LQPRS_WAITOPEN; else UNCHAR; } else if (state == LQPRS_WAITVAR) { if (ISALNUM(ptr)) { lptr++; lptr->start = ptr; state = LQPRS_WAITDELIM; curqlevel->numvar++; } else UNCHAR; } else if (state == LQPRS_WAITDELIM) { if (charlen == 1 && t_iseq(ptr, '@')) { if (lptr->start == ptr) UNCHAR; lptr->flag |= LVAR_INCASE; curqlevel->flag |= LVAR_INCASE; } else if (charlen == 1 && t_iseq(ptr, '*')) { if (lptr->start == ptr) UNCHAR; lptr->flag |= LVAR_ANYEND; curqlevel->flag |= LVAR_ANYEND; } else if (charlen == 1 && t_iseq(ptr, '%')) { if (lptr->start == ptr) UNCHAR; lptr->flag |= LVAR_SUBLEXEME; curqlevel->flag |= LVAR_SUBLEXEME; } else if (charlen == 1 && t_iseq(ptr, '|')) { lptr->len = ptr - lptr->start - ((lptr->flag & LVAR_SUBLEXEME) ? 1 : 0) - ((lptr->flag & LVAR_INCASE) ? 1 : 0) - ((lptr->flag & LVAR_ANYEND) ? 1 : 0); if (lptr->wlen > 255) ereport(ERROR, (errcode(ERRCODE_NAME_TOO_LONG), errmsg("name of level is too long"), errdetail("Name length is %d, must " "be < 256, in position %d.", lptr->wlen, pos))); state = LQPRS_WAITVAR; } else if (charlen == 1 && t_iseq(ptr, '.')) { lptr->len = ptr - lptr->start - ((lptr->flag & LVAR_SUBLEXEME) ? 1 : 0) - ((lptr->flag & LVAR_INCASE) ? 1 : 0) - ((lptr->flag & LVAR_ANYEND) ? 1 : 0); if (lptr->wlen > 255) ereport(ERROR, (errcode(ERRCODE_NAME_TOO_LONG), errmsg("name of level is too long"), errdetail("Name length is %d, must " "be < 256, in position %d.", lptr->wlen, pos))); state = LQPRS_WAITLEVEL; curqlevel = NEXTLEV(curqlevel); } else if (ISALNUM(ptr)) { if (lptr->flag) UNCHAR; } else UNCHAR; } else if (state == LQPRS_WAITOPEN) { if (charlen == 1 && t_iseq(ptr, '{')) state = LQPRS_WAITFNUM; else if (charlen == 1 && t_iseq(ptr, '.')) { curqlevel->low = 0; curqlevel->high = 0xffff; curqlevel = NEXTLEV(curqlevel); state = LQPRS_WAITLEVEL; } else UNCHAR; } else if (state == LQPRS_WAITFNUM) { if (charlen == 1 && t_iseq(ptr, ',')) state = LQPRS_WAITSNUM; else if (t_isdigit(ptr)) { curqlevel->low = atoi(ptr); state = LQPRS_WAITND; } else UNCHAR; } else if (state == LQPRS_WAITSNUM) { if (t_isdigit(ptr)) { curqlevel->high = atoi(ptr); state = LQPRS_WAITCLOSE; } else if (charlen == 1 && t_iseq(ptr, '}')) { curqlevel->high = 0xffff; state = LQPRS_WAITEND; } else UNCHAR; } else if (state == LQPRS_WAITCLOSE) { if (charlen == 1 && t_iseq(ptr, '}')) state = LQPRS_WAITEND; else if (!t_isdigit(ptr)) UNCHAR; } else if (state == LQPRS_WAITND) { if (charlen == 1 && t_iseq(ptr, '}')) { curqlevel->high = curqlevel->low; state = LQPRS_WAITEND; } else if (charlen == 1 && t_iseq(ptr, ',')) state = LQPRS_WAITSNUM; else if (!t_isdigit(ptr)) UNCHAR; } else if (state == LQPRS_WAITEND) { if (charlen == 1 && t_iseq(ptr, '.')) { state = LQPRS_WAITLEVEL; curqlevel = NEXTLEV(curqlevel); } else UNCHAR; } else /* internal error */ elog(ERROR, "internal error in parser"); ptr += charlen; if (state == LQPRS_WAITDELIM) lptr->wlen++; pos++; } if (state == LQPRS_WAITDELIM) { if (lptr->start == ptr) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("syntax error"), errdetail("Unexpected end of line."))); lptr->len = ptr - lptr->start - ((lptr->flag & LVAR_SUBLEXEME) ? 1 : 0) - ((lptr->flag & LVAR_INCASE) ? 1 : 0) - ((lptr->flag & LVAR_ANYEND) ? 1 : 0); if (lptr->len == 0) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("syntax error"), errdetail("Unexpected end of line."))); if (lptr->wlen > 255) ereport(ERROR, (errcode(ERRCODE_NAME_TOO_LONG), errmsg("name of level is too long"), errdetail("Name length is %d, must " "be < 256, in position %d.", lptr->wlen, pos))); } else if (state == LQPRS_WAITOPEN) curqlevel->high = 0xffff; else if (state != LQPRS_WAITEND) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("syntax error"), errdetail("Unexpected end of line."))); curqlevel = tmpql; totallen = LQUERY_HDRSIZE; while ((char *) curqlevel - (char *) tmpql < num * ITEMSIZE) { totallen += LQL_HDRSIZE; if (curqlevel->numvar) { lptr = GETVAR(curqlevel); while (lptr - GETVAR(curqlevel) < curqlevel->numvar) { totallen += MAXALIGN(LVAR_HDRSIZE + lptr->len); lptr++; } } else if (curqlevel->low > curqlevel->high) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("syntax error"), errdetail("Low limit(%d) is greater than upper(%d).", curqlevel->low, curqlevel->high))); curqlevel = NEXTLEV(curqlevel); } result = (lquery *) palloc0(totallen); SET_VARSIZE(result, totallen); result->numlevel = num; result->firstgood = 0; result->flag = 0; if (hasnot) result->flag |= LQUERY_HASNOT; cur = LQUERY_FIRST(result); curqlevel = tmpql; while ((char *) curqlevel - (char *) tmpql < num * ITEMSIZE) { memcpy(cur, curqlevel, LQL_HDRSIZE); cur->totallen = LQL_HDRSIZE; if (curqlevel->numvar) { lrptr = LQL_FIRST(cur); lptr = GETVAR(curqlevel); while (lptr - GETVAR(curqlevel) < curqlevel->numvar) { cur->totallen += MAXALIGN(LVAR_HDRSIZE + lptr->len); lrptr->len = lptr->len; lrptr->flag = lptr->flag; lrptr->val = ltree_crc32_sz(lptr->start, lptr->len); memcpy(lrptr->name, lptr->start, lptr->len); lptr++; lrptr = LVAR_NEXT(lrptr); } pfree(GETVAR(curqlevel)); if (cur->numvar > 1 || cur->flag != 0) wasbad = true; else if (wasbad == false) (result->firstgood)++; } else wasbad = true; curqlevel = NEXTLEV(curqlevel); cur = LQL_NEXT(cur); } pfree(tmpql); PG_RETURN_POINTER(result); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Predict integer overflow to avoid buffer overruns. Several functions, mostly type input functions, calculated an allocation size such that the calculation wrapped to a small positive value when arguments implied a sufficiently-large requirement. Writes past the end of the inadvertent small allocation followed shortly thereafter. Coverity identified the path_in() vulnerability; code inspection led to the rest. In passing, add check_stack_depth() to prevent stack overflow in related functions. Back-patch to 8.4 (all supported versions). The non-comment hstore changes touch code that did not exist in 8.4, so that part stops at 9.0. Noah Misch and Heikki Linnakangas, reviewed by Tom Lane. Security: CVE-2014-0064'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: hstore_slice_to_hstore(PG_FUNCTION_ARGS) { HStore *hs = PG_GETARG_HS(0); HEntry *entries = ARRPTR(hs); char *ptr = STRPTR(hs); ArrayType *key_array = PG_GETARG_ARRAYTYPE_P(1); HStore *out; int nkeys; Pairs *key_pairs = hstoreArrayToPairs(key_array, &nkeys); Pairs *out_pairs; int bufsiz; int lastidx = 0; int i; int out_count = 0; if (nkeys == 0) { out = hstorePairs(NULL, 0, 0); PG_RETURN_POINTER(out); } out_pairs = palloc(sizeof(Pairs) * nkeys); bufsiz = 0; /* * we exploit the fact that the pairs list is already sorted into strictly * increasing order to narrow the hstoreFindKey search; each search can * start one entry past the previous "found" entry, or at the lower bound * of the last search. */ for (i = 0; i < nkeys; ++i) { int idx = hstoreFindKey(hs, &lastidx, key_pairs[i].key, key_pairs[i].keylen); if (idx >= 0) { out_pairs[out_count].key = key_pairs[i].key; bufsiz += (out_pairs[out_count].keylen = key_pairs[i].keylen); out_pairs[out_count].val = HS_VAL(entries, ptr, idx); bufsiz += (out_pairs[out_count].vallen = HS_VALLEN(entries, idx)); out_pairs[out_count].isnull = HS_VALISNULL(entries, idx); out_pairs[out_count].needfree = false; ++out_count; } } /* * we don't use uniquePairs here because we know that the pairs list is * already sorted and uniq'ed. */ out = hstorePairs(out_pairs, out_count, bufsiz); PG_RETURN_POINTER(out); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Predict integer overflow to avoid buffer overruns. Several functions, mostly type input functions, calculated an allocation size such that the calculation wrapped to a small positive value when arguments implied a sufficiently-large requirement. Writes past the end of the inadvertent small allocation followed shortly thereafter. Coverity identified the path_in() vulnerability; code inspection led to the rest. In passing, add check_stack_depth() to prevent stack overflow in related functions. Back-patch to 8.4 (all supported versions). The non-comment hstore changes touch code that did not exist in 8.4, so that part stops at 9.0. Noah Misch and Heikki Linnakangas, reviewed by Tom Lane. Security: CVE-2014-0064'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: varbit_in(PG_FUNCTION_ARGS) { char *input_string = PG_GETARG_CSTRING(0); #ifdef NOT_USED Oid typelem = PG_GETARG_OID(1); #endif int32 atttypmod = PG_GETARG_INT32(2); VarBit *result; /* The resulting bit string */ char *sp; /* pointer into the character string */ bits8 *r; /* pointer into the result */ int len, /* Length of the whole data structure */ bitlen, /* Number of bits in the bit string */ slen; /* Length of the input string */ bool bit_not_hex; /* false = hex string true = bit string */ int bc; bits8 x = 0; /* Check that the first character is a b or an x */ if (input_string[0] == 'b' || input_string[0] == 'B') { bit_not_hex = true; sp = input_string + 1; } else if (input_string[0] == 'x' || input_string[0] == 'X') { bit_not_hex = false; sp = input_string + 1; } else { bit_not_hex = true; sp = input_string; } slen = strlen(sp); /* Determine bitlength from input string */ if (bit_not_hex) bitlen = slen; else bitlen = slen * 4; /* * Sometimes atttypmod is not supplied. If it is supplied we need to make * sure that the bitstring fits. */ if (atttypmod <= 0) atttypmod = bitlen; else if (bitlen > atttypmod) ereport(ERROR, (errcode(ERRCODE_STRING_DATA_RIGHT_TRUNCATION), errmsg("bit string too long for type bit varying(%d)", atttypmod))); len = VARBITTOTALLEN(bitlen); /* set to 0 so that *r is always initialised and string is zero-padded */ result = (VarBit *) palloc0(len); SET_VARSIZE(result, len); VARBITLEN(result) = Min(bitlen, atttypmod); r = VARBITS(result); if (bit_not_hex) { /* Parse the bit representation of the string */ /* We know it fits, as bitlen was compared to atttypmod */ x = HIGHBIT; for (; *sp; sp++) { if (*sp == '1') *r |= x; else if (*sp != '0') ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("\"%c\" is not a valid binary digit", *sp))); x >>= 1; if (x == 0) { x = HIGHBIT; r++; } } } else { /* Parse the hex representation of the string */ for (bc = 0; *sp; sp++) { if (*sp >= '0' && *sp <= '9') x = (bits8) (*sp - '0'); else if (*sp >= 'A' && *sp <= 'F') x = (bits8) (*sp - 'A') + 10; else if (*sp >= 'a' && *sp <= 'f') x = (bits8) (*sp - 'a') + 10; else ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("\"%c\" is not a valid hexadecimal digit", *sp))); if (bc) { *r++ |= x; bc = 0; } else { *r = x << 4; bc = 1; } } } PG_RETURN_VARBIT_P(result); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Predict integer overflow to avoid buffer overruns. Several functions, mostly type input functions, calculated an allocation size such that the calculation wrapped to a small positive value when arguments implied a sufficiently-large requirement. Writes past the end of the inadvertent small allocation followed shortly thereafter. Coverity identified the path_in() vulnerability; code inspection led to the rest. In passing, add check_stack_depth() to prevent stack overflow in related functions. Back-patch to 8.4 (all supported versions). The non-comment hstore changes touch code that did not exist in 8.4, so that part stops at 9.0. Noah Misch and Heikki Linnakangas, reviewed by Tom Lane. Security: CVE-2014-0064'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bit_in(PG_FUNCTION_ARGS) { char *input_string = PG_GETARG_CSTRING(0); #ifdef NOT_USED Oid typelem = PG_GETARG_OID(1); #endif int32 atttypmod = PG_GETARG_INT32(2); VarBit *result; /* The resulting bit string */ char *sp; /* pointer into the character string */ bits8 *r; /* pointer into the result */ int len, /* Length of the whole data structure */ bitlen, /* Number of bits in the bit string */ slen; /* Length of the input string */ bool bit_not_hex; /* false = hex string true = bit string */ int bc; bits8 x = 0; /* Check that the first character is a b or an x */ if (input_string[0] == 'b' || input_string[0] == 'B') { bit_not_hex = true; sp = input_string + 1; } else if (input_string[0] == 'x' || input_string[0] == 'X') { bit_not_hex = false; sp = input_string + 1; } else { /* * Otherwise it's binary. This allows things like cast('1001' as bit) * to work transparently. */ bit_not_hex = true; sp = input_string; } slen = strlen(sp); /* Determine bitlength from input string */ if (bit_not_hex) bitlen = slen; else bitlen = slen * 4; /* * Sometimes atttypmod is not supplied. If it is supplied we need to make * sure that the bitstring fits. */ if (atttypmod <= 0) atttypmod = bitlen; else if (bitlen != atttypmod) ereport(ERROR, (errcode(ERRCODE_STRING_DATA_LENGTH_MISMATCH), errmsg("bit string length %d does not match type bit(%d)", bitlen, atttypmod))); len = VARBITTOTALLEN(atttypmod); /* set to 0 so that *r is always initialised and string is zero-padded */ result = (VarBit *) palloc0(len); SET_VARSIZE(result, len); VARBITLEN(result) = atttypmod; r = VARBITS(result); if (bit_not_hex) { /* Parse the bit representation of the string */ /* We know it fits, as bitlen was compared to atttypmod */ x = HIGHBIT; for (; *sp; sp++) { if (*sp == '1') *r |= x; else if (*sp != '0') ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("\"%c\" is not a valid binary digit", *sp))); x >>= 1; if (x == 0) { x = HIGHBIT; r++; } } } else { /* Parse the hex representation of the string */ for (bc = 0; *sp; sp++) { if (*sp >= '0' && *sp <= '9') x = (bits8) (*sp - '0'); else if (*sp >= 'A' && *sp <= 'F') x = (bits8) (*sp - 'A') + 10; else if (*sp >= 'a' && *sp <= 'f') x = (bits8) (*sp - 'a') + 10; else ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("\"%c\" is not a valid hexadecimal digit", *sp))); if (bc) { *r++ |= x; bc = 0; } else { *r = x << 4; bc = 1; } } } PG_RETURN_VARBIT_P(result); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Predict integer overflow to avoid buffer overruns. Several functions, mostly type input functions, calculated an allocation size such that the calculation wrapped to a small positive value when arguments implied a sufficiently-large requirement. Writes past the end of the inadvertent small allocation followed shortly thereafter. Coverity identified the path_in() vulnerability; code inspection led to the rest. In passing, add check_stack_depth() to prevent stack overflow in related functions. Back-patch to 8.4 (all supported versions). The non-comment hstore changes touch code that did not exist in 8.4, so that part stops at 9.0. Noah Misch and Heikki Linnakangas, reviewed by Tom Lane. Security: CVE-2014-0064'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: txid_snapshot_recv(PG_FUNCTION_ARGS) { StringInfo buf = (StringInfo) PG_GETARG_POINTER(0); TxidSnapshot *snap; txid last = 0; int nxip; int i; int avail; int expect; txid xmin, xmax; /* * load nxip and check for nonsense. * * (nxip > avail) check is against int overflows in 'expect'. */ nxip = pq_getmsgint(buf, 4); avail = buf->len - buf->cursor; expect = 8 + 8 + nxip * 8; if (nxip < 0 || nxip > avail || expect > avail) goto bad_format; xmin = pq_getmsgint64(buf); xmax = pq_getmsgint64(buf); if (xmin == 0 || xmax == 0 || xmin > xmax || xmax > MAX_TXID) goto bad_format; snap = palloc(TXID_SNAPSHOT_SIZE(nxip)); snap->xmin = xmin; snap->xmax = xmax; snap->nxip = nxip; SET_VARSIZE(snap, TXID_SNAPSHOT_SIZE(nxip)); for (i = 0; i < nxip; i++) { txid cur = pq_getmsgint64(buf); if (cur <= last || cur < xmin || cur >= xmax) goto bad_format; snap->xip[i] = cur; last = cur; } PG_RETURN_POINTER(snap); bad_format: elog(ERROR, "invalid snapshot data"); return (Datum) NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Predict integer overflow to avoid buffer overruns. Several functions, mostly type input functions, calculated an allocation size such that the calculation wrapped to a small positive value when arguments implied a sufficiently-large requirement. Writes past the end of the inadvertent small allocation followed shortly thereafter. Coverity identified the path_in() vulnerability; code inspection led to the rest. In passing, add check_stack_depth() to prevent stack overflow in related functions. Back-patch to 8.4 (all supported versions). The non-comment hstore changes touch code that did not exist in 8.4, so that part stops at 9.0. Noah Misch and Heikki Linnakangas, reviewed by Tom Lane. Security: CVE-2014-0064'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: findoprnd(ITEM *ptr, int32 *pos) { #ifdef BS_DEBUG elog(DEBUG3, (ptr[*pos].type == OPR) ? "%d %c" : "%d %d", *pos, ptr[*pos].val); #endif if (ptr[*pos].type == VAL) { ptr[*pos].left = 0; (*pos)--; } else if (ptr[*pos].val == (int32) '!') { ptr[*pos].left = -1; (*pos)--; findoprnd(ptr, pos); } else { ITEM *curitem = &ptr[*pos]; int32 tmp = *pos; (*pos)--; findoprnd(ptr, pos); curitem->left = *pos - tmp; findoprnd(ptr, pos); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Predict integer overflow to avoid buffer overruns. Several functions, mostly type input functions, calculated an allocation size such that the calculation wrapped to a small positive value when arguments implied a sufficiently-large requirement. Writes past the end of the inadvertent small allocation followed shortly thereafter. Coverity identified the path_in() vulnerability; code inspection led to the rest. In passing, add check_stack_depth() to prevent stack overflow in related functions. Back-patch to 8.4 (all supported versions). The non-comment hstore changes touch code that did not exist in 8.4, so that part stops at 9.0. Noah Misch and Heikki Linnakangas, reviewed by Tom Lane. Security: CVE-2014-0064'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: hstore_from_array(PG_FUNCTION_ARGS) { ArrayType *in_array = PG_GETARG_ARRAYTYPE_P(0); int ndims = ARR_NDIM(in_array); int count; int32 buflen; HStore *out; Pairs *pairs; Datum *in_datums; bool *in_nulls; int in_count; int i; Assert(ARR_ELEMTYPE(in_array) == TEXTOID); switch (ndims) { case 0: out = hstorePairs(NULL, 0, 0); PG_RETURN_POINTER(out); case 1: if ((ARR_DIMS(in_array)[0]) % 2) ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), errmsg("array must have even number of elements"))); break; case 2: if ((ARR_DIMS(in_array)[1]) != 2) ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), errmsg("array must have two columns"))); break; default: ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), errmsg("wrong number of array subscripts"))); } deconstruct_array(in_array, TEXTOID, -1, false, 'i', &in_datums, &in_nulls, &in_count); count = in_count / 2; pairs = palloc(count * sizeof(Pairs)); for (i = 0; i < count; ++i) { if (in_nulls[i * 2]) ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg("null value not allowed for hstore key"))); if (in_nulls[i * 2 + 1]) { pairs[i].key = VARDATA_ANY(in_datums[i * 2]); pairs[i].val = NULL; pairs[i].keylen = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(in_datums[i * 2])); pairs[i].vallen = 4; pairs[i].isnull = true; pairs[i].needfree = false; } else { pairs[i].key = VARDATA_ANY(in_datums[i * 2]); pairs[i].val = VARDATA_ANY(in_datums[i * 2 + 1]); pairs[i].keylen = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(in_datums[i * 2])); pairs[i].vallen = hstoreCheckValLen(VARSIZE_ANY_EXHDR(in_datums[i * 2 + 1])); pairs[i].isnull = false; pairs[i].needfree = false; } } count = hstoreUniquePairs(pairs, count, &buflen); out = hstorePairs(pairs, count, buflen); PG_RETURN_POINTER(out); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Predict integer overflow to avoid buffer overruns. Several functions, mostly type input functions, calculated an allocation size such that the calculation wrapped to a small positive value when arguments implied a sufficiently-large requirement. Writes past the end of the inadvertent small allocation followed shortly thereafter. Coverity identified the path_in() vulnerability; code inspection led to the rest. In passing, add check_stack_depth() to prevent stack overflow in related functions. Back-patch to 8.4 (all supported versions). The non-comment hstore changes touch code that did not exist in 8.4, so that part stops at 9.0. Noah Misch and Heikki Linnakangas, reviewed by Tom Lane. Security: CVE-2014-0064'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: parse_tsquery(char *buf, PushFunction pushval, Datum opaque, bool isplain) { struct TSQueryParserStateData state; int i; TSQuery query; int commonlen; QueryItem *ptr; ListCell *cell; /* init state */ state.buffer = buf; state.buf = buf; state.state = (isplain) ? WAITSINGLEOPERAND : WAITFIRSTOPERAND; state.count = 0; state.polstr = NIL; /* init value parser's state */ state.valstate = init_tsvector_parser(state.buffer, true, true); /* init list of operand */ state.sumlen = 0; state.lenop = 64; state.curop = state.op = (char *) palloc(state.lenop); *(state.curop) = '\0'; /* parse query & make polish notation (postfix, but in reverse order) */ makepol(&state, pushval, opaque); close_tsvector_parser(state.valstate); if (list_length(state.polstr) == 0) { ereport(NOTICE, (errmsg("text-search query doesn't contain lexemes: \"%s\"", state.buffer))); query = (TSQuery) palloc(HDRSIZETQ); SET_VARSIZE(query, HDRSIZETQ); query->size = 0; return query; } /* Pack the QueryItems in the final TSQuery struct to return to caller */ commonlen = COMPUTESIZE(list_length(state.polstr), state.sumlen); query = (TSQuery) palloc0(commonlen); SET_VARSIZE(query, commonlen); query->size = list_length(state.polstr); ptr = GETQUERY(query); /* Copy QueryItems to TSQuery */ i = 0; foreach(cell, state.polstr) { QueryItem *item = (QueryItem *) lfirst(cell); switch (item->type) { case QI_VAL: memcpy(&ptr[i], item, sizeof(QueryOperand)); break; case QI_VALSTOP: ptr[i].type = QI_VALSTOP; break; case QI_OPR: memcpy(&ptr[i], item, sizeof(QueryOperator)); break; default: elog(ERROR, "unrecognized QueryItem type: %d", item->type); } i++; } /* Copy all the operand strings to TSQuery */ memcpy((void *) GETOPERAND(query), (void *) state.op, state.sumlen); pfree(state.op); /* Set left operand pointers for every operator. */ findoprnd(ptr, query->size); return query; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Predict integer overflow to avoid buffer overruns. Several functions, mostly type input functions, calculated an allocation size such that the calculation wrapped to a small positive value when arguments implied a sufficiently-large requirement. Writes past the end of the inadvertent small allocation followed shortly thereafter. Coverity identified the path_in() vulnerability; code inspection led to the rest. In passing, add check_stack_depth() to prevent stack overflow in related functions. Back-patch to 8.4 (all supported versions). The non-comment hstore changes touch code that did not exist in 8.4, so that part stops at 9.0. Noah Misch and Heikki Linnakangas, reviewed by Tom Lane. Security: CVE-2014-0064'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: pqParseInput3(PGconn *conn) { char id; int msgLength; int avail; /* * Loop to parse successive complete messages available in the buffer. */ for (;;) { /* * Try to read a message. First get the type code and length. Return * if not enough data. */ conn->inCursor = conn->inStart; if (pqGetc(&id, conn)) return; if (pqGetInt(&msgLength, 4, conn)) return; /* * Try to validate message type/length here. A length less than 4 is * definitely broken. Large lengths should only be believed for a few * message types. */ if (msgLength < 4) { handleSyncLoss(conn, id, msgLength); return; } if (msgLength > 30000 && !VALID_LONG_MESSAGE_TYPE(id)) { handleSyncLoss(conn, id, msgLength); return; } /* * Can't process if message body isn't all here yet. */ msgLength -= 4; avail = conn->inEnd - conn->inCursor; if (avail < msgLength) { /* * Before returning, enlarge the input buffer if needed to hold * the whole message. This is better than leaving it to * pqReadData because we can avoid multiple cycles of realloc() * when the message is large; also, we can implement a reasonable * recovery strategy if we are unable to make the buffer big * enough. */ if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength, conn)) { /* * XXX add some better recovery code... plan is to skip over * the message using its length, then report an error. For the * moment, just treat this like loss of sync (which indeed it * might be!) */ handleSyncLoss(conn, id, msgLength); } return; } /* * NOTIFY and NOTICE messages can happen in any state; always process * them right away. * * Most other messages should only be processed while in BUSY state. * (In particular, in READY state we hold off further parsing until * the application collects the current PGresult.) * * However, if the state is IDLE then we got trouble; we need to deal * with the unexpected message somehow. * * ParameterStatus ('S') messages are a special case: in IDLE state we * must process 'em (this case could happen if a new value was adopted * from config file due to SIGHUP), but otherwise we hold off until * BUSY state. */ if (id == 'A') { if (getNotify(conn)) return; } else if (id == 'N') { if (pqGetErrorNotice3(conn, false)) return; } else if (conn->asyncStatus != PGASYNC_BUSY) { /* If not IDLE state, just wait ... */ if (conn->asyncStatus != PGASYNC_IDLE) return; /* * Unexpected message in IDLE state; need to recover somehow. * ERROR messages are displayed using the notice processor; * ParameterStatus is handled normally; anything else is just * dropped on the floor after displaying a suitable warning * notice. (An ERROR is very possibly the backend telling us why * it is about to close the connection, so we don't want to just * discard it...) */ if (id == 'E') { if (pqGetErrorNotice3(conn, false /* treat as notice */ )) return; } else if (id == 'S') { if (getParameterStatus(conn)) return; } else { pqInternalNotice(&conn->noticeHooks, "message type 0x%02x arrived from server while idle", id); /* Discard the unexpected message */ conn->inCursor += msgLength; } } else { /* * In BUSY state, we can process everything. */ switch (id) { case 'C': /* command complete */ if (pqGets(&conn->workBuffer, conn)) return; if (conn->result == NULL) { conn->result = PQmakeEmptyPGresult(conn, PGRES_COMMAND_OK); if (!conn->result) return; } strncpy(conn->result->cmdStatus, conn->workBuffer.data, CMDSTATUS_LEN); conn->asyncStatus = PGASYNC_READY; break; case 'E': /* error return */ if (pqGetErrorNotice3(conn, true)) return; conn->asyncStatus = PGASYNC_READY; break; case 'Z': /* backend is ready for new query */ if (getReadyForQuery(conn)) return; conn->asyncStatus = PGASYNC_IDLE; break; case 'I': /* empty query */ if (conn->result == NULL) { conn->result = PQmakeEmptyPGresult(conn, PGRES_EMPTY_QUERY); if (!conn->result) return; } conn->asyncStatus = PGASYNC_READY; break; case '1': /* Parse Complete */ /* If we're doing PQprepare, we're done; else ignore */ if (conn->queryclass == PGQUERY_PREPARE) { if (conn->result == NULL) { conn->result = PQmakeEmptyPGresult(conn, PGRES_COMMAND_OK); if (!conn->result) return; } conn->asyncStatus = PGASYNC_READY; } break; case '2': /* Bind Complete */ case '3': /* Close Complete */ /* Nothing to do for these message types */ break; case 'S': /* parameter status */ if (getParameterStatus(conn)) return; break; case 'K': /* secret key data from the backend */ /* * This is expected only during backend startup, but it's * just as easy to handle it as part of the main loop. * Save the data and continue processing. */ if (pqGetInt(&(conn->be_pid), 4, conn)) return; if (pqGetInt(&(conn->be_key), 4, conn)) return; break; case 'T': /* Row Description */ if (conn->result == NULL || conn->queryclass == PGQUERY_DESCRIBE) { /* First 'T' in a query sequence */ if (getRowDescriptions(conn, msgLength)) return; /* getRowDescriptions() moves inStart itself */ continue; } else { /* * A new 'T' message is treated as the start of * another PGresult. (It is not clear that this is * really possible with the current backend.) We stop * parsing until the application accepts the current * result. */ conn->asyncStatus = PGASYNC_READY; return; } break; case 'n': /* No Data */ /* * NoData indicates that we will not be seeing a * RowDescription message because the statement or portal * inquired about doesn't return rows. * * If we're doing a Describe, we have to pass something * back to the client, so set up a COMMAND_OK result, * instead of TUPLES_OK. Otherwise we can just ignore * this message. */ if (conn->queryclass == PGQUERY_DESCRIBE) { if (conn->result == NULL) { conn->result = PQmakeEmptyPGresult(conn, PGRES_COMMAND_OK); if (!conn->result) return; } conn->asyncStatus = PGASYNC_READY; } break; case 't': /* Parameter Description */ if (getParamDescriptions(conn)) return; break; case 'D': /* Data Row */ if (conn->result != NULL && conn->result->resultStatus == PGRES_TUPLES_OK) { /* Read another tuple of a normal query response */ if (getAnotherTuple(conn, msgLength)) return; /* getAnotherTuple() moves inStart itself */ continue; } else if (conn->result != NULL && conn->result->resultStatus == PGRES_FATAL_ERROR) { /* * We've already choked for some reason. Just discard * tuples till we get to the end of the query. */ conn->inCursor += msgLength; } else { /* Set up to report error at end of query */ printfPQExpBuffer(&conn->errorMessage, libpq_gettext("server sent data (\"D\" message) without prior row description (\"T\" message)\n")); pqSaveErrorResult(conn); /* Discard the unexpected message */ conn->inCursor += msgLength; } break; case 'G': /* Start Copy In */ if (getCopyStart(conn, PGRES_COPY_IN)) return; conn->asyncStatus = PGASYNC_COPY_IN; break; case 'H': /* Start Copy Out */ if (getCopyStart(conn, PGRES_COPY_OUT)) return; conn->asyncStatus = PGASYNC_COPY_OUT; conn->copy_already_done = 0; break; case 'W': /* Start Copy Both */ if (getCopyStart(conn, PGRES_COPY_BOTH)) return; conn->asyncStatus = PGASYNC_COPY_BOTH; conn->copy_already_done = 0; break; case 'd': /* Copy Data */ /* * If we see Copy Data, just silently drop it. This would * only occur if application exits COPY OUT mode too * early. */ conn->inCursor += msgLength; break; case 'c': /* Copy Done */ /* * If we see Copy Done, just silently drop it. This is * the normal case during PQendcopy. We will keep * swallowing data, expecting to see command-complete for * the COPY command. */ break; default: printfPQExpBuffer(&conn->errorMessage, libpq_gettext( "unexpected response from server; first received character was \"%c\"\n"), id); /* build an error result holding the error message */ pqSaveErrorResult(conn); /* not sure if we will see more, so go to ready state */ conn->asyncStatus = PGASYNC_READY; /* Discard the unexpected message */ conn->inCursor += msgLength; break; } /* switch on protocol character */ } /* Successfully consumed this message */ if (conn->inCursor == conn->inStart + 5 + msgLength) { /* Normal case: parsing agrees with specified length */ conn->inStart = conn->inCursor; } else { /* Trouble --- report it */ printfPQExpBuffer(&conn->errorMessage, libpq_gettext("message contents do not agree with length in message type \"%c\"\n"), id); /* build an error result holding the error message */ pqSaveErrorResult(conn); conn->asyncStatus = PGASYNC_READY; /* trust the specified message length as what to skip */ conn->inStart += 5 + msgLength; } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Prevent potential overruns of fixed-size buffers. Coverity identified a number of places in which it couldn't prove that a string being copied into a fixed-size buffer would fit. We believe that most, perhaps all of these are in fact safe, or are copying data that is coming from a trusted source so that any overrun is not really a security issue. Nonetheless it seems prudent to forestall any risk by using strlcpy() and similar functions. Fixes by Peter Eisentraut and Jozef Mlich based on Coverity reports. In addition, fix a potential null-pointer-dereference crash in contrib/chkpass. The crypt(3) function is defined to return NULL on failure, but chkpass.c didn't check for that before using the result. The main practical case in which this could be an issue is if libc is configured to refuse to execute unapproved hashing algorithms (e.g., "FIPS mode"). This ideally should've been a separate commit, but since it touches code adjacent to one of the buffer overrun changes, I included it in this commit to avoid last-minute merge issues. This issue was reported by Honza Horak. Security: CVE-2014-0065 for buffer overruns, CVE-2014-0066 for crypt()'</s>