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 inline int ldsem_cmpxchg(long *old, long new, struct ld_semaphore *sem) { long tmp = *old; *old = atomic_long_cmpxchg(&sem->count, *old, new); return *old == tmp; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'tty: Fix hang at ldsem_down_read() When a controlling tty is being hung up and the hang up is waiting for a just-signalled tty reader or writer to exit, and a new tty reader/writer tries to acquire an ldisc reference concurrently with the ldisc reference release from the signalled reader/writer, the hangup can hang. The new reader/writer is sleeping in ldsem_down_read() and the hangup is sleeping in ldsem_down_write() [1]. The new reader/writer fails to wakeup the waiting hangup because the wrong lock count value is checked (the old lock count rather than the new lock count) to see if the lock is unowned. Change helper function to return the new lock count if the cmpxchg was successful; document this behavior. [1] edited dmesg log from reporter SysRq : Show Blocked State task PC stack pid father systemd D ffff88040c4f0000 0 1 0 0x00000000 ffff88040c49fbe0 0000000000000046 ffff88040c4a0000 ffff88040c49ffd8 00000000001d3980 00000000001d3980 ffff88040c4a0000 ffff88040593d840 ffff88040c49fb40 ffffffff810a4cc0 0000000000000006 0000000000000023 Call Trace: [<ffffffff810a4cc0>] ? sched_clock_cpu+0x9f/0xe4 [<ffffffff810a4cc0>] ? sched_clock_cpu+0x9f/0xe4 [<ffffffff810a4cc0>] ? sched_clock_cpu+0x9f/0xe4 [<ffffffff810a4cc0>] ? sched_clock_cpu+0x9f/0xe4 [<ffffffff817a6649>] schedule+0x24/0x5e [<ffffffff817a588b>] schedule_timeout+0x15b/0x1ec [<ffffffff810a4cc0>] ? sched_clock_cpu+0x9f/0xe4 [<ffffffff817aa691>] ? _raw_spin_unlock_irq+0x24/0x26 [<ffffffff817aa10c>] down_read_failed+0xe3/0x1b9 [<ffffffff817aa26d>] ldsem_down_read+0x8b/0xa5 [<ffffffff8142b5ca>] ? tty_ldisc_ref_wait+0x1b/0x44 [<ffffffff8142b5ca>] tty_ldisc_ref_wait+0x1b/0x44 [<ffffffff81423f5b>] tty_write+0x7d/0x28a [<ffffffff814241f5>] redirected_tty_write+0x8d/0x98 [<ffffffff81424168>] ? tty_write+0x28a/0x28a [<ffffffff8115d03f>] do_loop_readv_writev+0x56/0x79 [<ffffffff8115e604>] do_readv_writev+0x1b0/0x1ff [<ffffffff8116ea0b>] ? do_vfs_ioctl+0x32a/0x489 [<ffffffff81167d9d>] ? final_putname+0x1d/0x3a [<ffffffff8115e6c7>] vfs_writev+0x2e/0x49 [<ffffffff8115e7d3>] SyS_writev+0x47/0xaa [<ffffffff817ab822>] system_call_fastpath+0x16/0x1b bash D ffffffff81c104c0 0 5469 5302 0x00000082 ffff8800cf817ac0 0000000000000046 ffff8804086b22a0 ffff8800cf817fd8 00000000001d3980 00000000001d3980 ffff8804086b22a0 ffff8800cf817a48 000000000000b9a0 ffff8800cf817a78 ffffffff81004675 ffff8800cf817a44 Call Trace: [<ffffffff81004675>] ? dump_trace+0x165/0x29c [<ffffffff810a4cc0>] ? sched_clock_cpu+0x9f/0xe4 [<ffffffff8100edda>] ? save_stack_trace+0x26/0x41 [<ffffffff817a6649>] schedule+0x24/0x5e [<ffffffff817a588b>] schedule_timeout+0x15b/0x1ec [<ffffffff810a4cc0>] ? sched_clock_cpu+0x9f/0xe4 [<ffffffff817a9f03>] ? down_write_failed+0xa3/0x1c9 [<ffffffff817aa691>] ? _raw_spin_unlock_irq+0x24/0x26 [<ffffffff817a9f0b>] down_write_failed+0xab/0x1c9 [<ffffffff817aa300>] ldsem_down_write+0x79/0xb1 [<ffffffff817aada3>] ? tty_ldisc_lock_pair_timeout+0xa5/0xd9 [<ffffffff817aada3>] tty_ldisc_lock_pair_timeout+0xa5/0xd9 [<ffffffff8142bf33>] tty_ldisc_hangup+0xc4/0x218 [<ffffffff81423ab3>] __tty_hangup+0x2e2/0x3ed [<ffffffff81424a76>] disassociate_ctty+0x63/0x226 [<ffffffff81078aa7>] do_exit+0x79f/0xa11 [<ffffffff81086bdb>] ? get_signal_to_deliver+0x206/0x62f [<ffffffff810b4bfb>] ? lock_release_holdtime.part.8+0xf/0x16e [<ffffffff81079b05>] do_group_exit+0x47/0xb5 [<ffffffff81086c16>] get_signal_to_deliver+0x241/0x62f [<ffffffff810020a7>] do_signal+0x43/0x59d [<ffffffff810f2af7>] ? __audit_syscall_exit+0x21a/0x2a8 [<ffffffff810b4bfb>] ? lock_release_holdtime.part.8+0xf/0x16e [<ffffffff81002655>] do_notify_resume+0x54/0x6c [<ffffffff817abaf8>] int_signal+0x12/0x17 Reported-by: Sami Farin <[email protected]> Cc: <[email protected]> # 3.12.x Signed-off-by: Peter Hurley <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: XML_GetBuffer(XML_Parser parser, int len) { if (len < 0) { errorCode = XML_ERROR_NO_MEMORY; return NULL; } switch (ps_parsing) { case XML_SUSPENDED: errorCode = XML_ERROR_SUSPENDED; return NULL; case XML_FINISHED: errorCode = XML_ERROR_FINISHED; return NULL; default: ; } if (len > bufferLim - bufferEnd) { #ifdef XML_CONTEXT_BYTES int keep; #endif /* defined XML_CONTEXT_BYTES */ int neededSize = len + (int)(bufferEnd - bufferPtr); if (neededSize < 0) { errorCode = XML_ERROR_NO_MEMORY; return NULL; } #ifdef XML_CONTEXT_BYTES keep = (int)(bufferPtr - buffer); if (keep > XML_CONTEXT_BYTES) keep = XML_CONTEXT_BYTES; neededSize += keep; #endif /* defined XML_CONTEXT_BYTES */ if (neededSize <= bufferLim - buffer) { #ifdef XML_CONTEXT_BYTES if (keep < bufferPtr - buffer) { int offset = (int)(bufferPtr - buffer) - keep; memmove(buffer, &buffer[offset], bufferEnd - bufferPtr + keep); bufferEnd -= offset; bufferPtr -= offset; } #else memmove(buffer, bufferPtr, bufferEnd - bufferPtr); bufferEnd = buffer + (bufferEnd - bufferPtr); bufferPtr = buffer; #endif /* not defined XML_CONTEXT_BYTES */ } else { char *newBuf; int bufferSize = (int)(bufferLim - bufferPtr); if (bufferSize == 0) bufferSize = INIT_BUFFER_SIZE; do { bufferSize *= 2; } while (bufferSize < neededSize && bufferSize > 0); if (bufferSize <= 0) { errorCode = XML_ERROR_NO_MEMORY; return NULL; } newBuf = (char *)MALLOC(bufferSize); if (newBuf == 0) { errorCode = XML_ERROR_NO_MEMORY; return NULL; } bufferLim = newBuf + bufferSize; #ifdef XML_CONTEXT_BYTES if (bufferPtr) { int keep = (int)(bufferPtr - buffer); if (keep > XML_CONTEXT_BYTES) keep = XML_CONTEXT_BYTES; memcpy(newBuf, &bufferPtr[-keep], bufferEnd - bufferPtr + keep); FREE(buffer); buffer = newBuf; bufferEnd = buffer + (bufferEnd - bufferPtr) + keep; bufferPtr = buffer + keep; } else { bufferEnd = newBuf + (bufferEnd - bufferPtr); bufferPtr = buffer = newBuf; } #else if (bufferPtr) { memcpy(newBuf, bufferPtr, bufferEnd - bufferPtr); FREE(buffer); } bufferEnd = newBuf + (bufferEnd - bufferPtr); bufferPtr = buffer = newBuf; #endif /* not defined XML_CONTEXT_BYTES */ } eventPtr = eventEndPtr = NULL; positionPtr = NULL; } return bufferEnd; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Avoid relying on undefined behavior in CVE-2015-1283 fix. It does not really work: https://godbolt.org/g/Zl8gdF'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void CLASS bad_pixels (const char *cfname) { FILE *fp=NULL; #ifndef LIBRAW_LIBRARY_BUILD char *fname, *cp, line[128]; int len, time, row, col, r, c, rad, tot, n, fixed=0; #else char *cp, line[128]; int time, row, col, r, c, rad, tot, n; #ifdef DCRAW_VERBOSE int fixed = 0; #endif #endif if (!filters) return; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_BAD_PIXELS,0,2); #endif if (cfname) fp = fopen (cfname, "r"); #line 4151 "dcraw/dcraw.c" if (!fp) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_BADPIXELMAP; #endif return; } while (fgets (line, 128, fp)) { cp = strchr (line, '#'); if (cp) *cp = 0; if (sscanf (line, "%d %d %d", &col, &row, &time) != 3) continue; if ((unsigned) col >= width || (unsigned) row >= height) continue; if (time > timestamp) continue; for (tot=n=0, rad=1; rad < 3 && n==0; rad++) for (r = row-rad; r <= row+rad; r++) for (c = col-rad; c <= col+rad; c++) if ((unsigned) r < height && (unsigned) c < width && (r != row || c != col) && fcol(r,c) == fcol(row,col)) { tot += BAYER2(r,c); n++; } BAYER2(row,col) = tot/n; #ifdef DCRAW_VERBOSE if (verbose) { if (!fixed++) fprintf (stderr,_("Fixed dead pixels at:")); fprintf (stderr, " %d,%d", col, row); } #endif } #ifdef DCRAW_VERBOSE if (fixed) fputc ('\n', stderr); #endif fclose (fp); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_BAD_PIXELS,1,2); #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': '0.16.1: fix for dcraw ljpeg_start() vulnerability'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: inf_gtk_certificate_manager_certificate_func(InfXmppConnection* connection, gnutls_session_t session, InfCertificateChain* chain, gpointer user_data) { InfGtkCertificateManager* manager; InfGtkCertificateManagerPrivate* priv; InfGtkCertificateDialogFlags flags; gnutls_x509_crt_t presented_cert; gnutls_x509_crt_t known_cert; gchar* hostname; gboolean match_hostname; gboolean issuer_known; gnutls_x509_crt_t root_cert; int ret; unsigned int verify; GHashTable* table; gboolean cert_equal; time_t expiration_time; InfGtkCertificateManagerQuery* query; gchar* text; GtkWidget* vbox; GtkWidget* label; GError* error; manager = INF_GTK_CERTIFICATE_MANAGER(user_data); priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(manager); g_object_get(G_OBJECT(connection), "remote-hostname", &hostname, NULL); presented_cert = inf_certificate_chain_get_own_certificate(chain); match_hostname = gnutls_x509_crt_check_hostname(presented_cert, hostname); /* First, validate the certificate */ ret = gnutls_certificate_verify_peers2(session, &verify); error = NULL; if(ret != GNUTLS_E_SUCCESS) inf_gnutls_set_error(&error, ret); /* Remove the GNUTLS_CERT_ISSUER_NOT_KNOWN flag from the verification * result, and if the certificate is still invalid, then set an error. */ if(error == NULL) { issuer_known = TRUE; if(verify & GNUTLS_CERT_SIGNER_NOT_FOUND) { issuer_known = FALSE; /* Re-validate the certificate for other failure reasons -- * unfortunately the gnutls_certificate_verify_peers2() call * does not tell us whether the certificate is otherwise invalid * if a signer is not found already. */ /* TODO: Here it would be good to use the verify flags from the * certificate credentials, but GnuTLS does not have API to * retrieve them. */ root_cert = inf_certificate_chain_get_root_certificate(chain); ret = gnutls_x509_crt_list_verify( inf_certificate_chain_get_raw(chain), inf_certificate_chain_get_n_certificates(chain), &root_cert, 1, NULL, 0, GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT, &verify ); if(ret != GNUTLS_E_SUCCESS) inf_gnutls_set_error(&error, ret); else if(verify & GNUTLS_CERT_INVALID) inf_gnutls_certificate_verification_set_error(&error, verify); } } /* Look up the host in our database of pinned certificates if we could not * fully verify the certificate, i.e. if either the issuer is not known or * the hostname of the connection does not match the certificate. */ table = NULL; if(error == NULL) { known_cert = NULL; if(!match_hostname || !issuer_known) { /* If we cannot load the known host file, then cancel the connection. * Otherwise it might happen that someone shows us a certificate that we * tell the user we don't know, if though actually for that host we expect * a different certificate. */ table = inf_gtk_certificate_manager_ref_known_hosts(manager, &error); if(table != NULL) known_cert = g_hash_table_lookup(table, hostname); } } /* Next, configure the flags for the dialog to be shown based on the * verification result, and on whether the pinned certificate matches * the one presented by the host or not. */ flags = 0; if(error == NULL) { if(known_cert != NULL) { cert_equal = inf_gtk_certificate_manager_compare_fingerprint( known_cert, presented_cert, &error ); if(error == NULL && cert_equal == FALSE) { if(!match_hostname) flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_HOSTNAME_MISMATCH; if(!issuer_known) flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_ISSUER_NOT_KNOWN; flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_UNEXPECTED; expiration_time = gnutls_x509_crt_get_expiration_time(known_cert); if(expiration_time != (time_t)(-1)) { expiration_time -= INF_GTK_CERTIFICATE_MANAGER_EXPIRATION_TOLERANCE; if(time(NULL) > expiration_time) { flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_OLD_EXPIRED; } } } } else { if(!match_hostname) flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_HOSTNAME_MISMATCH; if(!issuer_known) flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_ISSUER_NOT_KNOWN; } } /* Now proceed either by accepting the connection, rejecting it, or * bothering the user with an annoying dialog. */ if(error == NULL) { if(flags == 0) { if(match_hostname && issuer_known) { /* Remove the pinned entry if we now have a valid certificate for * this host. */ if(table != NULL && g_hash_table_remove(table, hostname) == TRUE) { inf_gtk_certificate_manager_write_known_hosts_with_warning( manager, table ); } } inf_xmpp_connection_certificate_verify_continue(connection); } else { query = g_slice_new(InfGtkCertificateManagerQuery); query->manager = manager; query->known_hosts = table; query->connection = connection; query->dialog = inf_gtk_certificate_dialog_new( priv->parent_window, 0, flags, hostname, chain ); query->certificate_chain = chain; table = NULL; g_object_ref(query->connection); inf_certificate_chain_ref(chain); g_signal_connect( G_OBJECT(connection), "notify::status", G_CALLBACK(inf_gtk_certificate_manager_notify_status_cb), query ); g_signal_connect( G_OBJECT(query->dialog), "response", G_CALLBACK(inf_gtk_certificate_manager_response_cb), query ); gtk_dialog_add_button( GTK_DIALOG(query->dialog), _("_Cancel connection"), GTK_RESPONSE_REJECT ); gtk_dialog_add_button( GTK_DIALOG(query->dialog), _("C_ontinue connection"), GTK_RESPONSE_ACCEPT ); text = g_strdup_printf( _("Do you want to continue the connection to host \"%s\"? If you " "choose to continue, this certificate will be trusted in the " "future when connecting to this host."), hostname ); label = gtk_label_new(text); gtk_label_set_line_wrap(GTK_LABEL(label), TRUE); gtk_label_set_line_wrap_mode(GTK_LABEL(label), PANGO_WRAP_WORD_CHAR); gtk_label_set_max_width_chars(GTK_LABEL(label), 60); gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.0); gtk_widget_show(label); g_free(text); vbox = gtk_dialog_get_content_area(GTK_DIALOG(query->dialog)); gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0); priv->queries = g_slist_prepend(priv->queries, query); gtk_window_present(GTK_WINDOW(query->dialog)); } } else { inf_xmpp_connection_certificate_verify_cancel(connection, error); g_error_free(error); } if(table != NULL) g_hash_table_unref(table); g_free(hostname); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-295'], 'message': 'Fix expired certificate validation (gobby #61)'</s>
<s>[INST] Given the following code containing errors, provide 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 basic_globals_ctor(php_basic_globals *basic_globals_p TSRMLS_DC) /* {{{ */ { BG(rand_is_seeded) = 0; BG(mt_rand_is_seeded) = 0; BG(umask) = -1; BG(next) = NULL; BG(left) = -1; BG(user_tick_functions) = NULL; BG(user_filter_map) = NULL; BG(serialize_lock) = 0; memset(&BG(serialize), 0, sizeof(BG(serialize))); memset(&BG(unserialize), 0, sizeof(BG(unserialize))); memset(&BG(url_adapt_state_ex), 0, sizeof(BG(url_adapt_state_ex))); #if defined(_REENTRANT) && defined(HAVE_MBRLEN) && defined(HAVE_MBSTATE_T) memset(&BG(mblen_state), 0, sizeof(BG(mblen_state))); #endif BG(incomplete_class) = incomplete_class_entry; BG(page_uid) = -1; BG(page_gid) = -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-19'], 'message': 'Fixed bug #69418 - more s->p fixes for filenames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(getenv) { char *ptr, *str; int str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &str, &str_len) == FAILURE) { RETURN_FALSE; } /* SAPI method returns an emalloc()'d string */ ptr = sapi_getenv(str, str_len TSRMLS_CC); if (ptr) { RETURN_STRING(ptr, 0); } #ifdef PHP_WIN32 { char dummybuf; int size; SetLastError(0); /*If the given bugger is not large enough to hold the data, the return value is the buffer size, in characters, required to hold the string and its terminating null character. We use this return value to alloc the final buffer. */ size = GetEnvironmentVariableA(str, &dummybuf, 0); if (GetLastError() == ERROR_ENVVAR_NOT_FOUND) { /* The environment variable doesn't exist. */ RETURN_FALSE; } if (size == 0) { /* env exists, but it is empty */ RETURN_EMPTY_STRING(); } ptr = emalloc(size); size = GetEnvironmentVariableA(str, ptr, size); if (size == 0) { /* has been removed between the two calls */ efree(ptr); RETURN_EMPTY_STRING(); } else { RETURN_STRING(ptr, 0); } } #else /* system method returns a const */ ptr = getenv(str); if (ptr) { RETURN_STRING(ptr, 1); } #endif RETURN_FALSE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-19'], 'message': 'Fixed bug #69418 - more s->p fixes for filenames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(pcntl_wait) { long options = 0; zval *z_status = NULL; int status; pid_t child_id; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|l", &z_status, &options) == FAILURE) return; convert_to_long_ex(&z_status); status = Z_LVAL_P(z_status); #ifdef HAVE_WAIT3 if(options) { child_id = wait3(&status, options, NULL); } else { child_id = wait(&status); } #else child_id = wait(&status); #endif if (child_id < 0) { PCNTL_G(last_error) = errno; } Z_LVAL_P(z_status) = status; RETURN_LONG((long) child_id); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-19'], 'message': 'Fixed bug #69418 - more s->p fixes for filenames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(chroot) { char *str; int ret, str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &str, &str_len) == FAILURE) { RETURN_FALSE; } ret = chroot(str); if (ret != 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s (errno %d)", strerror(errno), errno); RETURN_FALSE; } php_clear_stat_cache(1, NULL, 0 TSRMLS_CC); ret = chdir("/"); if (ret != 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s (errno %d)", strerror(errno), errno); RETURN_FALSE; } RETURN_TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-19'], 'message': 'Fixed bug #69418 - more s->p fixes for filenames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(getcwd) { char path[MAXPATHLEN]; char *ret=NULL; if (zend_parse_parameters_none() == FAILURE) { return; } #if HAVE_GETCWD ret = VCWD_GETCWD(path, MAXPATHLEN); #elif HAVE_GETWD ret = VCWD_GETWD(path); #endif if (ret) { RETURN_STRING(path, 1); } else { RETURN_FALSE; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-19'], 'message': 'Fixed bug #69418 - more s->p fixes for filenames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(glob) { int cwd_skip = 0; #ifdef ZTS char cwd[MAXPATHLEN]; char work_pattern[MAXPATHLEN]; char *result; #endif char *pattern = NULL; int pattern_len; long flags = 0; glob_t globbuf; int n; int ret; zend_bool basedir_limit = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|l", &pattern, &pattern_len, &flags) == FAILURE) { return; } if (pattern_len >= MAXPATHLEN) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Pattern exceeds the maximum allowed length of %d characters", MAXPATHLEN); RETURN_FALSE; } if ((GLOB_AVAILABLE_FLAGS & flags) != flags) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "At least one of the passed flags is invalid or not supported on this platform"); RETURN_FALSE; } #ifdef ZTS if (!IS_ABSOLUTE_PATH(pattern, pattern_len)) { result = VCWD_GETCWD(cwd, MAXPATHLEN); if (!result) { cwd[0] = '\0'; } #ifdef PHP_WIN32 if (IS_SLASH(*pattern)) { cwd[2] = '\0'; } #endif cwd_skip = strlen(cwd)+1; snprintf(work_pattern, MAXPATHLEN, "%s%c%s", cwd, DEFAULT_SLASH, pattern); pattern = work_pattern; } #endif memset(&globbuf, 0, sizeof(glob_t)); globbuf.gl_offs = 0; if (0 != (ret = glob(pattern, flags & GLOB_FLAGMASK, NULL, &globbuf))) { #ifdef GLOB_NOMATCH if (GLOB_NOMATCH == ret) { /* Some glob implementation simply return no data if no matches were found, others return the GLOB_NOMATCH error code. We don't want to treat GLOB_NOMATCH as an error condition so that PHP glob() behaves the same on both types of implementations and so that 'foreach (glob() as ...' can be used for simple glob() calls without further error checking. */ goto no_results; } #endif RETURN_FALSE; } /* now catch the FreeBSD style of "no matches" */ if (!globbuf.gl_pathc || !globbuf.gl_pathv) { no_results: #ifndef PHP_WIN32 /* Paths containing '*', '?' and some other chars are illegal on Windows but legit on other platforms. For this reason the direct basedir check against the glob query is senseless on windows. For instance while *.txt is a pretty valid filename on EXT3, it's invalid on NTFS. */ if (PG(open_basedir) && *PG(open_basedir)) { if (php_check_open_basedir_ex(pattern, 0 TSRMLS_CC)) { RETURN_FALSE; } } #endif array_init(return_value); return; } array_init(return_value); for (n = 0; n < globbuf.gl_pathc; n++) { if (PG(open_basedir) && *PG(open_basedir)) { if (php_check_open_basedir_ex(globbuf.gl_pathv[n], 0 TSRMLS_CC)) { basedir_limit = 1; continue; } } /* we need to do this everytime since GLOB_ONLYDIR does not guarantee that * all directories will be filtered. GNU libc documentation states the * following: * If the information about the type of the file is easily available * non-directories will be rejected but no extra work will be done to * determine the information for each file. I.e., the caller must still be * able to filter directories out. */ if (flags & GLOB_ONLYDIR) { struct stat s; if (0 != VCWD_STAT(globbuf.gl_pathv[n], &s)) { continue; } if (S_IFDIR != (s.st_mode & S_IFMT)) { continue; } } add_next_index_string(return_value, globbuf.gl_pathv[n]+cwd_skip, 1); } globfree(&globbuf); if (basedir_limit && !zend_hash_num_elements(Z_ARRVAL_P(return_value))) { zval_dtor(return_value); RETURN_FALSE; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-19'], 'message': 'Fixed bug #69418 - more s->p fixes for filenames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(pcntl_setpriority) { long who = PRIO_PROCESS; long pid = getpid(); long pri; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|ll", &pri, &pid, &who) == FAILURE) { RETURN_FALSE; } if (setpriority(who, pid, pri)) { PCNTL_G(last_error) = errno; switch (errno) { case ESRCH: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error %d: No process was located using the given parameters", errno); break; case EINVAL: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error %d: Invalid identifier flag", errno); break; case EPERM: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error %d: A process was located, but neither its effective nor real user ID matched the effective user ID of the caller", errno); break; case EACCES: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error %d: Only a super user may attempt to increase the process priority", errno); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown error %d has occurred", errno); break; } RETURN_FALSE; } RETURN_TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-19'], 'message': 'Fixed bug #69418 - more s->p fixes for filenames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void pcntl_sigwaitinfo(INTERNAL_FUNCTION_PARAMETERS, int timedwait) /* {{{ */ { zval *user_set, **user_signo, *user_siginfo = NULL; long tv_sec = 0, tv_nsec = 0; sigset_t set; HashPosition pos; int signo; siginfo_t siginfo; struct timespec timeout; if (timedwait) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|zll", &user_set, &user_siginfo, &tv_sec, &tv_nsec) == FAILURE) { return; } } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|z", &user_set, &user_siginfo) == FAILURE) { return; } } if (sigemptyset(&set) != 0) { PCNTL_G(last_error) = errno; php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", strerror(errno)); RETURN_FALSE; } zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(user_set), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(user_set), (void **)&user_signo, &pos) == SUCCESS) { if (Z_TYPE_PP(user_signo) != IS_LONG) { SEPARATE_ZVAL(user_signo); convert_to_long_ex(user_signo); } signo = Z_LVAL_PP(user_signo); if (sigaddset(&set, signo) != 0) { PCNTL_G(last_error) = errno; php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", strerror(errno)); RETURN_FALSE; } zend_hash_move_forward_ex(Z_ARRVAL_P(user_set), &pos); } if (timedwait) { timeout.tv_sec = (time_t) tv_sec; timeout.tv_nsec = tv_nsec; signo = sigtimedwait(&set, &siginfo, &timeout); } else { signo = sigwaitinfo(&set, &siginfo); } if (signo == -1 && errno != EAGAIN) { PCNTL_G(last_error) = errno; php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", strerror(errno)); } /* * sigtimedwait and sigwaitinfo can return 0 on success on some * platforms, e.g. NetBSD */ if (!signo && siginfo.si_signo) { signo = siginfo.si_signo; } if (signo > 0 && user_siginfo) { if (Z_TYPE_P(user_siginfo) != IS_ARRAY) { zval_dtor(user_siginfo); array_init(user_siginfo); } else { zend_hash_clean(Z_ARRVAL_P(user_siginfo)); } add_assoc_long_ex(user_siginfo, "signo", sizeof("signo"), siginfo.si_signo); add_assoc_long_ex(user_siginfo, "errno", sizeof("errno"), siginfo.si_errno); add_assoc_long_ex(user_siginfo, "code", sizeof("code"), siginfo.si_code); switch(signo) { #ifdef SIGCHLD case SIGCHLD: add_assoc_long_ex(user_siginfo, "status", sizeof("status"), siginfo.si_status); # ifdef si_utime add_assoc_double_ex(user_siginfo, "utime", sizeof("utime"), siginfo.si_utime); # endif # ifdef si_stime add_assoc_double_ex(user_siginfo, "stime", sizeof("stime"), siginfo.si_stime); # endif add_assoc_long_ex(user_siginfo, "pid", sizeof("pid"), siginfo.si_pid); add_assoc_long_ex(user_siginfo, "uid", sizeof("uid"), siginfo.si_uid); break; #endif case SIGILL: case SIGFPE: case SIGSEGV: case SIGBUS: add_assoc_double_ex(user_siginfo, "addr", sizeof("addr"), (long)siginfo.si_addr); break; #ifdef SIGPOLL case SIGPOLL: add_assoc_long_ex(user_siginfo, "band", sizeof("band"), siginfo.si_band); # ifdef si_fd add_assoc_long_ex(user_siginfo, "fd", sizeof("fd"), siginfo.si_fd); # endif break; #endif EMPTY_SWITCH_DEFAULT_CASE(); } } RETURN_LONG(signo); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-19'], 'message': 'Fixed bug #69418 - more s->p fixes for filenames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(pcntl_alarm) { long seconds; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &seconds) == FAILURE) return; RETURN_LONG ((long) alarm(seconds)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-19'], 'message': 'Fixed bug #69418 - more s->p fixes for filenames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(tempnam) { char *dir, *prefix; int dir_len, prefix_len; size_t p_len; char *opened_path; char *p; int fd; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ps", &dir, &dir_len, &prefix, &prefix_len) == FAILURE) { return; } if (php_check_open_basedir(dir TSRMLS_CC)) { RETURN_FALSE; } php_basename(prefix, prefix_len, NULL, 0, &p, &p_len TSRMLS_CC); if (p_len > 64) { p[63] = '\0'; } RETVAL_FALSE; if ((fd = php_open_temporary_fd_ex(dir, p, &opened_path, 1 TSRMLS_CC)) >= 0) { close(fd); RETVAL_STRING(opened_path, 0); } efree(p); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-19'], 'message': 'Fixed bug #69418 - more s->p fixes for filenames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(pcntl_waitpid) { long pid, options = 0; zval *z_status = NULL; int status; pid_t child_id; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lz|l", &pid, &z_status, &options) == FAILURE) return; convert_to_long_ex(&z_status); status = Z_LVAL_P(z_status); child_id = waitpid((pid_t) pid, &status, options); if (child_id < 0) { PCNTL_G(last_error) = errno; } Z_LVAL_P(z_status) = status; RETURN_LONG((long) child_id); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-19'], 'message': 'Fixed bug #69418 - more s->p fixes for filenames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void php_set_default_dir(int id TSRMLS_DC) { if (DIRG(default_dir)!=-1) { zend_list_delete(DIRG(default_dir)); } if (id != -1) { zend_list_addref(id); } DIRG(default_dir) = id; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-19'], 'message': 'Fixed bug #69418 - more s->p fixes for filenames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(rewinddir) { zval *id = NULL, **tmp, *myself; php_stream *dirp; FETCH_DIRP(); if (!(dirp->flags & PHP_STREAM_FLAG_IS_DIR)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%d is not a valid Directory resource", dirp->rsrc_id); RETURN_FALSE; } php_stream_rewinddir(dirp); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-19'], 'message': 'Fixed bug #69418 - more s->p fixes for filenames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: data_close(ftpbuf_t *ftp, databuf_t *data) { #if HAVE_OPENSSL_EXT SSL_CTX *ctx; #endif if (data == NULL) { return NULL; } if (data->listener != -1) { #if HAVE_OPENSSL_EXT if (data->ssl_active) { ctx = SSL_get_SSL_CTX(data->ssl_handle); SSL_CTX_free(ctx); SSL_shutdown(data->ssl_handle); SSL_free(data->ssl_handle); data->ssl_active = 0; } #endif closesocket(data->listener); } if (data->fd != -1) { #if HAVE_OPENSSL_EXT if (data->ssl_active) { ctx = SSL_get_SSL_CTX(data->ssl_handle); SSL_CTX_free(ctx); SSL_shutdown(data->ssl_handle); SSL_free(data->ssl_handle); data->ssl_active = 0; } #endif closesocket(data->fd); } if (ftp) { ftp->data = NULL; } efree(data); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Fix bug #69545 - avoid overflow when reading list'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ftp_close(ftpbuf_t *ftp) { if (ftp == NULL) { return NULL; } if (ftp->data) { data_close(ftp, ftp->data); } if (ftp->stream && ftp->closestream) { TSRMLS_FETCH(); php_stream_close(ftp->stream); } if (ftp->fd != -1) { #if HAVE_OPENSSL_EXT if (ftp->ssl_active) { SSL_shutdown(ftp->ssl_handle); SSL_free(ftp->ssl_handle); } #endif closesocket(ftp->fd); } ftp_gc(ftp); efree(ftp); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Fix bug #69545 - avoid overflow when reading list'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ftp_putcmd(ftpbuf_t *ftp, const char *cmd, const char *args) { int size; char *data; if (strpbrk(cmd, "\r\n")) { return 0; } /* build the output buffer */ if (args && args[0]) { /* "cmd args\r\n\0" */ if (strlen(cmd) + strlen(args) + 4 > FTP_BUFSIZE) { return 0; } if (strpbrk(args, "\r\n")) { return 0; } size = slprintf(ftp->outbuf, sizeof(ftp->outbuf), "%s %s\r\n", cmd, args); } else { /* "cmd\r\n\0" */ if (strlen(cmd) + 3 > FTP_BUFSIZE) { return 0; } size = slprintf(ftp->outbuf, sizeof(ftp->outbuf), "%s\r\n", cmd); } data = ftp->outbuf; /* Clear the extra-lines buffer */ ftp->extra = NULL; if (my_send(ftp, ftp->fd, data, size) != size) { return 0; } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Fix bug #69545 - avoid overflow when reading list'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: my_send(ftpbuf_t *ftp, php_socket_t s, void *buf, size_t len) { long size, sent; int n; size = len; while (size) { n = php_pollfd_for_ms(s, POLLOUT, ftp->timeout_sec * 1000); if (n < 1) { #if !defined(PHP_WIN32) && !(defined(NETWARE) && defined(USE_WINSOCK)) if (n == 0) { errno = ETIMEDOUT; } #endif return -1; } #if HAVE_OPENSSL_EXT if (ftp->use_ssl && ftp->fd == s && ftp->ssl_active) { sent = SSL_write(ftp->ssl_handle, buf, size); } else if (ftp->use_ssl && ftp->fd != s && ftp->use_ssl_for_data && ftp->data->ssl_active) { sent = SSL_write(ftp->data->ssl_handle, buf, size); } else { #endif sent = send(s, buf, size, 0); #if HAVE_OPENSSL_EXT } #endif if (sent == -1) { return -1; } buf = (char*) buf + sent; size -= sent; } return len; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Fix bug #69545 - avoid overflow when reading list'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ftp_put(ftpbuf_t *ftp, const char *path, php_stream *instream, ftptype_t type, long startpos TSRMLS_DC) { databuf_t *data = NULL; long size; char *ptr; int ch; char arg[11]; if (ftp == NULL) { return 0; } if (!ftp_type(ftp, type)) { goto bail; } if ((data = ftp_getdata(ftp TSRMLS_CC)) == NULL) { goto bail; } ftp->data = data; if (startpos > 0) { snprintf(arg, sizeof(arg), "%ld", startpos); if (!ftp_putcmd(ftp, "REST", arg)) { goto bail; } if (!ftp_getresp(ftp) || (ftp->resp != 350)) { goto bail; } } if (!ftp_putcmd(ftp, "STOR", path)) { goto bail; } if (!ftp_getresp(ftp) || (ftp->resp != 150 && ftp->resp != 125)) { goto bail; } if ((data = data_accept(data, ftp TSRMLS_CC)) == NULL) { goto bail; } size = 0; ptr = data->buf; while (!php_stream_eof(instream) && (ch = php_stream_getc(instream))!=EOF) { /* flush if necessary */ if (FTP_BUFSIZE - size < 2) { if (my_send(ftp, data->fd, data->buf, size) != size) { goto bail; } ptr = data->buf; size = 0; } if (ch == '\n' && type == FTPTYPE_ASCII) { *ptr++ = '\r'; size++; } *ptr++ = ch; size++; } if (size && my_send(ftp, data->fd, data->buf, size) != size) { goto bail; } ftp->data = data = data_close(ftp, data); if (!ftp_getresp(ftp) || (ftp->resp != 226 && ftp->resp != 250 && ftp->resp != 200)) { goto bail; } return 1; bail: ftp->data = data_close(ftp, data); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Fix bug #69545 - avoid overflow when reading list'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ftp_nb_continue_write(ftpbuf_t *ftp TSRMLS_DC) { long size; char *ptr; int ch; /* check if we can write more data */ if (!data_writeable(ftp, ftp->data->fd)) { return PHP_FTP_MOREDATA; } size = 0; ptr = ftp->data->buf; while (!php_stream_eof(ftp->stream) && (ch = php_stream_getc(ftp->stream)) != EOF) { if (ch == '\n' && ftp->type == FTPTYPE_ASCII) { *ptr++ = '\r'; size++; } *ptr++ = ch; size++; /* flush if necessary */ if (FTP_BUFSIZE - size < 2) { if (my_send(ftp, ftp->data->fd, ftp->data->buf, size) != size) { goto bail; } return PHP_FTP_MOREDATA; } } if (size && my_send(ftp, ftp->data->fd, ftp->data->buf, size) != size) { goto bail; } ftp->data = data_close(ftp, ftp->data); if (!ftp_getresp(ftp) || (ftp->resp != 226 && ftp->resp != 250)) { goto bail; } ftp->nb = 0; return PHP_FTP_FINISHED; bail: ftp->data = data_close(ftp, ftp->data); ftp->nb = 0; return PHP_FTP_FAILED; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Fix bug #69545 - avoid overflow when reading list'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ftp_alloc(ftpbuf_t *ftp, const long size, char **response) { char buffer[64]; if (ftp == NULL || size <= 0) { return 0; } snprintf(buffer, sizeof(buffer) - 1, "%ld", size); if (!ftp_putcmd(ftp, "ALLO", buffer)) { return 0; } if (!ftp_getresp(ftp)) { return 0; } if (response) { *response = estrdup(ftp->inbuf); } if (ftp->resp < 200 || ftp->resp >= 300) { return 0; } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Fix bug #69545 - avoid overflow when reading list'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ftp_pwd(ftpbuf_t *ftp) { char *pwd, *end; if (ftp == NULL) { return NULL; } /* default to cached value */ if (ftp->pwd) { return ftp->pwd; } if (!ftp_putcmd(ftp, "PWD", NULL)) { return NULL; } if (!ftp_getresp(ftp) || ftp->resp != 257) { return NULL; } /* copy out the pwd from response */ if ((pwd = strchr(ftp->inbuf, '"')) == NULL) { return NULL; } if ((end = strrchr(++pwd, '"')) == NULL) { return NULL; } ftp->pwd = estrndup(pwd, end - pwd); return ftp->pwd; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Fix bug #69545 - avoid overflow when reading list'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ftp_syst(ftpbuf_t *ftp) { char *syst, *end; if (ftp == NULL) { return NULL; } /* default to cached value */ if (ftp->syst) { return ftp->syst; } if (!ftp_putcmd(ftp, "SYST", NULL)) { return NULL; } if (!ftp_getresp(ftp) || ftp->resp != 215) { return NULL; } syst = ftp->inbuf; while (*syst == ' ') { syst++; } if ((end = strchr(syst, ' '))) { *end = 0; } ftp->syst = estrdup(syst); if (end) { *end = ' '; } return ftp->syst; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Fix bug #69545 - avoid overflow when reading list'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ftp_nb_put(ftpbuf_t *ftp, const char *path, php_stream *instream, ftptype_t type, long startpos TSRMLS_DC) { databuf_t *data = NULL; char arg[11]; if (ftp == NULL) { return 0; } if (!ftp_type(ftp, type)) { goto bail; } if ((data = ftp_getdata(ftp TSRMLS_CC)) == NULL) { goto bail; } if (startpos > 0) { snprintf(arg, sizeof(arg), "%ld", startpos); if (!ftp_putcmd(ftp, "REST", arg)) { goto bail; } if (!ftp_getresp(ftp) || (ftp->resp != 350)) { goto bail; } } if (!ftp_putcmd(ftp, "STOR", path)) { goto bail; } if (!ftp_getresp(ftp) || (ftp->resp != 150 && ftp->resp != 125)) { goto bail; } if ((data = data_accept(data, ftp TSRMLS_CC)) == NULL) { goto bail; } ftp->data = data; ftp->stream = instream; ftp->lastch = 0; ftp->nb = 1; return (ftp_nb_continue_write(ftp TSRMLS_CC)); bail: ftp->data = data_close(ftp, data); return PHP_FTP_FAILED; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Fix bug #69545 - avoid overflow when reading list'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ftp_genlist(ftpbuf_t *ftp, const char *cmd, const char *path TSRMLS_DC) { php_stream *tmpstream = NULL; databuf_t *data = NULL; char *ptr; int ch, lastch; int size, rcvd; int lines; char **ret = NULL; char **entry; char *text; if ((tmpstream = php_stream_fopen_tmpfile()) == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create temporary file. Check permissions in temporary files directory."); return NULL; } if (!ftp_type(ftp, FTPTYPE_ASCII)) { goto bail; } if ((data = ftp_getdata(ftp TSRMLS_CC)) == NULL) { goto bail; } ftp->data = data; if (!ftp_putcmd(ftp, cmd, path)) { goto bail; } if (!ftp_getresp(ftp) || (ftp->resp != 150 && ftp->resp != 125 && ftp->resp != 226)) { goto bail; } /* some servers don't open a ftp-data connection if the directory is empty */ if (ftp->resp == 226) { ftp->data = data_close(ftp, data); php_stream_close(tmpstream); return ecalloc(1, sizeof(char**)); } /* pull data buffer into tmpfile */ if ((data = data_accept(data, ftp TSRMLS_CC)) == NULL) { goto bail; } size = 0; lines = 0; lastch = 0; while ((rcvd = my_recv(ftp, data->fd, data->buf, FTP_BUFSIZE))) { if (rcvd == -1) { goto bail; } php_stream_write(tmpstream, data->buf, rcvd); size += rcvd; for (ptr = data->buf; rcvd; rcvd--, ptr++) { if (*ptr == '\n' && lastch == '\r') { lines++; } else { size++; } lastch = *ptr; } } ftp->data = data = data_close(ftp, data); php_stream_rewind(tmpstream); ret = safe_emalloc((lines + 1), sizeof(char**), size * sizeof(char*)); entry = ret; text = (char*) (ret + lines + 1); *entry = text; lastch = 0; while ((ch = php_stream_getc(tmpstream)) != EOF) { if (ch == '\n' && lastch == '\r') { *(text - 1) = 0; *++entry = text; } else { *text++ = ch; } lastch = ch; } *entry = NULL; php_stream_close(tmpstream); if (!ftp_getresp(ftp) || (ftp->resp != 226 && ftp->resp != 250)) { efree(ret); return NULL; } return ret; bail: ftp->data = data_close(ftp, data); php_stream_close(tmpstream); if (ret) efree(ret); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Minor Coverity tweaks'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int phar_parse_tarfile(php_stream* fp, char *fname, int fname_len, char *alias, int alias_len, phar_archive_data** pphar, int is_data, php_uint32 compression, char **error TSRMLS_DC) /* {{{ */ { char buf[512], *actual_alias = NULL, *p; phar_entry_info entry = {0}; size_t pos = 0, read, totalsize; tar_header *hdr; php_uint32 sum1, sum2, size, old; phar_archive_data *myphar, **actual; int last_was_longlink = 0; if (error) { *error = NULL; } php_stream_seek(fp, 0, SEEK_END); totalsize = php_stream_tell(fp); php_stream_seek(fp, 0, SEEK_SET); read = php_stream_read(fp, buf, sizeof(buf)); if (read != sizeof(buf)) { if (error) { spprintf(error, 4096, "phar error: \"%s\" is not a tar file or is truncated", fname); } php_stream_close(fp); return FAILURE; } hdr = (tar_header*)buf; old = (memcmp(hdr->magic, "ustar", sizeof("ustar")-1) != 0); myphar = (phar_archive_data *) pecalloc(1, sizeof(phar_archive_data), PHAR_G(persist)); myphar->is_persistent = PHAR_G(persist); /* estimate number of entries, can't be certain with tar files */ zend_hash_init(&myphar->manifest, 2 + (totalsize >> 12), zend_get_hash_value, destroy_phar_manifest_entry, (zend_bool)myphar->is_persistent); zend_hash_init(&myphar->mounted_dirs, 5, zend_get_hash_value, NULL, (zend_bool)myphar->is_persistent); zend_hash_init(&myphar->virtual_dirs, 4 + (totalsize >> 11), zend_get_hash_value, NULL, (zend_bool)myphar->is_persistent); myphar->is_tar = 1; /* remember whether this entire phar was compressed with gz/bzip2 */ myphar->flags = compression; entry.is_tar = 1; entry.is_crc_checked = 1; entry.phar = myphar; pos += sizeof(buf); do { phar_entry_info *newentry; pos = php_stream_tell(fp); hdr = (tar_header*) buf; sum1 = phar_tar_number(hdr->checksum, sizeof(hdr->checksum)); if (sum1 == 0 && phar_tar_checksum(buf, sizeof(buf)) == 0) { break; } memset(hdr->checksum, ' ', sizeof(hdr->checksum)); sum2 = phar_tar_checksum(buf, old?sizeof(old_tar_header):sizeof(tar_header)); size = entry.uncompressed_filesize = entry.compressed_filesize = phar_tar_number(hdr->size, sizeof(hdr->size)); if (((!old && hdr->prefix[0] == 0) || old) && strlen(hdr->name) == sizeof(".phar/signature.bin")-1 && !strncmp(hdr->name, ".phar/signature.bin", sizeof(".phar/signature.bin")-1)) { off_t curloc; if (size > 511) { if (error) { spprintf(error, 4096, "phar error: tar-based phar \"%s\" has signature that is larger than 511 bytes, cannot process", fname); } bail: php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } curloc = php_stream_tell(fp); read = php_stream_read(fp, buf, size); if (read != size) { if (error) { spprintf(error, 4096, "phar error: tar-based phar \"%s\" signature cannot be read", fname); } goto bail; } #ifdef WORDS_BIGENDIAN # define PHAR_GET_32(buffer) \ (((((unsigned char*)(buffer))[3]) << 24) \ | ((((unsigned char*)(buffer))[2]) << 16) \ | ((((unsigned char*)(buffer))[1]) << 8) \ | (((unsigned char*)(buffer))[0])) #else # define PHAR_GET_32(buffer) (php_uint32) *(buffer) #endif myphar->sig_flags = PHAR_GET_32(buf); if (FAILURE == phar_verify_signature(fp, php_stream_tell(fp) - size - 512, myphar->sig_flags, buf + 8, size - 8, fname, &myphar->signature, &myphar->sig_len, error TSRMLS_CC)) { if (error) { char *save = *error; spprintf(error, 4096, "phar error: tar-based phar \"%s\" signature cannot be verified: %s", fname, save); efree(save); } goto bail; } php_stream_seek(fp, curloc + 512, SEEK_SET); /* signature checked out, let's ensure this is the last file in the phar */ if (((hdr->typeflag == '\0') || (hdr->typeflag == TAR_FILE)) && size > 0) { /* this is not good enough - seek succeeds even on truncated tars */ php_stream_seek(fp, 512, SEEK_CUR); if ((uint)php_stream_tell(fp) > totalsize) { if (error) { spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } } read = php_stream_read(fp, buf, sizeof(buf)); if (read != sizeof(buf)) { if (error) { spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } hdr = (tar_header*) buf; sum1 = phar_tar_number(hdr->checksum, sizeof(hdr->checksum)); if (sum1 == 0 && phar_tar_checksum(buf, sizeof(buf)) == 0) { break; } if (error) { spprintf(error, 4096, "phar error: \"%s\" has entries after signature, invalid phar", fname); } goto bail; } if (!last_was_longlink && hdr->typeflag == 'L') { last_was_longlink = 1; /* support the ././@LongLink system for storing long filenames */ entry.filename_len = entry.uncompressed_filesize; /* Check for overflow - bug 61065 */ if (entry.filename_len == UINT_MAX) { if (error) { spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (invalid entry size)", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } entry.filename = pemalloc(entry.filename_len+1, myphar->is_persistent); read = php_stream_read(fp, entry.filename, entry.filename_len); if (read != entry.filename_len) { efree(entry.filename); if (error) { spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } entry.filename[entry.filename_len] = '\0'; /* skip blank stuff */ size = ((size+511)&~511) - size; /* this is not good enough - seek succeeds even on truncated tars */ php_stream_seek(fp, size, SEEK_CUR); if ((uint)php_stream_tell(fp) > totalsize) { efree(entry.filename); if (error) { spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } read = php_stream_read(fp, buf, sizeof(buf)); if (read != sizeof(buf)) { efree(entry.filename); if (error) { spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } continue; } else if (!last_was_longlink && !old && hdr->prefix[0] != 0) { char name[256]; int i, j; for (i = 0; i < 155; i++) { name[i] = hdr->prefix[i]; if (name[i] == '\0') { break; } } name[i++] = '/'; for (j = 0; j < 100; j++) { name[i+j] = hdr->name[j]; if (name[i+j] == '\0') { break; } } entry.filename_len = i+j; if (name[entry.filename_len - 1] == '/') { /* some tar programs store directories with trailing slash */ entry.filename_len--; } entry.filename = pestrndup(name, entry.filename_len, myphar->is_persistent); } else if (!last_was_longlink) { int i; /* calculate strlen, which can be no longer than 100 */ for (i = 0; i < 100; i++) { if (hdr->name[i] == '\0') { break; } } entry.filename_len = i; entry.filename = pestrndup(hdr->name, i, myphar->is_persistent); if (entry.filename[entry.filename_len - 1] == '/') { /* some tar programs store directories with trailing slash */ entry.filename[entry.filename_len - 1] = '\0'; entry.filename_len--; } } last_was_longlink = 0; phar_add_virtual_dirs(myphar, entry.filename, entry.filename_len TSRMLS_CC); if (sum1 != sum2) { if (error) { spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (checksum mismatch of file \"%s\")", fname, entry.filename); } pefree(entry.filename, myphar->is_persistent); php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } entry.tar_type = ((old & (hdr->typeflag == '\0')) ? TAR_FILE : hdr->typeflag); entry.offset = entry.offset_abs = pos; /* header_offset unused in tar */ entry.fp_type = PHAR_FP; entry.flags = phar_tar_number(hdr->mode, sizeof(hdr->mode)) & PHAR_ENT_PERM_MASK; entry.timestamp = phar_tar_number(hdr->mtime, sizeof(hdr->mtime)); entry.is_persistent = myphar->is_persistent; #ifndef S_ISDIR #define S_ISDIR(mode) (((mode)&S_IFMT) == S_IFDIR) #endif if (old && entry.tar_type == TAR_FILE && S_ISDIR(entry.flags)) { entry.tar_type = TAR_DIR; } if (entry.tar_type == TAR_DIR) { entry.is_dir = 1; } else { entry.is_dir = 0; } entry.link = NULL; if (entry.tar_type == TAR_LINK) { if (!zend_hash_exists(&myphar->manifest, hdr->linkname, strlen(hdr->linkname))) { if (error) { spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file - hard link to non-existent file \"%s\"", fname, hdr->linkname); } pefree(entry.filename, entry.is_persistent); php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } entry.link = estrdup(hdr->linkname); } else if (entry.tar_type == TAR_SYMLINK) { entry.link = estrdup(hdr->linkname); } phar_set_inode(&entry TSRMLS_CC); zend_hash_add(&myphar->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info), (void **) &newentry); if (entry.is_persistent) { ++entry.manifest_pos; } if (entry.filename_len >= sizeof(".phar/.metadata")-1 && !memcmp(entry.filename, ".phar/.metadata", sizeof(".phar/.metadata")-1)) { if (FAILURE == phar_tar_process_metadata(newentry, fp TSRMLS_CC)) { if (error) { spprintf(error, 4096, "phar error: tar-based phar \"%s\" has invalid metadata in magic file \"%s\"", fname, entry.filename); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } } if (!actual_alias && entry.filename_len == sizeof(".phar/alias.txt")-1 && !strncmp(entry.filename, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) { /* found explicit alias */ if (size > 511) { if (error) { spprintf(error, 4096, "phar error: tar-based phar \"%s\" has alias that is larger than 511 bytes, cannot process", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } read = php_stream_read(fp, buf, size); if (read == size) { buf[size] = '\0'; if (!phar_validate_alias(buf, size)) { if (size > 50) { buf[50] = '.'; buf[51] = '.'; buf[52] = '.'; buf[53] = '\0'; } if (error) { spprintf(error, 4096, "phar error: invalid alias \"%s\" in tar-based phar \"%s\"", buf, fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } actual_alias = pestrndup(buf, size, myphar->is_persistent); myphar->alias = actual_alias; myphar->alias_len = size; php_stream_seek(fp, pos, SEEK_SET); } else { if (error) { spprintf(error, 4096, "phar error: Unable to read alias from tar-based phar \"%s\"", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } } size = (size+511)&~511; if (((hdr->typeflag == '\0') || (hdr->typeflag == TAR_FILE)) && size > 0) { /* this is not good enough - seek succeeds even on truncated tars */ php_stream_seek(fp, size, SEEK_CUR); if ((uint)php_stream_tell(fp) > totalsize) { if (error) { spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } } read = php_stream_read(fp, buf, sizeof(buf)); if (read != sizeof(buf)) { if (error) { spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } } while (read != 0); if (zend_hash_exists(&(myphar->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1)) { myphar->is_data = 0; } else { myphar->is_data = 1; } /* ensure signature set */ if (!myphar->is_data && PHAR_G(require_hash) && !myphar->signature) { php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); if (error) { spprintf(error, 0, "tar-based phar \"%s\" does not have a signature", fname); } return FAILURE; } myphar->fname = pestrndup(fname, fname_len, myphar->is_persistent); #ifdef PHP_WIN32 phar_unixify_path_separators(myphar->fname, fname_len); #endif myphar->fname_len = fname_len; myphar->fp = fp; p = strrchr(myphar->fname, '/'); if (p) { myphar->ext = memchr(p, '.', (myphar->fname + fname_len) - p); if (myphar->ext == p) { myphar->ext = memchr(p + 1, '.', (myphar->fname + fname_len) - p - 1); } if (myphar->ext) { myphar->ext_len = (myphar->fname + fname_len) - myphar->ext; } } phar_request_initialize(TSRMLS_C); if (SUCCESS != zend_hash_add(&(PHAR_GLOBALS->phar_fname_map), myphar->fname, fname_len, (void*)&myphar, sizeof(phar_archive_data*), (void **)&actual)) { if (error) { spprintf(error, 4096, "phar error: Unable to add tar-based phar \"%s\" to phar registry", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } myphar = *actual; if (actual_alias) { phar_archive_data **fd_ptr; myphar->is_temporary_alias = 0; if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), actual_alias, myphar->alias_len, (void **)&fd_ptr)) { if (SUCCESS != phar_free_alias(*fd_ptr, actual_alias, myphar->alias_len TSRMLS_CC)) { if (error) { spprintf(error, 4096, "phar error: Unable to add tar-based phar \"%s\", alias is already in use", fname); } zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), myphar->fname, fname_len); return FAILURE; } } zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), actual_alias, myphar->alias_len, (void*)&myphar, sizeof(phar_archive_data*), NULL); } else { phar_archive_data **fd_ptr; if (alias_len) { if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void **)&fd_ptr)) { if (SUCCESS != phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) { if (error) { spprintf(error, 4096, "phar error: Unable to add tar-based phar \"%s\", alias is already in use", fname); } zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), myphar->fname, fname_len); return FAILURE; } } zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void*)&myphar, sizeof(phar_archive_data*), NULL); myphar->alias = pestrndup(alias, alias_len, myphar->is_persistent); myphar->alias_len = alias_len; } else { myphar->alias = pestrndup(myphar->fname, fname_len, myphar->is_persistent); myphar->alias_len = fname_len; } myphar->is_temporary_alias = 1; } if (pphar) { *pphar = myphar; } return SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Fix bug #69453 - don't try to cut empty string'</s>
<s>[INST] Given the following code containing errors, provide 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 krb5_error_code verify_krb5_user(krb5_context context, krb5_principal principal, const char *password, krb5_principal server) { krb5_creds creds; krb5_get_init_creds_opt gic_options; krb5_error_code ret; char *name = NULL; memset(&creds, 0, sizeof(creds)); ret = krb5_unparse_name(context, principal, &name); if (ret == 0) { #ifdef PRINTFS printf("Trying to get TGT for user %s\n", name); #endif free(name); } krb5_get_init_creds_opt_init(&gic_options); ret = krb5_get_init_creds_password(context, &creds, principal, (char *)password, NULL, NULL, 0, NULL, &gic_options); if (ret) { set_basicauth_error(context, ret); goto end; } end: krb5_free_cred_contents(context, &creds); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-287'], 'message': 'adding KDC verification support (enabled by default)'</s>
<s>[INST] Given the following code containing errors, provide 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 check_client_passwd(PgSocket *client, const char *passwd) { char md5[MD5_PASSWD_LEN + 1]; const char *correct; PgUser *user = client->auth_user; /* disallow empty passwords */ if (!*passwd || !*user->passwd) return false; switch (cf_auth_type) { case AUTH_PLAIN: return strcmp(user->passwd, passwd) == 0; case AUTH_CRYPT: correct = crypt(user->passwd, (char *)client->tmp_login_salt); return correct && strcmp(correct, passwd) == 0; case AUTH_MD5: if (strlen(passwd) != MD5_PASSWD_LEN) return false; if (!isMD5(user->passwd)) pg_md5_encrypt(user->passwd, user->name, strlen(user->name), user->passwd); pg_md5_encrypt(user->passwd + 3, (char *)client->tmp_login_salt, 4, md5); return strcmp(md5, passwd) == 0; } return false; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Check if auth_user is set. Fixes a crash if password packet appears before startup packet (#42).'</s>
<s>[INST] Given the following code containing errors, provide 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 serveloop(GArray* servers) { struct sockaddr_storage addrin; socklen_t addrinlen=sizeof(addrin); int i; int max; fd_set mset; fd_set rset; /* * Set up the master fd_set. The set of descriptors we need * to select() for never changes anyway and it buys us a *lot* * of time to only build this once. However, if we ever choose * to not fork() for clients anymore, we may have to revisit * this. */ max=0; FD_ZERO(&mset); for(i=0;i<servers->len;i++) { int sock; if((sock=(g_array_index(servers, SERVER, i)).socket) >= 0) { FD_SET(sock, &mset); max=sock>max?sock:max; } } for(i=0;i<modernsocks->len;i++) { int sock = g_array_index(modernsocks, int, i); FD_SET(sock, &mset); max=sock>max?sock:max; } for(;;) { /* SIGHUP causes the root server process to reconfigure * itself and add new export servers for each newly * found export configuration group, i.e. spawn new * server processes for each previously non-existent * export. This does not alter old runtime configuration * but just appends new exports. */ if (is_sighup_caught) { int n; GError *gerror = NULL; msg(LOG_INFO, "reconfiguration request received"); is_sighup_caught = 0; /* Reset to allow catching * it again. */ n = append_new_servers(servers, &gerror); if (n == -1) msg(LOG_ERR, "failed to append new servers: %s", gerror->message); for (i = servers->len - n; i < servers->len; ++i) { const SERVER server = g_array_index(servers, SERVER, i); if (server.socket >= 0) { FD_SET(server.socket, &mset); max = server.socket > max ? server.socket : max; } msg(LOG_INFO, "reconfigured new server: %s", server.servename); } } memcpy(&rset, &mset, sizeof(fd_set)); if(select(max+1, &rset, NULL, NULL, NULL)>0) { int net; DEBUG("accept, "); for(i=0; i < modernsocks->len; i++) { int sock = g_array_index(modernsocks, int, i); if(!FD_ISSET(sock, &rset)) { continue; } CLIENT *client; if((net=accept(sock, (struct sockaddr *) &addrin, &addrinlen)) < 0) { err_nonfatal("accept: %m"); continue; } client = negotiate(net, NULL, servers, NEG_INIT | NEG_MODERN); if(!client) { close(net); continue; } handle_connection(servers, net, client->server, client); } for(i=0; i < servers->len; i++) { SERVER *serve; serve=&(g_array_index(servers, SERVER, i)); if(serve->socket < 0) { continue; } if(FD_ISSET(serve->socket, &rset)) { if ((net=accept(serve->socket, (struct sockaddr *) &addrin, &addrinlen)) < 0) { err_nonfatal("accept: %m"); continue; } handle_connection(servers, net, serve, NULL); } } } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-310'], 'message': 'nbd-server: handle modern-style negotiation in a child process Previously, the modern style negotiation was carried out in the root server (listener) process before forking the actual client handler. This made it possible for a malfunctioning or evil client to terminate the root process simply by querying a non-existent export or aborting in the middle of the negotation process (caused SIGPIPE in the server). This commit moves the negotiation process to the child to keep the root process up and running no matter what happens during the negotiation. See http://sourceforge.net/mailarchive/message.php?msg_id=30410146 Signed-off-by: Tuomas Räsänen <[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 CNB::SetupLSO(virtio_net_hdr_basic *VirtioHeader, PVOID IpHeader, ULONG EthPayloadLength) const { PopulateIPLength(reinterpret_cast<IPv4Header*>(IpHeader), static_cast<USHORT>(EthPayloadLength)); tTcpIpPacketParsingResult packetReview; packetReview = ParaNdis_CheckSumVerifyFlat(reinterpret_cast<IPv4Header*>(IpHeader), EthPayloadLength, pcrIpChecksum | pcrFixIPChecksum | pcrTcpChecksum | pcrFixPHChecksum, __FUNCTION__); if (packetReview.xxpCheckSum == ppresPCSOK || packetReview.fixedXxpCS) { auto IpHeaderOffset = m_Context->Offload.ipHeaderOffset; auto VHeader = static_cast<virtio_net_hdr_basic*>(VirtioHeader); auto PriorityHdrLen = (m_ParentNBL->TCI() != 0) ? ETH_PRIORITY_HEADER_SIZE : 0; VHeader->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM; VHeader->gso_type = packetReview.ipStatus == ppresIPV4 ? VIRTIO_NET_HDR_GSO_TCPV4 : VIRTIO_NET_HDR_GSO_TCPV6; VHeader->hdr_len = (USHORT)(packetReview.XxpIpHeaderSize + IpHeaderOffset + PriorityHdrLen); VHeader->gso_size = (USHORT)m_ParentNBL->MSS(); VHeader->csum_start = (USHORT)(m_ParentNBL->TCPHeaderOffset() + PriorityHdrLen); VHeader->csum_offset = TCP_CHECKSUM_OFFSET; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'NetKVM: BZ#1169718: Checking the length only on read Signed-off-by: Joseph Hindin <[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: tTcpIpPacketParsingResult ParaNdis_CheckSumVerify( tCompletePhysicalAddress *pDataPages, ULONG ulDataLength, ULONG ulStartOffset, ULONG flags, LPCSTR caller) { IPHeader *pIpHeader = (IPHeader *) RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset); tTcpIpPacketParsingResult res = QualifyIpPacket(pIpHeader, ulDataLength); if (res.ipStatus == ppresNotIP || res.ipCheckSum == ppresIPTooShort) return res; if (res.ipStatus == ppresIPV4) { if (flags & pcrIpChecksum) res = VerifyIpChecksum(&pIpHeader->v4, res, (flags & pcrFixIPChecksum) != 0); if(res.xxpStatus == ppresXxpKnown) { if (res.TcpUdp == ppresIsTCP) /* TCP */ { if(flags & pcrTcpV4Checksum) { res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV4Checksum)); } } else /* UDP */ { if (flags & pcrUdpV4Checksum) { res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV4Checksum)); } } } } else if (res.ipStatus == ppresIPV6) { if(res.xxpStatus == ppresXxpKnown) { if (res.TcpUdp == ppresIsTCP) /* TCP */ { if(flags & pcrTcpV6Checksum) { res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV6Checksum)); } } else /* UDP */ { if (flags & pcrUdpV6Checksum) { res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV6Checksum)); } } } } PrintOutParsingResult(res, 1, caller); return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'NetKVM: BZ#1169718: Checking the length only on read Signed-off-by: Joseph Hindin <[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: tTcpIpPacketParsingResult ParaNdis_CheckSumVerifyFlat( PVOID pBuffer, ULONG ulDataLength, ULONG flags, LPCSTR caller) { tCompletePhysicalAddress SGBuffer; SGBuffer.Virtual = pBuffer; SGBuffer.size = ulDataLength; return ParaNdis_CheckSumVerify(&SGBuffer, ulDataLength, 0, flags, caller); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'NetKVM: BZ#1169718: Checking the length only on read Signed-off-by: Joseph Hindin <[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: tTcpIpPacketParsingResult ParaNdis_ReviewIPPacket(PVOID buffer, ULONG size, LPCSTR caller) { tTcpIpPacketParsingResult res = QualifyIpPacket((IPHeader *) buffer, size); PrintOutParsingResult(res, 1, caller); return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'NetKVM: BZ#1169718: Checking the length only on read Signed-off-by: Joseph Hindin <[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: tChecksumCheckResult ParaNdis_CheckRxChecksum( PARANDIS_ADAPTER *pContext, ULONG virtioFlags, tCompletePhysicalAddress *pPacketPages, ULONG ulPacketLength, ULONG ulDataOffset) { tOffloadSettingsFlags f = pContext->Offload.flags; tChecksumCheckResult res, resIp; tTcpIpPacketParsingResult ppr; ULONG flagsToCalculate = 0; res.value = 0; resIp.value = 0; //VIRTIO_NET_HDR_F_NEEDS_CSUM - we need to calculate TCP/UDP CS //VIRTIO_NET_HDR_F_DATA_VALID - host tells us TCP/UDP CS is OK if (f.fRxIPChecksum) flagsToCalculate |= pcrIpChecksum; // check only if (!(virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID)) { if (virtioFlags & VIRTIO_NET_HDR_F_NEEDS_CSUM) { flagsToCalculate |= pcrFixXxpChecksum | pcrTcpChecksum | pcrUdpChecksum; } else { if (f.fRxTCPChecksum) flagsToCalculate |= pcrTcpV4Checksum; if (f.fRxUDPChecksum) flagsToCalculate |= pcrUdpV4Checksum; if (f.fRxTCPv6Checksum) flagsToCalculate |= pcrTcpV6Checksum; if (f.fRxUDPv6Checksum) flagsToCalculate |= pcrUdpV6Checksum; } } ppr = ParaNdis_CheckSumVerify(pPacketPages, ulPacketLength - ETH_HEADER_SIZE, ulDataOffset + ETH_HEADER_SIZE, flagsToCalculate, __FUNCTION__); if (virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID) { pContext->extraStatistics.framesRxCSHwOK++; ppr.xxpCheckSum = ppresCSOK; } if (ppr.ipStatus == ppresIPV4 && !ppr.IsFragment) { if (f.fRxIPChecksum) { res.flags.IpOK = ppr.ipCheckSum == ppresCSOK; res.flags.IpFailed = ppr.ipCheckSum == ppresCSBad; } if(ppr.xxpStatus == ppresXxpKnown) { if(ppr.TcpUdp == ppresIsTCP) /* TCP */ { if (f.fRxTCPChecksum) { res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; res.flags.TcpFailed = !res.flags.TcpOK; } } else /* UDP */ { if (f.fRxUDPChecksum) { res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; res.flags.UdpFailed = !res.flags.UdpOK; } } } } else if (ppr.ipStatus == ppresIPV6) { if(ppr.xxpStatus == ppresXxpKnown) { if(ppr.TcpUdp == ppresIsTCP) /* TCP */ { if (f.fRxTCPv6Checksum) { res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; res.flags.TcpFailed = !res.flags.TcpOK; } } else /* UDP */ { if (f.fRxUDPv6Checksum) { res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; res.flags.UdpFailed = !res.flags.UdpOK; } } } } return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'NetKVM: BZ#1169718: More rigoruous testing of incoming packet Signed-off-by: Joseph Hindin <[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: ProcessUDPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize) { tTcpIpPacketParsingResult res = _res; ULONG udpDataStart = ipHeaderSize + sizeof(UDPHeader); res.xxpStatus = ppresXxpIncomplete; res.TcpUdp = ppresIsUDP; res.XxpIpHeaderSize = udpDataStart; if (len >= udpDataStart) { UDPHeader *pUdpHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize); USHORT datagramLength = swap_short(pUdpHeader->udp_length); res.xxpStatus = ppresXxpKnown; // may be full or not, but the datagram length is known DPrintf(2, ("udp: len %d, datagramLength %d\n", len, datagramLength)); } return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'NetKVM: BZ#1169718: More rigoruous testing of incoming packet Signed-off-by: Joseph Hindin <[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: QualifyIpPacket(IPHeader *pIpHeader, ULONG len) { tTcpIpPacketParsingResult res; UCHAR ver_len = pIpHeader->v4.ip_verlen; UCHAR ip_version = (ver_len & 0xF0) >> 4; USHORT ipHeaderSize = 0; USHORT fullLength = 0; res.value = 0; if (ip_version == 4) { ipHeaderSize = (ver_len & 0xF) << 2; fullLength = swap_short(pIpHeader->v4.ip_length); DPrintf(3, ("ip_version %d, ipHeaderSize %d, protocol %d, iplen %d\n", ip_version, ipHeaderSize, pIpHeader->v4.ip_protocol, fullLength)); res.ipStatus = (ipHeaderSize >= sizeof(IPv4Header)) ? ppresIPV4 : ppresNotIP; if (len < ipHeaderSize) res.ipCheckSum = ppresIPTooShort; if (fullLength) {} else { DPrintf(2, ("ip v.%d, iplen %d\n", ip_version, fullLength)); } } else if (ip_version == 6) { UCHAR nextHeader = pIpHeader->v6.ip6_next_header; BOOLEAN bParsingDone = FALSE; ipHeaderSize = sizeof(pIpHeader->v6); res.ipStatus = ppresIPV6; res.ipCheckSum = ppresCSOK; fullLength = swap_short(pIpHeader->v6.ip6_payload_len); fullLength += ipHeaderSize; while (nextHeader != 59) { IPv6ExtHeader *pExt; switch (nextHeader) { case PROTOCOL_TCP: bParsingDone = TRUE; res.xxpStatus = ppresXxpKnown; res.TcpUdp = ppresIsTCP; res.xxpFull = len >= fullLength ? 1 : 0; res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize); break; case PROTOCOL_UDP: bParsingDone = TRUE; res.xxpStatus = ppresXxpKnown; res.TcpUdp = ppresIsUDP; res.xxpFull = len >= fullLength ? 1 : 0; res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize); break; //existing extended headers case 0: case 60: case 43: case 44: case 51: case 50: case 135: if (len >= ((ULONG)ipHeaderSize + 8)) { pExt = (IPv6ExtHeader *)((PUCHAR)pIpHeader + ipHeaderSize); nextHeader = pExt->ip6ext_next_header; ipHeaderSize += 8; ipHeaderSize += pExt->ip6ext_hdr_len * 8; } else { DPrintf(0, ("[%s] ERROR: Break in the middle of ext. headers(len %d, hdr > %d)\n", __FUNCTION__, len, ipHeaderSize)); res.ipStatus = ppresNotIP; bParsingDone = TRUE; } break; //any other protocol default: res.xxpStatus = ppresXxpOther; bParsingDone = TRUE; break; } if (bParsingDone) break; } if (ipHeaderSize <= MAX_SUPPORTED_IPV6_HEADERS) { DPrintf(3, ("ip_version %d, ipHeaderSize %d, protocol %d, iplen %d\n", ip_version, ipHeaderSize, nextHeader, fullLength)); res.ipHeaderSize = ipHeaderSize; } else { DPrintf(0, ("[%s] ERROR: IP chain is too large (%d)\n", __FUNCTION__, ipHeaderSize)); res.ipStatus = ppresNotIP; } } if (res.ipStatus == ppresIPV4) { res.ipHeaderSize = ipHeaderSize; res.xxpFull = len >= fullLength ? 1 : 0; // bit "more fragments" or fragment offset mean the packet is fragmented res.IsFragment = (pIpHeader->v4.ip_offset & ~0xC0) != 0; switch (pIpHeader->v4.ip_protocol) { case PROTOCOL_TCP: { res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize); } break; case PROTOCOL_UDP: { res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize); } break; default: res.xxpStatus = ppresXxpOther; break; } } return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'NetKVM: BZ#1169718: More rigoruous testing of incoming packet Signed-off-by: Joseph Hindin <[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 f_parser (lua_State *L, void *ud) { int i; Proto *tf; Closure *cl; struct SParser *p = cast(struct SParser *, ud); int c = luaZ_lookahead(p->z); luaC_checkGC(L); tf = ((c == LUA_SIGNATURE[0]) ? luaU_undump : luaY_parser)(L, p->z, &p->buff, p->name); cl = luaF_newLclosure(L, tf->nups, hvalue(gt(L))); cl->l.p = tf; for (i = 0; i < tf->nups; i++) /* initialize eventual upvalues */ cl->l.upvals[i] = luaF_newupval(L); setclvalue(L, L->top, cl); incr_top(L); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-17'], 'message': 'disable loading lua bytecode'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static uint64_t pit_ioport_read(void *opaque, hwaddr addr, unsigned size) { PITCommonState *pit = opaque; int ret, count; PITChannelState *s; addr &= 3; s = &pit->channels[addr]; if (s->status_latched) { s->status_latched = 0; ret = s->status; } else if (s->count_latched) { switch(s->count_latched) { default: case RW_STATE_LSB: ret = s->latched_count & 0xff; s->count_latched = 0; break; case RW_STATE_MSB: ret = s->latched_count >> 8; s->count_latched = 0; break; case RW_STATE_WORD0: ret = s->latched_count & 0xff; s->count_latched = RW_STATE_MSB; break; } } else { switch(s->read_state) { default: case RW_STATE_LSB: count = pit_get_count(s); ret = count & 0xff; break; case RW_STATE_MSB: count = pit_get_count(s); ret = (count >> 8) & 0xff; break; case RW_STATE_WORD0: count = pit_get_count(s); ret = count & 0xff; s->read_state = RW_STATE_WORD1; break; case RW_STATE_WORD1: count = pit_get_count(s); ret = (count >> 8) & 0xff; s->read_state = RW_STATE_WORD0; break; } } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'i8254: fix out-of-bounds memory access in pit_ioport_read() Due converting PIO to the new memory read/write api we no longer provide separate I/O region lenghts for read and write operations. As a result, reading from PIT Mode/Command register will end with accessing pit->channels with invalid index. Fix this by ignoring read from the Mode/Command register. This is CVE-2015-3214. Reported-by: Matt Tait <[email protected]> Fixes: 0505bcdec8228d8de39ab1a02644e71999e7c052 Cc: [email protected] Signed-off-by: Petr Matousek <[email protected]> Signed-off-by: Paolo Bonzini <[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 dom_load_html(INTERNAL_FUNCTION_PARAMETERS, int mode) /* {{{ */ { zval *id; xmlDoc *docp = NULL, *newdoc; dom_object *intern; dom_doc_propsptr doc_prop; char *source; int source_len, refcount, ret; long options = 0; htmlParserCtxtPtr ctxt; id = getThis(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|l", &source, &source_len, &options) == FAILURE) { return; } if (!source_len) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty string supplied as input"); RETURN_FALSE; } if (mode == DOM_LOAD_FILE) { ctxt = htmlCreateFileParserCtxt(source, NULL); } else { source_len = xmlStrlen(source); ctxt = htmlCreateMemoryParserCtxt(source, source_len); } if (!ctxt) { RETURN_FALSE; } if (options) { htmlCtxtUseOptions(ctxt, options); } ctxt->vctxt.error = php_libxml_ctx_error; ctxt->vctxt.warning = php_libxml_ctx_warning; if (ctxt->sax != NULL) { ctxt->sax->error = php_libxml_ctx_error; ctxt->sax->warning = php_libxml_ctx_warning; } htmlParseDocument(ctxt); newdoc = ctxt->myDoc; htmlFreeParserCtxt(ctxt); if (!newdoc) RETURN_FALSE; if (id != NULL && instanceof_function(Z_OBJCE_P(id), dom_document_class_entry TSRMLS_CC)) { intern = (dom_object *)zend_object_store_get_object(id TSRMLS_CC); if (intern != NULL) { docp = (xmlDocPtr) dom_object_get_node(intern); doc_prop = NULL; if (docp != NULL) { php_libxml_decrement_node_ptr((php_libxml_node_object *) intern TSRMLS_CC); doc_prop = intern->document->doc_props; intern->document->doc_props = NULL; refcount = php_libxml_decrement_doc_ref((php_libxml_node_object *)intern TSRMLS_CC); if (refcount != 0) { docp->_private = NULL; } } intern->document = NULL; if (php_libxml_increment_doc_ref((php_libxml_node_object *)intern, newdoc TSRMLS_CC) == -1) { RETURN_FALSE; } intern->document->doc_props = doc_prop; } php_libxml_increment_node_ptr((php_libxml_node_object *)intern, (xmlNodePtr)newdoc, (void *)intern TSRMLS_CC); RETURN_TRUE; } else { DOM_RET_OBJ((xmlNodePtr) newdoc, &ret, NULL); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix #69719 - more checks for nulls in paths'</s>
<s>[INST] Given the following code containing errors, provide 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(imagepsbbox) { zval *fnt; long sz = 0, sp = 0, wd = 0; char *str; int i, space = 0, add_width = 0, char_width, amount_kern; int cur_x, cur_y, dx, dy; int x1, y1, x2, y2, x3, y3, x4, y4; int *f_ind; int str_len, per_char = 0; int argc = ZEND_NUM_ARGS(); double angle = 0, sin_a = 0, cos_a = 0; BBox char_bbox, str_bbox = {0, 0, 0, 0}; if (argc != 3 && argc != 6) { ZEND_WRONG_PARAM_COUNT(); } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "srl|lld", &str, &str_len, &fnt, &sz, &sp, &wd, &angle) == FAILURE) { return; } if (argc == 6) { space = sp; add_width = wd; angle = angle * M_PI / 180; sin_a = sin(angle); cos_a = cos(angle); per_char = add_width || angle ? 1 : 0; } ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font); #define max(a, b) (a > b ? a : b) #define min(a, b) (a < b ? a : b) #define new_x(a, b) (int) ((a) * cos_a - (b) * sin_a) #define new_y(a, b) (int) ((a) * sin_a + (b) * cos_a) if (per_char) { space += T1_GetCharWidth(*f_ind, ' '); cur_x = cur_y = 0; for (i = 0; i < str_len; i++) { if (str[i] == ' ') { char_bbox.llx = char_bbox.lly = char_bbox.ury = 0; char_bbox.urx = char_width = space; } else { char_bbox = T1_GetCharBBox(*f_ind, str[i]); char_width = T1_GetCharWidth(*f_ind, str[i]); } amount_kern = i ? T1_GetKerning(*f_ind, str[i - 1], str[i]) : 0; /* Transfer character bounding box to right place */ x1 = new_x(char_bbox.llx, char_bbox.lly) + cur_x; y1 = new_y(char_bbox.llx, char_bbox.lly) + cur_y; x2 = new_x(char_bbox.llx, char_bbox.ury) + cur_x; y2 = new_y(char_bbox.llx, char_bbox.ury) + cur_y; x3 = new_x(char_bbox.urx, char_bbox.ury) + cur_x; y3 = new_y(char_bbox.urx, char_bbox.ury) + cur_y; x4 = new_x(char_bbox.urx, char_bbox.lly) + cur_x; y4 = new_y(char_bbox.urx, char_bbox.lly) + cur_y; /* Find min & max values and compare them with current bounding box */ str_bbox.llx = min(str_bbox.llx, min(x1, min(x2, min(x3, x4)))); str_bbox.lly = min(str_bbox.lly, min(y1, min(y2, min(y3, y4)))); str_bbox.urx = max(str_bbox.urx, max(x1, max(x2, max(x3, x4)))); str_bbox.ury = max(str_bbox.ury, max(y1, max(y2, max(y3, y4)))); /* Move to the next base point */ dx = new_x(char_width + add_width + amount_kern, 0); dy = new_y(char_width + add_width + amount_kern, 0); cur_x += dx; cur_y += dy; /* printf("%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n", x1, y1, x2, y2, x3, y3, x4, y4, char_bbox.llx, char_bbox.lly, char_bbox.urx, char_bbox.ury, char_width, amount_kern, cur_x, cur_y, dx, dy); */ } } else { str_bbox = T1_GetStringBBox(*f_ind, str, str_len, space, T1_KERNING); } if (T1_errno) { RETURN_FALSE; } array_init(return_value); /* printf("%d %d %d %d\n", str_bbox.llx, str_bbox.lly, str_bbox.urx, str_bbox.ury); */ add_next_index_long(return_value, (int) ceil(((double) str_bbox.llx)*sz/1000)); add_next_index_long(return_value, (int) ceil(((double) str_bbox.lly)*sz/1000)); add_next_index_long(return_value, (int) ceil(((double) str_bbox.urx)*sz/1000)); add_next_index_long(return_value, (int) ceil(((double) str_bbox.ury)*sz/1000)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix #69719 - more checks for nulls in paths'</s>
<s>[INST] Given the following code containing errors, provide 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(imagegrabwindow) { HWND window; long client_area = 0; RECT rc = {0}; RECT rc_win = {0}; int Width, Height; HDC hdc; HDC memDC; HBITMAP memBM; HBITMAP hOld; HINSTANCE handle; long lwindow_handle; typedef BOOL (WINAPI *tPrintWindow)(HWND, HDC,UINT); tPrintWindow pPrintWindow = 0; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|l", &lwindow_handle, &client_area) == FAILURE) { RETURN_FALSE; } window = (HWND) lwindow_handle; if (!IsWindow(window)) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid window handle"); RETURN_FALSE; } hdc = GetDC(0); if (client_area) { GetClientRect(window, &rc); Width = rc.right; Height = rc.bottom; } else { GetWindowRect(window, &rc); Width = rc.right - rc.left; Height = rc.bottom - rc.top; } Width = (Width/4)*4; memDC = CreateCompatibleDC(hdc); memBM = CreateCompatibleBitmap(hdc, Width, Height); hOld = (HBITMAP) SelectObject (memDC, memBM); handle = LoadLibrary("User32.dll"); if ( handle == 0 ) { goto clean; } pPrintWindow = (tPrintWindow) GetProcAddress(handle, "PrintWindow"); if ( pPrintWindow ) { pPrintWindow(window, memDC, (UINT) client_area); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Windows API too old"); goto clean; } FreeLibrary(handle); im = gdImageCreateTrueColor(Width, Height); if (im) { int x,y; for (y=0; y <= Height; y++) { for (x=0; x <= Width; x++) { int c = GetPixel(memDC, x,y); gdImageSetPixel(im, x, y, gdTrueColor(GetRValue(c), GetGValue(c), GetBValue(c))); } } } clean: SelectObject(memDC,hOld); DeleteObject(memBM); DeleteDC(memDC); ReleaseDC( 0, hdc ); if (!im) { RETURN_FALSE; } else { ZEND_REGISTER_RESOURCE(return_value, im, le_gd); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix #69719 - more checks for nulls in paths'</s>
<s>[INST] Given the following code containing errors, provide 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 _dom_document_schema_validate(INTERNAL_FUNCTION_PARAMETERS, int type) /* {{{ */ { zval *id; xmlDoc *docp; dom_object *intern; char *source = NULL, *valid_file = NULL; int source_len = 0; xmlSchemaParserCtxtPtr parser; xmlSchemaPtr sptr; xmlSchemaValidCtxtPtr vptr; int is_valid; char resolved_path[MAXPATHLEN + 1]; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Op", &id, dom_document_class_entry, &source, &source_len) == FAILURE) { return; } if (source_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Schema source"); RETURN_FALSE; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); switch (type) { case DOM_LOAD_FILE: valid_file = _dom_get_valid_file_path(source, resolved_path, MAXPATHLEN TSRMLS_CC); if (!valid_file) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Schema file source"); RETURN_FALSE; } parser = xmlSchemaNewParserCtxt(valid_file); break; case DOM_LOAD_STRING: parser = xmlSchemaNewMemParserCtxt(source, source_len); /* If loading from memory, we need to set the base directory for the document but it is not apparent how to do that for schema's */ break; default: return; } xmlSchemaSetParserErrors(parser, (xmlSchemaValidityErrorFunc) php_libxml_error_handler, (xmlSchemaValidityWarningFunc) php_libxml_error_handler, parser); sptr = xmlSchemaParse(parser); xmlSchemaFreeParserCtxt(parser); if (!sptr) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Schema"); RETURN_FALSE; } docp = (xmlDocPtr) dom_object_get_node(intern); vptr = xmlSchemaNewValidCtxt(sptr); if (!vptr) { xmlSchemaFree(sptr); php_error(E_ERROR, "Invalid Schema Validation Context"); RETURN_FALSE; } xmlSchemaSetValidErrors(vptr, php_libxml_error_handler, php_libxml_error_handler, vptr); is_valid = xmlSchemaValidateDoc(vptr, docp); xmlSchemaFree(sptr); xmlSchemaFreeValidCtxt(vptr); if (is_valid == 0) { RETURN_TRUE; } else { RETURN_FALSE; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix #69719 - more checks for nulls in paths'</s>
<s>[INST] Given the following code containing errors, provide 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_imagettftext_common(INTERNAL_FUNCTION_PARAMETERS, int mode, int extended) { zval *IM, *EXT = NULL; gdImagePtr im=NULL; long col = -1, x = -1, y = -1; int str_len, fontname_len, i, brect[8]; double ptsize, angle; char *str = NULL, *fontname = NULL; char *error = NULL; int argc = ZEND_NUM_ARGS(); #if HAVE_GD_STRINGFTEX gdFTStringExtra strex = {0}; #endif #if !HAVE_GD_STRINGFTEX assert(!extended); #endif if (mode == TTFTEXT_BBOX) { if (argc < 4 || argc > ((extended) ? 5 : 4)) { ZEND_WRONG_PARAM_COUNT(); } else if (zend_parse_parameters(argc TSRMLS_CC, "ddss|a", &ptsize, &angle, &fontname, &fontname_len, &str, &str_len, &EXT) == FAILURE) { RETURN_FALSE; } } else { if (argc < 8 || argc > ((extended) ? 9 : 8)) { ZEND_WRONG_PARAM_COUNT(); } else if (zend_parse_parameters(argc TSRMLS_CC, "rddlllss|a", &IM, &ptsize, &angle, &x, &y, &col, &fontname, &fontname_len, &str, &str_len, &EXT) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); } /* convert angle to radians */ angle = angle * (M_PI/180); #if HAVE_GD_STRINGFTEX if (extended && EXT) { /* parse extended info */ HashPosition pos; /* walk the assoc array */ zend_hash_internal_pointer_reset_ex(HASH_OF(EXT), &pos); do { zval ** item; char * key; ulong num_key; if (zend_hash_get_current_key_ex(HASH_OF(EXT), &key, NULL, &num_key, 0, &pos) != HASH_KEY_IS_STRING) { continue; } if (zend_hash_get_current_data_ex(HASH_OF(EXT), (void **) &item, &pos) == FAILURE) { continue; } if (strcmp("linespacing", key) == 0) { convert_to_double_ex(item); strex.flags |= gdFTEX_LINESPACE; strex.linespacing = Z_DVAL_PP(item); } } while (zend_hash_move_forward_ex(HASH_OF(EXT), &pos) == SUCCESS); } #endif #ifdef VIRTUAL_DIR { char tmp_font_path[MAXPATHLEN]; if (!VCWD_REALPATH(fontname, tmp_font_path)) { fontname = NULL; } } #endif PHP_GD_CHECK_OPEN_BASEDIR(fontname, "Invalid font filename"); #ifdef USE_GD_IMGSTRTTF # if HAVE_GD_STRINGFTEX if (extended) { error = gdImageStringFTEx(im, brect, col, fontname, ptsize, angle, x, y, str, &strex); } else # endif # if HAVE_GD_STRINGFT error = gdImageStringFT(im, brect, col, fontname, ptsize, angle, x, y, str); # elif HAVE_GD_STRINGTTF error = gdImageStringTTF(im, brect, col, fontname, ptsize, angle, x, y, str); # endif #endif if (error) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", error); RETURN_FALSE; } array_init(return_value); /* return array with the text's bounding box */ for (i = 0; i < 8; i++) { add_next_index_long(return_value, brect[i]); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix #69719 - more checks for nulls in paths'</s>
<s>[INST] Given the following code containing errors, provide 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(dom_document_save_html_file) { zval *id; xmlDoc *docp; int file_len, bytes, format; dom_object *intern; dom_doc_propsptr doc_props; char *file; const char *encoding; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &file, &file_len) == FAILURE) { return; } if (file_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Filename"); RETURN_FALSE; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); encoding = (const char *) htmlGetMetaEncoding(docp); doc_props = dom_get_doc_props(intern->document); format = doc_props->formatoutput; bytes = htmlSaveFileFormat(file, docp, encoding, format); if (bytes == -1) { RETURN_FALSE; } RETURN_LONG(bytes); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix #69719 - more checks for nulls in paths'</s>
<s>[INST] Given the following code containing errors, provide 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 bpf_int_jit_compile(struct bpf_prog *prog) { struct bpf_binary_header *header = NULL; int proglen, oldproglen = 0; struct jit_context ctx = {}; u8 *image = NULL; int *addrs; int pass; int i; if (!bpf_jit_enable) return; if (!prog || !prog->len) return; addrs = kmalloc(prog->len * sizeof(*addrs), GFP_KERNEL); if (!addrs) return; /* Before first pass, make a rough estimation of addrs[] * each bpf instruction is translated to less than 64 bytes */ for (proglen = 0, i = 0; i < prog->len; i++) { proglen += 64; addrs[i] = proglen; } ctx.cleanup_addr = proglen; for (pass = 0; pass < 10; pass++) { proglen = do_jit(prog, addrs, image, oldproglen, &ctx); if (proglen <= 0) { image = NULL; if (header) bpf_jit_binary_free(header); goto out; } if (image) { if (proglen != oldproglen) { pr_err("bpf_jit: proglen=%d != oldproglen=%d\n", proglen, oldproglen); goto out; } break; } if (proglen == oldproglen) { header = bpf_jit_binary_alloc(proglen, &image, 1, jit_fill_hole); if (!header) goto out; } oldproglen = proglen; } if (bpf_jit_enable > 1) bpf_jit_dump(prog->len, proglen, 0, image); if (image) { bpf_flush_icache(header, image + proglen); set_memory_ro((unsigned long)header, header->pages); prog->bpf_func = (void *)image; prog->jited = true; } out: kfree(addrs); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-17'], 'message': 'x86: bpf_jit: fix compilation of large bpf programs x86 has variable length encoding. x86 JIT compiler is trying to pick the shortest encoding for given bpf instruction. While doing so the jump targets are changing, so JIT is doing multiple passes over the program. Typical program needs 3 passes. Some very short programs converge with 2 passes. Large programs may need 4 or 5. But specially crafted bpf programs may hit the pass limit and if the program converges on the last iteration the JIT compiler will be producing an image full of 'int 3' insns. Fix this corner case by doing final iteration over bpf program. Fixes: 0a14842f5a3c ("net: filter: Just In Time compiler for x86-64") Reported-by: Daniel Borkmann <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> Tested-by: Daniel Borkmann <[email protected]> Acked-by: Daniel Borkmann <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SSL_CTX *tls_init_ctx(fr_tls_server_conf_t *conf, int client) { SSL_CTX *ctx; X509_STORE *certstore; int verify_mode = SSL_VERIFY_NONE; int ctx_options = 0; int ctx_tls_versions = 0; int type; /* * SHA256 is in all versions of OpenSSL, but isn't * initialized by default. It's needed for WiMAX * certificates. */ #ifdef HAVE_OPENSSL_EVP_SHA256 EVP_add_digest(EVP_sha256()); #endif ctx = SSL_CTX_new(SSLv23_method()); /* which is really "all known SSL / TLS methods". Idiots. */ if (!ctx) { int err; while ((err = ERR_get_error())) { ERROR(LOG_PREFIX ": Failed creating SSL context: %s", ERR_error_string(err, NULL)); return NULL; } } /* * Save the config on the context so that callbacks which * only get SSL_CTX* e.g. session persistence, can get it */ SSL_CTX_set_app_data(ctx, conf); /* * Identify the type of certificates that needs to be loaded */ if (conf->file_type) { type = SSL_FILETYPE_PEM; } else { type = SSL_FILETYPE_ASN1; } /* * Set the password to load private key */ if (conf->private_key_password) { #ifdef __APPLE__ /* * We don't want to put the private key password in eap.conf, so check * for our special string which indicates we should get the password * programmatically. */ char const* special_string = "Apple:UseCertAdmin"; if (strncmp(conf->private_key_password, special_string, strlen(special_string)) == 0) { char cmd[256]; char *password; long const max_password_len = 128; snprintf(cmd, sizeof(cmd) - 1, "/usr/sbin/certadmin --get-private-key-passphrase \"%s\"", conf->private_key_file); DEBUG2(LOG_PREFIX ": Getting private key passphrase using command \"%s\"", cmd); FILE* cmd_pipe = popen(cmd, "r"); if (!cmd_pipe) { ERROR(LOG_PREFIX ": %s command failed: Unable to get private_key_password", cmd); ERROR(LOG_PREFIX ": Error reading private_key_file %s", conf->private_key_file); return NULL; } rad_const_free(conf->private_key_password); password = talloc_array(conf, char, max_password_len); if (!password) { ERROR(LOG_PREFIX ": Can't allocate space for private_key_password"); ERROR(LOG_PREFIX ": Error reading private_key_file %s", conf->private_key_file); pclose(cmd_pipe); return NULL; } fgets(password, max_password_len, cmd_pipe); pclose(cmd_pipe); /* Get rid of newline at end of password. */ password[strlen(password) - 1] = '\0'; DEBUG3(LOG_PREFIX ": Password from command = \"%s\"", password); conf->private_key_password = password; } #endif { char *password; memcpy(&password, &conf->private_key_password, sizeof(password)); SSL_CTX_set_default_passwd_cb_userdata(ctx, password); SSL_CTX_set_default_passwd_cb(ctx, cbtls_password); } } #ifdef PSK_MAX_IDENTITY_LEN if (!client) { /* * No dynamic query exists. There MUST be a * statically configured identity and password. */ if (conf->psk_query && !*conf->psk_query) { ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_query cannot be empty"); return NULL; } /* * Set the callback only if we can check things. */ if (conf->psk_identity || conf->psk_query) { SSL_CTX_set_psk_server_callback(ctx, psk_server_callback); } } else if (conf->psk_query) { ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_query cannot be used for outgoing connections"); return NULL; } /* * Now check that if PSK is being used, the config is valid. */ if ((conf->psk_identity && !conf->psk_password) || (!conf->psk_identity && conf->psk_password) || (conf->psk_identity && !*conf->psk_identity) || (conf->psk_password && !*conf->psk_password)) { ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_identity or psk_password are empty"); return NULL; } if (conf->psk_identity) { size_t psk_len, hex_len; uint8_t buffer[PSK_MAX_PSK_LEN]; if (conf->certificate_file || conf->private_key_password || conf->private_key_file || conf->ca_file || conf->ca_path) { ERROR(LOG_PREFIX ": When PSKs are used, No certificate configuration is permitted"); return NULL; } if (client) { SSL_CTX_set_psk_client_callback(ctx, psk_client_callback); } psk_len = strlen(conf->psk_password); if (strlen(conf->psk_password) > (2 * PSK_MAX_PSK_LEN)) { ERROR(LOG_PREFIX ": psk_hexphrase is too long (max %d)", PSK_MAX_PSK_LEN); return NULL; } /* * Check the password now, so that we don't have * errors at run-time. */ hex_len = fr_hex2bin(buffer, sizeof(buffer), conf->psk_password, psk_len); if (psk_len != (2 * hex_len)) { ERROR(LOG_PREFIX ": psk_hexphrase is not all hex"); return NULL; } goto post_ca; } #else (void) client; /* -Wunused */ #endif /* * Load our keys and certificates * * If certificates are of type PEM then we can make use * of cert chain authentication using openssl api call * SSL_CTX_use_certificate_chain_file. Please see how * the cert chain needs to be given in PEM from * openSSL.org */ if (!conf->certificate_file) goto load_ca; if (type == SSL_FILETYPE_PEM) { if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) { ERROR(LOG_PREFIX ": Error reading certificate file %s:%s", conf->certificate_file, ERR_error_string(ERR_get_error(), NULL)); return NULL; } } else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) { ERROR(LOG_PREFIX ": Error reading certificate file %s:%s", conf->certificate_file, ERR_error_string(ERR_get_error(), NULL)); return NULL; } /* Load the CAs we trust */ load_ca: if (conf->ca_file || conf->ca_path) { if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) { ERROR(LOG_PREFIX ": SSL error %s", ERR_error_string(ERR_get_error(), NULL)); ERROR(LOG_PREFIX ": Error reading Trusted root CA list %s",conf->ca_file ); return NULL; } } if (conf->ca_file && *conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file)); if (conf->private_key_file) { if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) { ERROR(LOG_PREFIX ": Failed reading private key file %s:%s", conf->private_key_file, ERR_error_string(ERR_get_error(), NULL)); return NULL; } /* * Check if the loaded private key is the right one */ if (!SSL_CTX_check_private_key(ctx)) { ERROR(LOG_PREFIX ": Private key does not match the certificate public key"); return NULL; } } #ifdef PSK_MAX_IDENTITY_LEN post_ca: #endif /* * We never want SSLv2 or SSLv3. */ ctx_options |= SSL_OP_NO_SSLv2; ctx_options |= SSL_OP_NO_SSLv3; /* * As of 3.0.5, we always allow TLSv1.1 and TLSv1.2. * Though they can be *globally* disabled if necessary.x */ #ifdef SSL_OP_NO_TLSv1 if (conf->disable_tlsv1) ctx_options |= SSL_OP_NO_TLSv1; ctx_tls_versions |= SSL_OP_NO_TLSv1; #endif #ifdef SSL_OP_NO_TLSv1_1 if (conf->disable_tlsv1_1) ctx_options |= SSL_OP_NO_TLSv1_1; ctx_tls_versions |= SSL_OP_NO_TLSv1_1; #endif #ifdef SSL_OP_NO_TLSv1_2 if (conf->disable_tlsv1_2) ctx_options |= SSL_OP_NO_TLSv1_2; ctx_tls_versions |= SSL_OP_NO_TLSv1_2; #endif if ((ctx_options & ctx_tls_versions) == ctx_tls_versions) { ERROR(LOG_PREFIX ": You have disabled all available TLS versions. EAP will not work"); return NULL; } #ifdef SSL_OP_NO_TICKET ctx_options |= SSL_OP_NO_TICKET; #endif /* * SSL_OP_SINGLE_DH_USE must be used in order to prevent * small subgroup attacks and forward secrecy. Always * using * * SSL_OP_SINGLE_DH_USE has an impact on the computer * time needed during negotiation, but it is not very * large. */ ctx_options |= SSL_OP_SINGLE_DH_USE; /* * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues * in Windows Vista client. * http://www.openssl.org/~bodo/tls-cbc.txt * http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html */ ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; SSL_CTX_set_options(ctx, ctx_options); /* * TODO: Set the RSA & DH * SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa); * SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh); */ /* * set the message callback to identify the type of * message. For every new session, there can be a * different callback argument. * * SSL_CTX_set_msg_callback(ctx, cbtls_msg); */ /* * Set eliptical curve crypto configuration. */ #if OPENSSL_VERSION_NUMBER >= 0x0090800fL #ifndef OPENSSL_NO_ECDH if (set_ecdh_curve(ctx, conf->ecdh_curve) < 0) { return NULL; } #endif #endif /* Set Info callback */ SSL_CTX_set_info_callback(ctx, cbtls_info); /* * Callbacks, etc. for session resumption. */ if (conf->session_cache_enable) { /* * Cache sessions on disk if requested. */ if (conf->session_cache_path) { SSL_CTX_sess_set_new_cb(ctx, cbtls_new_session); SSL_CTX_sess_set_get_cb(ctx, cbtls_get_session); SSL_CTX_sess_set_remove_cb(ctx, cbtls_remove_session); } SSL_CTX_set_quiet_shutdown(ctx, 1); if (fr_tls_ex_index_vps < 0) fr_tls_ex_index_vps = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_vps); } /* * Check the certificates for revocation. */ #ifdef X509_V_FLAG_CRL_CHECK if (conf->check_crl) { certstore = SSL_CTX_get_cert_store(ctx); if (certstore == NULL) { ERROR(LOG_PREFIX ": SSL error %s", ERR_error_string(ERR_get_error(), NULL)); ERROR(LOG_PREFIX ": Error reading Certificate Store"); return NULL; } X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK); } #endif /* * Set verify modes * Always verify the peer certificate */ verify_mode |= SSL_VERIFY_PEER; verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT; verify_mode |= SSL_VERIFY_CLIENT_ONCE; SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify); if (conf->verify_depth) { SSL_CTX_set_verify_depth(ctx, conf->verify_depth); } /* Load randomness */ if (conf->random_file) { if (!(RAND_load_file(conf->random_file, 1024*10))) { ERROR(LOG_PREFIX ": SSL error %s", ERR_error_string(ERR_get_error(), NULL)); ERROR(LOG_PREFIX ": Error loading randomness"); return NULL; } } /* * Set the cipher list if we were told to */ if (conf->cipher_list) { if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) { ERROR(LOG_PREFIX ": Error setting cipher list"); return NULL; } } /* * Setup session caching */ if (conf->session_cache_enable) { /* * Create a unique context Id per EAP-TLS configuration. */ if (conf->session_id_name) { snprintf(conf->session_context_id, sizeof(conf->session_context_id), "FR eap %s", conf->session_id_name); } else { snprintf(conf->session_context_id, sizeof(conf->session_context_id), "FR eap %p", conf); } /* * Cache it, and DON'T auto-clear it. */ SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR); SSL_CTX_set_session_id_context(ctx, (unsigned char *) conf->session_context_id, (unsigned int) strlen(conf->session_context_id)); /* * Our timeout is in hours, this is in seconds. */ SSL_CTX_set_timeout(ctx, conf->session_timeout * 3600); /* * Set the maximum number of entries in the * session cache. */ SSL_CTX_sess_set_cache_size(ctx, conf->session_cache_size); } else { SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF); } return ctx; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-295'], 'message': 'Set X509_V_FLAG_CRL_CHECK_ALL'</s>
<s>[INST] Given the following code containing errors, provide 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 is_legal_file(const std::string &filename) { DBG_FS << "Looking for '" << filename << "'.\n"; if (filename.empty()) { LOG_FS << " invalid filename\n"; return false; } if (filename.find("..") != std::string::npos) { ERR_FS << "Illegal path '" << filename << "' (\"..\" not allowed).\n"; return false; } return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Disallow inclusion of .pbl files from WML (bug #23504) Note that this will also cause Lua wesnoth.have_file() to return false on .pbl files.'</s>
<s>[INST] Given the following code containing errors, provide 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 is_legal_file(const std::string &filename) { DBG_FS << "Looking for '" << filename << "'.\n"; if (filename.empty()) { LOG_FS << " invalid filename\n"; return false; } if (filename.find("..") != std::string::npos) { ERR_FS << "Illegal path '" << filename << "' (\"..\" not allowed).\n"; return false; } if (ends_with(filename, ".pbl")) { ERR_FS << "Illegal path '" << filename << "' (.pbl files are not allowed)." << std::endl; return false; } return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Use looks_like_pbl() to disallow .pbl file inclusion (bug #23504) This function is implemented using case-insensitive pattern matching, unlike filesystem::ends_with(). I missed this when writing my original fix, so the vulnerability still applied to .pbl files on a case-insensitive filesystem (e.g. NTFS and FAT* on Windows) by using different case to bypass the check.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: unsigned Utf8Decoder<kBufferSize>::WriteUtf16(uint16_t* data, unsigned length) const { DCHECK(length > 0); if (length > utf16_length_) length = utf16_length_; // memcpy everything in buffer. unsigned buffer_length = last_byte_of_buffer_unused_ ? kBufferSize - 1 : kBufferSize; unsigned memcpy_length = length <= buffer_length ? length : buffer_length; v8::internal::MemCopy(data, buffer_, memcpy_length * sizeof(uint16_t)); if (length <= buffer_length) return length; DCHECK(unbuffered_start_ != NULL); // Copy the rest the slow way. WriteUtf16Slow(unbuffered_start_, data + buffer_length, length - buffer_length); return length; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'deps: fix out-of-band write in utf8 decoder Originally reported by: Kris Reeves <[email protected]> Reviewed-By: Trevor Norris <[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 Utf8DecoderBase::WriteUtf16Slow(const uint8_t* stream, uint16_t* data, unsigned data_length) { while (data_length != 0) { unsigned cursor = 0; uint32_t character = Utf8::ValueOf(stream, Utf8::kMaxEncodedSize, &cursor); // There's a total lack of bounds checking for stream // as it was already done in Reset. stream += cursor; if (character > unibrow::Utf16::kMaxNonSurrogateCharCode) { *data++ = Utf16::LeadSurrogate(character); *data++ = Utf16::TrailSurrogate(character); DCHECK(data_length > 1); data_length -= 2; } else { *data++ = character; data_length -= 1; } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'deps: fix out-of-band write in utf8 decoder Originally reported by: Kris Reeves <[email protected]> Reviewed-By: Trevor Norris <[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 char *lxclock_name(const char *p, const char *n) { int ret; int len; char *dest; char *rundir; /* lockfile will be: * "/run" + "/lock/lxc/$lxcpath/$lxcname + '\0' if root * or * $XDG_RUNTIME_DIR + "/lock/lxc/$lxcpath/$lxcname + '\0' if non-root */ /* length of "/lock/lxc/" + $lxcpath + "/" + "." + $lxcname + '\0' */ len = strlen("/lock/lxc/") + strlen(n) + strlen(p) + 3; rundir = get_rundir(); if (!rundir) return NULL; len += strlen(rundir); if ((dest = malloc(len)) == NULL) { free(rundir); return NULL; } ret = snprintf(dest, len, "%s/lock/lxc/%s", rundir, p); if (ret < 0 || ret >= len) { free(dest); free(rundir); return NULL; } ret = mkdir_p(dest, 0755); if (ret < 0) { /* fall back to "/tmp/" + $(id -u) + "/lxc" + $lxcpath + "/" + "." + $lxcname + '\0' * * maximum length of $(id -u) is 10 calculated by (log (2 ** (sizeof(uid_t) * 8) - 1) / log 10 + 1) * * lxcpath always starts with '/' */ int l2 = 22 + strlen(n) + strlen(p); if (l2 > len) { char *d; d = realloc(dest, l2); if (!d) { free(dest); free(rundir); return NULL; } len = l2; dest = d; } ret = snprintf(dest, len, "/tmp/%d/lxc%s", geteuid(), p); if (ret < 0 || ret >= len) { free(dest); free(rundir); return NULL; } ret = mkdir_p(dest, 0755); if (ret < 0) { free(dest); free(rundir); return NULL; } ret = snprintf(dest, len, "/tmp/%d/lxc%s/.%s", geteuid(), p, n); } else ret = snprintf(dest, len, "%s/lock/lxc/%s/.%s", rundir, p, n); free(rundir); if (ret < 0 || ret >= len) { free(dest); return NULL; } return dest; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'CVE-2015-1331: lxclock: use /run/lxc/lock rather than /run/lock/lxc This prevents an unprivileged user to use LXC to create arbitrary file on the filesystem. Signed-off-by: Serge Hallyn <[email protected]> Signed-off-by: Tyler Hicks <[email protected]> Acked-by: Stéphane Graber <[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 attach_child_main(void* data) { struct attach_clone_payload* payload = (struct attach_clone_payload*)data; int ipc_socket = payload->ipc_socket; lxc_attach_options_t* options = payload->options; struct lxc_proc_context_info* init_ctx = payload->init_ctx; #if HAVE_SYS_PERSONALITY_H long new_personality; #endif int ret; int status; int expected; long flags; int fd; uid_t new_uid; gid_t new_gid; /* wait for the initial thread to signal us that it's ready * for us to start initializing */ expected = 0; status = -1; ret = lxc_read_nointr_expect(ipc_socket, &status, sizeof(status), &expected); if (ret <= 0) { ERROR("error using IPC to receive notification from initial process (0)"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } /* A description of the purpose of this functionality is * provided in the lxc-attach(1) manual page. We have to * remount here and not in the parent process, otherwise * /proc may not properly reflect the new pid namespace. */ if (!(options->namespaces & CLONE_NEWNS) && (options->attach_flags & LXC_ATTACH_REMOUNT_PROC_SYS)) { ret = lxc_attach_remount_sys_proc(); if (ret < 0) { shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } } /* now perform additional attachments*/ #if HAVE_SYS_PERSONALITY_H if (options->personality < 0) new_personality = init_ctx->personality; else new_personality = options->personality; if (options->attach_flags & LXC_ATTACH_SET_PERSONALITY) { ret = personality(new_personality); if (ret < 0) { SYSERROR("could not ensure correct architecture"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } } #endif if (options->attach_flags & LXC_ATTACH_DROP_CAPABILITIES) { ret = lxc_attach_drop_privs(init_ctx); if (ret < 0) { ERROR("could not drop privileges"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } } /* always set the environment (specify (LXC_ATTACH_KEEP_ENV, NULL, NULL) if you want this to be a no-op) */ ret = lxc_attach_set_environment(options->env_policy, options->extra_env_vars, options->extra_keep_env); if (ret < 0) { ERROR("could not set initial environment for attached process"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } /* set user / group id */ new_uid = 0; new_gid = 0; /* ignore errors, we will fall back to root in that case * (/proc was not mounted etc.) */ if (options->namespaces & CLONE_NEWUSER) lxc_attach_get_init_uidgid(&new_uid, &new_gid); if (options->uid != (uid_t)-1) new_uid = options->uid; if (options->gid != (gid_t)-1) new_gid = options->gid; /* setup the control tty */ if (options->stdin_fd && isatty(options->stdin_fd)) { if (setsid() < 0) { SYSERROR("unable to setsid"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } if (ioctl(options->stdin_fd, TIOCSCTTY, (char *)NULL) < 0) { SYSERROR("unable to TIOCSTTY"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } } /* try to set the uid/gid combination */ if ((new_gid != 0 || options->namespaces & CLONE_NEWUSER)) { if (setgid(new_gid) || setgroups(0, NULL)) { SYSERROR("switching to container gid"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } } if ((new_uid != 0 || options->namespaces & CLONE_NEWUSER) && setuid(new_uid)) { SYSERROR("switching to container uid"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } /* tell initial process it may now put us into the cgroups */ status = 1; ret = lxc_write_nointr(ipc_socket, &status, sizeof(status)); if (ret != sizeof(status)) { ERROR("error using IPC to notify initial process for initialization (1)"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } /* wait for the initial thread to signal us that it has done * everything for us when it comes to cgroups etc. */ expected = 2; status = -1; ret = lxc_read_nointr_expect(ipc_socket, &status, sizeof(status), &expected); if (ret <= 0) { ERROR("error using IPC to receive final notification from initial process (2)"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } shutdown(ipc_socket, SHUT_RDWR); close(ipc_socket); /* set new apparmor profile/selinux context */ if ((options->namespaces & CLONE_NEWNS) && (options->attach_flags & LXC_ATTACH_LSM)) { int on_exec; int proc_mounted; on_exec = options->attach_flags & LXC_ATTACH_LSM_EXEC ? 1 : 0; proc_mounted = mount_proc_if_needed("/"); if (proc_mounted == -1) { ERROR("Error mounting a sane /proc"); rexit(-1); } ret = lsm_process_label_set(init_ctx->lsm_label, init_ctx->container->lxc_conf, 0, on_exec); if (proc_mounted) umount("/proc"); if (ret < 0) { rexit(-1); } } if (init_ctx->container && init_ctx->container->lxc_conf && lxc_seccomp_load(init_ctx->container->lxc_conf) != 0) { ERROR("Loading seccomp policy"); rexit(-1); } lxc_proc_put_context_info(init_ctx); /* The following is done after the communication socket is * shut down. That way, all errors that might (though * unlikely) occur up until this point will have their messages * printed to the original stderr (if logging is so configured) * and not the fd the user supplied, if any. */ /* fd handling for stdin, stdout and stderr; * ignore errors here, user may want to make sure * the fds are closed, for example */ if (options->stdin_fd >= 0 && options->stdin_fd != 0) dup2(options->stdin_fd, 0); if (options->stdout_fd >= 0 && options->stdout_fd != 1) dup2(options->stdout_fd, 1); if (options->stderr_fd >= 0 && options->stderr_fd != 2) dup2(options->stderr_fd, 2); /* close the old fds */ if (options->stdin_fd > 2) close(options->stdin_fd); if (options->stdout_fd > 2) close(options->stdout_fd); if (options->stderr_fd > 2) close(options->stderr_fd); /* try to remove CLOEXEC flag from stdin/stdout/stderr, * but also here, ignore errors */ for (fd = 0; fd <= 2; fd++) { flags = fcntl(fd, F_GETFL); if (flags < 0) continue; if (flags & FD_CLOEXEC) { if (fcntl(fd, F_SETFL, flags & ~FD_CLOEXEC) < 0) { SYSERROR("Unable to clear CLOEXEC from fd"); } } } /* we're done, so we can now do whatever the user intended us to do */ rexit(payload->exec_function(payload->exec_payload)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-17'], 'message': 'CVE-2015-1334: Don't use the container's /proc during attach A user could otherwise over-mount /proc and prevent the apparmor profile or selinux label from being written which combined with a modified /bin/sh or other commonly used binary would lead to unconfined code execution. Reported-by: Roman Fiedler Signed-off-by: Stéphane Graber <[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 attach_child_main(void* data) { struct attach_clone_payload* payload = (struct attach_clone_payload*)data; int ipc_socket = payload->ipc_socket; lxc_attach_options_t* options = payload->options; struct lxc_proc_context_info* init_ctx = payload->init_ctx; #if HAVE_SYS_PERSONALITY_H long new_personality; #endif int ret; int status; int expected; long flags; int fd; uid_t new_uid; gid_t new_gid; /* wait for the initial thread to signal us that it's ready * for us to start initializing */ expected = 0; status = -1; ret = lxc_read_nointr_expect(ipc_socket, &status, sizeof(status), &expected); if (ret <= 0) { ERROR("error using IPC to receive notification from initial process (0)"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } /* A description of the purpose of this functionality is * provided in the lxc-attach(1) manual page. We have to * remount here and not in the parent process, otherwise * /proc may not properly reflect the new pid namespace. */ if (!(options->namespaces & CLONE_NEWNS) && (options->attach_flags & LXC_ATTACH_REMOUNT_PROC_SYS)) { ret = lxc_attach_remount_sys_proc(); if (ret < 0) { shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } } /* now perform additional attachments*/ #if HAVE_SYS_PERSONALITY_H if (options->personality < 0) new_personality = init_ctx->personality; else new_personality = options->personality; if (options->attach_flags & LXC_ATTACH_SET_PERSONALITY) { ret = personality(new_personality); if (ret < 0) { SYSERROR("could not ensure correct architecture"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } } #endif if (options->attach_flags & LXC_ATTACH_DROP_CAPABILITIES) { ret = lxc_attach_drop_privs(init_ctx); if (ret < 0) { ERROR("could not drop privileges"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } } /* always set the environment (specify (LXC_ATTACH_KEEP_ENV, NULL, NULL) if you want this to be a no-op) */ ret = lxc_attach_set_environment(options->env_policy, options->extra_env_vars, options->extra_keep_env); if (ret < 0) { ERROR("could not set initial environment for attached process"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } /* set user / group id */ new_uid = 0; new_gid = 0; /* ignore errors, we will fall back to root in that case * (/proc was not mounted etc.) */ if (options->namespaces & CLONE_NEWUSER) lxc_attach_get_init_uidgid(&new_uid, &new_gid); if (options->uid != (uid_t)-1) new_uid = options->uid; if (options->gid != (gid_t)-1) new_gid = options->gid; /* try to set the uid/gid combination */ if ((new_gid != 0 || options->namespaces & CLONE_NEWUSER)) { if (setgid(new_gid) || setgroups(0, NULL)) { SYSERROR("switching to container gid"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } } if ((new_uid != 0 || options->namespaces & CLONE_NEWUSER) && setuid(new_uid)) { SYSERROR("switching to container uid"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } /* tell initial process it may now put us into the cgroups */ status = 1; ret = lxc_write_nointr(ipc_socket, &status, sizeof(status)); if (ret != sizeof(status)) { ERROR("error using IPC to notify initial process for initialization (1)"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } /* wait for the initial thread to signal us that it has done * everything for us when it comes to cgroups etc. */ expected = 2; status = -1; ret = lxc_read_nointr_expect(ipc_socket, &status, sizeof(status), &expected); if (ret <= 0) { ERROR("error using IPC to receive final notification from initial process (2)"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } shutdown(ipc_socket, SHUT_RDWR); close(ipc_socket); /* set new apparmor profile/selinux context */ if ((options->namespaces & CLONE_NEWNS) && (options->attach_flags & LXC_ATTACH_LSM)) { int on_exec; on_exec = options->attach_flags & LXC_ATTACH_LSM_EXEC ? 1 : 0; ret = lsm_process_label_set(init_ctx->lsm_label, 0, on_exec); if (ret < 0) { rexit(-1); } } if (init_ctx->container && init_ctx->container->lxc_conf && lxc_seccomp_load(init_ctx->container->lxc_conf) != 0) { ERROR("Loading seccomp policy"); rexit(-1); } lxc_proc_put_context_info(init_ctx); /* The following is done after the communication socket is * shut down. That way, all errors that might (though * unlikely) occur up until this point will have their messages * printed to the original stderr (if logging is so configured) * and not the fd the user supplied, if any. */ /* fd handling for stdin, stdout and stderr; * ignore errors here, user may want to make sure * the fds are closed, for example */ if (options->stdin_fd >= 0 && options->stdin_fd != 0) dup2(options->stdin_fd, 0); if (options->stdout_fd >= 0 && options->stdout_fd != 1) dup2(options->stdout_fd, 1); if (options->stderr_fd >= 0 && options->stderr_fd != 2) dup2(options->stderr_fd, 2); /* close the old fds */ if (options->stdin_fd > 2) close(options->stdin_fd); if (options->stdout_fd > 2) close(options->stdout_fd); if (options->stderr_fd > 2) close(options->stderr_fd); /* try to remove CLOEXEC flag from stdin/stdout/stderr, * but also here, ignore errors */ for (fd = 0; fd <= 2; fd++) { flags = fcntl(fd, F_GETFL); if (flags < 0) continue; if (flags & FD_CLOEXEC) { if (fcntl(fd, F_SETFL, flags & ~FD_CLOEXEC) < 0) { SYSERROR("Unable to clear CLOEXEC from fd"); } } } /* we're done, so we can now do whatever the user intended us to do */ rexit(payload->exec_function(payload->exec_payload)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-17'], 'message': 'CVE-2015-1334: Don't use the container's /proc during attach A user could otherwise over-mount /proc and prevent the apparmor profile or selinux label from being written which combined with a modified /bin/sh or other commonly used binary would lead to unconfined code execution. Reported-by: Roman Fiedler Signed-off-by: Stéphane Graber <[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: rb_dlhandle_sym(VALUE self, VALUE sym) { void (*func)(); struct dl_handle *dlhandle; void *handle; const char *name; const char *err; int i; #if defined(HAVE_DLERROR) # define CHECK_DLERROR if( err = dlerror() ){ func = 0; } #else # define CHECK_DLERROR #endif rb_secure(2); name = StringValuePtr(sym); Data_Get_Struct(self, struct dl_handle, dlhandle); if( ! dlhandle->open ){ rb_raise(rb_eDLError, "closed handle"); } handle = dlhandle->ptr; func = dlsym(handle, name); CHECK_DLERROR; #if defined(FUNC_STDCALL) if( !func ){ int len = strlen(name); char *name_n; #if defined(__CYGWIN__) || defined(_WIN32) || defined(__MINGW32__) { char *name_a = (char*)xmalloc(len+2); strcpy(name_a, name); name_n = name_a; name_a[len] = 'A'; name_a[len+1] = '\0'; func = dlsym(handle, name_a); CHECK_DLERROR; if( func ) goto found; name_n = xrealloc(name_a, len+6); } #else name_n = (char*)xmalloc(len+6); #endif memcpy(name_n, name, len); name_n[len++] = '@'; for( i = 0; i < 256; i += 4 ){ sprintf(name_n + len, "%d", i); func = dlsym(handle, name_n); CHECK_DLERROR; if( func ) break; } if( func ) goto found; name_n[len-1] = 'A'; name_n[len++] = '@'; for( i = 0; i < 256; i += 4 ){ sprintf(name_n + len, "%d", i); func = dlsym(handle, name_n); CHECK_DLERROR; if( func ) break; } found: xfree(name_n); } #endif if( !func ){ rb_raise(rb_eDLError, "unknown symbol \"%s\"", name); } return PTR2NUM(func); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-399'], 'message': '* ext/dl/dl.c (rb_dlhandle_initialize): prohibits DL::dlopen with a tainted name of library. Patch by sheepman <sheepman AT sheepman.sakura.ne.jp>. * ext/dl/dl.c (rb_dlhandle_sym): ditto git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/branches/ruby_1_9_1@23405 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 umount_tree(struct mount *mnt, enum umount_tree_flags how) { LIST_HEAD(tmp_list); struct mount *p; if (how & UMOUNT_PROPAGATE) propagate_mount_unlock(mnt); /* Gather the mounts to umount */ for (p = mnt; p; p = next_mnt(p, mnt)) { p->mnt.mnt_flags |= MNT_UMOUNT; list_move(&p->mnt_list, &tmp_list); } /* Hide the mounts from mnt_mounts */ list_for_each_entry(p, &tmp_list, mnt_list) { list_del_init(&p->mnt_child); } /* Add propogated mounts to the tmp_list */ if (how & UMOUNT_PROPAGATE) propagate_umount(&tmp_list); while (!list_empty(&tmp_list)) { bool disconnect; p = list_first_entry(&tmp_list, struct mount, mnt_list); list_del_init(&p->mnt_expire); list_del_init(&p->mnt_list); __touch_mnt_namespace(p->mnt_ns); p->mnt_ns = NULL; if (how & UMOUNT_SYNC) p->mnt.mnt_flags |= MNT_SYNC_UMOUNT; disconnect = !IS_MNT_LOCKED_AND_LAZY(p); pin_insert_group(&p->mnt_umount, &p->mnt_parent->mnt, disconnect ? &unmounted : NULL); if (mnt_has_parent(p)) { mnt_add_count(p->mnt_parent, -1); if (!disconnect) { /* Don't forget about p */ list_add_tail(&p->mnt_child, &p->mnt_parent->mnt_mounts); } else { umount_mnt(p); } } change_mnt_propagation(p, MS_PRIVATE); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'mnt: Update detach_mounts to leave mounts connected Now that it is possible to lazily unmount an entire mount tree and leave the individual mounts connected to each other add a new flag UMOUNT_CONNECTED to umount_tree to force this behavior and use this flag in detach_mounts. This closes a bug where the deletion of a file or directory could trigger an unmount and reveal data under a mount point. Cc: [email protected] Signed-off-by: "Eric W. Biederman" <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void pin_remove(struct fs_pin *pin) { spin_lock(&pin_lock); hlist_del(&pin->m_list); hlist_del(&pin->s_list); spin_unlock(&pin_lock); spin_lock_irq(&pin->wait.lock); pin->done = 1; wake_up_locked(&pin->wait); spin_unlock_irq(&pin->wait.lock); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'fs_pin: Allow for the possibility that m_list or s_list go unused. This is needed to support lazily umounting locked mounts. Because the entire unmounted subtree needs to stay together until there are no users with references to any part of the subtree. To support this guarantee that the fs_pin m_list and s_list nodes are initialized by initializing them in init_fs_pin allowing for the possibility that pin_insert_group does not touch them. Further use hlist_del_init in pin_remove so that there is a hlist_unhashed test before the list we attempt to update the previous list item. Signed-off-by: "Eric W. Biederman" <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: sg_start_req(Sg_request *srp, unsigned char *cmd) { int res; struct request *rq; Sg_fd *sfp = srp->parentfp; sg_io_hdr_t *hp = &srp->header; int dxfer_len = (int) hp->dxfer_len; int dxfer_dir = hp->dxfer_direction; unsigned int iov_count = hp->iovec_count; Sg_scatter_hold *req_schp = &srp->data; Sg_scatter_hold *rsv_schp = &sfp->reserve; struct request_queue *q = sfp->parentdp->device->request_queue; struct rq_map_data *md, map_data; int rw = hp->dxfer_direction == SG_DXFER_TO_DEV ? WRITE : READ; unsigned char *long_cmdp = NULL; SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp, "sg_start_req: dxfer_len=%d\n", dxfer_len)); if (hp->cmd_len > BLK_MAX_CDB) { long_cmdp = kzalloc(hp->cmd_len, GFP_KERNEL); if (!long_cmdp) return -ENOMEM; } /* * NOTE * * With scsi-mq enabled, there are a fixed number of preallocated * requests equal in number to shost->can_queue. If all of the * preallocated requests are already in use, then using GFP_ATOMIC with * blk_get_request() will return -EWOULDBLOCK, whereas using GFP_KERNEL * will cause blk_get_request() to sleep until an active command * completes, freeing up a request. Neither option is ideal, but * GFP_KERNEL is the better choice to prevent userspace from getting an * unexpected EWOULDBLOCK. * * With scsi-mq disabled, blk_get_request() with GFP_KERNEL usually * does not sleep except under memory pressure. */ rq = blk_get_request(q, rw, GFP_KERNEL); if (IS_ERR(rq)) { kfree(long_cmdp); return PTR_ERR(rq); } blk_rq_set_block_pc(rq); if (hp->cmd_len > BLK_MAX_CDB) rq->cmd = long_cmdp; memcpy(rq->cmd, cmd, hp->cmd_len); rq->cmd_len = hp->cmd_len; srp->rq = rq; rq->end_io_data = srp; rq->sense = srp->sense_b; rq->retries = SG_DEFAULT_RETRIES; if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE)) return 0; if (sg_allow_dio && hp->flags & SG_FLAG_DIRECT_IO && dxfer_dir != SG_DXFER_UNKNOWN && !iov_count && !sfp->parentdp->device->host->unchecked_isa_dma && blk_rq_aligned(q, (unsigned long)hp->dxferp, dxfer_len)) md = NULL; else md = &map_data; if (md) { if (!sg_res_in_use(sfp) && dxfer_len <= rsv_schp->bufflen) sg_link_reserve(sfp, srp, dxfer_len); else { res = sg_build_indirect(req_schp, sfp, dxfer_len); if (res) return res; } md->pages = req_schp->pages; md->page_order = req_schp->page_order; md->nr_entries = req_schp->k_use_sg; md->offset = 0; md->null_mapped = hp->dxferp ? 0 : 1; if (dxfer_dir == SG_DXFER_TO_FROM_DEV) md->from_user = 1; else md->from_user = 0; } if (unlikely(iov_count > MAX_UIOVEC)) return -EINVAL; if (iov_count) { int size = sizeof(struct iovec) * iov_count; struct iovec *iov; struct iov_iter i; iov = memdup_user(hp->dxferp, size); if (IS_ERR(iov)) return PTR_ERR(iov); iov_iter_init(&i, rw, iov, iov_count, min_t(size_t, hp->dxfer_len, iov_length(iov, iov_count))); res = blk_rq_map_user_iov(q, rq, md, &i, GFP_ATOMIC); kfree(iov); } else res = blk_rq_map_user(q, rq, md, hp->dxferp, hp->dxfer_len, GFP_ATOMIC); if (!res) { srp->bio = rq->bio; if (!md) { req_schp->dio_in_use = 1; hp->info |= SG_INFO_DIRECT_IO; } } return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-189'], 'message': 'sg_start_req(): use import_iovec() Signed-off-by: Al Viro <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static struct file *path_openat(int dfd, struct filename *pathname, struct nameidata *nd, const struct open_flags *op, int flags) { struct file *file; struct path path; int opened = 0; int error; file = get_empty_filp(); if (IS_ERR(file)) return file; file->f_flags = op->open_flag; if (unlikely(file->f_flags & __O_TMPFILE)) { error = do_tmpfile(dfd, pathname, nd, flags, op, file, &opened); goto out; } error = path_init(dfd, pathname, flags, nd); if (unlikely(error)) goto out; error = do_last(nd, &path, file, op, &opened, pathname); while (unlikely(error > 0)) { /* trailing symlink */ struct path link = path; void *cookie; if (!(nd->flags & LOOKUP_FOLLOW)) { path_put_conditional(&path, nd); path_put(&nd->path); error = -ELOOP; break; } error = may_follow_link(&link, nd); if (unlikely(error)) break; nd->flags |= LOOKUP_PARENT; nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL); error = follow_link(&link, nd, &cookie); if (unlikely(error)) break; error = do_last(nd, &path, file, op, &opened, pathname); put_link(nd, &link, cookie); } out: path_cleanup(nd); if (!(opened & FILE_OPENED)) { BUG_ON(!error); put_filp(file); } if (unlikely(error)) { if (error == -EOPENSTALE) { if (flags & LOOKUP_RCU) error = -ECHILD; else error = -ESTALE; } file = ERR_PTR(error); } return file; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'path_openat(): fix double fput() path_openat() jumps to the wrong place after do_tmpfile() - it has already done path_cleanup() (as part of path_lookupat() called by do_tmpfile()), so doing that again can lead to double fput(). Cc: [email protected] # v3.11+ Signed-off-by: Al Viro <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Panic(const char *fmtstr, va_list args) { /* Ignored */ sLog(log_warning, "Panic call back invoked. \n"); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'randomly generate tmp directory name, and add StrUtil_ReplaceAll() function.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Debug(const char *fmtstr, va_list args) { /* Ignored */ #ifdef VMX86_DEBUG sLog(log_debug, "Debug callback invoked. \n"); #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'randomly generate tmp directory name, and add StrUtil_ReplaceAll() function.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: CloudInitSetup(const char *tmpDirPath) { int deployStatus = DEPLOY_ERROR; const char *cloudInitTmpDirPath = "/var/run/vmware-imc"; int forkExecResult; char command[1024]; Bool cloudInitTmpDirCreated = FALSE; snprintf(command, sizeof(command), "/bin/mkdir -p %s", cloudInitTmpDirPath); command[sizeof(command) - 1] = '\0'; forkExecResult = ForkExecAndWaitCommand(command); if (forkExecResult != 0) { SetDeployError("Error creating %s dir: %s", cloudInitTmpDirPath, strerror(errno)); goto done; } cloudInitTmpDirCreated = TRUE; snprintf(command, sizeof(command), "/bin/rm -f %s/cust.cfg %s/nics.txt", cloudInitTmpDirPath, cloudInitTmpDirPath); command[sizeof(command) - 1] = '\0'; forkExecResult = ForkExecAndWaitCommand(command); snprintf(command, sizeof(command), "/bin/cp %s/cust.cfg %s/cust.cfg", tmpDirPath, cloudInitTmpDirPath); command[sizeof(command) - 1] = '\0'; forkExecResult = ForkExecAndWaitCommand(command); if (forkExecResult != 0) { SetDeployError("Error copying cust.cfg file: %s", strerror(errno)); goto done; } snprintf(command, sizeof(command), "/usr/bin/test -f %s/nics.txt", tmpDirPath); command[sizeof(command) - 1] = '\0'; forkExecResult = ForkExecAndWaitCommand(command); /* * /usr/bin/test -f returns 0 if the file exists * non zero is returned if the file does not exist. * We need to copy the nics.txt only if it exists. */ if (forkExecResult == 0) { snprintf(command, sizeof(command), "/bin/cp %s/nics.txt %s/nics.txt", tmpDirPath, cloudInitTmpDirPath); command[sizeof(command) - 1] = '\0'; forkExecResult = ForkExecAndWaitCommand(command); if (forkExecResult != 0) { SetDeployError("Error copying nics.txt file: %s", strerror(errno)); goto done; } } deployStatus = DEPLOY_SUCCESS; done: if (DEPLOY_SUCCESS == deployStatus) { TransitionState(INPROGRESS, DONE); } else { if (cloudInitTmpDirCreated) { snprintf(command, sizeof(command), "/bin/rm -rf %s", cloudInitTmpDirPath); command[sizeof(command) - 1] = '\0'; ForkExecAndWaitCommand(command); } sLog(log_error, "Setting generic error status in vmx. \n"); SetCustomizationStatusInVmx(TOOLSDEPLOYPKG_RUNNING, GUESTCUST_EVENT_CUSTOMIZE_FAILED, NULL); TransitionState(INPROGRESS, ERRORED); } return deployStatus; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'randomly generate tmp directory name'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Panic(const char *fmtstr, ...) { /* Ignored */ sLog(log_warning, "Panic callback invoked. \n"); exit(1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'randomly generate tmp directory name'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: jas_stream_t *jas_stream_memopen(char *buf, int bufsize) { jas_stream_t *stream; jas_stream_memobj_t *obj; JAS_DBGLOG(100, ("jas_stream_memopen(%p, %d)\n", buf, bufsize)); if (!(stream = jas_stream_create())) { return 0; } /* A stream associated with a memory buffer is always opened for both reading and writing in binary mode. */ stream->openmode_ = JAS_STREAM_READ | JAS_STREAM_WRITE | JAS_STREAM_BINARY; /* Since the stream data is already resident in memory, buffering is not necessary. */ /* But... It still may be faster to use buffering anyways. */ jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0); /* Select the operations for a memory stream. */ stream->ops_ = &jas_stream_memops; /* Allocate memory for the underlying memory stream object. */ if (!(obj = jas_malloc(sizeof(jas_stream_memobj_t)))) { jas_stream_destroy(stream); return 0; } stream->obj_ = (void *) obj; /* Initialize a few important members of the memory stream object. */ obj->myalloc_ = 0; obj->buf_ = 0; /* If the buffer size specified is nonpositive, then the buffer is allocated internally and automatically grown as needed. */ if (bufsize <= 0) { obj->bufsize_ = 1024; obj->growable_ = 1; } else { obj->bufsize_ = bufsize; obj->growable_ = 0; } if (buf) { obj->buf_ = (unsigned char *) buf; } else { obj->buf_ = jas_malloc(obj->bufsize_); obj->myalloc_ = 1; } if (!obj->buf_) { jas_stream_close(stream); return 0; } JAS_DBGLOG(100, ("jas_stream_memopen buffer buf=%p myalloc=%d\n", obj->buf_, obj->myalloc_)); if (bufsize > 0 && buf) { /* If a buffer was supplied by the caller and its length is positive, make the associated buffer data appear in the stream initially. */ obj->len_ = bufsize; } else { /* The stream is initially empty. */ obj->len_ = 0; } obj->pos_ = 0; return stream; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415', 'CWE-190', 'CWE-369'], 'message': 'Made some changes to the I/O stream library for memory streams. There were a number of potential problems due to the possibility of integer overflow. Changed some integral types to the larger types size_t or ssize_t. For example, the function mem_resize now takes the buffer size parameter as a size_t. Added a new function jas_stream_memopen2, which takes a buffer size specified as a size_t instead of an int. This can be used in jas_image_cmpt_create to avoid potential overflow problems. Added a new function jas_deprecated to warn about reliance on deprecated library behavior.'</s>
<s>[INST] Given the following code containing errors, provide 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 jas_image_cmpt_t *jas_image_cmpt_create(int_fast32_t tlx, int_fast32_t tly, int_fast32_t hstep, int_fast32_t vstep, int_fast32_t width, int_fast32_t height, uint_fast16_t depth, bool sgnd, uint_fast32_t inmem) { jas_image_cmpt_t *cmpt; size_t size; cmpt = 0; if (width < 0 || height < 0 || hstep <= 0 || vstep <= 0) { goto error; } if (!jas_safe_intfast32_add(tlx, width, 0) || !jas_safe_intfast32_add(tly, height, 0)) { goto error; } if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) { goto error; } cmpt->type_ = JAS_IMAGE_CT_UNKNOWN; cmpt->tlx_ = tlx; cmpt->tly_ = tly; cmpt->hstep_ = hstep; cmpt->vstep_ = vstep; cmpt->width_ = width; cmpt->height_ = height; cmpt->prec_ = depth; cmpt->sgnd_ = sgnd; cmpt->stream_ = 0; cmpt->cps_ = (depth + 7) / 8; // Compute the number of samples in the image component, while protecting // against overflow. // size = cmpt->width_ * cmpt->height_ * cmpt->cps_; if (!jas_safe_size_mul(cmpt->width_, cmpt->height_, &size) || !jas_safe_size_mul(size, cmpt->cps_, &size)) { goto error; } cmpt->stream_ = (inmem) ? jas_stream_memopen(0, size) : jas_stream_tmpfile(); if (!cmpt->stream_) { goto error; } /* Zero the component data. This isn't necessary, but it is convenient for debugging purposes. */ /* Note: conversion of size - 1 to long can overflow */ if (jas_stream_seek(cmpt->stream_, size - 1, SEEK_SET) < 0 || jas_stream_putc(cmpt->stream_, 0) == EOF || jas_stream_seek(cmpt->stream_, 0, SEEK_SET) < 0) { goto error; } return cmpt; error: if (cmpt) { jas_image_cmpt_destroy(cmpt); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415', 'CWE-190', 'CWE-369'], 'message': 'Made some changes to the I/O stream library for memory streams. There were a number of potential problems due to the possibility of integer overflow. Changed some integral types to the larger types size_t or ssize_t. For example, the function mem_resize now takes the buffer size parameter as a size_t. Added a new function jas_stream_memopen2, which takes a buffer size specified as a size_t instead of an int. This can be used in jas_image_cmpt_create to avoid potential overflow problems. Added a new function jas_deprecated to warn about reliance on deprecated library behavior.'</s>
<s>[INST] Given the following code containing errors, provide 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 jas_stream_write(jas_stream_t *stream, const void *buf, int cnt) { int n; const char *bufptr; bufptr = buf; n = 0; while (n < cnt) { if (jas_stream_putc(stream, *bufptr) == EOF) { return n; } ++bufptr; ++n; } return n; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415', 'CWE-190', 'CWE-369'], 'message': 'Made some changes to the I/O stream library for memory streams. There were a number of potential problems due to the possibility of integer overflow. Changed some integral types to the larger types size_t or ssize_t. For example, the function mem_resize now takes the buffer size parameter as a size_t. Added a new function jas_stream_memopen2, which takes a buffer size specified as a size_t instead of an int. This can be used in jas_image_cmpt_create to avoid potential overflow problems. Added a new function jas_deprecated to warn about reliance on deprecated library behavior.'</s>
<s>[INST] Given the following code containing errors, provide 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 jas_stream_gobble(jas_stream_t *stream, int n) { int m; m = n; for (m = n; m > 0; --m) { if (jas_stream_getc(stream) == EOF) { return n - m; } } return n; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415', 'CWE-190', 'CWE-369'], 'message': 'Made some changes to the I/O stream library for memory streams. There were a number of potential problems due to the possibility of integer overflow. Changed some integral types to the larger types size_t or ssize_t. For example, the function mem_resize now takes the buffer size parameter as a size_t. Added a new function jas_stream_memopen2, which takes a buffer size specified as a size_t instead of an int. This can be used in jas_image_cmpt_create to avoid potential overflow problems. Added a new function jas_deprecated to warn about reliance on deprecated library behavior.'</s>
<s>[INST] Given the following code containing errors, provide 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 jas_stream_read(jas_stream_t *stream, void *buf, int cnt) { int n; int c; char *bufptr; bufptr = buf; n = 0; while (n < cnt) { if ((c = jas_stream_getc(stream)) == EOF) { return n; } *bufptr++ = c; ++n; } return n; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415', 'CWE-190', 'CWE-369'], 'message': 'Made some changes to the I/O stream library for memory streams. There were a number of potential problems due to the possibility of integer overflow. Changed some integral types to the larger types size_t or ssize_t. For example, the function mem_resize now takes the buffer size parameter as a size_t. Added a new function jas_stream_memopen2, which takes a buffer size specified as a size_t instead of an int. This can be used in jas_image_cmpt_create to avoid potential overflow problems. Added a new function jas_deprecated to warn about reliance on deprecated library behavior.'</s>
<s>[INST] Given the following code containing errors, provide 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 mif_process_cmpt(mif_hdr_t *hdr, char *buf) { jas_tvparser_t *tvp; mif_cmpt_t *cmpt; int id; cmpt = 0; tvp = 0; if (!(cmpt = mif_cmpt_create())) { goto error; } cmpt->tlx = 0; cmpt->tly = 0; cmpt->sampperx = 0; cmpt->samppery = 0; cmpt->width = 0; cmpt->height = 0; cmpt->prec = 0; cmpt->sgnd = -1; cmpt->data = 0; if (!(tvp = jas_tvparser_create(buf))) { goto error; } while (!(id = jas_tvparser_next(tvp))) { switch (jas_taginfo_nonull(jas_taginfos_lookup(mif_tags, jas_tvparser_gettag(tvp)))->id) { case MIF_TLX: cmpt->tlx = atoi(jas_tvparser_getval(tvp)); break; case MIF_TLY: cmpt->tly = atoi(jas_tvparser_getval(tvp)); break; case MIF_WIDTH: cmpt->width = atoi(jas_tvparser_getval(tvp)); break; case MIF_HEIGHT: cmpt->height = atoi(jas_tvparser_getval(tvp)); break; case MIF_HSAMP: cmpt->sampperx = atoi(jas_tvparser_getval(tvp)); break; case MIF_VSAMP: cmpt->samppery = atoi(jas_tvparser_getval(tvp)); break; case MIF_PREC: cmpt->prec = atoi(jas_tvparser_getval(tvp)); break; case MIF_SGND: cmpt->sgnd = atoi(jas_tvparser_getval(tvp)); break; case MIF_DATA: if (!(cmpt->data = jas_strdup(jas_tvparser_getval(tvp)))) { return -1; } break; } } jas_tvparser_destroy(tvp); if (!cmpt->sampperx || !cmpt->samppery) { goto error; } if (mif_hdr_addcmpt(hdr, hdr->numcmpts, cmpt)) { goto error; } return 0; error: if (cmpt) { mif_cmpt_destroy(cmpt); } if (tvp) { jas_tvparser_destroy(tvp); } return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'CVE-2015-5221'</s>
<s>[INST] Given the following code containing errors, provide 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 vnc_update_client(VncState *vs, int has_dirty, bool sync) { if (vs->need_update && vs->csock != -1) { VncDisplay *vd = vs->vd; VncJob *job; int y; int height, width; int n = 0; if (vs->output.offset && !vs->audio_cap && !vs->force_update) /* kernel send buffers are full -> drop frames to throttle */ return 0; if (!has_dirty && !vs->audio_cap && !vs->force_update) return 0; /* * Send screen updates to the vnc client using the server * surface and server dirty map. guest surface updates * happening in parallel don't disturb us, the next pass will * send them to the client. */ job = vnc_job_new(vs); height = MIN(pixman_image_get_height(vd->server), vs->client_height); width = MIN(pixman_image_get_width(vd->server), vs->client_width); y = 0; for (;;) { int x, h; unsigned long x2; unsigned long offset = find_next_bit((unsigned long *) &vs->dirty, height * VNC_DIRTY_BPL(vs), y * VNC_DIRTY_BPL(vs)); if (offset == height * VNC_DIRTY_BPL(vs)) { /* no more dirty bits */ break; } y = offset / VNC_DIRTY_BPL(vs); x = offset % VNC_DIRTY_BPL(vs); x2 = find_next_zero_bit((unsigned long *) &vs->dirty[y], VNC_DIRTY_BPL(vs), x); bitmap_clear(vs->dirty[y], x, x2 - x); h = find_and_clear_dirty_height(vs, y, x, x2, height); x2 = MIN(x2, width / VNC_DIRTY_PIXELS_PER_BIT); if (x2 > x) { n += vnc_job_add_rect(job, x * VNC_DIRTY_PIXELS_PER_BIT, y, (x2 - x) * VNC_DIRTY_PIXELS_PER_BIT, h); } } vnc_job_push(job); if (sync) { vnc_jobs_join(vs); } vs->force_update = 0; return n; } if (vs->csock == -1) { vnc_disconnect_finish(vs); } else if (sync) { vnc_jobs_join(vs); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'ui/vnc: fix potential memory corruption issues this patch makes the VNC server work correctly if the server surface and the guest surface have different sizes. Basically the server surface is adjusted to not exceed VNC_MAX_WIDTH x VNC_MAX_HEIGHT and additionally the width is rounded up to multiple of VNC_DIRTY_PIXELS_PER_BIT. If we have a resolution whose width is not dividable by VNC_DIRTY_PIXELS_PER_BIT we now get a small black bar on the right of the screen. If the surface is too big to fit the limits only the upper left area is shown. On top of that this fixes 2 memory corruption issues: The first was actually discovered during playing around with a Windows 7 vServer. During resolution change in Windows 7 it happens sometimes that Windows changes to an intermediate resolution where server_stride % cmp_bytes != 0 (in vnc_refresh_server_surface). This happens only if width % VNC_DIRTY_PIXELS_PER_BIT != 0. The second is a theoretical issue, but is maybe exploitable by the guest. If for some reason the guest surface size is bigger than VNC_MAX_WIDTH x VNC_MAX_HEIGHT we end up in severe corruption since this limit is nowhere enforced. Signed-off-by: Peter Lieven <[email protected]> Signed-off-by: Gerd Hoffmann <[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 pointer_event(VncState *vs, int button_mask, int x, int y) { static uint32_t bmap[INPUT_BUTTON_MAX] = { [INPUT_BUTTON_LEFT] = 0x01, [INPUT_BUTTON_MIDDLE] = 0x02, [INPUT_BUTTON_RIGHT] = 0x04, [INPUT_BUTTON_WHEEL_UP] = 0x08, [INPUT_BUTTON_WHEEL_DOWN] = 0x10, }; QemuConsole *con = vs->vd->dcl.con; int width = surface_width(vs->vd->ds); int height = surface_height(vs->vd->ds); if (vs->last_bmask != button_mask) { qemu_input_update_buttons(con, bmap, vs->last_bmask, button_mask); vs->last_bmask = button_mask; } if (vs->absolute) { qemu_input_queue_abs(con, INPUT_AXIS_X, x, width); qemu_input_queue_abs(con, INPUT_AXIS_Y, y, height); } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) { qemu_input_queue_rel(con, INPUT_AXIS_X, x - 0x7FFF); qemu_input_queue_rel(con, INPUT_AXIS_Y, y - 0x7FFF); } else { if (vs->last_x != -1) { qemu_input_queue_rel(con, INPUT_AXIS_X, x - vs->last_x); qemu_input_queue_rel(con, INPUT_AXIS_Y, y - vs->last_y); } vs->last_x = x; vs->last_y = y; } qemu_input_event_sync(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'ui/vnc: fix potential memory corruption issues this patch makes the VNC server work correctly if the server surface and the guest surface have different sizes. Basically the server surface is adjusted to not exceed VNC_MAX_WIDTH x VNC_MAX_HEIGHT and additionally the width is rounded up to multiple of VNC_DIRTY_PIXELS_PER_BIT. If we have a resolution whose width is not dividable by VNC_DIRTY_PIXELS_PER_BIT we now get a small black bar on the right of the screen. If the surface is too big to fit the limits only the upper left area is shown. On top of that this fixes 2 memory corruption issues: The first was actually discovered during playing around with a Windows 7 vServer. During resolution change in Windows 7 it happens sometimes that Windows changes to an intermediate resolution where server_stride % cmp_bytes != 0 (in vnc_refresh_server_surface). This happens only if width % VNC_DIRTY_PIXELS_PER_BIT != 0. The second is a theoretical issue, but is maybe exploitable by the guest. If for some reason the guest surface size is bigger than VNC_MAX_WIDTH x VNC_MAX_HEIGHT we end up in severe corruption since this limit is nowhere enforced. Signed-off-by: Peter Lieven <[email protected]> Signed-off-by: Gerd Hoffmann <[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 send_ext_audio_ack(VncState *vs) { vnc_lock_output(vs); vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE); vnc_write_u8(vs, 0); vnc_write_u16(vs, 1); vnc_framebuffer_update(vs, 0, 0, surface_width(vs->vd->ds), surface_height(vs->vd->ds), VNC_ENCODING_AUDIO); vnc_unlock_output(vs); vnc_flush(vs); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'ui/vnc: fix potential memory corruption issues this patch makes the VNC server work correctly if the server surface and the guest surface have different sizes. Basically the server surface is adjusted to not exceed VNC_MAX_WIDTH x VNC_MAX_HEIGHT and additionally the width is rounded up to multiple of VNC_DIRTY_PIXELS_PER_BIT. If we have a resolution whose width is not dividable by VNC_DIRTY_PIXELS_PER_BIT we now get a small black bar on the right of the screen. If the surface is too big to fit the limits only the upper left area is shown. On top of that this fixes 2 memory corruption issues: The first was actually discovered during playing around with a Windows 7 vServer. During resolution change in Windows 7 it happens sometimes that Windows changes to an intermediate resolution where server_stride % cmp_bytes != 0 (in vnc_refresh_server_surface). This happens only if width % VNC_DIRTY_PIXELS_PER_BIT != 0. The second is a theoretical issue, but is maybe exploitable by the guest. If for some reason the guest surface size is bigger than VNC_MAX_WIDTH x VNC_MAX_HEIGHT we end up in severe corruption since this limit is nowhere enforced. Signed-off-by: Peter Lieven <[email protected]> Signed-off-by: Gerd Hoffmann <[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 vnc_colordepth(VncState *vs) { if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) { /* Sending a WMVi message to notify the client*/ vnc_lock_output(vs); vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE); vnc_write_u8(vs, 0); vnc_write_u16(vs, 1); /* number of rects */ vnc_framebuffer_update(vs, 0, 0, surface_width(vs->vd->ds), surface_height(vs->vd->ds), VNC_ENCODING_WMVi); pixel_format_message(vs); vnc_unlock_output(vs); vnc_flush(vs); } else { set_pixel_conversion(vs); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'ui/vnc: fix potential memory corruption issues this patch makes the VNC server work correctly if the server surface and the guest surface have different sizes. Basically the server surface is adjusted to not exceed VNC_MAX_WIDTH x VNC_MAX_HEIGHT and additionally the width is rounded up to multiple of VNC_DIRTY_PIXELS_PER_BIT. If we have a resolution whose width is not dividable by VNC_DIRTY_PIXELS_PER_BIT we now get a small black bar on the right of the screen. If the surface is too big to fit the limits only the upper left area is shown. On top of that this fixes 2 memory corruption issues: The first was actually discovered during playing around with a Windows 7 vServer. During resolution change in Windows 7 it happens sometimes that Windows changes to an intermediate resolution where server_stride % cmp_bytes != 0 (in vnc_refresh_server_surface). This happens only if width % VNC_DIRTY_PIXELS_PER_BIT != 0. The second is a theoretical issue, but is maybe exploitable by the guest. If for some reason the guest surface size is bigger than VNC_MAX_WIDTH x VNC_MAX_HEIGHT we end up in severe corruption since this limit is nowhere enforced. Signed-off-by: Peter Lieven <[email protected]> Signed-off-by: Gerd Hoffmann <[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 send_ext_key_event_ack(VncState *vs) { vnc_lock_output(vs); vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE); vnc_write_u8(vs, 0); vnc_write_u16(vs, 1); vnc_framebuffer_update(vs, 0, 0, surface_width(vs->vd->ds), surface_height(vs->vd->ds), VNC_ENCODING_EXT_KEY_EVENT); vnc_unlock_output(vs); vnc_flush(vs); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'ui/vnc: fix potential memory corruption issues this patch makes the VNC server work correctly if the server surface and the guest surface have different sizes. Basically the server surface is adjusted to not exceed VNC_MAX_WIDTH x VNC_MAX_HEIGHT and additionally the width is rounded up to multiple of VNC_DIRTY_PIXELS_PER_BIT. If we have a resolution whose width is not dividable by VNC_DIRTY_PIXELS_PER_BIT we now get a small black bar on the right of the screen. If the surface is too big to fit the limits only the upper left area is shown. On top of that this fixes 2 memory corruption issues: The first was actually discovered during playing around with a Windows 7 vServer. During resolution change in Windows 7 it happens sometimes that Windows changes to an intermediate resolution where server_stride % cmp_bytes != 0 (in vnc_refresh_server_surface). This happens only if width % VNC_DIRTY_PIXELS_PER_BIT != 0. The second is a theoretical issue, but is maybe exploitable by the guest. If for some reason the guest surface size is bigger than VNC_MAX_WIDTH x VNC_MAX_HEIGHT we end up in severe corruption since this limit is nowhere enforced. Signed-off-by: Peter Lieven <[email protected]> Signed-off-by: Gerd Hoffmann <[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 framebuffer_update_request(VncState *vs, int incremental, int x_position, int y_position, int w, int h) { int i; const size_t width = surface_width(vs->vd->ds) / VNC_DIRTY_PIXELS_PER_BIT; const size_t height = surface_height(vs->vd->ds); if (y_position > height) { y_position = height; } if (y_position + h >= height) { h = height - y_position; } vs->need_update = 1; if (!incremental) { vs->force_update = 1; for (i = 0; i < h; i++) { bitmap_set(vs->dirty[y_position + i], 0, width); bitmap_clear(vs->dirty[y_position + i], width, VNC_DIRTY_BITS - width); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'ui/vnc: fix potential memory corruption issues this patch makes the VNC server work correctly if the server surface and the guest surface have different sizes. Basically the server surface is adjusted to not exceed VNC_MAX_WIDTH x VNC_MAX_HEIGHT and additionally the width is rounded up to multiple of VNC_DIRTY_PIXELS_PER_BIT. If we have a resolution whose width is not dividable by VNC_DIRTY_PIXELS_PER_BIT we now get a small black bar on the right of the screen. If the surface is too big to fit the limits only the upper left area is shown. On top of that this fixes 2 memory corruption issues: The first was actually discovered during playing around with a Windows 7 vServer. During resolution change in Windows 7 it happens sometimes that Windows changes to an intermediate resolution where server_stride % cmp_bytes != 0 (in vnc_refresh_server_surface). This happens only if width % VNC_DIRTY_PIXELS_PER_BIT != 0. The second is a theoretical issue, but is maybe exploitable by the guest. If for some reason the guest surface size is bigger than VNC_MAX_WIDTH x VNC_MAX_HEIGHT we end up in severe corruption since this limit is nowhere enforced. Signed-off-by: Peter Lieven <[email protected]> Signed-off-by: Gerd Hoffmann <[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 spl_object_storage_attach(spl_SplObjectStorage *intern, zval *this, zval *obj, zval *inf TSRMLS_DC) /* {{{ */ { spl_SplObjectStorageElement *pelement, element; int hash_len; char *hash = spl_object_storage_get_hash(intern, this, obj, &hash_len TSRMLS_CC); if (!hash) { return; } pelement = spl_object_storage_get(intern, hash, hash_len TSRMLS_CC); if (inf) { Z_ADDREF_P(inf); } else { ALLOC_INIT_ZVAL(inf); } if (pelement) { zval_ptr_dtor(&pelement->inf); pelement->inf = inf; spl_object_storage_free_hash(intern, hash); return; } Z_ADDREF_P(obj); element.obj = obj; element.inf = inf; zend_hash_update(&intern->storage, hash, hash_len, &element, sizeof(spl_SplObjectStorageElement), NULL); spl_object_storage_free_hash(intern, hash); } /* }}} */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fix bug #70168 - Use After Free Vulnerability in unserialize() with SplObjectStorage'</s>
<s>[INST] Given the following code containing errors, provide 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 spl_object_storage_detach(spl_SplObjectStorage *intern, zval *this, zval *obj TSRMLS_DC) /* {{{ */ { int hash_len, ret = FAILURE; char *hash = spl_object_storage_get_hash(intern, this, obj, &hash_len TSRMLS_CC); if (!hash) { return ret; } ret = zend_hash_del(&intern->storage, hash, hash_len); spl_object_storage_free_hash(intern, hash); return ret; } /* }}}*/ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fix bug #70168 - Use After Free Vulnerability in unserialize() with SplObjectStorage'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SPL_METHOD(SplObjectStorage, next) { spl_SplObjectStorage *intern = (spl_SplObjectStorage*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } zend_hash_move_forward_ex(&intern->storage, &intern->pos); intern->index++; } /* }}} */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fix bug #70168 - Use After Free Vulnerability in unserialize() with SplObjectStorage'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SPL_METHOD(SplObjectStorage, rewind) { spl_SplObjectStorage *intern = (spl_SplObjectStorage*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } zend_hash_internal_pointer_reset_ex(&intern->storage, &intern->pos); intern->index = 0; } /* }}} */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fix bug #70168 - Use After Free Vulnerability in unserialize() with SplObjectStorage'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SPL_METHOD(MultipleIterator, current) { spl_SplObjectStorage *intern; intern = (spl_SplObjectStorage*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } spl_multiple_iterator_get_all(intern, SPL_MULTIPLE_ITERATOR_GET_ALL_CURRENT, return_value TSRMLS_CC); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fix bug #70168 - Use After Free Vulnerability in unserialize() with SplObjectStorage'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SPL_METHOD(MultipleIterator, rewind) { spl_SplObjectStorage *intern; spl_SplObjectStorageElement *element; zval *it; intern = (spl_SplObjectStorage*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } zend_hash_internal_pointer_reset_ex(&intern->storage, &intern->pos); while (zend_hash_get_current_data_ex(&intern->storage, (void**)&element, &intern->pos) == SUCCESS && !EG(exception)) { it = element->obj; zend_call_method_with_0_params(&it, Z_OBJCE_P(it), &Z_OBJCE_P(it)->iterator_funcs.zf_rewind, "rewind", NULL); zend_hash_move_forward_ex(&intern->storage, &intern->pos); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fix bug #70168 - Use After Free Vulnerability in unserialize() with SplObjectStorage'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SPL_METHOD(MultipleIterator, valid) { spl_SplObjectStorage *intern; spl_SplObjectStorageElement *element; zval *it, *retval = NULL; long expect, valid; intern = (spl_SplObjectStorage*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!zend_hash_num_elements(&intern->storage)) { RETURN_FALSE; } expect = (intern->flags & MIT_NEED_ALL) ? 1 : 0; zend_hash_internal_pointer_reset_ex(&intern->storage, &intern->pos); while (zend_hash_get_current_data_ex(&intern->storage, (void**)&element, &intern->pos) == SUCCESS && !EG(exception)) { it = element->obj; zend_call_method_with_0_params(&it, Z_OBJCE_P(it), &Z_OBJCE_P(it)->iterator_funcs.zf_valid, "valid", &retval); if (retval) { valid = Z_LVAL_P(retval); zval_ptr_dtor(&retval); } else { valid = 0; } if (expect != valid) { RETURN_BOOL(!expect); } zend_hash_move_forward_ex(&intern->storage, &intern->pos); } RETURN_BOOL(expect); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fix bug #70168 - Use After Free Vulnerability in unserialize() with SplObjectStorage'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SPL_METHOD(SplObjectStorage, current) { spl_SplObjectStorageElement *element; spl_SplObjectStorage *intern = (spl_SplObjectStorage*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (zend_hash_get_current_data_ex(&intern->storage, (void**)&element, &intern->pos) == FAILURE) { return; } RETVAL_ZVAL(element->obj, 1, 0); } /* }}} */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fix bug #70168 - Use After Free Vulnerability in unserialize() with SplObjectStorage'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SPL_METHOD(SplObjectStorage, unserialize) { spl_SplObjectStorage *intern = (spl_SplObjectStorage*)zend_object_store_get_object(getThis() TSRMLS_CC); char *buf; int buf_len; const unsigned char *p, *s; php_unserialize_data_t var_hash; zval *pentry, *pmembers, *pcount = NULL, *pinf; long count; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &buf, &buf_len) == FAILURE) { return; } if (buf_len == 0) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Empty serialized string cannot be empty"); return; } /* storage */ s = p = (const unsigned char*)buf; PHP_VAR_UNSERIALIZE_INIT(var_hash); if (*p!= 'x' || *++p != ':') { goto outexcept; } ++p; ALLOC_INIT_ZVAL(pcount); if (!php_var_unserialize(&pcount, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pcount) != IS_LONG) { goto outexcept; } --p; /* for ';' */ count = Z_LVAL_P(pcount); while(count-- > 0) { spl_SplObjectStorageElement *pelement; char *hash; int hash_len; if (*p != ';') { goto outexcept; } ++p; if(*p != 'O' && *p != 'C' && *p != 'r') { goto outexcept; } ALLOC_INIT_ZVAL(pentry); if (!php_var_unserialize(&pentry, &p, s + buf_len, &var_hash TSRMLS_CC)) { zval_ptr_dtor(&pentry); goto outexcept; } if(Z_TYPE_P(pentry) != IS_OBJECT) { zval_ptr_dtor(&pentry); goto outexcept; } ALLOC_INIT_ZVAL(pinf); if (*p == ',') { /* new version has inf */ ++p; if (!php_var_unserialize(&pinf, &p, s + buf_len, &var_hash TSRMLS_CC)) { zval_ptr_dtor(&pinf); goto outexcept; } } hash = spl_object_storage_get_hash(intern, getThis(), pentry, &hash_len TSRMLS_CC); if (!hash) { zval_ptr_dtor(&pentry); zval_ptr_dtor(&pinf); goto outexcept; } pelement = spl_object_storage_get(intern, hash, hash_len TSRMLS_CC); spl_object_storage_free_hash(intern, hash); if(pelement) { if(pelement->inf) { var_push_dtor(&var_hash, &pelement->inf); } if(pelement->obj) { var_push_dtor(&var_hash, &pelement->obj); } } spl_object_storage_attach(intern, getThis(), pentry, pinf TSRMLS_CC); zval_ptr_dtor(&pentry); zval_ptr_dtor(&pinf); } if (*p != ';') { goto outexcept; } ++p; /* members */ if (*p!= 'm' || *++p != ':') { goto outexcept; } ++p; ALLOC_INIT_ZVAL(pmembers); if (!php_var_unserialize(&pmembers, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pmembers) != IS_ARRAY) { zval_ptr_dtor(&pmembers); goto outexcept; } /* copy members */ if (!intern->std.properties) { rebuild_object_properties(&intern->std); } zend_hash_copy(intern->std.properties, Z_ARRVAL_P(pmembers), (copy_ctor_func_t) zval_add_ref, (void *) NULL, sizeof(zval *)); zval_ptr_dtor(&pmembers); /* done reading $serialized */ if (pcount) { zval_ptr_dtor(&pcount); } PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return; outexcept: if (pcount) { zval_ptr_dtor(&pcount); } PHP_VAR_UNSERIALIZE_DESTROY(var_hash); zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Error at offset %ld of %d bytes", (long)((char*)p - buf), buf_len); return; } /* }}} */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fix bug #70168 - Use After Free Vulnerability in unserialize() with SplObjectStorage'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SPL_METHOD(MultipleIterator, key) { spl_SplObjectStorage *intern; intern = (spl_SplObjectStorage*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } spl_multiple_iterator_get_all(intern, SPL_MULTIPLE_ITERATOR_GET_ALL_KEY, return_value TSRMLS_CC); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fix bug #70168 - Use After Free Vulnerability in unserialize() with SplObjectStorage'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SPL_METHOD(SplDoublyLinkedList, shift) { zval *value; spl_dllist_object *intern; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "") == FAILURE) { return; } intern = (spl_dllist_object*)zend_object_store_get_object(getThis() TSRMLS_CC); value = (zval *)spl_ptr_llist_shift(intern->llist TSRMLS_CC); if (value == NULL) { zend_throw_exception(spl_ce_RuntimeException, "Can't shift from an empty datastructure", 0 TSRMLS_CC); return; } RETURN_ZVAL(value, 1, 1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fixed bug #70169 (Use After Free Vulnerability in unserialize() with SplDoublyLinkedList)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SPL_METHOD(SplDoublyLinkedList, serialize) { spl_dllist_object *intern = (spl_dllist_object*)zend_object_store_get_object(getThis() TSRMLS_CC); smart_str buf = {0}; spl_ptr_llist_element *current = intern->llist->head, *next; zval *flags; php_serialize_data_t var_hash; if (zend_parse_parameters_none() == FAILURE) { return; } PHP_VAR_SERIALIZE_INIT(var_hash); /* flags */ MAKE_STD_ZVAL(flags); ZVAL_LONG(flags, intern->flags); php_var_serialize(&buf, &flags, &var_hash TSRMLS_CC); zval_ptr_dtor(&flags); /* elements */ while (current) { smart_str_appendc(&buf, ':'); next = current->next; php_var_serialize(&buf, (zval **)&current->data, &var_hash TSRMLS_CC); current = next; } smart_str_0(&buf); /* done */ PHP_VAR_SERIALIZE_DESTROY(var_hash); if (buf.c) { RETURN_STRINGL(buf.c, buf.len, 0); } else { RETURN_NULL(); } } /* }}} */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fixed bug #70169 (Use After Free Vulnerability in unserialize() with SplDoublyLinkedList)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SPL_METHOD(SplDoublyLinkedList, push) { zval *value; spl_dllist_object *intern; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &value) == FAILURE) { return; } SEPARATE_ARG_IF_REF(value); intern = (spl_dllist_object*)zend_object_store_get_object(getThis() TSRMLS_CC); spl_ptr_llist_push(intern->llist, value TSRMLS_CC); RETURN_TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fixed bug #70169 (Use After Free Vulnerability in unserialize() with SplDoublyLinkedList)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SPL_METHOD(SplDoublyLinkedList, pop) { zval *value; spl_dllist_object *intern; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "") == FAILURE) { return; } intern = (spl_dllist_object*)zend_object_store_get_object(getThis() TSRMLS_CC); value = (zval *)spl_ptr_llist_pop(intern->llist TSRMLS_CC); if (value == NULL) { zend_throw_exception(spl_ce_RuntimeException, "Can't pop from an empty datastructure", 0 TSRMLS_CC); return; } RETURN_ZVAL(value, 1, 1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fixed bug #70169 (Use After Free Vulnerability in unserialize() with SplDoublyLinkedList)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SPL_METHOD(SplDoublyLinkedList, valid) { spl_dllist_object *intern = (spl_dllist_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(intern->traverse_pointer != NULL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fixed bug #70169 (Use After Free Vulnerability in unserialize() with SplDoublyLinkedList)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SPL_METHOD(SplDoublyLinkedList, rewind) { spl_dllist_object *intern = (spl_dllist_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } spl_dllist_it_helper_rewind(&intern->traverse_pointer, &intern->traverse_position, intern->llist, intern->flags TSRMLS_CC); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fixed bug #70169 (Use After Free Vulnerability in unserialize() with SplDoublyLinkedList)'</s>
<s>[INST] Given the following code containing errors, provide 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 FILE *xfmkstemp(char **tmpname, char *dir) { int fd; FILE *ret; fd = xmkstemp(tmpname, dir); if (fd == -1) return NULL; if (!(ret = fdopen(fd, "w+" UL_CLOEXECSTR))) { close(fd); return NULL; } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'chsh, chfn, vipw: fix filenames collision The utils when compiled WITHOUT libuser then mkostemp()ing "/etc/%s.XXXXXX" where the filename prefix is argv[0] basename. An attacker could repeatedly execute the util with modified argv[0] and after many many attempts mkostemp() may generate suffix which makes sense. The result maybe temporary file with name like rc.status ld.so.preload or krb5.keytab, etc. Note that distros usually use libuser based ch{sh,fn} or stuff from shadow-utils. It's probably very minor security bug. Addresses: CVE-2015-5224 Signed-off-by: Karel Zak <[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 FILE * pw_tmpfile(int lockfd) { FILE *fd; char *tmpname = NULL; char *dir = "/etc"; if ((fd = xfmkstemp(&tmpname, dir)) == NULL) { ulckpwdf(); err(EXIT_FAILURE, _("can't open temporary file")); } copyfile(lockfd, fileno(fd)); tmp_file = tmpname; return fd; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'chsh, chfn, vipw: fix filenames collision The utils when compiled WITHOUT libuser then mkostemp()ing "/etc/%s.XXXXXX" where the filename prefix is argv[0] basename. An attacker could repeatedly execute the util with modified argv[0] and after many many attempts mkostemp() may generate suffix which makes sense. The result maybe temporary file with name like rc.status ld.so.preload or krb5.keytab, etc. Note that distros usually use libuser based ch{sh,fn} or stuff from shadow-utils. It's probably very minor security bug. Addresses: CVE-2015-5224 Signed-off-by: Karel Zak <[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 MScrollV(Window *p, int n, int ys, int ye, int bce) { int i, cnt1, cnt2; struct mline tmp[256]; struct mline *ml; if (n == 0) return; if (n > 0) { if (n > 256) { MScrollV(p, n - 256, ys, ye, bce); n = 256; } if (ye - ys + 1 < n) n = ye - ys + 1; if (compacthist) { ye = MFindUsedLine(p, ye, ys); if (ye - ys + 1 < n) n = ye - ys + 1; if (n <= 0) return; } /* Clear lines */ ml = p->w_mlines + ys; for (i = ys; i < ys + n; i++, ml++) { if (ys == p->w_top) WAddLineToHist(p, ml); if (ml->attr != null) free(ml->attr); ml->attr = null; if (ml->font != null) free(ml->font); ml->font = null; if (ml->fontx != null) free(ml->fontx); ml->fontx = null; if (ml->colorbg != null) free(ml->colorbg); ml->colorbg = null; if (ml->colorfg != null) free(ml->colorfg); ml->colorfg = null; memmove(ml->image, blank, (p->w_width + 1) * 4); if (bce) MBceLine(p, i, 0, p->w_width, bce); } /* switch 'em over */ cnt1 = n * sizeof(struct mline); cnt2 = (ye - ys + 1 - n) * sizeof(struct mline); if (cnt1 && cnt2) Scroll((char *)(p->w_mlines + ys), cnt1, cnt2, (char *)tmp); } else { if (n < -256) { MScrollV(p, n + 256, ys, ye, bce); n = -256; } n = -n; if (ye - ys + 1 < n) n = ye - ys + 1; ml = p->w_mlines + ye; /* Clear lines */ for (i = ye; i > ye - n; i--, ml--) { if (ml->attr != null) free(ml->attr); ml->attr = null; if (ml->font != null) free(ml->font); ml->font = null; if (ml->fontx != null) free(ml->fontx); ml->fontx = null; if (ml->colorbg != null) free(ml->colorbg); ml->colorbg = null; if (ml->colorfg != null) free(ml->colorfg); ml->colorfg = null; memmove(ml->image, blank, (p->w_width + 1) * 4); if (bce) MBceLine(p, i, 0, p->w_width, bce); } cnt1 = n * sizeof(struct mline); cnt2 = (ye - ys + 1 - n) * sizeof(struct mline); if (cnt1 && cnt2) Scroll((char *)(p->w_mlines + ys), cnt2, cnt1, (char *)tmp); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix stack overflow due to too deep recursion Bug: 45713 How to reproduce: Run this command inside screen $ printf '\x1b[10000000T' screen will recursively call MScrollV to depth n/256. This is time consuming and will overflow stack if n is huge.'</s>
<s>[INST] Given the following code containing errors, provide 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 php_zip_parse_options(zval *options, long *remove_all_path, char **remove_path, int *remove_path_len, char **add_path, int *add_path_len TSRMLS_DC) /* {{{ */ { zval **option; if (zend_hash_find(HASH_OF(options), "remove_all_path", sizeof("remove_all_path"), (void **)&option) == SUCCESS) { long opt; if (Z_TYPE_PP(option) != IS_LONG) { zval tmp = **option; zval_copy_ctor(&tmp); convert_to_long(&tmp); opt = Z_LVAL(tmp); } else { opt = Z_LVAL_PP(option); } *remove_all_path = opt; } /* If I add more options, it would make sense to create a nice static struct and loop over it. */ if (zend_hash_find(HASH_OF(options), "remove_path", sizeof("remove_path"), (void **)&option) == SUCCESS) { if (Z_TYPE_PP(option) != IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "remove_path option expected to be a string"); return -1; } if (Z_STRLEN_PP(option) < 1) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Empty string given as remove_path option"); return -1; } if (Z_STRLEN_PP(option) >= MAXPATHLEN) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "remove_path string is too long (max: %i, %i given)", MAXPATHLEN - 1, Z_STRLEN_PP(option)); return -1; } *remove_path_len = Z_STRLEN_PP(option); *remove_path = Z_STRVAL_PP(option); } if (zend_hash_find(HASH_OF(options), "add_path", sizeof("add_path"), (void **)&option) == SUCCESS) { if (Z_TYPE_PP(option) != IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "add_path option expected to be a string"); return -1; } if (Z_STRLEN_PP(option) < 1) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Empty string given as the add_path option"); return -1; } if (Z_STRLEN_PP(option) >= MAXPATHLEN) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "add_path string too long (max: %i, %i given)", MAXPATHLEN - 1, Z_STRLEN_PP(option)); return -1; } *add_path_len = Z_STRLEN_PP(option); *add_path = Z_STRVAL_PP(option); } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'Fixed bug #70350: ZipArchive::extractTo allows for directory traversal when creating directories'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static zval **php_zip_get_property_ptr_ptr(zval *object, zval *member, const zend_literal *key TSRMLS_DC) /* {{{ */ { ze_zip_object *obj; zval tmp_member; zval **retval = NULL; zip_prop_handler *hnd; zend_object_handlers *std_hnd; int ret; if (member->type != IS_STRING) { tmp_member = *member; zval_copy_ctor(&tmp_member); convert_to_string(&tmp_member); member = &tmp_member; key = NULL; } ret = FAILURE; obj = (ze_zip_object *)zend_objects_get_address(object TSRMLS_CC); if (obj->prop_handler != NULL) { if (key) { ret = zend_hash_quick_find(obj->prop_handler, Z_STRVAL_P(member), Z_STRLEN_P(member)+1, key->hash_value, (void **) &hnd); } else { ret = zend_hash_find(obj->prop_handler, Z_STRVAL_P(member), Z_STRLEN_P(member)+1, (void **) &hnd); } } if (ret == FAILURE) { std_hnd = zend_get_std_object_handlers(); retval = std_hnd->get_property_ptr_ptr(object, member, key TSRMLS_CC); } if (member == &tmp_member) { zval_dtor(member); } return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'Fixed bug #70350: ZipArchive::extractTo allows for directory traversal when creating directories'</s>
<s>[INST] Given the following code containing errors, provide 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 ZIPARCHIVE_METHOD(getStatusString) { struct zip *intern; zval *this = getThis(); int zep, syp, len; char error_string[128]; if (!this) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, this); zip_error_get(intern, &zep, &syp); len = zip_error_to_str(error_string, 128, zep, syp); RETVAL_STRINGL(error_string, len, 1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'Fixed bug #70350: ZipArchive::extractTo allows for directory traversal when creating directories'</s>
<s>[INST] Given the following code containing errors, provide 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 php_zip_glob(char *pattern, int pattern_len, long flags, zval *return_value TSRMLS_DC) /* {{{ */ { #ifdef HAVE_GLOB char cwd[MAXPATHLEN]; int cwd_skip = 0; #ifdef ZTS char work_pattern[MAXPATHLEN]; char *result; #endif glob_t globbuf; int n; int ret; if (pattern_len >= MAXPATHLEN) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Pattern exceeds the maximum allowed length of %d characters", MAXPATHLEN); return -1; } if ((GLOB_AVAILABLE_FLAGS & flags) != flags) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "At least one of the passed flags is invalid or not supported on this platform"); return -1; } #ifdef ZTS if (!IS_ABSOLUTE_PATH(pattern, pattern_len)) { result = VCWD_GETCWD(cwd, MAXPATHLEN); if (!result) { cwd[0] = '\0'; } #ifdef PHP_WIN32 if (IS_SLASH(*pattern)) { cwd[2] = '\0'; } #endif cwd_skip = strlen(cwd)+1; snprintf(work_pattern, MAXPATHLEN, "%s%c%s", cwd, DEFAULT_SLASH, pattern); pattern = work_pattern; } #endif globbuf.gl_offs = 0; if (0 != (ret = glob(pattern, flags & GLOB_FLAGMASK, NULL, &globbuf))) { #ifdef GLOB_NOMATCH if (GLOB_NOMATCH == ret) { /* Some glob implementation simply return no data if no matches were found, others return the GLOB_NOMATCH error code. We don't want to treat GLOB_NOMATCH as an error condition so that PHP glob() behaves the same on both types of implementations and so that 'foreach (glob() as ...' can be used for simple glob() calls without further error checking. */ array_init(return_value); return 0; } #endif return 0; } /* now catch the FreeBSD style of "no matches" */ if (!globbuf.gl_pathc || !globbuf.gl_pathv) { array_init(return_value); return 0; } /* we assume that any glob pattern will match files from one directory only so checking the dirname of the first match should be sufficient */ strncpy(cwd, globbuf.gl_pathv[0], MAXPATHLEN); if (ZIP_OPENBASEDIR_CHECKPATH(cwd)) { return -1; } array_init(return_value); for (n = 0; n < globbuf.gl_pathc; n++) { /* we need to do this everytime since GLOB_ONLYDIR does not guarantee that * all directories will be filtered. GNU libc documentation states the * following: * If the information about the type of the file is easily available * non-directories will be rejected but no extra work will be done to * determine the information for each file. I.e., the caller must still be * able to filter directories out. */ if (flags & GLOB_ONLYDIR) { struct stat s; if (0 != VCWD_STAT(globbuf.gl_pathv[n], &s)) { continue; } if (S_IFDIR != (s.st_mode & S_IFMT)) { continue; } } add_next_index_string(return_value, globbuf.gl_pathv[n]+cwd_skip, 1); } globfree(&globbuf); return globbuf.gl_pathc; #else php_error_docref(NULL TSRMLS_CC, E_ERROR, "Glob support is not available"); return 0; #endif /* HAVE_GLOB */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'Fixed bug #70350: ZipArchive::extractTo allows for directory traversal when creating directories'</s>