summaryrefslogtreecommitdiffstats
path: root/security/manager/ssl/LibSecret.cpp
blob: 4b50c4d0b3f8ab8d12c564e7ed25b70fb3fbf4f0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "LibSecret.h"

#include <gio/gio.h>
#include <gmodule.h>
#include <memory>

#include "mozilla/Base64.h"
#include "mozilla/Logging.h"
#include "MainThreadUtils.h"
#include "prlink.h"

// This is the implementation of LibSecret, an instantiation of OSKeyStore for
// Linux.

using namespace mozilla;

LazyLogModule gLibSecretLog("libsecret");

static PRLibrary* libsecret = nullptr;

typedef struct _SecretService SecretService;
typedef struct _SecretCollection SecretCollection;

typedef enum {
  SECRET_SCHEMA_NONE = 0,
  SECRET_SCHEMA_DONT_MATCH_NAME = 1 << 1
} SecretSchemaFlags;

typedef enum {
  SECRET_SCHEMA_ATTRIBUTE_STRING = 0,
  SECRET_SCHEMA_ATTRIBUTE_INTEGER = 1,
  SECRET_SCHEMA_ATTRIBUTE_BOOLEAN = 2,
} SecretSchemaAttributeType;

typedef struct {
  const gchar* name;
  SecretSchemaAttributeType type;
} SecretSchemaAttribute;

typedef struct {
  const gchar* name;
  SecretSchemaFlags flags;
  SecretSchemaAttribute attributes[32];

  /* <private> */
  gint reserved;
  gpointer reserved1;
  gpointer reserved2;
  gpointer reserved3;
  gpointer reserved4;
  gpointer reserved5;
  gpointer reserved6;
  gpointer reserved7;
} SecretSchema;

typedef enum {
  SECRET_COLLECTION_NONE = 0 << 0,
  SECRET_COLLECTION_LOAD_ITEMS = 1 << 1,
} SecretCollectionFlags;

typedef enum {
  SECRET_SERVICE_NONE = 0,
  SECRET_SERVICE_OPEN_SESSION = 1 << 1,
  SECRET_SERVICE_LOAD_COLLECTIONS = 1 << 2,
} SecretServiceFlags;

typedef enum {
  SECRET_ERROR_PROTOCOL = 1,
  SECRET_ERROR_IS_LOCKED = 2,
  SECRET_ERROR_NO_SUCH_OBJECT = 3,
  SECRET_ERROR_ALREADY_EXISTS = 4,
} SecretError;

#define SECRET_COLLECTION_DEFAULT "default"

typedef SecretCollection* (*secret_collection_for_alias_sync_fn)(
    SecretService*, const gchar*, SecretCollectionFlags, GCancellable*,
    GError**);
typedef SecretService* (*secret_service_get_sync_fn)(SecretServiceFlags,
                                                     GCancellable*, GError**);
typedef gboolean (*secret_password_clear_sync_fn)(const SecretSchema*,
                                                  GCancellable*, GError**, ...);
typedef gchar* (*secret_password_lookup_sync_fn)(const SecretSchema*,
                                                 GCancellable*, GError**, ...);
typedef gboolean (*secret_password_store_sync_fn)(const SecretSchema*,
                                                  const gchar*, const gchar*,
                                                  const gchar*, GCancellable*,
                                                  GError**, ...);
typedef void (*secret_password_free_fn)(const gchar*);
typedef GQuark (*secret_error_get_quark_fn)();

static secret_collection_for_alias_sync_fn secret_collection_for_alias_sync =
    nullptr;
static secret_service_get_sync_fn secret_service_get_sync = nullptr;
static secret_password_clear_sync_fn secret_password_clear_sync = nullptr;
static secret_password_lookup_sync_fn secret_password_lookup_sync = nullptr;
static secret_password_store_sync_fn secret_password_store_sync = nullptr;
static secret_password_free_fn secret_password_free = nullptr;
static secret_error_get_quark_fn secret_error_get_quark = nullptr;

nsresult MaybeLoadLibSecret() {
  MOZ_ASSERT(NS_IsMainThread());
  if (!NS_IsMainThread()) {
    return NS_ERROR_NOT_SAME_THREAD;
  }

  if (!libsecret) {
    libsecret = PR_LoadLibrary("libsecret-1.so.0");
    if (!libsecret) {
      return NS_ERROR_NOT_AVAILABLE;
    }

// With TSan, we cannot unload libsecret once we have loaded it because
// TSan does not support unloading libraries that are matched from its
// suppression list. Hence we just keep the library loaded in TSan builds.
#ifdef MOZ_TSAN
#  define UNLOAD_LIBSECRET(x) \
    do {                      \
    } while (0)
#else
#  define UNLOAD_LIBSECRET(x) PR_UnloadLibrary(x)
#endif

#define FIND_FUNCTION_SYMBOL(function)                                   \
  function = (function##_fn)PR_FindFunctionSymbol(libsecret, #function); \
  if (!(function)) {                                                     \
    UNLOAD_LIBSECRET(libsecret);                                         \
    libsecret = nullptr;                                                 \
    return NS_ERROR_NOT_AVAILABLE;                                       \
  }
    FIND_FUNCTION_SYMBOL(secret_collection_for_alias_sync);
    FIND_FUNCTION_SYMBOL(secret_service_get_sync);
    FIND_FUNCTION_SYMBOL(secret_password_clear_sync);
    FIND_FUNCTION_SYMBOL(secret_password_lookup_sync);
    FIND_FUNCTION_SYMBOL(secret_password_store_sync);
    FIND_FUNCTION_SYMBOL(secret_password_free);
    FIND_FUNCTION_SYMBOL(secret_error_get_quark);
#undef FIND_FUNCTION_SYMBOL
  }

  return NS_OK;
}

struct ScopedDelete {
  void operator()(SecretService* ss) {
    if (ss) g_object_unref(ss);
  }
  void operator()(SecretCollection* sc) {
    if (sc) g_object_unref(sc);
  }
  void operator()(GError* error) {
    if (error) g_error_free(error);
  }
  void operator()(GList* list) {
    if (list) g_list_free(list);
  }
  void operator()(char* val) {
    if (val) secret_password_free(val);
  }
};

template <class T>
struct ScopedMaybeDelete {
  void operator()(T* ptr) {
    if (ptr) {
      ScopedDelete del;
      del(ptr);
    }
  }
};

typedef std::unique_ptr<GError, ScopedMaybeDelete<GError>> ScopedGError;
typedef std::unique_ptr<GList, ScopedMaybeDelete<GList>> ScopedGList;
typedef std::unique_ptr<char, ScopedMaybeDelete<char>> ScopedPassword;
typedef std::unique_ptr<SecretCollection, ScopedMaybeDelete<SecretCollection>>
    ScopedSecretCollection;
typedef std::unique_ptr<SecretService, ScopedMaybeDelete<SecretService>>
    ScopedSecretService;

LibSecret::LibSecret() = default;

LibSecret::~LibSecret() {
  MOZ_ASSERT(NS_IsMainThread());
  if (!NS_IsMainThread()) {
    return;
  }
  if (libsecret) {
    secret_collection_for_alias_sync = nullptr;
    secret_service_get_sync = nullptr;
    secret_password_clear_sync = nullptr;
    secret_password_lookup_sync = nullptr;
    secret_password_store_sync = nullptr;
    secret_password_free = nullptr;
    secret_error_get_quark = nullptr;
    UNLOAD_LIBSECRET(libsecret);
    libsecret = nullptr;
  }
}

static const SecretSchema kSchema = {
    "mozilla.firefox",
    SECRET_SCHEMA_NONE,
    {{"string", SECRET_SCHEMA_ATTRIBUTE_STRING}, /* the label */
     {"NULL", SECRET_SCHEMA_ATTRIBUTE_STRING}}};

nsresult GetScopedServices(ScopedSecretService& aSs,
                           ScopedSecretCollection& aSc) {
  MOZ_ASSERT(secret_service_get_sync && secret_collection_for_alias_sync);
  if (!secret_service_get_sync || !secret_collection_for_alias_sync) {
    return NS_ERROR_FAILURE;
  }
  GError* raw_error = nullptr;
  aSs = ScopedSecretService(secret_service_get_sync(
      static_cast<SecretServiceFlags>(
          SECRET_SERVICE_OPEN_SESSION),  // SecretServiceFlags
      nullptr,                           // GCancellable
      &raw_error));
  ScopedGError error(raw_error);
  if (error || !aSs) {
    MOZ_LOG(gLibSecretLog, LogLevel::Debug, ("Couldn't get a secret service"));
    return NS_ERROR_FAILURE;
  }

  aSc = ScopedSecretCollection(secret_collection_for_alias_sync(
      aSs.get(), "default", static_cast<SecretCollectionFlags>(0),
      nullptr,  // GCancellable
      &raw_error));
  error.reset(raw_error);
  if (!aSc) {
    MOZ_LOG(gLibSecretLog, LogLevel::Debug,
            ("Couldn't get a secret collection"));
    return NS_ERROR_FAILURE;
  }
  return NS_OK;
}

nsresult LibSecret::StoreSecret(const nsACString& aSecret,
                                const nsACString& aLabel) {
  MOZ_ASSERT(secret_password_store_sync);
  if (!secret_password_store_sync) {
    return NS_ERROR_FAILURE;
  }
  // libsecret expects a null-terminated string, so to be safe we store the
  // secret (which could be arbitrary bytes) base64-encoded.
  nsAutoCString base64;
  nsresult rv = Base64Encode(aSecret, base64);
  if (NS_FAILED(rv)) {
    MOZ_LOG(gLibSecretLog, LogLevel::Debug, ("Error base64-encoding secret"));
    return rv;
  }
  GError* raw_error = nullptr;
  bool stored = secret_password_store_sync(
      &kSchema, SECRET_COLLECTION_DEFAULT, PromiseFlatCString(aLabel).get(),
      PromiseFlatCString(base64).get(),
      nullptr,  // GCancellable
      &raw_error, "string", PromiseFlatCString(aLabel).get(), nullptr);
  ScopedGError error(raw_error);
  if (raw_error) {
    MOZ_LOG(gLibSecretLog, LogLevel::Debug, ("Error storing secret"));
    return NS_ERROR_FAILURE;
  }

  return stored ? NS_OK : NS_ERROR_FAILURE;
}

nsresult LibSecret::DeleteSecret(const nsACString& aLabel) {
  MOZ_ASSERT(secret_password_clear_sync && secret_error_get_quark);
  if (!secret_password_clear_sync || !secret_error_get_quark) {
    return NS_ERROR_FAILURE;
  }
  GError* raw_error = nullptr;
  Unused << secret_password_clear_sync(
      &kSchema,
      nullptr,  // GCancellable
      &raw_error, "string", PromiseFlatCString(aLabel).get(), nullptr);
  ScopedGError error(raw_error);
  if (raw_error && !(raw_error->domain == secret_error_get_quark() &&
                     raw_error->code == SECRET_ERROR_NO_SUCH_OBJECT)) {
    MOZ_LOG(gLibSecretLog, LogLevel::Debug, ("Error deleting secret"));
    return NS_ERROR_FAILURE;
  }

  return NS_OK;
}

nsresult LibSecret::RetrieveSecret(const nsACString& aLabel,
                                   /* out */ nsACString& aSecret) {
  MOZ_ASSERT(secret_password_lookup_sync && secret_password_free);
  if (!secret_password_lookup_sync || !secret_password_free) {
    return NS_ERROR_FAILURE;
  }
  GError* raw_error = nullptr;
  aSecret.Truncate();
  ScopedPassword s(secret_password_lookup_sync(
      &kSchema,
      nullptr,  // GCancellable
      &raw_error, "string", PromiseFlatCString(aLabel).get(), nullptr));
  ScopedGError error(raw_error);
  if (raw_error || !s) {
    MOZ_LOG(gLibSecretLog, LogLevel::Debug,
            ("Error retrieving secret or didn't find it"));
    return NS_ERROR_FAILURE;
  }
  // libsecret expects a null-terminated string, so to be safe we store the
  // secret (which could be arbitrary bytes) base64-encoded, which means we have
  // to base64-decode it here.
  nsAutoCString base64Encoded(s.get());
  nsresult rv = Base64Decode(base64Encoded, aSecret);
  if (NS_FAILED(rv)) {
    MOZ_LOG(gLibSecretLog, LogLevel::Debug, ("Error base64-decoding secret"));
    return rv;
  }

  return NS_OK;
}