summaryrefslogtreecommitdiffstats
path: root/chrome/browser/password_manager/native_backend_kwallet_x.cc
blob: 3ec2ec2ff2871e99d17283d37f430636148442c5 (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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/password_manager/native_backend_kwallet_x.h"

#include <sstream>

#include "base/logging.h"
#include "base/pickle.h"
#include "base/stl_util-inl.h"
#include "base/string_util.h"
#include "content/browser/browser_thread.h"

using std::string;
using std::vector;
using webkit_glue::PasswordForm;

// We could localize these strings, but then changing your locale would cause
// you to lose access to all your stored passwords. Maybe best not to do that.
const char* NativeBackendKWallet::kAppId = "Chrome";
const char* NativeBackendKWallet::kKWalletFolder = "Chrome Form Data";

const char* NativeBackendKWallet::kKWalletServiceName = "org.kde.kwalletd";
const char* NativeBackendKWallet::kKWalletPath = "/modules/kwalletd";
const char* NativeBackendKWallet::kKWalletInterface = "org.kde.KWallet";
const char* NativeBackendKWallet::kKLauncherServiceName = "org.kde.klauncher";
const char* NativeBackendKWallet::kKLauncherPath = "/KLauncher";
const char* NativeBackendKWallet::kKLauncherInterface = "org.kde.KLauncher";

NativeBackendKWallet::NativeBackendKWallet()
    : error_(NULL),
      connection_(NULL),
      proxy_(NULL) {
}

NativeBackendKWallet::~NativeBackendKWallet() {
  if (proxy_)
    g_object_unref(proxy_);
}

bool NativeBackendKWallet::Init() {
  // Get a connection to the session bus.
  connection_ = dbus_g_bus_get(DBUS_BUS_SESSION, &error_);
  if (CheckError())
    return false;

  if (!InitWallet()) {
    // kwalletd may not be running. Try to start it and try again.
    if (!StartKWalletd() || !InitWallet())
      return false;
  }

  return true;
}

bool NativeBackendKWallet::StartKWalletd() {
  // Sadly kwalletd doesn't use DBUS activation, so we have to make a call to
  // klauncher to start it.
  DBusGProxy* klauncher_proxy =
      dbus_g_proxy_new_for_name(connection_, kKLauncherServiceName,
                                kKLauncherPath, kKLauncherInterface);

  char* empty_string_list = NULL;
  int ret = 1;
  char* error = NULL;
  dbus_g_proxy_call(klauncher_proxy, "start_service_by_desktop_name", &error_,
                    G_TYPE_STRING,  "kwalletd",          // serviceName
                    G_TYPE_STRV,    &empty_string_list,  // urls
                    G_TYPE_STRV,    &empty_string_list,  // envs
                    G_TYPE_STRING,  "",                  // startup_id
                    G_TYPE_BOOLEAN, (gboolean) false,    // blind
                    G_TYPE_INVALID,
                    G_TYPE_INT,     &ret,                // result
                    G_TYPE_STRING,  NULL,                // dubsName
                    G_TYPE_STRING,  &error,              // error
                    G_TYPE_INT,     NULL,                // pid
                    G_TYPE_INVALID);

  if (error && *error) {
    LOG(ERROR) << "Error launching kwalletd: " << error;
    ret = 1;  // Make sure we return false after freeing.
  }

  g_free(error);
  g_object_unref(klauncher_proxy);

  if (CheckError() || ret != 0)
    return false;
  return true;
}

bool NativeBackendKWallet::InitWallet() {
  // Make a proxy to KWallet.
  proxy_ = dbus_g_proxy_new_for_name(connection_, kKWalletServiceName,
                                     kKWalletPath, kKWalletInterface);

  // Check KWallet is enabled.
  gboolean is_enabled = false;
  dbus_g_proxy_call(proxy_, "isEnabled", &error_,
                    G_TYPE_INVALID,
                    G_TYPE_BOOLEAN, &is_enabled,
                    G_TYPE_INVALID);
  if (CheckError() || !is_enabled)
    return false;

  // Get the wallet name.
  char* wallet_name = NULL;
  dbus_g_proxy_call(proxy_, "networkWallet", &error_,
                    G_TYPE_INVALID,
                    G_TYPE_STRING, &wallet_name,
                    G_TYPE_INVALID);
  if (CheckError() || !wallet_name)
    return false;

  wallet_name_.assign(wallet_name);
  g_free(wallet_name);

  return true;
}

bool NativeBackendKWallet::AddLogin(const PasswordForm& form) {
  int wallet_handle = WalletHandle();
  if (wallet_handle == kInvalidKWalletHandle)
    return false;

  PasswordFormList forms;
  GetLoginsList(&forms, form.signon_realm, wallet_handle);

  forms.push_back(new PasswordForm(form));
  bool ok = SetLoginsList(forms, form.signon_realm, wallet_handle);

  STLDeleteElements(&forms);
  return ok;
}

bool NativeBackendKWallet::UpdateLogin(const PasswordForm& form) {
  int wallet_handle = WalletHandle();
  if (wallet_handle == kInvalidKWalletHandle)
    return false;

  PasswordFormList forms;
  GetLoginsList(&forms, form.signon_realm, wallet_handle);

  for (size_t i = 0; i < forms.size(); ++i) {
    if (CompareForms(form, *forms[i], true))
      *forms[i] = form;
  }

  bool ok = SetLoginsList(forms, form.signon_realm, wallet_handle);

  STLDeleteElements(&forms);
  return ok;
}

bool NativeBackendKWallet::RemoveLogin(const PasswordForm& form) {
  int wallet_handle = WalletHandle();
  if (wallet_handle == kInvalidKWalletHandle)
    return false;

  PasswordFormList all_forms;
  GetLoginsList(&all_forms, form.signon_realm, wallet_handle);

  PasswordFormList kept_forms;
  kept_forms.reserve(all_forms.size());
  for (size_t i = 0; i < all_forms.size(); ++i) {
    if (CompareForms(form, *all_forms[i], false))
      delete all_forms[i];
    else
      kept_forms.push_back(all_forms[i]);
  }

  // Update the entry in the wallet, possibly deleting it.
  bool ok = SetLoginsList(kept_forms, form.signon_realm, wallet_handle);

  STLDeleteElements(&kept_forms);
  return ok;
}

bool NativeBackendKWallet::RemoveLoginsCreatedBetween(
    const base::Time& delete_begin,
    const base::Time& delete_end) {
  int wallet_handle = WalletHandle();
  if (wallet_handle == kInvalidKWalletHandle)
    return false;

  // We could probably also use readEntryList here.
  char** realm_list = NULL;
  dbus_g_proxy_call(proxy_, "entryList", &error_,
                    G_TYPE_INT,     wallet_handle,             // handle
                    G_TYPE_STRING,  kKWalletFolder,            // folder
                    G_TYPE_STRING,  kAppId,                    // appid
                    G_TYPE_INVALID,
                    G_TYPE_STRV,    &realm_list,
                    G_TYPE_INVALID);
  if (CheckError())
    return false;

  bool ok = true;
  for (char** realm = realm_list; *realm; ++realm) {
    GArray* byte_array = NULL;
    dbus_g_proxy_call(proxy_, "readEntry", &error_,
                      G_TYPE_INT,     wallet_handle,           // handle
                      G_TYPE_STRING,  kKWalletFolder,          // folder
                      G_TYPE_STRING,  *realm,                  // key
                      G_TYPE_STRING,  kAppId,                  // appid
                      G_TYPE_INVALID,
                      DBUS_TYPE_G_UCHAR_ARRAY, &byte_array,
                      G_TYPE_INVALID);

    if (CheckError() || !byte_array ||
        !CheckSerializedValue(byte_array, *realm)) {
      continue;
    }

    string signon_realm(*realm);
    Pickle pickle(byte_array->data, byte_array->len);
    PasswordFormList all_forms;
    DeserializeValue(signon_realm, pickle, &all_forms);
    g_array_free(byte_array, true);

    PasswordFormList kept_forms;
    kept_forms.reserve(all_forms.size());
    for (size_t i = 0; i < all_forms.size(); ++i) {
      if (delete_begin <= all_forms[i]->date_created &&
          (delete_end.is_null() || all_forms[i]->date_created < delete_end)) {
        delete all_forms[i];
      } else {
        kept_forms.push_back(all_forms[i]);
      }
    }

    if (!SetLoginsList(kept_forms, signon_realm, wallet_handle))
      ok = false;
    STLDeleteElements(&kept_forms);
  }
  g_strfreev(realm_list);
  return ok;
}

bool NativeBackendKWallet::GetLogins(const PasswordForm& form,
                                     PasswordFormList* forms) {
  int wallet_handle = WalletHandle();
  if (wallet_handle == kInvalidKWalletHandle)
    return false;
  return GetLoginsList(forms, form.signon_realm, wallet_handle);
}

bool NativeBackendKWallet::GetLoginsCreatedBetween(const base::Time& get_begin,
                                                   const base::Time& get_end,
                                                   PasswordFormList* forms) {
  int wallet_handle = WalletHandle();
  if (wallet_handle == kInvalidKWalletHandle)
    return false;
  return GetLoginsList(forms, get_begin, get_end, wallet_handle);
}

bool NativeBackendKWallet::GetAutofillableLogins(PasswordFormList* forms) {
  int wallet_handle = WalletHandle();
  if (wallet_handle == kInvalidKWalletHandle)
    return false;
  return GetLoginsList(forms, true, wallet_handle);
}

bool NativeBackendKWallet::GetBlacklistLogins(PasswordFormList* forms) {
  int wallet_handle = WalletHandle();
  if (wallet_handle == kInvalidKWalletHandle)
    return false;
  return GetLoginsList(forms, false, wallet_handle);
}

bool NativeBackendKWallet::GetLoginsList(PasswordFormList* forms,
                                         const string& signon_realm,
                                         int wallet_handle) {
  // Is there an entry in the wallet?
  gboolean has_entry = false;
  dbus_g_proxy_call(proxy_, "hasEntry", &error_,
                    G_TYPE_INT,     wallet_handle,         // handle
                    G_TYPE_STRING,  kKWalletFolder,        // folder
                    G_TYPE_STRING,  signon_realm.c_str(),  // key
                    G_TYPE_STRING,  kAppId,                // appid
                    G_TYPE_INVALID,
                    G_TYPE_BOOLEAN, &has_entry,
                    G_TYPE_INVALID);

  if (CheckError())
    return false;
  if (!has_entry) {
    // This is not an error. There just isn't a matching entry.
    return true;
  }

  GArray* byte_array = NULL;
  dbus_g_proxy_call(proxy_, "readEntry", &error_,
                    G_TYPE_INT,     wallet_handle,         // handle
                    G_TYPE_STRING,  kKWalletFolder,        // folder
                    G_TYPE_STRING,  signon_realm.c_str(),  // key
                    G_TYPE_STRING,  kAppId,                // appid
                    G_TYPE_INVALID,
                    DBUS_TYPE_G_UCHAR_ARRAY, &byte_array,
                    G_TYPE_INVALID);

  if (CheckError() || !byte_array)
    return false;
  if (!CheckSerializedValue(byte_array, signon_realm.c_str())) {
    // This is weird, but we choose not to call it an error. There's an invalid
    // entry somehow, but by pretending it just doesn't exist, we make it easier
    // to repair without having to delete it using kwalletmanager (that is, by
    // just saving a new password within this realm to overwrite it).
    g_array_free(byte_array, true);
    return true;
  }

  Pickle pickle(byte_array->data, byte_array->len);
  DeserializeValue(signon_realm, pickle, forms);
  g_array_free(byte_array, true);

  return true;
}

bool NativeBackendKWallet::GetLoginsList(PasswordFormList* forms,
                                         bool autofillable,
                                         int wallet_handle) {
  PasswordFormList all_forms;
  if (!GetAllLogins(&all_forms, wallet_handle))
    return false;

  // We have to read all the entries, and then filter them here.
  forms->reserve(forms->size() + all_forms.size());
  for (size_t i = 0; i < all_forms.size(); ++i) {
    if (all_forms[i]->blacklisted_by_user == !autofillable)
      forms->push_back(all_forms[i]);
    else
      delete all_forms[i];
  }

  return true;
}

bool NativeBackendKWallet::GetLoginsList(PasswordFormList* forms,
                                         const base::Time& begin,
                                         const base::Time& end,
                                         int wallet_handle) {
  PasswordFormList all_forms;
  if (!GetAllLogins(&all_forms, wallet_handle))
    return false;

  // We have to read all the entries, and then filter them here.
  forms->reserve(forms->size() + all_forms.size());
  for (size_t i = 0; i < all_forms.size(); ++i) {
    if (begin <= all_forms[i]->date_created &&
        (end.is_null() || all_forms[i]->date_created < end)) {
      forms->push_back(all_forms[i]);
    } else {
      delete all_forms[i];
    }
  }

  return true;
}

bool NativeBackendKWallet::GetAllLogins(PasswordFormList* forms,
                                        int wallet_handle) {
  // We could probably also use readEntryList here.
  char** realm_list = NULL;
  dbus_g_proxy_call(proxy_, "entryList", &error_,
                    G_TYPE_INT,     wallet_handle,             // handle
                    G_TYPE_STRING,  kKWalletFolder,            // folder
                    G_TYPE_STRING,  kAppId,                    // appid
                    G_TYPE_INVALID,
                    G_TYPE_STRV,    &realm_list,
                    G_TYPE_INVALID);
  if (CheckError())
    return false;

  for (char** realm = realm_list; *realm; ++realm) {
    GArray* byte_array = NULL;
    dbus_g_proxy_call(proxy_, "readEntry", &error_,
                      G_TYPE_INT,     wallet_handle,           // handle
                      G_TYPE_STRING,  kKWalletFolder,          // folder
                      G_TYPE_STRING,  *realm,                  // key
                      G_TYPE_STRING,  kAppId,                  // appid
                      G_TYPE_INVALID,
                      DBUS_TYPE_G_UCHAR_ARRAY, &byte_array,
                      G_TYPE_INVALID);

    if (CheckError() || !byte_array ||
        !CheckSerializedValue(byte_array, *realm)) {
      continue;
    }

    Pickle pickle(byte_array->data, byte_array->len);
    DeserializeValue(*realm, pickle, forms);
    g_array_free(byte_array, true);
  }
  g_strfreev(realm_list);
  return true;
}

bool NativeBackendKWallet::SetLoginsList(const PasswordFormList& forms,
                                         const string& signon_realm,
                                         int wallet_handle) {
  if (forms.empty()) {
    // No items left? Remove the entry from the wallet.
    int ret = 0;
    dbus_g_proxy_call(proxy_, "removeEntry", &error_,
                      G_TYPE_INT,     wallet_handle,         // handle
                      G_TYPE_STRING,  kKWalletFolder,        // folder
                      G_TYPE_STRING,  signon_realm.c_str(),  // key
                      G_TYPE_STRING,  kAppId,                // appid
                      G_TYPE_INVALID,
                      G_TYPE_INT,     &ret,
                      G_TYPE_INVALID);
    CheckError();
    if (ret != 0)
      LOG(ERROR) << "Bad return code " << ret << " from kwallet removeEntry";
    return ret == 0;
  }

  Pickle value;
  SerializeValue(forms, &value);

  // Convert the pickled bytes to a GByteArray.
  GArray* byte_array = g_array_sized_new(false, false, sizeof(char),
                                         value.size());
  g_array_append_vals(byte_array, value.data(), value.size());

  // Make the call.
  int ret = 0;
  dbus_g_proxy_call(proxy_, "writeEntry", &error_,
                    G_TYPE_INT,           wallet_handle,         // handle
                    G_TYPE_STRING,        kKWalletFolder,        // folder
                    G_TYPE_STRING,        signon_realm.c_str(),  // key
                    DBUS_TYPE_G_UCHAR_ARRAY, byte_array,         // value
                    G_TYPE_STRING,        kAppId,                // appid
                    G_TYPE_INVALID,
                    G_TYPE_INT,           &ret,
                    G_TYPE_INVALID);
  g_array_free(byte_array, true);

  CheckError();
  if (ret != 0)
    LOG(ERROR) << "Bad return code " << ret << " from kwallet writeEntry";
  return ret == 0;
}

bool NativeBackendKWallet::CompareForms(const PasswordForm& a,
                                        const PasswordForm& b,
                                        bool update_check) {
  // An update check doesn't care about the submit element.
  if (!update_check && a.submit_element != b.submit_element)
    return false;
  return a.origin           == b.origin &&
         a.password_element == b.password_element &&
         a.signon_realm     == b.signon_realm &&
         a.username_element == b.username_element &&
         a.username_value   == b.username_value;
}

void NativeBackendKWallet::SerializeValue(const PasswordFormList& forms,
                                          Pickle* pickle) {
  pickle->WriteInt(kPickleVersion);
  pickle->WriteSize(forms.size());
  for (PasswordFormList::const_iterator it = forms.begin() ;
       it != forms.end() ; ++it) {
    const PasswordForm* form = *it;
    pickle->WriteInt(form->scheme);
    pickle->WriteString(form->origin.spec());
    pickle->WriteString(form->action.spec());
    pickle->WriteString16(form->username_element);
    pickle->WriteString16(form->username_value);
    pickle->WriteString16(form->password_element);
    pickle->WriteString16(form->password_value);
    pickle->WriteString16(form->submit_element);
    pickle->WriteBool(form->ssl_valid);
    pickle->WriteBool(form->preferred);
    pickle->WriteBool(form->blacklisted_by_user);
    pickle->WriteInt64(form->date_created.ToTimeT());
  }
}

bool NativeBackendKWallet::CheckSerializedValue(const GArray* byte_array,
                                                const char* realm) {
  const Pickle::Header* header =
      reinterpret_cast<const Pickle::Header*>(byte_array->data);
  if (byte_array->len < sizeof(*header) ||
      header->payload_size > byte_array->len - sizeof(*header)) {
    LOG(WARNING) << "Invalid KWallet entry detected! (realm: " << realm << ")";
    return false;
  }
  return true;
}

void NativeBackendKWallet::DeserializeValue(const string& signon_realm,
                                            const Pickle& pickle,
                                            PasswordFormList* forms) {
  void* iter = NULL;

  int version = -1;
  pickle.ReadInt(&iter, &version);
  if (version != kPickleVersion) {
    // This is the only version so far, so anything else is an error.
    return;
  }

  size_t count = 0;
  pickle.ReadSize(&iter, &count);

  forms->reserve(forms->size() + count);
  for (size_t i = 0; i < count; ++i) {
    PasswordForm* form = new PasswordForm();
    form->signon_realm.assign(signon_realm);

    int scheme = 0;
    pickle.ReadInt(&iter, &scheme);
    form->scheme = static_cast<PasswordForm::Scheme>(scheme);
    ReadGURL(pickle, &iter, &form->origin);
    ReadGURL(pickle, &iter, &form->action);
    pickle.ReadString16(&iter, &form->username_element);
    pickle.ReadString16(&iter, &form->username_value);
    pickle.ReadString16(&iter, &form->password_element);
    pickle.ReadString16(&iter, &form->password_value);
    pickle.ReadString16(&iter, &form->submit_element);
    pickle.ReadBool(&iter, &form->ssl_valid);
    pickle.ReadBool(&iter, &form->preferred);
    pickle.ReadBool(&iter, &form->blacklisted_by_user);
    int64 date_created = 0;
    pickle.ReadInt64(&iter, &date_created);
    form->date_created = base::Time::FromTimeT(date_created);
    forms->push_back(form);
  }
}

void NativeBackendKWallet::ReadGURL(const Pickle& pickle, void** iter,
                                    GURL* url) {
  string url_string;
  if (!pickle.ReadString(iter, &url_string)) {
    LOG(ERROR) << "Failed to read url string";
    *url = GURL();
    return;
  }
  *url = GURL(url_string);
}

bool NativeBackendKWallet::CheckError() {
  if (error_) {
    LOG(ERROR) << "Failed to complete KWallet call: " << error_->message;
    g_error_free(error_);
    error_ = NULL;
    return true;
  }
  return false;
}

int NativeBackendKWallet::WalletHandle() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));
  // Open the wallet.
  int handle = kInvalidKWalletHandle;
  dbus_g_proxy_call(proxy_, "open", &error_,
                    G_TYPE_STRING, wallet_name_.c_str(),  // wallet
                    G_TYPE_INT64,  0LL,                   // wid
                    G_TYPE_STRING, kAppId,                // appid
                    G_TYPE_INVALID,
                    G_TYPE_INT,    &handle,
                    G_TYPE_INVALID);
  if (CheckError() || handle == kInvalidKWalletHandle)
    return kInvalidKWalletHandle;

  // Check if our folder exists.
  gboolean has_folder = false;
  dbus_g_proxy_call(proxy_, "hasFolder", &error_,
                    G_TYPE_INT,    handle,          // handle
                    G_TYPE_STRING, kKWalletFolder,  // folder
                    G_TYPE_STRING, kAppId,          // appid
                    G_TYPE_INVALID,
                    G_TYPE_BOOLEAN, &has_folder,
                    G_TYPE_INVALID);
  if (CheckError())
    return kInvalidKWalletHandle;

  // Create it if it didn't.
  if (!has_folder) {
    gboolean success = false;
    dbus_g_proxy_call(proxy_, "createFolder", &error_,
                      G_TYPE_INT,    handle,          // handle
                      G_TYPE_STRING, kKWalletFolder,  // folder
                      G_TYPE_STRING, kAppId,          // appid
                      G_TYPE_INVALID,
                      G_TYPE_BOOLEAN, &success,
                      G_TYPE_INVALID);
    if (CheckError() || !success)
      return kInvalidKWalletHandle;
  }

  return handle;
}