CVE-2021-43860 (published 2022-01-12T22:15Z)

Flatpak is a Linux application sandboxing and distribution framework. Prior to versions 1.12.3 and 1.10.6, Flatpak doesn\'t properly validate that the permissions displayed to the user for an app at install time match the actual permissions granted to the app at runtime, in the case that there\'s a null byte in the metadata file of an app. Therefore apps can grant themselves permissions without the consent of the user. Flatpak shows permissions to the user during install by reading them from the "xa.metadata" key in the commit metadata. This cannot contain a null terminator, because it is an untrusted GVariant. Flatpak compares these permissions to the *actual* metadata, from the "metadata" file to ensure it wasn\'t lied to. However, the actual metadata contents are loaded in several places where they are read as simple C-style strings. That means that, if the metadata file includes a null terminator, only the content of the file from *before* the terminator gets compared to xa.metadata. Thus, any permissions that appear in the metadata file after a null terminator are applied at runtime but not shown to the user. So maliciously crafted apps can give themselves hidden permissions. Users who have Flatpaks installed from untrusted sources are at risk in case the Flatpak has a maliciously crafted metadata file, either initially or in an update. This issue is patched in versions 1.12.3 and 1.10.6. As a workaround, users can manually check the permissions of installed apps by checking the metadata file or the xa.metadata key on the commit metadata.

Severity: MEDIUM
CVSS v2 base score: 6.8 (AV:N/AC:M/Au:N/C:P/I:P/A:P)
CVSS v3 base score: 8.6, HIGH (CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:C/C:H/I:H/A:H)

Weakness information:
cwe_id: CWE-276
cwe_name: Incorrect Default Permissions
description: During installation, installed file permissions are set to allow anyone to modify those files.
extended_description: 
      
      
     
     

Fix information:
repo_url: https://github.com/flatpak/flatpak
commit_details: repo_url: https://github.com/flatpak/flatpak
author: Alexander Larsson
author_date: 2022-01-10 16:43:08+01:00
msg: Transaction: Fail the resolve if xa.metadata invalid or missing

If we fail to parse xa.metadata from the summary cache or the commit
xa.metadata we fail the resolve.

If xa.metadata is missing in the commit we fail the resolve (it is
always set in the summary cache, because summary update converts
missing xa.metadata to "", so we either get that, or cache miss which
leads to resolving from the commit.

This means that op->resolved_metadata is always set during install and
updates, which means we will show the app permissions. The transaction
will also always make sure that this data actually matches what gets
deployed.

Before this change an invalid metadata in the summary cache could lead
to a NULL resolved_metadata, which means we wouldn't print the app
permissions, yet we would still deploy some metadata file that could
have permissions. (NOTE: It would fail to deploy unless the
xa.metadata in the commit matched the metadata file, but in this
corner case we would't compare the summary and commit metadata, so
they may differ.)
repository: repo_url: https://github.com/flatpak/flatpak
repo_name: flatpak/flatpak
description: Linux application sandboxing and distribution framework
repo_language: C
owner: flatpak
file_changes: filename: flatpak-transaction.c
change_type: ModificationType.MODIFY
diff: @@ -2970,12 +2970,13 @@ emit_eol_and_maybe_skip (FlatpakTransaction          *self,
   g_signal_emit (self, signals[END_OF_LIFED_WITH_REBASE], 0, op->remote, flatpak_decomposed_get_ref (op->ref), op->eol, op->eol_rebase, previous_ids, &op->skip);
 }
 
-static void
+static gboolean
 mark_op_resolved (FlatpakTransactionOperation *op,
                   const char                  *commit,
                   GFile                       *sideload_path,
                   GBytes                      *metadata,
-                  GBytes                      *old_metadata)
+                  GBytes                      *old_metadata,
+                  GError                     **error)
 {
   g_debug ("marking op %s:%s resolved to %s", kind_to_str (op->kind), flatpak_decomposed_get_ref (op->ref), commit ? commit : "-");
 
@@ -2997,13 +2998,12 @@ mark_op_resolved (FlatpakTransactionOperation *op,
   if (metadata)
     {
       g_autoptr(GKeyFile) metakey = g_key_file_new ();
-      if (g_key_file_load_from_bytes (metakey, metadata, G_KEY_FILE_NONE, NULL))
-        {
-          op->resolved_metadata = g_bytes_ref (metadata);
-          op->resolved_metakey = g_steal_pointer (&metakey);
-        }
-      else
-        g_message ("Warning: Failed to parse metadata for %s\n", flatpak_decomposed_get_ref (op->ref));
+      if (!g_key_file_load_from_bytes (metakey, metadata, G_KEY_FILE_NONE, NULL))
+        return flatpak_fail_error (error, FLATPAK_ERROR_INVALID_DATA,
+                                   "Metadata for %s is invalid", flatpak_decomposed_get_ref (op->ref));
+
+      op->resolved_metadata = g_bytes_ref (metadata);
+      op->resolved_metakey = g_steal_pointer (&metakey);
     }
   if (old_metadata)
     {
@@ -3014,31 +3014,40 @@ mark_op_resolved (FlatpakTransactionOperation *op,
           op->resolved_old_metakey = g_steal_pointer (&metakey);
         }
       else
-        g_message ("Warning: Failed to parse old metadata for %s\n", flatpak_decomposed_get_ref (op->ref));
+        {
+          /* This shouldn't happen, but a NULL old metadata is safe (all permisssions are considered new) */
+          g_message ("Warning: Failed to parse old metadata for %s\n", flatpak_decomposed_get_ref (op->ref));
+        }
     }
+
+  return TRUE;
 }
 
-static void
+static gboolean
 resolve_op_end (FlatpakTransaction *self,
                 FlatpakTransactionOperation *op,
                 const char *checksum,
                 GFile *sideload_path,
-                GBytes *metadata_bytes)
+                GBytes *metadata_bytes,
+                GError **error)
 {
   g_autoptr(GBytes) old_metadata_bytes = NULL;
 
   old_metadata_bytes = load_deployed_metadata (self, op->ref, NULL, NULL);
-  mark_op_resolved (op, checksum, sideload_path, metadata_bytes, old_metadata_bytes);
+  if (!mark_op_resolved (op, checksum, sideload_path, metadata_bytes, old_metadata_bytes, error))
+    return FALSE;
   emit_eol_and_maybe_skip (self, op);
+  return TRUE;
  }
 
 
-static void
+static gboolean
 resolve_op_from_commit (FlatpakTransaction *self,
                         FlatpakTransactionOperation *op,
                         const char *checksum,
                         GFile *sideload_path,
-                        GVariant *commit_data)
+                        GVariant *commit_data,
+                        GError **error)
 {
   g_autoptr(GBytes) metadata_bytes = NULL;
   g_autoptr(GVariant) commit_metadata = NULL;
@@ -3049,9 +3058,11 @@ resolve_op_from_commit (FlatpakTransaction *self,
   commit_metadata = g_variant_get_child_value (commit_data, 0);
   g_variant_lookup (commit_metadata, "xa.metadata", "&s", &xa_metadata);
   if (xa_metadata == NULL)
-    g_message ("Warning: No xa.metadata in local commit %s ref %s", checksum, flatpak_decomposed_get_ref (op->ref));
-  else
-    metadata_bytes = g_bytes_new (xa_metadata, strlen (xa_metadata));
+    return flatpak_fail_error (error, FLATPAK_ERROR_INVALID_DATA,
+                               "No xa.metadata in local commit %s ref %s",
+                               checksum, flatpak_decomposed_get_ref (op->ref));
+
+  metadata_bytes = g_bytes_new (xa_metadata, strlen (xa_metadata));
 
   if (g_variant_lookup (commit_metadata, "xa.download-size", "t", &download_size))
     op->download_size = GUINT64_FROM_BE (download_size);
@@ -3061,15 +3072,19 @@ resolve_op_from_commit (FlatpakTransaction *self,
   g_variant_lookup (commit_metadata, OSTREE_COMMIT_META_KEY_ENDOFLIFE, "s", &op->eol);
   g_variant_lookup (commit_metadata, OSTREE_COMMIT_META_KEY_ENDOFLIFE_REBASE, "s", &op->eol_rebase);
 
-  resolve_op_end (self, op, checksum, sideload_path, metadata_bytes);
+  return resolve_op_end (self, op, checksum, sideload_path, metadata_bytes, error);
 }
 
+/* NOTE: In case of non-available summary this returns FALSE with a
+ * NULL error, but for other error cases it will be set.
+ */
 static gboolean
 try_resolve_op_from_metadata (FlatpakTransaction *self,
                               FlatpakTransactionOperation *op,
                               const char *checksum,
                               GFile *sideload_path,
-                              FlatpakRemoteState *state)
+                              FlatpakRemoteState *state,
+                              GError **error)
 {
   g_autoptr(GBytes) metadata_bytes = NULL;
   guint64 download_size = 0;
@@ -3109,8 +3124,7 @@ try_resolve_op_from_metadata (FlatpakTransaction *self,
       op->token_type = GINT32_FROM_LE (var_metadata_lookup_int32 (sparse_cache, FLATPAK_SPARSE_CACHE_KEY_TOKEN_TYPE, op->token_type));
     }
 
-  resolve_op_end (self, op, checksum, sideload_path, metadata_bytes);
-  return TRUE;
+  return resolve_op_end (self, op, checksum, sideload_path, metadata_bytes, error);
 }
 
 static gboolean
@@ -3153,7 +3167,8 @@ resolve_ops (FlatpakTransaction *self,
            * checksum we got was the version already installed.
            */
           g_assert (op->resolved_commit != NULL);
-          mark_op_resolved (op, op->resolved_commit, NULL, NULL, NULL);
+          if (!mark_op_resolved (op, op->resolved_commit, NULL, NULL, NULL, error))
+            return FALSE;
           continue;
         }
 
@@ -3167,14 +3182,16 @@ resolve_ops (FlatpakTransaction *self,
               op->skip = TRUE;
               continue;
             }
-          mark_op_resolved (op, checksum, NULL, metadata_bytes, NULL);
+          if (!mark_op_resolved (op, checksum, NULL, metadata_bytes, NULL, error))
+            return FALSE;
           continue;
         }
 
       if (op->kind == FLATPAK_TRANSACTION_OPERATION_INSTALL_BUNDLE)
         {
           g_assert (op->commit != NULL);
-          mark_op_resolved (op, op->commit, NULL, op->external_metadata, NULL);
+          if (!mark_op_resolved (op, op->commit, NULL, op->external_metadata, NULL, error))
+            return FALSE;
           continue;
         }
 
@@ -3205,7 +3222,8 @@ resolve_ops (FlatpakTransaction *self,
           if (commit_data == NULL)
             return FALSE;
 
-          resolve_op_from_commit (self, op, checksum, NULL, commit_data);
+          if (!resolve_op_from_commit (self, op, checksum, NULL, commit_data, error))
+            return FALSE;
         }
       else
         {
@@ -3264,9 +3282,16 @@ resolve_ops (FlatpakTransaction *self,
             }
 
           /* First try to resolve via metadata (if remote is available and its metadata matches the commit version) */
-          if (!try_resolve_op_from_metadata (self, op, checksum, sideload_path, state))
+          if (!try_resolve_op_from_metadata (self, op, checksum, sideload_path, state, &local_error))
             {
-              /* Else try to load the commit object.
+              if (local_error)
+                {
+                  /* Actual error, not just missing from summary */
+                  g_propagate_error (error, g_steal_pointer (&local_error));
+                  return FALSE;
+                }
+
+              /* Missing from summary, try to load the commit object.
                * Note, we don't have a token here, so this will not work for authenticated apps.
                * We handle this by catching the 401 http status and retrying. */
               g_autoptr(GVariant) commit_data = NULL;
@@ -3302,7 +3327,8 @@ resolve_ops (FlatpakTransaction *self,
                   return FALSE;
                 }
 
-              resolve_op_from_commit (self, op, checksum, sideload_path, commit_data);
+              if (!resolve_op_from_commit (self, op, checksum, sideload_path, commit_data, error))
+                return FALSE;
             }
         }
     }

programming_language: C
repo_url: https://github.com/flatpak/flatpak
commit_details: repo_url: https://github.com/flatpak/flatpak
author: Alexander Larsson
author_date: 2022-01-12 11:00:56+01:00
msg: Ensure that bundles have metadata on install

If we have a bundle without metadata we wouldn't properly present
the permissions in the transaction.
repository: repo_url: https://github.com/flatpak/flatpak
repo_name: flatpak/flatpak
description: Linux application sandboxing and distribution framework
repo_language: C
owner: flatpak
file_changes: filename: flatpak-dir.c
change_type: ModificationType.MODIFY
diff: @@ -9372,6 +9372,13 @@ flatpak_dir_ensure_bundle_remote (FlatpakDir         *self,
   if (metadata == NULL)
     return NULL;
 
+  /* If we rely on metadata (to e.g. print permissions), check it exists before creating the remote */
+  if (out_metadata && fp_metadata == NULL)
+    {
+      flatpak_fail_error (error, FLATPAK_ERROR_INVALID_DATA, "No metadata in bundler header");
+      return NULL;
+    }
+
   gpg_data = extra_gpg_data ? extra_gpg_data : included_gpg_data;
 
   deploy_data = flatpak_dir_get_deploy_data (self, ref, FLATPAK_DEPLOY_VERSION_ANY, cancellable, NULL);

programming_language: C
repo_url: https://github.com/flatpak/flatpak
commit_details: repo_url: https://github.com/flatpak/flatpak
author: Alexander Larsson
author_date: 2022-01-11 10:27:46+01:00
msg: Require metadata in commit also for OCI remotes

This was disables a long time ago because the fedora remotes didn't
contain metadata, but that has been added since then. Requiring fixes
a security concern where an app claims to require no permissions (by
having no metadata in commit) but then actually requires permissions
in the installed app.
repository: repo_url: https://github.com/flatpak/flatpak
repo_name: flatpak/flatpak
description: Linux application sandboxing and distribution framework
repo_language: C
owner: flatpak
file_changes: filename: flatpak-dir.c
change_type: ModificationType.MODIFY
diff: @@ -1795,7 +1795,6 @@ validate_commit_metadata (GVariant   *commit_data,
                           const char *ref,
                           const char *required_metadata,
                           gsize       required_metadata_size,
-                          gboolean   require_xa_metadata,
                           GError   **error)
 {
   g_autoptr(GVariant) commit_metadata = NULL;
@@ -1814,9 +1813,9 @@ validate_commit_metadata (GVariant   *commit_data,
         xa_metadata = g_variant_get_string (xa_metadata_v, &xa_metadata_size);
     }
 
-  if ((xa_metadata == NULL && require_xa_metadata) ||
-      (xa_metadata != NULL && (xa_metadata_size != required_metadata_size ||
-                               memcmp (xa_metadata, required_metadata, xa_metadata_size) != 0)))
+  if (xa_metadata == NULL ||
+      xa_metadata_size != required_metadata_size ||
+      memcmp (xa_metadata, required_metadata, xa_metadata_size) != 0)
     {
       g_set_error (error, G_IO_ERROR, G_IO_ERROR_PERMISSION_DENIED,
                    _("Commit metadata for %s not matching expected metadata"), ref);
@@ -5848,7 +5847,6 @@ flatpak_dir_pull (FlatpakDir                           *self,
                                      ref,
                                      (const char *)g_bytes_get_data (require_metadata, NULL),
                                      g_bytes_get_size (require_metadata),
-                                     TRUE,
                                      error))
         goto out;
     }
@@ -8173,7 +8171,6 @@ flatpak_dir_deploy (FlatpakDir          *self,
   g_autoptr(GFile) metadata_file = NULL;
   g_autofree char *metadata_contents = NULL;
   gsize metadata_size = 0;
-  gboolean is_oci;
   const char *flatpak;
 
   if (!flatpak_dir_ensure_repo (self, cancellable, error))
@@ -8399,12 +8396,9 @@ flatpak_dir_deploy (FlatpakDir          *self,
   /* Check the metadata in the commit to make sure it matches the actual
    * deployed metadata, in case we relied on the one in the commit for
    * a decision
-   * Note: For historical reason we don't enforce commits to contain xa.metadata
-   * since this was lacking in fedora builds.
    */
-  is_oci = flatpak_dir_get_remote_oci (self, origin);
   if (!validate_commit_metadata (commit_data, flatpak_decomposed_get_ref (ref),
-                                 metadata_contents, metadata_size, !is_oci, error))
+                                 metadata_contents, metadata_size, error))
     return FALSE;
 
   dotref = g_file_resolve_relative_path (checkoutdir, "files/.ref");

programming_language: C
repo_url: https://github.com/flatpak/flatpak
commit_details: repo_url: https://github.com/flatpak/flatpak
author: Ryan Gonzalez
author_date: 2021-12-23 18:30:17-06:00
msg: Fix metadata file contents after null terminators being ignored

In particular, if a null terminator is placed inside the metadata file,
Flatpak will only compare the text *before* it to the value of
xa.metadata, but the full file will be parsed when permissions are set
at runtime. This means that any app can include a null terminator in its
permissions metadata, and Flatpak will only show the user the
permissions *preceding* the terminator during install, but the
permissions *after* the terminator are applied at runtime.

Fixes GHSA-qpjc-vq3c-572j / CVE-2021-43860

Signed-off-by: Ryan Gonzalez <ryan.gonzalez@collabora.com>
repository: repo_url: https://github.com/flatpak/flatpak
repo_name: flatpak/flatpak
description: Linux application sandboxing and distribution framework
repo_language: C
owner: flatpak
file_changes: filename: flatpak-dir.c
change_type: ModificationType.MODIFY
diff: @@ -1794,19 +1794,29 @@ static gboolean
 validate_commit_metadata (GVariant   *commit_data,
                           const char *ref,
                           const char *required_metadata,
+                          gsize       required_metadata_size,
                           gboolean   require_xa_metadata,
                           GError   **error)
 {
   g_autoptr(GVariant) commit_metadata = NULL;
+  g_autoptr(GVariant) xa_metadata_v = NULL;
   const char *xa_metadata = NULL;
+  gsize xa_metadata_size = 0;
 
   commit_metadata = g_variant_get_child_value (commit_data, 0);
 
   if (commit_metadata != NULL)
-    g_variant_lookup (commit_metadata, "xa.metadata", "&s", &xa_metadata);
+    {
+      xa_metadata_v = g_variant_lookup_value (commit_metadata,
+                                              "xa.metadata",
+                                              G_VARIANT_TYPE_STRING);
+      if (xa_metadata_v)
+        xa_metadata = g_variant_get_string (xa_metadata_v, &xa_metadata_size);
+    }
 
   if ((xa_metadata == NULL && require_xa_metadata) ||
-      (xa_metadata != NULL && g_strcmp0 (required_metadata, xa_metadata) != 0))
+      (xa_metadata != NULL && (xa_metadata_size != required_metadata_size ||
+                               memcmp (xa_metadata, required_metadata, xa_metadata_size) != 0)))
     {
       g_set_error (error, G_IO_ERROR, G_IO_ERROR_PERMISSION_DENIED,
                    _("Commit metadata for %s not matching expected metadata"), ref);
@@ -3515,6 +3525,7 @@ upgrade_deploy_data (GBytes             *deploy_data,
       g_autoptr(GKeyFile) keyfile = NULL;
       g_autoptr(GFile) metadata_file = NULL;
       g_autofree char *metadata_contents = NULL;
+      gsize metadata_size = 0;
       g_autofree char *id = flatpak_decomposed_dup_id (ref);
 
       /* Add fields from commit metadata to deploy */
@@ -3528,9 +3539,9 @@ upgrade_deploy_data (GBytes             *deploy_data,
       keyfile = g_key_file_new ();
       metadata_file = g_file_resolve_relative_path (deploy_dir, "metadata");
       if (!g_file_load_contents (metadata_file, cancellable,
-                                 &metadata_contents, NULL, NULL, error))
+                                 &metadata_contents, &metadata_size, NULL, error))
         return NULL;
-      if (!g_key_file_load_from_data (keyfile, metadata_contents, -1, 0, error))
+      if (!g_key_file_load_from_data (keyfile, metadata_contents, metadata_size, 0, error))
         return NULL;
       add_metadata_to_deploy_data (&metadata_dict, keyfile);
 
@@ -5833,8 +5844,13 @@ flatpak_dir_pull (FlatpakDir                           *self,
     {
       g_autoptr(GVariant) commit_data = NULL;
       if (!ostree_repo_load_commit (repo, rev, &commit_data, NULL, error) ||
-          !validate_commit_metadata (commit_data, ref, (const char *)g_bytes_get_data (require_metadata, NULL), TRUE, error))
-        return FALSE;
+          !validate_commit_metadata (commit_data,
+                                     ref,
+                                     (const char *)g_bytes_get_data (require_metadata, NULL),
+                                     g_bytes_get_size (require_metadata),
+                                     TRUE,
+                                     error))
+        goto out;
     }
 
   if (!flatpak_dir_pull_extra_data (self, repo,
@@ -8156,6 +8172,7 @@ flatpak_dir_deploy (FlatpakDir          *self,
   g_auto(GLnxLockFile) lock = { 0, };
   g_autoptr(GFile) metadata_file = NULL;
   g_autofree char *metadata_contents = NULL;
+  gsize metadata_size = 0;
   gboolean is_oci;
   const char *flatpak;
 
@@ -8366,11 +8383,12 @@ flatpak_dir_deploy (FlatpakDir          *self,
   keyfile = g_key_file_new ();
   metadata_file = g_file_resolve_relative_path (checkoutdir, "metadata");
   if (g_file_load_contents (metadata_file, NULL,
-                            &metadata_contents, NULL, NULL, NULL))
+                            &metadata_contents,
+                            &metadata_size, NULL, NULL))
     {
       if (!g_key_file_load_from_data (keyfile,
                                       metadata_contents,
-                                      -1,
+                                      metadata_size,
                                       0, error))
         return FALSE;
 
@@ -8386,7 +8404,7 @@ flatpak_dir_deploy (FlatpakDir          *self,
    */
   is_oci = flatpak_dir_get_remote_oci (self, origin);
   if (!validate_commit_metadata (commit_data, flatpak_decomposed_get_ref (ref),
-                                 metadata_contents, !is_oci, error))
+                                 metadata_contents, metadata_size, !is_oci, error))
     return FALSE;
 
   dotref = g_file_resolve_relative_path (checkoutdir, "files/.ref");

programming_language: C
filename: flatpak-transaction.c
change_type: ModificationType.MODIFY
diff: @@ -2539,7 +2539,7 @@ flatpak_transaction_add_ref (FlatpakTransaction             *self,
     return FALSE;
 
   if (external_metadata)
-    op->external_metadata = g_bytes_new (external_metadata, strlen (external_metadata) + 1);
+    op->external_metadata = g_bytes_new (external_metadata, strlen (external_metadata));
 
   return TRUE;
 }
@@ -2950,7 +2950,7 @@ load_deployed_metadata (FlatpakTransaction *self, FlatpakDecomposed *ref, char *
       return NULL;
     }
 
-  return g_bytes_new_take (g_steal_pointer (&metadata_contents), metadata_contents_length + 1);
+  return g_bytes_new_take (g_steal_pointer (&metadata_contents), metadata_contents_length);
 }
 
 static void
@@ -3051,7 +3051,7 @@ resolve_op_from_commit (FlatpakTransaction *self,
   if (xa_metadata == NULL)
     g_message ("Warning: No xa.metadata in local commit %s ref %s", checksum, flatpak_decomposed_get_ref (op->ref));
   else
-    metadata_bytes = g_bytes_new (xa_metadata, strlen (xa_metadata) + 1);
+    metadata_bytes = g_bytes_new (xa_metadata, strlen (xa_metadata));
 
   if (g_variant_lookup (commit_metadata, "xa.download-size", "t", &download_size))
     op->download_size = GUINT64_FROM_BE (download_size);
@@ -3091,7 +3091,7 @@ try_resolve_op_from_metadata (FlatpakTransaction *self,
                                           &download_size, &installed_size, &metadata, NULL))
       return FALSE;
 
-  metadata_bytes = g_bytes_new (metadata, strlen (metadata) + 1);
+  metadata_bytes = g_bytes_new (metadata, strlen (metadata));
 
   if (flatpak_remote_state_lookup_ref (state, flatpak_decomposed_get_ref (op->ref),
                                        NULL, NULL, &info, NULL, NULL))

programming_language: C
filename: flatpak-utils.c
change_type: ModificationType.MODIFY
diff: @@ -6667,6 +6667,7 @@ flatpak_pull_from_bundle (OstreeRepo   *repo,
                           GCancellable *cancellable,
                           GError      **error)
 {
+  gsize metadata_size = 0;
   g_autofree char *metadata_contents = NULL;
   g_autofree char *to_checksum = NULL;
   g_autoptr(GFile) root = NULL;
@@ -6683,6 +6684,8 @@ flatpak_pull_from_bundle (OstreeRepo   *repo,
   if (metadata == NULL)
     return FALSE;
 
+  metadata_size = strlen (metadata_contents);
+
   if (!ostree_repo_get_remote_option (repo, remote, "collection-id", NULL,
                                       &remote_collection_id, NULL))
     remote_collection_id = NULL;
@@ -6752,12 +6755,10 @@ flatpak_pull_from_bundle (OstreeRepo   *repo,
                                   cancellable, error) < 0)
         return FALSE;
 
-      /* Null terminate */
-      g_output_stream_write (G_OUTPUT_STREAM (data_stream), "\0", 1, NULL, NULL);
-
       metadata_valid =
         metadata_contents != NULL &&
-        strcmp (metadata_contents, g_memory_output_stream_get_data (data_stream)) == 0;
+        metadata_size == g_memory_output_stream_get_data_size (data_stream) &&
+        memcmp (metadata_contents, g_memory_output_stream_get_data (data_stream), metadata_size) == 0;
     }
   else
     {

programming_language: C
repo_url: https://github.com/flatpak/flatpak
commit_details: repo_url: https://github.com/flatpak/flatpak
author: Phaedrus Leeds
author_date: 2021-12-28 11:48:16-08:00
msg: Add test for metadata validation

This tests for invalid metadata, missing xa.metadata and mismatched
values in xa.metadata and the real metadata, including the embedded
null leading to the hidden permissions of CVE-2021-43860.
repository: repo_url: https://github.com/flatpak/flatpak
repo_name: flatpak/flatpak
description: Linux application sandboxing and distribution framework
repo_language: C
owner: flatpak
file_changes: filename: Makefile-test-matrix.am.inc
change_type: ModificationType.MODIFY
diff: @@ -37,6 +37,7 @@ TEST_MATRIX_DIST= \
 	tests/test-http-utils.sh \
 	tests/test-history.sh \
 	tests/test-default-remotes.sh \
+	tests/test-metadata-validation.sh \
 	tests/test-extensions.sh \
 	tests/test-oci.sh \
 	tests/test-override.sh \

programming_language: Shell
filename: Makefile.am.inc
change_type: ModificationType.MODIFY
diff: @@ -269,6 +269,7 @@ TEST_MATRIX_SOURCE = \
 	tests/test-history.sh \
 	tests/test-sideload.sh{user+system} \
 	tests/test-default-remotes.sh \
+	tests/test-metadata-validation.sh \
 	tests/test-extensions.sh \
 	tests/test-bundle.sh{user+system+system-norevokefs} \
 	tests/test-oci.sh \

programming_language: Shell
filename: test-metadata-validation.sh
change_type: ModificationType.ADD
diff: @@ -0,0 +1,158 @@
+#!/bin/bash
+#
+# Copyright (C) 2021 Matthew Leeds <mwleeds@protonmail.com>
+#
+# SPDX-License-Identifier: LGPL-2.0-or-later
+
+set -euo pipefail
+
+. $(dirname $0)/libtest.sh
+
+echo "1..7"
+
+setup_repo
+
+COUNTER=1
+
+create_app () {
+    local OPTIONS="$1"
+    local DIR=`mktemp -d`
+
+    mkdir ${DIR}/files
+    echo $COUNTER > ${DIR}/files/counter
+    let COUNTER=COUNTER+1
+
+    local INVALID=""
+    if [[ $OPTIONS =~ "invalid" ]]; then
+        INVALID=invalidkeyfileline
+    fi
+    cat > ${DIR}/metadata <<EOF
+[Application]
+name=org.test.Malicious
+runtime=org.test.Platform/${ARCH}/master
+$INVALID
+
+[Context]
+EOF
+    if [[ $OPTIONS =~ "mismatch" ]]; then
+        echo -e "filesystems=host;" >> ${DIR}/metadata
+    fi
+    if [[ $OPTIONS =~ "hidden" ]]; then
+        echo -ne "\0" >> ${DIR}/metadata
+        echo -e "\nfilesystems=home;" >> ${DIR}/metadata
+    fi
+    local XA_METADATA=--add-metadata-string=xa.metadata="$(head -n6 ${DIR}/metadata)"$'\n'
+    if [[ $OPTIONS =~ "no-xametadata" ]]; then
+        XA_METADATA="--add-metadata-string=xa.nometadata=1"
+    fi
+    ostree commit --repo=repos/test --branch=app/org.test.Malicious/${ARCH}/master ${FL_GPGARGS} "$XA_METADATA" ${DIR}/
+    if [[ $OPTIONS =~ "no-cache-in-summary" ]]; then
+        ostree --repo=repos/test ${FL_GPGARGS} summary -u
+        # force use of legacy summary format
+        rm -rf repos/test/summary.idx repos/test/summaries
+    else
+        update_repo
+    fi
+    rm -rf ${DIR}
+}
+
+cleanup_repo () {
+    ostree refs --repo=repos/test --delete app/org.test.Malicious/${ARCH}/master
+    update_repo
+}
+
+create_app "hidden"
+
+if ${FLATPAK} ${U} install -y test-repo org.test.Malicious 2>install-error-log; then
+    assert_not_reached "Should not be able to install app with hidden permissions"
+fi
+
+assert_file_has_content install-error-log "not matching expected metadata"
+
+assert_not_has_dir $FL_DIR/app/org.test.Malicious/current/active
+
+cleanup_repo
+
+ok "app with hidden permissions can't be installed (CVE-2021-43860)"
+
+create_app no-xametadata
+
+# The install will fail because the metadata in the summary doesn't match the metadata on the commit
+# The missing xa.metadata in the commit got turned into "" in the xa.cache
+if ${FLATPAK} ${U} install -y test-repo org.test.Malicious 2>install-error-log; then
+    assert_not_reached "Should not be able to install app with missing xa.metadata"
+fi
+
+assert_file_has_content install-error-log "not matching expected metadata"
+
+assert_not_has_dir $FL_DIR/app/org.test.Malicious/current/active
+
+cleanup_repo
+
+ok "app with no xa.metadata can't be installed"
+
+create_app "no-xametadata no-cache-in-summary"
+
+# The install will fail because there's no metadata in the summary or on the commit
+if ${FLATPAK} ${U} install -y test-repo org.test.Malicious 2>install-error-log; then
+    assert_not_reached "Should not be able to install app with missing metadata"
+fi
+assert_file_has_content install-error-log "No xa.metadata in local commit"
+
+assert_not_has_dir $FL_DIR/app/org.test.Malicious/current/active
+
+cleanup_repo
+
+ok "app with no xa.metadata and no metadata in summary can't be installed"
+
+create_app "invalid"
+
+if ${FLATPAK} ${U} install -y test-repo org.test.Malicious 2>install-error-log; then
+    assert_not_reached "Should not be able to install app with invalid metadata"
+fi
+assert_file_has_content install-error-log "Metadata for .* is invalid"
+
+assert_not_has_dir $FL_DIR/app/org.test.Malicious/current/active
+
+cleanup_repo
+
+ok "app with invalid metadata (in summary) can't be installed"
+
+create_app "invalid no-cache-in-summary"
+
+if ${FLATPAK} ${U} install -y test-repo org.test.Malicious 2>install-error-log; then
+    assert_not_reached "Should not be able to install app with invalid metadata"
+fi
+assert_file_has_content install-error-log "Metadata for .* is invalid"
+
+assert_not_has_dir $FL_DIR/app/org.test.Malicious/current/active
+
+cleanup_repo
+
+ok "app with invalid metadata (in commit) can't be installed"
+
+create_app "mismatch no-cache-in-summary"
+
+if ${FLATPAK} ${U} install -y test-repo org.test.Malicious 2>install-error-log; then
+    assert_not_reached "Should not be able to install app with non-matching metadata"
+fi
+assert_file_has_content install-error-log "Commit metadata for .* not matching expected metadata"
+
+assert_not_has_dir $FL_DIR/app/org.test.Malicious/current/active
+
+cleanup_repo
+
+ok "app with mismatched metadata (in commit) can't be installed"
+
+create_app "mismatch"
+
+if ${FLATPAK} ${U} install -y test-repo org.test.Malicious 2>install-error-log; then
+    assert_not_reached "Should not be able to install app with non-matching metadata"
+fi
+assert_file_has_content install-error-log "Commit metadata for .* not matching expected metadata"
+
+assert_not_has_dir $FL_DIR/app/org.test.Malicious/current/active
+
+cleanup_repo
+
+ok "app with mismatched metadata (in summary) can't be installed"

programming_language: Shell