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: ebb_ews_connect_sync (EBookMetaBackend *meta_backend,
const ENamedParameters *credentials,
ESourceAuthenticationResult *out_auth_result,
gchar **out_certificate_pem,
GTlsCertificateFlags *out_certificate_errors,
GCancellable *cancellable,
GError **error)
{
EBookBackendEws *bbews;
EBookCache *book_cache;
CamelEwsSettings *ews_settings;
gchar *hosturl;
gboolean success = FALSE;
g_return_val_if_fail (E_IS_BOOK_BACKEND_EWS (meta_backend), FALSE);
g_return_val_if_fail (out_auth_result != NULL, FALSE);
bbews = E_BOOK_BACKEND_EWS (meta_backend);
g_rec_mutex_lock (&bbews->priv->cnc_lock);
if (bbews->priv->cnc) {
g_rec_mutex_unlock (&bbews->priv->cnc_lock);
*out_auth_result = E_SOURCE_AUTHENTICATION_ACCEPTED;
return TRUE;
}
book_cache = e_book_meta_backend_ref_cache (E_BOOK_META_BACKEND (bbews));
if (book_cache) {
ECache *cache = E_CACHE (book_cache);
gint data_version;
data_version = e_cache_get_key_int (cache, EBB_EWS_DATA_VERSION_KEY, NULL);
if (data_version != EBB_EWS_DATA_VERSION) {
MigrateData md;
e_cache_set_key_int (cache, EBB_EWS_DATA_VERSION_KEY, EBB_EWS_DATA_VERSION, NULL);
md.data_version = data_version;
md.is_gal = ebb_ews_check_is_gal (bbews);
if (e_cache_foreach_update (cache, E_CACHE_INCLUDE_DELETED, NULL, ebb_ews_migrate_data_cb, &md, cancellable, NULL))
e_cache_sqlite_exec (cache, "vacuum;", cancellable, NULL);
}
g_clear_object (&book_cache);
}
ews_settings = ebb_ews_get_collection_settings (bbews);
hosturl = camel_ews_settings_dup_hosturl (ews_settings);
bbews->priv->cnc = e_ews_connection_new_for_backend (E_BACKEND (bbews), e_book_backend_get_registry (E_BOOK_BACKEND (bbews)), hosturl, ews_settings);
e_binding_bind_property (
bbews, "proxy-resolver",
bbews->priv->cnc, "proxy-resolver",
G_BINDING_SYNC_CREATE);
*out_auth_result = e_ews_connection_try_credentials_sync (bbews->priv->cnc, credentials, cancellable, error);
if (*out_auth_result == E_SOURCE_AUTHENTICATION_ACCEPTED) {
ESource *source = e_backend_get_source (E_BACKEND (bbews));
ESourceEwsFolder *ews_folder;
ews_folder = e_source_get_extension (source, E_SOURCE_EXTENSION_EWS_FOLDER);
g_free (bbews->priv->folder_id);
bbews->priv->folder_id = e_source_ews_folder_dup_id (ews_folder);
bbews->priv->is_gal = ebb_ews_check_is_gal (bbews);
g_signal_connect_swapped (bbews->priv->cnc, "server-notification",
G_CALLBACK (ebb_ews_server_notification_cb), bbews);
if (!bbews->priv->is_gal &&
camel_ews_settings_get_listen_notifications (ews_settings) &&
e_ews_connection_satisfies_server_version (bbews->priv->cnc, E_EWS_EXCHANGE_2010_SP1)) {
GSList *folders = NULL;
folders = g_slist_prepend (folders, bbews->priv->folder_id);
e_ews_connection_enable_notifications_sync (bbews->priv->cnc,
folders, &bbews->priv->subscription_key);
g_slist_free (folders);
}
e_book_backend_set_writable (E_BOOK_BACKEND (bbews), !bbews->priv->is_gal);
success = TRUE;
} else {
ebb_ews_convert_error_to_edb_error (error);
g_clear_object (&bbews->priv->cnc);
}
g_rec_mutex_unlock (&bbews->priv->cnc_lock);
g_free (hosturl);
return success;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-295'], 'message': 'I#27 - SSL Certificates are not validated
This depends on https://gitlab.gnome.org/GNOME/evolution-data-server/commit/6672b8236139bd6ef41ecb915f4c72e2a052dba5 too.
Closes https://gitlab.gnome.org/GNOME/evolution-ews/issues/27'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ews_backend_create_resource_sync (ECollectionBackend *backend,
ESource *source,
GCancellable *cancellable,
GError **error)
{
EEwsConnection *connection = NULL;
EwsFolderId *out_folder_id = NULL;
EEwsFolderType folder_type = E_EWS_FOLDER_TYPE_UNKNOWN;
const gchar *extension_name;
const gchar *parent_folder_id = NULL;
gchar *folder_name;
gboolean success = FALSE;
extension_name = E_SOURCE_EXTENSION_EWS_FOLDER;
if (e_source_has_extension (source, extension_name)) {
ESourceEwsFolder *extension;
/* foreign and public folders are just added */
extension = e_source_get_extension (source, extension_name);
if (e_source_ews_folder_get_foreign (extension) ||
e_source_ews_folder_get_public (extension))
success = TRUE;
}
if (!success) {
connection = e_ews_backend_ref_connection_sync (E_EWS_BACKEND (backend), NULL, cancellable, error);
if (connection == NULL)
return FALSE;
extension_name = E_SOURCE_EXTENSION_ADDRESS_BOOK;
if (e_source_has_extension (source, extension_name)) {
folder_type = E_EWS_FOLDER_TYPE_CONTACTS;
parent_folder_id = "contacts";
}
extension_name = E_SOURCE_EXTENSION_CALENDAR;
if (e_source_has_extension (source, extension_name)) {
folder_type = E_EWS_FOLDER_TYPE_CALENDAR;
parent_folder_id = "calendar";
}
extension_name = E_SOURCE_EXTENSION_TASK_LIST;
if (e_source_has_extension (source, extension_name)) {
folder_type = E_EWS_FOLDER_TYPE_TASKS;
parent_folder_id = "tasks";
}
/* FIXME No support for memo lists. */
if (parent_folder_id == NULL) {
g_set_error (
error, G_IO_ERROR,
G_IO_ERROR_INVALID_ARGUMENT,
_("Could not determine a suitable folder "
"class for a new folder named “%s”"),
e_source_get_display_name (source));
goto exit;
}
folder_name = e_source_dup_display_name (source);
success = e_ews_connection_create_folder_sync (
connection, EWS_PRIORITY_MEDIUM,
parent_folder_id, TRUE,
folder_name, folder_type,
&out_folder_id, cancellable, error);
g_free (folder_name);
/* Sanity check */
g_warn_if_fail (
(success && out_folder_id != NULL) ||
(!success && out_folder_id == NULL));
if (out_folder_id != NULL) {
ESourceEwsFolder *extension;
const gchar *extension_name;
extension_name = E_SOURCE_EXTENSION_EWS_FOLDER;
extension = e_source_get_extension (source, extension_name);
e_source_ews_folder_set_id (
extension, out_folder_id->id);
e_source_ews_folder_set_change_key (
extension, out_folder_id->change_key);
e_ews_folder_id_free (out_folder_id);
}
}
if (success) {
ESourceRegistryServer *server;
ESource *parent_source;
const gchar *cache_dir;
const gchar *parent_uid;
/* Configure the source as a collection member. */
parent_source = e_backend_get_source (E_BACKEND (backend));
parent_uid = e_source_get_uid (parent_source);
e_source_set_parent (source, parent_uid);
/* Changes should be written back to the cache directory. */
cache_dir = e_collection_backend_get_cache_dir (backend);
e_server_side_source_set_write_directory (
E_SERVER_SIDE_SOURCE (source), cache_dir);
/* Set permissions for clients. */
e_server_side_source_set_writable (E_SERVER_SIDE_SOURCE (source), TRUE);
e_server_side_source_set_remote_deletable (E_SERVER_SIDE_SOURCE (source), TRUE);
server = e_collection_backend_ref_server (backend);
e_source_registry_server_add_source (server, source);
g_object_unref (server);
}
exit:
if (connection)
g_object_unref (connection);
return success;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-295'], 'message': 'I#27 - SSL Certificates are not validated
This depends on https://gitlab.gnome.org/GNOME/evolution-data-server/commit/6672b8236139bd6ef41ecb915f4c72e2a052dba5 too.
Closes https://gitlab.gnome.org/GNOME/evolution-ews/issues/27'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: oal_response_cb (SoupSession *soup_session,
SoupMessage *soup_message,
gpointer user_data)
{
GSimpleAsyncResult *simple;
struct _oal_req_data *data;
const gchar *etag;
xmlDoc *doc;
xmlNode *node;
simple = G_SIMPLE_ASYNC_RESULT (user_data);
data = g_simple_async_result_get_op_res_gpointer (simple);
if (ews_connection_credentials_failed (data->cnc, soup_message, simple)) {
goto exit;
} else if (soup_message->status_code != 200) {
if (soup_message->status_code == SOUP_STATUS_UNAUTHORIZED &&
soup_message->response_headers) {
const gchar *diagnostics;
diagnostics = soup_message_headers_get_list (soup_message->response_headers, "X-MS-DIAGNOSTICS");
if (diagnostics && strstr (diagnostics, "invalid_grant")) {
g_simple_async_result_set_error (
simple,
EWS_CONNECTION_ERROR,
EWS_CONNECTION_ERROR_ACCESSDENIED,
"%s", diagnostics);
goto exit;
} else if (diagnostics && *diagnostics) {
g_simple_async_result_set_error (
simple,
EWS_CONNECTION_ERROR,
EWS_CONNECTION_ERROR_AUTHENTICATION_FAILED,
"%s", diagnostics);
goto exit;
}
}
g_simple_async_result_set_error (
simple, SOUP_HTTP_ERROR,
soup_message->status_code,
"%d %s",
soup_message->status_code,
soup_message->reason_phrase);
goto exit;
}
etag = soup_message_headers_get_one(soup_message->response_headers,
"ETag");
if (etag)
data->etag = g_strdup(etag);
e_ews_debug_dump_raw_soup_response (soup_message);
doc = xmlReadMemory (
soup_message->response_body->data,
soup_message->response_body->length,
"oab.xml", NULL, 0);
if (doc == NULL) {
g_simple_async_result_set_error (
simple, EWS_CONNECTION_ERROR, -1,
"%s", _("Failed to parse oab XML"));
goto exit;
}
node = xmlDocGetRootElement (doc);
if (strcmp ((gchar *) node->name, "OAB") != 0) {
g_simple_async_result_set_error (
simple, EWS_CONNECTION_ERROR, -1,
"%s", _("Failed to find <OAB> element\n"));
goto exit_doc;
}
for (node = node->children; node; node = node->next) {
if (node->type == XML_ELEMENT_NODE && strcmp ((gchar *) node->name, "OAL") == 0) {
if (data->oal_id == NULL) {
EwsOAL *oal = g_new0 (EwsOAL, 1);
oal->id = get_property (node, "id");
oal->dn = get_property (node, "dn");
oal->name = get_property (node, "name");
data->oals = g_slist_prepend (data->oals, oal);
} else {
gchar *id = get_property (node, "id");
if (strcmp (id, data->oal_id) == 0) {
/* parse details of full_details file */
data->elements = parse_oal_full_details (node, data->oal_element);
g_free (id);
break;
}
g_free (id);
}
}
}
data->oals = g_slist_reverse (data->oals);
exit_doc:
xmlFreeDoc (doc);
exit:
g_simple_async_result_complete_in_idle (simple);
/* This is run in cnc->priv->soup_thread, and the cnc is held by simple, thus
* for cases when the complete_in_idle is finished before the unref call, when
* the cnc will be left with the last reference and thus cannot join the soup_thread
* while still in it, the unref is done in a dedicated thread. */
e_ews_connection_utils_unref_in_thread (simple);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-295'], 'message': 'I#27 - SSL Certificates are not validated
This depends on https://gitlab.gnome.org/GNOME/evolution-data-server/commit/6672b8236139bd6ef41ecb915f4c72e2a052dba5 too.
Closes https://gitlab.gnome.org/GNOME/evolution-ews/issues/27'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: e_ews_connection_get_oal_list (EEwsConnection *cnc,
GCancellable *cancellable,
GAsyncReadyCallback callback,
gpointer user_data)
{
GSimpleAsyncResult *simple;
SoupMessage *soup_message;
struct _oal_req_data *data;
GError *error = NULL;
g_return_if_fail (E_IS_EWS_CONNECTION (cnc));
soup_message = e_ews_get_msg_for_url (cnc->priv->settings, cnc->priv->uri, NULL, &error);
simple = g_simple_async_result_new (
G_OBJECT (cnc), callback, user_data,
e_ews_connection_get_oal_list);
if (!soup_message) {
g_simple_async_result_take_error (simple, error);
g_simple_async_result_complete_in_idle (simple);
return;
}
data = g_slice_new0 (struct _oal_req_data);
data->cnc = g_object_ref (cnc);
data->soup_message = soup_message; /* the session owns this */
if (G_IS_CANCELLABLE (cancellable)) {
data->cancellable = g_object_ref (cancellable);
data->cancel_id = g_cancellable_connect (
data->cancellable,
G_CALLBACK (ews_cancel_msg),
data, (GDestroyNotify) NULL);
}
g_simple_async_result_set_op_res_gpointer (
simple, data, (GDestroyNotify) oal_req_data_free);
ews_connection_schedule_queue_message (cnc, soup_message, oal_response_cb, simple);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-295'], 'message': 'I#27 - SSL Certificates are not validated
This depends on https://gitlab.gnome.org/GNOME/evolution-data-server/commit/6672b8236139bd6ef41ecb915f4c72e2a052dba5 too.
Closes https://gitlab.gnome.org/GNOME/evolution-ews/issues/27'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: e_ews_autodiscover_ws_url (ESource *source,
CamelEwsSettings *settings,
const gchar *email_address,
const gchar *password,
GCancellable *cancellable,
GAsyncReadyCallback callback,
gpointer user_data)
{
GSimpleAsyncResult *simple;
struct _autodiscover_data *ad;
xmlOutputBuffer *buf;
gchar *url1, *url2, *url3, *url4, *url5;
gchar *domain;
xmlDoc *doc;
EEwsConnection *cnc;
SoupURI *soup_uri = NULL;
gboolean use_secure = TRUE;
const gchar *host_url;
GError *error = NULL;
g_return_if_fail (CAMEL_IS_EWS_SETTINGS (settings));
g_return_if_fail (email_address != NULL);
g_return_if_fail (password != NULL);
simple = g_simple_async_result_new (
G_OBJECT (settings), callback,
user_data, e_ews_autodiscover_ws_url);
domain = strchr (email_address, '@');
if (domain == NULL || *domain == '\0') {
g_simple_async_result_set_error (
simple, EWS_CONNECTION_ERROR, -1,
"%s", _("Email address is missing a domain part"));
g_simple_async_result_complete_in_idle (simple);
g_object_unref (simple);
return;
}
domain++;
doc = e_ews_autodiscover_ws_xml (email_address);
buf = xmlAllocOutputBuffer (NULL);
xmlNodeDumpOutput (buf, doc, xmlDocGetRootElement (doc), 0, 1, NULL);
xmlOutputBufferFlush (buf);
url1 = NULL;
url2 = NULL;
url3 = NULL;
url4 = NULL;
url5 = NULL;
host_url = camel_ews_settings_get_hosturl (settings);
if (host_url != NULL)
soup_uri = soup_uri_new (host_url);
if (soup_uri != NULL) {
const gchar *host = soup_uri_get_host (soup_uri);
const gchar *scheme = soup_uri_get_scheme (soup_uri);
use_secure = g_strcmp0 (scheme, "https") == 0;
url1 = g_strdup_printf ("http%s://%s/autodiscover/autodiscover.xml", use_secure ? "s" : "", host);
url2 = g_strdup_printf ("http%s://autodiscover.%s/autodiscover/autodiscover.xml", use_secure ? "s" : "", host);
/* outlook.office365.com has its autodiscovery at outlook.com */
if (host && g_ascii_strcasecmp (host, "outlook.office365.com") == 0 &&
domain && g_ascii_strcasecmp (host, "outlook.com") != 0) {
url5 = g_strdup_printf ("https://outlook.com/autodiscover/autodiscover.xml");
}
soup_uri_free (soup_uri);
}
url3 = g_strdup_printf ("http%s://%s/autodiscover/autodiscover.xml", use_secure ? "s" : "", domain);
url4 = g_strdup_printf ("http%s://autodiscover.%s/autodiscover/autodiscover.xml", use_secure ? "s" : "", domain);
cnc = e_ews_connection_new (source, url3, settings);
e_ews_connection_set_password (cnc, password);
/*
* http://msdn.microsoft.com/en-us/library/ee332364.aspx says we are
* supposed to try $domain and then autodiscover.$domain. But some
* people have broken firewalls on the former which drop packets
* instead of rejecting connections, and make the request take ages
* to time out. So run both queries in parallel and let the fastest
* (successful) one win.
*/
ad = g_slice_new0 (struct _autodiscover_data);
ad->cnc = cnc; /* takes ownership */
ad->buf = buf; /* takes ownership */
if (G_IS_CANCELLABLE (cancellable)) {
ad->cancellable = g_object_ref (cancellable);
ad->cancel_id = g_cancellable_connect (
ad->cancellable,
G_CALLBACK (autodiscover_cancelled_cb),
g_object_ref (cnc),
g_object_unref);
}
g_simple_async_result_set_op_res_gpointer (
simple, ad, (GDestroyNotify) autodiscover_data_free);
/* Passing a NULL URL string returns NULL. */
ad->msgs[0] = e_ews_get_msg_for_url (settings, url1, buf, &error);
ad->msgs[1] = e_ews_get_msg_for_url (settings, url2, buf, NULL);
ad->msgs[2] = e_ews_get_msg_for_url (settings, url3, buf, NULL);
ad->msgs[3] = e_ews_get_msg_for_url (settings, url4, buf, NULL);
ad->msgs[4] = e_ews_get_msg_for_url (settings, url5, buf, NULL);
/* These have to be submitted only after they're both set in ad->msgs[]
* or there will be races with fast completion */
if (ad->msgs[0] != NULL)
ews_connection_schedule_queue_message (cnc, ad->msgs[0], autodiscover_response_cb, g_object_ref (simple));
if (ad->msgs[1] != NULL)
ews_connection_schedule_queue_message (cnc, ad->msgs[1], autodiscover_response_cb, g_object_ref (simple));
if (ad->msgs[2] != NULL)
ews_connection_schedule_queue_message (cnc, ad->msgs[2], autodiscover_response_cb, g_object_ref (simple));
if (ad->msgs[3] != NULL)
ews_connection_schedule_queue_message (cnc, ad->msgs[3], autodiscover_response_cb, g_object_ref (simple));
if (ad->msgs[4] != NULL)
ews_connection_schedule_queue_message (cnc, ad->msgs[4], autodiscover_response_cb, g_object_ref (simple));
xmlFreeDoc (doc);
g_free (url1);
g_free (url2);
g_free (url3);
g_free (url4);
if (error && !ad->msgs[0] && !ad->msgs[1] && !ad->msgs[2] && !ad->msgs[3] && !ad->msgs[4]) {
g_simple_async_result_take_error (simple, error);
g_simple_async_result_complete_in_idle (simple);
} else {
g_clear_error (&error);
/* each request holds a reference to 'simple',
* thus remove one, to have it actually freed */
g_object_unref (simple);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-295'], 'message': 'I#27 - SSL Certificates are not validated
This depends on https://gitlab.gnome.org/GNOME/evolution-data-server/commit/6672b8236139bd6ef41ecb915f4c72e2a052dba5 too.
Closes https://gitlab.gnome.org/GNOME/evolution-ews/issues/27'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ews_connection_constructed (GObject *object)
{
EEwsConnection *cnc = E_EWS_CONNECTION (object);
gint log_level;
/* Chain up to parent's method. */
G_OBJECT_CLASS (e_ews_connection_parent_class)->constructed (object);
cnc->priv->soup_thread = g_thread_new (NULL, e_ews_soup_thread, cnc);
cnc->priv->soup_session = soup_session_async_new_with_options (
SOUP_SESSION_ASYNC_CONTEXT, cnc->priv->soup_context,
NULL);
/* Do not use G_BINDING_SYNC_CREATE because the property_lock is
* not initialized and we don't have a GProxyResolver yet anyway. */
e_binding_bind_property (
cnc, "proxy-resolver",
cnc->priv->soup_session, "proxy-resolver",
G_BINDING_DEFAULT);
cnc->priv->version = E_EWS_EXCHANGE_UNKNOWN;
log_level = e_ews_debug_get_log_level ();
if (log_level >= 2) {
SoupLogger *logger;
logger = soup_logger_new (SOUP_LOGGER_LOG_BODY, -1);
if (log_level >= 3) {
soup_logger_set_printer (logger, e_ews_soup_log_printer, NULL, NULL);
g_log_set_handler (
G_LOG_DOMAIN,
G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING |
G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO,
e_ews_debug_handler, cnc);
}
soup_session_add_feature (
cnc->priv->soup_session,
SOUP_SESSION_FEATURE (logger));
g_object_unref (logger);
}
soup_session_add_feature_by_type (cnc->priv->soup_session,
SOUP_TYPE_COOKIE_JAR);
g_signal_connect (
cnc->priv->soup_session, "authenticate",
G_CALLBACK (ews_connection_authenticate), cnc);
e_ews_connection_utils_prepare_auth_method (cnc->priv->soup_session,
camel_ews_settings_get_auth_mechanism (cnc->priv->settings));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-295'], 'message': 'I#27 - SSL Certificates are not validated
This depends on https://gitlab.gnome.org/GNOME/evolution-data-server/commit/6672b8236139bd6ef41ecb915f4c72e2a052dba5 too.
Closes https://gitlab.gnome.org/GNOME/evolution-ews/issues/27'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: mail_config_ews_autodiscover_sync (ECredentialsPrompter *prompter,
ESource *source,
const ENamedParameters *credentials,
gboolean *out_authenticated,
gpointer user_data,
GCancellable *cancellable,
GError **error)
{
AsyncContext *async_context = user_data;
GError *local_error = NULL;
gboolean res = TRUE;
e_ews_autodiscover_ws_url_sync (source,
async_context->ews_settings, async_context->email_address,
credentials && e_named_parameters_get (credentials, E_SOURCE_CREDENTIAL_PASSWORD) ?
e_named_parameters_get (credentials, E_SOURCE_CREDENTIAL_PASSWORD) : "",
cancellable, &local_error);
if (local_error == NULL) {
*out_authenticated = TRUE;
} else if (g_error_matches (local_error, SOUP_HTTP_ERROR, SOUP_STATUS_UNAUTHORIZED)) {
*out_authenticated = FALSE;
g_error_free (local_error);
} else {
res = FALSE;
g_propagate_error (error, local_error);
}
return res;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-295'], 'message': 'I#27 - SSL Certificates are not validated
This depends on https://gitlab.gnome.org/GNOME/evolution-data-server/commit/6672b8236139bd6ef41ecb915f4c72e2a052dba5 too.
Closes https://gitlab.gnome.org/GNOME/evolution-ews/issues/27'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: mail_config_ews_autodiscover_run_cb (GObject *source_object,
GAsyncResult *result,
gpointer user_data)
{
AsyncContext *async_context = user_data;
EMailConfigEwsAutodiscover *autodiscover;
EAlertSink *alert_sink;
GError *error = NULL;
EMailConfigServiceBackend *backend;
CamelSettings *settings;
autodiscover = async_context->autodiscover;
alert_sink = e_activity_get_alert_sink (async_context->activity);
mail_config_ews_autodiscover_finish (E_MAIL_CONFIG_EWS_AUTODISCOVER (source_object), result, &error);
backend = e_mail_config_ews_autodiscover_get_backend (autodiscover);
settings = e_mail_config_service_backend_get_settings (backend);
/*
* And unstop since we are back to the main thread.
*/
g_object_thaw_notify (G_OBJECT (settings));
if (e_activity_handle_cancellation (async_context->activity, error)) {
g_error_free (error);
} else if (error != NULL) {
e_alert_submit (
alert_sink,
"ews:autodiscovery-error",
error->message, NULL);
g_error_free (error);
}
gtk_widget_set_sensitive (GTK_WIDGET (autodiscover), TRUE);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-295'], 'message': 'I#27 - SSL Certificates are not validated
This depends on https://gitlab.gnome.org/GNOME/evolution-data-server/commit/6672b8236139bd6ef41ecb915f4c72e2a052dba5 too.
Closes https://gitlab.gnome.org/GNOME/evolution-ews/issues/27'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: oal_download_response_cb (SoupSession *soup_session,
SoupMessage *soup_message,
gpointer user_data)
{
GSimpleAsyncResult *simple;
struct _oal_req_data *data;
simple = G_SIMPLE_ASYNC_RESULT (user_data);
data = g_simple_async_result_get_op_res_gpointer (simple);
if (ews_connection_credentials_failed (data->cnc, soup_message, simple)) {
g_unlink (data->cache_filename);
} else if (soup_message->status_code != 200) {
g_simple_async_result_set_error (
simple, SOUP_HTTP_ERROR,
soup_message->status_code,
"%d %s",
soup_message->status_code,
soup_message->reason_phrase);
g_unlink (data->cache_filename);
} else if (data->error != NULL) {
g_simple_async_result_take_error (simple, data->error);
data->error = NULL;
g_unlink (data->cache_filename);
}
e_ews_debug_dump_raw_soup_response (soup_message);
g_simple_async_result_complete_in_idle (simple);
e_ews_connection_utils_unref_in_thread (simple);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-295'], 'message': 'I#27 - SSL Certificates are not validated
This depends on https://gitlab.gnome.org/GNOME/evolution-data-server/commit/6672b8236139bd6ef41ecb915f4c72e2a052dba5 too.
Closes https://gitlab.gnome.org/GNOME/evolution-ews/issues/27'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ews_backend_delete_resource_sync (ECollectionBackend *backend,
ESource *source,
GCancellable *cancellable,
GError **error)
{
EEwsConnection *connection;
ESourceEwsFolder *extension;
const gchar *extension_name;
gboolean success = FALSE;
connection = e_ews_backend_ref_connection_sync (E_EWS_BACKEND (backend), NULL, cancellable, error);
if (connection == NULL)
return FALSE;
extension_name = E_SOURCE_EXTENSION_EWS_FOLDER;
if (!e_source_has_extension (source, extension_name)) {
g_set_error (
error, G_IO_ERROR,
G_IO_ERROR_INVALID_ARGUMENT,
_("Data source “%s” does not represent "
"an Exchange Web Services folder"),
e_source_get_display_name (source));
goto exit;
}
extension = e_source_get_extension (source, extension_name);
if (e_source_ews_folder_get_foreign (extension) ||
e_source_ews_folder_get_public (extension)) {
/* do not delete foreign or public folders,
* just remove them from local store */
success = TRUE;
} else {
gchar *folder_id;
folder_id = e_source_ews_folder_dup_id (extension);
success = e_ews_connection_delete_folder_sync (
connection, EWS_PRIORITY_MEDIUM, folder_id,
FALSE, "HardDelete", cancellable, error);
g_free (folder_id);
}
if (success)
success = e_source_remove_sync (source, cancellable, error);
exit:
g_object_unref (connection);
return success;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-295'], 'message': 'I#27 - SSL Certificates are not validated
This depends on https://gitlab.gnome.org/GNOME/evolution-data-server/commit/6672b8236139bd6ef41ecb915f4c72e2a052dba5 too.
Closes https://gitlab.gnome.org/GNOME/evolution-ews/issues/27'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: _gnutls13_recv_async_handshake(gnutls_session_t session)
{
int ret;
handshake_buffer_st hsk;
recv_state_t next_state = RECV_STATE_0;
/* The following messages are expected asynchronously after
* the handshake process is complete */
if (unlikely(session->internals.handshake_in_progress))
return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET);
do {
/* the received handshake message has already been pushed into
* handshake buffers. As we do not need to use the handshake hash
* buffers we call the lower level receive functions */
ret = _gnutls_handshake_io_recv_int(session, GNUTLS_HANDSHAKE_ANY, &hsk, 0);
if (ret < 0) {
gnutls_assert();
goto cleanup;
}
session->internals.last_handshake_in = hsk.htype;
ret = _gnutls_call_hook_func(session, hsk.htype, GNUTLS_HOOK_PRE, 1,
hsk.data.data, hsk.data.length);
if (ret < 0) {
gnutls_assert();
goto cleanup;
}
switch(hsk.htype) {
case GNUTLS_HANDSHAKE_CERTIFICATE_REQUEST:
if (!(session->security_parameters.entity == GNUTLS_CLIENT) ||
!(session->internals.flags & GNUTLS_POST_HANDSHAKE_AUTH)) {
ret = gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET);
goto cleanup;
}
_gnutls_buffer_reset(&session->internals.reauth_buffer);
/* include the handshake headers in reauth buffer */
ret = _gnutls_buffer_append_data(&session->internals.reauth_buffer,
hsk.header, hsk.header_size);
if (ret < 0) {
gnutls_assert();
goto cleanup;
}
ret = _gnutls_buffer_append_data(&session->internals.reauth_buffer,
hsk.data.data, hsk.data.length);
if (ret < 0) {
gnutls_assert();
goto cleanup;
}
if (session->internals.flags & GNUTLS_AUTO_REAUTH) {
ret = gnutls_reauth(session, 0);
if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED) {
next_state = RECV_STATE_REAUTH;
} else if (ret < 0) {
gnutls_assert();
goto cleanup;
}
} else {
/* Application is expected to handle re-authentication
* explicitly. */
ret = GNUTLS_E_REAUTH_REQUEST;
}
goto cleanup;
case GNUTLS_HANDSHAKE_KEY_UPDATE:
ret = _gnutls13_recv_key_update(session, &hsk.data);
if (ret < 0) {
gnutls_assert();
goto cleanup;
}
/* Handshake messages MUST NOT span key changes, i.e., we
* should not have any other pending handshake messages from
* the same record. */
if (session->internals.handshake_recv_buffer_size != 0) {
ret = gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET);
goto cleanup;
}
break;
case GNUTLS_HANDSHAKE_NEW_SESSION_TICKET:
if (session->security_parameters.entity != GNUTLS_CLIENT) {
ret = gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET);
goto cleanup;
}
ret = _gnutls13_recv_session_ticket(session, &hsk.data);
if (ret < 0) {
gnutls_assert();
goto cleanup;
}
memcpy(session->internals.tls13_ticket.resumption_master_secret,
session->key.proto.tls13.ap_rms,
session->key.proto.tls13.temp_secret_size);
session->internals.tls13_ticket.prf = session->security_parameters.prf;
session->internals.hsk_flags |= HSK_TICKET_RECEIVED;
break;
default:
gnutls_assert();
ret = GNUTLS_E_UNEXPECTED_PACKET;
goto cleanup;
}
ret = _gnutls_call_hook_func(session, hsk.htype, GNUTLS_HOOK_POST, 1, hsk.data.data, hsk.data.length);
if (ret < 0) {
gnutls_assert();
goto cleanup;
}
_gnutls_handshake_buffer_clear(&hsk);
} while (_gnutls_record_buffer_get_size(session) > 0);
session->internals.recv_state = next_state;
return 0;
cleanup:
/* if we have pending/partial handshake data in buffers, ensure that
* next read will read handshake data */
if (_gnutls_record_buffer_get_size(session) > 0)
session->internals.recv_state = RECV_STATE_ASYNC_HANDSHAKE;
else
session->internals.recv_state = next_state;
_gnutls_handshake_buffer_clear(&hsk);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-824'], 'message': 'handshake: add missing initialization of local variable
Resolves: #704
Signed-off-by: Daiki Ueno <[email protected]>
Signed-off-by: Nikos Mavrogiannopoulos <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int af_alg_release(struct socket *sock)
{
if (sock->sk)
sock_put(sock->sk);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'net: crypto set sk to NULL when af_alg_release.
KASAN has found use-after-free in sockfs_setattr.
The existed commit 6d8c50dcb029 ("socket: close race condition between sock_close()
and sockfs_setattr()") is to fix this simillar issue, but it seems to ignore
that crypto module forgets to set the sk to NULL after af_alg_release.
KASAN report details as below:
BUG: KASAN: use-after-free in sockfs_setattr+0x120/0x150
Write of size 4 at addr ffff88837b956128 by task syz-executor0/4186
CPU: 2 PID: 4186 Comm: syz-executor0 Not tainted xxx + #1
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS
1.10.2-1ubuntu1 04/01/2014
Call Trace:
dump_stack+0xca/0x13e
print_address_description+0x79/0x330
? vprintk_func+0x5e/0xf0
kasan_report+0x18a/0x2e0
? sockfs_setattr+0x120/0x150
sockfs_setattr+0x120/0x150
? sock_register+0x2d0/0x2d0
notify_change+0x90c/0xd40
? chown_common+0x2ef/0x510
chown_common+0x2ef/0x510
? chmod_common+0x3b0/0x3b0
? __lock_is_held+0xbc/0x160
? __sb_start_write+0x13d/0x2b0
? __mnt_want_write+0x19a/0x250
do_fchownat+0x15c/0x190
? __ia32_sys_chmod+0x80/0x80
? trace_hardirqs_on_thunk+0x1a/0x1c
__x64_sys_fchownat+0xbf/0x160
? lockdep_hardirqs_on+0x39a/0x5e0
do_syscall_64+0xc8/0x580
entry_SYSCALL_64_after_hwframe+0x49/0xbe
RIP: 0033:0x462589
Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89
f7 48 89 d6 48 89
ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3
48 c7 c1 bc ff ff
ff f7 d8 64 89 01 48
RSP: 002b:00007fb4b2c83c58 EFLAGS: 00000246 ORIG_RAX: 0000000000000104
RAX: ffffffffffffffda RBX: 000000000072bfa0 RCX: 0000000000462589
RDX: 0000000000000000 RSI: 00000000200000c0 RDI: 0000000000000007
RBP: 0000000000000005 R08: 0000000000001000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 00007fb4b2c846bc
R13: 00000000004bc733 R14: 00000000006f5138 R15: 00000000ffffffff
Allocated by task 4185:
kasan_kmalloc+0xa0/0xd0
__kmalloc+0x14a/0x350
sk_prot_alloc+0xf6/0x290
sk_alloc+0x3d/0xc00
af_alg_accept+0x9e/0x670
hash_accept+0x4a3/0x650
__sys_accept4+0x306/0x5c0
__x64_sys_accept4+0x98/0x100
do_syscall_64+0xc8/0x580
entry_SYSCALL_64_after_hwframe+0x49/0xbe
Freed by task 4184:
__kasan_slab_free+0x12e/0x180
kfree+0xeb/0x2f0
__sk_destruct+0x4e6/0x6a0
sk_destruct+0x48/0x70
__sk_free+0xa9/0x270
sk_free+0x2a/0x30
af_alg_release+0x5c/0x70
__sock_release+0xd3/0x280
sock_close+0x1a/0x20
__fput+0x27f/0x7f0
task_work_run+0x136/0x1b0
exit_to_usermode_loop+0x1a7/0x1d0
do_syscall_64+0x461/0x580
entry_SYSCALL_64_after_hwframe+0x49/0xbe
Syzkaller reproducer:
r0 = perf_event_open(&(0x7f0000000000)={0x0, 0x70, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, @perf_config_ext}, 0x0, 0x0,
0xffffffffffffffff, 0x0)
r1 = socket$alg(0x26, 0x5, 0x0)
getrusage(0x0, 0x0)
bind(r1, &(0x7f00000001c0)=@alg={0x26, 'hash\x00', 0x0, 0x0,
'sha256-ssse3\x00'}, 0x80)
r2 = accept(r1, 0x0, 0x0)
r3 = accept4$unix(r2, 0x0, 0x0, 0x0)
r4 = dup3(r3, r0, 0x0)
fchownat(r4, &(0x7f00000000c0)='\x00', 0x0, 0x0, 0x1000)
Fixes: 6d8c50dcb029 ("socket: close race condition between sock_close() and sockfs_setattr()")
Signed-off-by: Mao Wenan <[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: file_printable(char *buf, size_t bufsiz, const char *str)
{
char *ptr, *eptr;
const unsigned char *s = (const unsigned char *)str;
for (ptr = buf, eptr = ptr + bufsiz - 1; ptr < eptr && *s; s++) {
if (isprint(*s)) {
*ptr++ = *s;
continue;
}
if (ptr >= eptr - 3)
break;
*ptr++ = '\\';
*ptr++ = ((CAST(unsigned int, *s) >> 6) & 7) + '0';
*ptr++ = ((CAST(unsigned int, *s) >> 3) & 7) + '0';
*ptr++ = ((CAST(unsigned int, *s) >> 0) & 7) + '0';
}
*ptr = '\0';
return buf;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'PR/62: spinpx: limit size of file_printable.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: mprint(struct magic_set *ms, struct magic *m)
{
uint64_t v;
float vf;
double vd;
int64_t t = 0;
char buf[128], tbuf[26], sbuf[512], ebuf[512];
const char *desc;
union VALUETYPE *p = &ms->ms_value;
if (varexpand(ms, ebuf, sizeof(ebuf), m->desc) == -1)
desc = m->desc;
else
desc = ebuf;
switch (m->type) {
case FILE_BYTE:
v = file_signextend(ms, m, (uint64_t)p->b);
switch (check_fmt(ms, desc)) {
case -1:
return -1;
case 1:
(void)snprintf(buf, sizeof(buf), "%d",
(unsigned char)v);
if (file_printf(ms, F(ms, desc, "%s"), buf) == -1)
return -1;
break;
default:
if (file_printf(ms, F(ms, desc, "%d"),
(unsigned char) v) == -1)
return -1;
break;
}
t = ms->offset + sizeof(char);
break;
case FILE_SHORT:
case FILE_BESHORT:
case FILE_LESHORT:
v = file_signextend(ms, m, (uint64_t)p->h);
switch (check_fmt(ms, desc)) {
case -1:
return -1;
case 1:
(void)snprintf(buf, sizeof(buf), "%u",
(unsigned short)v);
if (file_printf(ms, F(ms, desc, "%s"), buf) == -1)
return -1;
break;
default:
if (file_printf(ms, F(ms, desc, "%u"),
(unsigned short) v) == -1)
return -1;
break;
}
t = ms->offset + sizeof(short);
break;
case FILE_LONG:
case FILE_BELONG:
case FILE_LELONG:
case FILE_MELONG:
v = file_signextend(ms, m, (uint64_t)p->l);
switch (check_fmt(ms, desc)) {
case -1:
return -1;
case 1:
(void)snprintf(buf, sizeof(buf), "%u", (uint32_t) v);
if (file_printf(ms, F(ms, desc, "%s"), buf) == -1)
return -1;
break;
default:
if (file_printf(ms, F(ms, desc, "%u"), (uint32_t) v) == -1)
return -1;
break;
}
t = ms->offset + sizeof(int32_t);
break;
case FILE_QUAD:
case FILE_BEQUAD:
case FILE_LEQUAD:
v = file_signextend(ms, m, p->q);
switch (check_fmt(ms, desc)) {
case -1:
return -1;
case 1:
(void)snprintf(buf, sizeof(buf), "%" INT64_T_FORMAT "u",
(unsigned long long)v);
if (file_printf(ms, F(ms, desc, "%s"), buf) == -1)
return -1;
break;
default:
if (file_printf(ms, F(ms, desc, "%" INT64_T_FORMAT "u"),
(unsigned long long) v) == -1)
return -1;
break;
}
t = ms->offset + sizeof(int64_t);
break;
case FILE_STRING:
case FILE_PSTRING:
case FILE_BESTRING16:
case FILE_LESTRING16:
if (m->reln == '=' || m->reln == '!') {
if (file_printf(ms, F(ms, desc, "%s"),
file_printable(sbuf, sizeof(sbuf), m->value.s))
== -1)
return -1;
t = ms->offset + m->vallen;
}
else {
char *str = p->s;
/* compute t before we mangle the string? */
t = ms->offset + strlen(str);
if (*m->value.s == '\0')
str[strcspn(str, "\r\n")] = '\0';
if (m->str_flags & STRING_TRIM) {
char *last;
while (isspace((unsigned char)*str))
str++;
last = str;
while (*last)
last++;
--last;
while (isspace((unsigned char)*last))
last--;
*++last = '\0';
}
if (file_printf(ms, F(ms, desc, "%s"),
file_printable(sbuf, sizeof(sbuf), str)) == -1)
return -1;
if (m->type == FILE_PSTRING)
t += file_pstring_length_size(m);
}
break;
case FILE_DATE:
case FILE_BEDATE:
case FILE_LEDATE:
case FILE_MEDATE:
if (file_printf(ms, F(ms, desc, "%s"),
file_fmttime(p->l, 0, tbuf)) == -1)
return -1;
t = ms->offset + sizeof(uint32_t);
break;
case FILE_LDATE:
case FILE_BELDATE:
case FILE_LELDATE:
case FILE_MELDATE:
if (file_printf(ms, F(ms, desc, "%s"),
file_fmttime(p->l, FILE_T_LOCAL, tbuf)) == -1)
return -1;
t = ms->offset + sizeof(uint32_t);
break;
case FILE_QDATE:
case FILE_BEQDATE:
case FILE_LEQDATE:
if (file_printf(ms, F(ms, desc, "%s"),
file_fmttime(p->q, 0, tbuf)) == -1)
return -1;
t = ms->offset + sizeof(uint64_t);
break;
case FILE_QLDATE:
case FILE_BEQLDATE:
case FILE_LEQLDATE:
if (file_printf(ms, F(ms, desc, "%s"),
file_fmttime(p->q, FILE_T_LOCAL, tbuf)) == -1)
return -1;
t = ms->offset + sizeof(uint64_t);
break;
case FILE_QWDATE:
case FILE_BEQWDATE:
case FILE_LEQWDATE:
if (file_printf(ms, F(ms, desc, "%s"),
file_fmttime(p->q, FILE_T_WINDOWS, tbuf)) == -1)
return -1;
t = ms->offset + sizeof(uint64_t);
break;
case FILE_FLOAT:
case FILE_BEFLOAT:
case FILE_LEFLOAT:
vf = p->f;
switch (check_fmt(ms, desc)) {
case -1:
return -1;
case 1:
(void)snprintf(buf, sizeof(buf), "%g", vf);
if (file_printf(ms, F(ms, desc, "%s"), buf) == -1)
return -1;
break;
default:
if (file_printf(ms, F(ms, desc, "%g"), vf) == -1)
return -1;
break;
}
t = ms->offset + sizeof(float);
break;
case FILE_DOUBLE:
case FILE_BEDOUBLE:
case FILE_LEDOUBLE:
vd = p->d;
switch (check_fmt(ms, desc)) {
case -1:
return -1;
case 1:
(void)snprintf(buf, sizeof(buf), "%g", vd);
if (file_printf(ms, F(ms, desc, "%s"), buf) == -1)
return -1;
break;
default:
if (file_printf(ms, F(ms, desc, "%g"), vd) == -1)
return -1;
break;
}
t = ms->offset + sizeof(double);
break;
case FILE_SEARCH:
case FILE_REGEX: {
char *cp;
int rval;
cp = strndup((const char *)ms->search.s, ms->search.rm_len);
if (cp == NULL) {
file_oomem(ms, ms->search.rm_len);
return -1;
}
rval = file_printf(ms, F(ms, desc, "%s"),
file_printable(sbuf, sizeof(sbuf), cp));
free(cp);
if (rval == -1)
return -1;
if ((m->str_flags & REGEX_OFFSET_START))
t = ms->search.offset;
else
t = ms->search.offset + ms->search.rm_len;
break;
}
case FILE_DEFAULT:
case FILE_CLEAR:
if (file_printf(ms, "%s", m->desc) == -1)
return -1;
t = ms->offset;
break;
case FILE_INDIRECT:
case FILE_USE:
case FILE_NAME:
t = ms->offset;
break;
case FILE_DER:
if (file_printf(ms, F(ms, desc, "%s"),
file_printable(sbuf, sizeof(sbuf), ms->ms_value.s)) == -1)
return -1;
t = ms->offset;
break;
default:
file_magerror(ms, "invalid m->type (%d) in mprint()", m->type);
return -1;
}
return (int32_t)t;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'PR/62: spinpx: limit size of file_printable.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: do_bid_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
int swap __attribute__((__unused__)), uint32_t namesz, uint32_t descsz,
size_t noff, size_t doff, int *flags)
{
if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 &&
type == NT_GNU_BUILD_ID && (descsz >= 4 && descsz <= 20)) {
uint8_t desc[20];
const char *btype;
uint32_t i;
*flags |= FLAGS_DID_BUILD_ID;
switch (descsz) {
case 8:
btype = "xxHash";
break;
case 16:
btype = "md5/uuid";
break;
case 20:
btype = "sha1";
break;
default:
btype = "unknown";
break;
}
if (file_printf(ms, ", BuildID[%s]=", btype) == -1)
return 1;
memcpy(desc, &nbuf[doff], descsz);
for (i = 0; i < descsz; i++)
if (file_printf(ms, "%02x", desc[i]) == -1)
return 1;
return 1;
}
if (namesz == 4 && strcmp((char *)&nbuf[noff], "Go") == 0 &&
type == NT_GO_BUILD_ID && descsz < 128) {
if (file_printf(ms, ", Go BuildID=%s",
(char *)&nbuf[doff]) == -1)
return -1;
return 1;
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'PR/62: spinpx: Avoid non-nul-terminated string read.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: compute_tag(dns_name_t *name, dns_rdata_dnskey_t *dnskey, isc_mem_t *mctx,
dns_keytag_t *tag)
{
isc_result_t result;
dns_rdata_t rdata = DNS_RDATA_INIT;
unsigned char data[4096];
isc_buffer_t buffer;
dst_key_t *dstkey = NULL;
isc_buffer_init(&buffer, data, sizeof(data));
dns_rdata_fromstruct(&rdata, dnskey->common.rdclass,
dns_rdatatype_dnskey, dnskey, &buffer);
result = dns_dnssec_keyfromrdata(name, &rdata, mctx, &dstkey);
if (result == ISC_R_SUCCESS)
*tag = dst_key_id(dstkey);
dst_key_free(&dstkey);
return (result);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-327'], 'message': 'Don't free key in compute_tag in case of failure
If `dns_dnssec_keyfromrdata` failed we don't need to call
`dst_key_free` because no `dstkey` was created. Doing so
nevertheless will result in an assertion failure.
This can happen if the key uses an unsupported algorithm.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: dlz_allowzonexfr(void *dbdata, const char *name, const char *client) {
UNUSED(client);
/* Just say yes for all our zones */
return (dlz_findzonedb(dbdata, name, NULL, NULL));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-732'], 'message': 'denied axfr requests were not effective for writable DLZ zones
(cherry picked from commit d9077cd0038e59726e1956de18b4b7872038a283)'</s> |
<s>[INST] Given the following code containing errors, provide 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 snmp_version(void *context, size_t hdrlen, unsigned char tag,
const void *data, size_t datalen)
{
if (*(unsigned char *)data > 1)
return -ENOTSUPP;
return 1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-401', 'CWE-129', 'CWE-787'], 'message': 'netfilter: nf_nat_snmp_basic: add missing length checks in ASN.1 cbs
The generic ASN.1 decoder infrastructure doesn't guarantee that callbacks
will get as much data as they expect; callbacks have to check the `datalen`
parameter before looking at `data`. Make sure that snmp_version() and
snmp_helper() don't read/write beyond the end of the packet data.
(Also move the assignment to `pdata` down below the check to make it clear
that it isn't necessarily a pointer we can use before the `datalen` check.)
Fixes: cc2d58634e0f ("netfilter: nf_nat_snmp_basic: use asn1 decoder library")
Signed-off-by: Jann Horn <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int kernel_read_file(struct file *file, void **buf, loff_t *size,
loff_t max_size, enum kernel_read_file_id id)
{
loff_t i_size, pos;
ssize_t bytes = 0;
int ret;
if (!S_ISREG(file_inode(file)->i_mode) || max_size < 0)
return -EINVAL;
ret = deny_write_access(file);
if (ret)
return ret;
ret = security_kernel_read_file(file, id);
if (ret)
goto out;
i_size = i_size_read(file_inode(file));
if (i_size <= 0) {
ret = -EINVAL;
goto out;
}
if (i_size > SIZE_MAX || (max_size > 0 && i_size > max_size)) {
ret = -EFBIG;
goto out;
}
if (id != READING_FIRMWARE_PREALLOC_BUFFER)
*buf = vmalloc(i_size);
if (!*buf) {
ret = -ENOMEM;
goto out;
}
pos = 0;
while (pos < i_size) {
bytes = kernel_read(file, *buf + pos, i_size - pos, &pos);
if (bytes < 0) {
ret = bytes;
goto out;
}
if (bytes == 0)
break;
}
if (pos != i_size) {
ret = -EIO;
goto out_free;
}
ret = security_kernel_post_read_file(file, *buf, i_size, id);
if (!ret)
*size = pos;
out_free:
if (ret < 0) {
if (id != READING_FIRMWARE_PREALLOC_BUFFER) {
vfree(*buf);
*buf = NULL;
}
}
out:
allow_write_access(file);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-401'], 'message': 'exec: Fix mem leak in kernel_read_file
syzkaller report this:
BUG: memory leak
unreferenced object 0xffffc9000488d000 (size 9195520):
comm "syz-executor.0", pid 2752, jiffies 4294787496 (age 18.757s)
hex dump (first 32 bytes):
ff ff ff ff ff ff ff ff a8 00 00 00 01 00 00 00 ................
02 00 00 00 00 00 00 00 80 a1 7a c1 ff ff ff ff ..........z.....
backtrace:
[<000000000863775c>] __vmalloc_node mm/vmalloc.c:1795 [inline]
[<000000000863775c>] __vmalloc_node_flags mm/vmalloc.c:1809 [inline]
[<000000000863775c>] vmalloc+0x8c/0xb0 mm/vmalloc.c:1831
[<000000003f668111>] kernel_read_file+0x58f/0x7d0 fs/exec.c:924
[<000000002385813f>] kernel_read_file_from_fd+0x49/0x80 fs/exec.c:993
[<0000000011953ff1>] __do_sys_finit_module+0x13b/0x2a0 kernel/module.c:3895
[<000000006f58491f>] do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290
[<00000000ee78baf4>] entry_SYSCALL_64_after_hwframe+0x49/0xbe
[<00000000241f889b>] 0xffffffffffffffff
It should goto 'out_free' lable to free allocated buf while kernel_read
fails.
Fixes: 39d637af5aa7 ("vfs: forbid write access when reading a file into memory")
Signed-off-by: YueHaibing <[email protected]>
Signed-off-by: Al Viro <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void update_blocked_averages(int cpu)
{
struct rq *rq = cpu_rq(cpu);
struct cfs_rq *cfs_rq, *pos;
const struct sched_class *curr_class;
struct rq_flags rf;
bool done = true;
rq_lock_irqsave(rq, &rf);
update_rq_clock(rq);
/*
* Iterates the task_group tree in a bottom up fashion, see
* list_add_leaf_cfs_rq() for details.
*/
for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) {
struct sched_entity *se;
/* throttled entities do not contribute to load */
if (throttled_hierarchy(cfs_rq))
continue;
if (update_cfs_rq_load_avg(cfs_rq_clock_task(cfs_rq), cfs_rq))
update_tg_load_avg(cfs_rq, 0);
/* Propagate pending load changes to the parent, if any: */
se = cfs_rq->tg->se[cpu];
if (se && !skip_blocked_update(se))
update_load_avg(cfs_rq_of(se), se, 0);
/*
* There can be a lot of idle CPU cgroups. Don't let fully
* decayed cfs_rqs linger on the list.
*/
if (cfs_rq_is_decayed(cfs_rq))
list_del_leaf_cfs_rq(cfs_rq);
/* Don't need periodic decay once load/util_avg are null */
if (cfs_rq_has_blocked(cfs_rq))
done = false;
}
curr_class = rq->curr->sched_class;
update_rt_rq_load_avg(rq_clock_task(rq), rq, curr_class == &rt_sched_class);
update_dl_rq_load_avg(rq_clock_task(rq), rq, curr_class == &dl_sched_class);
update_irq_load_avg(rq, 0);
/* Don't need periodic decay once load/util_avg are null */
if (others_have_blocked(rq))
done = false;
#ifdef CONFIG_NO_HZ_COMMON
rq->last_blocked_load_update_tick = jiffies;
if (done)
rq->has_blocked_load = 0;
#endif
rq_unlock_irqrestore(rq, &rf);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-703', 'CWE-835'], 'message': 'sched/fair: Fix infinite loop in update_blocked_averages() by reverting a9e7f6544b9c
Zhipeng Xie, Xie XiuQi and Sargun Dhillon reported lockups in the
scheduler under high loads, starting at around the v4.18 time frame,
and Zhipeng Xie tracked it down to bugs in the rq->leaf_cfs_rq_list
manipulation.
Do a (manual) revert of:
a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path")
It turns out that the list_del_leaf_cfs_rq() introduced by this commit
is a surprising property that was not considered in followup commits
such as:
9c2791f936ef ("sched/fair: Fix hierarchical order in rq->leaf_cfs_rq_list")
As Vincent Guittot explains:
"I think that there is a bigger problem with commit a9e7f6544b9c and
cfs_rq throttling:
Let take the example of the following topology TG2 --> TG1 --> root:
1) The 1st time a task is enqueued, we will add TG2 cfs_rq then TG1
cfs_rq to leaf_cfs_rq_list and we are sure to do the whole branch in
one path because it has never been used and can't be throttled so
tmp_alone_branch will point to leaf_cfs_rq_list at the end.
2) Then TG1 is throttled
3) and we add TG3 as a new child of TG1.
4) The 1st enqueue of a task on TG3 will add TG3 cfs_rq just before TG1
cfs_rq and tmp_alone_branch will stay on rq->leaf_cfs_rq_list.
With commit a9e7f6544b9c, we can del a cfs_rq from rq->leaf_cfs_rq_list.
So if the load of TG1 cfs_rq becomes NULL before step 2) above, TG1
cfs_rq is removed from the list.
Then at step 4), TG3 cfs_rq is added at the beginning of rq->leaf_cfs_rq_list
but tmp_alone_branch still points to TG3 cfs_rq because its throttled
parent can't be enqueued when the lock is released.
tmp_alone_branch doesn't point to rq->leaf_cfs_rq_list whereas it should.
So if TG3 cfs_rq is removed or destroyed before tmp_alone_branch
points on another TG cfs_rq, the next TG cfs_rq that will be added,
will be linked outside rq->leaf_cfs_rq_list - which is bad.
In addition, we can break the ordering of the cfs_rq in
rq->leaf_cfs_rq_list but this ordering is used to update and
propagate the update from leaf down to root."
Instead of trying to work through all these cases and trying to reproduce
the very high loads that produced the lockup to begin with, simplify
the code temporarily by reverting a9e7f6544b9c - which change was clearly
not thought through completely.
This (hopefully) gives us a kernel that doesn't lock up so people
can continue to enjoy their holidays without worrying about regressions. ;-)
[ mingo: Wrote changelog, fixed weird spelling in code comment while at it. ]
Analyzed-by: Xie XiuQi <[email protected]>
Analyzed-by: Vincent Guittot <[email protected]>
Reported-by: Zhipeng Xie <[email protected]>
Reported-by: Sargun Dhillon <[email protected]>
Reported-by: Xie XiuQi <[email protected]>
Tested-by: Zhipeng Xie <[email protected]>
Tested-by: Sargun Dhillon <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Acked-by: Vincent Guittot <[email protected]>
Cc: <[email protected]> # v4.13+
Cc: Bin Li <[email protected]>
Cc: Mike Galbraith <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Tejun Heo <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Fixes: a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path")
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
{
if (cfs_rq->load.weight)
return false;
if (cfs_rq->avg.load_sum)
return false;
if (cfs_rq->avg.util_sum)
return false;
if (cfs_rq->avg.runnable_load_sum)
return false;
return true;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-703', 'CWE-835'], 'message': 'sched/fair: Fix infinite loop in update_blocked_averages() by reverting a9e7f6544b9c
Zhipeng Xie, Xie XiuQi and Sargun Dhillon reported lockups in the
scheduler under high loads, starting at around the v4.18 time frame,
and Zhipeng Xie tracked it down to bugs in the rq->leaf_cfs_rq_list
manipulation.
Do a (manual) revert of:
a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path")
It turns out that the list_del_leaf_cfs_rq() introduced by this commit
is a surprising property that was not considered in followup commits
such as:
9c2791f936ef ("sched/fair: Fix hierarchical order in rq->leaf_cfs_rq_list")
As Vincent Guittot explains:
"I think that there is a bigger problem with commit a9e7f6544b9c and
cfs_rq throttling:
Let take the example of the following topology TG2 --> TG1 --> root:
1) The 1st time a task is enqueued, we will add TG2 cfs_rq then TG1
cfs_rq to leaf_cfs_rq_list and we are sure to do the whole branch in
one path because it has never been used and can't be throttled so
tmp_alone_branch will point to leaf_cfs_rq_list at the end.
2) Then TG1 is throttled
3) and we add TG3 as a new child of TG1.
4) The 1st enqueue of a task on TG3 will add TG3 cfs_rq just before TG1
cfs_rq and tmp_alone_branch will stay on rq->leaf_cfs_rq_list.
With commit a9e7f6544b9c, we can del a cfs_rq from rq->leaf_cfs_rq_list.
So if the load of TG1 cfs_rq becomes NULL before step 2) above, TG1
cfs_rq is removed from the list.
Then at step 4), TG3 cfs_rq is added at the beginning of rq->leaf_cfs_rq_list
but tmp_alone_branch still points to TG3 cfs_rq because its throttled
parent can't be enqueued when the lock is released.
tmp_alone_branch doesn't point to rq->leaf_cfs_rq_list whereas it should.
So if TG3 cfs_rq is removed or destroyed before tmp_alone_branch
points on another TG cfs_rq, the next TG cfs_rq that will be added,
will be linked outside rq->leaf_cfs_rq_list - which is bad.
In addition, we can break the ordering of the cfs_rq in
rq->leaf_cfs_rq_list but this ordering is used to update and
propagate the update from leaf down to root."
Instead of trying to work through all these cases and trying to reproduce
the very high loads that produced the lockup to begin with, simplify
the code temporarily by reverting a9e7f6544b9c - which change was clearly
not thought through completely.
This (hopefully) gives us a kernel that doesn't lock up so people
can continue to enjoy their holidays without worrying about regressions. ;-)
[ mingo: Wrote changelog, fixed weird spelling in code comment while at it. ]
Analyzed-by: Xie XiuQi <[email protected]>
Analyzed-by: Vincent Guittot <[email protected]>
Reported-by: Zhipeng Xie <[email protected]>
Reported-by: Sargun Dhillon <[email protected]>
Reported-by: Xie XiuQi <[email protected]>
Tested-by: Zhipeng Xie <[email protected]>
Tested-by: Sargun Dhillon <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Acked-by: Vincent Guittot <[email protected]>
Cc: <[email protected]> # v4.13+
Cc: Bin Li <[email protected]>
Cc: Mike Galbraith <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Tejun Heo <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Fixes: a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path")
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: VTermState *vterm_obtain_state(VTerm *vt)
{
VTermState *state;
if(vt->state)
return vt->state;
state = vterm_state_new(vt);
vt->state = state;
state->combine_chars_size = 16;
state->combine_chars = vterm_allocator_malloc(state->vt, state->combine_chars_size * sizeof(state->combine_chars[0]));
state->tabstops = vterm_allocator_malloc(state->vt, (state->cols + 7) / 8);
state->lineinfo = vterm_allocator_malloc(state->vt, state->rows * sizeof(VTermLineInfo));
state->encoding_utf8.enc = vterm_lookup_encoding(ENC_UTF8, 'u');
if(*state->encoding_utf8.enc->init != NULL)
(*state->encoding_utf8.enc->init)(state->encoding_utf8.enc, state->encoding_utf8.data);
vterm_parser_set_callbacks(vt, &parser_callbacks, state);
return state;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'patch 8.1.0633: crash when out of memory while opening a terminal window
Problem: Crash when out of memory while opening a terminal window.
Solution: Handle out-of-memory more gracefully.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: term_and_job_init(
term_T *term,
typval_T *argvar,
char **argv UNUSED,
jobopt_T *opt,
jobopt_T *orig_opt)
{
WCHAR *cmd_wchar = NULL;
WCHAR *cwd_wchar = NULL;
WCHAR *env_wchar = NULL;
channel_T *channel = NULL;
job_T *job = NULL;
DWORD error;
HANDLE jo = NULL;
HANDLE child_process_handle;
HANDLE child_thread_handle;
void *winpty_err = NULL;
void *spawn_config = NULL;
garray_T ga_cmd, ga_env;
char_u *cmd = NULL;
if (dyn_winpty_init(TRUE) == FAIL)
return FAIL;
ga_init2(&ga_cmd, (int)sizeof(char*), 20);
ga_init2(&ga_env, (int)sizeof(char*), 20);
if (argvar->v_type == VAR_STRING)
{
cmd = argvar->vval.v_string;
}
else if (argvar->v_type == VAR_LIST)
{
if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
goto failed;
cmd = ga_cmd.ga_data;
}
if (cmd == NULL || *cmd == NUL)
{
EMSG(_(e_invarg));
goto failed;
}
cmd_wchar = enc_to_utf16(cmd, NULL);
ga_clear(&ga_cmd);
if (cmd_wchar == NULL)
goto failed;
if (opt->jo_cwd != NULL)
cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
win32_build_env(opt->jo_env, &ga_env, TRUE);
env_wchar = ga_env.ga_data;
term->tl_winpty_config = winpty_config_new(0, &winpty_err);
if (term->tl_winpty_config == NULL)
goto failed;
winpty_config_set_mouse_mode(term->tl_winpty_config,
WINPTY_MOUSE_MODE_FORCE);
winpty_config_set_initial_size(term->tl_winpty_config,
term->tl_cols, term->tl_rows);
term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
if (term->tl_winpty == NULL)
goto failed;
spawn_config = winpty_spawn_config_new(
WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
NULL,
cmd_wchar,
cwd_wchar,
env_wchar,
&winpty_err);
if (spawn_config == NULL)
goto failed;
channel = add_channel();
if (channel == NULL)
goto failed;
job = job_alloc();
if (job == NULL)
goto failed;
if (argvar->v_type == VAR_STRING)
{
int argc;
build_argv_from_string(cmd, &job->jv_argv, &argc);
}
else
{
int argc;
build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
}
if (opt->jo_set & JO_IN_BUF)
job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
&child_thread_handle, &error, &winpty_err))
goto failed;
channel_set_pipes(channel,
(sock_T)CreateFileW(
winpty_conin_name(term->tl_winpty),
GENERIC_WRITE, 0, NULL,
OPEN_EXISTING, 0, NULL),
(sock_T)CreateFileW(
winpty_conout_name(term->tl_winpty),
GENERIC_READ, 0, NULL,
OPEN_EXISTING, 0, NULL),
(sock_T)CreateFileW(
winpty_conerr_name(term->tl_winpty),
GENERIC_READ, 0, NULL,
OPEN_EXISTING, 0, NULL));
/* Write lines with CR instead of NL. */
channel->ch_write_text_mode = TRUE;
jo = CreateJobObject(NULL, NULL);
if (jo == NULL)
goto failed;
if (!AssignProcessToJobObject(jo, child_process_handle))
{
/* Failed, switch the way to terminate process with TerminateProcess. */
CloseHandle(jo);
jo = NULL;
}
winpty_spawn_config_free(spawn_config);
vim_free(cmd_wchar);
vim_free(cwd_wchar);
vim_free(env_wchar);
create_vterm(term, term->tl_rows, term->tl_cols);
#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
if (opt->jo_set2 & JO2_ANSI_COLORS)
set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
else
init_vterm_ansi_colors(term->tl_vterm);
#endif
channel_set_job(channel, job, opt);
job_set_options(job, opt);
job->jv_channel = channel;
job->jv_proc_info.hProcess = child_process_handle;
job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
job->jv_job_object = jo;
job->jv_status = JOB_STARTED;
job->jv_tty_in = utf16_to_enc(
(short_u*)winpty_conin_name(term->tl_winpty), NULL);
job->jv_tty_out = utf16_to_enc(
(short_u*)winpty_conout_name(term->tl_winpty), NULL);
++job->jv_refcount;
term->tl_job = job;
/* Redirecting stdout and stderr doesn't work at the job level. Instead
* open the file here and handle it in. opt->jo_io was changed in
* setup_job_options(), use the original flags here. */
if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
{
char_u *fname = opt->jo_io_name[PART_OUT];
ch_log(channel, "Opening output file %s", fname);
term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
if (term->tl_out_fd == NULL)
EMSG2(_(e_notopen), fname);
}
return OK;
failed:
ga_clear(&ga_cmd);
ga_clear(&ga_env);
vim_free(cmd_wchar);
vim_free(cwd_wchar);
if (spawn_config != NULL)
winpty_spawn_config_free(spawn_config);
if (channel != NULL)
channel_clear(channel);
if (job != NULL)
{
job->jv_channel = NULL;
job_cleanup(job);
}
term->tl_job = NULL;
if (jo != NULL)
CloseHandle(jo);
if (term->tl_winpty != NULL)
winpty_free(term->tl_winpty);
term->tl_winpty = NULL;
if (term->tl_winpty_config != NULL)
winpty_config_free(term->tl_winpty_config);
term->tl_winpty_config = NULL;
if (winpty_err != NULL)
{
char_u *msg = utf16_to_enc(
(short_u *)winpty_error_msg(winpty_err), NULL);
EMSG(msg);
winpty_error_free(winpty_err);
}
return FAIL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'patch 8.1.0633: crash when out of memory while opening a terminal window
Problem: Crash when out of memory while opening a terminal window.
Solution: Handle out-of-memory more gracefully.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: term_and_job_init(
term_T *term,
typval_T *argvar,
char **argv,
jobopt_T *opt,
jobopt_T *orig_opt UNUSED)
{
create_vterm(term, term->tl_rows, term->tl_cols);
#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
if (opt->jo_set2 & JO2_ANSI_COLORS)
set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
else
init_vterm_ansi_colors(term->tl_vterm);
#endif
/* This may change a string in "argvar". */
term->tl_job = job_start(argvar, argv, opt, TRUE);
if (term->tl_job != NULL)
++term->tl_job->jv_refcount;
return term->tl_job != NULL
&& term->tl_job->jv_channel != NULL
&& term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'patch 8.1.0633: crash when out of memory while opening a terminal window
Problem: Crash when out of memory while opening a terminal window.
Solution: Handle out-of-memory more gracefully.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: create_pty_only(term_T *term, jobopt_T *opt)
{
create_vterm(term, term->tl_rows, term->tl_cols);
term->tl_job = job_alloc();
if (term->tl_job == NULL)
return FAIL;
++term->tl_job->jv_refcount;
/* behave like the job is already finished */
term->tl_job->jv_status = JOB_FINISHED;
return mch_create_pty_channel(term->tl_job, opt);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'patch 8.1.0633: crash when out of memory while opening a terminal window
Problem: Crash when out of memory while opening a terminal window.
Solution: Handle out-of-memory more gracefully.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: INTERNAL void vterm_screen_free(VTermScreen *screen)
{
vterm_allocator_free(screen->vt, screen->buffers[0]);
if(screen->buffers[1])
vterm_allocator_free(screen->vt, screen->buffers[1]);
vterm_allocator_free(screen->vt, screen->sb_buffer);
vterm_allocator_free(screen->vt, screen);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'patch 8.1.0633: crash when out of memory while opening a terminal window
Problem: Crash when out of memory while opening a terminal window.
Solution: Handle out-of-memory more gracefully.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: create_vterm(term_T *term, int rows, int cols)
{
VTerm *vterm;
VTermScreen *screen;
VTermState *state;
VTermValue value;
vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
term->tl_vterm = vterm;
screen = vterm_obtain_screen(vterm);
vterm_screen_set_callbacks(screen, &screen_callbacks, term);
/* TODO: depends on 'encoding'. */
vterm_set_utf8(vterm, 1);
init_default_colors(term);
vterm_state_set_default_colors(
vterm_obtain_state(vterm),
&term->tl_default_color.fg,
&term->tl_default_color.bg);
if (t_colors >= 16)
vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
/* Required to initialize most things. */
vterm_screen_reset(screen, 1 /* hard */);
/* Allow using alternate screen. */
vterm_screen_enable_altscreen(screen, 1);
/* For unix do not use a blinking cursor. In an xterm this causes the
* cursor to blink if it's blinking in the xterm.
* For Windows we respect the system wide setting. */
#ifdef WIN3264
if (GetCaretBlinkTime() == INFINITE)
value.boolean = 0;
else
value.boolean = 1;
#else
value.boolean = 0;
#endif
state = vterm_obtain_state(vterm);
vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'patch 8.1.0633: crash when out of memory while opening a terminal window
Problem: Crash when out of memory while opening a terminal window.
Solution: Handle out-of-memory more gracefully.'</s> |
<s>[INST] Given the following code containing errors, provide 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 VTermScreen *screen_new(VTerm *vt)
{
VTermState *state = vterm_obtain_state(vt);
VTermScreen *screen;
int rows, cols;
if(!state)
return NULL;
screen = vterm_allocator_malloc(vt, sizeof(VTermScreen));
vterm_get_size(vt, &rows, &cols);
screen->vt = vt;
screen->state = state;
screen->damage_merge = VTERM_DAMAGE_CELL;
screen->damaged.start_row = -1;
screen->pending_scrollrect.start_row = -1;
screen->rows = rows;
screen->cols = cols;
screen->callbacks = NULL;
screen->cbdata = NULL;
screen->buffers[0] = realloc_buffer(screen, NULL, rows, cols);
screen->buffer = screen->buffers[0];
screen->sb_buffer = vterm_allocator_malloc(screen->vt, sizeof(VTermScreenCell) * cols);
vterm_state_set_callbacks(screen->state, &state_cbs, screen);
return screen;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'patch 8.1.0633: crash when out of memory while opening a terminal window
Problem: Crash when out of memory while opening a terminal window.
Solution: Handle out-of-memory more gracefully.'</s> |
<s>[INST] Given the following code containing errors, provide 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 free_user(struct kref *ref)
{
struct ipmi_user *user = container_of(ref, struct ipmi_user, refcount);
kfree(user);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416', 'CWE-284'], 'message': 'ipmi: fix use-after-free of user->release_barrier.rda
When we do the following test, we got oops in ipmi_msghandler driver
while((1))
do
service ipmievd restart & service ipmievd restart
done
---------------------------------------------------------------
[ 294.230186] Unable to handle kernel paging request at virtual address 0000803fea6ea008
[ 294.230188] Mem abort info:
[ 294.230190] ESR = 0x96000004
[ 294.230191] Exception class = DABT (current EL), IL = 32 bits
[ 294.230193] SET = 0, FnV = 0
[ 294.230194] EA = 0, S1PTW = 0
[ 294.230195] Data abort info:
[ 294.230196] ISV = 0, ISS = 0x00000004
[ 294.230197] CM = 0, WnR = 0
[ 294.230199] user pgtable: 4k pages, 48-bit VAs, pgdp = 00000000a1c1b75a
[ 294.230201] [0000803fea6ea008] pgd=0000000000000000
[ 294.230204] Internal error: Oops: 96000004 [#1] SMP
[ 294.235211] Modules linked in: nls_utf8 isofs rpcrdma ib_iser ib_srpt target_core_mod ib_srp scsi_transport_srp ib_ipoib rdma_ucm ib_umad rdma_cm ib_cm iw_cm dm_mirror dm_region_hash dm_log dm_mod aes_ce_blk crypto_simd cryptd aes_ce_cipher ghash_ce sha2_ce ses sha256_arm64 sha1_ce hibmc_drm hisi_sas_v2_hw enclosure sg hisi_sas_main sbsa_gwdt ip_tables mlx5_ib ib_uverbs marvell ib_core mlx5_core ixgbe ipmi_si mdio hns_dsaf ipmi_devintf ipmi_msghandler hns_enet_drv hns_mdio
[ 294.277745] CPU: 3 PID: 0 Comm: swapper/3 Kdump: loaded Not tainted 5.0.0-rc2+ #113
[ 294.285511] Hardware name: Huawei TaiShan 2280 /BC11SPCD, BIOS 1.37 11/21/2017
[ 294.292835] pstate: 80000005 (Nzcv daif -PAN -UAO)
[ 294.297695] pc : __srcu_read_lock+0x38/0x58
[ 294.301940] lr : acquire_ipmi_user+0x2c/0x70 [ipmi_msghandler]
[ 294.307853] sp : ffff00001001bc80
[ 294.311208] x29: ffff00001001bc80 x28: ffff0000117e5000
[ 294.316594] x27: 0000000000000000 x26: dead000000000100
[ 294.321980] x25: dead000000000200 x24: ffff803f6bd06800
[ 294.327366] x23: 0000000000000000 x22: 0000000000000000
[ 294.332752] x21: ffff00001001bd04 x20: ffff80df33d19018
[ 294.338137] x19: ffff80df33d19018 x18: 0000000000000000
[ 294.343523] x17: 0000000000000000 x16: 0000000000000000
[ 294.348908] x15: 0000000000000000 x14: 0000000000000002
[ 294.354293] x13: 0000000000000000 x12: 0000000000000000
[ 294.359679] x11: 0000000000000000 x10: 0000000000100000
[ 294.365065] x9 : 0000000000000000 x8 : 0000000000000004
[ 294.370451] x7 : 0000000000000000 x6 : ffff80df34558678
[ 294.375836] x5 : 000000000000000c x4 : 0000000000000000
[ 294.381221] x3 : 0000000000000001 x2 : 0000803fea6ea000
[ 294.386607] x1 : 0000803fea6ea008 x0 : 0000000000000001
[ 294.391994] Process swapper/3 (pid: 0, stack limit = 0x0000000083087293)
[ 294.398791] Call trace:
[ 294.401266] __srcu_read_lock+0x38/0x58
[ 294.405154] acquire_ipmi_user+0x2c/0x70 [ipmi_msghandler]
[ 294.410716] deliver_response+0x80/0xf8 [ipmi_msghandler]
[ 294.416189] deliver_local_response+0x28/0x68 [ipmi_msghandler]
[ 294.422193] handle_one_recv_msg+0x158/0xcf8 [ipmi_msghandler]
[ 294.432050] handle_new_recv_msgs+0xc0/0x210 [ipmi_msghandler]
[ 294.441984] smi_recv_tasklet+0x8c/0x158 [ipmi_msghandler]
[ 294.451618] tasklet_action_common.isra.5+0x88/0x138
[ 294.460661] tasklet_action+0x2c/0x38
[ 294.468191] __do_softirq+0x120/0x2f8
[ 294.475561] irq_exit+0x134/0x140
[ 294.482445] __handle_domain_irq+0x6c/0xc0
[ 294.489954] gic_handle_irq+0xb8/0x178
[ 294.497037] el1_irq+0xb0/0x140
[ 294.503381] arch_cpu_idle+0x34/0x1a8
[ 294.510096] do_idle+0x1d4/0x290
[ 294.516322] cpu_startup_entry+0x28/0x30
[ 294.523230] secondary_start_kernel+0x184/0x1d0
[ 294.530657] Code: d538d082 d2800023 8b010c81 8b020021 (c85f7c25)
[ 294.539746] ---[ end trace 8a7a880dee570b29 ]---
[ 294.547341] Kernel panic - not syncing: Fatal exception in interrupt
[ 294.556837] SMP: stopping secondary CPUs
[ 294.563996] Kernel Offset: disabled
[ 294.570515] CPU features: 0x002,21006008
[ 294.577638] Memory Limit: none
[ 294.587178] Starting crashdump kernel...
[ 294.594314] Bye!
Because the user->release_barrier.rda is freed in ipmi_destroy_user(), but
the refcount is not zero, when acquire_ipmi_user() uses user->release_barrier.rda
in __srcu_read_lock(), it causes oops.
Fix this by calling cleanup_srcu_struct() when the refcount is zero.
Fixes: e86ee2d44b44 ("ipmi: Rework locking and shutdown for hot remove")
Cc: [email protected] # 4.18
Signed-off-by: Yang Yingliang <[email protected]>
Signed-off-by: Corey Minyard <[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: parse_reg_exp (re_string_t *regexp, regex_t *preg, re_token_t *token,
reg_syntax_t syntax, Idx nest, reg_errcode_t *err)
{
re_dfa_t *dfa = preg->buffer;
bin_tree_t *tree, *branch = NULL;
tree = parse_branch (regexp, preg, token, syntax, nest, err);
if (BE (*err != REG_NOERROR && tree == NULL, 0))
return NULL;
while (token->type == OP_ALT)
{
fetch_token (token, regexp, syntax | RE_CARET_ANCHORS_HERE);
if (token->type != OP_ALT && token->type != END_OF_RE
&& (nest == 0 || token->type != OP_CLOSE_SUBEXP))
{
branch = parse_branch (regexp, preg, token, syntax, nest, err);
if (BE (*err != REG_NOERROR && branch == NULL, 0))
{
if (tree != NULL)
postorder (tree, free_tree, NULL);
return NULL;
}
}
else
branch = NULL;
tree = create_tree (dfa, tree, branch, OP_ALT);
if (BE (tree == NULL, 0))
{
*err = REG_ESPACE;
return NULL;
}
}
return tree;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-19'], 'message': 'Diagnose ERE '()|\1'
Problem reported by Hanno Böck in: http://bugs.gnu.org/21513
* lib/regcomp.c (parse_reg_exp): While parsing alternatives, keep
track of the set of previously-completed subexpressions available
before the first alternative, and restore this set just before
parsing each subsequent alternative. This lets us diagnose the
invalid back-reference in the ERE '()|\1'.'</s> |
<s>[INST] Given the following code containing errors, provide 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 bus_append_execute_property(sd_bus_message *m, const char *field, const char *eq) {
const char *suffix;
int r;
if (STR_IN_SET(field,
"User", "Group",
"UtmpIdentifier", "UtmpMode", "PAMName", "TTYPath",
"WorkingDirectory", "RootDirectory", "SyslogIdentifier",
"ProtectSystem", "ProtectHome", "SELinuxContext", "RootImage",
"RuntimeDirectoryPreserve", "Personality", "KeyringMode", "NetworkNamespacePath"))
return bus_append_string(m, field, eq);
if (STR_IN_SET(field,
"IgnoreSIGPIPE", "TTYVHangup", "TTYReset", "TTYVTDisallocate",
"PrivateTmp", "PrivateDevices", "PrivateNetwork", "PrivateUsers",
"PrivateMounts", "NoNewPrivileges", "SyslogLevelPrefix",
"MemoryDenyWriteExecute", "RestrictRealtime", "DynamicUser", "RemoveIPC",
"ProtectKernelTunables", "ProtectKernelModules", "ProtectControlGroups",
"MountAPIVFS", "CPUSchedulingResetOnFork", "LockPersonality", "ProtectHostname"))
return bus_append_parse_boolean(m, field, eq);
if (STR_IN_SET(field,
"ReadWriteDirectories", "ReadOnlyDirectories", "InaccessibleDirectories",
"ReadWritePaths", "ReadOnlyPaths", "InaccessiblePaths",
"RuntimeDirectory", "StateDirectory", "CacheDirectory", "LogsDirectory", "ConfigurationDirectory",
"SupplementaryGroups", "SystemCallArchitectures"))
return bus_append_strv(m, field, eq, EXTRACT_QUOTES);
if (STR_IN_SET(field, "SyslogLevel", "LogLevelMax"))
return bus_append_log_level_from_string(m, field, eq);
if (streq(field, "SyslogFacility"))
return bus_append_log_facility_unshifted_from_string(m, field, eq);
if (streq(field, "SecureBits"))
return bus_append_secure_bits_from_string(m, field, eq);
if (streq(field, "CPUSchedulingPolicy"))
return bus_append_sched_policy_from_string(m, field, eq);
if (STR_IN_SET(field, "CPUSchedulingPriority", "OOMScoreAdjust"))
return bus_append_safe_atoi(m, field, eq);
if (streq(field, "Nice"))
return bus_append_parse_nice(m, field, eq);
if (streq(field, "SystemCallErrorNumber"))
return bus_append_parse_errno(m, field, eq);
if (streq(field, "IOSchedulingClass"))
return bus_append_ioprio_class_from_string(m, field, eq);
if (streq(field, "IOSchedulingPriority"))
return bus_append_ioprio_parse_priority(m, field, eq);
if (STR_IN_SET(field,
"RuntimeDirectoryMode", "StateDirectoryMode", "CacheDirectoryMode",
"LogsDirectoryMode", "ConfigurationDirectoryMode", "UMask"))
return bus_append_parse_mode(m, field, eq);
if (streq(field, "TimerSlackNSec"))
return bus_append_parse_nsec(m, field, eq);
if (streq(field, "LogRateLimitIntervalSec"))
return bus_append_parse_sec_rename(m, field, eq);
if (streq(field, "LogRateLimitBurst"))
return bus_append_safe_atou(m, field, eq);
if (streq(field, "MountFlags"))
return bus_append_mount_propagation_flags_from_string(m, field, eq);
if (STR_IN_SET(field, "Environment", "UnsetEnvironment", "PassEnvironment"))
return bus_append_strv(m, field, eq, EXTRACT_QUOTES|EXTRACT_CUNESCAPE);
if (streq(field, "EnvironmentFile")) {
if (isempty(eq))
r = sd_bus_message_append(m, "(sv)", "EnvironmentFiles", "a(sb)", 0);
else
r = sd_bus_message_append(m, "(sv)", "EnvironmentFiles", "a(sb)", 1,
eq[0] == '-' ? eq + 1 : eq,
eq[0] == '-');
if (r < 0)
return bus_log_create_error(r);
return 1;
}
if (streq(field, "LogExtraFields")) {
r = sd_bus_message_open_container(m, 'r', "sv");
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_append_basic(m, 's', "LogExtraFields");
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_open_container(m, 'v', "aay");
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_open_container(m, 'a', "ay");
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_append_array(m, 'y', eq, strlen(eq));
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_close_container(m);
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_close_container(m);
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_close_container(m);
if (r < 0)
return bus_log_create_error(r);
return 1;
}
if (STR_IN_SET(field, "StandardInput", "StandardOutput", "StandardError")) {
const char *n, *appended;
if ((n = startswith(eq, "fd:"))) {
appended = strjoina(field, "FileDescriptorName");
r = sd_bus_message_append(m, "(sv)", appended, "s", n);
} else if ((n = startswith(eq, "file:"))) {
appended = strjoina(field, "File");
r = sd_bus_message_append(m, "(sv)", appended, "s", n);
} else if ((n = startswith(eq, "append:"))) {
appended = strjoina(field, "FileToAppend");
r = sd_bus_message_append(m, "(sv)", appended, "s", n);
} else
r = sd_bus_message_append(m, "(sv)", field, "s", eq);
if (r < 0)
return bus_log_create_error(r);
return 1;
}
if (streq(field, "StandardInputText")) {
_cleanup_free_ char *unescaped = NULL;
r = cunescape(eq, 0, &unescaped);
if (r < 0)
return log_error_errno(r, "Failed to unescape text '%s': %m", eq);
if (!strextend(&unescaped, "\n", NULL))
return log_oom();
/* Note that we don't expand specifiers here, but that should be OK, as this is a programmatic
* interface anyway */
return bus_append_byte_array(m, field, unescaped, strlen(unescaped));
}
if (streq(field, "StandardInputData")) {
_cleanup_free_ void *decoded = NULL;
size_t sz;
r = unbase64mem(eq, (size_t) -1, &decoded, &sz);
if (r < 0)
return log_error_errno(r, "Failed to decode base64 data '%s': %m", eq);
return bus_append_byte_array(m, field, decoded, sz);
}
if ((suffix = startswith(field, "Limit"))) {
int rl;
rl = rlimit_from_string(suffix);
if (rl >= 0) {
const char *sn;
struct rlimit l;
r = rlimit_parse(rl, eq, &l);
if (r < 0)
return log_error_errno(r, "Failed to parse resource limit: %s", eq);
r = sd_bus_message_append(m, "(sv)", field, "t", l.rlim_max);
if (r < 0)
return bus_log_create_error(r);
sn = strjoina(field, "Soft");
r = sd_bus_message_append(m, "(sv)", sn, "t", l.rlim_cur);
if (r < 0)
return bus_log_create_error(r);
return 1;
}
}
if (STR_IN_SET(field, "AppArmorProfile", "SmackProcessLabel")) {
int ignore = 0;
const char *s = eq;
if (eq[0] == '-') {
ignore = 1;
s = eq + 1;
}
r = sd_bus_message_append(m, "(sv)", field, "(bs)", ignore, s);
if (r < 0)
return bus_log_create_error(r);
return 1;
}
if (STR_IN_SET(field, "CapabilityBoundingSet", "AmbientCapabilities")) {
uint64_t sum = 0;
bool invert = false;
const char *p = eq;
if (*p == '~') {
invert = true;
p++;
}
r = capability_set_from_string(p, &sum);
if (r < 0)
return log_error_errno(r, "Failed to parse %s value %s: %m", field, eq);
sum = invert ? ~sum : sum;
r = sd_bus_message_append(m, "(sv)", field, "t", sum);
if (r < 0)
return bus_log_create_error(r);
return 1;
}
if (streq(field, "CPUAffinity")) {
_cleanup_cpu_free_ cpu_set_t *cpuset = NULL;
r = parse_cpu_set(eq, &cpuset);
if (r < 0)
return log_error_errno(r, "Failed to parse %s value: %s", field, eq);
return bus_append_byte_array(m, field, cpuset, CPU_ALLOC_SIZE(r));
}
if (STR_IN_SET(field, "RestrictAddressFamilies", "SystemCallFilter")) {
int whitelist = 1;
const char *p = eq;
if (*p == '~') {
whitelist = 0;
p++;
}
r = sd_bus_message_open_container(m, SD_BUS_TYPE_STRUCT, "sv");
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_append_basic(m, SD_BUS_TYPE_STRING, field);
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_open_container(m, 'v', "(bas)");
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_open_container(m, 'r', "bas");
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_append_basic(m, 'b', &whitelist);
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_open_container(m, 'a', "s");
if (r < 0)
return bus_log_create_error(r);
for (;;) {
_cleanup_free_ char *word = NULL;
r = extract_first_word(&p, &word, NULL, EXTRACT_QUOTES);
if (r == 0)
break;
if (r == -ENOMEM)
return log_oom();
if (r < 0)
return log_error_errno(r, "Invalid syntax: %s", eq);
r = sd_bus_message_append_basic(m, 's', word);
if (r < 0)
return bus_log_create_error(r);
}
r = sd_bus_message_close_container(m);
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_close_container(m);
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_close_container(m);
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_close_container(m);
if (r < 0)
return bus_log_create_error(r);
return 1;
}
if (streq(field, "RestrictNamespaces")) {
bool invert = false;
unsigned long flags;
r = parse_boolean(eq);
if (r > 0)
flags = 0;
else if (r == 0)
flags = NAMESPACE_FLAGS_ALL;
else {
if (eq[0] == '~') {
invert = true;
eq++;
}
r = namespace_flags_from_string(eq, &flags);
if (r < 0)
return log_error_errno(r, "Failed to parse %s value %s.", field, eq);
}
if (invert)
flags = (~flags) & NAMESPACE_FLAGS_ALL;
r = sd_bus_message_append(m, "(sv)", field, "t", (uint64_t) flags);
if (r < 0)
return bus_log_create_error(r);
return 1;
}
if (STR_IN_SET(field, "BindPaths", "BindReadOnlyPaths")) {
const char *p = eq;
r = sd_bus_message_open_container(m, SD_BUS_TYPE_STRUCT, "sv");
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_append_basic(m, SD_BUS_TYPE_STRING, field);
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_open_container(m, 'v', "a(ssbt)");
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_open_container(m, 'a', "(ssbt)");
if (r < 0)
return bus_log_create_error(r);
for (;;) {
_cleanup_free_ char *source = NULL, *destination = NULL;
char *s = NULL, *d = NULL;
bool ignore_enoent = false;
uint64_t flags = MS_REC;
r = extract_first_word(&p, &source, ":" WHITESPACE, EXTRACT_QUOTES|EXTRACT_DONT_COALESCE_SEPARATORS);
if (r < 0)
return log_error_errno(r, "Failed to parse argument: %m");
if (r == 0)
break;
s = source;
if (s[0] == '-') {
ignore_enoent = true;
s++;
}
if (p && p[-1] == ':') {
r = extract_first_word(&p, &destination, ":" WHITESPACE, EXTRACT_QUOTES|EXTRACT_DONT_COALESCE_SEPARATORS);
if (r < 0)
return log_error_errno(r, "Failed to parse argument: %m");
if (r == 0)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"Missing argument after ':': %s",
eq);
d = destination;
if (p && p[-1] == ':') {
_cleanup_free_ char *options = NULL;
r = extract_first_word(&p, &options, NULL, EXTRACT_QUOTES);
if (r < 0)
return log_error_errno(r, "Failed to parse argument: %m");
if (isempty(options) || streq(options, "rbind"))
flags = MS_REC;
else if (streq(options, "norbind"))
flags = 0;
else
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"Unknown options: %s",
eq);
}
} else
d = s;
r = sd_bus_message_append(m, "(ssbt)", s, d, ignore_enoent, flags);
if (r < 0)
return bus_log_create_error(r);
}
r = sd_bus_message_close_container(m);
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_close_container(m);
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_close_container(m);
if (r < 0)
return bus_log_create_error(r);
return 1;
}
if (streq(field, "TemporaryFileSystem")) {
const char *p = eq;
r = sd_bus_message_open_container(m, SD_BUS_TYPE_STRUCT, "sv");
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_append_basic(m, SD_BUS_TYPE_STRING, field);
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_open_container(m, 'v', "a(ss)");
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_open_container(m, 'a', "(ss)");
if (r < 0)
return bus_log_create_error(r);
for (;;) {
_cleanup_free_ char *word = NULL, *path = NULL;
const char *w;
r = extract_first_word(&p, &word, NULL, EXTRACT_QUOTES);
if (r < 0)
return log_error_errno(r, "Failed to parse argument: %m");
if (r == 0)
break;
w = word;
r = extract_first_word(&w, &path, ":", EXTRACT_DONT_COALESCE_SEPARATORS);
if (r < 0)
return log_error_errno(r, "Failed to parse argument: %m");
if (r == 0)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"Failed to parse argument: %s",
p);
r = sd_bus_message_append(m, "(ss)", path, w);
if (r < 0)
return bus_log_create_error(r);
}
r = sd_bus_message_close_container(m);
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_close_container(m);
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_close_container(m);
if (r < 0)
return bus_log_create_error(r);
return 1;
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-269'], 'message': 'core: expose SUID/SGID restriction as new unit setting RestrictSUIDSGID='</s> |
<s>[INST] Given the following code containing errors, provide 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 bus_exec_context_set_transient_property(
Unit *u,
ExecContext *c,
const char *name,
sd_bus_message *message,
UnitWriteFlags flags,
sd_bus_error *error) {
const char *suffix;
int r;
assert(u);
assert(c);
assert(name);
assert(message);
flags |= UNIT_PRIVATE;
if (streq(name, "User"))
return bus_set_transient_user(u, name, &c->user, message, flags, error);
if (streq(name, "Group"))
return bus_set_transient_user(u, name, &c->group, message, flags, error);
if (streq(name, "TTYPath"))
return bus_set_transient_path(u, name, &c->tty_path, message, flags, error);
if (streq(name, "RootImage"))
return bus_set_transient_path(u, name, &c->root_image, message, flags, error);
if (streq(name, "RootDirectory"))
return bus_set_transient_path(u, name, &c->root_directory, message, flags, error);
if (streq(name, "SyslogIdentifier"))
return bus_set_transient_string(u, name, &c->syslog_identifier, message, flags, error);
if (streq(name, "LogLevelMax"))
return bus_set_transient_log_level(u, name, &c->log_level_max, message, flags, error);
if (streq(name, "LogRateLimitIntervalUSec"))
return bus_set_transient_usec(u, name, &c->log_rate_limit_interval_usec, message, flags, error);
if (streq(name, "LogRateLimitBurst"))
return bus_set_transient_unsigned(u, name, &c->log_rate_limit_burst, message, flags, error);
if (streq(name, "Personality"))
return bus_set_transient_personality(u, name, &c->personality, message, flags, error);
if (streq(name, "StandardInput"))
return bus_set_transient_std_input(u, name, &c->std_input, message, flags, error);
if (streq(name, "StandardOutput"))
return bus_set_transient_std_output(u, name, &c->std_output, message, flags, error);
if (streq(name, "StandardError"))
return bus_set_transient_std_output(u, name, &c->std_error, message, flags, error);
if (streq(name, "IgnoreSIGPIPE"))
return bus_set_transient_bool(u, name, &c->ignore_sigpipe, message, flags, error);
if (streq(name, "TTYVHangup"))
return bus_set_transient_bool(u, name, &c->tty_vhangup, message, flags, error);
if (streq(name, "TTYReset"))
return bus_set_transient_bool(u, name, &c->tty_reset, message, flags, error);
if (streq(name, "TTYVTDisallocate"))
return bus_set_transient_bool(u, name, &c->tty_vt_disallocate, message, flags, error);
if (streq(name, "PrivateTmp"))
return bus_set_transient_bool(u, name, &c->private_tmp, message, flags, error);
if (streq(name, "PrivateDevices"))
return bus_set_transient_bool(u, name, &c->private_devices, message, flags, error);
if (streq(name, "PrivateMounts"))
return bus_set_transient_bool(u, name, &c->private_mounts, message, flags, error);
if (streq(name, "PrivateNetwork"))
return bus_set_transient_bool(u, name, &c->private_network, message, flags, error);
if (streq(name, "PrivateUsers"))
return bus_set_transient_bool(u, name, &c->private_users, message, flags, error);
if (streq(name, "NoNewPrivileges"))
return bus_set_transient_bool(u, name, &c->no_new_privileges, message, flags, error);
if (streq(name, "SyslogLevelPrefix"))
return bus_set_transient_bool(u, name, &c->syslog_level_prefix, message, flags, error);
if (streq(name, "MemoryDenyWriteExecute"))
return bus_set_transient_bool(u, name, &c->memory_deny_write_execute, message, flags, error);
if (streq(name, "RestrictRealtime"))
return bus_set_transient_bool(u, name, &c->restrict_realtime, message, flags, error);
if (streq(name, "DynamicUser"))
return bus_set_transient_bool(u, name, &c->dynamic_user, message, flags, error);
if (streq(name, "RemoveIPC"))
return bus_set_transient_bool(u, name, &c->remove_ipc, message, flags, error);
if (streq(name, "ProtectKernelTunables"))
return bus_set_transient_bool(u, name, &c->protect_kernel_tunables, message, flags, error);
if (streq(name, "ProtectKernelModules"))
return bus_set_transient_bool(u, name, &c->protect_kernel_modules, message, flags, error);
if (streq(name, "ProtectControlGroups"))
return bus_set_transient_bool(u, name, &c->protect_control_groups, message, flags, error);
if (streq(name, "MountAPIVFS"))
return bus_set_transient_bool(u, name, &c->mount_apivfs, message, flags, error);
if (streq(name, "CPUSchedulingResetOnFork"))
return bus_set_transient_bool(u, name, &c->cpu_sched_reset_on_fork, message, flags, error);
if (streq(name, "NonBlocking"))
return bus_set_transient_bool(u, name, &c->non_blocking, message, flags, error);
if (streq(name, "LockPersonality"))
return bus_set_transient_bool(u, name, &c->lock_personality, message, flags, error);
if (streq(name, "ProtectHostname"))
return bus_set_transient_bool(u, name, &c->protect_hostname, message, flags, error);
if (streq(name, "UtmpIdentifier"))
return bus_set_transient_string(u, name, &c->utmp_id, message, flags, error);
if (streq(name, "UtmpMode"))
return bus_set_transient_utmp_mode(u, name, &c->utmp_mode, message, flags, error);
if (streq(name, "PAMName"))
return bus_set_transient_string(u, name, &c->pam_name, message, flags, error);
if (streq(name, "TimerSlackNSec"))
return bus_set_transient_nsec(u, name, &c->timer_slack_nsec, message, flags, error);
if (streq(name, "ProtectSystem"))
return bus_set_transient_protect_system(u, name, &c->protect_system, message, flags, error);
if (streq(name, "ProtectHome"))
return bus_set_transient_protect_home(u, name, &c->protect_home, message, flags, error);
if (streq(name, "KeyringMode"))
return bus_set_transient_keyring_mode(u, name, &c->keyring_mode, message, flags, error);
if (streq(name, "RuntimeDirectoryPreserve"))
return bus_set_transient_preserve_mode(u, name, &c->runtime_directory_preserve_mode, message, flags, error);
if (streq(name, "UMask"))
return bus_set_transient_mode_t(u, name, &c->umask, message, flags, error);
if (streq(name, "RuntimeDirectoryMode"))
return bus_set_transient_mode_t(u, name, &c->directories[EXEC_DIRECTORY_RUNTIME].mode, message, flags, error);
if (streq(name, "StateDirectoryMode"))
return bus_set_transient_mode_t(u, name, &c->directories[EXEC_DIRECTORY_STATE].mode, message, flags, error);
if (streq(name, "CacheDirectoryMode"))
return bus_set_transient_mode_t(u, name, &c->directories[EXEC_DIRECTORY_CACHE].mode, message, flags, error);
if (streq(name, "LogsDirectoryMode"))
return bus_set_transient_mode_t(u, name, &c->directories[EXEC_DIRECTORY_LOGS].mode, message, flags, error);
if (streq(name, "ConfigurationDirectoryMode"))
return bus_set_transient_mode_t(u, name, &c->directories[EXEC_DIRECTORY_CONFIGURATION].mode, message, flags, error);
if (streq(name, "SELinuxContext"))
return bus_set_transient_string(u, name, &c->selinux_context, message, flags, error);
if (streq(name, "SecureBits"))
return bus_set_transient_secure_bits(u, name, &c->secure_bits, message, flags, error);
if (streq(name, "CapabilityBoundingSet"))
return bus_set_transient_capability(u, name, &c->capability_bounding_set, message, flags, error);
if (streq(name, "AmbientCapabilities"))
return bus_set_transient_capability(u, name, &c->capability_ambient_set, message, flags, error);
if (streq(name, "RestrictNamespaces"))
return bus_set_transient_namespace_flag(u, name, &c->restrict_namespaces, message, flags, error);
if (streq(name, "MountFlags"))
return bus_set_transient_mount_flags(u, name, &c->mount_flags, message, flags, error);
if (streq(name, "NetworkNamespacePath"))
return bus_set_transient_path(u, name, &c->network_namespace_path, message, flags, error);
if (streq(name, "SupplementaryGroups")) {
_cleanup_strv_free_ char **l = NULL;
char **p;
r = sd_bus_message_read_strv(message, &l);
if (r < 0)
return r;
STRV_FOREACH(p, l) {
if (!isempty(*p) && !valid_user_group_name_or_id(*p))
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid supplementary group names");
}
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
if (strv_isempty(l)) {
c->supplementary_groups = strv_free(c->supplementary_groups);
unit_write_settingf(u, flags, name, "%s=", name);
} else {
_cleanup_free_ char *joined = NULL;
r = strv_extend_strv(&c->supplementary_groups, l, true);
if (r < 0)
return -ENOMEM;
joined = strv_join(c->supplementary_groups, " ");
if (!joined)
return -ENOMEM;
unit_write_settingf(u, flags|UNIT_ESCAPE_SPECIFIERS, name, "%s=%s", name, joined);
}
}
return 1;
} else if (streq(name, "SyslogLevel")) {
int32_t level;
r = sd_bus_message_read(message, "i", &level);
if (r < 0)
return r;
if (!log_level_is_valid(level))
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Log level value out of range");
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
c->syslog_priority = (c->syslog_priority & LOG_FACMASK) | level;
unit_write_settingf(u, flags, name, "SyslogLevel=%i", level);
}
return 1;
} else if (streq(name, "SyslogFacility")) {
int32_t facility;
r = sd_bus_message_read(message, "i", &facility);
if (r < 0)
return r;
if (!log_facility_unshifted_is_valid(facility))
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Log facility value out of range");
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
c->syslog_priority = (facility << 3) | LOG_PRI(c->syslog_priority);
unit_write_settingf(u, flags, name, "SyslogFacility=%i", facility);
}
return 1;
} else if (streq(name, "LogExtraFields")) {
size_t n = 0;
r = sd_bus_message_enter_container(message, 'a', "ay");
if (r < 0)
return r;
for (;;) {
_cleanup_free_ void *copy = NULL;
struct iovec *t;
const char *eq;
const void *p;
size_t sz;
/* Note that we expect a byte array for each field, instead of a string. That's because on the
* lower-level journal fields can actually contain binary data and are not restricted to text,
* and we should not "lose precision" in our types on the way. That said, I am pretty sure
* actually encoding binary data as unit metadata is not a good idea. Hence we actually refuse
* any actual binary data, and only accept UTF-8. This allows us to eventually lift this
* limitation, should a good, valid usecase arise. */
r = sd_bus_message_read_array(message, 'y', &p, &sz);
if (r < 0)
return r;
if (r == 0)
break;
if (memchr(p, 0, sz))
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Journal field contains zero byte");
eq = memchr(p, '=', sz);
if (!eq)
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Journal field contains no '=' character");
if (!journal_field_valid(p, eq - (const char*) p, false))
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Journal field invalid");
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
t = reallocarray(c->log_extra_fields, c->n_log_extra_fields+1, sizeof(struct iovec));
if (!t)
return -ENOMEM;
c->log_extra_fields = t;
}
copy = malloc(sz + 1);
if (!copy)
return -ENOMEM;
memcpy(copy, p, sz);
((uint8_t*) copy)[sz] = 0;
if (!utf8_is_valid(copy))
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Journal field is not valid UTF-8");
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
c->log_extra_fields[c->n_log_extra_fields++] = IOVEC_MAKE(copy, sz);
unit_write_settingf(u, flags|UNIT_ESCAPE_SPECIFIERS|UNIT_ESCAPE_C, name, "LogExtraFields=%s", (char*) copy);
copy = NULL;
}
n++;
}
r = sd_bus_message_exit_container(message);
if (r < 0)
return r;
if (!UNIT_WRITE_FLAGS_NOOP(flags) && n == 0) {
exec_context_free_log_extra_fields(c);
unit_write_setting(u, flags, name, "LogExtraFields=");
}
return 1;
}
#if HAVE_SECCOMP
if (streq(name, "SystemCallErrorNumber"))
return bus_set_transient_errno(u, name, &c->syscall_errno, message, flags, error);
if (streq(name, "SystemCallFilter")) {
int whitelist;
_cleanup_strv_free_ char **l = NULL;
r = sd_bus_message_enter_container(message, 'r', "bas");
if (r < 0)
return r;
r = sd_bus_message_read(message, "b", &whitelist);
if (r < 0)
return r;
r = sd_bus_message_read_strv(message, &l);
if (r < 0)
return r;
r = sd_bus_message_exit_container(message);
if (r < 0)
return r;
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
_cleanup_free_ char *joined = NULL;
bool invert = !whitelist;
char **s;
if (strv_isempty(l)) {
c->syscall_whitelist = false;
c->syscall_filter = hashmap_free(c->syscall_filter);
unit_write_settingf(u, flags, name, "SystemCallFilter=");
return 1;
}
if (!c->syscall_filter) {
c->syscall_filter = hashmap_new(NULL);
if (!c->syscall_filter)
return log_oom();
c->syscall_whitelist = whitelist;
if (c->syscall_whitelist) {
r = seccomp_parse_syscall_filter("@default", -1, c->syscall_filter, SECCOMP_PARSE_WHITELIST | (invert ? SECCOMP_PARSE_INVERT : 0));
if (r < 0)
return r;
}
}
STRV_FOREACH(s, l) {
_cleanup_free_ char *n = NULL;
int e;
r = parse_syscall_and_errno(*s, &n, &e);
if (r < 0)
return r;
r = seccomp_parse_syscall_filter(n, e, c->syscall_filter, (invert ? SECCOMP_PARSE_INVERT : 0) | (c->syscall_whitelist ? SECCOMP_PARSE_WHITELIST : 0));
if (r < 0)
return r;
}
joined = strv_join(l, " ");
if (!joined)
return -ENOMEM;
unit_write_settingf(u, flags, name, "SystemCallFilter=%s%s", whitelist ? "" : "~", joined);
}
return 1;
} else if (streq(name, "SystemCallArchitectures")) {
_cleanup_strv_free_ char **l = NULL;
r = sd_bus_message_read_strv(message, &l);
if (r < 0)
return r;
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
_cleanup_free_ char *joined = NULL;
if (strv_isempty(l))
c->syscall_archs = set_free(c->syscall_archs);
else {
char **s;
r = set_ensure_allocated(&c->syscall_archs, NULL);
if (r < 0)
return r;
STRV_FOREACH(s, l) {
uint32_t a;
r = seccomp_arch_from_string(*s, &a);
if (r < 0)
return r;
r = set_put(c->syscall_archs, UINT32_TO_PTR(a + 1));
if (r < 0)
return r;
}
}
joined = strv_join(l, " ");
if (!joined)
return -ENOMEM;
unit_write_settingf(u, flags, name, "%s=%s", name, joined);
}
return 1;
} else if (streq(name, "RestrictAddressFamilies")) {
int whitelist;
_cleanup_strv_free_ char **l = NULL;
r = sd_bus_message_enter_container(message, 'r', "bas");
if (r < 0)
return r;
r = sd_bus_message_read(message, "b", &whitelist);
if (r < 0)
return r;
r = sd_bus_message_read_strv(message, &l);
if (r < 0)
return r;
r = sd_bus_message_exit_container(message);
if (r < 0)
return r;
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
_cleanup_free_ char *joined = NULL;
bool invert = !whitelist;
char **s;
if (strv_isempty(l)) {
c->address_families_whitelist = false;
c->address_families = set_free(c->address_families);
unit_write_settingf(u, flags, name, "RestrictAddressFamilies=");
return 1;
}
if (!c->address_families) {
c->address_families = set_new(NULL);
if (!c->address_families)
return log_oom();
c->address_families_whitelist = whitelist;
}
STRV_FOREACH(s, l) {
int af;
af = af_from_name(*s);
if (af < 0)
return af;
if (!invert == c->address_families_whitelist) {
r = set_put(c->address_families, INT_TO_PTR(af));
if (r < 0)
return r;
} else
(void) set_remove(c->address_families, INT_TO_PTR(af));
}
joined = strv_join(l, " ");
if (!joined)
return -ENOMEM;
unit_write_settingf(u, flags, name, "RestrictAddressFamilies=%s%s", whitelist ? "" : "~", joined);
}
return 1;
}
#endif
if (streq(name, "CPUAffinity")) {
const void *a;
size_t n = 0;
r = sd_bus_message_read_array(message, 'y', &a, &n);
if (r < 0)
return r;
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
if (n == 0) {
c->cpuset = cpu_set_mfree(c->cpuset);
c->cpuset_ncpus = 0;
unit_write_settingf(u, flags, name, "%s=", name);
} else {
_cleanup_free_ char *str = NULL;
size_t allocated = 0, len = 0, i, ncpus;
ncpus = CPU_SIZE_TO_NUM(n);
for (i = 0; i < ncpus; i++) {
_cleanup_free_ char *p = NULL;
size_t add;
if (!CPU_ISSET_S(i, n, (cpu_set_t*) a))
continue;
r = asprintf(&p, "%zu", i);
if (r < 0)
return -ENOMEM;
add = strlen(p);
if (!GREEDY_REALLOC(str, allocated, len + add + 2))
return -ENOMEM;
strcpy(mempcpy(str + len, p, add), " ");
len += add + 1;
}
if (len != 0)
str[len - 1] = '\0';
if (!c->cpuset || c->cpuset_ncpus < ncpus) {
cpu_set_t *cpuset;
cpuset = CPU_ALLOC(ncpus);
if (!cpuset)
return -ENOMEM;
CPU_ZERO_S(n, cpuset);
if (c->cpuset) {
CPU_OR_S(CPU_ALLOC_SIZE(c->cpuset_ncpus), cpuset, c->cpuset, (cpu_set_t*) a);
CPU_FREE(c->cpuset);
} else
CPU_OR_S(n, cpuset, cpuset, (cpu_set_t*) a);
c->cpuset = cpuset;
c->cpuset_ncpus = ncpus;
} else
CPU_OR_S(n, c->cpuset, c->cpuset, (cpu_set_t*) a);
unit_write_settingf(u, flags, name, "%s=%s", name, str);
}
}
return 1;
} else if (streq(name, "Nice")) {
int32_t q;
r = sd_bus_message_read(message, "i", &q);
if (r < 0)
return r;
if (!nice_is_valid(q))
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid Nice value: %i", q);
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
c->nice = q;
c->nice_set = true;
unit_write_settingf(u, flags, name, "Nice=%i", q);
}
return 1;
} else if (streq(name, "CPUSchedulingPolicy")) {
int32_t q;
r = sd_bus_message_read(message, "i", &q);
if (r < 0)
return r;
if (!sched_policy_is_valid(q))
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid CPU scheduling policy: %i", q);
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
_cleanup_free_ char *s = NULL;
r = sched_policy_to_string_alloc(q, &s);
if (r < 0)
return r;
c->cpu_sched_policy = q;
c->cpu_sched_priority = CLAMP(c->cpu_sched_priority, sched_get_priority_min(q), sched_get_priority_max(q));
c->cpu_sched_set = true;
unit_write_settingf(u, flags, name, "CPUSchedulingPolicy=%s", s);
}
return 1;
} else if (streq(name, "CPUSchedulingPriority")) {
int32_t p, min, max;
r = sd_bus_message_read(message, "i", &p);
if (r < 0)
return r;
min = sched_get_priority_min(c->cpu_sched_policy);
max = sched_get_priority_max(c->cpu_sched_policy);
if (p < min || p > max)
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid CPU scheduling priority: %i", p);
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
c->cpu_sched_priority = p;
c->cpu_sched_set = true;
unit_write_settingf(u, flags, name, "CPUSchedulingPriority=%i", p);
}
return 1;
} else if (streq(name, "IOSchedulingClass")) {
int32_t q;
r = sd_bus_message_read(message, "i", &q);
if (r < 0)
return r;
if (!ioprio_class_is_valid(q))
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid IO scheduling class: %i", q);
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
_cleanup_free_ char *s = NULL;
r = ioprio_class_to_string_alloc(q, &s);
if (r < 0)
return r;
c->ioprio = IOPRIO_PRIO_VALUE(q, IOPRIO_PRIO_DATA(c->ioprio));
c->ioprio_set = true;
unit_write_settingf(u, flags, name, "IOSchedulingClass=%s", s);
}
return 1;
} else if (streq(name, "IOSchedulingPriority")) {
int32_t p;
r = sd_bus_message_read(message, "i", &p);
if (r < 0)
return r;
if (!ioprio_priority_is_valid(p))
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid IO scheduling priority: %i", p);
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
c->ioprio = IOPRIO_PRIO_VALUE(IOPRIO_PRIO_CLASS(c->ioprio), p);
c->ioprio_set = true;
unit_write_settingf(u, flags, name, "IOSchedulingPriority=%i", p);
}
return 1;
} else if (streq(name, "WorkingDirectory")) {
const char *s;
bool missing_ok;
r = sd_bus_message_read(message, "s", &s);
if (r < 0)
return r;
if (s[0] == '-') {
missing_ok = true;
s++;
} else
missing_ok = false;
if (!isempty(s) && !streq(s, "~") && !path_is_absolute(s))
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "WorkingDirectory= expects an absolute path or '~'");
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
if (streq(s, "~")) {
c->working_directory = mfree(c->working_directory);
c->working_directory_home = true;
} else {
r = free_and_strdup(&c->working_directory, empty_to_null(s));
if (r < 0)
return r;
c->working_directory_home = false;
}
c->working_directory_missing_ok = missing_ok;
unit_write_settingf(u, flags|UNIT_ESCAPE_SPECIFIERS, name, "WorkingDirectory=%s%s", missing_ok ? "-" : "", s);
}
return 1;
} else if (STR_IN_SET(name,
"StandardInputFileDescriptorName", "StandardOutputFileDescriptorName", "StandardErrorFileDescriptorName")) {
const char *s;
r = sd_bus_message_read(message, "s", &s);
if (r < 0)
return r;
if (!isempty(s) && !fdname_is_valid(s))
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid file descriptor name");
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
if (streq(name, "StandardInputFileDescriptorName")) {
r = free_and_strdup(c->stdio_fdname + STDIN_FILENO, empty_to_null(s));
if (r < 0)
return r;
c->std_input = EXEC_INPUT_NAMED_FD;
unit_write_settingf(u, flags|UNIT_ESCAPE_SPECIFIERS, name, "StandardInput=fd:%s", exec_context_fdname(c, STDIN_FILENO));
} else if (streq(name, "StandardOutputFileDescriptorName")) {
r = free_and_strdup(c->stdio_fdname + STDOUT_FILENO, empty_to_null(s));
if (r < 0)
return r;
c->std_output = EXEC_OUTPUT_NAMED_FD;
unit_write_settingf(u, flags|UNIT_ESCAPE_SPECIFIERS, name, "StandardOutput=fd:%s", exec_context_fdname(c, STDOUT_FILENO));
} else {
assert(streq(name, "StandardErrorFileDescriptorName"));
r = free_and_strdup(&c->stdio_fdname[STDERR_FILENO], empty_to_null(s));
if (r < 0)
return r;
c->std_error = EXEC_OUTPUT_NAMED_FD;
unit_write_settingf(u, flags|UNIT_ESCAPE_SPECIFIERS, name, "StandardError=fd:%s", exec_context_fdname(c, STDERR_FILENO));
}
}
return 1;
} else if (STR_IN_SET(name,
"StandardInputFile",
"StandardOutputFile", "StandardOutputFileToAppend",
"StandardErrorFile", "StandardErrorFileToAppend")) {
const char *s;
r = sd_bus_message_read(message, "s", &s);
if (r < 0)
return r;
if (!isempty(s)) {
if (!path_is_absolute(s))
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Path %s is not absolute", s);
if (!path_is_normalized(s))
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Path %s is not normalized", s);
}
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
if (streq(name, "StandardInputFile")) {
r = free_and_strdup(&c->stdio_file[STDIN_FILENO], empty_to_null(s));
if (r < 0)
return r;
c->std_input = EXEC_INPUT_FILE;
unit_write_settingf(u, flags|UNIT_ESCAPE_SPECIFIERS, name, "StandardInput=file:%s", s);
} else if (STR_IN_SET(name, "StandardOutputFile", "StandardOutputFileToAppend")) {
r = free_and_strdup(&c->stdio_file[STDOUT_FILENO], empty_to_null(s));
if (r < 0)
return r;
if (streq(name, "StandardOutputFile")) {
c->std_output = EXEC_OUTPUT_FILE;
unit_write_settingf(u, flags|UNIT_ESCAPE_SPECIFIERS, name, "StandardOutput=file:%s", s);
} else {
assert(streq(name, "StandardOutputFileToAppend"));
c->std_output = EXEC_OUTPUT_FILE_APPEND;
unit_write_settingf(u, flags|UNIT_ESCAPE_SPECIFIERS, name, "StandardOutput=append:%s", s);
}
} else {
assert(STR_IN_SET(name, "StandardErrorFile", "StandardErrorFileToAppend"));
r = free_and_strdup(&c->stdio_file[STDERR_FILENO], empty_to_null(s));
if (r < 0)
return r;
if (streq(name, "StandardErrorFile")) {
c->std_error = EXEC_OUTPUT_FILE;
unit_write_settingf(u, flags|UNIT_ESCAPE_SPECIFIERS, name, "StandardError=file:%s", s);
} else {
assert(streq(name, "StandardErrorFileToAppend"));
c->std_error = EXEC_OUTPUT_FILE_APPEND;
unit_write_settingf(u, flags|UNIT_ESCAPE_SPECIFIERS, name, "StandardError=append:%s", s);
}
}
}
return 1;
} else if (streq(name, "StandardInputData")) {
const void *p;
size_t sz;
r = sd_bus_message_read_array(message, 'y', &p, &sz);
if (r < 0)
return r;
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
_cleanup_free_ char *encoded = NULL;
if (sz == 0) {
c->stdin_data = mfree(c->stdin_data);
c->stdin_data_size = 0;
unit_write_settingf(u, flags, name, "StandardInputData=");
} else {
void *q;
ssize_t n;
if (c->stdin_data_size + sz < c->stdin_data_size || /* check for overflow */
c->stdin_data_size + sz > EXEC_STDIN_DATA_MAX)
return -E2BIG;
n = base64mem(p, sz, &encoded);
if (n < 0)
return (int) n;
q = realloc(c->stdin_data, c->stdin_data_size + sz);
if (!q)
return -ENOMEM;
memcpy((uint8_t*) q + c->stdin_data_size, p, sz);
c->stdin_data = q;
c->stdin_data_size += sz;
unit_write_settingf(u, flags, name, "StandardInputData=%s", encoded);
}
}
return 1;
} else if (streq(name, "Environment")) {
_cleanup_strv_free_ char **l = NULL;
r = sd_bus_message_read_strv(message, &l);
if (r < 0)
return r;
if (!strv_env_is_valid(l))
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid environment block.");
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
if (strv_isempty(l)) {
c->environment = strv_free(c->environment);
unit_write_setting(u, flags, name, "Environment=");
} else {
_cleanup_free_ char *joined = NULL;
char **e;
joined = unit_concat_strv(l, UNIT_ESCAPE_SPECIFIERS|UNIT_ESCAPE_C);
if (!joined)
return -ENOMEM;
e = strv_env_merge(2, c->environment, l);
if (!e)
return -ENOMEM;
strv_free_and_replace(c->environment, e);
unit_write_settingf(u, flags, name, "Environment=%s", joined);
}
}
return 1;
} else if (streq(name, "UnsetEnvironment")) {
_cleanup_strv_free_ char **l = NULL;
r = sd_bus_message_read_strv(message, &l);
if (r < 0)
return r;
if (!strv_env_name_or_assignment_is_valid(l))
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid UnsetEnvironment= list.");
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
if (strv_isempty(l)) {
c->unset_environment = strv_free(c->unset_environment);
unit_write_setting(u, flags, name, "UnsetEnvironment=");
} else {
_cleanup_free_ char *joined = NULL;
char **e;
joined = unit_concat_strv(l, UNIT_ESCAPE_SPECIFIERS|UNIT_ESCAPE_C);
if (!joined)
return -ENOMEM;
e = strv_env_merge(2, c->unset_environment, l);
if (!e)
return -ENOMEM;
strv_free_and_replace(c->unset_environment, e);
unit_write_settingf(u, flags, name, "UnsetEnvironment=%s", joined);
}
}
return 1;
} else if (streq(name, "OOMScoreAdjust")) {
int oa;
r = sd_bus_message_read(message, "i", &oa);
if (r < 0)
return r;
if (!oom_score_adjust_is_valid(oa))
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "OOM score adjust value out of range");
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
c->oom_score_adjust = oa;
c->oom_score_adjust_set = true;
unit_write_settingf(u, flags, name, "OOMScoreAdjust=%i", oa);
}
return 1;
} else if (streq(name, "EnvironmentFiles")) {
_cleanup_free_ char *joined = NULL;
_cleanup_fclose_ FILE *f = NULL;
_cleanup_strv_free_ char **l = NULL;
size_t size = 0;
char **i;
r = sd_bus_message_enter_container(message, 'a', "(sb)");
if (r < 0)
return r;
f = open_memstream(&joined, &size);
if (!f)
return -ENOMEM;
(void) __fsetlocking(f, FSETLOCKING_BYCALLER);
fputs("EnvironmentFile=\n", f);
STRV_FOREACH(i, c->environment_files) {
_cleanup_free_ char *q = NULL;
q = specifier_escape(*i);
if (!q)
return -ENOMEM;
fprintf(f, "EnvironmentFile=%s\n", q);
}
while ((r = sd_bus_message_enter_container(message, 'r', "sb")) > 0) {
const char *path;
int b;
r = sd_bus_message_read(message, "sb", &path, &b);
if (r < 0)
return r;
r = sd_bus_message_exit_container(message);
if (r < 0)
return r;
if (!path_is_absolute(path))
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Path %s is not absolute.", path);
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
_cleanup_free_ char *q = NULL;
char *buf;
buf = strjoin(b ? "-" : "", path);
if (!buf)
return -ENOMEM;
q = specifier_escape(buf);
if (!q) {
free(buf);
return -ENOMEM;
}
fprintf(f, "EnvironmentFile=%s\n", q);
r = strv_consume(&l, buf);
if (r < 0)
return r;
}
}
if (r < 0)
return r;
r = sd_bus_message_exit_container(message);
if (r < 0)
return r;
r = fflush_and_check(f);
if (r < 0)
return r;
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
if (strv_isempty(l)) {
c->environment_files = strv_free(c->environment_files);
unit_write_setting(u, flags, name, "EnvironmentFile=");
} else {
r = strv_extend_strv(&c->environment_files, l, true);
if (r < 0)
return r;
unit_write_setting(u, flags, name, joined);
}
}
return 1;
} else if (streq(name, "PassEnvironment")) {
_cleanup_strv_free_ char **l = NULL;
r = sd_bus_message_read_strv(message, &l);
if (r < 0)
return r;
if (!strv_env_name_is_valid(l))
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid PassEnvironment= block.");
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
if (strv_isempty(l)) {
c->pass_environment = strv_free(c->pass_environment);
unit_write_setting(u, flags, name, "PassEnvironment=");
} else {
_cleanup_free_ char *joined = NULL;
r = strv_extend_strv(&c->pass_environment, l, true);
if (r < 0)
return r;
/* We write just the new settings out to file, with unresolved specifiers. */
joined = unit_concat_strv(l, UNIT_ESCAPE_SPECIFIERS);
if (!joined)
return -ENOMEM;
unit_write_settingf(u, flags, name, "PassEnvironment=%s", joined);
}
}
return 1;
} else if (STR_IN_SET(name, "ReadWriteDirectories", "ReadOnlyDirectories", "InaccessibleDirectories",
"ReadWritePaths", "ReadOnlyPaths", "InaccessiblePaths")) {
_cleanup_strv_free_ char **l = NULL;
char ***dirs;
char **p;
r = sd_bus_message_read_strv(message, &l);
if (r < 0)
return r;
STRV_FOREACH(p, l) {
char *i = *p;
size_t offset;
offset = i[0] == '-';
offset += i[offset] == '+';
if (!path_is_absolute(i + offset))
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid %s", name);
path_simplify(i + offset, false);
}
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
if (STR_IN_SET(name, "ReadWriteDirectories", "ReadWritePaths"))
dirs = &c->read_write_paths;
else if (STR_IN_SET(name, "ReadOnlyDirectories", "ReadOnlyPaths"))
dirs = &c->read_only_paths;
else /* "InaccessiblePaths" */
dirs = &c->inaccessible_paths;
if (strv_isempty(l)) {
*dirs = strv_free(*dirs);
unit_write_settingf(u, flags, name, "%s=", name);
} else {
_cleanup_free_ char *joined = NULL;
joined = unit_concat_strv(l, UNIT_ESCAPE_SPECIFIERS);
if (!joined)
return -ENOMEM;
r = strv_extend_strv(dirs, l, true);
if (r < 0)
return -ENOMEM;
unit_write_settingf(u, flags, name, "%s=%s", name, joined);
}
}
return 1;
} else if (STR_IN_SET(name, "RuntimeDirectory", "StateDirectory", "CacheDirectory", "LogsDirectory", "ConfigurationDirectory")) {
_cleanup_strv_free_ char **l = NULL;
char **p;
r = sd_bus_message_read_strv(message, &l);
if (r < 0)
return r;
STRV_FOREACH(p, l) {
if (!path_is_normalized(*p))
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "%s= path is not normalized: %s", name, *p);
if (path_is_absolute(*p))
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "%s= path is absolute: %s", name, *p);
if (path_startswith(*p, "private"))
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "%s= path can't be 'private': %s", name, *p);
}
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
ExecDirectoryType i;
ExecDirectory *d;
assert_se((i = exec_directory_type_from_string(name)) >= 0);
d = c->directories + i;
if (strv_isempty(l)) {
d->paths = strv_free(d->paths);
unit_write_settingf(u, flags, name, "%s=", name);
} else {
_cleanup_free_ char *joined = NULL;
r = strv_extend_strv(&d->paths, l, true);
if (r < 0)
return r;
joined = unit_concat_strv(l, UNIT_ESCAPE_SPECIFIERS);
if (!joined)
return -ENOMEM;
unit_write_settingf(u, flags, name, "%s=%s", name, joined);
}
}
return 1;
} else if (STR_IN_SET(name, "AppArmorProfile", "SmackProcessLabel")) {
int ignore;
const char *s;
r = sd_bus_message_read(message, "(bs)", &ignore, &s);
if (r < 0)
return r;
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
char **p;
bool *b;
if (streq(name, "AppArmorProfile")) {
p = &c->apparmor_profile;
b = &c->apparmor_profile_ignore;
} else { /* "SmackProcessLabel" */
p = &c->smack_process_label;
b = &c->smack_process_label_ignore;
}
if (isempty(s)) {
*p = mfree(*p);
*b = false;
} else {
if (free_and_strdup(p, s) < 0)
return -ENOMEM;
*b = ignore;
}
unit_write_settingf(u, flags|UNIT_ESCAPE_SPECIFIERS, name, "%s=%s%s", name, ignore ? "-" : "", strempty(s));
}
return 1;
} else if (STR_IN_SET(name, "BindPaths", "BindReadOnlyPaths")) {
const char *source, *destination;
int ignore_enoent;
uint64_t mount_flags;
bool empty = true;
r = sd_bus_message_enter_container(message, 'a', "(ssbt)");
if (r < 0)
return r;
while ((r = sd_bus_message_read(message, "(ssbt)", &source, &destination, &ignore_enoent, &mount_flags)) > 0) {
if (!path_is_absolute(source))
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Source path %s is not absolute.", source);
if (!path_is_absolute(destination))
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Destination path %s is not absolute.", destination);
if (!IN_SET(mount_flags, 0, MS_REC))
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Unknown mount flags.");
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
r = bind_mount_add(&c->bind_mounts, &c->n_bind_mounts,
&(BindMount) {
.source = strdup(source),
.destination = strdup(destination),
.read_only = !!strstr(name, "ReadOnly"),
.recursive = !!(mount_flags & MS_REC),
.ignore_enoent = ignore_enoent,
});
if (r < 0)
return r;
unit_write_settingf(
u, flags|UNIT_ESCAPE_SPECIFIERS, name,
"%s=%s%s:%s:%s",
name,
ignore_enoent ? "-" : "",
source,
destination,
(mount_flags & MS_REC) ? "rbind" : "norbind");
}
empty = false;
}
if (r < 0)
return r;
r = sd_bus_message_exit_container(message);
if (r < 0)
return r;
if (empty) {
bind_mount_free_many(c->bind_mounts, c->n_bind_mounts);
c->bind_mounts = NULL;
c->n_bind_mounts = 0;
unit_write_settingf(u, flags, name, "%s=", name);
}
return 1;
} else if (streq(name, "TemporaryFileSystem")) {
const char *path, *options;
bool empty = true;
r = sd_bus_message_enter_container(message, 'a', "(ss)");
if (r < 0)
return r;
while ((r = sd_bus_message_read(message, "(ss)", &path, &options)) > 0) {
if (!path_is_absolute(path))
return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Mount point %s is not absolute.", path);
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
r = temporary_filesystem_add(&c->temporary_filesystems, &c->n_temporary_filesystems, path, options);
if (r < 0)
return r;
unit_write_settingf(
u, flags|UNIT_ESCAPE_SPECIFIERS, name,
"%s=%s:%s",
name,
path,
options);
}
empty = false;
}
if (r < 0)
return r;
r = sd_bus_message_exit_container(message);
if (r < 0)
return r;
if (empty) {
temporary_filesystem_free_many(c->temporary_filesystems, c->n_temporary_filesystems);
c->temporary_filesystems = NULL;
c->n_temporary_filesystems = 0;
unit_write_settingf(u, flags, name, "%s=", name);
}
return 1;
} else if ((suffix = startswith(name, "Limit"))) {
const char *soft = NULL;
int ri;
ri = rlimit_from_string(suffix);
if (ri < 0) {
soft = endswith(suffix, "Soft");
if (soft) {
const char *n;
n = strndupa(suffix, soft - suffix);
ri = rlimit_from_string(n);
if (ri >= 0)
name = strjoina("Limit", n);
}
}
if (ri >= 0) {
uint64_t rl;
rlim_t x;
r = sd_bus_message_read(message, "t", &rl);
if (r < 0)
return r;
if (rl == (uint64_t) -1)
x = RLIM_INFINITY;
else {
x = (rlim_t) rl;
if ((uint64_t) x != rl)
return -ERANGE;
}
if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
_cleanup_free_ char *f = NULL;
struct rlimit nl;
if (c->rlimit[ri]) {
nl = *c->rlimit[ri];
if (soft)
nl.rlim_cur = x;
else
nl.rlim_max = x;
} else
/* When the resource limit is not initialized yet, then assign the value to both fields */
nl = (struct rlimit) {
.rlim_cur = x,
.rlim_max = x,
};
r = rlimit_format(&nl, &f);
if (r < 0)
return r;
if (c->rlimit[ri])
*c->rlimit[ri] = nl;
else {
c->rlimit[ri] = newdup(struct rlimit, &nl, 1);
if (!c->rlimit[ri])
return -ENOMEM;
}
unit_write_settingf(u, flags, name, "%s=%s", name, f);
}
return 1;
}
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-269'], 'message': 'core: expose SUID/SGID restriction as new unit setting RestrictSUIDSGID='</s> |
<s>[INST] Given the following code containing errors, provide 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 exec_context_dump(const ExecContext *c, FILE* f, const char *prefix) {
ExecDirectoryType dt;
char **e, **d;
unsigned i;
int r;
assert(c);
assert(f);
prefix = strempty(prefix);
fprintf(f,
"%sUMask: %04o\n"
"%sWorkingDirectory: %s\n"
"%sRootDirectory: %s\n"
"%sNonBlocking: %s\n"
"%sPrivateTmp: %s\n"
"%sPrivateDevices: %s\n"
"%sProtectKernelTunables: %s\n"
"%sProtectKernelModules: %s\n"
"%sProtectControlGroups: %s\n"
"%sPrivateNetwork: %s\n"
"%sPrivateUsers: %s\n"
"%sProtectHome: %s\n"
"%sProtectSystem: %s\n"
"%sMountAPIVFS: %s\n"
"%sIgnoreSIGPIPE: %s\n"
"%sMemoryDenyWriteExecute: %s\n"
"%sRestrictRealtime: %s\n"
"%sKeyringMode: %s\n"
"%sProtectHostname: %s\n",
prefix, c->umask,
prefix, c->working_directory ? c->working_directory : "/",
prefix, c->root_directory ? c->root_directory : "/",
prefix, yes_no(c->non_blocking),
prefix, yes_no(c->private_tmp),
prefix, yes_no(c->private_devices),
prefix, yes_no(c->protect_kernel_tunables),
prefix, yes_no(c->protect_kernel_modules),
prefix, yes_no(c->protect_control_groups),
prefix, yes_no(c->private_network),
prefix, yes_no(c->private_users),
prefix, protect_home_to_string(c->protect_home),
prefix, protect_system_to_string(c->protect_system),
prefix, yes_no(c->mount_apivfs),
prefix, yes_no(c->ignore_sigpipe),
prefix, yes_no(c->memory_deny_write_execute),
prefix, yes_no(c->restrict_realtime),
prefix, exec_keyring_mode_to_string(c->keyring_mode),
prefix, yes_no(c->protect_hostname));
if (c->root_image)
fprintf(f, "%sRootImage: %s\n", prefix, c->root_image);
STRV_FOREACH(e, c->environment)
fprintf(f, "%sEnvironment: %s\n", prefix, *e);
STRV_FOREACH(e, c->environment_files)
fprintf(f, "%sEnvironmentFile: %s\n", prefix, *e);
STRV_FOREACH(e, c->pass_environment)
fprintf(f, "%sPassEnvironment: %s\n", prefix, *e);
STRV_FOREACH(e, c->unset_environment)
fprintf(f, "%sUnsetEnvironment: %s\n", prefix, *e);
fprintf(f, "%sRuntimeDirectoryPreserve: %s\n", prefix, exec_preserve_mode_to_string(c->runtime_directory_preserve_mode));
for (dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
fprintf(f, "%s%sMode: %04o\n", prefix, exec_directory_type_to_string(dt), c->directories[dt].mode);
STRV_FOREACH(d, c->directories[dt].paths)
fprintf(f, "%s%s: %s\n", prefix, exec_directory_type_to_string(dt), *d);
}
if (c->nice_set)
fprintf(f,
"%sNice: %i\n",
prefix, c->nice);
if (c->oom_score_adjust_set)
fprintf(f,
"%sOOMScoreAdjust: %i\n",
prefix, c->oom_score_adjust);
for (i = 0; i < RLIM_NLIMITS; i++)
if (c->rlimit[i]) {
fprintf(f, "%sLimit%s: " RLIM_FMT "\n",
prefix, rlimit_to_string(i), c->rlimit[i]->rlim_max);
fprintf(f, "%sLimit%sSoft: " RLIM_FMT "\n",
prefix, rlimit_to_string(i), c->rlimit[i]->rlim_cur);
}
if (c->ioprio_set) {
_cleanup_free_ char *class_str = NULL;
r = ioprio_class_to_string_alloc(IOPRIO_PRIO_CLASS(c->ioprio), &class_str);
if (r >= 0)
fprintf(f, "%sIOSchedulingClass: %s\n", prefix, class_str);
fprintf(f, "%sIOPriority: %lu\n", prefix, IOPRIO_PRIO_DATA(c->ioprio));
}
if (c->cpu_sched_set) {
_cleanup_free_ char *policy_str = NULL;
r = sched_policy_to_string_alloc(c->cpu_sched_policy, &policy_str);
if (r >= 0)
fprintf(f, "%sCPUSchedulingPolicy: %s\n", prefix, policy_str);
fprintf(f,
"%sCPUSchedulingPriority: %i\n"
"%sCPUSchedulingResetOnFork: %s\n",
prefix, c->cpu_sched_priority,
prefix, yes_no(c->cpu_sched_reset_on_fork));
}
if (c->cpuset) {
fprintf(f, "%sCPUAffinity:", prefix);
for (i = 0; i < c->cpuset_ncpus; i++)
if (CPU_ISSET_S(i, CPU_ALLOC_SIZE(c->cpuset_ncpus), c->cpuset))
fprintf(f, " %u", i);
fputs("\n", f);
}
if (c->timer_slack_nsec != NSEC_INFINITY)
fprintf(f, "%sTimerSlackNSec: "NSEC_FMT "\n", prefix, c->timer_slack_nsec);
fprintf(f,
"%sStandardInput: %s\n"
"%sStandardOutput: %s\n"
"%sStandardError: %s\n",
prefix, exec_input_to_string(c->std_input),
prefix, exec_output_to_string(c->std_output),
prefix, exec_output_to_string(c->std_error));
if (c->std_input == EXEC_INPUT_NAMED_FD)
fprintf(f, "%sStandardInputFileDescriptorName: %s\n", prefix, c->stdio_fdname[STDIN_FILENO]);
if (c->std_output == EXEC_OUTPUT_NAMED_FD)
fprintf(f, "%sStandardOutputFileDescriptorName: %s\n", prefix, c->stdio_fdname[STDOUT_FILENO]);
if (c->std_error == EXEC_OUTPUT_NAMED_FD)
fprintf(f, "%sStandardErrorFileDescriptorName: %s\n", prefix, c->stdio_fdname[STDERR_FILENO]);
if (c->std_input == EXEC_INPUT_FILE)
fprintf(f, "%sStandardInputFile: %s\n", prefix, c->stdio_file[STDIN_FILENO]);
if (c->std_output == EXEC_OUTPUT_FILE)
fprintf(f, "%sStandardOutputFile: %s\n", prefix, c->stdio_file[STDOUT_FILENO]);
if (c->std_output == EXEC_OUTPUT_FILE_APPEND)
fprintf(f, "%sStandardOutputFileToAppend: %s\n", prefix, c->stdio_file[STDOUT_FILENO]);
if (c->std_error == EXEC_OUTPUT_FILE)
fprintf(f, "%sStandardErrorFile: %s\n", prefix, c->stdio_file[STDERR_FILENO]);
if (c->std_error == EXEC_OUTPUT_FILE_APPEND)
fprintf(f, "%sStandardErrorFileToAppend: %s\n", prefix, c->stdio_file[STDERR_FILENO]);
if (c->tty_path)
fprintf(f,
"%sTTYPath: %s\n"
"%sTTYReset: %s\n"
"%sTTYVHangup: %s\n"
"%sTTYVTDisallocate: %s\n",
prefix, c->tty_path,
prefix, yes_no(c->tty_reset),
prefix, yes_no(c->tty_vhangup),
prefix, yes_no(c->tty_vt_disallocate));
if (IN_SET(c->std_output,
EXEC_OUTPUT_SYSLOG,
EXEC_OUTPUT_KMSG,
EXEC_OUTPUT_JOURNAL,
EXEC_OUTPUT_SYSLOG_AND_CONSOLE,
EXEC_OUTPUT_KMSG_AND_CONSOLE,
EXEC_OUTPUT_JOURNAL_AND_CONSOLE) ||
IN_SET(c->std_error,
EXEC_OUTPUT_SYSLOG,
EXEC_OUTPUT_KMSG,
EXEC_OUTPUT_JOURNAL,
EXEC_OUTPUT_SYSLOG_AND_CONSOLE,
EXEC_OUTPUT_KMSG_AND_CONSOLE,
EXEC_OUTPUT_JOURNAL_AND_CONSOLE)) {
_cleanup_free_ char *fac_str = NULL, *lvl_str = NULL;
r = log_facility_unshifted_to_string_alloc(c->syslog_priority >> 3, &fac_str);
if (r >= 0)
fprintf(f, "%sSyslogFacility: %s\n", prefix, fac_str);
r = log_level_to_string_alloc(LOG_PRI(c->syslog_priority), &lvl_str);
if (r >= 0)
fprintf(f, "%sSyslogLevel: %s\n", prefix, lvl_str);
}
if (c->log_level_max >= 0) {
_cleanup_free_ char *t = NULL;
(void) log_level_to_string_alloc(c->log_level_max, &t);
fprintf(f, "%sLogLevelMax: %s\n", prefix, strna(t));
}
if (c->log_rate_limit_interval_usec > 0) {
char buf_timespan[FORMAT_TIMESPAN_MAX];
fprintf(f,
"%sLogRateLimitIntervalSec: %s\n",
prefix, format_timespan(buf_timespan, sizeof(buf_timespan), c->log_rate_limit_interval_usec, USEC_PER_SEC));
}
if (c->log_rate_limit_burst > 0)
fprintf(f, "%sLogRateLimitBurst: %u\n", prefix, c->log_rate_limit_burst);
if (c->n_log_extra_fields > 0) {
size_t j;
for (j = 0; j < c->n_log_extra_fields; j++) {
fprintf(f, "%sLogExtraFields: ", prefix);
fwrite(c->log_extra_fields[j].iov_base,
1, c->log_extra_fields[j].iov_len,
f);
fputc('\n', f);
}
}
if (c->secure_bits) {
_cleanup_free_ char *str = NULL;
r = secure_bits_to_string_alloc(c->secure_bits, &str);
if (r >= 0)
fprintf(f, "%sSecure Bits: %s\n", prefix, str);
}
if (c->capability_bounding_set != CAP_ALL) {
_cleanup_free_ char *str = NULL;
r = capability_set_to_string_alloc(c->capability_bounding_set, &str);
if (r >= 0)
fprintf(f, "%sCapabilityBoundingSet: %s\n", prefix, str);
}
if (c->capability_ambient_set != 0) {
_cleanup_free_ char *str = NULL;
r = capability_set_to_string_alloc(c->capability_ambient_set, &str);
if (r >= 0)
fprintf(f, "%sAmbientCapabilities: %s\n", prefix, str);
}
if (c->user)
fprintf(f, "%sUser: %s\n", prefix, c->user);
if (c->group)
fprintf(f, "%sGroup: %s\n", prefix, c->group);
fprintf(f, "%sDynamicUser: %s\n", prefix, yes_no(c->dynamic_user));
if (!strv_isempty(c->supplementary_groups)) {
fprintf(f, "%sSupplementaryGroups:", prefix);
strv_fprintf(f, c->supplementary_groups);
fputs("\n", f);
}
if (c->pam_name)
fprintf(f, "%sPAMName: %s\n", prefix, c->pam_name);
if (!strv_isempty(c->read_write_paths)) {
fprintf(f, "%sReadWritePaths:", prefix);
strv_fprintf(f, c->read_write_paths);
fputs("\n", f);
}
if (!strv_isempty(c->read_only_paths)) {
fprintf(f, "%sReadOnlyPaths:", prefix);
strv_fprintf(f, c->read_only_paths);
fputs("\n", f);
}
if (!strv_isempty(c->inaccessible_paths)) {
fprintf(f, "%sInaccessiblePaths:", prefix);
strv_fprintf(f, c->inaccessible_paths);
fputs("\n", f);
}
if (c->n_bind_mounts > 0)
for (i = 0; i < c->n_bind_mounts; i++)
fprintf(f, "%s%s: %s%s:%s:%s\n", prefix,
c->bind_mounts[i].read_only ? "BindReadOnlyPaths" : "BindPaths",
c->bind_mounts[i].ignore_enoent ? "-": "",
c->bind_mounts[i].source,
c->bind_mounts[i].destination,
c->bind_mounts[i].recursive ? "rbind" : "norbind");
if (c->n_temporary_filesystems > 0)
for (i = 0; i < c->n_temporary_filesystems; i++) {
TemporaryFileSystem *t = c->temporary_filesystems + i;
fprintf(f, "%sTemporaryFileSystem: %s%s%s\n", prefix,
t->path,
isempty(t->options) ? "" : ":",
strempty(t->options));
}
if (c->utmp_id)
fprintf(f,
"%sUtmpIdentifier: %s\n",
prefix, c->utmp_id);
if (c->selinux_context)
fprintf(f,
"%sSELinuxContext: %s%s\n",
prefix, c->selinux_context_ignore ? "-" : "", c->selinux_context);
if (c->apparmor_profile)
fprintf(f,
"%sAppArmorProfile: %s%s\n",
prefix, c->apparmor_profile_ignore ? "-" : "", c->apparmor_profile);
if (c->smack_process_label)
fprintf(f,
"%sSmackProcessLabel: %s%s\n",
prefix, c->smack_process_label_ignore ? "-" : "", c->smack_process_label);
if (c->personality != PERSONALITY_INVALID)
fprintf(f,
"%sPersonality: %s\n",
prefix, strna(personality_to_string(c->personality)));
fprintf(f,
"%sLockPersonality: %s\n",
prefix, yes_no(c->lock_personality));
if (c->syscall_filter) {
#if HAVE_SECCOMP
Iterator j;
void *id, *val;
bool first = true;
#endif
fprintf(f,
"%sSystemCallFilter: ",
prefix);
if (!c->syscall_whitelist)
fputc('~', f);
#if HAVE_SECCOMP
HASHMAP_FOREACH_KEY(val, id, c->syscall_filter, j) {
_cleanup_free_ char *name = NULL;
const char *errno_name = NULL;
int num = PTR_TO_INT(val);
if (first)
first = false;
else
fputc(' ', f);
name = seccomp_syscall_resolve_num_arch(SCMP_ARCH_NATIVE, PTR_TO_INT(id) - 1);
fputs(strna(name), f);
if (num >= 0) {
errno_name = errno_to_name(num);
if (errno_name)
fprintf(f, ":%s", errno_name);
else
fprintf(f, ":%d", num);
}
}
#endif
fputc('\n', f);
}
if (c->syscall_archs) {
#if HAVE_SECCOMP
Iterator j;
void *id;
#endif
fprintf(f,
"%sSystemCallArchitectures:",
prefix);
#if HAVE_SECCOMP
SET_FOREACH(id, c->syscall_archs, j)
fprintf(f, " %s", strna(seccomp_arch_to_string(PTR_TO_UINT32(id) - 1)));
#endif
fputc('\n', f);
}
if (exec_context_restrict_namespaces_set(c)) {
_cleanup_free_ char *s = NULL;
r = namespace_flags_to_string(c->restrict_namespaces, &s);
if (r >= 0)
fprintf(f, "%sRestrictNamespaces: %s\n",
prefix, s);
}
if (c->network_namespace_path)
fprintf(f,
"%sNetworkNamespacePath: %s\n",
prefix, c->network_namespace_path);
if (c->syscall_errno > 0) {
const char *errno_name;
fprintf(f, "%sSystemCallErrorNumber: ", prefix);
errno_name = errno_to_name(c->syscall_errno);
if (errno_name)
fprintf(f, "%s\n", errno_name);
else
fprintf(f, "%d\n", c->syscall_errno);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-269'], 'message': 'core: expose SUID/SGID restriction as new unit setting RestrictSUIDSGID='</s> |
<s>[INST] Given the following code containing errors, provide 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 unit_patch_contexts(Unit *u) {
CGroupContext *cc;
ExecContext *ec;
unsigned i;
int r;
assert(u);
/* Patch in the manager defaults into the exec and cgroup
* contexts, _after_ the rest of the settings have been
* initialized */
ec = unit_get_exec_context(u);
if (ec) {
/* This only copies in the ones that need memory */
for (i = 0; i < _RLIMIT_MAX; i++)
if (u->manager->rlimit[i] && !ec->rlimit[i]) {
ec->rlimit[i] = newdup(struct rlimit, u->manager->rlimit[i], 1);
if (!ec->rlimit[i])
return -ENOMEM;
}
if (MANAGER_IS_USER(u->manager) &&
!ec->working_directory) {
r = get_home_dir(&ec->working_directory);
if (r < 0)
return r;
/* Allow user services to run, even if the
* home directory is missing */
ec->working_directory_missing_ok = true;
}
if (ec->private_devices)
ec->capability_bounding_set &= ~((UINT64_C(1) << CAP_MKNOD) | (UINT64_C(1) << CAP_SYS_RAWIO));
if (ec->protect_kernel_modules)
ec->capability_bounding_set &= ~(UINT64_C(1) << CAP_SYS_MODULE);
if (ec->dynamic_user) {
if (!ec->user) {
r = user_from_unit_name(u, &ec->user);
if (r < 0)
return r;
}
if (!ec->group) {
ec->group = strdup(ec->user);
if (!ec->group)
return -ENOMEM;
}
/* If the dynamic user option is on, let's make sure that the unit can't leave its UID/GID
* around in the file system or on IPC objects. Hence enforce a strict sandbox. */
ec->private_tmp = true;
ec->remove_ipc = true;
ec->protect_system = PROTECT_SYSTEM_STRICT;
if (ec->protect_home == PROTECT_HOME_NO)
ec->protect_home = PROTECT_HOME_READ_ONLY;
}
}
cc = unit_get_cgroup_context(u);
if (cc && ec) {
if (ec->private_devices &&
cc->device_policy == CGROUP_AUTO)
cc->device_policy = CGROUP_CLOSED;
if (ec->root_image &&
(cc->device_policy != CGROUP_AUTO || cc->device_allow)) {
/* When RootImage= is specified, the following devices are touched. */
r = cgroup_add_device_allow(cc, "/dev/loop-control", "rw");
if (r < 0)
return r;
r = cgroup_add_device_allow(cc, "block-loop", "rwm");
if (r < 0)
return r;
r = cgroup_add_device_allow(cc, "block-blkext", "rwm");
if (r < 0)
return r;
}
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-269'], 'message': 'core: imply NNP and SUID/SGID restriction for DynamicUser=yes service
Let's be safe, rather than sorry. This way DynamicUser=yes services can
neither take benefit of, nor create SUID/SGID binaries.
Given that DynamicUser= is a recent addition only we should be able to
get away with turning this on, even though this is strictly speaking a
binary compatibility breakage.'</s> |
<s>[INST] Given the following code containing errors, provide 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 XMLRPC_AddValueToVector(XMLRPC_VALUE target, XMLRPC_VALUE source) {
if(target && source) {
if(target->type == xmlrpc_vector && target->v &&
target->v->q && target->v->type != xmlrpc_vector_none) {
/* guard against putting value of unknown type into vector */
switch(source->type) {
case xmlrpc_empty:
case xmlrpc_base64:
case xmlrpc_boolean:
case xmlrpc_datetime:
case xmlrpc_double:
case xmlrpc_int:
case xmlrpc_string:
case xmlrpc_vector:
/* Guard against putting a key/val pair into an array vector */
if( !(source->id.len && target->v->type == xmlrpc_vector_array) ) {
if (isDuplicateEntry (target, source)
|| Q_PushTail (target->v->q, XMLRPC_CopyValue (source))) {
return 1;
}
}
else {
fprintf (stderr,
"xmlrpc: attempted to add key/val pair to vector of type array\n");
}
break;
default:
fprintf (stderr,
"xmlrpc: attempted to add value of unknown type to vector\n");
break;
}
}
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'MFH: Fixed bug #46746 (xmlrpc_decode_request outputs non-suppressable error
when given bad data).'</s> |
<s>[INST] Given the following code containing errors, provide 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 xml_element_serialize(xml_element *el, int (*fptr)(void *data, const char *text, int size), void *data, XML_ELEM_OUTPUT_OPTIONS options, int depth)
{
int i;
static STRUCT_XML_ELEM_OUTPUT_OPTIONS default_opts = {xml_elem_pretty, xml_elem_markup_escaping | xml_elem_non_print_escaping, XML_DECL_ENCODING_DEFAULT};
static char whitespace[] = " "
" "
" ";
depth++;
if(!el) {
fprintf(stderr, "Nothing to write\n");
return;
}
if(!options) {
options = &default_opts;
}
/* print xml declaration if at root level */
if(depth == 1) {
xml_elem_writefunc(fptr, XML_DECL_START, data, XML_DECL_START_LEN);
xml_elem_writefunc(fptr, WHITESPACE, data, WHITESPACE_LEN);
xml_elem_writefunc(fptr, XML_DECL_VERSION, data, XML_DECL_VERSION_LEN);
if(options->encoding && *options->encoding) {
xml_elem_writefunc(fptr, WHITESPACE, data, WHITESPACE_LEN);
xml_elem_writefunc(fptr, XML_DECL_ENCODING_ATTR, data, XML_DECL_ENCODING_ATTR_LEN);
xml_elem_writefunc(fptr, EQUALS, data, EQUALS_LEN);
xml_elem_writefunc(fptr, ATTR_DELIMITER, data, ATTR_DELIMITER_LEN);
xml_elem_writefunc(fptr, options->encoding, data, 0);
xml_elem_writefunc(fptr, ATTR_DELIMITER, data, ATTR_DELIMITER_LEN);
}
xml_elem_writefunc(fptr, XML_DECL_END, data, XML_DECL_END_LEN);
if(options->verbosity != xml_elem_no_white_space) {
xml_elem_writefunc(fptr, NEWLINE, data, NEWLINE_LEN);
}
}
if(options->verbosity == xml_elem_pretty && depth > 2) {
xml_elem_writefunc(fptr, whitespace, data, depth - 2);
}
/* begin element */
xml_elem_writefunc(fptr,START_TOKEN_BEGIN, data, START_TOKEN_BEGIN_LEN);
if(el->name) {
xml_elem_writefunc(fptr, el->name, data, 0);
/* write attrs, if any */
if(Q_Size(&el->attrs)) {
xml_element_attr* iter = Q_Head(&el->attrs);
while( iter ) {
xml_elem_writefunc(fptr, WHITESPACE, data, WHITESPACE_LEN);
xml_elem_writefunc(fptr, iter->key, data, 0);
xml_elem_writefunc(fptr, EQUALS, data, EQUALS_LEN);
xml_elem_writefunc(fptr, ATTR_DELIMITER, data, ATTR_DELIMITER_LEN);
xml_elem_writefunc(fptr, iter->val, data, 0);
xml_elem_writefunc(fptr, ATTR_DELIMITER, data, ATTR_DELIMITER_LEN);
iter = Q_Next(&el->attrs);
}
}
}
else {
xml_elem_writefunc(fptr, "None", data, 0);
}
/* if no text and no children, use abbreviated form, eg: <foo/> */
if(!el->text.len && !Q_Size(&el->children)) {
xml_elem_writefunc(fptr, EMPTY_START_TOKEN_END, data, EMPTY_START_TOKEN_END_LEN);
}
/* otherwise, print element contents */
else {
xml_elem_writefunc(fptr, START_TOKEN_END, data, START_TOKEN_END_LEN);
/* print text, if any */
if(el->text.len) {
char* escaped_str = el->text.str;
int buflen = el->text.len;
if(options->escaping && options->escaping != xml_elem_cdata_escaping) {
escaped_str = xml_elem_entity_escape(el->text.str, buflen, &buflen, options->escaping );
if(!escaped_str) {
escaped_str = el->text.str;
}
}
if(options->escaping & xml_elem_cdata_escaping) {
xml_elem_writefunc(fptr, CDATA_BEGIN, data, CDATA_BEGIN_LEN);
}
xml_elem_writefunc(fptr, escaped_str, data, buflen);
if(escaped_str != el->text.str) {
my_free(escaped_str);
}
if(options->escaping & xml_elem_cdata_escaping) {
xml_elem_writefunc(fptr, CDATA_END, data, CDATA_END_LEN);
}
}
/* no text, so print child elems */
else {
xml_element *kids = Q_Head(&el->children);
i = 0;
while( kids ) {
if(i++ == 0) {
if(options->verbosity != xml_elem_no_white_space) {
xml_elem_writefunc(fptr, NEWLINE, data, NEWLINE_LEN);
}
}
xml_element_serialize(kids, fptr, data, options, depth);
kids = Q_Next(&el->children);
}
if(i) {
if(options->verbosity == xml_elem_pretty && depth > 2) {
xml_elem_writefunc(fptr, whitespace, data, depth - 2);
}
}
}
xml_elem_writefunc(fptr, END_TOKEN_BEGIN, data, END_TOKEN_BEGIN_LEN);
xml_elem_writefunc(fptr,el->name ? el->name : "None", data, 0);
xml_elem_writefunc(fptr, END_TOKEN_END, data, END_TOKEN_END_LEN);
}
if(options->verbosity != xml_elem_no_white_space) {
xml_elem_writefunc(fptr, NEWLINE, data, NEWLINE_LEN);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'MFH: Fixed bug #46746 (xmlrpc_decode_request outputs non-suppressable error
when given bad data).'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: utf32be_mbc_to_code(const UChar* p, const UChar* end ARG_UNUSED)
{
return (OnigCodePoint )(((p[0] * 256 + p[1]) * 256 + p[2]) * 256 + p[3]);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #77418 - Heap overflow in utf32be_mbc_to_code'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: utf16be_mbc_to_code(const UChar* p, const UChar* end ARG_UNUSED)
{
OnigCodePoint code;
if (UTF16_IS_SURROGATE_FIRST(*p)) {
code = ((((p[0] - 0xd8) << 2) + ((p[1] & 0xc0) >> 6) + 1) << 16)
+ ((((p[1] & 0x3f) << 2) + (p[2] - 0xdc)) << 8)
+ p[3];
}
else {
code = p[0] * 256 + p[1];
}
return code;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #77418 - Heap overflow in utf32be_mbc_to_code'</s> |
<s>[INST] Given the following code containing errors, provide 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 base64_encode_xmlrpc(struct buffer_st *b, const char *source, int length)
{
int i, hiteof = 0;
int offset = 0;
int olen;
olen = 0;
buffer_new(b);
/* Fill dtable with character encodings. */
for (i = 0; i < 26; i++) {
dtable[i] = 'A' + i;
dtable[26 + i] = 'a' + i;
}
for (i = 0; i < 10; i++) {
dtable[52 + i] = '0' + i;
}
dtable[62] = '+';
dtable[63] = '/';
while (!hiteof) {
unsigned char igroup[3], ogroup[4];
int c, n;
igroup[0] = igroup[1] = igroup[2] = 0;
for (n = 0; n < 3; n++) {
c = *(source++);
offset++;
if (offset > length || offset <= 0) {
hiteof = 1;
break;
}
igroup[n] = (unsigned char) c;
}
if (n > 0) {
ogroup[0] = dtable[igroup[0] >> 2];
ogroup[1] = dtable[((igroup[0] & 3) << 4) | (igroup[1] >> 4)];
ogroup[2] = dtable[((igroup[1] & 0xF) << 2) | (igroup[2] >> 6)];
ogroup[3] = dtable[igroup[2] & 0x3F];
/* Replace characters in output stream with "=" pad
characters if fewer than three characters were
read from the end of the input stream. */
if (n < 3) {
ogroup[3] = '=';
if (n < 2) {
ogroup[2] = '=';
}
}
for (i = 0; i < 4; i++) {
buffer_add(b, ogroup[i]);
if (!(b->offset % 72)) {
/* buffer_add(b, '\r'); */
buffer_add(b, '\n');
}
}
}
}
/* buffer_add(b, '\r'); */
buffer_add(b, '\n');
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #77380 (Global out of bounds read in xmlrpc base64 code)'</s> |
<s>[INST] Given the following code containing errors, provide 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 base64_encode_xmlrpc(struct buffer_st *b, const char *source, int length)
{
int i, hiteof = 0;
int offset = 0;
buffer_new(b);
/* Fill dtable with character encodings. */
for (i = 0; i < 26; i++) {
dtable[i] = 'A' + i;
dtable[26 + i] = 'a' + i;
}
for (i = 0; i < 10; i++) {
dtable[52 + i] = '0' + i;
}
dtable[62] = '+';
dtable[63] = '/';
while (!hiteof) {
unsigned char igroup[3], ogroup[4];
int c, n;
igroup[0] = igroup[1] = igroup[2] = 0;
for (n = 0; n < 3; n++) {
c = *(source++);
offset++;
if (offset > length || offset <= 0) {
hiteof = 1;
break;
}
igroup[n] = (unsigned char) c;
}
if (n > 0) {
ogroup[0] = dtable[igroup[0] >> 2];
ogroup[1] = dtable[((igroup[0] & 3) << 4) | (igroup[1] >> 4)];
ogroup[2] = dtable[((igroup[1] & 0xF) << 2) | (igroup[2] >> 6)];
ogroup[3] = dtable[igroup[2] & 0x3F];
/* Replace characters in output stream with "=" pad
characters if fewer than three characters were
read from the end of the input stream. */
if (n < 3) {
ogroup[3] = '=';
if (n < 2) {
ogroup[2] = '=';
}
}
for (i = 0; i < 4; i++) {
buffer_add(b, ogroup[i]);
if (!(b->offset % 72)) {
/* buffer_add(b, '\r'); */
buffer_add(b, '\n');
}
}
}
}
/* buffer_add(b, '\r'); */
buffer_add(b, '\n');
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #77380 (Global out of bounds read in xmlrpc base64 code)
(cherry picked from commit 1cc2182bcc81e185c14837e659d12b268cb99d63)'</s> |
<s>[INST] Given the following code containing errors, provide 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 u_char *php_parserr(u_char *cp, u_char *end, querybuf *answer, int type_to_fetch, int store, int raw, zval *subarray)
{
u_short type, class, dlen;
u_long ttl;
long n, i;
u_short s;
u_char *tp, *p;
char name[MAXHOSTNAMELEN];
int have_v6_break = 0, in_v6_break = 0;
ZVAL_UNDEF(subarray);
n = dn_expand(answer->qb2, end, cp, name, sizeof(name) - 2);
if (n < 0) {
return NULL;
}
cp += n;
CHECKCP(10);
GETSHORT(type, cp);
GETSHORT(class, cp);
GETLONG(ttl, cp);
GETSHORT(dlen, cp);
CHECKCP(dlen);
if (type_to_fetch != T_ANY && type != type_to_fetch) {
cp += dlen;
return cp;
}
if (!store) {
cp += dlen;
return cp;
}
array_init(subarray);
add_assoc_string(subarray, "host", name);
add_assoc_string(subarray, "class", "IN");
add_assoc_long(subarray, "ttl", ttl);
(void) class;
if (raw) {
add_assoc_long(subarray, "type", type);
add_assoc_stringl(subarray, "data", (char*) cp, (uint) dlen);
cp += dlen;
return cp;
}
switch (type) {
case DNS_T_A:
CHECKCP(4);
add_assoc_string(subarray, "type", "A");
snprintf(name, sizeof(name), "%d.%d.%d.%d", cp[0], cp[1], cp[2], cp[3]);
add_assoc_string(subarray, "ip", name);
cp += dlen;
break;
case DNS_T_MX:
CHECKCP(2);
add_assoc_string(subarray, "type", "MX");
GETSHORT(n, cp);
add_assoc_long(subarray, "pri", n);
/* no break; */
case DNS_T_CNAME:
if (type == DNS_T_CNAME) {
add_assoc_string(subarray, "type", "CNAME");
}
/* no break; */
case DNS_T_NS:
if (type == DNS_T_NS) {
add_assoc_string(subarray, "type", "NS");
}
/* no break; */
case DNS_T_PTR:
if (type == DNS_T_PTR) {
add_assoc_string(subarray, "type", "PTR");
}
n = dn_expand(answer->qb2, end, cp, name, (sizeof name) - 2);
if (n < 0) {
return NULL;
}
cp += n;
add_assoc_string(subarray, "target", name);
break;
case DNS_T_HINFO:
/* See RFC 1010 for values */
add_assoc_string(subarray, "type", "HINFO");
CHECKCP(1);
n = *cp & 0xFF;
cp++;
CHECKCP(n);
add_assoc_stringl(subarray, "cpu", (char*)cp, n);
cp += n;
CHECKCP(1);
n = *cp & 0xFF;
cp++;
CHECKCP(n);
add_assoc_stringl(subarray, "os", (char*)cp, n);
cp += n;
break;
case DNS_T_CAA:
/* See RFC 6844 for values https://tools.ietf.org/html/rfc6844 */
add_assoc_string(subarray, "type", "CAA");
// 1 flag byte
CHECKCP(1);
n = *cp & 0xFF;
add_assoc_long(subarray, "flags", n);
cp++;
// Tag length (1 byte)
CHECKCP(1);
n = *cp & 0xFF;
cp++;
CHECKCP(n);
add_assoc_stringl(subarray, "tag", (char*)cp, n);
cp += n;
n = dlen - n - 2;
CHECKCP(n);
add_assoc_stringl(subarray, "value", (char*)cp, n);
cp += n;
break;
case DNS_T_TXT:
{
int l1 = 0, l2 = 0;
zval entries;
zend_string *tp;
add_assoc_string(subarray, "type", "TXT");
tp = zend_string_alloc(dlen, 0);
array_init(&entries);
while (l1 < dlen) {
n = cp[l1];
if ((l1 + n) >= dlen) {
// Invalid chunk length, truncate
n = dlen - (l1 + 1);
}
if (n) {
memcpy(ZSTR_VAL(tp) + l2 , cp + l1 + 1, n);
add_next_index_stringl(&entries, (char *) cp + l1 + 1, n);
}
l1 = l1 + n + 1;
l2 = l2 + n;
}
ZSTR_VAL(tp)[l2] = '\0';
ZSTR_LEN(tp) = l2;
cp += dlen;
add_assoc_str(subarray, "txt", tp);
add_assoc_zval(subarray, "entries", &entries);
}
break;
case DNS_T_SOA:
add_assoc_string(subarray, "type", "SOA");
n = dn_expand(answer->qb2, end, cp, name, (sizeof name) -2);
if (n < 0) {
return NULL;
}
cp += n;
add_assoc_string(subarray, "mname", name);
n = dn_expand(answer->qb2, end, cp, name, (sizeof name) -2);
if (n < 0) {
return NULL;
}
cp += n;
add_assoc_string(subarray, "rname", name);
CHECKCP(5*4);
GETLONG(n, cp);
add_assoc_long(subarray, "serial", n);
GETLONG(n, cp);
add_assoc_long(subarray, "refresh", n);
GETLONG(n, cp);
add_assoc_long(subarray, "retry", n);
GETLONG(n, cp);
add_assoc_long(subarray, "expire", n);
GETLONG(n, cp);
add_assoc_long(subarray, "minimum-ttl", n);
break;
case DNS_T_AAAA:
tp = (u_char*)name;
CHECKCP(8*2);
for(i=0; i < 8; i++) {
GETSHORT(s, cp);
if (s != 0) {
if (tp > (u_char *)name) {
in_v6_break = 0;
tp[0] = ':';
tp++;
}
tp += sprintf((char*)tp,"%x",s);
} else {
if (!have_v6_break) {
have_v6_break = 1;
in_v6_break = 1;
tp[0] = ':';
tp++;
} else if (!in_v6_break) {
tp[0] = ':';
tp++;
tp[0] = '0';
tp++;
}
}
}
if (have_v6_break && in_v6_break) {
tp[0] = ':';
tp++;
}
tp[0] = '\0';
add_assoc_string(subarray, "type", "AAAA");
add_assoc_string(subarray, "ipv6", name);
break;
case DNS_T_A6:
p = cp;
add_assoc_string(subarray, "type", "A6");
CHECKCP(1);
n = ((int)cp[0]) & 0xFF;
cp++;
add_assoc_long(subarray, "masklen", n);
tp = (u_char*)name;
if (n > 15) {
have_v6_break = 1;
in_v6_break = 1;
tp[0] = ':';
tp++;
}
if (n % 16 > 8) {
/* Partial short */
if (cp[0] != 0) {
if (tp > (u_char *)name) {
in_v6_break = 0;
tp[0] = ':';
tp++;
}
sprintf((char*)tp, "%x", cp[0] & 0xFF);
} else {
if (!have_v6_break) {
have_v6_break = 1;
in_v6_break = 1;
tp[0] = ':';
tp++;
} else if (!in_v6_break) {
tp[0] = ':';
tp++;
tp[0] = '0';
tp++;
}
}
cp++;
}
for (i = (n + 8) / 16; i < 8; i++) {
CHECKCP(2);
GETSHORT(s, cp);
if (s != 0) {
if (tp > (u_char *)name) {
in_v6_break = 0;
tp[0] = ':';
tp++;
}
tp += sprintf((char*)tp,"%x",s);
} else {
if (!have_v6_break) {
have_v6_break = 1;
in_v6_break = 1;
tp[0] = ':';
tp++;
} else if (!in_v6_break) {
tp[0] = ':';
tp++;
tp[0] = '0';
tp++;
}
}
}
if (have_v6_break && in_v6_break) {
tp[0] = ':';
tp++;
}
tp[0] = '\0';
add_assoc_string(subarray, "ipv6", name);
if (cp < p + dlen) {
n = dn_expand(answer->qb2, end, cp, name, (sizeof name) - 2);
if (n < 0) {
return NULL;
}
cp += n;
add_assoc_string(subarray, "chain", name);
}
break;
case DNS_T_SRV:
CHECKCP(3*2);
add_assoc_string(subarray, "type", "SRV");
GETSHORT(n, cp);
add_assoc_long(subarray, "pri", n);
GETSHORT(n, cp);
add_assoc_long(subarray, "weight", n);
GETSHORT(n, cp);
add_assoc_long(subarray, "port", n);
n = dn_expand(answer->qb2, end, cp, name, (sizeof name) - 2);
if (n < 0) {
return NULL;
}
cp += n;
add_assoc_string(subarray, "target", name);
break;
case DNS_T_NAPTR:
CHECKCP(2*2);
add_assoc_string(subarray, "type", "NAPTR");
GETSHORT(n, cp);
add_assoc_long(subarray, "order", n);
GETSHORT(n, cp);
add_assoc_long(subarray, "pref", n);
CHECKCP(1);
n = (cp[0] & 0xFF);
cp++;
CHECKCP(n);
add_assoc_stringl(subarray, "flags", (char*)cp, n);
cp += n;
CHECKCP(1);
n = (cp[0] & 0xFF);
cp++;
CHECKCP(n);
add_assoc_stringl(subarray, "services", (char*)cp, n);
cp += n;
CHECKCP(1);
n = (cp[0] & 0xFF);
cp++;
CHECKCP(n);
add_assoc_stringl(subarray, "regex", (char*)cp, n);
cp += n;
n = dn_expand(answer->qb2, end, cp, name, (sizeof name) - 2);
if (n < 0) {
return NULL;
}
cp += n;
add_assoc_string(subarray, "replacement", name);
break;
default:
zval_ptr_dtor(subarray);
ZVAL_UNDEF(subarray);
cp += dlen;
break;
}
return cp;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Fix #77369 - memcpy with negative length via crafted DNS response'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: jio_vsnprintf(char * str, int n, const char * format, va_list args)
{
int result;
Trc_SC_vsnprintf_Entry(str, n, format);
#if defined(WIN32) && !defined(WIN32_IBMC)
result = _vsnprintf( str, n, format, args );
#else
result = vsprintf( str, format, args );
#endif
Trc_SC_vsnprintf_Exit(result);
return result;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'Clean up jio_snprintf and jio_vfprintf
Fixes https://bugs.eclipse.org/bugs/show_bug.cgi?id=543659
Signed-off-by: Peter Bain <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int expand_downwards(struct vm_area_struct *vma,
unsigned long address)
{
struct mm_struct *mm = vma->vm_mm;
struct vm_area_struct *prev;
int error;
address &= PAGE_MASK;
error = security_mmap_addr(address);
if (error)
return error;
/* Enforce stack_guard_gap */
prev = vma->vm_prev;
/* Check that both stack segments have the same anon_vma? */
if (prev && !(prev->vm_flags & VM_GROWSDOWN) &&
(prev->vm_flags & (VM_WRITE|VM_READ|VM_EXEC))) {
if (address - prev->vm_end < stack_guard_gap)
return -ENOMEM;
}
/* We must make sure the anon_vma is allocated. */
if (unlikely(anon_vma_prepare(vma)))
return -ENOMEM;
/*
* vma->vm_start/vm_end cannot change under us because the caller
* is required to hold the mmap_sem in read mode. We need the
* anon_vma lock to serialize against concurrent expand_stacks.
*/
anon_vma_lock_write(vma->anon_vma);
/* Somebody else might have raced and expanded it already */
if (address < vma->vm_start) {
unsigned long size, grow;
size = vma->vm_end - address;
grow = (vma->vm_start - address) >> PAGE_SHIFT;
error = -ENOMEM;
if (grow <= vma->vm_pgoff) {
error = acct_stack_growth(vma, size, grow);
if (!error) {
/*
* vma_gap_update() doesn't support concurrent
* updates, but we only hold a shared mmap_sem
* lock here, so we need to protect against
* concurrent vma expansions.
* anon_vma_lock_write() doesn't help here, as
* we don't guarantee that all growable vmas
* in a mm share the same root anon vma.
* So, we reuse mm->page_table_lock to guard
* against concurrent vma expansions.
*/
spin_lock(&mm->page_table_lock);
if (vma->vm_flags & VM_LOCKED)
mm->locked_vm += grow;
vm_stat_account(mm, vma->vm_flags, grow);
anon_vma_interval_tree_pre_update_vma(vma);
vma->vm_start = address;
vma->vm_pgoff -= grow;
anon_vma_interval_tree_post_update_vma(vma);
vma_gap_update(vma);
spin_unlock(&mm->page_table_lock);
perf_event_mmap(vma);
}
}
}
anon_vma_unlock_write(vma->anon_vma);
khugepaged_enter_vma_merge(vma, vma->vm_flags);
validate_mm(mm);
return error;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'mm: enforce min addr even if capable() in expand_downwards()
security_mmap_addr() does a capability check with current_cred(), but
we can reach this code from contexts like a VFS write handler where
current_cred() must not be used.
This can be abused on systems without SMAP to make NULL pointer
dereferences exploitable again.
Fixes: 8869477a49c3 ("security: protect from stack expansion into low vm addresses")
Cc: [email protected]
Signed-off-by: Jann Horn <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: HiiDrawImage (
IN CONST EFI_HII_IMAGE_PROTOCOL *This,
IN EFI_HII_DRAW_FLAGS Flags,
IN CONST EFI_IMAGE_INPUT *Image,
IN OUT EFI_IMAGE_OUTPUT **Blt,
IN UINTN BltX,
IN UINTN BltY
)
{
EFI_STATUS Status;
HII_DATABASE_PRIVATE_DATA *Private;
BOOLEAN Transparent;
EFI_IMAGE_OUTPUT *ImageOut;
EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BltBuffer;
UINTN BufferLen;
UINTN Width;
UINTN Height;
UINTN Xpos;
UINTN Ypos;
UINTN OffsetY1;
UINTN OffsetY2;
EFI_FONT_DISPLAY_INFO *FontInfo;
UINTN Index;
if (This == NULL || Image == NULL || Blt == NULL) {
return EFI_INVALID_PARAMETER;
}
if ((Flags & EFI_HII_DRAW_FLAG_CLIP) == EFI_HII_DRAW_FLAG_CLIP && *Blt == NULL) {
return EFI_INVALID_PARAMETER;
}
if ((Flags & EFI_HII_DRAW_FLAG_TRANSPARENT) == EFI_HII_DRAW_FLAG_TRANSPARENT) {
return EFI_INVALID_PARAMETER;
}
FontInfo = NULL;
//
// Check whether the image will be drawn transparently or opaquely.
//
Transparent = FALSE;
if ((Flags & EFI_HII_DRAW_FLAG_TRANSPARENT) == EFI_HII_DRAW_FLAG_FORCE_TRANS) {
Transparent = TRUE;
} else if ((Flags & EFI_HII_DRAW_FLAG_TRANSPARENT) == EFI_HII_DRAW_FLAG_FORCE_OPAQUE){
Transparent = FALSE;
} else {
//
// Now EFI_HII_DRAW_FLAG_DEFAULT is set, whether image will be drawn depending
// on the image's transparency setting.
//
if ((Image->Flags & EFI_IMAGE_TRANSPARENT) == EFI_IMAGE_TRANSPARENT) {
Transparent = TRUE;
}
}
//
// Image cannot be drawn transparently if Blt points to NULL on entry.
// Currently output to Screen transparently is not supported, either.
//
if (Transparent) {
if (*Blt == NULL) {
return EFI_INVALID_PARAMETER;
} else if ((Flags & EFI_HII_DIRECT_TO_SCREEN) == EFI_HII_DIRECT_TO_SCREEN) {
return EFI_INVALID_PARAMETER;
}
}
Private = HII_IMAGE_DATABASE_PRIVATE_DATA_FROM_THIS (This);
//
// When Blt points to a non-NULL on entry, this image will be drawn onto
// this bitmap or screen pointed by "*Blt" and EFI_HII_DRAW_FLAG_CLIP is implied.
// Otherwise a new bitmap will be allocated to hold this image.
//
if (*Blt != NULL) {
//
// Clip the image by (Width, Height)
//
Width = Image->Width;
Height = Image->Height;
if (Width > (*Blt)->Width - BltX) {
Width = (*Blt)->Width - BltX;
}
if (Height > (*Blt)->Height - BltY) {
Height = (*Blt)->Height - BltY;
}
BufferLen = Width * Height * sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL);
BltBuffer = (EFI_GRAPHICS_OUTPUT_BLT_PIXEL *) AllocateZeroPool (BufferLen);
if (BltBuffer == NULL) {
return EFI_OUT_OF_RESOURCES;
}
if (Width == Image->Width && Height == Image->Height) {
CopyMem (BltBuffer, Image->Bitmap, BufferLen);
} else {
for (Ypos = 0; Ypos < Height; Ypos++) {
OffsetY1 = Image->Width * Ypos;
OffsetY2 = Width * Ypos;
for (Xpos = 0; Xpos < Width; Xpos++) {
BltBuffer[OffsetY2 + Xpos] = Image->Bitmap[OffsetY1 + Xpos];
}
}
}
//
// Draw the image to existing bitmap or screen depending on flag.
//
if ((Flags & EFI_HII_DIRECT_TO_SCREEN) == EFI_HII_DIRECT_TO_SCREEN) {
//
// Caller should make sure the current UGA console is grarphic mode.
//
//
// Write the image directly to the output device specified by Screen.
//
Status = (*Blt)->Image.Screen->Blt (
(*Blt)->Image.Screen,
BltBuffer,
EfiBltBufferToVideo,
0,
0,
BltX,
BltY,
Width,
Height,
0
);
} else {
//
// Draw the image onto the existing bitmap specified by Bitmap.
//
Status = ImageToBlt (
BltBuffer,
BltX,
BltY,
Width,
Height,
Transparent,
Blt
);
}
FreePool (BltBuffer);
return Status;
} else {
//
// Allocate a new bitmap to hold the incoming image.
//
Width = Image->Width + BltX;
Height = Image->Height + BltY;
BufferLen = Width * Height * sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL);
BltBuffer = (EFI_GRAPHICS_OUTPUT_BLT_PIXEL *) AllocateZeroPool (BufferLen);
if (BltBuffer == NULL) {
return EFI_OUT_OF_RESOURCES;
}
ImageOut = (EFI_IMAGE_OUTPUT *) AllocateZeroPool (sizeof (EFI_IMAGE_OUTPUT));
if (ImageOut == NULL) {
FreePool (BltBuffer);
return EFI_OUT_OF_RESOURCES;
}
ImageOut->Width = (UINT16) Width;
ImageOut->Height = (UINT16) Height;
ImageOut->Image.Bitmap = BltBuffer;
//
// BUGBUG: Now all the "blank" pixels are filled with system default background
// color. Not sure if it need to be updated or not.
//
Status = GetSystemFont (Private, &FontInfo, NULL);
if (EFI_ERROR (Status)) {
FreePool (BltBuffer);
FreePool (ImageOut);
return Status;
}
ASSERT (FontInfo != NULL);
for (Index = 0; Index < Width * Height; Index++) {
BltBuffer[Index] = FontInfo->BackgroundColor;
}
FreePool (FontInfo);
//
// Draw the incoming image to the new created image.
//
*Blt = ImageOut;
return ImageToBlt (
Image->Bitmap,
BltX,
BltY,
Image->Width,
Image->Height,
Transparent,
Blt
);
}
}
; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'MdeModulePkg/HiiDatabase: Fix potential integer overflow (CVE-2018-12181)
REF: https://bugzilla.tianocore.org/show_bug.cgi?id=1135
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Ray Ni <[email protected]>
Cc: Dandan Bi <[email protected]>
Cc: Hao A Wu <[email protected]>
Reviewed-by: Hao Wu <[email protected]>
Reviewed-by: Jian J Wang <[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: HiiNewImage (
IN CONST EFI_HII_IMAGE_PROTOCOL *This,
IN EFI_HII_HANDLE PackageList,
OUT EFI_IMAGE_ID *ImageId,
IN CONST EFI_IMAGE_INPUT *Image
)
{
HII_DATABASE_PRIVATE_DATA *Private;
HII_DATABASE_PACKAGE_LIST_INSTANCE *PackageListNode;
HII_IMAGE_PACKAGE_INSTANCE *ImagePackage;
EFI_HII_IMAGE_BLOCK *ImageBlocks;
UINT32 NewBlockSize;
if (This == NULL || ImageId == NULL || Image == NULL || Image->Bitmap == NULL) {
return EFI_INVALID_PARAMETER;
}
Private = HII_IMAGE_DATABASE_PRIVATE_DATA_FROM_THIS (This);
PackageListNode = LocatePackageList (&Private->DatabaseList, PackageList);
if (PackageListNode == NULL) {
return EFI_NOT_FOUND;
}
EfiAcquireLock (&mHiiDatabaseLock);
NewBlockSize = sizeof (EFI_HII_IIBT_IMAGE_24BIT_BLOCK) - sizeof (EFI_HII_RGB_PIXEL) +
BITMAP_LEN_24_BIT ((UINT32) Image->Width, Image->Height);
//
// Get the image package in the package list,
// or create a new image package if image package does not exist.
//
if (PackageListNode->ImagePkg != NULL) {
ImagePackage = PackageListNode->ImagePkg;
//
// Output the image id of the incoming image being inserted, which is the
// image id of the EFI_HII_IIBT_END block of old image package.
//
*ImageId = 0;
GetImageIdOrAddress (ImagePackage->ImageBlock, ImageId);
//
// Update the package's image block by appending the new block to the end.
//
ImageBlocks = AllocatePool (ImagePackage->ImageBlockSize + NewBlockSize);
if (ImageBlocks == NULL) {
EfiReleaseLock (&mHiiDatabaseLock);
return EFI_OUT_OF_RESOURCES;
}
//
// Copy the original content.
//
CopyMem (
ImageBlocks,
ImagePackage->ImageBlock,
ImagePackage->ImageBlockSize - sizeof (EFI_HII_IIBT_END_BLOCK)
);
FreePool (ImagePackage->ImageBlock);
ImagePackage->ImageBlock = ImageBlocks;
//
// Point to the very last block.
//
ImageBlocks = (EFI_HII_IMAGE_BLOCK *) (
(UINT8 *) ImageBlocks + ImagePackage->ImageBlockSize - sizeof (EFI_HII_IIBT_END_BLOCK)
);
//
// Update the length record.
//
ImagePackage->ImageBlockSize += NewBlockSize;
ImagePackage->ImagePkgHdr.Header.Length += NewBlockSize;
PackageListNode->PackageListHdr.PackageLength += NewBlockSize;
} else {
//
// The specified package list does not contain image package.
// Create one to add this image block.
//
ImagePackage = (HII_IMAGE_PACKAGE_INSTANCE *) AllocateZeroPool (sizeof (HII_IMAGE_PACKAGE_INSTANCE));
if (ImagePackage == NULL) {
EfiReleaseLock (&mHiiDatabaseLock);
return EFI_OUT_OF_RESOURCES;
}
//
// Output the image id of the incoming image being inserted, which is the
// first image block so that id is initially to one.
//
*ImageId = 1;
//
// Fill in image package header.
//
ImagePackage->ImagePkgHdr.Header.Length = sizeof (EFI_HII_IMAGE_PACKAGE_HDR) + NewBlockSize + sizeof (EFI_HII_IIBT_END_BLOCK);
ImagePackage->ImagePkgHdr.Header.Type = EFI_HII_PACKAGE_IMAGES;
ImagePackage->ImagePkgHdr.ImageInfoOffset = sizeof (EFI_HII_IMAGE_PACKAGE_HDR);
ImagePackage->ImagePkgHdr.PaletteInfoOffset = 0;
//
// Fill in palette info.
//
ImagePackage->PaletteBlock = NULL;
ImagePackage->PaletteInfoSize = 0;
//
// Fill in image blocks.
//
ImagePackage->ImageBlockSize = NewBlockSize + sizeof (EFI_HII_IIBT_END_BLOCK);
ImagePackage->ImageBlock = AllocateZeroPool (NewBlockSize + sizeof (EFI_HII_IIBT_END_BLOCK));
if (ImagePackage->ImageBlock == NULL) {
FreePool (ImagePackage);
EfiReleaseLock (&mHiiDatabaseLock);
return EFI_OUT_OF_RESOURCES;
}
ImageBlocks = ImagePackage->ImageBlock;
//
// Insert this image package.
//
PackageListNode->ImagePkg = ImagePackage;
PackageListNode->PackageListHdr.PackageLength += ImagePackage->ImagePkgHdr.Header.Length;
}
//
// Append the new block here
//
if (Image->Flags == EFI_IMAGE_TRANSPARENT) {
ImageBlocks->BlockType = EFI_HII_IIBT_IMAGE_24BIT_TRANS;
} else {
ImageBlocks->BlockType = EFI_HII_IIBT_IMAGE_24BIT;
}
WriteUnaligned16 ((VOID *) &((EFI_HII_IIBT_IMAGE_24BIT_BLOCK *) ImageBlocks)->Bitmap.Width, Image->Width);
WriteUnaligned16 ((VOID *) &((EFI_HII_IIBT_IMAGE_24BIT_BLOCK *) ImageBlocks)->Bitmap.Height, Image->Height);
CopyGopToRgbPixel (((EFI_HII_IIBT_IMAGE_24BIT_BLOCK *) ImageBlocks)->Bitmap.Bitmap, Image->Bitmap, (UINT32) Image->Width * Image->Height);
//
// Append the block end
//
ImageBlocks = (EFI_HII_IMAGE_BLOCK *) ((UINT8 *) ImageBlocks + NewBlockSize);
ImageBlocks->BlockType = EFI_HII_IIBT_END;
//
// Check whether need to get the contents of HiiDataBase.
// Only after ReadyToBoot to do the export.
//
if (gExportAfterReadyToBoot) {
HiiGetDatabaseInfo(&Private->HiiDatabase);
}
EfiReleaseLock (&mHiiDatabaseLock);
return EFI_SUCCESS;
}
; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'MdeModulePkg/HiiDatabase: Fix potential integer overflow (CVE-2018-12181)
REF: https://bugzilla.tianocore.org/show_bug.cgi?id=1135
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Ray Ni <[email protected]>
Cc: Dandan Bi <[email protected]>
Cc: Hao A Wu <[email protected]>
Reviewed-by: Hao Wu <[email protected]>
Reviewed-by: Jian J Wang <[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: Output4bitPixel (
IN OUT EFI_IMAGE_INPUT *Image,
IN UINT8 *Data,
IN EFI_HII_IMAGE_PALETTE_INFO *PaletteInfo
)
{
UINT16 Xpos;
UINT16 Ypos;
UINTN OffsetY;
EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BitMapPtr;
EFI_GRAPHICS_OUTPUT_BLT_PIXEL PaletteValue[16];
EFI_HII_IMAGE_PALETTE_INFO *Palette;
UINTN PaletteSize;
UINT16 PaletteNum;
UINT8 Byte;
ASSERT (Image != NULL && Data != NULL && PaletteInfo != NULL);
BitMapPtr = Image->Bitmap;
//
// The bitmap should allocate each color index starting from 0.
//
PaletteSize = 0;
CopyMem (&PaletteSize, PaletteInfo, sizeof (UINT16));
PaletteSize += sizeof (UINT16);
Palette = AllocateZeroPool (PaletteSize);
ASSERT (Palette != NULL);
if (Palette == NULL) {
return;
}
CopyMem (Palette, PaletteInfo, PaletteSize);
PaletteNum = (UINT16)(Palette->PaletteSize / sizeof (EFI_HII_RGB_PIXEL));
ZeroMem (PaletteValue, sizeof (PaletteValue));
CopyRgbToGopPixel (PaletteValue, Palette->PaletteValue, PaletteNum);
FreePool (Palette);
//
// Convert the pixel from 4 bit to corresponding color.
//
for (Ypos = 0; Ypos < Image->Height; Ypos++) {
OffsetY = BITMAP_LEN_4_BIT (Image->Width, Ypos);
//
// All bits in these bytes are meaningful
//
for (Xpos = 0; Xpos < Image->Width / 2; Xpos++) {
Byte = *(Data + OffsetY + Xpos);
BitMapPtr[Ypos * Image->Width + Xpos * 2] = PaletteValue[Byte >> 4];
BitMapPtr[Ypos * Image->Width + Xpos * 2 + 1] = PaletteValue[Byte & 0x0F];
}
if (Image->Width % 2 != 0) {
//
// Padding bits in this byte should be ignored.
//
Byte = *(Data + OffsetY + Xpos);
BitMapPtr[Ypos * Image->Width + Xpos * 2] = PaletteValue[Byte >> 4];
}
}
}
; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'MdeModulePkg/HiiImage: Fix stack overflow when corrupted BMP is parsed (CVE-2018-12181)
REF: https://bugzilla.tianocore.org/show_bug.cgi?id=1135
For 4bit BMP, there are only 2^4 = 16 colors in the palette.
But when a corrupted BMP contains more than 16 colors in the palette,
today's implementation wrongly copies all colors to the local
PaletteValue[16] array which causes stack overflow.
The similar issue also exists in the logic to handle 8bit BMP.
The patch fixes the issue by only copies the first 16 or 256 colors
in the palette depending on the BMP type.
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Ray Ni <[email protected]>
Cc: Liming Gao <[email protected]>
Cc: Jiewen Yao <[email protected]>
Reviewed-by: Jian J Wang <[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
kex_method_diffie_hellman_group_exchange_sha256_key_exchange
(LIBSSH2_SESSION * session, key_exchange_state_low_t * key_state)
{
unsigned long p_len, g_len;
int ret = 0;
int rc;
if(key_state->state == libssh2_NB_state_idle) {
key_state->p = _libssh2_bn_init();
key_state->g = _libssh2_bn_init();
/* Ask for a P and G pair */
#ifdef LIBSSH2_DH_GEX_NEW
key_state->request[0] = SSH_MSG_KEX_DH_GEX_REQUEST;
_libssh2_htonu32(key_state->request + 1, LIBSSH2_DH_GEX_MINGROUP);
_libssh2_htonu32(key_state->request + 5, LIBSSH2_DH_GEX_OPTGROUP);
_libssh2_htonu32(key_state->request + 9, LIBSSH2_DH_GEX_MAXGROUP);
key_state->request_len = 13;
_libssh2_debug(session, LIBSSH2_TRACE_KEX,
"Initiating Diffie-Hellman Group-Exchange (New Method SHA256)");
#else
key_state->request[0] = SSH_MSG_KEX_DH_GEX_REQUEST_OLD;
_libssh2_htonu32(key_state->request + 1, LIBSSH2_DH_GEX_OPTGROUP);
key_state->request_len = 5;
_libssh2_debug(session, LIBSSH2_TRACE_KEX,
"Initiating Diffie-Hellman Group-Exchange (Old Method SHA256)");
#endif
key_state->state = libssh2_NB_state_created;
}
if(key_state->state == libssh2_NB_state_created) {
rc = _libssh2_transport_send(session, key_state->request,
key_state->request_len, NULL, 0);
if(rc == LIBSSH2_ERROR_EAGAIN) {
return rc;
}
else if(rc) {
ret = _libssh2_error(session, rc,
"Unable to send Group Exchange Request SHA256");
goto dh_gex_clean_exit;
}
key_state->state = libssh2_NB_state_sent;
}
if(key_state->state == libssh2_NB_state_sent) {
rc = _libssh2_packet_require(session, SSH_MSG_KEX_DH_GEX_GROUP,
&key_state->data, &key_state->data_len,
0, NULL, 0, &key_state->req_state);
if(rc == LIBSSH2_ERROR_EAGAIN) {
return rc;
}
else if(rc) {
ret = _libssh2_error(session, rc,
"Timeout waiting for GEX_GROUP reply SHA256");
goto dh_gex_clean_exit;
}
key_state->state = libssh2_NB_state_sent1;
}
if(key_state->state == libssh2_NB_state_sent1) {
unsigned char *s = key_state->data + 1;
p_len = _libssh2_ntohu32(s);
s += 4;
_libssh2_bn_from_bin(key_state->p, p_len, s);
s += p_len;
g_len = _libssh2_ntohu32(s);
s += 4;
_libssh2_bn_from_bin(key_state->g, g_len, s);
ret = diffie_hellman_sha256(session, key_state->g, key_state->p, p_len,
SSH_MSG_KEX_DH_GEX_INIT,
SSH_MSG_KEX_DH_GEX_REPLY,
key_state->data + 1,
key_state->data_len - 1,
&key_state->exchange_state);
if(ret == LIBSSH2_ERROR_EAGAIN) {
return ret;
}
LIBSSH2_FREE(session, key_state->data);
}
dh_gex_clean_exit:
key_state->state = libssh2_NB_state_idle;
_libssh2_bn_free(key_state->g);
key_state->g = NULL;
_libssh2_bn_free(key_state->p);
key_state->p = NULL;
; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Security fixes (#315)
* Bounds checks
Fixes for CVEs
https://www.libssh2.org/CVE-2019-3863.html
https://www.libssh2.org/CVE-2019-3856.html
* Packet length bounds check
CVE
https://www.libssh2.org/CVE-2019-3855.html
* Response length check
CVE
https://www.libssh2.org/CVE-2019-3859.html
* Bounds check
CVE
https://www.libssh2.org/CVE-2019-3857.html
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
and additional data validation
* Check bounds before reading into buffers
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
* declare SIZE_MAX and UINT_MAX if needed'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: _libssh2_userauth_publickey(LIBSSH2_SESSION *session,
const char *username,
unsigned int username_len,
const unsigned char *pubkeydata,
unsigned long pubkeydata_len,
LIBSSH2_USERAUTH_PUBLICKEY_SIGN_FUNC((*sign_callback)),
void *abstract)
{
unsigned char reply_codes[4] =
{ SSH_MSG_USERAUTH_SUCCESS, SSH_MSG_USERAUTH_FAILURE,
SSH_MSG_USERAUTH_PK_OK, 0
};
int rc;
unsigned char *s;
if(session->userauth_pblc_state == libssh2_NB_state_idle) {
/*
* The call to _libssh2_ntohu32 later relies on pubkeydata having at
* least 4 valid bytes containing the length of the method name.
*/
if(pubkeydata_len < 4)
return _libssh2_error(session, LIBSSH2_ERROR_PUBLICKEY_UNVERIFIED,
"Invalid public key, too short");
/* Zero the whole thing out */
memset(&session->userauth_pblc_packet_requirev_state, 0,
sizeof(session->userauth_pblc_packet_requirev_state));
/*
* As an optimisation, userauth_publickey_fromfile reuses a
* previously allocated copy of the method name to avoid an extra
* allocation/free.
* For other uses, we allocate and populate it here.
*/
if(!session->userauth_pblc_method) {
session->userauth_pblc_method_len = _libssh2_ntohu32(pubkeydata);
if(session->userauth_pblc_method_len > pubkeydata_len)
/* the method length simply cannot be longer than the entire
passed in data, so we use this to detect crazy input
data */
return _libssh2_error(session,
LIBSSH2_ERROR_PUBLICKEY_UNVERIFIED,
"Invalid public key");
session->userauth_pblc_method =
LIBSSH2_ALLOC(session, session->userauth_pblc_method_len);
if(!session->userauth_pblc_method) {
return _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
"Unable to allocate memory for public key "
"data");
}
memcpy(session->userauth_pblc_method, pubkeydata + 4,
session->userauth_pblc_method_len);
}
/*
* The length of the method name read from plaintext prefix in the
* file must match length embedded in the key.
* TODO: The data should match too but we don't check that. Should we?
*/
else if(session->userauth_pblc_method_len !=
_libssh2_ntohu32(pubkeydata))
return _libssh2_error(session, LIBSSH2_ERROR_PUBLICKEY_UNVERIFIED,
"Invalid public key");
/*
* 45 = packet_type(1) + username_len(4) + servicename_len(4) +
* service_name(14)"ssh-connection" + authmethod_len(4) +
* authmethod(9)"publickey" + sig_included(1)'\0' + algmethod_len(4) +
* publickey_len(4)
*/
session->userauth_pblc_packet_len =
username_len + session->userauth_pblc_method_len + pubkeydata_len +
45;
/*
* Preallocate space for an overall length, method name again, and the
* signature, which won't be any larger than the size of the
* publickeydata itself.
*
* Note that the 'pubkeydata_len' extra bytes allocated here will not
* be used in this first send, but will be used in the later one where
* this same allocation is re-used.
*/
s = session->userauth_pblc_packet =
LIBSSH2_ALLOC(session,
session->userauth_pblc_packet_len + 4 +
(4 + session->userauth_pblc_method_len)
+ (4 + pubkeydata_len));
if(!session->userauth_pblc_packet) {
LIBSSH2_FREE(session, session->userauth_pblc_method);
session->userauth_pblc_method = NULL;
return _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
"Out of memory");
}
*s++ = SSH_MSG_USERAUTH_REQUEST;
_libssh2_store_str(&s, username, username_len);
_libssh2_store_str(&s, "ssh-connection", 14);
_libssh2_store_str(&s, "publickey", 9);
session->userauth_pblc_b = s;
/* Not sending signature with *this* packet */
*s++ = 0;
_libssh2_store_str(&s, (const char *)session->userauth_pblc_method,
session->userauth_pblc_method_len);
_libssh2_store_str(&s, (const char *)pubkeydata, pubkeydata_len);
_libssh2_debug(session, LIBSSH2_TRACE_AUTH,
"Attempting publickey authentication");
session->userauth_pblc_state = libssh2_NB_state_created;
}
if(session->userauth_pblc_state == libssh2_NB_state_created) {
rc = _libssh2_transport_send(session, session->userauth_pblc_packet,
session->userauth_pblc_packet_len,
NULL, 0);
if(rc == LIBSSH2_ERROR_EAGAIN)
return _libssh2_error(session, LIBSSH2_ERROR_EAGAIN, "Would block");
else if(rc) {
LIBSSH2_FREE(session, session->userauth_pblc_packet);
session->userauth_pblc_packet = NULL;
LIBSSH2_FREE(session, session->userauth_pblc_method);
session->userauth_pblc_method = NULL;
session->userauth_pblc_state = libssh2_NB_state_idle;
return _libssh2_error(session, LIBSSH2_ERROR_SOCKET_SEND,
"Unable to send userauth-publickey request");
}
session->userauth_pblc_state = libssh2_NB_state_sent;
}
if(session->userauth_pblc_state == libssh2_NB_state_sent) {
rc = _libssh2_packet_requirev(session, reply_codes,
&session->userauth_pblc_data,
&session->userauth_pblc_data_len, 0,
NULL, 0,
&session->
userauth_pblc_packet_requirev_state);
if(rc == LIBSSH2_ERROR_EAGAIN) {
return _libssh2_error(session, LIBSSH2_ERROR_EAGAIN, "Would block");
}
else if(rc) {
LIBSSH2_FREE(session, session->userauth_pblc_packet);
session->userauth_pblc_packet = NULL;
LIBSSH2_FREE(session, session->userauth_pblc_method);
session->userauth_pblc_method = NULL;
session->userauth_pblc_state = libssh2_NB_state_idle;
return _libssh2_error(session, LIBSSH2_ERROR_PUBLICKEY_UNVERIFIED,
"Waiting for USERAUTH response");
}
if(session->userauth_pblc_data[0] == SSH_MSG_USERAUTH_SUCCESS) {
_libssh2_debug(session, LIBSSH2_TRACE_AUTH,
"Pubkey authentication prematurely successful");
/*
* God help any SSH server that allows an UNVERIFIED
* public key to validate the user
*/
LIBSSH2_FREE(session, session->userauth_pblc_data);
session->userauth_pblc_data = NULL;
LIBSSH2_FREE(session, session->userauth_pblc_packet);
session->userauth_pblc_packet = NULL;
LIBSSH2_FREE(session, session->userauth_pblc_method);
session->userauth_pblc_method = NULL;
session->state |= LIBSSH2_STATE_AUTHENTICATED;
session->userauth_pblc_state = libssh2_NB_state_idle;
return 0;
}
if(session->userauth_pblc_data[0] == SSH_MSG_USERAUTH_FAILURE) {
/* This public key is not allowed for this user on this server */
LIBSSH2_FREE(session, session->userauth_pblc_data);
session->userauth_pblc_data = NULL;
LIBSSH2_FREE(session, session->userauth_pblc_packet);
session->userauth_pblc_packet = NULL;
LIBSSH2_FREE(session, session->userauth_pblc_method);
session->userauth_pblc_method = NULL;
session->userauth_pblc_state = libssh2_NB_state_idle;
return _libssh2_error(session, LIBSSH2_ERROR_AUTHENTICATION_FAILED,
"Username/PublicKey combination invalid");
}
/* Semi-Success! */
LIBSSH2_FREE(session, session->userauth_pblc_data);
session->userauth_pblc_data = NULL;
*session->userauth_pblc_b = 0x01;
session->userauth_pblc_state = libssh2_NB_state_sent1;
}
if(session->userauth_pblc_state == libssh2_NB_state_sent1) {
unsigned char *buf;
unsigned char *sig;
size_t sig_len;
s = buf = LIBSSH2_ALLOC(session, 4 + session->session_id_len
+ session->userauth_pblc_packet_len);
if(!buf) {
return _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
"Unable to allocate memory for "
"userauth-publickey signed data");
}
_libssh2_store_str(&s, (const char *)session->session_id,
session->session_id_len);
memcpy(s, session->userauth_pblc_packet,
session->userauth_pblc_packet_len);
s += session->userauth_pblc_packet_len;
rc = sign_callback(session, &sig, &sig_len, buf, s - buf, abstract);
LIBSSH2_FREE(session, buf);
if(rc == LIBSSH2_ERROR_EAGAIN) {
return _libssh2_error(session, LIBSSH2_ERROR_EAGAIN, "Would block");
}
else if(rc) {
LIBSSH2_FREE(session, session->userauth_pblc_method);
session->userauth_pblc_method = NULL;
LIBSSH2_FREE(session, session->userauth_pblc_packet);
session->userauth_pblc_packet = NULL;
session->userauth_pblc_state = libssh2_NB_state_idle;
return _libssh2_error(session, LIBSSH2_ERROR_PUBLICKEY_UNVERIFIED,
"Callback returned error");
}
/*
* If this function was restarted, pubkeydata_len might still be 0
* which will cause an unnecessary but harmless realloc here.
*/
if(sig_len > pubkeydata_len) {
unsigned char *newpacket;
/* Should *NEVER* happen, but...well.. better safe than sorry */
newpacket = LIBSSH2_REALLOC(session,
session->userauth_pblc_packet,
session->userauth_pblc_packet_len + 4 +
(4 + session->userauth_pblc_method_len)
+ (4 + sig_len)); /* PK sigblob */
if(!newpacket) {
LIBSSH2_FREE(session, sig);
LIBSSH2_FREE(session, session->userauth_pblc_packet);
session->userauth_pblc_packet = NULL;
LIBSSH2_FREE(session, session->userauth_pblc_method);
session->userauth_pblc_method = NULL;
session->userauth_pblc_state = libssh2_NB_state_idle;
return _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
"Failed allocating additional space for "
"userauth-publickey packet");
}
session->userauth_pblc_packet = newpacket;
}
s = session->userauth_pblc_packet + session->userauth_pblc_packet_len;
session->userauth_pblc_b = NULL;
_libssh2_store_u32(&s,
4 + session->userauth_pblc_method_len + 4 + sig_len);
_libssh2_store_str(&s, (const char *)session->userauth_pblc_method,
session->userauth_pblc_method_len);
LIBSSH2_FREE(session, session->userauth_pblc_method);
session->userauth_pblc_method = NULL;
_libssh2_store_str(&s, (const char *)sig, sig_len);
LIBSSH2_FREE(session, sig);
_libssh2_debug(session, LIBSSH2_TRACE_AUTH,
"Attempting publickey authentication -- phase 2");
session->userauth_pblc_s = s;
session->userauth_pblc_state = libssh2_NB_state_sent2;
}
if(session->userauth_pblc_state == libssh2_NB_state_sent2) {
rc = _libssh2_transport_send(session, session->userauth_pblc_packet,
session->userauth_pblc_s -
session->userauth_pblc_packet,
NULL, 0);
if(rc == LIBSSH2_ERROR_EAGAIN) {
return _libssh2_error(session, LIBSSH2_ERROR_EAGAIN, "Would block");
}
else if(rc) {
LIBSSH2_FREE(session, session->userauth_pblc_packet);
session->userauth_pblc_packet = NULL;
session->userauth_pblc_state = libssh2_NB_state_idle;
return _libssh2_error(session, LIBSSH2_ERROR_SOCKET_SEND,
"Unable to send userauth-publickey request");
}
LIBSSH2_FREE(session, session->userauth_pblc_packet);
session->userauth_pblc_packet = NULL;
session->userauth_pblc_state = libssh2_NB_state_sent3;
}
/* PK_OK is no longer valid */
reply_codes[2] = 0;
rc = _libssh2_packet_requirev(session, reply_codes,
&session->userauth_pblc_data,
&session->userauth_pblc_data_len, 0, NULL, 0,
&session->userauth_pblc_packet_requirev_state);
if(rc == LIBSSH2_ERROR_EAGAIN) {
return _libssh2_error(session, LIBSSH2_ERROR_EAGAIN,
"Would block requesting userauth list");
}
else if(rc) {
session->userauth_pblc_state = libssh2_NB_state_idle;
return _libssh2_error(session, LIBSSH2_ERROR_PUBLICKEY_UNVERIFIED,
"Waiting for publickey USERAUTH response");
}
if(session->userauth_pblc_data[0] == SSH_MSG_USERAUTH_SUCCESS) {
_libssh2_debug(session, LIBSSH2_TRACE_AUTH,
"Publickey authentication successful");
/* We are us and we've proved it. */
LIBSSH2_FREE(session, session->userauth_pblc_data);
session->userauth_pblc_data = NULL;
session->state |= LIBSSH2_STATE_AUTHENTICATED;
session->userauth_pblc_state = libssh2_NB_state_idle;
return 0;
}
/* This public key is not allowed for this user on this server */
LIBSSH2_FREE(session, session->userauth_pblc_data);
session->userauth_pblc_data = NULL;
session->userauth_pblc_state = libssh2_NB_state_idle;
return _libssh2_error(session, LIBSSH2_ERROR_PUBLICKEY_UNVERIFIED,
"Invalid signature for supplied public key, or bad "
"username/public key combination");
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Security fixes (#315)
* Bounds checks
Fixes for CVEs
https://www.libssh2.org/CVE-2019-3863.html
https://www.libssh2.org/CVE-2019-3856.html
* Packet length bounds check
CVE
https://www.libssh2.org/CVE-2019-3855.html
* Response length check
CVE
https://www.libssh2.org/CVE-2019-3859.html
* Bounds check
CVE
https://www.libssh2.org/CVE-2019-3857.html
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
and additional data validation
* Check bounds before reading into buffers
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
* declare SIZE_MAX and UINT_MAX if needed'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: userauth_password(LIBSSH2_SESSION *session,
const char *username, unsigned int username_len,
const unsigned char *password, unsigned int password_len,
LIBSSH2_PASSWD_CHANGEREQ_FUNC((*passwd_change_cb)))
{
unsigned char *s;
static const unsigned char reply_codes[4] =
{ SSH_MSG_USERAUTH_SUCCESS, SSH_MSG_USERAUTH_FAILURE,
SSH_MSG_USERAUTH_PASSWD_CHANGEREQ, 0
};
int rc;
if(session->userauth_pswd_state == libssh2_NB_state_idle) {
/* Zero the whole thing out */
memset(&session->userauth_pswd_packet_requirev_state, 0,
sizeof(session->userauth_pswd_packet_requirev_state));
/*
* 40 = packet_type(1) + username_len(4) + service_len(4) +
* service(14)"ssh-connection" + method_len(4) + method(8)"password" +
* chgpwdbool(1) + password_len(4) */
session->userauth_pswd_data_len = username_len + 40;
session->userauth_pswd_data0 =
(unsigned char) ~SSH_MSG_USERAUTH_PASSWD_CHANGEREQ;
/* TODO: remove this alloc with a fixed buffer in the session
struct */
s = session->userauth_pswd_data =
LIBSSH2_ALLOC(session, session->userauth_pswd_data_len);
if(!session->userauth_pswd_data) {
return _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
"Unable to allocate memory for "
"userauth-password request");
}
*(s++) = SSH_MSG_USERAUTH_REQUEST;
_libssh2_store_str(&s, username, username_len);
_libssh2_store_str(&s, "ssh-connection", sizeof("ssh-connection") - 1);
_libssh2_store_str(&s, "password", sizeof("password") - 1);
*s++ = '\0';
_libssh2_store_u32(&s, password_len);
/* 'password' is sent separately */
_libssh2_debug(session, LIBSSH2_TRACE_AUTH,
"Attempting to login using password authentication");
session->userauth_pswd_state = libssh2_NB_state_created;
}
if(session->userauth_pswd_state == libssh2_NB_state_created) {
rc = _libssh2_transport_send(session, session->userauth_pswd_data,
session->userauth_pswd_data_len,
password, password_len);
if(rc == LIBSSH2_ERROR_EAGAIN) {
return _libssh2_error(session, LIBSSH2_ERROR_EAGAIN,
"Would block writing password request");
}
/* now free the sent packet */
LIBSSH2_FREE(session, session->userauth_pswd_data);
session->userauth_pswd_data = NULL;
if(rc) {
session->userauth_pswd_state = libssh2_NB_state_idle;
return _libssh2_error(session, LIBSSH2_ERROR_SOCKET_SEND,
"Unable to send userauth-password request");
}
session->userauth_pswd_state = libssh2_NB_state_sent;
}
password_response:
if((session->userauth_pswd_state == libssh2_NB_state_sent)
|| (session->userauth_pswd_state == libssh2_NB_state_sent1)
|| (session->userauth_pswd_state == libssh2_NB_state_sent2)) {
if(session->userauth_pswd_state == libssh2_NB_state_sent) {
rc = _libssh2_packet_requirev(session, reply_codes,
&session->userauth_pswd_data,
&session->userauth_pswd_data_len,
0, NULL, 0,
&session->
userauth_pswd_packet_requirev_state);
if(rc) {
if(rc != LIBSSH2_ERROR_EAGAIN)
session->userauth_pswd_state = libssh2_NB_state_idle;
return _libssh2_error(session, rc,
"Waiting for password response");
}
if(session->userauth_pswd_data[0] == SSH_MSG_USERAUTH_SUCCESS) {
_libssh2_debug(session, LIBSSH2_TRACE_AUTH,
"Password authentication successful");
LIBSSH2_FREE(session, session->userauth_pswd_data);
session->userauth_pswd_data = NULL;
session->state |= LIBSSH2_STATE_AUTHENTICATED;
session->userauth_pswd_state = libssh2_NB_state_idle;
return 0;
}
else if(session->userauth_pswd_data[0] == SSH_MSG_USERAUTH_FAILURE) {
_libssh2_debug(session, LIBSSH2_TRACE_AUTH,
"Password authentication failed");
LIBSSH2_FREE(session, session->userauth_pswd_data);
session->userauth_pswd_data = NULL;
session->userauth_pswd_state = libssh2_NB_state_idle;
return _libssh2_error(session,
LIBSSH2_ERROR_AUTHENTICATION_FAILED,
"Authentication failed "
"(username/password)");
}
session->userauth_pswd_newpw = NULL;
session->userauth_pswd_newpw_len = 0;
session->userauth_pswd_state = libssh2_NB_state_sent1;
}
if((session->userauth_pswd_data[0] ==
SSH_MSG_USERAUTH_PASSWD_CHANGEREQ)
|| (session->userauth_pswd_data0 ==
SSH_MSG_USERAUTH_PASSWD_CHANGEREQ)) {
session->userauth_pswd_data0 = SSH_MSG_USERAUTH_PASSWD_CHANGEREQ;
if((session->userauth_pswd_state == libssh2_NB_state_sent1) ||
(session->userauth_pswd_state == libssh2_NB_state_sent2)) {
if(session->userauth_pswd_state == libssh2_NB_state_sent1) {
_libssh2_debug(session, LIBSSH2_TRACE_AUTH,
"Password change required");
LIBSSH2_FREE(session, session->userauth_pswd_data);
session->userauth_pswd_data = NULL;
}
if(passwd_change_cb) {
if(session->userauth_pswd_state == libssh2_NB_state_sent1) {
passwd_change_cb(session,
&session->userauth_pswd_newpw,
&session->userauth_pswd_newpw_len,
&session->abstract);
if(!session->userauth_pswd_newpw) {
return _libssh2_error(session,
LIBSSH2_ERROR_PASSWORD_EXPIRED,
"Password expired, and "
"callback failed");
}
/* basic data_len + newpw_len(4) */
session->userauth_pswd_data_len =
username_len + password_len + 44;
s = session->userauth_pswd_data =
LIBSSH2_ALLOC(session,
session->userauth_pswd_data_len);
if(!session->userauth_pswd_data) {
LIBSSH2_FREE(session,
session->userauth_pswd_newpw);
session->userauth_pswd_newpw = NULL;
return _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
"Unable to allocate memory "
"for userauth password "
"change request");
}
*(s++) = SSH_MSG_USERAUTH_REQUEST;
_libssh2_store_str(&s, username, username_len);
_libssh2_store_str(&s, "ssh-connection",
sizeof("ssh-connection") - 1);
_libssh2_store_str(&s, "password",
sizeof("password") - 1);
*s++ = 0x01;
_libssh2_store_str(&s, (char *)password, password_len);
_libssh2_store_u32(&s,
session->userauth_pswd_newpw_len);
/* send session->userauth_pswd_newpw separately */
session->userauth_pswd_state = libssh2_NB_state_sent2;
}
if(session->userauth_pswd_state == libssh2_NB_state_sent2) {
rc = _libssh2_transport_send(session,
session->userauth_pswd_data,
session->userauth_pswd_data_len,
(unsigned char *)
session->userauth_pswd_newpw,
session->userauth_pswd_newpw_len);
if(rc == LIBSSH2_ERROR_EAGAIN) {
return _libssh2_error(session, LIBSSH2_ERROR_EAGAIN,
"Would block waiting");
}
/* free the allocated packets again */
LIBSSH2_FREE(session, session->userauth_pswd_data);
session->userauth_pswd_data = NULL;
LIBSSH2_FREE(session, session->userauth_pswd_newpw);
session->userauth_pswd_newpw = NULL;
if(rc) {
return _libssh2_error(session,
LIBSSH2_ERROR_SOCKET_SEND,
"Unable to send userauth "
"password-change request");
}
/*
* Ugliest use of goto ever. Blame it on the
* askN => requirev migration.
*/
session->userauth_pswd_state = libssh2_NB_state_sent;
goto password_response;
}
}
}
else {
session->userauth_pswd_state = libssh2_NB_state_idle;
return _libssh2_error(session, LIBSSH2_ERROR_PASSWORD_EXPIRED,
"Password Expired, and no callback "
"specified");
}
}
}
/* FAILURE */
LIBSSH2_FREE(session, session->userauth_pswd_data);
session->userauth_pswd_data = NULL;
session->userauth_pswd_state = libssh2_NB_state_idle;
return _libssh2_error(session, LIBSSH2_ERROR_AUTHENTICATION_FAILED,
"Authentication failed");
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Security fixes (#315)
* Bounds checks
Fixes for CVEs
https://www.libssh2.org/CVE-2019-3863.html
https://www.libssh2.org/CVE-2019-3856.html
* Packet length bounds check
CVE
https://www.libssh2.org/CVE-2019-3855.html
* Response length check
CVE
https://www.libssh2.org/CVE-2019-3859.html
* Bounds check
CVE
https://www.libssh2.org/CVE-2019-3857.html
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
and additional data validation
* Check bounds before reading into buffers
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
* declare SIZE_MAX and UINT_MAX if needed'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: _libssh2_packet_add(LIBSSH2_SESSION * session, unsigned char *data,
size_t datalen, int macstate)
{
int rc = 0;
char *message = NULL;
char *language = NULL;
size_t message_len = 0;
size_t language_len = 0;
LIBSSH2_CHANNEL *channelp = NULL;
size_t data_head = 0;
unsigned char msg = data[0];
switch(session->packAdd_state) {
case libssh2_NB_state_idle:
_libssh2_debug(session, LIBSSH2_TRACE_TRANS,
"Packet type %d received, length=%d",
(int) msg, (int) datalen);
if((macstate == LIBSSH2_MAC_INVALID) &&
(!session->macerror ||
LIBSSH2_MACERROR(session, (char *) data, datalen))) {
/* Bad MAC input, but no callback set or non-zero return from the
callback */
LIBSSH2_FREE(session, data);
return _libssh2_error(session, LIBSSH2_ERROR_INVALID_MAC,
"Invalid MAC received");
}
session->packAdd_state = libssh2_NB_state_allocated;
break;
case libssh2_NB_state_jump1:
goto libssh2_packet_add_jump_point1;
case libssh2_NB_state_jump2:
goto libssh2_packet_add_jump_point2;
case libssh2_NB_state_jump3:
goto libssh2_packet_add_jump_point3;
case libssh2_NB_state_jump4:
goto libssh2_packet_add_jump_point4;
case libssh2_NB_state_jump5:
goto libssh2_packet_add_jump_point5;
default: /* nothing to do */
break;
}
if(session->packAdd_state == libssh2_NB_state_allocated) {
/* A couple exceptions to the packet adding rule: */
switch(msg) {
/*
byte SSH_MSG_DISCONNECT
uint32 reason code
string description in ISO-10646 UTF-8 encoding [RFC3629]
string language tag [RFC3066]
*/
case SSH_MSG_DISCONNECT:
if(datalen >= 5) {
size_t reason = _libssh2_ntohu32(data + 1);
if(datalen >= 9) {
message_len = _libssh2_ntohu32(data + 5);
if(message_len < datalen-13) {
/* 9 = packet_type(1) + reason(4) + message_len(4) */
message = (char *) data + 9;
language_len = _libssh2_ntohu32(data + 9 + message_len);
language = (char *) data + 9 + message_len + 4;
if(language_len > (datalen-13-message_len)) {
/* bad input, clear info */
language = message = NULL;
language_len = message_len = 0;
}
}
else
/* bad size, clear it */
message_len = 0;
}
if(session->ssh_msg_disconnect) {
LIBSSH2_DISCONNECT(session, reason, message,
message_len, language, language_len);
}
_libssh2_debug(session, LIBSSH2_TRACE_TRANS,
"Disconnect(%d): %s(%s)", reason,
message, language);
}
LIBSSH2_FREE(session, data);
session->socket_state = LIBSSH2_SOCKET_DISCONNECTED;
session->packAdd_state = libssh2_NB_state_idle;
return _libssh2_error(session, LIBSSH2_ERROR_SOCKET_DISCONNECT,
"socket disconnect");
/*
byte SSH_MSG_IGNORE
string data
*/
case SSH_MSG_IGNORE:
if(datalen >= 2) {
if(session->ssh_msg_ignore) {
LIBSSH2_IGNORE(session, (char *) data + 1, datalen - 1);
}
}
else if(session->ssh_msg_ignore) {
LIBSSH2_IGNORE(session, "", 0);
}
LIBSSH2_FREE(session, data);
session->packAdd_state = libssh2_NB_state_idle;
return 0;
/*
byte SSH_MSG_DEBUG
boolean always_display
string message in ISO-10646 UTF-8 encoding [RFC3629]
string language tag [RFC3066]
*/
case SSH_MSG_DEBUG:
if(datalen >= 2) {
int always_display = data[1];
if(datalen >= 6) {
message_len = _libssh2_ntohu32(data + 2);
if(message_len <= (datalen - 10)) {
/* 6 = packet_type(1) + display(1) + message_len(4) */
message = (char *) data + 6;
language_len = _libssh2_ntohu32(data + 6 + message_len);
if(language_len <= (datalen - 10 - message_len))
language = (char *) data + 10 + message_len;
}
}
if(session->ssh_msg_debug) {
LIBSSH2_DEBUG(session, always_display, message,
message_len, language, language_len);
}
}
/*
* _libssh2_debug will actually truncate this for us so
* that it's not an inordinate about of data
*/
_libssh2_debug(session, LIBSSH2_TRACE_TRANS,
"Debug Packet: %s", message);
LIBSSH2_FREE(session, data);
session->packAdd_state = libssh2_NB_state_idle;
return 0;
/*
byte SSH_MSG_GLOBAL_REQUEST
string request name in US-ASCII only
boolean want reply
.... request-specific data follows
*/
case SSH_MSG_GLOBAL_REQUEST:
if(datalen >= 5) {
uint32_t len = 0;
unsigned char want_reply = 0;
len = _libssh2_ntohu32(data + 1);
if(datalen >= (6 + len)) {
want_reply = data[5 + len];
_libssh2_debug(session,
LIBSSH2_TRACE_CONN,
"Received global request type %.*s (wr %X)",
len, data + 5, want_reply);
}
if(want_reply) {
static const unsigned char packet =
SSH_MSG_REQUEST_FAILURE;
libssh2_packet_add_jump_point5:
session->packAdd_state = libssh2_NB_state_jump5;
rc = _libssh2_transport_send(session, &packet, 1, NULL, 0);
if(rc == LIBSSH2_ERROR_EAGAIN)
return rc;
}
}
LIBSSH2_FREE(session, data);
session->packAdd_state = libssh2_NB_state_idle;
return 0;
/*
byte SSH_MSG_CHANNEL_EXTENDED_DATA
uint32 recipient channel
uint32 data_type_code
string data
*/
case SSH_MSG_CHANNEL_EXTENDED_DATA:
/* streamid(4) */
data_head += 4;
/* fall-through */
/*
byte SSH_MSG_CHANNEL_DATA
uint32 recipient channel
string data
*/
case SSH_MSG_CHANNEL_DATA:
/* packet_type(1) + channelno(4) + datalen(4) */
data_head += 9;
if(datalen >= data_head)
channelp =
_libssh2_channel_locate(session,
_libssh2_ntohu32(data + 1));
if(!channelp) {
_libssh2_error(session, LIBSSH2_ERROR_CHANNEL_UNKNOWN,
"Packet received for unknown channel");
LIBSSH2_FREE(session, data);
session->packAdd_state = libssh2_NB_state_idle;
return 0;
}
#ifdef LIBSSH2DEBUG
{
uint32_t stream_id = 0;
if(msg == SSH_MSG_CHANNEL_EXTENDED_DATA)
stream_id = _libssh2_ntohu32(data + 5);
_libssh2_debug(session, LIBSSH2_TRACE_CONN,
"%d bytes packet_add() for %lu/%lu/%lu",
(int) (datalen - data_head),
channelp->local.id,
channelp->remote.id,
stream_id);
}
#endif
if((channelp->remote.extended_data_ignore_mode ==
LIBSSH2_CHANNEL_EXTENDED_DATA_IGNORE) &&
(msg == SSH_MSG_CHANNEL_EXTENDED_DATA)) {
/* Pretend we didn't receive this */
LIBSSH2_FREE(session, data);
_libssh2_debug(session, LIBSSH2_TRACE_CONN,
"Ignoring extended data and refunding %d bytes",
(int) (datalen - 13));
if(channelp->read_avail + datalen - data_head >=
channelp->remote.window_size)
datalen = channelp->remote.window_size -
channelp->read_avail + data_head;
channelp->remote.window_size -= datalen - data_head;
_libssh2_debug(session, LIBSSH2_TRACE_CONN,
"shrinking window size by %lu bytes to %lu, read_avail %lu",
datalen - data_head,
channelp->remote.window_size,
channelp->read_avail);
session->packAdd_channelp = channelp;
/* Adjust the window based on the block we just freed */
libssh2_packet_add_jump_point1:
session->packAdd_state = libssh2_NB_state_jump1;
rc = _libssh2_channel_receive_window_adjust(session->
packAdd_channelp,
datalen - 13,
1, NULL);
if(rc == LIBSSH2_ERROR_EAGAIN)
return rc;
session->packAdd_state = libssh2_NB_state_idle;
return 0;
}
/*
* REMEMBER! remote means remote as source of data,
* NOT remote window!
*/
if(channelp->remote.packet_size < (datalen - data_head)) {
/*
* Spec says we MAY ignore bytes sent beyond
* packet_size
*/
_libssh2_error(session,
LIBSSH2_ERROR_CHANNEL_PACKET_EXCEEDED,
"Packet contains more data than we offered"
" to receive, truncating");
datalen = channelp->remote.packet_size + data_head;
}
if(channelp->remote.window_size <= channelp->read_avail) {
/*
* Spec says we MAY ignore bytes sent beyond
* window_size
*/
_libssh2_error(session,
LIBSSH2_ERROR_CHANNEL_WINDOW_EXCEEDED,
"The current receive window is full,"
" data ignored");
LIBSSH2_FREE(session, data);
session->packAdd_state = libssh2_NB_state_idle;
return 0;
}
/* Reset EOF status */
channelp->remote.eof = 0;
if(channelp->read_avail + datalen - data_head >
channelp->remote.window_size) {
_libssh2_error(session,
LIBSSH2_ERROR_CHANNEL_WINDOW_EXCEEDED,
"Remote sent more data than current "
"window allows, truncating");
datalen = channelp->remote.window_size -
channelp->read_avail + data_head;
}
/* Update the read_avail counter. The window size will be
* updated once the data is actually read from the queue
* from an upper layer */
channelp->read_avail += datalen - data_head;
_libssh2_debug(session, LIBSSH2_TRACE_CONN,
"increasing read_avail by %lu bytes to %lu/%lu",
(long)(datalen - data_head),
(long)channelp->read_avail,
(long)channelp->remote.window_size);
break;
/*
byte SSH_MSG_CHANNEL_EOF
uint32 recipient channel
*/
case SSH_MSG_CHANNEL_EOF:
if(datalen >= 5)
channelp =
_libssh2_channel_locate(session,
_libssh2_ntohu32(data + 1));
if(!channelp)
/* We may have freed already, just quietly ignore this... */
;
else {
_libssh2_debug(session,
LIBSSH2_TRACE_CONN,
"EOF received for channel %lu/%lu",
channelp->local.id,
channelp->remote.id);
channelp->remote.eof = 1;
}
LIBSSH2_FREE(session, data);
session->packAdd_state = libssh2_NB_state_idle;
return 0;
/*
byte SSH_MSG_CHANNEL_REQUEST
uint32 recipient channel
string request type in US-ASCII characters only
boolean want reply
.... type-specific data follows
*/
case SSH_MSG_CHANNEL_REQUEST:
if(datalen >= 9) {
uint32_t channel = _libssh2_ntohu32(data + 1);
uint32_t len = _libssh2_ntohu32(data + 5);
unsigned char want_reply = 1;
if(len < (datalen - 10))
want_reply = data[9 + len];
_libssh2_debug(session,
LIBSSH2_TRACE_CONN,
"Channel %d received request type %.*s (wr %X)",
channel, len, data + 9, want_reply);
if(len == sizeof("exit-status") - 1
&& !memcmp("exit-status", data + 9,
sizeof("exit-status") - 1)) {
/* we've got "exit-status" packet. Set the session value */
if(datalen >= 20)
channelp =
_libssh2_channel_locate(session, channel);
if(channelp) {
channelp->exit_status =
_libssh2_ntohu32(data + 9 + sizeof("exit-status"));
_libssh2_debug(session, LIBSSH2_TRACE_CONN,
"Exit status %lu received for "
"channel %lu/%lu",
channelp->exit_status,
channelp->local.id,
channelp->remote.id);
}
}
else if(len == sizeof("exit-signal") - 1
&& !memcmp("exit-signal", data + 9,
sizeof("exit-signal") - 1)) {
/* command terminated due to signal */
if(datalen >= 20)
channelp = _libssh2_channel_locate(session, channel);
if(channelp) {
/* set signal name (without SIG prefix) */
uint32_t namelen =
_libssh2_ntohu32(data + 9 + sizeof("exit-signal"));
channelp->exit_signal =
LIBSSH2_ALLOC(session, namelen + 1);
if(!channelp->exit_signal)
rc = _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
"memory for signal name");
else {
memcpy(channelp->exit_signal,
data + 13 + sizeof("exit_signal"), namelen);
channelp->exit_signal[namelen] = '\0';
/* TODO: save error message and language tag */
_libssh2_debug(session, LIBSSH2_TRACE_CONN,
"Exit signal %s received for "
"channel %lu/%lu",
channelp->exit_signal,
channelp->local.id,
channelp->remote.id);
}
}
}
if(want_reply) {
unsigned char packet[5];
libssh2_packet_add_jump_point4:
session->packAdd_state = libssh2_NB_state_jump4;
packet[0] = SSH_MSG_CHANNEL_FAILURE;
memcpy(&packet[1], data + 1, 4);
rc = _libssh2_transport_send(session, packet, 5, NULL, 0);
if(rc == LIBSSH2_ERROR_EAGAIN)
return rc;
}
}
LIBSSH2_FREE(session, data);
session->packAdd_state = libssh2_NB_state_idle;
return rc;
/*
byte SSH_MSG_CHANNEL_CLOSE
uint32 recipient channel
*/
case SSH_MSG_CHANNEL_CLOSE:
if(datalen >= 5)
channelp =
_libssh2_channel_locate(session,
_libssh2_ntohu32(data + 1));
if(!channelp) {
/* We may have freed already, just quietly ignore this... */
LIBSSH2_FREE(session, data);
session->packAdd_state = libssh2_NB_state_idle;
return 0;
}
_libssh2_debug(session, LIBSSH2_TRACE_CONN,
"Close received for channel %lu/%lu",
channelp->local.id,
channelp->remote.id);
channelp->remote.close = 1;
channelp->remote.eof = 1;
LIBSSH2_FREE(session, data);
session->packAdd_state = libssh2_NB_state_idle;
return 0;
/*
byte SSH_MSG_CHANNEL_OPEN
string "session"
uint32 sender channel
uint32 initial window size
uint32 maximum packet size
*/
case SSH_MSG_CHANNEL_OPEN:
if(datalen < 17)
;
else if((datalen >= (sizeof("forwarded-tcpip") + 4)) &&
((sizeof("forwarded-tcpip") - 1) ==
_libssh2_ntohu32(data + 1))
&&
(memcmp(data + 5, "forwarded-tcpip",
sizeof("forwarded-tcpip") - 1) == 0)) {
/* init the state struct */
memset(&session->packAdd_Qlstn_state, 0,
sizeof(session->packAdd_Qlstn_state));
libssh2_packet_add_jump_point2:
session->packAdd_state = libssh2_NB_state_jump2;
rc = packet_queue_listener(session, data, datalen,
&session->packAdd_Qlstn_state);
}
else if((datalen >= (sizeof("x11") + 4)) &&
((sizeof("x11") - 1) == _libssh2_ntohu32(data + 1)) &&
(memcmp(data + 5, "x11", sizeof("x11") - 1) == 0)) {
/* init the state struct */
memset(&session->packAdd_x11open_state, 0,
sizeof(session->packAdd_x11open_state));
libssh2_packet_add_jump_point3:
session->packAdd_state = libssh2_NB_state_jump3;
rc = packet_x11_open(session, data, datalen,
&session->packAdd_x11open_state);
}
if(rc == LIBSSH2_ERROR_EAGAIN)
return rc;
LIBSSH2_FREE(session, data);
session->packAdd_state = libssh2_NB_state_idle;
return rc;
/*
byte SSH_MSG_CHANNEL_WINDOW_ADJUST
uint32 recipient channel
uint32 bytes to add
*/
case SSH_MSG_CHANNEL_WINDOW_ADJUST:
if(datalen < 9)
;
else {
uint32_t bytestoadd = _libssh2_ntohu32(data + 5);
channelp =
_libssh2_channel_locate(session,
_libssh2_ntohu32(data + 1));
if(channelp) {
channelp->local.window_size += bytestoadd;
_libssh2_debug(session, LIBSSH2_TRACE_CONN,
"Window adjust for channel %lu/%lu, "
"adding %lu bytes, new window_size=%lu",
channelp->local.id,
channelp->remote.id,
bytestoadd,
channelp->local.window_size);
}
}
LIBSSH2_FREE(session, data);
session->packAdd_state = libssh2_NB_state_idle;
return 0;
default:
break;
}
session->packAdd_state = libssh2_NB_state_sent;
}
if(session->packAdd_state == libssh2_NB_state_sent) {
LIBSSH2_PACKET *packetp =
LIBSSH2_ALLOC(session, sizeof(LIBSSH2_PACKET));
if(!packetp) {
_libssh2_debug(session, LIBSSH2_ERROR_ALLOC,
"memory for packet");
LIBSSH2_FREE(session, data);
session->packAdd_state = libssh2_NB_state_idle;
return LIBSSH2_ERROR_ALLOC;
}
packetp->data = data;
packetp->data_len = datalen;
packetp->data_head = data_head;
_libssh2_list_add(&session->packets, &packetp->node);
session->packAdd_state = libssh2_NB_state_sent1;
}
if((msg == SSH_MSG_KEXINIT &&
!(session->state & LIBSSH2_STATE_EXCHANGING_KEYS)) ||
(session->packAdd_state == libssh2_NB_state_sent2)) {
if(session->packAdd_state == libssh2_NB_state_sent1) {
/*
* Remote wants new keys
* Well, it's already in the brigade,
* let's just call back into ourselves
*/
_libssh2_debug(session, LIBSSH2_TRACE_TRANS, "Renegotiating Keys");
session->packAdd_state = libssh2_NB_state_sent2;
}
/*
* The KEXINIT message has been added to the queue. The packAdd and
* readPack states need to be reset because _libssh2_kex_exchange
* (eventually) calls upon _libssh2_transport_read to read the rest of
* the key exchange conversation.
*/
session->readPack_state = libssh2_NB_state_idle;
session->packet.total_num = 0;
session->packAdd_state = libssh2_NB_state_idle;
session->fullpacket_state = libssh2_NB_state_idle;
memset(&session->startup_key_state, 0, sizeof(key_exchange_state_t));
/*
* If there was a key reexchange failure, let's just hope we didn't
* send NEWKEYS yet, otherwise remote will drop us like a rock
*/
rc = _libssh2_kex_exchange(session, 1, &session->startup_key_state);
if(rc == LIBSSH2_ERROR_EAGAIN)
return rc;
}
session->packAdd_state = libssh2_NB_state_idle;
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Security fixes (#315)
* Bounds checks
Fixes for CVEs
https://www.libssh2.org/CVE-2019-3863.html
https://www.libssh2.org/CVE-2019-3856.html
* Packet length bounds check
CVE
https://www.libssh2.org/CVE-2019-3855.html
* Response length check
CVE
https://www.libssh2.org/CVE-2019-3859.html
* Bounds check
CVE
https://www.libssh2.org/CVE-2019-3857.html
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
and additional data validation
* Check bounds before reading into buffers
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
* declare SIZE_MAX and UINT_MAX if needed'</s> |
<s>[INST] Given the following code containing errors, provide 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 channel_request_pty(LIBSSH2_CHANNEL *channel,
const char *term, unsigned int term_len,
const char *modes, unsigned int modes_len,
int width, int height,
int width_px, int height_px)
{
LIBSSH2_SESSION *session = channel->session;
unsigned char *s;
static const unsigned char reply_codes[3] =
{ SSH_MSG_CHANNEL_SUCCESS, SSH_MSG_CHANNEL_FAILURE, 0 };
int rc;
if(channel->reqPTY_state == libssh2_NB_state_idle) {
/* 41 = packet_type(1) + channel(4) + pty_req_len(4) + "pty_req"(7) +
* want_reply(1) + term_len(4) + width(4) + height(4) + width_px(4) +
* height_px(4) + modes_len(4) */
if(term_len + modes_len > 256) {
return _libssh2_error(session, LIBSSH2_ERROR_INVAL,
"term + mode lengths too large");
}
channel->reqPTY_packet_len = term_len + modes_len + 41;
/* Zero the whole thing out */
memset(&channel->reqPTY_packet_requirev_state, 0,
sizeof(channel->reqPTY_packet_requirev_state));
_libssh2_debug(session, LIBSSH2_TRACE_CONN,
"Allocating tty on channel %lu/%lu", channel->local.id,
channel->remote.id);
s = channel->reqPTY_packet;
*(s++) = SSH_MSG_CHANNEL_REQUEST;
_libssh2_store_u32(&s, channel->remote.id);
_libssh2_store_str(&s, (char *)"pty-req", sizeof("pty-req") - 1);
*(s++) = 0x01;
_libssh2_store_str(&s, term, term_len);
_libssh2_store_u32(&s, width);
_libssh2_store_u32(&s, height);
_libssh2_store_u32(&s, width_px);
_libssh2_store_u32(&s, height_px);
_libssh2_store_str(&s, modes, modes_len);
channel->reqPTY_state = libssh2_NB_state_created;
}
if(channel->reqPTY_state == libssh2_NB_state_created) {
rc = _libssh2_transport_send(session, channel->reqPTY_packet,
channel->reqPTY_packet_len,
NULL, 0);
if(rc == LIBSSH2_ERROR_EAGAIN) {
_libssh2_error(session, rc,
"Would block sending pty request");
return rc;
}
else if(rc) {
channel->reqPTY_state = libssh2_NB_state_idle;
return _libssh2_error(session, rc,
"Unable to send pty-request packet");
}
_libssh2_htonu32(channel->reqPTY_local_channel, channel->local.id);
channel->reqPTY_state = libssh2_NB_state_sent;
}
if(channel->reqPTY_state == libssh2_NB_state_sent) {
unsigned char *data;
size_t data_len;
unsigned char code;
rc = _libssh2_packet_requirev(session, reply_codes, &data, &data_len,
1, channel->reqPTY_local_channel, 4,
&channel->reqPTY_packet_requirev_state);
if(rc == LIBSSH2_ERROR_EAGAIN) {
return rc;
}
else if(rc) {
channel->reqPTY_state = libssh2_NB_state_idle;
return _libssh2_error(session, LIBSSH2_ERROR_PROTO,
"Failed to require the PTY package");
}
code = data[0];
LIBSSH2_FREE(session, data);
channel->reqPTY_state = libssh2_NB_state_idle;
if(code == SSH_MSG_CHANNEL_SUCCESS)
return 0;
}
return _libssh2_error(session, LIBSSH2_ERROR_CHANNEL_REQUEST_DENIED,
"Unable to complete request for channel request-pty");
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Security fixes (#315)
* Bounds checks
Fixes for CVEs
https://www.libssh2.org/CVE-2019-3863.html
https://www.libssh2.org/CVE-2019-3856.html
* Packet length bounds check
CVE
https://www.libssh2.org/CVE-2019-3855.html
* Response length check
CVE
https://www.libssh2.org/CVE-2019-3859.html
* Bounds check
CVE
https://www.libssh2.org/CVE-2019-3857.html
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
and additional data validation
* Check bounds before reading into buffers
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
* declare SIZE_MAX and UINT_MAX if needed'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: session_startup(LIBSSH2_SESSION *session, libssh2_socket_t sock)
{
int rc;
if(session->startup_state == libssh2_NB_state_idle) {
_libssh2_debug(session, LIBSSH2_TRACE_TRANS,
"session_startup for socket %d", sock);
if(LIBSSH2_INVALID_SOCKET == sock) {
/* Did we forget something? */
return _libssh2_error(session, LIBSSH2_ERROR_BAD_SOCKET,
"Bad socket provided");
}
session->socket_fd = sock;
session->socket_prev_blockstate =
!get_socket_nonblocking(session->socket_fd);
if(session->socket_prev_blockstate) {
/* If in blocking state change to non-blocking */
rc = session_nonblock(session->socket_fd, 1);
if(rc) {
return _libssh2_error(session, rc,
"Failed changing socket's "
"blocking state to non-blocking");
}
}
session->startup_state = libssh2_NB_state_created;
}
if(session->startup_state == libssh2_NB_state_created) {
rc = banner_send(session);
if(rc == LIBSSH2_ERROR_EAGAIN)
return rc;
else if(rc) {
return _libssh2_error(session, rc,
"Failed sending banner");
}
session->startup_state = libssh2_NB_state_sent;
session->banner_TxRx_state = libssh2_NB_state_idle;
}
if(session->startup_state == libssh2_NB_state_sent) {
do {
rc = banner_receive(session);
if(rc == LIBSSH2_ERROR_EAGAIN)
return rc;
else if(rc)
return _libssh2_error(session, rc,
"Failed getting banner");
} while(strncmp("SSH-", (char *)session->remote.banner, 4));
session->startup_state = libssh2_NB_state_sent1;
}
if(session->startup_state == libssh2_NB_state_sent1) {
rc = _libssh2_kex_exchange(session, 0, &session->startup_key_state);
if(rc == LIBSSH2_ERROR_EAGAIN)
return rc;
else if(rc)
return _libssh2_error(session, rc,
"Unable to exchange encryption keys");
session->startup_state = libssh2_NB_state_sent2;
}
if(session->startup_state == libssh2_NB_state_sent2) {
_libssh2_debug(session, LIBSSH2_TRACE_TRANS,
"Requesting userauth service");
/* Request the userauth service */
session->startup_service[0] = SSH_MSG_SERVICE_REQUEST;
_libssh2_htonu32(session->startup_service + 1,
sizeof("ssh-userauth") - 1);
memcpy(session->startup_service + 5, "ssh-userauth",
sizeof("ssh-userauth") - 1);
session->startup_state = libssh2_NB_state_sent3;
}
if(session->startup_state == libssh2_NB_state_sent3) {
rc = _libssh2_transport_send(session, session->startup_service,
sizeof("ssh-userauth") + 5 - 1,
NULL, 0);
if(rc == LIBSSH2_ERROR_EAGAIN)
return rc;
else if(rc) {
return _libssh2_error(session, rc,
"Unable to ask for ssh-userauth service");
}
session->startup_state = libssh2_NB_state_sent4;
}
if(session->startup_state == libssh2_NB_state_sent4) {
rc = _libssh2_packet_require(session, SSH_MSG_SERVICE_ACCEPT,
&session->startup_data,
&session->startup_data_len, 0, NULL, 0,
&session->startup_req_state);
if(rc)
return rc;
session->startup_service_length =
_libssh2_ntohu32(session->startup_data + 1);
if((session->startup_service_length != (sizeof("ssh-userauth") - 1))
|| strncmp("ssh-userauth", (char *) session->startup_data + 5,
session->startup_service_length)) {
LIBSSH2_FREE(session, session->startup_data);
session->startup_data = NULL;
return _libssh2_error(session, LIBSSH2_ERROR_PROTO,
"Invalid response received from server");
}
LIBSSH2_FREE(session, session->startup_data);
session->startup_data = NULL;
session->startup_state = libssh2_NB_state_idle;
return 0;
}
/* just for safety return some error */
return LIBSSH2_ERROR_INVAL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Security fixes (#315)
* Bounds checks
Fixes for CVEs
https://www.libssh2.org/CVE-2019-3863.html
https://www.libssh2.org/CVE-2019-3856.html
* Packet length bounds check
CVE
https://www.libssh2.org/CVE-2019-3855.html
* Response length check
CVE
https://www.libssh2.org/CVE-2019-3859.html
* Bounds check
CVE
https://www.libssh2.org/CVE-2019-3857.html
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
and additional data validation
* Check bounds before reading into buffers
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
* declare SIZE_MAX and UINT_MAX if needed'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: * Diffie Hellman Key Exchange, Group Agnostic
*/
static int diffie_hellman_sha256(LIBSSH2_SESSION *session,
_libssh2_bn *g,
_libssh2_bn *p,
int group_order,
unsigned char packet_type_init,
unsigned char packet_type_reply,
unsigned char *midhash,
unsigned long midhash_len,
kmdhgGPshakex_state_t *exchange_state)
{
int ret = 0;
int rc;
libssh2_sha256_ctx exchange_hash_ctx;
if(exchange_state->state == libssh2_NB_state_idle) {
/* Setup initial values */
exchange_state->e_packet = NULL;
exchange_state->s_packet = NULL;
exchange_state->k_value = NULL;
exchange_state->ctx = _libssh2_bn_ctx_new();
libssh2_dh_init(&exchange_state->x);
exchange_state->e = _libssh2_bn_init(); /* g^x mod p */
exchange_state->f = _libssh2_bn_init_from_bin(); /* g^(Random from server) mod p */
exchange_state->k = _libssh2_bn_init(); /* The shared secret: f^x mod p */
/* Zero the whole thing out */
memset(&exchange_state->req_state, 0, sizeof(packet_require_state_t));
/* Generate x and e */
rc = libssh2_dh_key_pair(&exchange_state->x, exchange_state->e, g, p,
group_order, exchange_state->ctx);
if(rc)
goto clean_exit;
/* Send KEX init */
/* packet_type(1) + String Length(4) + leading 0(1) */
exchange_state->e_packet_len =
_libssh2_bn_bytes(exchange_state->e) + 6;
if(_libssh2_bn_bits(exchange_state->e) % 8) {
/* Leading 00 not needed */
exchange_state->e_packet_len--;
}
exchange_state->e_packet =
LIBSSH2_ALLOC(session, exchange_state->e_packet_len);
if(!exchange_state->e_packet) {
ret = _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
"Out of memory error");
goto clean_exit;
}
exchange_state->e_packet[0] = packet_type_init;
_libssh2_htonu32(exchange_state->e_packet + 1,
exchange_state->e_packet_len - 5);
if(_libssh2_bn_bits(exchange_state->e) % 8) {
_libssh2_bn_to_bin(exchange_state->e,
exchange_state->e_packet + 5);
}
else {
exchange_state->e_packet[5] = 0;
_libssh2_bn_to_bin(exchange_state->e,
exchange_state->e_packet + 6);
}
_libssh2_debug(session, LIBSSH2_TRACE_KEX, "Sending KEX packet %d",
(int) packet_type_init);
exchange_state->state = libssh2_NB_state_created;
}
if(exchange_state->state == libssh2_NB_state_created) {
rc = _libssh2_transport_send(session, exchange_state->e_packet,
exchange_state->e_packet_len,
NULL, 0);
if(rc == LIBSSH2_ERROR_EAGAIN) {
return rc;
}
else if(rc) {
ret = _libssh2_error(session, rc,
"Unable to send KEX init message");
goto clean_exit;
}
exchange_state->state = libssh2_NB_state_sent;
}
if(exchange_state->state == libssh2_NB_state_sent) {
if(session->burn_optimistic_kexinit) {
/* The first KEX packet to come along will be the guess initially
* sent by the server. That guess turned out to be wrong so we
* need to silently ignore it */
int burn_type;
_libssh2_debug(session, LIBSSH2_TRACE_KEX,
"Waiting for badly guessed KEX packet (to be ignored)");
burn_type =
_libssh2_packet_burn(session, &exchange_state->burn_state);
if(burn_type == LIBSSH2_ERROR_EAGAIN) {
return burn_type;
}
else if(burn_type <= 0) {
/* Failed to receive a packet */
ret = burn_type;
goto clean_exit;
}
session->burn_optimistic_kexinit = 0;
_libssh2_debug(session, LIBSSH2_TRACE_KEX,
"Burnt packet of type: %02x",
(unsigned int) burn_type);
}
exchange_state->state = libssh2_NB_state_sent1;
}
if(exchange_state->state == libssh2_NB_state_sent1) {
/* Wait for KEX reply */
rc = _libssh2_packet_require(session, packet_type_reply,
&exchange_state->s_packet,
&exchange_state->s_packet_len, 0, NULL,
0, &exchange_state->req_state);
if(rc == LIBSSH2_ERROR_EAGAIN) {
return rc;
}
if(rc) {
ret = _libssh2_error(session, LIBSSH2_ERROR_TIMEOUT,
"Timed out waiting for KEX reply");
goto clean_exit;
}
/* Parse KEXDH_REPLY */
exchange_state->s = exchange_state->s_packet + 1;
session->server_hostkey_len = _libssh2_ntohu32(exchange_state->s);
exchange_state->s += 4;
if(session->server_hostkey)
LIBSSH2_FREE(session, session->server_hostkey);
session->server_hostkey =
LIBSSH2_ALLOC(session, session->server_hostkey_len);
if(!session->server_hostkey) {
ret = _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
"Unable to allocate memory for a copy "
"of the host key");
goto clean_exit;
}
memcpy(session->server_hostkey, exchange_state->s,
session->server_hostkey_len);
exchange_state->s += session->server_hostkey_len;
#if LIBSSH2_MD5
{
libssh2_md5_ctx fingerprint_ctx;
if(libssh2_md5_init(&fingerprint_ctx)) {
libssh2_md5_update(fingerprint_ctx, session->server_hostkey,
session->server_hostkey_len);
libssh2_md5_final(fingerprint_ctx,
session->server_hostkey_md5);
session->server_hostkey_md5_valid = TRUE;
}
else {
session->server_hostkey_md5_valid = FALSE;
}
}
#ifdef LIBSSH2DEBUG
{
char fingerprint[50], *fprint = fingerprint;
int i;
for(i = 0; i < 16; i++, fprint += 3) {
snprintf(fprint, 4, "%02x:", session->server_hostkey_md5[i]);
}
*(--fprint) = '\0';
_libssh2_debug(session, LIBSSH2_TRACE_KEX,
"Server's MD5 Fingerprint: %s", fingerprint);
}
#endif /* LIBSSH2DEBUG */
#endif /* ! LIBSSH2_MD5 */
{
libssh2_sha1_ctx fingerprint_ctx;
if(libssh2_sha1_init(&fingerprint_ctx)) {
libssh2_sha1_update(fingerprint_ctx, session->server_hostkey,
session->server_hostkey_len);
libssh2_sha1_final(fingerprint_ctx,
session->server_hostkey_sha1);
session->server_hostkey_sha1_valid = TRUE;
}
else {
session->server_hostkey_sha1_valid = FALSE;
}
}
#ifdef LIBSSH2DEBUG
{
char fingerprint[64], *fprint = fingerprint;
int i;
for(i = 0; i < 20; i++, fprint += 3) {
snprintf(fprint, 4, "%02x:", session->server_hostkey_sha1[i]);
}
*(--fprint) = '\0';
_libssh2_debug(session, LIBSSH2_TRACE_KEX,
"Server's SHA1 Fingerprint: %s", fingerprint);
}
#endif /* LIBSSH2DEBUG */
{
libssh2_sha256_ctx fingerprint_ctx;
if(libssh2_sha256_init(&fingerprint_ctx)) {
libssh2_sha256_update(fingerprint_ctx, session->server_hostkey,
session->server_hostkey_len);
libssh2_sha256_final(fingerprint_ctx,
session->server_hostkey_sha256);
session->server_hostkey_sha256_valid = TRUE;
}
else {
session->server_hostkey_sha256_valid = FALSE;
}
}
#ifdef LIBSSH2DEBUG
{
char *base64Fingerprint = NULL;
_libssh2_base64_encode(session, (const char *)session->server_hostkey_sha256,
SHA256_DIGEST_LENGTH, &base64Fingerprint);
if(base64Fingerprint != NULL) {
_libssh2_debug(session, LIBSSH2_TRACE_KEX,
"Server's SHA256 Fingerprint: %s", base64Fingerprint);
LIBSSH2_FREE(session, base64Fingerprint);
}
}
#endif /* LIBSSH2DEBUG */
if(session->hostkey->init(session, session->server_hostkey,
session->server_hostkey_len,
&session->server_hostkey_abstract)) {
ret = _libssh2_error(session, LIBSSH2_ERROR_HOSTKEY_INIT,
"Unable to initialize hostkey importer");
goto clean_exit;
}
exchange_state->f_value_len = _libssh2_ntohu32(exchange_state->s);
exchange_state->s += 4;
exchange_state->f_value = exchange_state->s;
exchange_state->s += exchange_state->f_value_len;
_libssh2_bn_from_bin(exchange_state->f, exchange_state->f_value_len,
exchange_state->f_value);
exchange_state->h_sig_len = _libssh2_ntohu32(exchange_state->s);
exchange_state->s += 4;
exchange_state->h_sig = exchange_state->s;
/* Compute the shared secret */
libssh2_dh_secret(&exchange_state->x, exchange_state->k,
exchange_state->f, p, exchange_state->ctx);
exchange_state->k_value_len = _libssh2_bn_bytes(exchange_state->k) + 5;
if(_libssh2_bn_bits(exchange_state->k) % 8) {
/* don't need leading 00 */
exchange_state->k_value_len--;
}
exchange_state->k_value =
LIBSSH2_ALLOC(session, exchange_state->k_value_len);
if(!exchange_state->k_value) {
ret = _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
"Unable to allocate buffer for K");
goto clean_exit;
}
_libssh2_htonu32(exchange_state->k_value,
exchange_state->k_value_len - 4);
if(_libssh2_bn_bits(exchange_state->k) % 8) {
_libssh2_bn_to_bin(exchange_state->k, exchange_state->k_value + 4);
}
else {
exchange_state->k_value[4] = 0;
_libssh2_bn_to_bin(exchange_state->k, exchange_state->k_value + 5);
}
exchange_state->exchange_hash = (void *)&exchange_hash_ctx;
libssh2_sha256_init(&exchange_hash_ctx);
if(session->local.banner) {
_libssh2_htonu32(exchange_state->h_sig_comp,
strlen((char *) session->local.banner) - 2);
libssh2_sha256_update(exchange_hash_ctx,
exchange_state->h_sig_comp, 4);
libssh2_sha256_update(exchange_hash_ctx,
session->local.banner,
strlen((char *) session->local.banner) - 2);
}
else {
_libssh2_htonu32(exchange_state->h_sig_comp,
sizeof(LIBSSH2_SSH_DEFAULT_BANNER) - 1);
libssh2_sha256_update(exchange_hash_ctx,
exchange_state->h_sig_comp, 4);
libssh2_sha256_update(exchange_hash_ctx,
(const unsigned char *)LIBSSH2_SSH_DEFAULT_BANNER,
sizeof(LIBSSH2_SSH_DEFAULT_BANNER) - 1);
}
_libssh2_htonu32(exchange_state->h_sig_comp,
strlen((char *) session->remote.banner));
libssh2_sha256_update(exchange_hash_ctx,
exchange_state->h_sig_comp, 4);
libssh2_sha256_update(exchange_hash_ctx,
session->remote.banner,
strlen((char *) session->remote.banner));
_libssh2_htonu32(exchange_state->h_sig_comp,
session->local.kexinit_len);
libssh2_sha256_update(exchange_hash_ctx,
exchange_state->h_sig_comp, 4);
libssh2_sha256_update(exchange_hash_ctx,
session->local.kexinit,
session->local.kexinit_len);
_libssh2_htonu32(exchange_state->h_sig_comp,
session->remote.kexinit_len);
libssh2_sha256_update(exchange_hash_ctx,
exchange_state->h_sig_comp, 4);
libssh2_sha256_update(exchange_hash_ctx,
session->remote.kexinit,
session->remote.kexinit_len);
_libssh2_htonu32(exchange_state->h_sig_comp,
session->server_hostkey_len);
libssh2_sha256_update(exchange_hash_ctx,
exchange_state->h_sig_comp, 4);
libssh2_sha256_update(exchange_hash_ctx,
session->server_hostkey,
session->server_hostkey_len);
if(packet_type_init == SSH_MSG_KEX_DH_GEX_INIT) {
/* diffie-hellman-group-exchange hashes additional fields */
#ifdef LIBSSH2_DH_GEX_NEW
_libssh2_htonu32(exchange_state->h_sig_comp,
LIBSSH2_DH_GEX_MINGROUP);
_libssh2_htonu32(exchange_state->h_sig_comp + 4,
LIBSSH2_DH_GEX_OPTGROUP);
_libssh2_htonu32(exchange_state->h_sig_comp + 8,
LIBSSH2_DH_GEX_MAXGROUP);
libssh2_sha256_update(exchange_hash_ctx,
exchange_state->h_sig_comp, 12);
#else
_libssh2_htonu32(exchange_state->h_sig_comp,
LIBSSH2_DH_GEX_OPTGROUP);
libssh2_sha256_update(exchange_hash_ctx,
exchange_state->h_sig_comp, 4);
#endif
}
if(midhash) {
libssh2_sha256_update(exchange_hash_ctx, midhash,
midhash_len);
}
libssh2_sha256_update(exchange_hash_ctx,
exchange_state->e_packet + 1,
exchange_state->e_packet_len - 1);
_libssh2_htonu32(exchange_state->h_sig_comp,
exchange_state->f_value_len);
libssh2_sha256_update(exchange_hash_ctx,
exchange_state->h_sig_comp, 4);
libssh2_sha256_update(exchange_hash_ctx,
exchange_state->f_value,
exchange_state->f_value_len);
libssh2_sha256_update(exchange_hash_ctx,
exchange_state->k_value,
exchange_state->k_value_len);
libssh2_sha256_final(exchange_hash_ctx,
exchange_state->h_sig_comp);
if(session->hostkey->
sig_verify(session, exchange_state->h_sig,
exchange_state->h_sig_len, exchange_state->h_sig_comp,
SHA256_DIGEST_LENGTH, &session->server_hostkey_abstract)) {
ret = _libssh2_error(session, LIBSSH2_ERROR_HOSTKEY_SIGN,
"Unable to verify hostkey signature");
goto clean_exit;
}
_libssh2_debug(session, LIBSSH2_TRACE_KEX, "Sending NEWKEYS message");
exchange_state->c = SSH_MSG_NEWKEYS;
exchange_state->state = libssh2_NB_state_sent2;
}
if(exchange_state->state == libssh2_NB_state_sent2) {
rc = _libssh2_transport_send(session, &exchange_state->c, 1, NULL, 0);
if(rc == LIBSSH2_ERROR_EAGAIN) {
return rc;
}
else if(rc) {
ret = _libssh2_error(session, rc, "Unable to send NEWKEYS message");
goto clean_exit;
}
exchange_state->state = libssh2_NB_state_sent3;
}
if(exchange_state->state == libssh2_NB_state_sent3) {
rc = _libssh2_packet_require(session, SSH_MSG_NEWKEYS,
&exchange_state->tmp,
&exchange_state->tmp_len, 0, NULL, 0,
&exchange_state->req_state);
if(rc == LIBSSH2_ERROR_EAGAIN) {
return rc;
}
else if(rc) {
ret = _libssh2_error(session, rc, "Timed out waiting for NEWKEYS");
goto clean_exit;
}
/* The first key exchange has been performed,
switch to active crypt/comp/mac mode */
session->state |= LIBSSH2_STATE_NEWKEYS;
_libssh2_debug(session, LIBSSH2_TRACE_KEX, "Received NEWKEYS message");
/* This will actually end up being just packet_type(1)
for this packet type anyway */
LIBSSH2_FREE(session, exchange_state->tmp);
if(!session->session_id) {
session->session_id = LIBSSH2_ALLOC(session, SHA256_DIGEST_LENGTH);
if(!session->session_id) {
ret = _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
"Unable to allocate buffer for SHA digest");
goto clean_exit;
}
memcpy(session->session_id, exchange_state->h_sig_comp,
SHA256_DIGEST_LENGTH);
session->session_id_len = SHA256_DIGEST_LENGTH;
_libssh2_debug(session, LIBSSH2_TRACE_KEX, "session_id calculated");
}
/* Cleanup any existing cipher */
if(session->local.crypt->dtor) {
session->local.crypt->dtor(session,
&session->local.crypt_abstract);
}
/* Calculate IV/Secret/Key for each direction */
if(session->local.crypt->init) {
unsigned char *iv = NULL, *secret = NULL;
int free_iv = 0, free_secret = 0;
LIBSSH2_KEX_METHOD_SHA_VALUE_HASH(256, iv,
session->local.crypt->
iv_len,
(const unsigned char *)"A");
if(!iv) {
ret = -1;
goto clean_exit;
}
LIBSSH2_KEX_METHOD_SHA_VALUE_HASH(256, secret,
session->local.crypt->
secret_len,
(const unsigned char *)"C");
if(!secret) {
LIBSSH2_FREE(session, iv);
ret = LIBSSH2_ERROR_KEX_FAILURE;
goto clean_exit;
}
if(session->local.crypt->
init(session, session->local.crypt, iv, &free_iv, secret,
&free_secret, 1, &session->local.crypt_abstract)) {
LIBSSH2_FREE(session, iv);
LIBSSH2_FREE(session, secret);
ret = LIBSSH2_ERROR_KEX_FAILURE;
goto clean_exit;
}
if(free_iv) {
_libssh2_explicit_zero(iv, session->local.crypt->iv_len);
LIBSSH2_FREE(session, iv);
}
if(free_secret) {
_libssh2_explicit_zero(secret, session->local.crypt->secret_len);
LIBSSH2_FREE(session, secret);
}
}
_libssh2_debug(session, LIBSSH2_TRACE_KEX,
"Client to Server IV and Key calculated");
if(session->remote.crypt->dtor) {
/* Cleanup any existing cipher */
session->remote.crypt->dtor(session,
&session->remote.crypt_abstract);
}
if(session->remote.crypt->init) {
unsigned char *iv = NULL, *secret = NULL;
int free_iv = 0, free_secret = 0;
LIBSSH2_KEX_METHOD_SHA_VALUE_HASH(256, iv,
session->remote.crypt->
iv_len,
(const unsigned char *)"B");
if(!iv) {
ret = LIBSSH2_ERROR_KEX_FAILURE;
goto clean_exit;
}
LIBSSH2_KEX_METHOD_SHA_VALUE_HASH(256, secret,
session->remote.crypt->
secret_len,
(const unsigned char *)"D");
if(!secret) {
LIBSSH2_FREE(session, iv);
ret = LIBSSH2_ERROR_KEX_FAILURE;
goto clean_exit;
}
if(session->remote.crypt->
init(session, session->remote.crypt, iv, &free_iv, secret,
&free_secret, 0, &session->remote.crypt_abstract)) {
LIBSSH2_FREE(session, iv);
LIBSSH2_FREE(session, secret);
ret = LIBSSH2_ERROR_KEX_FAILURE;
goto clean_exit;
}
if(free_iv) {
_libssh2_explicit_zero(iv, session->remote.crypt->iv_len);
LIBSSH2_FREE(session, iv);
}
if(free_secret) {
_libssh2_explicit_zero(secret, session->remote.crypt->secret_len);
LIBSSH2_FREE(session, secret);
}
}
_libssh2_debug(session, LIBSSH2_TRACE_KEX,
"Server to Client IV and Key calculated");
if(session->local.mac->dtor) {
session->local.mac->dtor(session, &session->local.mac_abstract);
}
if(session->local.mac->init) {
unsigned char *key = NULL;
int free_key = 0;
LIBSSH2_KEX_METHOD_SHA_VALUE_HASH(256, key,
session->local.mac->
key_len,
(const unsigned char *)"E");
if(!key) {
ret = LIBSSH2_ERROR_KEX_FAILURE;
goto clean_exit;
}
session->local.mac->init(session, key, &free_key,
&session->local.mac_abstract);
if(free_key) {
_libssh2_explicit_zero(key, session->local.mac->key_len);
LIBSSH2_FREE(session, key);
}
}
_libssh2_debug(session, LIBSSH2_TRACE_KEX,
"Client to Server HMAC Key calculated");
if(session->remote.mac->dtor) {
session->remote.mac->dtor(session, &session->remote.mac_abstract);
}
if(session->remote.mac->init) {
unsigned char *key = NULL;
int free_key = 0;
LIBSSH2_KEX_METHOD_SHA_VALUE_HASH(256, key,
session->remote.mac->
key_len,
(const unsigned char *)"F");
if(!key) {
ret = LIBSSH2_ERROR_KEX_FAILURE;
goto clean_exit;
}
session->remote.mac->init(session, key, &free_key,
&session->remote.mac_abstract);
if(free_key) {
_libssh2_explicit_zero(key, session->remote.mac->key_len);
LIBSSH2_FREE(session, key);
}
}
_libssh2_debug(session, LIBSSH2_TRACE_KEX,
"Server to Client HMAC Key calculated");
/* Initialize compression for each direction */
/* Cleanup any existing compression */
if(session->local.comp && session->local.comp->dtor) {
session->local.comp->dtor(session, 1,
&session->local.comp_abstract);
}
if(session->local.comp && session->local.comp->init) {
if(session->local.comp->init(session, 1,
&session->local.comp_abstract)) {
ret = LIBSSH2_ERROR_KEX_FAILURE;
goto clean_exit;
}
}
_libssh2_debug(session, LIBSSH2_TRACE_KEX,
"Client to Server compression initialized");
if(session->remote.comp && session->remote.comp->dtor) {
session->remote.comp->dtor(session, 0,
&session->remote.comp_abstract);
}
if(session->remote.comp && session->remote.comp->init) {
if(session->remote.comp->init(session, 0,
&session->remote.comp_abstract)) {
ret = LIBSSH2_ERROR_KEX_FAILURE;
goto clean_exit;
}
}
_libssh2_debug(session, LIBSSH2_TRACE_KEX,
"Server to Client compression initialized");
}
clean_exit:
libssh2_dh_dtor(&exchange_state->x);
_libssh2_bn_free(exchange_state->e);
exchange_state->e = NULL;
_libssh2_bn_free(exchange_state->f);
exchange_state->f = NULL;
_libssh2_bn_free(exchange_state->k);
exchange_state->k = NULL;
_libssh2_bn_ctx_free(exchange_state->ctx);
exchange_state->ctx = NULL;
if(exchange_state->e_packet) {
LIBSSH2_FREE(session, exchange_state->e_packet);
exchange_state->e_packet = NULL;
}
if(exchange_state->s_packet) {
LIBSSH2_FREE(session, exchange_state->s_packet);
exchange_state->s_packet = NULL;
}
if(exchange_state->k_value) {
LIBSSH2_FREE(session, exchange_state->k_value);
exchange_state->k_value = NULL;
}
exchange_state->state = libssh2_NB_state_idle;
; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Security fixes (#315)
* Bounds checks
Fixes for CVEs
https://www.libssh2.org/CVE-2019-3863.html
https://www.libssh2.org/CVE-2019-3856.html
* Packet length bounds check
CVE
https://www.libssh2.org/CVE-2019-3855.html
* Response length check
CVE
https://www.libssh2.org/CVE-2019-3859.html
* Bounds check
CVE
https://www.libssh2.org/CVE-2019-3857.html
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
and additional data validation
* Check bounds before reading into buffers
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
* declare SIZE_MAX and UINT_MAX if needed'</s> |
<s>[INST] Given the following code containing errors, provide 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 _libssh2_transport_read(LIBSSH2_SESSION * session)
{
int rc;
struct transportpacket *p = &session->packet;
int remainbuf;
int remainpack;
int numbytes;
int numdecrypt;
unsigned char block[MAX_BLOCKSIZE];
int blocksize;
int encrypted = 1;
size_t total_num;
/* default clear the bit */
session->socket_block_directions &= ~LIBSSH2_SESSION_BLOCK_INBOUND;
/*
* All channels, systems, subsystems, etc eventually make it down here
* when looking for more incoming data. If a key exchange is going on
* (LIBSSH2_STATE_EXCHANGING_KEYS bit is set) then the remote end will
* ONLY send key exchange related traffic. In non-blocking mode, there is
* a chance to break out of the kex_exchange function with an EAGAIN
* status, and never come back to it. If LIBSSH2_STATE_EXCHANGING_KEYS is
* active, then we must redirect to the key exchange. However, if
* kex_exchange is active (as in it is the one that calls this execution
* of packet_read, then don't redirect, as that would be an infinite loop!
*/
if(session->state & LIBSSH2_STATE_EXCHANGING_KEYS &&
!(session->state & LIBSSH2_STATE_KEX_ACTIVE)) {
/* Whoever wants a packet won't get anything until the key re-exchange
* is done!
*/
_libssh2_debug(session, LIBSSH2_TRACE_TRANS, "Redirecting into the"
" key re-exchange from _libssh2_transport_read");
rc = _libssh2_kex_exchange(session, 1, &session->startup_key_state);
if(rc)
return rc;
}
/*
* =============================== NOTE ===============================
* I know this is very ugly and not a really good use of "goto", but
* this case statement would be even uglier to do it any other way
*/
if(session->readPack_state == libssh2_NB_state_jump1) {
session->readPack_state = libssh2_NB_state_idle;
encrypted = session->readPack_encrypted;
goto libssh2_transport_read_point1;
}
do {
if(session->socket_state == LIBSSH2_SOCKET_DISCONNECTED) {
return LIBSSH2_ERROR_NONE;
}
if(session->state & LIBSSH2_STATE_NEWKEYS) {
blocksize = session->remote.crypt->blocksize;
}
else {
encrypted = 0; /* not encrypted */
blocksize = 5; /* not strictly true, but we can use 5 here to
make the checks below work fine still */
}
/* read/use a whole big chunk into a temporary area stored in
the LIBSSH2_SESSION struct. We will decrypt data from that
buffer into the packet buffer so this temp one doesn't have
to be able to keep a whole SSH packet, just be large enough
so that we can read big chunks from the network layer. */
/* how much data there is remaining in the buffer to deal with
before we should read more from the network */
remainbuf = p->writeidx - p->readidx;
/* if remainbuf turns negative we have a bad internal error */
assert(remainbuf >= 0);
if(remainbuf < blocksize) {
/* If we have less than a blocksize left, it is too
little data to deal with, read more */
ssize_t nread;
/* move any remainder to the start of the buffer so
that we can do a full refill */
if(remainbuf) {
memmove(p->buf, &p->buf[p->readidx], remainbuf);
p->readidx = 0;
p->writeidx = remainbuf;
}
else {
/* nothing to move, just zero the indexes */
p->readidx = p->writeidx = 0;
}
/* now read a big chunk from the network into the temp buffer */
nread =
LIBSSH2_RECV(session, &p->buf[remainbuf],
PACKETBUFSIZE - remainbuf,
LIBSSH2_SOCKET_RECV_FLAGS(session));
if(nread <= 0) {
/* check if this is due to EAGAIN and return the special
return code if so, error out normally otherwise */
if((nread < 0) && (nread == -EAGAIN)) {
session->socket_block_directions |=
LIBSSH2_SESSION_BLOCK_INBOUND;
return LIBSSH2_ERROR_EAGAIN;
}
_libssh2_debug(session, LIBSSH2_TRACE_SOCKET,
"Error recving %d bytes (got %d)",
PACKETBUFSIZE - remainbuf, -nread);
return LIBSSH2_ERROR_SOCKET_RECV;
}
_libssh2_debug(session, LIBSSH2_TRACE_SOCKET,
"Recved %d/%d bytes to %p+%d", nread,
PACKETBUFSIZE - remainbuf, p->buf, remainbuf);
debugdump(session, "libssh2_transport_read() raw",
&p->buf[remainbuf], nread);
/* advance write pointer */
p->writeidx += nread;
/* update remainbuf counter */
remainbuf = p->writeidx - p->readidx;
}
/* how much data to deal with from the buffer */
numbytes = remainbuf;
if(!p->total_num) {
/* No payload package area allocated yet. To know the
size of this payload, we need to decrypt the first
blocksize data. */
if(numbytes < blocksize) {
/* we can't act on anything less than blocksize, but this
check is only done for the initial block since once we have
got the start of a block we can in fact deal with fractions
*/
session->socket_block_directions |=
LIBSSH2_SESSION_BLOCK_INBOUND;
return LIBSSH2_ERROR_EAGAIN;
}
if(encrypted) {
rc = decrypt(session, &p->buf[p->readidx], block, blocksize);
if(rc != LIBSSH2_ERROR_NONE) {
return rc;
}
/* save the first 5 bytes of the decrypted package, to be
used in the hash calculation later down. */
memcpy(p->init, block, 5);
}
else {
/* the data is plain, just copy it verbatim to
the working block buffer */
memcpy(block, &p->buf[p->readidx], blocksize);
}
/* advance the read pointer */
p->readidx += blocksize;
/* we now have the initial blocksize bytes decrypted,
* and we can extract packet and padding length from it
*/
p->packet_length = _libssh2_ntohu32(block);
if(p->packet_length < 1)
return LIBSSH2_ERROR_DECRYPT;
p->padding_length = block[4];
/* total_num is the number of bytes following the initial
(5 bytes) packet length and padding length fields */
total_num =
p->packet_length - 1 +
(encrypted ? session->remote.mac->mac_len : 0);
/* RFC4253 section 6.1 Maximum Packet Length says:
*
* "All implementations MUST be able to process
* packets with uncompressed payload length of 32768
* bytes or less and total packet size of 35000 bytes
* or less (including length, padding length, payload,
* padding, and MAC.)."
*/
if(total_num > LIBSSH2_PACKET_MAXPAYLOAD) {
return LIBSSH2_ERROR_OUT_OF_BOUNDARY;
}
/* Get a packet handle put data into. We get one to
hold all data, including padding and MAC. */
p->payload = LIBSSH2_ALLOC(session, total_num);
if(!p->payload) {
return LIBSSH2_ERROR_ALLOC;
}
p->total_num = total_num;
/* init write pointer to start of payload buffer */
p->wptr = p->payload;
if(blocksize > 5) {
/* copy the data from index 5 to the end of
the blocksize from the temporary buffer to
the start of the decrypted buffer */
memcpy(p->wptr, &block[5], blocksize - 5);
p->wptr += blocksize - 5; /* advance write pointer */
}
/* init the data_num field to the number of bytes of
the package read so far */
p->data_num = p->wptr - p->payload;
/* we already dealt with a blocksize worth of data */
numbytes -= blocksize;
}
/* how much there is left to add to the current payload
package */
remainpack = p->total_num - p->data_num;
if(numbytes > remainpack) {
/* if we have more data in the buffer than what is going into this
particular packet, we limit this round to this packet only */
numbytes = remainpack;
}
if(encrypted) {
/* At the end of the incoming stream, there is a MAC,
and we don't want to decrypt that since we need it
"raw". We MUST however decrypt the padding data
since it is used for the hash later on. */
int skip = session->remote.mac->mac_len;
/* if what we have plus numbytes is bigger than the
total minus the skip margin, we should lower the
amount to decrypt even more */
if((p->data_num + numbytes) > (p->total_num - skip)) {
numdecrypt = (p->total_num - skip) - p->data_num;
}
else {
int frac;
numdecrypt = numbytes;
frac = numdecrypt % blocksize;
if(frac) {
/* not an aligned amount of blocks,
align it */
numdecrypt -= frac;
/* and make it no unencrypted data
after it */
numbytes = 0;
}
}
}
else {
/* unencrypted data should not be decrypted at all */
numdecrypt = 0;
}
/* if there are bytes to decrypt, do that */
if(numdecrypt > 0) {
/* now decrypt the lot */
rc = decrypt(session, &p->buf[p->readidx], p->wptr, numdecrypt);
if(rc != LIBSSH2_ERROR_NONE) {
p->total_num = 0; /* no packet buffer available */
return rc;
}
/* advance the read pointer */
p->readidx += numdecrypt;
/* advance write pointer */
p->wptr += numdecrypt;
/* increase data_num */
p->data_num += numdecrypt;
/* bytes left to take care of without decryption */
numbytes -= numdecrypt;
}
/* if there are bytes to copy that aren't decrypted, simply
copy them as-is to the target buffer */
if(numbytes > 0) {
memcpy(p->wptr, &p->buf[p->readidx], numbytes);
/* advance the read pointer */
p->readidx += numbytes;
/* advance write pointer */
p->wptr += numbytes;
/* increase data_num */
p->data_num += numbytes;
}
/* now check how much data there's left to read to finish the
current packet */
remainpack = p->total_num - p->data_num;
if(!remainpack) {
/* we have a full packet */
libssh2_transport_read_point1:
rc = fullpacket(session, encrypted);
if(rc == LIBSSH2_ERROR_EAGAIN) {
if(session->packAdd_state != libssh2_NB_state_idle) {
/* fullpacket only returns LIBSSH2_ERROR_EAGAIN if
* libssh2_packet_add returns LIBSSH2_ERROR_EAGAIN. If that
* returns LIBSSH2_ERROR_EAGAIN but the packAdd_state is idle,
* then the packet has been added to the brigade, but some
* immediate action that was taken based on the packet
* type (such as key re-exchange) is not yet complete.
* Clear the way for a new packet to be read in.
*/
session->readPack_encrypted = encrypted;
session->readPack_state = libssh2_NB_state_jump1;
}
return rc;
}
p->total_num = 0; /* no packet buffer available */
return rc;
}
} while(1); /* loop */
return LIBSSH2_ERROR_SOCKET_RECV; /* we never reach this point */
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Security fixes (#315)
* Bounds checks
Fixes for CVEs
https://www.libssh2.org/CVE-2019-3863.html
https://www.libssh2.org/CVE-2019-3856.html
* Packet length bounds check
CVE
https://www.libssh2.org/CVE-2019-3855.html
* Response length check
CVE
https://www.libssh2.org/CVE-2019-3859.html
* Bounds check
CVE
https://www.libssh2.org/CVE-2019-3857.html
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
and additional data validation
* Check bounds before reading into buffers
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
* declare SIZE_MAX and UINT_MAX if needed'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: userauth_hostbased_fromfile(LIBSSH2_SESSION *session,
const char *username, size_t username_len,
const char *publickey, const char *privatekey,
const char *passphrase, const char *hostname,
size_t hostname_len,
const char *local_username,
size_t local_username_len)
{
int rc;
#if !LIBSSH2_RSA
return _libssh2_error(session, LIBSSH2_ERROR_METHOD_NOT_SUPPORTED,
"RSA is not supported by crypto backend");
#endif
if(session->userauth_host_state == libssh2_NB_state_idle) {
const LIBSSH2_HOSTKEY_METHOD *privkeyobj;
unsigned char *pubkeydata, *sig = NULL;
size_t pubkeydata_len = 0;
size_t sig_len = 0;
void *abstract;
unsigned char buf[5];
struct iovec datavec[4];
/* Zero the whole thing out */
memset(&session->userauth_host_packet_requirev_state, 0,
sizeof(session->userauth_host_packet_requirev_state));
if(publickey) {
rc = file_read_publickey(session, &session->userauth_host_method,
&session->userauth_host_method_len,
&pubkeydata, &pubkeydata_len, publickey);
if(rc)
/* Note: file_read_publickey() calls _libssh2_error() */
return rc;
}
else {
/* Compute public key from private key. */
rc = _libssh2_pub_priv_keyfile(session,
&session->userauth_host_method,
&session->userauth_host_method_len,
&pubkeydata, &pubkeydata_len,
privatekey, passphrase);
if(rc)
/* libssh2_pub_priv_keyfile calls _libssh2_error() */
return rc;
}
/*
* 52 = packet_type(1) + username_len(4) + servicename_len(4) +
* service_name(14)"ssh-connection" + authmethod_len(4) +
* authmethod(9)"hostbased" + method_len(4) + pubkeydata_len(4) +
* hostname_len(4) + local_username_len(4)
*/
session->userauth_host_packet_len =
username_len + session->userauth_host_method_len + hostname_len +
local_username_len + pubkeydata_len + 52;
/*
* Preallocate space for an overall length, method name again,
* and the signature, which won't be any larger than the size of
* the publickeydata itself
*/
session->userauth_host_s = session->userauth_host_packet =
LIBSSH2_ALLOC(session,
session->userauth_host_packet_len + 4 +
(4 + session->userauth_host_method_len) +
(4 + pubkeydata_len));
if(!session->userauth_host_packet) {
LIBSSH2_FREE(session, session->userauth_host_method);
session->userauth_host_method = NULL;
LIBSSH2_FREE(session, pubkeydata);
return _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
"Out of memory");
}
*(session->userauth_host_s++) = SSH_MSG_USERAUTH_REQUEST;
_libssh2_store_str(&session->userauth_host_s, username, username_len);
_libssh2_store_str(&session->userauth_host_s, "ssh-connection", 14);
_libssh2_store_str(&session->userauth_host_s, "hostbased", 9);
_libssh2_store_str(&session->userauth_host_s,
(const char *)session->userauth_host_method,
session->userauth_host_method_len);
_libssh2_store_str(&session->userauth_host_s, (const char *)pubkeydata,
pubkeydata_len);
LIBSSH2_FREE(session, pubkeydata);
_libssh2_store_str(&session->userauth_host_s, hostname, hostname_len);
_libssh2_store_str(&session->userauth_host_s, local_username,
local_username_len);
rc = file_read_privatekey(session, &privkeyobj, &abstract,
session->userauth_host_method,
session->userauth_host_method_len,
privatekey, passphrase);
if(rc) {
/* Note: file_read_privatekey() calls _libssh2_error() */
LIBSSH2_FREE(session, session->userauth_host_method);
session->userauth_host_method = NULL;
LIBSSH2_FREE(session, session->userauth_host_packet);
session->userauth_host_packet = NULL;
return rc;
}
_libssh2_htonu32(buf, session->session_id_len);
libssh2_prepare_iovec(datavec, 4);
datavec[0].iov_base = (void *)buf;
datavec[0].iov_len = 4;
datavec[1].iov_base = (void *)session->session_id;
datavec[1].iov_len = session->session_id_len;
datavec[2].iov_base = (void *)session->userauth_host_packet;
datavec[2].iov_len = session->userauth_host_packet_len;
if(privkeyobj && privkeyobj->signv &&
privkeyobj->signv(session, &sig, &sig_len, 3,
datavec, &abstract)) {
LIBSSH2_FREE(session, session->userauth_host_method);
session->userauth_host_method = NULL;
LIBSSH2_FREE(session, session->userauth_host_packet);
session->userauth_host_packet = NULL;
if(privkeyobj->dtor) {
privkeyobj->dtor(session, &abstract);
}
return -1;
}
if(privkeyobj && privkeyobj->dtor) {
privkeyobj->dtor(session, &abstract);
}
if(sig_len > pubkeydata_len) {
unsigned char *newpacket;
/* Should *NEVER* happen, but...well.. better safe than sorry */
newpacket = LIBSSH2_REALLOC(session, session->userauth_host_packet,
session->userauth_host_packet_len + 4 +
(4 + session->userauth_host_method_len)
+ (4 + sig_len)); /* PK sigblob */
if(!newpacket) {
LIBSSH2_FREE(session, sig);
LIBSSH2_FREE(session, session->userauth_host_packet);
session->userauth_host_packet = NULL;
LIBSSH2_FREE(session, session->userauth_host_method);
session->userauth_host_method = NULL;
return _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
"Failed allocating additional space for "
"userauth-hostbased packet");
}
session->userauth_host_packet = newpacket;
}
session->userauth_host_s =
session->userauth_host_packet + session->userauth_host_packet_len;
_libssh2_store_u32(&session->userauth_host_s,
4 + session->userauth_host_method_len + 4 + sig_len);
_libssh2_store_str(&session->userauth_host_s,
(const char *)session->userauth_host_method,
session->userauth_host_method_len);
LIBSSH2_FREE(session, session->userauth_host_method);
session->userauth_host_method = NULL;
_libssh2_store_str(&session->userauth_host_s, (const char *)sig,
sig_len);
LIBSSH2_FREE(session, sig);
_libssh2_debug(session, LIBSSH2_TRACE_AUTH,
"Attempting hostbased authentication");
session->userauth_host_state = libssh2_NB_state_created;
}
if(session->userauth_host_state == libssh2_NB_state_created) {
rc = _libssh2_transport_send(session, session->userauth_host_packet,
session->userauth_host_s -
session->userauth_host_packet,
NULL, 0);
if(rc == LIBSSH2_ERROR_EAGAIN) {
return _libssh2_error(session, LIBSSH2_ERROR_EAGAIN, "Would block");
}
else if(rc) {
LIBSSH2_FREE(session, session->userauth_host_packet);
session->userauth_host_packet = NULL;
session->userauth_host_state = libssh2_NB_state_idle;
return _libssh2_error(session, LIBSSH2_ERROR_SOCKET_SEND,
"Unable to send userauth-hostbased request");
}
LIBSSH2_FREE(session, session->userauth_host_packet);
session->userauth_host_packet = NULL;
session->userauth_host_state = libssh2_NB_state_sent;
}
if(session->userauth_host_state == libssh2_NB_state_sent) {
static const unsigned char reply_codes[3] =
{ SSH_MSG_USERAUTH_SUCCESS, SSH_MSG_USERAUTH_FAILURE, 0 };
size_t data_len;
rc = _libssh2_packet_requirev(session, reply_codes,
&session->userauth_host_data,
&data_len, 0, NULL, 0,
&session->
userauth_host_packet_requirev_state);
if(rc == LIBSSH2_ERROR_EAGAIN) {
return _libssh2_error(session, LIBSSH2_ERROR_EAGAIN, "Would block");
}
session->userauth_host_state = libssh2_NB_state_idle;
if(rc) {
return _libssh2_error(session, LIBSSH2_ERROR_PUBLICKEY_UNVERIFIED,
"Auth failed");
}
if(session->userauth_host_data[0] == SSH_MSG_USERAUTH_SUCCESS) {
_libssh2_debug(session, LIBSSH2_TRACE_AUTH,
"Hostbased authentication successful");
/* We are us and we've proved it. */
LIBSSH2_FREE(session, session->userauth_host_data);
session->userauth_host_data = NULL;
session->state |= LIBSSH2_STATE_AUTHENTICATED;
return 0;
}
}
/* This public key is not allowed for this user on this server */
LIBSSH2_FREE(session, session->userauth_host_data);
session->userauth_host_data = NULL;
return _libssh2_error(session, LIBSSH2_ERROR_PUBLICKEY_UNVERIFIED,
"Invalid signature for supplied public key, or bad "
"username/public key combination");
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Security fixes (#315)
* Bounds checks
Fixes for CVEs
https://www.libssh2.org/CVE-2019-3863.html
https://www.libssh2.org/CVE-2019-3856.html
* Packet length bounds check
CVE
https://www.libssh2.org/CVE-2019-3855.html
* Response length check
CVE
https://www.libssh2.org/CVE-2019-3859.html
* Bounds check
CVE
https://www.libssh2.org/CVE-2019-3857.html
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
and additional data validation
* Check bounds before reading into buffers
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
* declare SIZE_MAX and UINT_MAX if needed'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: _libssh2_channel_process_startup(LIBSSH2_CHANNEL *channel,
const char *request, size_t request_len,
const char *message, size_t message_len)
{
LIBSSH2_SESSION *session = channel->session;
unsigned char *s;
static const unsigned char reply_codes[3] =
{ SSH_MSG_CHANNEL_SUCCESS, SSH_MSG_CHANNEL_FAILURE, 0 };
int rc;
if(channel->process_state == libssh2_NB_state_end) {
return _libssh2_error(session, LIBSSH2_ERROR_BAD_USE,
"Channel can not be reused");
}
if(channel->process_state == libssh2_NB_state_idle) {
/* 10 = packet_type(1) + channel(4) + request_len(4) + want_reply(1) */
channel->process_packet_len = request_len + 10;
/* Zero the whole thing out */
memset(&channel->process_packet_requirev_state, 0,
sizeof(channel->process_packet_requirev_state));
if(message)
channel->process_packet_len += + 4;
_libssh2_debug(session, LIBSSH2_TRACE_CONN,
"starting request(%s) on channel %lu/%lu, message=%s",
request, channel->local.id, channel->remote.id,
message ? message : "<null>");
s = channel->process_packet =
LIBSSH2_ALLOC(session, channel->process_packet_len);
if(!channel->process_packet)
return _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
"Unable to allocate memory "
"for channel-process request");
*(s++) = SSH_MSG_CHANNEL_REQUEST;
_libssh2_store_u32(&s, channel->remote.id);
_libssh2_store_str(&s, request, request_len);
*(s++) = 0x01;
if(message)
_libssh2_store_u32(&s, message_len);
channel->process_state = libssh2_NB_state_created;
}
if(channel->process_state == libssh2_NB_state_created) {
rc = _libssh2_transport_send(session,
channel->process_packet,
channel->process_packet_len,
(unsigned char *)message, message_len);
if(rc == LIBSSH2_ERROR_EAGAIN) {
_libssh2_error(session, rc,
"Would block sending channel request");
return rc;
}
else if(rc) {
LIBSSH2_FREE(session, channel->process_packet);
channel->process_packet = NULL;
channel->process_state = libssh2_NB_state_end;
return _libssh2_error(session, rc,
"Unable to send channel request");
}
LIBSSH2_FREE(session, channel->process_packet);
channel->process_packet = NULL;
_libssh2_htonu32(channel->process_local_channel, channel->local.id);
channel->process_state = libssh2_NB_state_sent;
}
if(channel->process_state == libssh2_NB_state_sent) {
unsigned char *data;
size_t data_len;
unsigned char code;
rc = _libssh2_packet_requirev(session, reply_codes, &data, &data_len,
1, channel->process_local_channel, 4,
&channel->process_packet_requirev_state);
if(rc == LIBSSH2_ERROR_EAGAIN) {
return rc;
}
else if(rc) {
channel->process_state = libssh2_NB_state_end;
return _libssh2_error(session, rc,
"Failed waiting for channel success");
}
code = data[0];
LIBSSH2_FREE(session, data);
channel->process_state = libssh2_NB_state_end;
if(code == SSH_MSG_CHANNEL_SUCCESS)
return 0;
}
return _libssh2_error(session, LIBSSH2_ERROR_CHANNEL_REQUEST_DENIED,
"Unable to complete request for "
"channel-process-startup");
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Security fixes (#315)
* Bounds checks
Fixes for CVEs
https://www.libssh2.org/CVE-2019-3863.html
https://www.libssh2.org/CVE-2019-3856.html
* Packet length bounds check
CVE
https://www.libssh2.org/CVE-2019-3855.html
* Response length check
CVE
https://www.libssh2.org/CVE-2019-3859.html
* Bounds check
CVE
https://www.libssh2.org/CVE-2019-3857.html
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
and additional data validation
* Check bounds before reading into buffers
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
* declare SIZE_MAX and UINT_MAX if needed'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: hostkey_method_ssh_dss_sig_verify(LIBSSH2_SESSION * session,
const unsigned char *sig,
size_t sig_len,
const unsigned char *m,
size_t m_len, void **abstract)
{
libssh2_dsa_ctx *dsactx = (libssh2_dsa_ctx *) (*abstract);
/* Skip past keyname_len(4) + keyname(7){"ssh-dss"} + signature_len(4) */
sig += 15;
sig_len -= 15;
if(sig_len != 40) {
return _libssh2_error(session, LIBSSH2_ERROR_PROTO,
"Invalid DSS signature length");
}
return _libssh2_dsa_sha1_verify(dsactx, sig, m, m_len);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Security fixes (#315)
* Bounds checks
Fixes for CVEs
https://www.libssh2.org/CVE-2019-3863.html
https://www.libssh2.org/CVE-2019-3856.html
* Packet length bounds check
CVE
https://www.libssh2.org/CVE-2019-3855.html
* Response length check
CVE
https://www.libssh2.org/CVE-2019-3859.html
* Bounds check
CVE
https://www.libssh2.org/CVE-2019-3857.html
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
and additional data validation
* Check bounds before reading into buffers
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
* declare SIZE_MAX and UINT_MAX if needed'</s> |
<s>[INST] Given the following code containing errors, provide 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
kex_method_diffie_hellman_group_exchange_sha1_key_exchange
(LIBSSH2_SESSION * session, key_exchange_state_low_t * key_state)
{
unsigned long p_len, g_len;
int ret = 0;
int rc;
if(key_state->state == libssh2_NB_state_idle) {
key_state->p = _libssh2_bn_init_from_bin();
key_state->g = _libssh2_bn_init_from_bin();
/* Ask for a P and G pair */
#ifdef LIBSSH2_DH_GEX_NEW
key_state->request[0] = SSH_MSG_KEX_DH_GEX_REQUEST;
_libssh2_htonu32(key_state->request + 1, LIBSSH2_DH_GEX_MINGROUP);
_libssh2_htonu32(key_state->request + 5, LIBSSH2_DH_GEX_OPTGROUP);
_libssh2_htonu32(key_state->request + 9, LIBSSH2_DH_GEX_MAXGROUP);
key_state->request_len = 13;
_libssh2_debug(session, LIBSSH2_TRACE_KEX,
"Initiating Diffie-Hellman Group-Exchange (New Method)");
#else
key_state->request[0] = SSH_MSG_KEX_DH_GEX_REQUEST_OLD;
_libssh2_htonu32(key_state->request + 1, LIBSSH2_DH_GEX_OPTGROUP);
key_state->request_len = 5;
_libssh2_debug(session, LIBSSH2_TRACE_KEX,
"Initiating Diffie-Hellman Group-Exchange (Old Method)");
#endif
key_state->state = libssh2_NB_state_created;
}
if(key_state->state == libssh2_NB_state_created) {
rc = _libssh2_transport_send(session, key_state->request,
key_state->request_len, NULL, 0);
if(rc == LIBSSH2_ERROR_EAGAIN) {
return rc;
}
else if(rc) {
ret = _libssh2_error(session, rc,
"Unable to send Group Exchange Request");
goto dh_gex_clean_exit;
}
key_state->state = libssh2_NB_state_sent;
}
if(key_state->state == libssh2_NB_state_sent) {
rc = _libssh2_packet_require(session, SSH_MSG_KEX_DH_GEX_GROUP,
&key_state->data, &key_state->data_len,
0, NULL, 0, &key_state->req_state);
if(rc == LIBSSH2_ERROR_EAGAIN) {
return rc;
}
else if(rc) {
ret = _libssh2_error(session, rc,
"Timeout waiting for GEX_GROUP reply");
goto dh_gex_clean_exit;
}
key_state->state = libssh2_NB_state_sent1;
}
if(key_state->state == libssh2_NB_state_sent1) {
unsigned char *s = key_state->data + 1;
p_len = _libssh2_ntohu32(s);
s += 4;
_libssh2_bn_from_bin(key_state->p, p_len, s);
s += p_len;
g_len = _libssh2_ntohu32(s);
s += 4;
_libssh2_bn_from_bin(key_state->g, g_len, s);
ret = diffie_hellman_sha1(session, key_state->g, key_state->p, p_len,
SSH_MSG_KEX_DH_GEX_INIT,
SSH_MSG_KEX_DH_GEX_REPLY,
key_state->data + 1,
key_state->data_len - 1,
&key_state->exchange_state);
if(ret == LIBSSH2_ERROR_EAGAIN) {
return ret;
}
LIBSSH2_FREE(session, key_state->data);
}
dh_gex_clean_exit:
key_state->state = libssh2_NB_state_idle;
_libssh2_bn_free(key_state->g);
key_state->g = NULL;
_libssh2_bn_free(key_state->p);
key_state->p = NULL;
; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Security fixes (#315)
* Bounds checks
Fixes for CVEs
https://www.libssh2.org/CVE-2019-3863.html
https://www.libssh2.org/CVE-2019-3856.html
* Packet length bounds check
CVE
https://www.libssh2.org/CVE-2019-3855.html
* Response length check
CVE
https://www.libssh2.org/CVE-2019-3859.html
* Bounds check
CVE
https://www.libssh2.org/CVE-2019-3857.html
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
and additional data validation
* Check bounds before reading into buffers
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
* declare SIZE_MAX and UINT_MAX if needed'</s> |
<s>[INST] Given the following code containing errors, provide 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 channel_setenv(LIBSSH2_CHANNEL *channel,
const char *varname, unsigned int varname_len,
const char *value, unsigned int value_len)
{
LIBSSH2_SESSION *session = channel->session;
unsigned char *s, *data;
static const unsigned char reply_codes[3] =
{ SSH_MSG_CHANNEL_SUCCESS, SSH_MSG_CHANNEL_FAILURE, 0 };
size_t data_len;
int rc;
if(channel->setenv_state == libssh2_NB_state_idle) {
/* 21 = packet_type(1) + channel_id(4) + request_len(4) +
* request(3)"env" + want_reply(1) + varname_len(4) + value_len(4) */
channel->setenv_packet_len = varname_len + value_len + 21;
/* Zero the whole thing out */
memset(&channel->setenv_packet_requirev_state, 0,
sizeof(channel->setenv_packet_requirev_state));
_libssh2_debug(session, LIBSSH2_TRACE_CONN,
"Setting remote environment variable: %s=%s on "
"channel %lu/%lu",
varname, value, channel->local.id, channel->remote.id);
s = channel->setenv_packet =
LIBSSH2_ALLOC(session, channel->setenv_packet_len);
if(!channel->setenv_packet) {
return _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
"Unable to allocate memory "
"for setenv packet");
}
*(s++) = SSH_MSG_CHANNEL_REQUEST;
_libssh2_store_u32(&s, channel->remote.id);
_libssh2_store_str(&s, "env", sizeof("env") - 1);
*(s++) = 0x01;
_libssh2_store_str(&s, varname, varname_len);
_libssh2_store_str(&s, value, value_len);
channel->setenv_state = libssh2_NB_state_created;
}
if(channel->setenv_state == libssh2_NB_state_created) {
rc = _libssh2_transport_send(session,
channel->setenv_packet,
channel->setenv_packet_len,
NULL, 0);
if(rc == LIBSSH2_ERROR_EAGAIN) {
_libssh2_error(session, rc,
"Would block sending setenv request");
return rc;
}
else if(rc) {
LIBSSH2_FREE(session, channel->setenv_packet);
channel->setenv_packet = NULL;
channel->setenv_state = libssh2_NB_state_idle;
return _libssh2_error(session, LIBSSH2_ERROR_SOCKET_SEND,
"Unable to send channel-request packet for "
"setenv request");
}
LIBSSH2_FREE(session, channel->setenv_packet);
channel->setenv_packet = NULL;
_libssh2_htonu32(channel->setenv_local_channel, channel->local.id);
channel->setenv_state = libssh2_NB_state_sent;
}
if(channel->setenv_state == libssh2_NB_state_sent) {
rc = _libssh2_packet_requirev(session, reply_codes, &data, &data_len,
1, channel->setenv_local_channel, 4,
&channel->
setenv_packet_requirev_state);
if(rc == LIBSSH2_ERROR_EAGAIN) {
return rc;
}
if(rc) {
channel->setenv_state = libssh2_NB_state_idle;
return rc;
}
if(data[0] == SSH_MSG_CHANNEL_SUCCESS) {
LIBSSH2_FREE(session, data);
channel->setenv_state = libssh2_NB_state_idle;
return 0;
}
LIBSSH2_FREE(session, data);
}
channel->setenv_state = libssh2_NB_state_idle;
return _libssh2_error(session, LIBSSH2_ERROR_CHANNEL_REQUEST_DENIED,
"Unable to complete request for channel-setenv");
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Security fixes (#315)
* Bounds checks
Fixes for CVEs
https://www.libssh2.org/CVE-2019-3863.html
https://www.libssh2.org/CVE-2019-3856.html
* Packet length bounds check
CVE
https://www.libssh2.org/CVE-2019-3855.html
* Response length check
CVE
https://www.libssh2.org/CVE-2019-3859.html
* Bounds check
CVE
https://www.libssh2.org/CVE-2019-3857.html
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
and additional data validation
* Check bounds before reading into buffers
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
* declare SIZE_MAX and UINT_MAX if needed'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: userauth_keyboard_interactive(LIBSSH2_SESSION * session,
const char *username,
unsigned int username_len,
LIBSSH2_USERAUTH_KBDINT_RESPONSE_FUNC((*response_callback)))
{
unsigned char *s;
int rc;
static const unsigned char reply_codes[4] = {
SSH_MSG_USERAUTH_SUCCESS,
SSH_MSG_USERAUTH_FAILURE, SSH_MSG_USERAUTH_INFO_REQUEST, 0
};
unsigned int language_tag_len;
unsigned int i;
if(session->userauth_kybd_state == libssh2_NB_state_idle) {
session->userauth_kybd_auth_name = NULL;
session->userauth_kybd_auth_instruction = NULL;
session->userauth_kybd_num_prompts = 0;
session->userauth_kybd_auth_failure = 1;
session->userauth_kybd_prompts = NULL;
session->userauth_kybd_responses = NULL;
/* Zero the whole thing out */
memset(&session->userauth_kybd_packet_requirev_state, 0,
sizeof(session->userauth_kybd_packet_requirev_state));
session->userauth_kybd_packet_len =
1 /* byte SSH_MSG_USERAUTH_REQUEST */
+ 4 + username_len /* string user name (ISO-10646 UTF-8, as
defined in [RFC-3629]) */
+ 4 + 14 /* string service name (US-ASCII) */
+ 4 + 20 /* string "keyboard-interactive" (US-ASCII) */
+ 4 + 0 /* string language tag (as defined in
[RFC-3066]) */
+ 4 + 0 /* string submethods (ISO-10646 UTF-8) */
;
session->userauth_kybd_data = s =
LIBSSH2_ALLOC(session, session->userauth_kybd_packet_len);
if(!s) {
return _libssh2_error(session, LIBSSH2_ERROR_ALLOC,
"Unable to allocate memory for "
"keyboard-interactive authentication");
}
*s++ = SSH_MSG_USERAUTH_REQUEST;
/* user name */
_libssh2_store_str(&s, username, username_len);
/* service name */
_libssh2_store_str(&s, "ssh-connection", sizeof("ssh-connection") - 1);
/* "keyboard-interactive" */
_libssh2_store_str(&s, "keyboard-interactive",
sizeof("keyboard-interactive") - 1);
/* language tag */
_libssh2_store_u32(&s, 0);
/* submethods */
_libssh2_store_u32(&s, 0);
_libssh2_debug(session, LIBSSH2_TRACE_AUTH,
"Attempting keyboard-interactive authentication");
session->userauth_kybd_state = libssh2_NB_state_created;
}
if(session->userauth_kybd_state == libssh2_NB_state_created) {
rc = _libssh2_transport_send(session, session->userauth_kybd_data,
session->userauth_kybd_packet_len,
NULL, 0);
if(rc == LIBSSH2_ERROR_EAGAIN) {
return _libssh2_error(session, LIBSSH2_ERROR_EAGAIN, "Would block");
}
else if(rc) {
LIBSSH2_FREE(session, session->userauth_kybd_data);
session->userauth_kybd_data = NULL;
session->userauth_kybd_state = libssh2_NB_state_idle;
return _libssh2_error(session, LIBSSH2_ERROR_SOCKET_SEND,
"Unable to send keyboard-interactive request");
}
LIBSSH2_FREE(session, session->userauth_kybd_data);
session->userauth_kybd_data = NULL;
session->userauth_kybd_state = libssh2_NB_state_sent;
}
for(;;) {
if(session->userauth_kybd_state == libssh2_NB_state_sent) {
rc = _libssh2_packet_requirev(session, reply_codes,
&session->userauth_kybd_data,
&session->userauth_kybd_data_len,
0, NULL, 0,
&session->
userauth_kybd_packet_requirev_state);
if(rc == LIBSSH2_ERROR_EAGAIN) {
return _libssh2_error(session, LIBSSH2_ERROR_EAGAIN,
"Would block");
}
else if(rc) {
session->userauth_kybd_state = libssh2_NB_state_idle;
return _libssh2_error(session,
LIBSSH2_ERROR_AUTHENTICATION_FAILED,
"Waiting for keyboard USERAUTH response");
}
if(session->userauth_kybd_data[0] == SSH_MSG_USERAUTH_SUCCESS) {
_libssh2_debug(session, LIBSSH2_TRACE_AUTH,
"Keyboard-interactive authentication successful");
LIBSSH2_FREE(session, session->userauth_kybd_data);
session->userauth_kybd_data = NULL;
session->state |= LIBSSH2_STATE_AUTHENTICATED;
session->userauth_kybd_state = libssh2_NB_state_idle;
return 0;
}
if(session->userauth_kybd_data[0] == SSH_MSG_USERAUTH_FAILURE) {
_libssh2_debug(session, LIBSSH2_TRACE_AUTH,
"Keyboard-interactive authentication failed");
LIBSSH2_FREE(session, session->userauth_kybd_data);
session->userauth_kybd_data = NULL;
session->userauth_kybd_state = libssh2_NB_state_idle;
return _libssh2_error(session,
LIBSSH2_ERROR_AUTHENTICATION_FAILED,
"Authentication failed "
"(keyboard-interactive)");
}
/* server requested PAM-like conversation */
s = session->userauth_kybd_data + 1;
/* string name (ISO-10646 UTF-8) */
session->userauth_kybd_auth_name_len = _libssh2_ntohu32(s);
s += 4;
if(session->userauth_kybd_auth_name_len) {
session->userauth_kybd_auth_name =
LIBSSH2_ALLOC(session,
session->userauth_kybd_auth_name_len);
if(!session->userauth_kybd_auth_name) {
_libssh2_error(session, LIBSSH2_ERROR_ALLOC,
"Unable to allocate memory for "
"keyboard-interactive 'name' "
"request field");
goto cleanup;
}
memcpy(session->userauth_kybd_auth_name, s,
session->userauth_kybd_auth_name_len);
s += session->userauth_kybd_auth_name_len;
}
/* string instruction (ISO-10646 UTF-8) */
session->userauth_kybd_auth_instruction_len = _libssh2_ntohu32(s);
s += 4;
if(session->userauth_kybd_auth_instruction_len) {
session->userauth_kybd_auth_instruction =
LIBSSH2_ALLOC(session,
session->userauth_kybd_auth_instruction_len);
if(!session->userauth_kybd_auth_instruction) {
_libssh2_error(session, LIBSSH2_ERROR_ALLOC,
"Unable to allocate memory for "
"keyboard-interactive 'instruction' "
"request field");
goto cleanup;
}
memcpy(session->userauth_kybd_auth_instruction, s,
session->userauth_kybd_auth_instruction_len);
s += session->userauth_kybd_auth_instruction_len;
}
/* string language tag (as defined in [RFC-3066]) */
language_tag_len = _libssh2_ntohu32(s);
s += 4;
/* ignoring this field as deprecated */
s += language_tag_len;
/* int num-prompts */
session->userauth_kybd_num_prompts = _libssh2_ntohu32(s);
s += 4;
if(session->userauth_kybd_num_prompts) {
session->userauth_kybd_prompts =
LIBSSH2_CALLOC(session,
sizeof(LIBSSH2_USERAUTH_KBDINT_PROMPT) *
session->userauth_kybd_num_prompts);
if(!session->userauth_kybd_prompts) {
_libssh2_error(session, LIBSSH2_ERROR_ALLOC,
"Unable to allocate memory for "
"keyboard-interactive prompts array");
goto cleanup;
}
session->userauth_kybd_responses =
LIBSSH2_CALLOC(session,
sizeof(LIBSSH2_USERAUTH_KBDINT_RESPONSE) *
session->userauth_kybd_num_prompts);
if(!session->userauth_kybd_responses) {
_libssh2_error(session, LIBSSH2_ERROR_ALLOC,
"Unable to allocate memory for "
"keyboard-interactive responses array");
goto cleanup;
}
for(i = 0; i < session->userauth_kybd_num_prompts; i++) {
/* string prompt[1] (ISO-10646 UTF-8) */
session->userauth_kybd_prompts[i].length =
_libssh2_ntohu32(s);
s += 4;
session->userauth_kybd_prompts[i].text =
LIBSSH2_CALLOC(session,
session->userauth_kybd_prompts[i].length);
if(!session->userauth_kybd_prompts[i].text) {
_libssh2_error(session, LIBSSH2_ERROR_ALLOC,
"Unable to allocate memory for "
"keyboard-interactive prompt message");
goto cleanup;
}
memcpy(session->userauth_kybd_prompts[i].text, s,
session->userauth_kybd_prompts[i].length);
s += session->userauth_kybd_prompts[i].length;
/* boolean echo[1] */
session->userauth_kybd_prompts[i].echo = *s++;
}
}
response_callback(session->userauth_kybd_auth_name,
session->userauth_kybd_auth_name_len,
session->userauth_kybd_auth_instruction,
session->userauth_kybd_auth_instruction_len,
session->userauth_kybd_num_prompts,
session->userauth_kybd_prompts,
session->userauth_kybd_responses,
&session->abstract);
_libssh2_debug(session, LIBSSH2_TRACE_AUTH,
"Keyboard-interactive response callback function"
" invoked");
session->userauth_kybd_packet_len =
1 /* byte SSH_MSG_USERAUTH_INFO_RESPONSE */
+ 4 /* int num-responses */
;
for(i = 0; i < session->userauth_kybd_num_prompts; i++) {
/* string response[1] (ISO-10646 UTF-8) */
session->userauth_kybd_packet_len +=
4 + session->userauth_kybd_responses[i].length;
}
/* A new userauth_kybd_data area is to be allocated, free the
former one. */
LIBSSH2_FREE(session, session->userauth_kybd_data);
session->userauth_kybd_data = s =
LIBSSH2_ALLOC(session, session->userauth_kybd_packet_len);
if(!s) {
_libssh2_error(session, LIBSSH2_ERROR_ALLOC,
"Unable to allocate memory for keyboard-"
"interactive response packet");
goto cleanup;
}
*s = SSH_MSG_USERAUTH_INFO_RESPONSE;
s++;
_libssh2_store_u32(&s, session->userauth_kybd_num_prompts);
for(i = 0; i < session->userauth_kybd_num_prompts; i++) {
_libssh2_store_str(&s,
session->userauth_kybd_responses[i].text,
session->userauth_kybd_responses[i].length);
}
session->userauth_kybd_state = libssh2_NB_state_sent1;
}
if(session->userauth_kybd_state == libssh2_NB_state_sent1) {
rc = _libssh2_transport_send(session, session->userauth_kybd_data,
session->userauth_kybd_packet_len,
NULL, 0);
if(rc == LIBSSH2_ERROR_EAGAIN)
return _libssh2_error(session, LIBSSH2_ERROR_EAGAIN,
"Would block");
if(rc) {
_libssh2_error(session, LIBSSH2_ERROR_SOCKET_SEND,
"Unable to send userauth-keyboard-interactive"
" request");
goto cleanup;
}
session->userauth_kybd_auth_failure = 0;
}
cleanup:
/*
* It's safe to clean all the data here, because unallocated pointers
* are filled by zeroes
*/
LIBSSH2_FREE(session, session->userauth_kybd_data);
session->userauth_kybd_data = NULL;
if(session->userauth_kybd_prompts) {
for(i = 0; i < session->userauth_kybd_num_prompts; i++) {
LIBSSH2_FREE(session, session->userauth_kybd_prompts[i].text);
session->userauth_kybd_prompts[i].text = NULL;
}
}
if(session->userauth_kybd_responses) {
for(i = 0; i < session->userauth_kybd_num_prompts; i++) {
LIBSSH2_FREE(session,
session->userauth_kybd_responses[i].text);
session->userauth_kybd_responses[i].text = NULL;
}
}
if(session->userauth_kybd_prompts) {
LIBSSH2_FREE(session, session->userauth_kybd_prompts);
session->userauth_kybd_prompts = NULL;
}
if(session->userauth_kybd_responses) {
LIBSSH2_FREE(session, session->userauth_kybd_responses);
session->userauth_kybd_responses = NULL;
}
if(session->userauth_kybd_auth_name) {
LIBSSH2_FREE(session, session->userauth_kybd_auth_name);
session->userauth_kybd_auth_name = NULL;
}
if(session->userauth_kybd_auth_instruction) {
LIBSSH2_FREE(session, session->userauth_kybd_auth_instruction);
session->userauth_kybd_auth_instruction = NULL;
}
if(session->userauth_kybd_auth_failure) {
session->userauth_kybd_state = libssh2_NB_state_idle;
return -1;
}
session->userauth_kybd_state = libssh2_NB_state_sent;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Security fixes (#315)
* Bounds checks
Fixes for CVEs
https://www.libssh2.org/CVE-2019-3863.html
https://www.libssh2.org/CVE-2019-3856.html
* Packet length bounds check
CVE
https://www.libssh2.org/CVE-2019-3855.html
* Response length check
CVE
https://www.libssh2.org/CVE-2019-3859.html
* Bounds check
CVE
https://www.libssh2.org/CVE-2019-3857.html
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
and additional data validation
* Check bounds before reading into buffers
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
* declare SIZE_MAX and UINT_MAX if needed'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: hostkey_method_ssh_ed25519_init(LIBSSH2_SESSION * session,
const unsigned char *hostkey_data,
size_t hostkey_data_len,
void **abstract)
{
const unsigned char *s;
unsigned long len, key_len;
libssh2_ed25519_ctx *ctx = NULL;
if(*abstract) {
hostkey_method_ssh_ed25519_dtor(session, abstract);
*abstract = NULL;
}
if(hostkey_data_len < 15) {
return -1;
}
s = hostkey_data;
len = _libssh2_ntohu32(s);
s += 4;
if(len != 11 || strncmp((char *) s, "ssh-ed25519", 11) != 0) {
return -1;
}
s += 11;
//public key
key_len = _libssh2_ntohu32(s);
s += 4;
if(_libssh2_ed25519_new_public(&ctx, session, s, key_len) != 0) {
return -1;
}
*abstract = ctx;
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Security fixes (#315)
* Bounds checks
Fixes for CVEs
https://www.libssh2.org/CVE-2019-3863.html
https://www.libssh2.org/CVE-2019-3856.html
* Packet length bounds check
CVE
https://www.libssh2.org/CVE-2019-3855.html
* Response length check
CVE
https://www.libssh2.org/CVE-2019-3859.html
* Bounds check
CVE
https://www.libssh2.org/CVE-2019-3857.html
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
and additional data validation
* Check bounds before reading into buffers
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
* declare SIZE_MAX and UINT_MAX if needed'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ssize_t _libssh2_channel_read(LIBSSH2_CHANNEL *channel, int stream_id,
char *buf, size_t buflen)
{
LIBSSH2_SESSION *session = channel->session;
int rc;
int bytes_read = 0;
int bytes_want;
int unlink_packet;
LIBSSH2_PACKET *read_packet;
LIBSSH2_PACKET *read_next;
_libssh2_debug(session, LIBSSH2_TRACE_CONN,
"channel_read() wants %d bytes from channel %lu/%lu "
"stream #%d",
(int) buflen, channel->local.id, channel->remote.id,
stream_id);
/* expand the receiving window first if it has become too narrow */
if((channel->read_state == libssh2_NB_state_jump1) ||
(channel->remote.window_size < channel->remote.window_size_initial / 4 * 3 + buflen) ) {
uint32_t adjustment = channel->remote.window_size_initial + buflen - channel->remote.window_size;
if(adjustment < LIBSSH2_CHANNEL_MINADJUST)
adjustment = LIBSSH2_CHANNEL_MINADJUST;
/* the actual window adjusting may not finish so we need to deal with
this special state here */
channel->read_state = libssh2_NB_state_jump1;
rc = _libssh2_channel_receive_window_adjust(channel, adjustment,
0, NULL);
if(rc)
return rc;
channel->read_state = libssh2_NB_state_idle;
}
/* Process all pending incoming packets. Tests prove that this way
produces faster transfers. */
do {
rc = _libssh2_transport_read(session);
} while(rc > 0);
if((rc < 0) && (rc != LIBSSH2_ERROR_EAGAIN))
return _libssh2_error(session, rc, "transport read");
read_packet = _libssh2_list_first(&session->packets);
while(read_packet && (bytes_read < (int) buflen)) {
/* previously this loop condition also checked for
!channel->remote.close but we cannot let it do this:
We may have a series of packets to read that are still pending even
if a close has been received. Acknowledging the close too early
makes us flush buffers prematurely and loose data.
*/
LIBSSH2_PACKET *readpkt = read_packet;
/* In case packet gets destroyed during this iteration */
read_next = _libssh2_list_next(&readpkt->node);
channel->read_local_id =
_libssh2_ntohu32(readpkt->data + 1);
/*
* Either we asked for a specific extended data stream
* (and data was available),
* or the standard stream (and data was available),
* or the standard stream with extended_data_merge
* enabled and data was available
*/
if((stream_id
&& (readpkt->data[0] == SSH_MSG_CHANNEL_EXTENDED_DATA)
&& (channel->local.id == channel->read_local_id)
&& (stream_id == (int) _libssh2_ntohu32(readpkt->data + 5)))
|| (!stream_id && (readpkt->data[0] == SSH_MSG_CHANNEL_DATA)
&& (channel->local.id == channel->read_local_id))
|| (!stream_id
&& (readpkt->data[0] == SSH_MSG_CHANNEL_EXTENDED_DATA)
&& (channel->local.id == channel->read_local_id)
&& (channel->remote.extended_data_ignore_mode ==
LIBSSH2_CHANNEL_EXTENDED_DATA_MERGE))) {
/* figure out much more data we want to read */
bytes_want = buflen - bytes_read;
unlink_packet = FALSE;
if(bytes_want >= (int) (readpkt->data_len - readpkt->data_head)) {
/* we want more than this node keeps, so adjust the number and
delete this node after the copy */
bytes_want = readpkt->data_len - readpkt->data_head;
unlink_packet = TRUE;
}
_libssh2_debug(session, LIBSSH2_TRACE_CONN,
"channel_read() got %d of data from %lu/%lu/%d%s",
bytes_want, channel->local.id,
channel->remote.id, stream_id,
unlink_packet?" [ul]":"");
/* copy data from this struct to the target buffer */
memcpy(&buf[bytes_read],
&readpkt->data[readpkt->data_head], bytes_want);
/* advance pointer and counter */
readpkt->data_head += bytes_want;
bytes_read += bytes_want;
/* if drained, remove from list */
if(unlink_packet) {
/* detach readpkt from session->packets list */
_libssh2_list_remove(&readpkt->node);
LIBSSH2_FREE(session, readpkt->data);
LIBSSH2_FREE(session, readpkt);
}
}
/* check the next struct in the chain */
read_packet = read_next;
}
if(!bytes_read) {
/* If the channel is already at EOF or even closed, we need to signal
that back. We may have gotten that info while draining the incoming
transport layer until EAGAIN so we must not be fooled by that
return code. */
if(channel->remote.eof || channel->remote.close)
return 0;
else if(rc != LIBSSH2_ERROR_EAGAIN)
return 0;
/* if the transport layer said EAGAIN then we say so as well */
return _libssh2_error(session, rc, "would block");
}
channel->read_avail -= bytes_read;
channel->remote.window_size -= bytes_read;
return bytes_read;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Security fixes (#315)
* Bounds checks
Fixes for CVEs
https://www.libssh2.org/CVE-2019-3863.html
https://www.libssh2.org/CVE-2019-3856.html
* Packet length bounds check
CVE
https://www.libssh2.org/CVE-2019-3855.html
* Response length check
CVE
https://www.libssh2.org/CVE-2019-3859.html
* Bounds check
CVE
https://www.libssh2.org/CVE-2019-3857.html
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
and additional data validation
* Check bounds before reading into buffers
* Bounds checking
CVE
https://www.libssh2.org/CVE-2019-3859.html
* declare SIZE_MAX and UINT_MAX if needed'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: read_pbm_integer(j_compress_ptr cinfo, FILE *infile, unsigned int maxval)
/* Read an unsigned decimal integer from the PPM file */
/* Swallows one trailing character after the integer */
/* Note that on a 16-bit-int machine, only values up to 64k can be read. */
/* This should not be a problem in practice. */
{
register int ch;
register unsigned int val;
/* Skip any leading whitespace */
do {
ch = pbm_getc(infile);
if (ch == EOF)
ERREXIT(cinfo, JERR_INPUT_EOF);
} while (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r');
if (ch < '0' || ch > '9')
ERREXIT(cinfo, JERR_PPM_NONNUMERIC);
val = ch - '0';
while ((ch = pbm_getc(infile)) >= '0' && ch <= '9') {
val *= 10;
val += ch - '0';
}
if (val > maxval)
ERREXIT(cinfo, JERR_PPM_TOOLARGE);
return val;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200', 'CWE-125'], 'message': 'cjpeg: Fix OOB read caused by malformed 8-bit BMP
... in which one or more of the color indices is out of range for the
number of palette entries.
Fix partly borrowed from jpeg-9c. This commit also adopts Guido's
JERR_PPM_OUTOFRANGE enum value in lieu of our project-specific
JERR_PPM_TOOLARGE enum value.
Fixes #258'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: start_input_bmp(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
{
bmp_source_ptr source = (bmp_source_ptr)sinfo;
U_CHAR bmpfileheader[14];
U_CHAR bmpinfoheader[64];
#define GET_2B(array, offset) \
((unsigned short)UCH(array[offset]) + \
(((unsigned short)UCH(array[offset + 1])) << 8))
#define GET_4B(array, offset) \
((unsigned int)UCH(array[offset]) + \
(((unsigned int)UCH(array[offset + 1])) << 8) + \
(((unsigned int)UCH(array[offset + 2])) << 16) + \
(((unsigned int)UCH(array[offset + 3])) << 24))
unsigned int bfOffBits;
unsigned int headerSize;
int biWidth;
int biHeight;
unsigned short biPlanes;
unsigned int biCompression;
int biXPelsPerMeter, biYPelsPerMeter;
unsigned int biClrUsed = 0;
int mapentrysize = 0; /* 0 indicates no colormap */
int bPad;
JDIMENSION row_width = 0;
/* Read and verify the bitmap file header */
if (!ReadOK(source->pub.input_file, bmpfileheader, 14))
ERREXIT(cinfo, JERR_INPUT_EOF);
if (GET_2B(bmpfileheader, 0) != 0x4D42) /* 'BM' */
ERREXIT(cinfo, JERR_BMP_NOT);
bfOffBits = GET_4B(bmpfileheader, 10);
/* We ignore the remaining fileheader fields */
/* The infoheader might be 12 bytes (OS/2 1.x), 40 bytes (Windows),
* or 64 bytes (OS/2 2.x). Check the first 4 bytes to find out which.
*/
if (!ReadOK(source->pub.input_file, bmpinfoheader, 4))
ERREXIT(cinfo, JERR_INPUT_EOF);
headerSize = GET_4B(bmpinfoheader, 0);
if (headerSize < 12 || headerSize > 64)
ERREXIT(cinfo, JERR_BMP_BADHEADER);
if (!ReadOK(source->pub.input_file, bmpinfoheader + 4, headerSize - 4))
ERREXIT(cinfo, JERR_INPUT_EOF);
switch (headerSize) {
case 12:
/* Decode OS/2 1.x header (Microsoft calls this a BITMAPCOREHEADER) */
biWidth = (int)GET_2B(bmpinfoheader, 4);
biHeight = (int)GET_2B(bmpinfoheader, 6);
biPlanes = GET_2B(bmpinfoheader, 8);
source->bits_per_pixel = (int)GET_2B(bmpinfoheader, 10);
switch (source->bits_per_pixel) {
case 8: /* colormapped image */
mapentrysize = 3; /* OS/2 uses RGBTRIPLE colormap */
TRACEMS2(cinfo, 1, JTRC_BMP_OS2_MAPPED, biWidth, biHeight);
break;
case 24: /* RGB image */
TRACEMS2(cinfo, 1, JTRC_BMP_OS2, biWidth, biHeight);
break;
default:
ERREXIT(cinfo, JERR_BMP_BADDEPTH);
break;
}
break;
case 40:
case 64:
/* Decode Windows 3.x header (Microsoft calls this a BITMAPINFOHEADER) */
/* or OS/2 2.x header, which has additional fields that we ignore */
biWidth = (int)GET_4B(bmpinfoheader, 4);
biHeight = (int)GET_4B(bmpinfoheader, 8);
biPlanes = GET_2B(bmpinfoheader, 12);
source->bits_per_pixel = (int)GET_2B(bmpinfoheader, 14);
biCompression = GET_4B(bmpinfoheader, 16);
biXPelsPerMeter = (int)GET_4B(bmpinfoheader, 24);
biYPelsPerMeter = (int)GET_4B(bmpinfoheader, 28);
biClrUsed = GET_4B(bmpinfoheader, 32);
/* biSizeImage, biClrImportant fields are ignored */
switch (source->bits_per_pixel) {
case 8: /* colormapped image */
mapentrysize = 4; /* Windows uses RGBQUAD colormap */
TRACEMS2(cinfo, 1, JTRC_BMP_MAPPED, biWidth, biHeight);
break;
case 24: /* RGB image */
TRACEMS2(cinfo, 1, JTRC_BMP, biWidth, biHeight);
break;
case 32: /* RGB image + Alpha channel */
TRACEMS2(cinfo, 1, JTRC_BMP, biWidth, biHeight);
break;
default:
ERREXIT(cinfo, JERR_BMP_BADDEPTH);
break;
}
if (biCompression != 0)
ERREXIT(cinfo, JERR_BMP_COMPRESSED);
if (biXPelsPerMeter > 0 && biYPelsPerMeter > 0) {
/* Set JFIF density parameters from the BMP data */
cinfo->X_density = (UINT16)(biXPelsPerMeter / 100); /* 100 cm per meter */
cinfo->Y_density = (UINT16)(biYPelsPerMeter / 100);
cinfo->density_unit = 2; /* dots/cm */
}
break;
default:
ERREXIT(cinfo, JERR_BMP_BADHEADER);
return;
}
if (biWidth <= 0 || biHeight <= 0)
ERREXIT(cinfo, JERR_BMP_EMPTY);
if (biPlanes != 1)
ERREXIT(cinfo, JERR_BMP_BADPLANES);
/* Compute distance to bitmap data --- will adjust for colormap below */
bPad = bfOffBits - (headerSize + 14);
/* Read the colormap, if any */
if (mapentrysize > 0) {
if (biClrUsed <= 0)
biClrUsed = 256; /* assume it's 256 */
else if (biClrUsed > 256)
ERREXIT(cinfo, JERR_BMP_BADCMAP);
/* Allocate space to store the colormap */
source->colormap = (*cinfo->mem->alloc_sarray)
((j_common_ptr)cinfo, JPOOL_IMAGE, (JDIMENSION)biClrUsed, (JDIMENSION)3);
/* and read it from the file */
read_colormap(source, (int)biClrUsed, mapentrysize);
/* account for size of colormap */
bPad -= biClrUsed * mapentrysize;
}
/* Skip any remaining pad bytes */
if (bPad < 0) /* incorrect bfOffBits value? */
ERREXIT(cinfo, JERR_BMP_BADHEADER);
while (--bPad >= 0) {
(void)read_byte(source);
}
/* Compute row width in file, including padding to 4-byte boundary */
switch (source->bits_per_pixel) {
case 8:
if (cinfo->in_color_space == JCS_UNKNOWN)
cinfo->in_color_space = JCS_EXT_RGB;
if (IsExtRGB(cinfo->in_color_space))
cinfo->input_components = rgb_pixelsize[cinfo->in_color_space];
else if (cinfo->in_color_space == JCS_GRAYSCALE)
cinfo->input_components = 1;
else if (cinfo->in_color_space == JCS_CMYK)
cinfo->input_components = 4;
else
ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
row_width = (JDIMENSION)biWidth;
break;
case 24:
if (cinfo->in_color_space == JCS_UNKNOWN)
cinfo->in_color_space = JCS_EXT_BGR;
if (IsExtRGB(cinfo->in_color_space))
cinfo->input_components = rgb_pixelsize[cinfo->in_color_space];
else if (cinfo->in_color_space == JCS_CMYK)
cinfo->input_components = 4;
else
ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
row_width = (JDIMENSION)(biWidth * 3);
break;
case 32:
if (cinfo->in_color_space == JCS_UNKNOWN)
cinfo->in_color_space = JCS_EXT_BGRA;
if (IsExtRGB(cinfo->in_color_space))
cinfo->input_components = rgb_pixelsize[cinfo->in_color_space];
else if (cinfo->in_color_space == JCS_CMYK)
cinfo->input_components = 4;
else
ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
row_width = (JDIMENSION)(biWidth * 4);
break;
default:
ERREXIT(cinfo, JERR_BMP_BADDEPTH);
}
while ((row_width & 3) != 0) row_width++;
source->row_width = row_width;
if (source->use_inversion_array) {
/* Allocate space for inversion array, prepare for preload pass */
source->whole_image = (*cinfo->mem->request_virt_sarray)
((j_common_ptr)cinfo, JPOOL_IMAGE, FALSE,
row_width, (JDIMENSION)biHeight, (JDIMENSION)1);
source->pub.get_pixel_rows = preload_image;
if (cinfo->progress != NULL) {
cd_progress_ptr progress = (cd_progress_ptr)cinfo->progress;
progress->total_extra_passes++; /* count file input as separate pass */
}
} else {
source->iobuffer = (U_CHAR *)
(*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE, row_width);
switch (source->bits_per_pixel) {
case 8:
source->pub.get_pixel_rows = get_8bit_row;
break;
case 24:
source->pub.get_pixel_rows = get_24bit_row;
break;
case 32:
source->pub.get_pixel_rows = get_32bit_row;
break;
default:
ERREXIT(cinfo, JERR_BMP_BADDEPTH);
}
}
/* Ensure that biWidth * cinfo->input_components doesn't exceed the maximum
value of the JDIMENSION type. This is only a danger with BMP files, since
their width and height fields are 32-bit integers. */
if ((unsigned long long)biWidth *
(unsigned long long)cinfo->input_components > 0xFFFFFFFFULL)
ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
/* Allocate one-row buffer for returned data */
source->pub.buffer = (*cinfo->mem->alloc_sarray)
((j_common_ptr)cinfo, JPOOL_IMAGE,
(JDIMENSION)(biWidth * cinfo->input_components), (JDIMENSION)1);
source->pub.buffer_height = 1;
cinfo->data_precision = 8;
cinfo->image_width = (JDIMENSION)biWidth;
cinfo->image_height = (JDIMENSION)biHeight;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200', 'CWE-125'], 'message': 'cjpeg: Fix OOB read caused by malformed 8-bit BMP
... in which one or more of the color indices is out of range for the
number of palette entries.
Fix partly borrowed from jpeg-9c. This commit also adopts Guido's
JERR_PPM_OUTOFRANGE enum value in lieu of our project-specific
JERR_PPM_TOOLARGE enum value.
Fixes #258'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static MagickBooleanType DecodeImage(Image *image,unsigned char *luma,
unsigned char *chroma1,unsigned char *chroma2,ExceptionInfo *exception)
{
#define IsSync(sum) ((sum & 0xffffff00UL) == 0xfffffe00UL)
#define PCDGetBits(n) \
{ \
sum=(sum << n) & 0xffffffff; \
bits-=n; \
while (bits <= 24) \
{ \
if (p >= (buffer+0x800)) \
{ \
count=ReadBlob(image,0x800,buffer); \
p=buffer; \
} \
sum|=((unsigned int) (*p) << (24-bits)); \
bits+=8; \
p++; \
} \
}
typedef struct PCDTable
{
unsigned int
length,
sequence;
MagickStatusType
mask;
unsigned char
key;
} PCDTable;
PCDTable
*pcd_table[3];
register ssize_t
i,
j;
register PCDTable
*r;
register unsigned char
*p,
*q;
size_t
bits,
length,
plane,
pcd_length[3],
row,
sum;
ssize_t
count,
quantum;
unsigned char
*buffer;
/*
Initialize Huffman tables.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(luma != (unsigned char *) NULL);
assert(chroma1 != (unsigned char *) NULL);
assert(chroma2 != (unsigned char *) NULL);
buffer=(unsigned char *) AcquireQuantumMemory(0x800,sizeof(*buffer));
if (buffer == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
sum=0;
bits=32;
p=buffer+0x800;
for (i=0; i < 3; i++)
{
pcd_table[i]=(PCDTable *) NULL;
pcd_length[i]=0;
}
for (i=0; i < (image->columns > 1536 ? 3 : 1); i++)
{
PCDGetBits(8);
length=(sum & 0xff)+1;
pcd_table[i]=(PCDTable *) AcquireQuantumMemory(length,
sizeof(*pcd_table[i]));
if (pcd_table[i] == (PCDTable *) NULL)
{
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
r=pcd_table[i];
for (j=0; j < (ssize_t) length; j++)
{
PCDGetBits(8);
r->length=(unsigned int) (sum & 0xff)+1;
if (r->length > 16)
{
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
return(MagickFalse);
}
PCDGetBits(16);
r->sequence=(unsigned int) (sum & 0xffff) << 16;
PCDGetBits(8);
r->key=(unsigned char) (sum & 0xff);
r->mask=(~((1U << (32-r->length))-1));
r++;
}
pcd_length[i]=(size_t) length;
}
/*
Search for Sync byte.
*/
for (i=0; i < 1; i++)
PCDGetBits(16);
for (i=0; i < 1; i++)
PCDGetBits(16);
while ((sum & 0x00fff000UL) != 0x00fff000UL)
PCDGetBits(8);
while (IsSync(sum) == 0)
PCDGetBits(1);
/*
Recover the Huffman encoded luminance and chrominance deltas.
*/
count=0;
length=0;
plane=0;
row=0;
q=luma;
for ( ; ; )
{
if (IsSync(sum) != 0)
{
/*
Determine plane and row number.
*/
PCDGetBits(16);
row=((sum >> 9) & 0x1fff);
if (row == image->rows)
break;
PCDGetBits(8);
plane=sum >> 30;
PCDGetBits(16);
switch (plane)
{
case 0:
{
q=luma+row*image->columns;
count=(ssize_t) image->columns;
break;
}
case 2:
{
q=chroma1+(row >> 1)*image->columns;
count=(ssize_t) (image->columns >> 1);
plane--;
break;
}
case 3:
{
q=chroma2+(row >> 1)*image->columns;
count=(ssize_t) (image->columns >> 1);
plane--;
break;
}
default:
{
for (i=0; i < (image->columns > 1536 ? 3 : 1); i++)
pcd_table[i]=(PCDTable *) RelinquishMagickMemory(pcd_table[i]);
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
ThrowBinaryException(CorruptImageError,"CorruptImage",
image->filename);
}
}
length=pcd_length[plane];
continue;
}
/*
Decode luminance or chrominance deltas.
*/
r=pcd_table[plane];
for (i=0; ((i < (ssize_t) length) && ((sum & r->mask) != r->sequence)); i++)
r++;
if ((row > image->rows) || (r == (PCDTable *) NULL))
{
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageWarning,"SkipToSyncByte","`%s'",image->filename);
while ((sum & 0x00fff000) != 0x00fff000)
PCDGetBits(8);
while (IsSync(sum) == 0)
PCDGetBits(1);
continue;
}
if (r->key < 128)
quantum=(ssize_t) (*q)+r->key;
else
quantum=(ssize_t) (*q)+r->key-256;
*q=(unsigned char) ((quantum < 0) ? 0 : (quantum > 255) ? 255 : quantum);
q++;
PCDGetBits(r->length);
count--;
}
/*
Relinquish resources.
*/
for (i=0; i < (image->columns > 1536 ? 3 : 1); i++)
pcd_table[i]=(PCDTable *) RelinquishMagickMemory(pcd_table[i]);
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
return(MagickTrue);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399', 'CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1450'</s> |
<s>[INST] Given the following code containing errors, provide 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 replace_cmd(void) {
char n[MAX_FNAME], envstr[MAX_ENVSTR];
FILE *tmp;
int ch, eof, fd;
int error = 0;
entry *e;
uid_t file_owner;
char **envp;
char *safename;
safename = host_specific_filename("#tmp", "XXXXXXXXXX");
if (!safename || !glue_strings(TempFilename, sizeof TempFilename, SPOOL_DIR,
safename, '/')) {
TempFilename[0] = '\0';
fprintf(stderr, "path too long\n");
return (-2);
}
if ((fd = mkstemp(TempFilename)) == -1 || !(tmp = fdopen(fd, "w+"))) {
perror(TempFilename);
if (fd != -1) {
close(fd);
unlink(TempFilename);
}
TempFilename[0] = '\0';
return (-2);
}
(void) signal(SIGHUP, die);
(void) signal(SIGINT, die);
(void) signal(SIGQUIT, die);
/* write a signature at the top of the file.
*
* VERY IMPORTANT: make sure NHEADER_LINES agrees with this code.
*/
/*fprintf(tmp, "# DO NOT EDIT THIS FILE - edit the master and reinstall.\n");
*fprintf(tmp, "# (%s installed on %-24.24s)\n", Filename, ctime(&now));
*fprintf(tmp, "# (Cron version %s)\n", CRON_VERSION);
*/
#ifdef WITH_SELINUX
if (selinux_context)
fprintf(tmp, "SELINUX_ROLE_TYPE=%s\n", selinux_context);
#endif
/* copy the crontab to the tmp
*/
rewind(NewCrontab);
Set_LineNum(1)
while (EOF != (ch = get_char(NewCrontab)))
putc(ch, tmp);
if (ftruncate(fileno(tmp), ftell(tmp)) == -1) {
fprintf(stderr, "%s: error while writing new crontab to %s\n",
ProgramName, TempFilename);
fclose(tmp);
error = -2;
goto done;
}
fflush(tmp);
rewind(tmp);
if (ferror(tmp)) {
fprintf(stderr, "%s: error while writing new crontab to %s\n",
ProgramName, TempFilename);
fclose(tmp);
error = -2;
goto done;
}
/* check the syntax of the file being installed.
*/
/* BUG: was reporting errors after the EOF if there were any errors
* in the file proper -- kludged it by stopping after first error.
* vix 31mar87
*/
Set_LineNum(1 - NHEADER_LINES)
CheckErrorCount = 0;
eof = FALSE;
envp = env_init();
if (envp == NULL) {
fprintf(stderr, "%s: Cannot allocate memory.\n", ProgramName);
fclose(tmp);
error = -2;
goto done;
}
while (!CheckErrorCount && !eof) {
switch (load_env(envstr, tmp)) {
case ERR:
/* check for data before the EOF */
if (envstr[0] != '\0') {
Set_LineNum(LineNumber + 1);
check_error("premature EOF");
}
eof = TRUE;
break;
case FALSE:
e = load_entry(tmp, check_error, pw, envp);
if (e)
free_entry(e);
break;
case TRUE:
break;
}
}
env_free(envp);
if (CheckErrorCount != 0) {
fprintf(stderr, "errors in crontab file, can't install.\n");
fclose(tmp);
error = -1;
goto done;
}
file_owner = (getgid() == geteuid() && getgid() == getegid()) ? ROOT_UID : pw->pw_uid;
#ifdef HAVE_FCHOWN
if (fchown(fileno(tmp), file_owner, (gid_t)-1) < OK) {
perror("fchown");
fclose(tmp);
error = -2;
goto done;
}
#else
if (chown(TempFilename, file_owner, (gid_t)-1) < OK) {
perror("chown");
fclose(tmp);
error = -2;
goto done;
}
#endif
if (fclose(tmp) == EOF) {
perror("fclose");
error = -2;
goto done;
}
if (!glue_strings(n, sizeof n, SPOOL_DIR, User, '/')) {
fprintf(stderr, "path too long\n");
error = -2;
goto done;
}
if (rename(TempFilename, n)) {
fprintf(stderr, "%s: error renaming %s to %s\n",
ProgramName, TempFilename, n);
perror("rename");
error = -2;
goto done;
}
TempFilename[0] = '\0';
log_it(RealUser, Pid, "REPLACE", User, 0);
poke_daemon();
done:
(void) signal(SIGHUP, SIG_DFL);
(void) signal(SIGINT, SIG_DFL);
(void) signal(SIGQUIT, SIG_DFL);
if (TempFilename[0]) {
(void) unlink(TempFilename);
TempFilename[0] = '\0';
}
return (error);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'Fix CVE-2019-9704 and CVE-2019-9705
The users can cause DoS of the crond by loading huge crontab files.
We now allow maximum 1000 environment variables and 1000 crontab entries.
Also the comments and whitespace between the entries and variables
are now limited to 32768 characters.'</s> |
<s>[INST] Given the following code containing errors, provide 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 skip_comments(FILE * file) {
int ch;
while (EOF != (ch = get_char(file))) {
/* ch is now the first character of a line.
*/
while (ch == ' ' || ch == '\t')
ch = get_char(file);
if (ch == EOF)
break;
/* ch is now the first non-blank character of a line.
*/
if (ch != '\n' && ch != '#')
break;
/* ch must be a newline or comment as first non-blank
* character on a line.
*/
while (ch != '\n' && ch != EOF)
ch = get_char(file);
/* ch is now the newline of a line which we're going to
* ignore.
*/
}
if (ch != EOF)
unget_char(ch, file);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'Fix CVE-2019-9704 and CVE-2019-9705
The users can cause DoS of the crond by loading huge crontab files.
We now allow maximum 1000 environment variables and 1000 crontab entries.
Also the comments and whitespace between the entries and variables
are now limited to 32768 characters.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: load_user (int crontab_fd, struct passwd *pw, const char *uname,
const char *fname, const char *tabname) {
char envstr[MAX_ENVSTR];
FILE *file;
user *u;
entry *e;
int status = TRUE, save_errno = 0;
char **envp = NULL, **tenvp;
if (!(file = fdopen(crontab_fd, "r"))) {
save_errno = errno;
log_it(uname, getpid (), "FAILED", "fdopen on crontab_fd in load_user",
save_errno);
close(crontab_fd);
return (NULL);
}
Debug(DPARS, ("load_user()\n"));
/* file is open. build user entry, then read the crontab file.
*/
if ((u = (user *) malloc (sizeof (user))) == NULL) {
save_errno = errno;
goto done;
}
memset(u, 0, sizeof(*u));
if (((u->name = strdup(fname)) == NULL)
|| ((u->tabname = strdup(tabname)) == NULL)) {
save_errno = errno;
goto done;
}
u->system = pw == NULL;
/* init environment. this will be copied/augmented for each entry.
*/
if ((envp = env_init()) == NULL) {
save_errno = errno;
goto done;
}
if (env_set_from_environ(&envp) == FALSE) {
save_errno = errno;
goto done;
}
#ifdef WITH_SELINUX
if (get_security_context(pw == NULL ? NULL : uname,
crontab_fd, &u->scontext, tabname) != 0) {
goto done;
}
#endif
/* load the crontab
*/
while ((status = load_env (envstr, file)) >= OK) {
switch (status) {
case FALSE:
FileName = tabname;
e = load_entry(file, log_error, pw, envp);
if (e) {
e->next = u->crontab;
u->crontab = e;
}
break;
case TRUE:
if ((tenvp = env_set (envp, envstr)) == NULL) {
save_errno = errno;
goto done;
}
envp = tenvp;
break;
}
}
done:
if (status == TRUE) {
log_it(uname, getpid(), "FAILED", "loading cron table",
save_errno);
free_user(u);
u = NULL;
}
if (envp)
env_free(envp);
fclose(file);
Debug(DPARS, ("...load_user() done\n"));
errno = save_errno;
return (u);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'Fix CVE-2019-9704 and CVE-2019-9705
The users can cause DoS of the crond by loading huge crontab files.
We now allow maximum 1000 environment variables and 1000 crontab entries.
Also the comments and whitespace between the entries and variables
are now limited to 32768 characters.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: on_connection_attempt_timeout (gpointer data)
{
ConnectionAttempt *attempt = data;
enumerator_next_async (attempt->data);
g_clear_pointer (&attempt->timeout_source, g_source_unref);
return G_SOURCE_REMOVE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-754'], 'message': 'gsocketclient: Fix criticals
This ensures the parent GTask is kept alive as long as an enumeration
is running and trying to connect.
Closes #1646
Closes #1649'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: g_socket_client_proxy_connect_callback (GObject *object,
GAsyncResult *result,
gpointer user_data)
{
GSocketClientAsyncConnectData *data = user_data;
g_object_unref (data->connection);
data->connection = g_proxy_connect_finish (G_PROXY (object),
result,
&data->last_error);
if (data->connection)
{
g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_PROXY_NEGOTIATED, data->connectable, data->connection);
}
else
{
enumerator_next_async (data);
return;
}
g_socket_client_tls_handshake (data);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-754'], 'message': 'gsocketclient: Fix criticals
This ensures the parent GTask is kept alive as long as an enumeration
is running and trying to connect.
Closes #1646
Closes #1649'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: g_socket_client_tls_handshake_callback (GObject *object,
GAsyncResult *result,
gpointer user_data)
{
GSocketClientAsyncConnectData *data = user_data;
if (g_tls_connection_handshake_finish (G_TLS_CONNECTION (object),
result,
&data->last_error))
{
g_object_unref (data->connection);
data->connection = G_IO_STREAM (object);
g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_TLS_HANDSHAKED, data->connectable, data->connection);
g_socket_client_async_connect_complete (data);
}
else
{
g_object_unref (object);
enumerator_next_async (data);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-754'], 'message': 'gsocketclient: Fix criticals
This ensures the parent GTask is kept alive as long as an enumeration
is running and trying to connect.
Closes #1646
Closes #1649'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: g_socket_client_connected_callback (GObject *source,
GAsyncResult *result,
gpointer user_data)
{
ConnectionAttempt *attempt = user_data;
GSocketClientAsyncConnectData *data = attempt->data;
GSList *l;
GError *error = NULL;
GProxy *proxy;
const gchar *protocol;
/* data is NULL once the task is completed */
if (data && g_task_return_error_if_cancelled (data->task))
{
g_object_unref (data->task);
connection_attempt_unref (attempt);
return;
}
if (attempt->timeout_source)
{
g_source_destroy (attempt->timeout_source);
g_clear_pointer (&attempt->timeout_source, g_source_unref);
}
if (!g_socket_connection_connect_finish (G_SOCKET_CONNECTION (source),
result, &error))
{
if (!g_cancellable_is_cancelled (attempt->cancellable))
{
clarify_connect_error (error, data->connectable, attempt->address);
set_last_error (data, error);
}
else
g_clear_error (&error);
if (data)
{
connection_attempt_remove (attempt);
enumerator_next_async (data);
}
else
connection_attempt_unref (attempt);
return;
}
data->socket = g_steal_pointer (&attempt->socket);
data->connection = g_steal_pointer (&attempt->connection);
for (l = data->connection_attempts; l; l = g_slist_next (l))
{
ConnectionAttempt *attempt_entry = l->data;
g_cancellable_cancel (attempt_entry->cancellable);
attempt_entry->data = NULL;
connection_attempt_unref (attempt_entry);
}
g_slist_free (data->connection_attempts);
data->connection_attempts = NULL;
connection_attempt_unref (attempt);
g_socket_connection_set_cached_remote_address ((GSocketConnection*)data->connection, NULL);
g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_CONNECTED, data->connectable, data->connection);
/* wrong, but backward compatible */
g_socket_set_blocking (data->socket, TRUE);
if (!data->proxy_addr)
{
g_socket_client_tls_handshake (data);
return;
}
protocol = g_proxy_address_get_protocol (data->proxy_addr);
/* The connection should not be anything other than TCP,
* but let's put a safety guard in case
*/
if (!G_IS_TCP_CONNECTION (data->connection))
{
g_critical ("Trying to proxy over non-TCP connection, this is "
"most likely a bug in GLib IO library.");
g_set_error_literal (&data->last_error,
G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
_("Proxying over a non-TCP connection is not supported."));
enumerator_next_async (data);
}
else if (g_hash_table_contains (data->client->priv->app_proxies, protocol))
{
/* Simply complete the connection, we don't want to do TLS handshake
* as the application proxy handling may need proxy handshake first */
g_socket_client_async_connect_complete (data);
}
else if ((proxy = g_proxy_get_default_for_protocol (protocol)))
{
g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_PROXY_NEGOTIATING, data->connectable, data->connection);
g_proxy_connect_async (proxy,
data->connection,
data->proxy_addr,
g_task_get_cancellable (data->task),
g_socket_client_proxy_connect_callback,
data);
g_object_unref (proxy);
}
else
{
g_clear_error (&data->last_error);
g_set_error (&data->last_error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
_("Proxy protocol “%s” is not supported."),
protocol);
enumerator_next_async (data);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-754'], 'message': 'gsocketclient: Fix criticals
This ensures the parent GTask is kept alive as long as an enumeration
is running and trying to connect.
Closes #1646
Closes #1649'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: g_socket_client_connect_async (GSocketClient *client,
GSocketConnectable *connectable,
GCancellable *cancellable,
GAsyncReadyCallback callback,
gpointer user_data)
{
GSocketClientAsyncConnectData *data;
g_return_if_fail (G_IS_SOCKET_CLIENT (client));
data = g_slice_new0 (GSocketClientAsyncConnectData);
data->client = client;
data->connectable = g_object_ref (connectable);
if (can_use_proxy (client))
{
data->enumerator = g_socket_connectable_proxy_enumerate (connectable);
if (client->priv->proxy_resolver &&
G_IS_PROXY_ADDRESS_ENUMERATOR (data->enumerator))
{
g_object_set (G_OBJECT (data->enumerator),
"proxy-resolver", client->priv->proxy_resolver,
NULL);
}
}
else
data->enumerator = g_socket_connectable_enumerate (connectable);
data->task = g_task_new (client, cancellable, callback, user_data);
g_task_set_source_tag (data->task, g_socket_client_connect_async);
g_task_set_task_data (data->task, data, (GDestroyNotify)g_socket_client_async_connect_data_free);
enumerator_next_async (data);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-754'], 'message': 'gsocketclient: Fix criticals
This ensures the parent GTask is kept alive as long as an enumeration
is running and trying to connect.
Closes #1646
Closes #1649'</s> |
<s>[INST] Given the following code containing errors, provide 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_plain_files_rename(php_stream_wrapper *wrapper, const char *url_from, const char *url_to, int options, php_stream_context *context)
{
int ret;
if (!url_from || !url_to) {
return 0;
}
#ifdef PHP_WIN32
if (!php_win32_check_trailing_space(url_from, (int)strlen(url_from))) {
php_win32_docref2_from_error(ERROR_INVALID_NAME, url_from, url_to);
return 0;
}
if (!php_win32_check_trailing_space(url_to, (int)strlen(url_to))) {
php_win32_docref2_from_error(ERROR_INVALID_NAME, url_from, url_to);
return 0;
}
#endif
if (strncasecmp(url_from, "file://", sizeof("file://") - 1) == 0) {
url_from += sizeof("file://") - 1;
}
if (strncasecmp(url_to, "file://", sizeof("file://") - 1) == 0) {
url_to += sizeof("file://") - 1;
}
if (php_check_open_basedir(url_from) || php_check_open_basedir(url_to)) {
return 0;
}
ret = VCWD_RENAME(url_from, url_to);
if (ret == -1) {
#ifndef PHP_WIN32
# ifdef EXDEV
if (errno == EXDEV) {
zend_stat_t sb;
if (php_copy_file(url_from, url_to) == SUCCESS) {
if (VCWD_STAT(url_from, &sb) == 0) {
# if !defined(TSRM_WIN32) && !defined(NETWARE)
if (VCWD_CHMOD(url_to, sb.st_mode)) {
if (errno == EPERM) {
php_error_docref2(NULL, url_from, url_to, E_WARNING, "%s", strerror(errno));
VCWD_UNLINK(url_from);
return 1;
}
php_error_docref2(NULL, url_from, url_to, E_WARNING, "%s", strerror(errno));
return 0;
}
if (VCWD_CHOWN(url_to, sb.st_uid, sb.st_gid)) {
if (errno == EPERM) {
php_error_docref2(NULL, url_from, url_to, E_WARNING, "%s", strerror(errno));
VCWD_UNLINK(url_from);
return 1;
}
php_error_docref2(NULL, url_from, url_to, E_WARNING, "%s", strerror(errno));
return 0;
}
# endif
VCWD_UNLINK(url_from);
return 1;
}
}
php_error_docref2(NULL, url_from, url_to, E_WARNING, "%s", strerror(errno));
return 0;
}
# endif
#endif
#ifdef PHP_WIN32
php_win32_docref2_from_error(GetLastError(), url_from, url_to);
#else
php_error_docref2(NULL, url_from, url_to, E_WARNING, "%s", strerror(errno));
#endif
return 0;
}
/* Clear stat cache (and realpath cache) */
php_clear_stat_cache(1, NULL, 0);
return 1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-264'], 'message': 'Fix bug #77630 - safer rename() procedure
In order to rename safer, we do the following:
- set umask to 077 (unfortunately, not TS, so excluding ZTS)
- chown() first, to set proper group before allowing group access
- chmod() after, even if chown() fails'</s> |
<s>[INST] Given the following code containing errors, provide 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(exif_thumbnail)
{
int ret, arg_c = ZEND_NUM_ARGS();
image_info_type ImageInfo;
zval *stream;
zval *z_width = NULL, *z_height = NULL, *z_imagetype = NULL;
/* Parse arguments */
ZEND_PARSE_PARAMETERS_START(1, 4)
Z_PARAM_ZVAL(stream)
Z_PARAM_OPTIONAL
Z_PARAM_ZVAL(z_width)
Z_PARAM_ZVAL(z_height)
Z_PARAM_ZVAL(z_imagetype)
ZEND_PARSE_PARAMETERS_END();
memset(&ImageInfo, 0, sizeof(ImageInfo));
if (Z_TYPE_P(stream) == IS_RESOURCE) {
php_stream *p_stream = NULL;
php_stream_from_res(p_stream, Z_RES_P(stream));
ret = exif_read_from_stream(&ImageInfo, p_stream, 1, 0);
} else {
convert_to_string(stream);
if (!Z_STRLEN_P(stream)) {
exif_error_docref(NULL EXIFERR_CC, &ImageInfo, E_WARNING, "Filename cannot be empty");
RETURN_FALSE;
}
ret = exif_read_from_file(&ImageInfo, Z_STRVAL_P(stream), 1, 0);
}
if (ret == FALSE) {
exif_discard_imageinfo(&ImageInfo);
RETURN_FALSE;
}
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, &ImageInfo, E_NOTICE, "Thumbnail data %d %d %d, %d x %d", ImageInfo.Thumbnail.data, ImageInfo.Thumbnail.size, ImageInfo.Thumbnail.filetype, ImageInfo.Thumbnail.width, ImageInfo.Thumbnail.height);
#endif
if (!ImageInfo.Thumbnail.data || !ImageInfo.Thumbnail.size) {
exif_discard_imageinfo(&ImageInfo);
RETURN_FALSE;
}
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, &ImageInfo, E_NOTICE, "Returning thumbnail(%d)", ImageInfo.Thumbnail.size);
#endif
ZVAL_STRINGL(return_value, ImageInfo.Thumbnail.data, ImageInfo.Thumbnail.size);
if (arg_c >= 3) {
if (!ImageInfo.Thumbnail.width || !ImageInfo.Thumbnail.height) {
exif_scan_thumbnail(&ImageInfo);
}
ZEND_TRY_ASSIGN_LONG(z_width, ImageInfo.Thumbnail.width);
ZEND_TRY_ASSIGN_LONG(z_height, ImageInfo.Thumbnail.height);
}
if (arg_c >= 4) {
ZEND_TRY_ASSIGN_LONG(z_imagetype, ImageInfo.Thumbnail.filetype);
}
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, &ImageInfo, E_NOTICE, "Discarding info");
#endif
exif_discard_imageinfo(&ImageInfo);
#ifdef EXIF_DEBUG
php_error_docref1(NULL, (Z_TYPE_P(stream) == IS_RESOURCE ? "<stream>" : Z_STRVAL_P(stream)), E_NOTICE, "Done");
#endif
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #77540 - Invalid Read on exif_process_SOFn'</s> |
<s>[INST] Given the following code containing errors, provide 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 exif_process_IFD_in_TIFF(image_info_type *ImageInfo, size_t dir_offset, int section_index)
{
int i, sn, num_entries, sub_section_index = 0;
unsigned char *dir_entry;
char tagname[64];
size_t ifd_size, dir_size, entry_offset, next_offset, entry_length, entry_value=0, fgot;
int entry_tag , entry_type;
tag_table_type tag_table = exif_get_tag_table(section_index);
if (ImageInfo->ifd_nesting_level > MAX_IFD_NESTING_LEVEL) {
return FALSE;
}
if (ImageInfo->FileSize >= dir_offset+2) {
sn = exif_file_sections_add(ImageInfo, M_PSEUDO, 2, NULL);
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Read from TIFF: filesize(x%04X), IFD dir(x%04X + x%04X)", ImageInfo->FileSize, dir_offset, 2);
#endif
php_stream_seek(ImageInfo->infile, dir_offset, SEEK_SET); /* we do not know the order of sections */
php_stream_read(ImageInfo->infile, (char*)ImageInfo->file.list[sn].data, 2);
num_entries = php_ifd_get16u(ImageInfo->file.list[sn].data, ImageInfo->motorola_intel);
dir_size = 2/*num dir entries*/ +12/*length of entry*/*num_entries +4/* offset to next ifd (points to thumbnail or NULL)*/;
if (ImageInfo->FileSize >= dir_offset+dir_size) {
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Read from TIFF: filesize(x%04X), IFD dir(x%04X + x%04X), IFD entries(%d)", ImageInfo->FileSize, dir_offset+2, dir_size-2, num_entries);
#endif
if (exif_file_sections_realloc(ImageInfo, sn, dir_size)) {
return FALSE;
}
php_stream_read(ImageInfo->infile, (char*)(ImageInfo->file.list[sn].data+2), dir_size-2);
/*exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Dump: %s", exif_char_dump(ImageInfo->file.list[sn].data, dir_size, 0));*/
next_offset = php_ifd_get32u(ImageInfo->file.list[sn].data + dir_size - 4, ImageInfo->motorola_intel);
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Read from TIFF done, next offset x%04X", next_offset);
#endif
/* now we have the directory we can look how long it should be */
ifd_size = dir_size;
for(i=0;i<num_entries;i++) {
dir_entry = ImageInfo->file.list[sn].data+2+i*12;
entry_tag = php_ifd_get16u(dir_entry+0, ImageInfo->motorola_intel);
entry_type = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel);
if (entry_type > NUM_FORMATS) {
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Read from TIFF: tag(0x%04X,%12s): Illegal format code 0x%04X, switching to BYTE", entry_tag, exif_get_tagname(entry_tag, tagname, -12, tag_table), entry_type);
/* Since this is repeated in exif_process_IFD_TAG make it a notice here */
/* and make it a warning in the exif_process_IFD_TAG which is called */
/* elsewhere. */
entry_type = TAG_FMT_BYTE;
/*The next line would break the image on writeback: */
/* php_ifd_set16u(dir_entry+2, entry_type, ImageInfo->motorola_intel);*/
}
entry_length = php_ifd_get32u(dir_entry+4, ImageInfo->motorola_intel) * php_tiff_bytes_per_format[entry_type];
if (entry_length <= 4) {
switch(entry_type) {
case TAG_FMT_USHORT:
entry_value = php_ifd_get16u(dir_entry+8, ImageInfo->motorola_intel);
break;
case TAG_FMT_SSHORT:
entry_value = php_ifd_get16s(dir_entry+8, ImageInfo->motorola_intel);
break;
case TAG_FMT_ULONG:
entry_value = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel);
break;
case TAG_FMT_SLONG:
entry_value = php_ifd_get32s(dir_entry+8, ImageInfo->motorola_intel);
break;
}
switch(entry_tag) {
case TAG_IMAGEWIDTH:
case TAG_COMP_IMAGE_WIDTH:
ImageInfo->Width = entry_value;
break;
case TAG_IMAGEHEIGHT:
case TAG_COMP_IMAGE_HEIGHT:
ImageInfo->Height = entry_value;
break;
case TAG_PHOTOMETRIC_INTERPRETATION:
switch (entry_value) {
case PMI_BLACK_IS_ZERO:
case PMI_WHITE_IS_ZERO:
case PMI_TRANSPARENCY_MASK:
ImageInfo->IsColor = 0;
break;
case PMI_RGB:
case PMI_PALETTE_COLOR:
case PMI_SEPARATED:
case PMI_YCBCR:
case PMI_CIELAB:
ImageInfo->IsColor = 1;
break;
}
break;
}
} else {
entry_offset = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel);
/* if entry needs expading ifd cache and entry is at end of current ifd cache. */
/* otherwise there may be huge holes between two entries */
if (entry_offset + entry_length > dir_offset + ifd_size
&& entry_offset == dir_offset + ifd_size) {
ifd_size = entry_offset + entry_length - dir_offset;
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Resize struct: x%04X + x%04X - x%04X = x%04X", entry_offset, entry_length, dir_offset, ifd_size);
#endif
}
}
}
if (ImageInfo->FileSize >= dir_offset + ImageInfo->file.list[sn].size) {
if (ifd_size > dir_size) {
if (dir_offset + ifd_size > ImageInfo->FileSize) {
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Error in TIFF: filesize(x%04X) less than size of IFD(x%04X + x%04X)", ImageInfo->FileSize, dir_offset, ifd_size);
return FALSE;
}
if (exif_file_sections_realloc(ImageInfo, sn, ifd_size)) {
return FALSE;
}
/* read values not stored in directory itself */
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Read from TIFF: filesize(x%04X), IFD(x%04X + x%04X)", ImageInfo->FileSize, dir_offset, ifd_size);
#endif
php_stream_read(ImageInfo->infile, (char*)(ImageInfo->file.list[sn].data+dir_size), ifd_size-dir_size);
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Read from TIFF, done");
#endif
}
/* now process the tags */
for(i=0;i<num_entries;i++) {
dir_entry = ImageInfo->file.list[sn].data+2+i*12;
entry_tag = php_ifd_get16u(dir_entry+0, ImageInfo->motorola_intel);
entry_type = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel);
/*entry_length = php_ifd_get32u(dir_entry+4, ImageInfo->motorola_intel);*/
if (entry_tag == TAG_EXIF_IFD_POINTER ||
entry_tag == TAG_INTEROP_IFD_POINTER ||
entry_tag == TAG_GPS_IFD_POINTER ||
entry_tag == TAG_SUB_IFD
) {
switch(entry_tag) {
case TAG_EXIF_IFD_POINTER:
ImageInfo->sections_found |= FOUND_EXIF;
sub_section_index = SECTION_EXIF;
break;
case TAG_GPS_IFD_POINTER:
ImageInfo->sections_found |= FOUND_GPS;
sub_section_index = SECTION_GPS;
break;
case TAG_INTEROP_IFD_POINTER:
ImageInfo->sections_found |= FOUND_INTEROP;
sub_section_index = SECTION_INTEROP;
break;
case TAG_SUB_IFD:
ImageInfo->sections_found |= FOUND_THUMBNAIL;
sub_section_index = SECTION_THUMBNAIL;
break;
}
entry_offset = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel);
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Next IFD: %s @x%04X", exif_get_sectionname(sub_section_index), entry_offset);
#endif
ImageInfo->ifd_nesting_level++;
exif_process_IFD_in_TIFF(ImageInfo, entry_offset, sub_section_index);
if (section_index!=SECTION_THUMBNAIL && entry_tag==TAG_SUB_IFD) {
if (ImageInfo->Thumbnail.filetype != IMAGE_FILETYPE_UNKNOWN
&& ImageInfo->Thumbnail.size
&& ImageInfo->Thumbnail.offset
&& ImageInfo->read_thumbnail
) {
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "%s THUMBNAIL @0x%04X + 0x%04X", ImageInfo->Thumbnail.data ? "Ignore" : "Read", ImageInfo->Thumbnail.offset, ImageInfo->Thumbnail.size);
#endif
if (!ImageInfo->Thumbnail.data) {
ImageInfo->Thumbnail.data = safe_emalloc(ImageInfo->Thumbnail.size, 1, 0);
php_stream_seek(ImageInfo->infile, ImageInfo->Thumbnail.offset, SEEK_SET);
fgot = php_stream_read(ImageInfo->infile, ImageInfo->Thumbnail.data, ImageInfo->Thumbnail.size);
if (fgot < ImageInfo->Thumbnail.size) {
EXIF_ERRLOG_THUMBEOF(ImageInfo)
efree(ImageInfo->Thumbnail.data);
ImageInfo->Thumbnail.data = NULL;
} else {
exif_thumbnail_build(ImageInfo);
}
}
}
}
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Next IFD: %s done", exif_get_sectionname(sub_section_index));
#endif
} else {
if (!exif_process_IFD_TAG(ImageInfo, (char*)dir_entry,
(char*)(ImageInfo->file.list[sn].data-dir_offset),
ifd_size, 0, section_index, 0, tag_table)) {
return FALSE;
}
}
}
/* If we had a thumbnail in a SUB_IFD we have ANOTHER image in NEXT IFD */
if (next_offset && section_index != SECTION_THUMBNAIL) {
/* this should be a thumbnail IFD */
/* the thumbnail itself is stored at Tag=StripOffsets */
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Read next IFD (THUMBNAIL) at x%04X", next_offset);
#endif
ImageInfo->ifd_nesting_level++;
exif_process_IFD_in_TIFF(ImageInfo, next_offset, SECTION_THUMBNAIL);
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "%s THUMBNAIL @0x%04X + 0x%04X", ImageInfo->Thumbnail.data ? "Ignore" : "Read", ImageInfo->Thumbnail.offset, ImageInfo->Thumbnail.size);
#endif
if (!ImageInfo->Thumbnail.data && ImageInfo->Thumbnail.offset && ImageInfo->Thumbnail.size && ImageInfo->read_thumbnail) {
ImageInfo->Thumbnail.data = safe_emalloc(ImageInfo->Thumbnail.size, 1, 0);
php_stream_seek(ImageInfo->infile, ImageInfo->Thumbnail.offset, SEEK_SET);
fgot = php_stream_read(ImageInfo->infile, ImageInfo->Thumbnail.data, ImageInfo->Thumbnail.size);
if (fgot < ImageInfo->Thumbnail.size) {
EXIF_ERRLOG_THUMBEOF(ImageInfo)
efree(ImageInfo->Thumbnail.data);
ImageInfo->Thumbnail.data = NULL;
} else {
exif_thumbnail_build(ImageInfo);
}
}
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Read next IFD (THUMBNAIL) done");
#endif
}
return TRUE;
} else {
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Error in TIFF: filesize(x%04X) less than size of IFD(x%04X)", ImageInfo->FileSize, dir_offset+ImageInfo->file.list[sn].size);
return FALSE;
}
} else {
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Error in TIFF: filesize(x%04X) less than size of IFD dir(x%04X)", ImageInfo->FileSize, dir_offset+dir_size);
return FALSE;
}
} else {
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Error in TIFF: filesize(x%04X) less than start of IFD dir(x%04X)", ImageInfo->FileSize, dir_offset+2);
return FALSE;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-908'], 'message': 'Fix integer overflows on 32-bits'</s> |
<s>[INST] Given the following code containing errors, provide 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 PDFDoc::markObject (Object* obj, XRef *xRef, XRef *countRef, unsigned int numOffset, int oldRefNum, int newRefNum, std::set<Dict*> *alreadyMarkedDicts)
{
Array *array;
switch (obj->getType()) {
case objArray:
array = obj->getArray();
for (int i=0; i<array->getLength(); i++) {
Object obj1 = array->getNF(i).copy();
markObject(&obj1, xRef, countRef, numOffset, oldRefNum, newRefNum);
}
break;
case objDict:
markDictionnary (obj->getDict(), xRef, countRef, numOffset, oldRefNum, newRefNum, alreadyMarkedDicts);
break;
case objStream:
{
Stream *stream = obj->getStream();
markDictionnary (stream->getDict(), xRef, countRef, numOffset, oldRefNum, newRefNum, alreadyMarkedDicts);
}
break;
case objRef:
{
if (obj->getRef().num + (int) numOffset >= xRef->getNumObjects() || xRef->getEntry(obj->getRef().num + numOffset)->type == xrefEntryFree) {
if (getXRef()->getEntry(obj->getRef().num)->type == xrefEntryFree) {
return; // already marked as free => should be replaced
}
xRef->add(obj->getRef().num + numOffset, obj->getRef().gen, 0, true);
if (getXRef()->getEntry(obj->getRef().num)->type == xrefEntryCompressed) {
xRef->getEntry(obj->getRef().num + numOffset)->type = xrefEntryCompressed;
}
}
if (obj->getRef().num + (int) numOffset >= countRef->getNumObjects() ||
countRef->getEntry(obj->getRef().num + numOffset)->type == xrefEntryFree)
{
countRef->add(obj->getRef().num + numOffset, 1, 0, true);
} else {
XRefEntry *entry = countRef->getEntry(obj->getRef().num + numOffset);
entry->gen++;
if (entry->gen > 9)
break;
}
Object obj1 = getXRef()->fetch(obj->getRef());
markObject(&obj1, xRef, countRef, numOffset, oldRefNum, newRefNum);
}
break;
default:
break;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'pdfunite: Fix stack overflow on broken file
Fixes issue #741'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static MagickBooleanType WritePSImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
#define WriteRunlengthPacket(image,pixel,length,p) \
{ \
if ((image->alpha_trait != UndefinedPixelTrait) && (length != 0) && \
(GetPixelAlpha(image,p) == (Quantum) TransparentAlpha)) \
{ \
q=PopHexPixel(hex_digits,0xff,q); \
q=PopHexPixel(hex_digits,0xff,q); \
q=PopHexPixel(hex_digits,0xff,q); \
} \
else \
{ \
q=PopHexPixel(hex_digits,ScaleQuantumToChar(ClampToQuantum(pixel.red)),q); \
q=PopHexPixel(hex_digits,ScaleQuantumToChar(ClampToQuantum(pixel.green)),q); \
q=PopHexPixel(hex_digits,ScaleQuantumToChar(ClampToQuantum(pixel.blue)),q); \
} \
q=PopHexPixel(hex_digits,(size_t) MagickMin(length,0xff),q); \
}
static const char
*const hex_digits[] =
{
"00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B",
"0C", "0D", "0E", "0F", "10", "11", "12", "13", "14", "15", "16", "17",
"18", "19", "1A", "1B", "1C", "1D", "1E", "1F", "20", "21", "22", "23",
"24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F",
"30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B",
"3C", "3D", "3E", "3F", "40", "41", "42", "43", "44", "45", "46", "47",
"48", "49", "4A", "4B", "4C", "4D", "4E", "4F", "50", "51", "52", "53",
"54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F",
"60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B",
"6C", "6D", "6E", "6F", "70", "71", "72", "73", "74", "75", "76", "77",
"78", "79", "7A", "7B", "7C", "7D", "7E", "7F", "80", "81", "82", "83",
"84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F",
"90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B",
"9C", "9D", "9E", "9F", "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7",
"A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF", "B0", "B1", "B2", "B3",
"B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF",
"C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB",
"CC", "CD", "CE", "CF", "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7",
"D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF", "E0", "E1", "E2", "E3",
"E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF",
"F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB",
"FC", "FD", "FE", "FF", (const char *) NULL
},
*const PostscriptProlog[]=
{
"%%BeginProlog",
"%",
"% Display a color image. The image is displayed in color on",
"% Postscript viewers or printers that support color, otherwise",
"% it is displayed as grayscale.",
"%",
"/DirectClassPacket",
"{",
" %",
" % Get a DirectClass packet.",
" %",
" % Parameters:",
" % red.",
" % green.",
" % blue.",
" % length: number of pixels minus one of this color (optional).",
" %",
" currentfile color_packet readhexstring pop pop",
" compression 0 eq",
" {",
" /number_pixels 3 def",
" }",
" {",
" currentfile byte readhexstring pop 0 get",
" /number_pixels exch 1 add 3 mul def",
" } ifelse",
" 0 3 number_pixels 1 sub",
" {",
" pixels exch color_packet putinterval",
" } for",
" pixels 0 number_pixels getinterval",
"} bind def",
"",
"/DirectClassImage",
"{",
" %",
" % Display a DirectClass image.",
" %",
" systemdict /colorimage known",
" {",
" columns rows 8",
" [",
" columns 0 0",
" rows neg 0 rows",
" ]",
" { DirectClassPacket } false 3 colorimage",
" }",
" {",
" %",
" % No colorimage operator; convert to grayscale.",
" %",
" columns rows 8",
" [",
" columns 0 0",
" rows neg 0 rows",
" ]",
" { GrayDirectClassPacket } image",
" } ifelse",
"} bind def",
"",
"/GrayDirectClassPacket",
"{",
" %",
" % Get a DirectClass packet; convert to grayscale.",
" %",
" % Parameters:",
" % red",
" % green",
" % blue",
" % length: number of pixels minus one of this color (optional).",
" %",
" currentfile color_packet readhexstring pop pop",
" color_packet 0 get 0.299 mul",
" color_packet 1 get 0.587 mul add",
" color_packet 2 get 0.114 mul add",
" cvi",
" /gray_packet exch def",
" compression 0 eq",
" {",
" /number_pixels 1 def",
" }",
" {",
" currentfile byte readhexstring pop 0 get",
" /number_pixels exch 1 add def",
" } ifelse",
" 0 1 number_pixels 1 sub",
" {",
" pixels exch gray_packet put",
" } for",
" pixels 0 number_pixels getinterval",
"} bind def",
"",
"/GrayPseudoClassPacket",
"{",
" %",
" % Get a PseudoClass packet; convert to grayscale.",
" %",
" % Parameters:",
" % index: index into the colormap.",
" % length: number of pixels minus one of this color (optional).",
" %",
" currentfile byte readhexstring pop 0 get",
" /offset exch 3 mul def",
" /color_packet colormap offset 3 getinterval def",
" color_packet 0 get 0.299 mul",
" color_packet 1 get 0.587 mul add",
" color_packet 2 get 0.114 mul add",
" cvi",
" /gray_packet exch def",
" compression 0 eq",
" {",
" /number_pixels 1 def",
" }",
" {",
" currentfile byte readhexstring pop 0 get",
" /number_pixels exch 1 add def",
" } ifelse",
" 0 1 number_pixels 1 sub",
" {",
" pixels exch gray_packet put",
" } for",
" pixels 0 number_pixels getinterval",
"} bind def",
"",
"/PseudoClassPacket",
"{",
" %",
" % Get a PseudoClass packet.",
" %",
" % Parameters:",
" % index: index into the colormap.",
" % length: number of pixels minus one of this color (optional).",
" %",
" currentfile byte readhexstring pop 0 get",
" /offset exch 3 mul def",
" /color_packet colormap offset 3 getinterval def",
" compression 0 eq",
" {",
" /number_pixels 3 def",
" }",
" {",
" currentfile byte readhexstring pop 0 get",
" /number_pixels exch 1 add 3 mul def",
" } ifelse",
" 0 3 number_pixels 1 sub",
" {",
" pixels exch color_packet putinterval",
" } for",
" pixels 0 number_pixels getinterval",
"} bind def",
"",
"/PseudoClassImage",
"{",
" %",
" % Display a PseudoClass image.",
" %",
" % Parameters:",
" % class: 0-PseudoClass or 1-Grayscale.",
" %",
" currentfile buffer readline pop",
" token pop /class exch def pop",
" class 0 gt",
" {",
" currentfile buffer readline pop",
" token pop /depth exch def pop",
" /grays columns 8 add depth sub depth mul 8 idiv string def",
" columns rows depth",
" [",
" columns 0 0",
" rows neg 0 rows",
" ]",
" { currentfile grays readhexstring pop } image",
" }",
" {",
" %",
" % Parameters:",
" % colors: number of colors in the colormap.",
" % colormap: red, green, blue color packets.",
" %",
" currentfile buffer readline pop",
" token pop /colors exch def pop",
" /colors colors 3 mul def",
" /colormap colors string def",
" currentfile colormap readhexstring pop pop",
" systemdict /colorimage known",
" {",
" columns rows 8",
" [",
" columns 0 0",
" rows neg 0 rows",
" ]",
" { PseudoClassPacket } false 3 colorimage",
" }",
" {",
" %",
" % No colorimage operator; convert to grayscale.",
" %",
" columns rows 8",
" [",
" columns 0 0",
" rows neg 0 rows",
" ]",
" { GrayPseudoClassPacket } image",
" } ifelse",
" } ifelse",
"} bind def",
"",
"/DisplayImage",
"{",
" %",
" % Display a DirectClass or PseudoClass image.",
" %",
" % Parameters:",
" % x & y translation.",
" % x & y scale.",
" % label pointsize.",
" % image label.",
" % image columns & rows.",
" % class: 0-DirectClass or 1-PseudoClass.",
" % compression: 0-none or 1-RunlengthEncoded.",
" % hex color packets.",
" %",
" gsave",
" /buffer 512 string def",
" /byte 1 string def",
" /color_packet 3 string def",
" /pixels 768 string def",
"",
" currentfile buffer readline pop",
" token pop /x exch def",
" token pop /y exch def pop",
" x y translate",
" currentfile buffer readline pop",
" token pop /x exch def",
" token pop /y exch def pop",
" currentfile buffer readline pop",
" token pop /pointsize exch def pop",
(const char *) NULL
},
*const PostscriptEpilog[]=
{
" x y scale",
" currentfile buffer readline pop",
" token pop /columns exch def",
" token pop /rows exch def pop",
" currentfile buffer readline pop",
" token pop /class exch def pop",
" currentfile buffer readline pop",
" token pop /compression exch def pop",
" class 0 gt { PseudoClassImage } { DirectClassImage } ifelse",
" grestore",
(const char *) NULL
};
char
buffer[MagickPathExtent],
date[MagickPathExtent],
**labels,
page_geometry[MagickPathExtent];
CompressionType
compression;
const char
*const *s,
*value;
const StringInfo
*profile;
double
pointsize;
GeometryInfo
geometry_info;
MagickBooleanType
status;
MagickOffsetType
scene;
MagickStatusType
flags;
PixelInfo
pixel;
PointInfo
delta,
resolution,
scale;
Quantum
index;
RectangleInfo
geometry,
media_info,
page_info;
register const Quantum
*p;
register ssize_t
i,
x;
register unsigned char
*q;
SegmentInfo
bounds;
size_t
bit,
byte,
imageListLength,
length,
page,
text_size;
ssize_t
j,
y;
time_t
timer;
unsigned char
pixels[2048];
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
(void) memset(&bounds,0,sizeof(bounds));
compression=image->compression;
if (image_info->compression != UndefinedCompression)
compression=image_info->compression;
page=1;
scene=0;
imageListLength=GetImageListLength(image);
do
{
/*
Scale relative to dots-per-inch.
*/
(void) TransformImageColorspace(image,sRGBColorspace,exception);
delta.x=DefaultResolution;
delta.y=DefaultResolution;
resolution.x=image->resolution.x;
resolution.y=image->resolution.y;
if ((resolution.x == 0.0) || (resolution.y == 0.0))
{
flags=ParseGeometry(PSDensityGeometry,&geometry_info);
resolution.x=geometry_info.rho;
resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
resolution.y=resolution.x;
}
if (image_info->density != (char *) NULL)
{
flags=ParseGeometry(image_info->density,&geometry_info);
resolution.x=geometry_info.rho;
resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
resolution.y=resolution.x;
}
if (image->units == PixelsPerCentimeterResolution)
{
resolution.x=(double) ((size_t) (100.0*2.54*resolution.x+0.5)/100.0);
resolution.y=(double) ((size_t) (100.0*2.54*resolution.y+0.5)/100.0);
}
SetGeometry(image,&geometry);
(void) FormatLocaleString(page_geometry,MagickPathExtent,"%.20gx%.20g",
(double) image->columns,(double) image->rows);
if (image_info->page != (char *) NULL)
(void) CopyMagickString(page_geometry,image_info->page,MagickPathExtent);
else
if ((image->page.width != 0) && (image->page.height != 0))
(void) FormatLocaleString(page_geometry,MagickPathExtent,
"%.20gx%.20g%+.20g%+.20g",(double) image->page.width,(double)
image->page.height,(double) image->page.x,(double) image->page.y);
else
if ((image->gravity != UndefinedGravity) &&
(LocaleCompare(image_info->magick,"PS") == 0))
(void) CopyMagickString(page_geometry,PSPageGeometry,MagickPathExtent);
(void) ConcatenateMagickString(page_geometry,">",MagickPathExtent);
(void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y,
&geometry.width,&geometry.height);
scale.x=(double) (geometry.width*delta.x)/resolution.x;
geometry.width=(size_t) floor(scale.x+0.5);
scale.y=(double) (geometry.height*delta.y)/resolution.y;
geometry.height=(size_t) floor(scale.y+0.5);
(void) ParseAbsoluteGeometry(page_geometry,&media_info);
(void) ParseGravityGeometry(image,page_geometry,&page_info,exception);
if (image->gravity != UndefinedGravity)
{
geometry.x=(-page_info.x);
geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows);
}
pointsize=12.0;
if (image_info->pointsize != 0.0)
pointsize=image_info->pointsize;
text_size=0;
value=GetImageProperty(image,"label",exception);
if (value != (const char *) NULL)
text_size=(size_t) (MultilineCensus(value)*pointsize+12);
if (page == 1)
{
/*
Output Postscript header.
*/
if (LocaleCompare(image_info->magick,"PS") == 0)
(void) CopyMagickString(buffer,"%!PS-Adobe-3.0\n",MagickPathExtent);
else
(void) CopyMagickString(buffer,"%!PS-Adobe-3.0 EPSF-3.0\n",
MagickPathExtent);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"%%Creator: (ImageMagick)\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"%%%%Title: (%s)\n",
image->filename);
(void) WriteBlobString(image,buffer);
timer=time((time_t *) NULL);
(void) FormatMagickTime(timer,MagickPathExtent,date);
(void) FormatLocaleString(buffer,MagickPathExtent,
"%%%%CreationDate: (%s)\n",date);
(void) WriteBlobString(image,buffer);
bounds.x1=(double) geometry.x;
bounds.y1=(double) geometry.y;
bounds.x2=(double) geometry.x+scale.x;
bounds.y2=(double) geometry.y+(geometry.height+text_size);
if ((image_info->adjoin != MagickFalse) &&
(GetNextImageInList(image) != (Image *) NULL))
(void) CopyMagickString(buffer,"%%%%BoundingBox: (atend)\n",
MagickPathExtent);
else
{
(void) FormatLocaleString(buffer,MagickPathExtent,
"%%%%BoundingBox: %.20g %.20g %.20g %.20g\n",ceil(bounds.x1-0.5),
ceil(bounds.y1-0.5),floor(bounds.x2+0.5),floor(bounds.y2+0.5));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,
"%%%%HiResBoundingBox: %g %g %g %g\n",bounds.x1,
bounds.y1,bounds.x2,bounds.y2);
}
(void) WriteBlobString(image,buffer);
profile=GetImageProfile(image,"8bim");
if (profile != (StringInfo *) NULL)
{
/*
Embed Photoshop profile.
*/
(void) FormatLocaleString(buffer,MagickPathExtent,
"%%BeginPhotoshop: %.20g",(double) GetStringInfoLength(profile));
(void) WriteBlobString(image,buffer);
for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++)
{
if ((i % 32) == 0)
(void) WriteBlobString(image,"\n% ");
(void) FormatLocaleString(buffer,MagickPathExtent,"%02X",
(unsigned int) (GetStringInfoDatum(profile)[i] & 0xff));
(void) WriteBlobString(image,buffer);
}
(void) WriteBlobString(image,"\n%EndPhotoshop\n");
}
profile=GetImageProfile(image,"xmp");
DisableMSCWarning(4127)
if (0 && (profile != (StringInfo *) NULL))
RestoreMSCWarning
{
/*
Embed XML profile.
*/
(void) WriteBlobString(image,"\n%begin_xml_code\n");
(void) FormatLocaleString(buffer,MagickPathExtent,
"\n%%begin_xml_packet: %.20g\n",(double)
GetStringInfoLength(profile));
(void) WriteBlobString(image,buffer);
for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++)
(void) WriteBlobByte(image,GetStringInfoDatum(profile)[i]);
(void) WriteBlobString(image,"\n%end_xml_packet\n%end_xml_code\n");
}
value=GetImageProperty(image,"label",exception);
if (value != (const char *) NULL)
(void) WriteBlobString(image,
"%%DocumentNeededResources: font Times-Roman\n");
(void) WriteBlobString(image,"%%DocumentData: Clean7Bit\n");
(void) WriteBlobString(image,"%%LanguageLevel: 1\n");
if (LocaleCompare(image_info->magick,"PS") != 0)
(void) WriteBlobString(image,"%%Pages: 1\n");
else
{
/*
Compute the number of pages.
*/
(void) WriteBlobString(image,"%%Orientation: Portrait\n");
(void) WriteBlobString(image,"%%PageOrder: Ascend\n");
(void) FormatLocaleString(buffer,MagickPathExtent,
"%%%%Pages: %.20g\n",image_info->adjoin != MagickFalse ?
(double) imageListLength : 1.0);
(void) WriteBlobString(image,buffer);
}
(void) WriteBlobString(image,"%%EndComments\n");
(void) WriteBlobString(image,"\n%%BeginDefaults\n");
(void) WriteBlobString(image,"%%EndDefaults\n\n");
if ((LocaleCompare(image_info->magick,"EPI") == 0) ||
(LocaleCompare(image_info->magick,"EPSI") == 0) ||
(LocaleCompare(image_info->magick,"EPT") == 0))
{
Image
*preview_image;
Quantum
pixel;
register ssize_t
x;
ssize_t
y;
/*
Create preview image.
*/
preview_image=CloneImage(image,0,0,MagickTrue,exception);
if (preview_image == (Image *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Dump image as bitmap.
*/
(void) FormatLocaleString(buffer,MagickPathExtent,
"%%%%BeginPreview: %.20g %.20g %.20g %.20g\n%% ",(double)
preview_image->columns,(double) preview_image->rows,1.0,
(double) ((((preview_image->columns+7) >> 3)*preview_image->rows+
35)/36));
(void) WriteBlobString(image,buffer);
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(preview_image,0,y,preview_image->columns,1,
exception);
if (p == (const Quantum *) NULL)
break;
bit=0;
byte=0;
for (x=0; x < (ssize_t) preview_image->columns; x++)
{
byte<<=1;
pixel=ClampToQuantum(GetPixelLuma(preview_image,p));
if (pixel >= (Quantum) (QuantumRange/2))
byte|=0x01;
bit++;
if (bit == 8)
{
q=PopHexPixel(hex_digits,byte,q);
if ((q-pixels+8) >= 80)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
(void) WriteBlobString(image,"% ");
};
bit=0;
byte=0;
}
}
if (bit != 0)
{
byte<<=(8-bit);
q=PopHexPixel(hex_digits,byte,q);
if ((q-pixels+8) >= 80)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
(void) WriteBlobString(image,"% ");
};
};
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
(void) WriteBlobString(image,"\n%%EndPreview\n");
preview_image=DestroyImage(preview_image);
}
/*
Output Postscript commands.
*/
for (s=PostscriptProlog; *s != (char *) NULL; s++)
{
(void) FormatLocaleString(buffer,MagickPathExtent,"%s\n",*s);
(void) WriteBlobString(image,buffer);
}
value=GetImageProperty(image,"label",exception);
if (value != (const char *) NULL)
{
(void) WriteBlobString(image,
" /Times-Roman findfont pointsize scalefont setfont\n");
for (j=(ssize_t) MultilineCensus(value)-1; j >= 0; j--)
{
(void) WriteBlobString(image," /label 512 string def\n");
(void) WriteBlobString(image,
" currentfile label readline pop\n");
(void) FormatLocaleString(buffer,MagickPathExtent,
" 0 y %g add moveto label show pop\n",j*pointsize+12);
(void) WriteBlobString(image,buffer);
}
}
for (s=PostscriptEpilog; *s != (char *) NULL; s++)
{
(void) FormatLocaleString(buffer,MagickPathExtent,"%s\n",*s);
(void) WriteBlobString(image,buffer);
}
if (LocaleCompare(image_info->magick,"PS") == 0)
(void) WriteBlobString(image," showpage\n");
(void) WriteBlobString(image,"} bind def\n");
(void) WriteBlobString(image,"%%EndProlog\n");
}
(void) FormatLocaleString(buffer,MagickPathExtent,"%%%%Page: 1 %.20g\n",
(double) (page++));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,
"%%%%PageBoundingBox: %.20g %.20g %.20g %.20g\n",(double) geometry.x,
(double) geometry.y,geometry.x+(double) geometry.width,geometry.y+(double)
(geometry.height+text_size));
(void) WriteBlobString(image,buffer);
if ((double) geometry.x < bounds.x1)
bounds.x1=(double) geometry.x;
if ((double) geometry.y < bounds.y1)
bounds.y1=(double) geometry.y;
if ((double) (geometry.x+geometry.width-1) > bounds.x2)
bounds.x2=(double) geometry.x+geometry.width-1;
if ((double) (geometry.y+(geometry.height+text_size)-1) > bounds.y2)
bounds.y2=(double) geometry.y+(geometry.height+text_size)-1;
value=GetImageProperty(image,"label",exception);
if (value != (const char *) NULL)
(void) WriteBlobString(image,"%%%%PageResources: font Times-Roman\n");
if (LocaleCompare(image_info->magick,"PS") != 0)
(void) WriteBlobString(image,"userdict begin\n");
(void) WriteBlobString(image,"DisplayImage\n");
/*
Output image data.
*/
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g %.20g\n%g %g\n%g\n",
(double) geometry.x,(double) geometry.y,scale.x,scale.y,pointsize);
(void) WriteBlobString(image,buffer);
labels=(char **) NULL;
value=GetImageProperty(image,"label",exception);
if (value != (const char *) NULL)
labels=StringToList(value);
if (labels != (char **) NULL)
{
for (i=0; labels[i] != (char *) NULL; i++)
{
(void) FormatLocaleString(buffer,MagickPathExtent,"%s \n",
labels[i]);
(void) WriteBlobString(image,buffer);
labels[i]=DestroyString(labels[i]);
}
labels=(char **) RelinquishMagickMemory(labels);
}
(void) memset(&pixel,0,sizeof(pixel));
pixel.alpha=(MagickRealType) TransparentAlpha;
index=0;
x=0;
if ((image_info->type != TrueColorType) &&
(SetImageGray(image,exception) != MagickFalse))
{
if (SetImageMonochrome(image,exception) == MagickFalse)
{
Quantum
pixel;
/*
Dump image as grayscale.
*/
(void) FormatLocaleString(buffer,MagickPathExtent,
"%.20g %.20g\n1\n1\n1\n8\n",(double) image->columns,(double)
image->rows);
(void) WriteBlobString(image,buffer);
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=(Quantum) ScaleQuantumToChar(ClampToQuantum(GetPixelLuma(
image,p)));
q=PopHexPixel(hex_digits,(size_t) pixel,q);
if ((q-pixels+8) >= 80)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p+=GetPixelChannels(image);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
}
else
{
ssize_t
y;
Quantum
pixel;
/*
Dump image as bitmap.
*/
(void) FormatLocaleString(buffer,MagickPathExtent,
"%.20g %.20g\n1\n1\n1\n1\n",(double) image->columns,(double)
image->rows);
(void) WriteBlobString(image,buffer);
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
bit=0;
byte=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
byte<<=1;
pixel=ClampToQuantum(GetPixelLuma(image,p));
if (pixel >= (Quantum) (QuantumRange/2))
byte|=0x01;
bit++;
if (bit == 8)
{
q=PopHexPixel(hex_digits,byte,q);
if ((q-pixels+2) >= 80)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
};
bit=0;
byte=0;
}
p+=GetPixelChannels(image);
}
if (bit != 0)
{
byte<<=(8-bit);
q=PopHexPixel(hex_digits,byte,q);
if ((q-pixels+2) >= 80)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
};
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
}
}
else
if ((image->storage_class == DirectClass) ||
(image->colors > 256) || (image->alpha_trait != UndefinedPixelTrait))
{
/*
Dump DirectClass image.
*/
(void) FormatLocaleString(buffer,MagickPathExtent,
"%.20g %.20g\n0\n%d\n",(double) image->columns,(double) image->rows,
compression == RLECompression ? 1 : 0);
(void) WriteBlobString(image,buffer);
switch (compression)
{
case RLECompression:
{
/*
Dump runlength-encoded DirectColor packets.
*/
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
GetPixelInfoPixel(image,p,&pixel);
length=255;
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((GetPixelRed(image,p) == ClampToQuantum(pixel.red)) &&
(GetPixelGreen(image,p) == ClampToQuantum(pixel.green)) &&
(GetPixelBlue(image,p) == ClampToQuantum(pixel.blue)) &&
(GetPixelAlpha(image,p) == ClampToQuantum(pixel.alpha)) &&
(length < 255) && (x < (ssize_t) (image->columns-1)))
length++;
else
{
if (x > 0)
{
WriteRunlengthPacket(image,pixel,length,p);
if ((q-pixels+10) >= 80)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
}
length=0;
}
GetPixelInfoPixel(image,p,&pixel);
p+=GetPixelChannels(image);
}
WriteRunlengthPacket(image,pixel,length,p);
if ((q-pixels+10) >= 80)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) y,image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case NoCompression:
default:
{
/*
Dump uncompressed DirectColor packets.
*/
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((image->alpha_trait != UndefinedPixelTrait) &&
(GetPixelAlpha(image,p) == (Quantum) TransparentAlpha))
{
q=PopHexPixel(hex_digits,0xff,q);
q=PopHexPixel(hex_digits,0xff,q);
q=PopHexPixel(hex_digits,0xff,q);
}
else
{
q=PopHexPixel(hex_digits,ScaleQuantumToChar(
GetPixelRed(image,p)),q);
q=PopHexPixel(hex_digits,ScaleQuantumToChar(
GetPixelGreen(image,p)),q);
q=PopHexPixel(hex_digits,ScaleQuantumToChar(
GetPixelBlue(image,p)),q);
}
if ((q-pixels+6) >= 80)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p+=GetPixelChannels(image);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) y,image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
}
(void) WriteBlobByte(image,'\n');
}
else
{
/*
Dump PseudoClass image.
*/
(void) FormatLocaleString(buffer,MagickPathExtent,
"%.20g %.20g\n%d\n%d\n0\n",(double) image->columns,(double)
image->rows,image->storage_class == PseudoClass ? 1 : 0,
compression == RLECompression ? 1 : 0);
(void) WriteBlobString(image,buffer);
/*
Dump number of colors and colormap.
*/
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
image->colors);
(void) WriteBlobString(image,buffer);
for (i=0; i < (ssize_t) image->colors; i++)
{
(void) FormatLocaleString(buffer,MagickPathExtent,"%02X%02X%02X\n",
ScaleQuantumToChar(ClampToQuantum(image->colormap[i].red)),
ScaleQuantumToChar(ClampToQuantum(image->colormap[i].green)),
ScaleQuantumToChar(ClampToQuantum(image->colormap[i].blue)));
(void) WriteBlobString(image,buffer);
}
switch (compression)
{
case RLECompression:
{
/*
Dump runlength-encoded PseudoColor packets.
*/
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
index=GetPixelIndex(image,p);
length=255;
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((index == GetPixelIndex(image,p)) &&
(length < 255) && (x < ((ssize_t) image->columns-1)))
length++;
else
{
if (x > 0)
{
q=PopHexPixel(hex_digits,(size_t) index,q);
q=PopHexPixel(hex_digits,(size_t)
MagickMin(length,0xff),q);
i++;
if ((q-pixels+6) >= 80)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
}
length=0;
}
index=GetPixelIndex(image,p);
pixel.red=(MagickRealType) GetPixelRed(image,p);
pixel.green=(MagickRealType) GetPixelGreen(image,p);
pixel.blue=(MagickRealType) GetPixelBlue(image,p);
pixel.alpha=(MagickRealType) GetPixelAlpha(image,p);
p+=GetPixelChannels(image);
}
q=PopHexPixel(hex_digits,(size_t) index,q);
q=PopHexPixel(hex_digits,(size_t)
MagickMin(length,0xff),q);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) y,image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case NoCompression:
default:
{
/*
Dump uncompressed PseudoColor packets.
*/
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
q=PopHexPixel(hex_digits,(size_t) GetPixelIndex(image,p),q);
if ((q-pixels+4) >= 80)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p+=GetPixelChannels(image);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) y,image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
}
(void) WriteBlobByte(image,'\n');
}
if (LocaleCompare(image_info->magick,"PS") != 0)
(void) WriteBlobString(image,"end\n");
(void) WriteBlobString(image,"%%PageTrailer\n");
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) WriteBlobString(image,"%%Trailer\n");
if (page > 2)
{
(void) FormatLocaleString(buffer,MagickPathExtent,
"%%%%BoundingBox: %.20g %.20g %.20g %.20g\n",ceil(bounds.x1-0.5),
ceil(bounds.y1-0.5),floor(bounds.x2-0.5),floor(bounds.y2-0.5));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,
"%%%%HiResBoundingBox: %g %g %g %g\n",bounds.x1,bounds.y1,bounds.x2,
bounds.y2);
(void) WriteBlobString(image,buffer);
}
(void) WriteBlobString(image,"%%EOF\n");
(void) CloseBlob(image);
return(MagickTrue);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1523'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: TEST_F(ZNCTest, Modpython) {
if (QProcessEnvironment::systemEnvironment().value(
"DISABLED_ZNC_PERL_PYTHON_TEST") == "1") {
return;
}
auto znc = Run();
znc->CanLeak();
auto ircd = ConnectIRCd();
auto client = LoginClient();
client.Write("znc loadmod modpython");
client.Write("znc loadmod pyeval");
client.Write("PRIVMSG *pyeval :2+2");
client.ReadUntil(":*[email protected] PRIVMSG nick :4");
client.Write("PRIVMSG *pyeval :module.GetUser().GetUserName()");
client.ReadUntil("nick :'user'");
ircd.Write(":server 001 nick :Hello");
ircd.Write(":n!u@h PRIVMSG nick :Hi\xF0, github issue #1229");
// "replacement character"
client.ReadUntil("Hi\xEF\xBF\xBD, github issue");
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Don't crash if user specified invalid encoding.
This is CVE-2019-9917'</s> |
<s>[INST] Given the following code containing errors, provide 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 Set(const CString& sLine) {
const CString sVar = sLine.Token(1).AsLower();
CString sUserName = sLine.Token(2);
CString sValue = sLine.Token(3, true);
if (sValue.empty()) {
PutModule(t_s("Usage: Set <variable> <username> <value>"));
return;
}
CUser* pUser = FindUser(sUserName);
if (!pUser) return;
if (sVar == "nick") {
pUser->SetNick(sValue);
PutModule("Nick = " + sValue);
} else if (sVar == "altnick") {
pUser->SetAltNick(sValue);
PutModule("AltNick = " + sValue);
} else if (sVar == "ident") {
pUser->SetIdent(sValue);
PutModule("Ident = " + sValue);
} else if (sVar == "realname") {
pUser->SetRealName(sValue);
PutModule("RealName = " + sValue);
} else if (sVar == "bindhost") {
if (!pUser->DenySetBindHost() || GetUser()->IsAdmin()) {
if (sValue.Equals(pUser->GetBindHost())) {
PutModule(t_s("This bind host is already set!"));
return;
}
pUser->SetBindHost(sValue);
PutModule("BindHost = " + sValue);
} else {
PutModule(t_s("Access denied!"));
}
} else if (sVar == "multiclients") {
bool b = sValue.ToBool();
pUser->SetMultiClients(b);
PutModule("MultiClients = " + CString(b));
} else if (sVar == "denyloadmod") {
if (GetUser()->IsAdmin()) {
bool b = sValue.ToBool();
pUser->SetDenyLoadMod(b);
PutModule("DenyLoadMod = " + CString(b));
} else {
PutModule(t_s("Access denied!"));
}
} else if (sVar == "denysetbindhost") {
if (GetUser()->IsAdmin()) {
bool b = sValue.ToBool();
pUser->SetDenySetBindHost(b);
PutModule("DenySetBindHost = " + CString(b));
} else {
PutModule(t_s("Access denied!"));
}
} else if (sVar == "defaultchanmodes") {
pUser->SetDefaultChanModes(sValue);
PutModule("DefaultChanModes = " + sValue);
} else if (sVar == "quitmsg") {
pUser->SetQuitMsg(sValue);
PutModule("QuitMsg = " + sValue);
} else if (sVar == "chanbuffersize" || sVar == "buffercount") {
unsigned int i = sValue.ToUInt();
// Admins don't have to honour the buffer limit
if (pUser->SetChanBufferSize(i, GetUser()->IsAdmin())) {
PutModule("ChanBufferSize = " + sValue);
} else {
PutModule(t_f("Setting failed, limit for buffer size is {1}")(
CString(CZNC::Get().GetMaxBufferSize())));
}
} else if (sVar == "querybuffersize") {
unsigned int i = sValue.ToUInt();
// Admins don't have to honour the buffer limit
if (pUser->SetQueryBufferSize(i, GetUser()->IsAdmin())) {
PutModule("QueryBufferSize = " + sValue);
} else {
PutModule(t_f("Setting failed, limit for buffer size is {1}")(
CString(CZNC::Get().GetMaxBufferSize())));
}
} else if (sVar == "keepbuffer") {
// XXX compatibility crap, added in 0.207
bool b = !sValue.ToBool();
pUser->SetAutoClearChanBuffer(b);
PutModule("AutoClearChanBuffer = " + CString(b));
} else if (sVar == "autoclearchanbuffer") {
bool b = sValue.ToBool();
pUser->SetAutoClearChanBuffer(b);
PutModule("AutoClearChanBuffer = " + CString(b));
} else if (sVar == "autoclearquerybuffer") {
bool b = sValue.ToBool();
pUser->SetAutoClearQueryBuffer(b);
PutModule("AutoClearQueryBuffer = " + CString(b));
} else if (sVar == "password") {
const CString sSalt = CUtils::GetSalt();
const CString sHash = CUser::SaltedHash(sValue, sSalt);
pUser->SetPass(sHash, CUser::HASH_DEFAULT, sSalt);
PutModule(t_s("Password has been changed!"));
} else if (sVar == "maxjoins") {
unsigned int i = sValue.ToUInt();
pUser->SetMaxJoins(i);
PutModule("MaxJoins = " + CString(pUser->MaxJoins()));
} else if (sVar == "notraffictimeout") {
unsigned int i = sValue.ToUInt();
if (i < 30) {
PutModule(t_s("Timeout can't be less than 30 seconds!"));
} else {
pUser->SetNoTrafficTimeout(i);
PutModule("NoTrafficTimeout = " +
CString(pUser->GetNoTrafficTimeout()));
}
} else if (sVar == "maxnetworks") {
if (GetUser()->IsAdmin()) {
unsigned int i = sValue.ToUInt();
pUser->SetMaxNetworks(i);
PutModule("MaxNetworks = " + sValue);
} else {
PutModule(t_s("Access denied!"));
}
} else if (sVar == "maxquerybuffers") {
unsigned int i = sValue.ToUInt();
pUser->SetMaxQueryBuffers(i);
PutModule("MaxQueryBuffers = " + sValue);
} else if (sVar == "jointries") {
unsigned int i = sValue.ToUInt();
pUser->SetJoinTries(i);
PutModule("JoinTries = " + CString(pUser->JoinTries()));
} else if (sVar == "timezone") {
pUser->SetTimezone(sValue);
PutModule("Timezone = " + pUser->GetTimezone());
} else if (sVar == "admin") {
if (GetUser()->IsAdmin() && pUser != GetUser()) {
bool b = sValue.ToBool();
pUser->SetAdmin(b);
PutModule("Admin = " + CString(pUser->IsAdmin()));
} else {
PutModule(t_s("Access denied!"));
}
} else if (sVar == "prependtimestamp") {
bool b = sValue.ToBool();
pUser->SetTimestampPrepend(b);
PutModule("PrependTimestamp = " + CString(b));
} else if (sVar == "appendtimestamp") {
bool b = sValue.ToBool();
pUser->SetTimestampAppend(b);
PutModule("AppendTimestamp = " + CString(b));
} else if (sVar == "authonlyviamodule") {
if (GetUser()->IsAdmin()) {
bool b = sValue.ToBool();
pUser->SetAuthOnlyViaModule(b);
PutModule("AuthOnlyViaModule = " + CString(b));
} else {
PutModule(t_s("Access denied!"));
}
} else if (sVar == "timestampformat") {
pUser->SetTimestampFormat(sValue);
PutModule("TimestampFormat = " + sValue);
} else if (sVar == "dccbindhost") {
if (!pUser->DenySetBindHost() || GetUser()->IsAdmin()) {
pUser->SetDCCBindHost(sValue);
PutModule("DCCBindHost = " + sValue);
} else {
PutModule(t_s("Access denied!"));
}
} else if (sVar == "statusprefix") {
if (sVar.find_first_of(" \t\n") == CString::npos) {
pUser->SetStatusPrefix(sValue);
PutModule("StatusPrefix = " + sValue);
} else {
PutModule(t_s("That would be a bad idea!"));
}
}
#ifdef HAVE_I18N
else if (sVar == "language") {
auto mTranslations = CTranslationInfo::GetTranslations();
// TODO: maybe stop special-casing English
if (sValue == "en") {
pUser->SetLanguage("");
PutModule("Language is set to English");
} else if (mTranslations.count(sValue)) {
pUser->SetLanguage(sValue);
PutModule("Language = " + sValue);
} else {
VCString vsCodes = {"en"};
for (const auto it : mTranslations) {
vsCodes.push_back(it.first);
}
PutModule(t_f("Supported languages: {1}")(
CString(", ").Join(vsCodes.begin(), vsCodes.end())));
}
}
#endif
#ifdef HAVE_ICU
else if (sVar == "clientencoding") {
pUser->SetClientEncoding(sValue);
PutModule("ClientEncoding = " + sValue);
}
#endif
else
PutModule(t_s("Error: Unknown variable"));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Don't crash if user specified invalid encoding.
This is CVE-2019-9917'</s> |
<s>[INST] Given the following code containing errors, provide 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 CIRCNetwork::SetEncoding(const CString& s) {
m_sEncoding = s;
if (GetIRCSock()) {
GetIRCSock()->SetEncoding(s);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Don't crash if user specified invalid encoding.
This is CVE-2019-9917'</s> |
<s>[INST] Given the following code containing errors, provide 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 *load_device_tree(const char *filename_path, int *sizep)
{
int dt_size;
int dt_file_load_size;
int ret;
void *fdt = NULL;
*sizep = 0;
dt_size = get_image_size(filename_path);
if (dt_size < 0) {
error_report("Unable to get size of device tree file '%s'",
filename_path);
goto fail;
}
/* Expand to 2x size to give enough room for manipulation. */
dt_size += 10000;
dt_size *= 2;
/* First allocate space in qemu for device tree */
fdt = g_malloc0(dt_size);
dt_file_load_size = load_image(filename_path, fdt);
if (dt_file_load_size < 0) {
error_report("Unable to open device tree file '%s'",
filename_path);
goto fail;
}
ret = fdt_open_into(fdt, fdt, dt_size);
if (ret) {
error_report("Unable to copy device tree in memory");
goto fail;
}
/* Check sanity of device tree */
if (fdt_check_header(fdt)) {
error_report("Device tree file loaded into memory is invalid: %s",
filename_path);
goto fail;
}
*sizep = dt_size;
return fdt;
fail:
g_free(fdt);
return NULL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'device_tree.c: Don't use load_image()
The load_image() function is deprecated, as it does not let the
caller specify how large the buffer to read the file into is.
Instead use load_image_size().
Signed-off-by: Peter Maydell <[email protected]>
Reviewed-by: Richard Henderson <[email protected]>
Reviewed-by: Stefan Hajnoczi <[email protected]>
Reviewed-by: Michael S. Tsirkin <[email protected]>
Reviewed-by: Eric Blake <[email protected]>
Message-id: [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: UsbHubReadDesc (
IN USB_DEVICE *HubDev,
OUT EFI_USB_HUB_DESCRIPTOR *HubDesc
)
{
EFI_STATUS Status;
if (HubDev->Speed == EFI_USB_SPEED_SUPER) {
//
// Get the super speed hub descriptor
//
Status = UsbHubCtrlGetSuperSpeedHubDesc (HubDev, HubDesc);
} else {
//
// First get the hub descriptor length
//
Status = UsbHubCtrlGetHubDesc (HubDev, HubDesc, 2);
if (EFI_ERROR (Status)) {
return Status;
}
//
// Get the whole hub descriptor
//
Status = UsbHubCtrlGetHubDesc (HubDev, HubDesc, HubDesc->Length);
}
return Status;
}
; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'MdeModulePkg UsbBusDxe: Fix wrong buffer length used to read hub desc
REF: https://bugzilla.tianocore.org/show_bug.cgi?id=973
HUB descriptor has variable length.
But the code uses stack (HubDesc in UsbHubInit) with fixed length
sizeof(EFI_USB_HUB_DESCRIPTOR) to hold HUB descriptor data.
It uses hard code length value (32 that is greater than
sizeof(EFI_USB_HUB_DESCRIPTOR)) for SuperSpeed path, then there will
be stack overflow when IOMMU is enabled because the Unmap operation
will copy the data from device buffer to host buffer.
And it uses HubDesc->Length for none SuperSpeed path, then there will
be stack overflow when HubDesc->Length is greater than
sizeof(EFI_USB_HUB_DESCRIPTOR).
The patch updates the code to use a big enough buffer to hold the
descriptor data.
The definition EFI_USB_SUPER_SPEED_HUB_DESCRIPTOR is wrong (HubDelay
field should be UINT16 type) and no code is using it, the patch
removes it.
Cc: Jiewen Yao <[email protected]>
Cc: Ruiyu Ni <[email protected]>
Cc: Bret Barkelew <[email protected]>
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Star Zeng <[email protected]>
Reviewed-by: Bret Barkelew <[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: UsbHubCtrlGetHubDesc (
IN USB_DEVICE *HubDev,
OUT VOID *Buf,
IN UINTN Len
)
{
EFI_STATUS Status;
Status = UsbCtrlRequest (
HubDev,
EfiUsbDataIn,
USB_REQ_TYPE_CLASS,
USB_HUB_TARGET_HUB,
USB_HUB_REQ_GET_DESC,
(UINT16) (USB_DESC_TYPE_HUB << 8),
0,
Buf,
Len
);
return Status;
}
; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'MdeModulePkg UsbBusDxe: Fix wrong buffer length used to read hub desc
REF: https://bugzilla.tianocore.org/show_bug.cgi?id=973
HUB descriptor has variable length.
But the code uses stack (HubDesc in UsbHubInit) with fixed length
sizeof(EFI_USB_HUB_DESCRIPTOR) to hold HUB descriptor data.
It uses hard code length value (32 that is greater than
sizeof(EFI_USB_HUB_DESCRIPTOR)) for SuperSpeed path, then there will
be stack overflow when IOMMU is enabled because the Unmap operation
will copy the data from device buffer to host buffer.
And it uses HubDesc->Length for none SuperSpeed path, then there will
be stack overflow when HubDesc->Length is greater than
sizeof(EFI_USB_HUB_DESCRIPTOR).
The patch updates the code to use a big enough buffer to hold the
descriptor data.
The definition EFI_USB_SUPER_SPEED_HUB_DESCRIPTOR is wrong (HubDelay
field should be UINT16 type) and no code is using it, the patch
removes it.
Cc: Jiewen Yao <[email protected]>
Cc: Ruiyu Ni <[email protected]>
Cc: Bret Barkelew <[email protected]>
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Star Zeng <[email protected]>
Reviewed-by: Bret Barkelew <[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: PeiDoHubConfig (
IN EFI_PEI_SERVICES **PeiServices,
IN PEI_USB_DEVICE *PeiUsbDevice
)
{
EFI_USB_HUB_DESCRIPTOR HubDescriptor;
EFI_STATUS Status;
EFI_USB_HUB_STATUS HubStatus;
UINTN Index;
PEI_USB_IO_PPI *UsbIoPpi;
ZeroMem (&HubDescriptor, sizeof (HubDescriptor));
UsbIoPpi = &PeiUsbDevice->UsbIoPpi;
//
// Get the hub descriptor
//
Status = PeiUsbHubReadDesc (
PeiServices,
PeiUsbDevice,
UsbIoPpi,
&HubDescriptor
);
if (EFI_ERROR (Status)) {
return EFI_DEVICE_ERROR;
}
PeiUsbDevice->DownStreamPortNo = HubDescriptor.NbrPorts;
if (PeiUsbDevice->DeviceSpeed == EFI_USB_SPEED_SUPER) {
DEBUG ((EFI_D_INFO, "PeiDoHubConfig: Set Hub Depth as 0x%x\n", PeiUsbDevice->Tier));
PeiUsbHubCtrlSetHubDepth (
PeiServices,
PeiUsbDevice,
UsbIoPpi
);
} else {
//
// Power all the hub ports
//
for (Index = 0; Index < PeiUsbDevice->DownStreamPortNo; Index++) {
Status = PeiHubSetPortFeature (
PeiServices,
UsbIoPpi,
(UINT8) (Index + 1),
EfiUsbPortPower
);
if (EFI_ERROR (Status)) {
DEBUG (( EFI_D_ERROR, "PeiDoHubConfig: PeiHubSetPortFeature EfiUsbPortPower failed %x\n", Index));
continue;
}
}
DEBUG (( EFI_D_INFO, "PeiDoHubConfig: HubDescriptor.PwrOn2PwrGood: 0x%x\n", HubDescriptor.PwrOn2PwrGood));
if (HubDescriptor.PwrOn2PwrGood > 0) {
MicroSecondDelay (HubDescriptor.PwrOn2PwrGood * USB_SET_PORT_POWER_STALL);
}
//
// Clear Hub Status Change
//
Status = PeiHubGetHubStatus (
PeiServices,
UsbIoPpi,
(UINT32 *) &HubStatus
);
if (EFI_ERROR (Status)) {
return EFI_DEVICE_ERROR;
} else {
//
// Hub power supply change happens
//
if ((HubStatus.HubChangeStatus & HUB_CHANGE_LOCAL_POWER) != 0) {
PeiHubClearHubFeature (
PeiServices,
UsbIoPpi,
C_HUB_LOCAL_POWER
);
}
//
// Hub change overcurrent happens
//
if ((HubStatus.HubChangeStatus & HUB_CHANGE_OVERCURRENT) != 0) {
PeiHubClearHubFeature (
PeiServices,
UsbIoPpi,
C_HUB_OVER_CURRENT
);
}
}
}
return EFI_SUCCESS;
}
; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'MdeModulePkg UsbBusPei: Fix wrong buffer length used to read hub desc
REF: https://bugzilla.tianocore.org/show_bug.cgi?id=973
Bug 973 just mentions UsbBusDxe, but UsbBusPei has similar issue.
HUB descriptor has variable length.
But the code uses stack (HubDescriptor in PeiDoHubConfig) with fixed
length sizeof(EFI_USB_HUB_DESCRIPTOR) to hold HUB descriptor data.
It uses hard code length value (12) for SuperSpeed path.
And it uses HubDesc->Length for none SuperSpeed path, then there will
be stack overflow when HubDesc->Length is greater than
sizeof(EFI_USB_HUB_DESCRIPTOR).
The patch updates the code to use a big enough buffer to hold the
descriptor data.
Cc: Jiewen Yao <[email protected]>
Cc: Ruiyu Ni <[email protected]>
Cc: Bret Barkelew <[email protected]>
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Star Zeng <[email protected]>
Reviewed-by: Bret Barkelew <[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: PeiGetSuperSpeedHubDesc (
IN EFI_PEI_SERVICES **PeiServices,
IN PEI_USB_IO_PPI *UsbIoPpi,
OUT EFI_USB_HUB_DESCRIPTOR *HubDescriptor
)
{
EFI_USB_DEVICE_REQUEST DevReq;
ZeroMem (&DevReq, sizeof (EFI_USB_DEVICE_REQUEST));
//
// Fill Device request packet
//
DevReq.RequestType = USB_RT_HUB | 0x80;
DevReq.Request = USB_HUB_GET_DESCRIPTOR;
DevReq.Value = USB_DT_SUPERSPEED_HUB << 8;
DevReq.Length = 12;
return UsbIoPpi->UsbControlTransfer (
PeiServices,
UsbIoPpi,
&DevReq,
EfiUsbDataIn,
PcdGet32 (PcdUsbTransferTimeoutValue),
HubDescriptor,
12
);
}
; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'MdeModulePkg UsbBusPei: Fix wrong buffer length used to read hub desc
REF: https://bugzilla.tianocore.org/show_bug.cgi?id=973
Bug 973 just mentions UsbBusDxe, but UsbBusPei has similar issue.
HUB descriptor has variable length.
But the code uses stack (HubDescriptor in PeiDoHubConfig) with fixed
length sizeof(EFI_USB_HUB_DESCRIPTOR) to hold HUB descriptor data.
It uses hard code length value (12) for SuperSpeed path.
And it uses HubDesc->Length for none SuperSpeed path, then there will
be stack overflow when HubDesc->Length is greater than
sizeof(EFI_USB_HUB_DESCRIPTOR).
The patch updates the code to use a big enough buffer to hold the
descriptor data.
Cc: Jiewen Yao <[email protected]>
Cc: Ruiyu Ni <[email protected]>
Cc: Bret Barkelew <[email protected]>
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Star Zeng <[email protected]>
Reviewed-by: Bret Barkelew <[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: CpuMpPeimInit (
IN EFI_PEI_FILE_HANDLE FileHandle,
IN CONST EFI_PEI_SERVICES **PeiServices
)
{
EFI_STATUS Status;
EFI_VECTOR_HANDOFF_INFO *VectorInfo;
EFI_PEI_VECTOR_HANDOFF_INFO_PPI *VectorHandoffInfoPpi;
//
// Get Vector Hand-off Info PPI
//
VectorInfo = NULL;
Status = PeiServicesLocatePpi (
&gEfiVectorHandoffInfoPpiGuid,
0,
NULL,
(VOID **)&VectorHandoffInfoPpi
);
if (Status == EFI_SUCCESS) {
VectorInfo = VectorHandoffInfoPpi->Info;
}
Status = InitializeCpuExceptionHandlers (VectorInfo);
ASSERT_EFI_ERROR (Status);
//
// Wakeup APs to do initialization
//
Status = MpInitLibInitialize ();
ASSERT_EFI_ERROR (Status);
//
// Update and publish CPU BIST information
//
CollectBistDataFromPpi (PeiServices);
//
// Install CPU MP PPI
//
Status = PeiServicesInstallPpi(&mPeiCpuMpPpiDesc);
ASSERT_EFI_ERROR (Status);
return Status;
}
; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'UefiCpuPkg/CpuMpPei: support stack guard feature
This feature is the same as Stack Guard enabled in driver CpuDxe but
applies to PEI phase. Due to the specialty in PEI module dispatching,
this driver is changed to do the actual initialization in notify
callback of event gEfiPeiMemoryDiscoveredPpiGuid. This can let the
stack guard apply to as most PEI drivers as possible.
To let Stack Guard work, some simple page table management code are
introduced to setup Guard page at base of stack for each processor.
Cc: Eric Dong <[email protected]>
Cc: Laszlo Ersek <[email protected]>
Cc: Ruiyu Ni <[email protected]>
Cc: Jiewen Yao <[email protected]>
Cc: Star Zeng <[email protected]>
Cc: "Ware, Ryan R" <[email protected]>
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Jian J Wang <[email protected]>
Regression-tested-by: Laszlo Ersek <[email protected]>
Reviewed-by: Eric Dong <[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: request_rec *h2_request_create_rec(const h2_request *req, conn_rec *c)
{
int access_status = HTTP_OK;
const char *rpath;
const char *s;
#if AP_MODULE_MAGIC_AT_LEAST(20150222, 13)
request_rec *r = ap_create_request(c);
#else
request_rec *r = my_ap_create_request(c);
#endif
r->headers_in = apr_table_clone(r->pool, req->headers);
ap_run_pre_read_request(r, c);
/* Time to populate r with the data we have. */
r->request_time = req->request_time;
r->method = req->method;
/* Provide quick information about the request method as soon as known */
r->method_number = ap_method_number_of(r->method);
if (r->method_number == M_GET && r->method[0] == 'H') {
r->header_only = 1;
}
rpath = (req->path ? req->path : "");
ap_parse_uri(r, rpath);
r->protocol = (char*)"HTTP/2.0";
r->proto_num = HTTP_VERSION(2, 0);
r->the_request = apr_psprintf(r->pool, "%s %s %s",
r->method, rpath, r->protocol);
/* update what we think the virtual host is based on the headers we've
* now read. may update status.
* Leave r->hostname empty, vhost will parse if form our Host: header,
* otherwise we get complains about port numbers.
*/
r->hostname = NULL;
ap_update_vhost_from_headers(r);
/* we may have switched to another server */
r->per_dir_config = r->server->lookup_defaults;
s = apr_table_get(r->headers_in, "Expect");
if (s && s[0]) {
if (ap_cstr_casecmp(s, "100-continue") == 0) {
r->expecting_100 = 1;
}
else {
r->status = HTTP_EXPECTATION_FAILED;
ap_send_error_response(r, 0);
}
}
/*
* Add the HTTP_IN filter here to ensure that ap_discard_request_body
* called by ap_die and by ap_send_error_response works correctly on
* status codes that do not cause the connection to be dropped and
* in situations where the connection should be kept alive.
*/
ap_add_input_filter_handle(ap_http_input_filter_handle,
NULL, r, r->connection);
if (access_status != HTTP_OK
|| (access_status = ap_run_post_read_request(r))) {
/* Request check post hooks failed. An example of this would be a
* request for a vhost where h2 is disabled --> 421.
*/
ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, c, APLOGNO(03367)
"h2_request: access_status=%d, request_create failed",
access_status);
ap_die(access_status, r);
ap_update_child_status(c->sbh, SERVER_BUSY_LOG, r);
ap_run_log_transaction(r);
r = NULL;
goto traceout;
}
AP_READ_REQUEST_SUCCESS((uintptr_t)r, (char *)r->method,
(char *)r->uri, (char *)r->server->defn_name,
r->status);
return r;
traceout:
AP_READ_REQUEST_FAILURE((uintptr_t)r);
return r;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': '* Integrated a forgotten request init fix from Apache subversion'</s> |
<s>[INST] Given the following code containing errors, provide 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 h2_task_pre_conn(conn_rec* c, void *arg)
{
h2_ctx *ctx;
if (!c->master) {
return OK;
}
ctx = h2_ctx_get(c, 0);
(void)arg;
if (ctx->task) {
ap_log_cerror(APLOG_MARK, APLOG_TRACE2, 0, c,
"h2_h2, pre_connection, found stream task");
ap_add_input_filter("H2_SLAVE_IN", NULL, NULL, c);
ap_add_output_filter("H2_PARSE_H1", NULL, NULL, c);
ap_add_output_filter("H2_SLAVE_OUT", NULL, NULL, c);
}
return OK;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-444'], 'message': '* Fixed keepalives counter on slave connections.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: apr_status_t h2_slave_run_pre_connection(conn_rec *slave, apr_socket_t *csd)
{
if (slave->keepalives == 0) {
/* Simulate that we had already a request on this connection. Some
* hooks trigger special behaviour when keepalives is 0.
* (Not necessarily in pre_connection, but later. Set it here, so it
* is in place.) */
slave->keepalives = 1;
/* We signal that this connection will be closed after the request.
* Which is true in that sense that we throw away all traffic data
* on this slave connection after each requests. Although we might
* reuse internal structures like memory pools.
* The wanted effect of this is that httpd does not try to clean up
* any dangling data on this connection when a request is done. Which
* is unneccessary on a h2 stream.
*/
slave->keepalive = AP_CONN_CLOSE;
return ap_run_pre_connection(slave, csd);
}
return APR_SUCCESS;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-444'], 'message': '* Fixed keepalives counter on slave connections.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static apr_status_t unschedule_slow_tasks(h2_mplx *m)
{
h2_stream *stream;
int n;
/* Try to get rid of streams that occupy workers. Look for safe requests
* that are repeatable. If none found, fail the connection.
*/
n = (m->tasks_active - m->limit_active - (int)h2_ihash_count(m->sredo));
while (n > 0 && (stream = get_latest_repeatable_unsubmitted_stream(m))) {
h2_task_rst(stream->task, H2_ERR_CANCEL);
h2_ihash_add(m->sredo, stream);
--n;
}
if ((m->tasks_active - h2_ihash_count(m->sredo)) > m->limit_active) {
stream = get_timed_out_busy_stream(m);
if (stream) {
/* Too many busy workers, unable to cancel enough streams
* and with a busy, timed out stream, we tell the client
* to go away... */
return APR_TIMEUP;
}
}
return APR_SUCCESS;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-444'], 'message': '* Fixed keepalives counter on slave connections.'</s> |
<s>[INST] Given the following code containing errors, provide 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 bool nested_vmx_prepare_msr_bitmap(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12)
{
int msr;
struct page *page;
unsigned long *msr_bitmap_l1;
unsigned long *msr_bitmap_l0 = to_vmx(vcpu)->nested.vmcs02.msr_bitmap;
/*
* pred_cmd & spec_ctrl are trying to verify two things:
*
* 1. L0 gave a permission to L1 to actually passthrough the MSR. This
* ensures that we do not accidentally generate an L02 MSR bitmap
* from the L12 MSR bitmap that is too permissive.
* 2. That L1 or L2s have actually used the MSR. This avoids
* unnecessarily merging of the bitmap if the MSR is unused. This
* works properly because we only update the L01 MSR bitmap lazily.
* So even if L0 should pass L1 these MSRs, the L01 bitmap is only
* updated to reflect this when L1 (or its L2s) actually write to
* the MSR.
*/
bool pred_cmd = !msr_write_intercepted_l01(vcpu, MSR_IA32_PRED_CMD);
bool spec_ctrl = !msr_write_intercepted_l01(vcpu, MSR_IA32_SPEC_CTRL);
/* Nothing to do if the MSR bitmap is not in use. */
if (!cpu_has_vmx_msr_bitmap() ||
!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
return false;
if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
!pred_cmd && !spec_ctrl)
return false;
page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->msr_bitmap);
if (is_error_page(page))
return false;
msr_bitmap_l1 = (unsigned long *)kmap(page);
/*
* To keep the control flow simple, pay eight 8-byte writes (sixteen
* 4-byte writes on 32-bit systems) up front to enable intercepts for
* the x2APIC MSR range and selectively disable them below.
*/
enable_x2apic_msr_intercepts(msr_bitmap_l0);
if (nested_cpu_has_virt_x2apic_mode(vmcs12)) {
if (nested_cpu_has_apic_reg_virt(vmcs12)) {
/*
* L0 need not intercept reads for MSRs between 0x800
* and 0x8ff, it just lets the processor take the value
* from the virtual-APIC page; take those 256 bits
* directly from the L1 bitmap.
*/
for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
unsigned word = msr / BITS_PER_LONG;
msr_bitmap_l0[word] = msr_bitmap_l1[word];
}
}
nested_vmx_disable_intercept_for_msr(
msr_bitmap_l1, msr_bitmap_l0,
X2APIC_MSR(APIC_TASKPRI),
MSR_TYPE_W);
if (nested_cpu_has_vid(vmcs12)) {
nested_vmx_disable_intercept_for_msr(
msr_bitmap_l1, msr_bitmap_l0,
X2APIC_MSR(APIC_EOI),
MSR_TYPE_W);
nested_vmx_disable_intercept_for_msr(
msr_bitmap_l1, msr_bitmap_l0,
X2APIC_MSR(APIC_SELF_IPI),
MSR_TYPE_W);
}
}
if (spec_ctrl)
nested_vmx_disable_intercept_for_msr(
msr_bitmap_l1, msr_bitmap_l0,
MSR_IA32_SPEC_CTRL,
MSR_TYPE_R | MSR_TYPE_W);
if (pred_cmd)
nested_vmx_disable_intercept_for_msr(
msr_bitmap_l1, msr_bitmap_l0,
MSR_IA32_PRED_CMD,
MSR_TYPE_W);
kunmap(page);
kvm_release_page_clean(page);
return true;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-863'], 'message': 'KVM: x86: nVMX: fix x2APIC VTPR read intercept
Referring to the "VIRTUALIZING MSR-BASED APIC ACCESSES" chapter of the
SDM, when "virtualize x2APIC mode" is 1 and "APIC-register
virtualization" is 0, a RDMSR of 808H should return the VTPR from the
virtual APIC page.
However, for nested, KVM currently fails to disable the read intercept
for this MSR. This means that a RDMSR exit takes precedence over
"virtualize x2APIC mode", and KVM passes through L1's TPR to L2,
instead of sourcing the value from L2's virtual APIC page.
This patch fixes the issue by disabling the read intercept, in VMCS02,
for the VTPR when "APIC-register virtualization" is 0.
The issue described above and fix prescribed here, were verified with
a related patch in kvm-unit-tests titled "Test VMX's virtualize x2APIC
mode w/ nested".
Signed-off-by: Marc Orr <[email protected]>
Reviewed-by: Jim Mattson <[email protected]>
Fixes: c992384bde84f ("KVM: vmx: speed up MSR bitmap merge")
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 int __io_submit_one(struct kioctx *ctx, const struct iocb *iocb,
struct iocb __user *user_iocb, bool compat)
{
struct aio_kiocb *req;
ssize_t ret;
/* enforce forwards compatibility on users */
if (unlikely(iocb->aio_reserved2)) {
pr_debug("EINVAL: reserve field set\n");
return -EINVAL;
}
/* prevent overflows */
if (unlikely(
(iocb->aio_buf != (unsigned long)iocb->aio_buf) ||
(iocb->aio_nbytes != (size_t)iocb->aio_nbytes) ||
((ssize_t)iocb->aio_nbytes < 0)
)) {
pr_debug("EINVAL: overflow check\n");
return -EINVAL;
}
if (!get_reqs_available(ctx))
return -EAGAIN;
ret = -EAGAIN;
req = aio_get_req(ctx);
if (unlikely(!req))
goto out_put_reqs_available;
if (iocb->aio_flags & IOCB_FLAG_RESFD) {
/*
* If the IOCB_FLAG_RESFD flag of aio_flags is set, get an
* instance of the file* now. The file descriptor must be
* an eventfd() fd, and will be signaled for each completed
* event using the eventfd_signal() function.
*/
req->ki_eventfd = eventfd_ctx_fdget((int) iocb->aio_resfd);
if (IS_ERR(req->ki_eventfd)) {
ret = PTR_ERR(req->ki_eventfd);
req->ki_eventfd = NULL;
goto out_put_req;
}
}
ret = put_user(KIOCB_KEY, &user_iocb->aio_key);
if (unlikely(ret)) {
pr_debug("EFAULT: aio_key\n");
goto out_put_req;
}
req->ki_user_iocb = user_iocb;
req->ki_user_data = iocb->aio_data;
switch (iocb->aio_lio_opcode) {
case IOCB_CMD_PREAD:
ret = aio_read(&req->rw, iocb, false, compat);
break;
case IOCB_CMD_PWRITE:
ret = aio_write(&req->rw, iocb, false, compat);
break;
case IOCB_CMD_PREADV:
ret = aio_read(&req->rw, iocb, true, compat);
break;
case IOCB_CMD_PWRITEV:
ret = aio_write(&req->rw, iocb, true, compat);
break;
case IOCB_CMD_FSYNC:
ret = aio_fsync(&req->fsync, iocb, false);
break;
case IOCB_CMD_FDSYNC:
ret = aio_fsync(&req->fsync, iocb, true);
break;
case IOCB_CMD_POLL:
ret = aio_poll(req, iocb);
break;
default:
pr_debug("invalid aio operation %d\n", iocb->aio_lio_opcode);
ret = -EINVAL;
break;
}
/*
* If ret is 0, we'd either done aio_complete() ourselves or have
* arranged for that to be done asynchronously. Anything non-zero
* means that we need to destroy req ourselves.
*/
if (ret)
goto out_put_req;
return 0;
out_put_req:
if (req->ki_eventfd)
eventfd_ctx_put(req->ki_eventfd);
iocb_put(req);
out_put_reqs_available:
put_reqs_available(ctx, 1);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'aio: simplify - and fix - fget/fput for io_submit()
Al Viro root-caused a race where the IOCB_CMD_POLL handling of
fget/fput() could cause us to access the file pointer after it had
already been freed:
"In more details - normally IOCB_CMD_POLL handling looks so:
1) io_submit(2) allocates aio_kiocb instance and passes it to
aio_poll()
2) aio_poll() resolves the descriptor to struct file by req->file =
fget(iocb->aio_fildes)
3) aio_poll() sets ->woken to false and raises ->ki_refcnt of that
aio_kiocb to 2 (bumps by 1, that is).
4) aio_poll() calls vfs_poll(). After sanity checks (basically,
"poll_wait() had been called and only once") it locks the queue.
That's what the extra reference to iocb had been for - we know we
can safely access it.
5) With queue locked, we check if ->woken has already been set to
true (by aio_poll_wake()) and, if it had been, we unlock the
queue, drop a reference to aio_kiocb and bugger off - at that
point it's a responsibility to aio_poll_wake() and the stuff
called/scheduled by it. That code will drop the reference to file
in req->file, along with the other reference to our aio_kiocb.
6) otherwise, we see whether we need to wait. If we do, we unlock the
queue, drop one reference to aio_kiocb and go away - eventual
wakeup (or cancel) will deal with the reference to file and with
the other reference to aio_kiocb
7) otherwise we remove ourselves from waitqueue (still under the
queue lock), so that wakeup won't get us. No async activity will
be happening, so we can safely drop req->file and iocb ourselves.
If wakeup happens while we are in vfs_poll(), we are fine - aio_kiocb
won't get freed under us, so we can do all the checks and locking
safely. And we don't touch ->file if we detect that case.
However, vfs_poll() most certainly *does* touch the file it had been
given. So wakeup coming while we are still in ->poll() might end up
doing fput() on that file. That case is not too rare, and usually we
are saved by the still present reference from descriptor table - that
fput() is not the final one.
But if another thread closes that descriptor right after our fget()
and wakeup does happen before ->poll() returns, we are in trouble -
final fput() done while we are in the middle of a method:
Al also wrote a patch to take an extra reference to the file descriptor
to fix this, but I instead suggested we just streamline the whole file
pointer handling by submit_io() so that the generic aio submission code
simply keeps the file pointer around until the aio has completed.
Fixes: bfe4037e722e ("aio: implement IOCB_CMD_POLL")
Acked-by: Al Viro <[email protected]>
Reported-by: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static ssize_t aio_poll(struct aio_kiocb *aiocb, const struct iocb *iocb)
{
struct kioctx *ctx = aiocb->ki_ctx;
struct poll_iocb *req = &aiocb->poll;
struct aio_poll_table apt;
__poll_t mask;
/* reject any unknown events outside the normal event mask. */
if ((u16)iocb->aio_buf != iocb->aio_buf)
return -EINVAL;
/* reject fields that are not defined for poll */
if (iocb->aio_offset || iocb->aio_nbytes || iocb->aio_rw_flags)
return -EINVAL;
INIT_WORK(&req->work, aio_poll_complete_work);
req->events = demangle_poll(iocb->aio_buf) | EPOLLERR | EPOLLHUP;
req->file = fget(iocb->aio_fildes);
if (unlikely(!req->file))
return -EBADF;
req->head = NULL;
req->woken = false;
req->cancelled = false;
apt.pt._qproc = aio_poll_queue_proc;
apt.pt._key = req->events;
apt.iocb = aiocb;
apt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
/* initialized the list so that we can do list_empty checks */
INIT_LIST_HEAD(&req->wait.entry);
init_waitqueue_func_entry(&req->wait, aio_poll_wake);
/* one for removal from waitqueue, one for this function */
refcount_set(&aiocb->ki_refcnt, 2);
mask = vfs_poll(req->file, &apt.pt) & req->events;
if (unlikely(!req->head)) {
/* we did not manage to set up a waitqueue, done */
goto out;
}
spin_lock_irq(&ctx->ctx_lock);
spin_lock(&req->head->lock);
if (req->woken) {
/* wake_up context handles the rest */
mask = 0;
apt.error = 0;
} else if (mask || apt.error) {
/* if we get an error or a mask we are done */
WARN_ON_ONCE(list_empty(&req->wait.entry));
list_del_init(&req->wait.entry);
} else {
/* actually waiting for an event */
list_add_tail(&aiocb->ki_list, &ctx->active_reqs);
aiocb->ki_cancel = aio_poll_cancel;
}
spin_unlock(&req->head->lock);
spin_unlock_irq(&ctx->ctx_lock);
out:
if (unlikely(apt.error)) {
fput(req->file);
return apt.error;
}
if (mask)
aio_poll_complete(aiocb, mask);
iocb_put(aiocb);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'aio: simplify - and fix - fget/fput for io_submit()
Al Viro root-caused a race where the IOCB_CMD_POLL handling of
fget/fput() could cause us to access the file pointer after it had
already been freed:
"In more details - normally IOCB_CMD_POLL handling looks so:
1) io_submit(2) allocates aio_kiocb instance and passes it to
aio_poll()
2) aio_poll() resolves the descriptor to struct file by req->file =
fget(iocb->aio_fildes)
3) aio_poll() sets ->woken to false and raises ->ki_refcnt of that
aio_kiocb to 2 (bumps by 1, that is).
4) aio_poll() calls vfs_poll(). After sanity checks (basically,
"poll_wait() had been called and only once") it locks the queue.
That's what the extra reference to iocb had been for - we know we
can safely access it.
5) With queue locked, we check if ->woken has already been set to
true (by aio_poll_wake()) and, if it had been, we unlock the
queue, drop a reference to aio_kiocb and bugger off - at that
point it's a responsibility to aio_poll_wake() and the stuff
called/scheduled by it. That code will drop the reference to file
in req->file, along with the other reference to our aio_kiocb.
6) otherwise, we see whether we need to wait. If we do, we unlock the
queue, drop one reference to aio_kiocb and go away - eventual
wakeup (or cancel) will deal with the reference to file and with
the other reference to aio_kiocb
7) otherwise we remove ourselves from waitqueue (still under the
queue lock), so that wakeup won't get us. No async activity will
be happening, so we can safely drop req->file and iocb ourselves.
If wakeup happens while we are in vfs_poll(), we are fine - aio_kiocb
won't get freed under us, so we can do all the checks and locking
safely. And we don't touch ->file if we detect that case.
However, vfs_poll() most certainly *does* touch the file it had been
given. So wakeup coming while we are still in ->poll() might end up
doing fput() on that file. That case is not too rare, and usually we
are saved by the still present reference from descriptor table - that
fput() is not the final one.
But if another thread closes that descriptor right after our fget()
and wakeup does happen before ->poll() returns, we are in trouble -
final fput() done while we are in the middle of a method:
Al also wrote a patch to take an extra reference to the file descriptor
to fix this, but I instead suggested we just streamline the whole file
pointer handling by submit_io() so that the generic aio submission code
simply keeps the file pointer around until the aio has completed.
Fixes: bfe4037e722e ("aio: implement IOCB_CMD_POLL")
Acked-by: Al Viro <[email protected]>
Reported-by: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static inline void aio_poll_complete(struct aio_kiocb *iocb, __poll_t mask)
{
struct file *file = iocb->poll.file;
aio_complete(iocb, mangle_poll(mask), 0);
fput(file);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'aio: simplify - and fix - fget/fput for io_submit()
Al Viro root-caused a race where the IOCB_CMD_POLL handling of
fget/fput() could cause us to access the file pointer after it had
already been freed:
"In more details - normally IOCB_CMD_POLL handling looks so:
1) io_submit(2) allocates aio_kiocb instance and passes it to
aio_poll()
2) aio_poll() resolves the descriptor to struct file by req->file =
fget(iocb->aio_fildes)
3) aio_poll() sets ->woken to false and raises ->ki_refcnt of that
aio_kiocb to 2 (bumps by 1, that is).
4) aio_poll() calls vfs_poll(). After sanity checks (basically,
"poll_wait() had been called and only once") it locks the queue.
That's what the extra reference to iocb had been for - we know we
can safely access it.
5) With queue locked, we check if ->woken has already been set to
true (by aio_poll_wake()) and, if it had been, we unlock the
queue, drop a reference to aio_kiocb and bugger off - at that
point it's a responsibility to aio_poll_wake() and the stuff
called/scheduled by it. That code will drop the reference to file
in req->file, along with the other reference to our aio_kiocb.
6) otherwise, we see whether we need to wait. If we do, we unlock the
queue, drop one reference to aio_kiocb and go away - eventual
wakeup (or cancel) will deal with the reference to file and with
the other reference to aio_kiocb
7) otherwise we remove ourselves from waitqueue (still under the
queue lock), so that wakeup won't get us. No async activity will
be happening, so we can safely drop req->file and iocb ourselves.
If wakeup happens while we are in vfs_poll(), we are fine - aio_kiocb
won't get freed under us, so we can do all the checks and locking
safely. And we don't touch ->file if we detect that case.
However, vfs_poll() most certainly *does* touch the file it had been
given. So wakeup coming while we are still in ->poll() might end up
doing fput() on that file. That case is not too rare, and usually we
are saved by the still present reference from descriptor table - that
fput() is not the final one.
But if another thread closes that descriptor right after our fget()
and wakeup does happen before ->poll() returns, we are in trouble -
final fput() done while we are in the middle of a method:
Al also wrote a patch to take an extra reference to the file descriptor
to fix this, but I instead suggested we just streamline the whole file
pointer handling by submit_io() so that the generic aio submission code
simply keeps the file pointer around until the aio has completed.
Fixes: bfe4037e722e ("aio: implement IOCB_CMD_POLL")
Acked-by: Al Viro <[email protected]>
Reported-by: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static inline void iocb_put(struct aio_kiocb *iocb)
{
if (refcount_read(&iocb->ki_refcnt) == 0 ||
refcount_dec_and_test(&iocb->ki_refcnt)) {
percpu_ref_put(&iocb->ki_ctx->reqs);
kmem_cache_free(kiocb_cachep, iocb);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'aio: simplify - and fix - fget/fput for io_submit()
Al Viro root-caused a race where the IOCB_CMD_POLL handling of
fget/fput() could cause us to access the file pointer after it had
already been freed:
"In more details - normally IOCB_CMD_POLL handling looks so:
1) io_submit(2) allocates aio_kiocb instance and passes it to
aio_poll()
2) aio_poll() resolves the descriptor to struct file by req->file =
fget(iocb->aio_fildes)
3) aio_poll() sets ->woken to false and raises ->ki_refcnt of that
aio_kiocb to 2 (bumps by 1, that is).
4) aio_poll() calls vfs_poll(). After sanity checks (basically,
"poll_wait() had been called and only once") it locks the queue.
That's what the extra reference to iocb had been for - we know we
can safely access it.
5) With queue locked, we check if ->woken has already been set to
true (by aio_poll_wake()) and, if it had been, we unlock the
queue, drop a reference to aio_kiocb and bugger off - at that
point it's a responsibility to aio_poll_wake() and the stuff
called/scheduled by it. That code will drop the reference to file
in req->file, along with the other reference to our aio_kiocb.
6) otherwise, we see whether we need to wait. If we do, we unlock the
queue, drop one reference to aio_kiocb and go away - eventual
wakeup (or cancel) will deal with the reference to file and with
the other reference to aio_kiocb
7) otherwise we remove ourselves from waitqueue (still under the
queue lock), so that wakeup won't get us. No async activity will
be happening, so we can safely drop req->file and iocb ourselves.
If wakeup happens while we are in vfs_poll(), we are fine - aio_kiocb
won't get freed under us, so we can do all the checks and locking
safely. And we don't touch ->file if we detect that case.
However, vfs_poll() most certainly *does* touch the file it had been
given. So wakeup coming while we are still in ->poll() might end up
doing fput() on that file. That case is not too rare, and usually we
are saved by the still present reference from descriptor table - that
fput() is not the final one.
But if another thread closes that descriptor right after our fget()
and wakeup does happen before ->poll() returns, we are in trouble -
final fput() done while we are in the middle of a method:
Al also wrote a patch to take an extra reference to the file descriptor
to fix this, but I instead suggested we just streamline the whole file
pointer handling by submit_io() so that the generic aio submission code
simply keeps the file pointer around until the aio has completed.
Fixes: bfe4037e722e ("aio: implement IOCB_CMD_POLL")
Acked-by: Al Viro <[email protected]>
Reported-by: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void aio_complete_rw(struct kiocb *kiocb, long res, long res2)
{
struct aio_kiocb *iocb = container_of(kiocb, struct aio_kiocb, rw);
if (!list_empty_careful(&iocb->ki_list))
aio_remove_iocb(iocb);
if (kiocb->ki_flags & IOCB_WRITE) {
struct inode *inode = file_inode(kiocb->ki_filp);
/*
* Tell lockdep we inherited freeze protection from submission
* thread.
*/
if (S_ISREG(inode->i_mode))
__sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
file_end_write(kiocb->ki_filp);
}
fput(kiocb->ki_filp);
aio_complete(iocb, res, res2);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'aio: simplify - and fix - fget/fput for io_submit()
Al Viro root-caused a race where the IOCB_CMD_POLL handling of
fget/fput() could cause us to access the file pointer after it had
already been freed:
"In more details - normally IOCB_CMD_POLL handling looks so:
1) io_submit(2) allocates aio_kiocb instance and passes it to
aio_poll()
2) aio_poll() resolves the descriptor to struct file by req->file =
fget(iocb->aio_fildes)
3) aio_poll() sets ->woken to false and raises ->ki_refcnt of that
aio_kiocb to 2 (bumps by 1, that is).
4) aio_poll() calls vfs_poll(). After sanity checks (basically,
"poll_wait() had been called and only once") it locks the queue.
That's what the extra reference to iocb had been for - we know we
can safely access it.
5) With queue locked, we check if ->woken has already been set to
true (by aio_poll_wake()) and, if it had been, we unlock the
queue, drop a reference to aio_kiocb and bugger off - at that
point it's a responsibility to aio_poll_wake() and the stuff
called/scheduled by it. That code will drop the reference to file
in req->file, along with the other reference to our aio_kiocb.
6) otherwise, we see whether we need to wait. If we do, we unlock the
queue, drop one reference to aio_kiocb and go away - eventual
wakeup (or cancel) will deal with the reference to file and with
the other reference to aio_kiocb
7) otherwise we remove ourselves from waitqueue (still under the
queue lock), so that wakeup won't get us. No async activity will
be happening, so we can safely drop req->file and iocb ourselves.
If wakeup happens while we are in vfs_poll(), we are fine - aio_kiocb
won't get freed under us, so we can do all the checks and locking
safely. And we don't touch ->file if we detect that case.
However, vfs_poll() most certainly *does* touch the file it had been
given. So wakeup coming while we are still in ->poll() might end up
doing fput() on that file. That case is not too rare, and usually we
are saved by the still present reference from descriptor table - that
fput() is not the final one.
But if another thread closes that descriptor right after our fget()
and wakeup does happen before ->poll() returns, we are in trouble -
final fput() done while we are in the middle of a method:
Al also wrote a patch to take an extra reference to the file descriptor
to fix this, but I instead suggested we just streamline the whole file
pointer handling by submit_io() so that the generic aio submission code
simply keeps the file pointer around until the aio has completed.
Fixes: bfe4037e722e ("aio: implement IOCB_CMD_POLL")
Acked-by: Al Viro <[email protected]>
Reported-by: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: MagickExport int LocaleLowercase(const int c)
{
#if defined(MAGICKCORE_LOCALE_SUPPORT)
if (c_locale != (locale_t) NULL)
return(tolower_l(c,c_locale));
#endif
return(tolower(c));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': '...'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: MagickExport int LocaleUppercase(const int c)
{
if (c < 0)
return(c);
#if defined(MAGICKCORE_LOCALE_SUPPORT)
if (c_locale != (locale_t) NULL)
return(toupper_l((int) ((unsigned char) c),c_locale));
#endif
return(toupper((int) ((unsigned char) c)));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': '...'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: MagickExport int LocaleUppercase(const int c)
{
#if defined(MAGICKCORE_LOCALE_SUPPORT)
if (c_locale != (locale_t) NULL)
return(toupper_l((int) ((unsigned char) c),c_locale));
#endif
return(toupper((int) ((unsigned char) c)));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399', 'CWE-125'], 'message': '...'</s> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.