-
Notifications
You must be signed in to change notification settings - Fork 270
Expand file tree
/
Copy pathlogin.rs
More file actions
1610 lines (1489 loc) · 63.2 KB
/
Copy pathlogin.rs
File metadata and controls
1610 lines (1489 loc) · 63.2 KB
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* 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/. */
// N.B. if you're making a documentation change here, you might also want to make it in:
//
// * The API docs in ../ios/Logins/LoginRecord.swift
// * The API docs in ../android/src/main/java/mozilla/appservices/logins/ServerPassword.kt
// * The android-components docs at
// https://github.com/mozilla-mobile/android-components/tree/master/components/service/sync-logins
//
// We'll figure out a more scalable approach to maintaining all those docs at some point...
//! # Login Structs
//!
//! This module defines a number of core structs for Logins. They are:
//! * [`LoginEntry`] A login entry by the user. This includes the username/password, the site it
//! was submitted to, etc. [`LoginEntry`] does not store data specific to a DB record.
//! * [`Login`] - A [`LoginEntry`] plus DB record information. This includes the GUID and metadata
//! like time_last_used.
//! * [`EncryptedLogin`] -- A Login above with the username/password data encrypted.
//! * [`LoginFields`], [`SecureLoginFields`], [`LoginMeta`] -- These group the common fields in the
//! structs above.
//!
//! Why so many structs for similar data? Consider some common use cases in a hypothetical browser
//! (currently no browsers act exactly like this, although Fenix/android-components comes close):
//!
//! - User visits a page with a login form.
//! - We inform the user if there are saved logins that can be autofilled. We use the
//! `LoginDb.get_by_base_domain()` which returns a `Vec<EncryptedLogin>`. We don't decrypt the
//! logins because we want to avoid requiring the encryption key at this point, which would
//! force the user to authenticate. Note: this is aspirational at this point, no actual
//! implementations follow this flow. Still, we want application-services to support it.
//! - If the user chooses to autofill, we decrypt the logins into a `Vec<Login>`. We need to
//! decrypt at this point to display the username and autofill the password if they select one.
//! - When the user selects a login, we can use the already decrypted data from `Login` to fill
//! in the form.
//! - User chooses to save a login for autofilling later.
//! - We present the user with a dialog that:
//! - Displays a header that differentiates between different types of save: adding a new
//! login, updating an existing login, filling in a blank username, etc.
//! - Allows the user to tweak the username, in case we failed to detect the form field
//! correctly. This may affect which header should be shown.
//! - Here we use `find_login_to_update()` which returns an `Option<Login>`. Returning a login
//! that has decrypted data avoids forcing the consumer code to decrypt the username again.
//!
//! # Login
//! This has the complete set of data about a login. Very closely related is the
//! "sync payload", defined in sync/payload.rs, which handles all aspects of the JSON serialization.
//! It contains the following fields:
//! - `meta`: A [`LoginMeta`] struct.
//! - fields: A [`LoginFields`] struct.
//! - sec_fields: A [`SecureLoginFields`] struct.
//!
//! # LoginEntry
//! The struct used to add or update logins. This has the plain-text version of the fields that are
//! stored encrypted, so almost all uses of an LoginEntry struct will also require the
//! encryption key to be known and passed in. [LoginDB] methods that save data typically input
//! [LoginEntry] instances. This allows the DB code to handle dupe-checking issues like
//! determining which login record should be updated for a newly submitted [LoginEntry].
//! It contains the following fields:
//! - fields: A [`LoginFields`] struct.
//! - sec_fields: A [`SecureLoginFields`] struct.
//!
//! # EncryptedLogin
//! Encrypted version of [`Login`]. [LoginDB] methods that return data typically return [EncryptedLogin]
//! this allows deferring decryption, and therefore user authentication, until the secure data is needed.
//! It contains the following fields
//! - `meta`: A [`LoginMeta`] struct.
//! - `fields`: A [`LoginFields`] struct.
//! - `sec_fields`: The secure fields as an encrypted string
//!
//! # SecureLoginFields
//! The struct used to hold the fields which are stored encrypted. It contains:
//! - username: A string.
//! - password: A string.
//!
//! # LoginFields
//!
//! The core set of fields, use by both [`Login`] and [`LoginEntry`]
//! It contains the following fields:
//!
//! - `origin`: The origin at which this login can be used, as a string.
//!
//! The login should only be used on sites that match this origin (for whatever definition
//! of "matches" makes sense at the application level, e.g. eTLD+1 matching).
//! This field is required, must be a valid origin in punycode format, and must not be
//! set to the empty string.
//!
//! Examples of valid `origin` values include:
//! - "https://site.com"
//! - "http://site.com:1234"
//! - "ftp://ftp.site.com"
//! - "moz-proxy://127.0.0.1:8888"
//! - "chrome://MyLegacyExtension"
//! - "file://"
//! - "https://\[::1\]"
//!
//! If invalid data is received in this field (either from the application, or via sync)
//! then the logins store will attempt to coerce it into valid data by:
//! - truncating full URLs to just their origin component, if it is not an opaque origin
//! - converting values with non-ascii characters into punycode
//!
//! **XXX TODO:**
//! - Add a field with the original unicode versions of the URLs instead of punycode?
//!
//! - `sec_fields`: The `username` and `password` for the site, stored as a encrypted JSON
//! representation of an `SecureLoginFields`.
//!
//! This field is required and usually encrypted. There are two different value types:
//! - Plaintext empty string: Used for deleted records
//! - Encrypted value: The credentials associated with the login.
//!
//! - `http_realm`: The challenge string for HTTP Basic authentication, if any.
//!
//! If present, the login should only be used in response to a HTTP Basic Auth
//! challenge that specifies a matching realm. For legacy reasons this string may not
//! contain null bytes, carriage returns or newlines.
//!
//! If this field is set to the empty string, this indicates a wildcard match on realm.
//!
//! This field must not be present if `form_action_origin` is set, since they indicate different types
//! of login (HTTP-Auth based versus form-based). Exactly one of `http_realm` and `form_action_origin`
//! must be present.
//!
//! - `form_action_origin`: The target origin of forms in which this login can be used, if any, as a string.
//!
//! If present, the login should only be used in forms whose target submission URL matches this origin.
//! This field must be a valid origin or one of the following special cases:
//! - An empty string, which is a wildcard match for any origin.
//! - The single character ".", which is equivalent to the empty string
//! - The string "javascript:", which matches any form with javascript target URL.
//!
//! This field must not be present if `http_realm` is set, since they indicate different types of login
//! (HTTP-Auth based versus form-based). Exactly one of `http_realm` and `form_action_origin` must be present.
//!
//! If invalid data is received in this field (either from the application, or via sync) then the
//! logins store will attempt to coerce it into valid data by:
//! - truncating full URLs to just their origin component
//! - converting origins with non-ascii characters into punycode
//! - replacing invalid values with null if a valid 'http_realm' field is present
//!
//! - `username_field`: The name of the form field into which the 'username' should be filled, if any.
//!
//! This value is stored if provided by the application, but does not imply any restrictions on
//! how the login may be used in practice. For legacy reasons this string may not contain null
//! bytes, carriage returns or newlines. This field must be empty unless `form_action_origin` is set.
//!
//! If invalid data is received in this field (either from the application, or via sync)
//! then the logins store will attempt to coerce it into valid data by:
//! - setting to the empty string if 'form_action_origin' is not present
//!
//! - `password_field`: The name of the form field into which the 'password' should be filled, if any.
//!
//! This value is stored if provided by the application, but does not imply any restrictions on
//! how the login may be used in practice. For legacy reasons this string may not contain null
//! bytes, carriage returns or newlines. This field must be empty unless `form_action_origin` is set.
//!
//! If invalid data is received in this field (either from the application, or via sync)
//! then the logins store will attempt to coerce it into valid data by:
//! - setting to the empty string if 'form_action_origin' is not present
//!
//! # LoginMeta
//!
//! This contains data relating to the login database record -- both on the local instance and
//! synced to other browsers.
//! It contains the following fields:
//! - `id`: A unique string identifier for this record.
//!
//! Consumers may assume that `id` contains only "safe" ASCII characters but should otherwise
//! treat this it as an opaque identifier. These are generated as needed.
//!
//! - `timesUsed`: A lower bound on the number of times the password from this record has been used, as an integer.
//!
//! Applications should use the `touch()` method of the logins store to indicate when a password
//! has been used, and should ensure that they only count uses of the actual `password` field
//! (so for example, copying the `password` field to the clipboard should count as a "use", but
//! copying just the `username` field should not).
//!
//! This number may not record uses that occurred on other devices, since some legacy
//! sync clients do not record this information. It may be zero for records obtained
//! via sync that have never been used locally.
//!
//! When merging duplicate records, the two usage counts are summed.
//!
//! This field is managed internally by the logins store by default and does not need to
//! be set explicitly, although any application-provided value will be preserved when creating
//! a new record.
//!
//! If invalid data is received in this field (either from the application, or via sync)
//! then the logins store will attempt to coerce it into valid data by:
//! - replacing missing or negative values with 0
//!
//! **XXX TODO:**
//! - test that we prevent this counter from moving backwards.
//! - test fixups of missing or negative values
//! - test that we correctly merge dupes
//!
//! - `time_created`: An upper bound on the time of creation of this login, in integer milliseconds from the unix epoch.
//!
//! This is an upper bound because some legacy sync clients do not record this information.
//!
//! Note that this field is typically a timestamp taken from the local machine clock, so it
//! may be wildly inaccurate if the client does not have an accurate clock.
//!
//! This field is managed internally by the logins store by default and does not need to
//! be set explicitly, although any application-provided value will be preserved when creating
//! a new record.
//!
//! When merging duplicate records, the smallest non-zero value is taken.
//!
//! If invalid data is received in this field (either from the application, or via sync)
//! then the logins store will attempt to coerce it into valid data by:
//! - replacing missing or negative values with the current time
//!
//! **XXX TODO:**
//! - test that we prevent this timestamp from moving backwards.
//! - test fixups of missing or negative values
//! - test that we correctly merge dupes
//!
//! - `time_last_used`: A lower bound on the time of last use of this login, in integer milliseconds from the unix epoch.
//!
//! This is a lower bound because some legacy sync clients do not record this information;
//! in that case newer clients set `timeLastUsed` when they use the record for the first time.
//!
//! Note that this field is typically a timestamp taken from the local machine clock, so it
//! may be wildly inaccurate if the client does not have an accurate clock.
//!
//! This field is managed internally by the logins store by default and does not need to
//! be set explicitly, although any application-provided value will be preserved when creating
//! a new record.
//!
//! When merging duplicate records, the largest non-zero value is taken.
//!
//! If invalid data is received in this field (either from the application, or via sync)
//! then the logins store will attempt to coerce it into valid data by:
//! - removing negative values
//!
//! **XXX TODO:**
//! - test that we prevent this timestamp from moving backwards.
//! - test fixups of missing or negative values
//! - test that we correctly merge dupes
//!
//! - `time_password_changed`: A lower bound on the time that the `password` field was last changed, in integer
//! milliseconds from the unix epoch.
//!
//! Changes to other fields (such as `username`) are not reflected in this timestamp.
//! This is a lower bound because some legacy sync clients do not record this information;
//! in that case newer clients set `time_password_changed` when they change the `password` field.
//!
//! Note that this field is typically a timestamp taken from the local machine clock, so it
//! may be wildly inaccurate if the client does not have an accurate clock.
//!
//! This field is managed internally by the logins store by default and does not need to
//! be set explicitly, although any application-provided value will be preserved when creating
//! a new record.
//!
//! When merging duplicate records, the largest non-zero value is taken.
//!
//! If invalid data is received in this field (either from the application, or via sync)
//! then the logins store will attempt to coerce it into valid data by:
//! - removing negative values
//!
//! **XXX TODO:**
//! - test that we prevent this timestamp from moving backwards.
//! - test that we don't set this for changes to other fields.
//! - test that we correctly merge dupes
//!
//!
//! In order to deal with data from legacy clients in a robust way, it is necessary to be able to build
//! and manipulate all these `Login` structs that contain invalid data. The non-encrypted structs
//! implement the `ValidateAndFixup` trait, providing the following methods which can be used by
//! callers to ensure that they're only working with valid records:
//!
//! - `Login::check_valid()`: Checks validity of a login record, returning `()` if it is valid
//! or an error if it is not.
//!
//! - `Login::fixup()`: Returns either the existing login if it is valid, a clone with invalid fields
//! fixed up if it was safe to do so, or an error if the login is irreparably invalid.
use crate::{encryption::EncryptorDecryptor, error::*};
use rusqlite::Row;
use serde_derive::*;
use sync_guid::Guid;
use url::Url;
// The Desktop FxA session-credentials pseudo-login. Firefox stores its account
// credentials as a login under this origin; it must never be synced. This
// mirrors the exclusion the JS `PasswordEngine` does via
// `Utils.getSyncCredentialsHosts()`. Only relevant on Desktop (mobile never has
// such a login), but it's harmless to filter everywhere.
pub(crate) const FXA_CREDENTIALS_ORIGIN: &str = "chrome://FirefoxAccounts";
// LoginEntry fields that are stored in cleartext
#[derive(Debug, Clone, Hash, PartialEq, Eq, Default)]
pub struct LoginFields {
pub origin: String,
pub form_action_origin: Option<String>,
pub http_realm: Option<String>,
pub username_field: String,
pub password_field: String,
}
/// LoginEntry fields that are stored encrypted
#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct SecureLoginFields {
// - Username cannot be null, use the empty string instead
// - Password can't be empty or null (enforced in the ValidateAndFixup code)
//
// This matches the desktop behavior:
// https://searchfox.org/mozilla-central/rev/d3683dbb252506400c71256ef3994cdbdfb71ada/toolkit/components/passwordmgr/LoginManager.jsm#260-267
// Because we store the json version of this in the DB, and that's the only place the json
// is used, we rename the fields to short names, just to reduce the overhead in the DB.
#[serde(rename = "u")]
pub username: String,
#[serde(rename = "p")]
pub password: String,
}
impl SecureLoginFields {
pub fn encrypt(&self, encdec: &dyn EncryptorDecryptor, login_id: &str) -> Result<String> {
let string = serde_json::to_string(&self)?;
let cipherbytes = encdec
.encrypt(string.as_bytes().into())
.map_err(|e| Error::EncryptionFailed(format!("{e} (encrypting {login_id})")))?;
let ciphertext = std::str::from_utf8(&cipherbytes).map_err(|e| {
Error::EncryptionFailed(format!("{e} (encrypting {login_id}: data not utf8)"))
})?;
Ok(ciphertext.to_owned())
}
pub fn decrypt(
ciphertext: &str,
encdec: &dyn EncryptorDecryptor,
login_id: &str,
) -> Result<Self> {
let jsonbytes = encdec.decrypt(ciphertext.as_bytes().into()).map_err(|e| {
Error::DecryptionFailed(format!(
"{e} (decrypting {login_id}, ciphertext length: {})",
ciphertext.len(),
))
})?;
let json =
std::str::from_utf8(&jsonbytes).map_err(|e| Error::DecryptionFailed(e.to_string()))?;
Ok(serde_json::from_str(json)?)
}
}
/// Login data specific to database records
#[derive(Debug, Clone, Hash, PartialEq, Eq, Default)]
pub struct LoginMeta {
pub id: String,
pub time_created: i64,
pub time_password_changed: i64,
pub time_last_used: i64,
pub times_used: i64,
pub time_last_breach_alert_dismissed: Option<i64>,
}
/// A login together with meta fields, handed over to the store API; ie a login persisted
/// elsewhere, useful for migrations
pub struct LoginEntryWithMeta {
pub entry: LoginEntry,
pub meta: LoginMeta,
}
/// A bulk insert result entry, returned by `add_many` and `add_many_with_records`
/// Please note that although the success case is much larger than the error case, this is
/// negligible in real life, as we expect a very small success/error ratio.
#[allow(clippy::large_enum_variant)]
pub enum BulkResultEntry {
Success { login: Login },
Error { message: String },
}
/// A login handed over to the store API; ie a login not yet persisted
#[derive(Debug, Clone, Hash, PartialEq, Eq, Default)]
pub struct LoginEntry {
// login fields
pub origin: String,
pub form_action_origin: Option<String>,
pub http_realm: Option<String>,
pub username_field: String,
pub password_field: String,
// secure fields
pub username: String,
pub password: String,
}
#[cfg(feature = "perform_additional_origin_fixups")]
mod origin_fixup {
fn looks_like_bare_ipv4(s: &str) -> bool {
let parts: Vec<&str> = s.split('.').collect();
parts.len() == 4 && parts.iter().all(|p| p.parse::<u8>().is_ok())
}
// Returns true if `s` looks like a bare domain name (e.g. `example.com`):
// at least two dot-separated labels, each label only ASCII alphanumeric or hyphens.
fn looks_like_bare_domain(s: &str) -> bool {
let parts: Vec<&str> = s.split('.').collect();
parts.len() >= 2
&& parts
.iter()
.all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_alphanumeric() || c == '-'))
}
// Returns true if `s` looks like a single hostname label (no dots),
// e.g. addon-generated origins like "example".
fn looks_like_bare_label(s: &str) -> bool {
!s.is_empty()
&& !s.contains('.')
&& s.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
}
// Attempts to repair origins that fail URL parsing:
// - bare https: / https:/ / https:// → https://moz.pwmngr.fixed
// - http://ftp.<IPv4>[:port] → ftp://<IPv4>[:port] (FireFTP quirk)
// - ftp.<IPv4>[:port] without a scheme → ftp://<IPv4>[:port]
// - ftp.<domain> without a scheme → ftp://ftp.<domain>
// - bare IPv4 address or bare domain → moz-pwmngr-fixed://<host>
// - bare label (e.g. example) → moz-pwmngr-fixed://<label>
pub fn perform_additional_origin_fixup(origin: &str) -> Option<String> {
// Bare https: with missing or incomplete authority.
if matches!(origin, "https:" | "https:/" | "https://") {
return Some("https://moz.pwmngr.fixed".to_string());
}
// http://ftp.<IP>[:port] → ftp://<IP>[:port]
if let Some(rest) = origin.strip_prefix("http://ftp.") {
let host = rest.split(':').next().unwrap_or(rest);
if looks_like_bare_ipv4(host) {
return Some(format!("ftp://{rest}"));
}
}
// ftp.<IPv4 or bare domain> without a scheme
if let Some(rest) = origin.strip_prefix("ftp.") {
if looks_like_bare_ipv4(rest) {
// ftp.<IP> → ftp://<IP> (strips ftp. prefix; ftp://ftp.<IP> would fail URL parsing)
return Some(format!("ftp://{rest}"));
} else if looks_like_bare_domain(rest) {
// ftp.<domain> → ftp://ftp.<domain>
return Some(format!("ftp://{origin}"));
}
}
// bare domain, IPv4 address, or single-label hostname → moz-pwmngr-fixed://
if looks_like_bare_domain(origin) || looks_like_bare_label(origin) {
return Some(format!("moz-pwmngr-fixed://{origin}"));
}
None
}
}
impl LoginEntry {
pub fn new(fields: LoginFields, sec_fields: SecureLoginFields) -> Self {
Self {
origin: fields.origin,
form_action_origin: fields.form_action_origin,
http_realm: fields.http_realm,
username_field: fields.username_field,
password_field: fields.password_field,
username: sec_fields.username,
password: sec_fields.password,
}
}
/// Shared core logic for origin-like fields: parses `origin` as a URL and
/// normalizes it to origin-only form. Returns `Ok(None)` if the input is
/// already a valid, normalized origin, `Ok(Some(fixed))` if it needed
/// normalization, or `Err` if the input cannot be parsed as a URL.
fn parse_and_normalize_origin(origin: &str) -> Result<Option<String>> {
match Url::parse(origin) {
Ok(mut u) => {
// Presumably this is a faster path than always setting?
if u.path() != "/"
|| u.fragment().is_some()
|| u.query().is_some()
|| u.username() != "/"
|| u.password().is_some()
{
// Not identical - we only want the origin part, so kill
// any other parts which may exist.
// But first special case `file://` URLs which always
// resolve to `file://`
if u.scheme() == "file" {
return Ok(if origin == "file://" {
None
} else {
Some("file://".into())
});
}
u.set_path("");
u.set_fragment(None);
u.set_query(None);
let _ = u.set_username("");
let _ = u.set_password(None);
let mut href = String::from(u);
// We always store without the trailing "/" which Urls have.
if href.ends_with('/') {
href.pop().expect("url must have a length");
}
if origin != href {
// Needs to be fixed up.
return Ok(Some(href));
}
}
Ok(None)
}
Err(e) => {
breadcrumb!(
"Error parsing login origin: {e:?} ({})",
error_support::redact_url(origin)
);
Err(InvalidLogin::IllegalOrigin {
reason: e.to_string(),
}
.into())
}
}
}
/// Validation and fixups for a login `origin`.
///
/// When the `perform_additional_origin_fixups` feature is enabled, some
/// origins that fail URL parsing (bare domains, FireFTP quirks, etc.)
/// are repaired into parseable URLs.
pub fn validate_and_fixup_origin(origin: &str) -> Result<Option<String>> {
match Self::parse_and_normalize_origin(origin) {
Ok(result) => Ok(result),
Err(e) => {
#[cfg(feature = "perform_additional_origin_fixups")]
if let Some(fixed) = origin_fixup::perform_additional_origin_fixup(origin) {
if Url::parse(&fixed).is_ok() {
return Ok(Some(fixed));
}
}
Err(e)
}
}
}
/// Validation and normalizations for a login `form_action_origin`.
///
/// When the `ignore_form_action_origin_validation_errors` feature is
/// enabled, unparseable values are accepted as-is (returning `Ok(None)`
/// so callers keep the original string), allowing non-URL values such
/// as "email" or "UserCode" that exist in some Desktop databases to be
/// saved regardless.
pub fn validate_and_normalize_form_action_origin(
form_action_origin: &str,
) -> Result<Option<String>> {
match Self::parse_and_normalize_origin(form_action_origin) {
Ok(result) => Ok(result),
#[cfg(feature = "ignore_form_action_origin_validation_errors")]
Err(_) => Ok(None),
#[cfg(not(feature = "ignore_form_action_origin_validation_errors"))]
Err(e) => Err(e),
}
}
}
/// A login handed over from the store API, which has been persisted and contains persistence
/// information such as id and time stamps
#[derive(Debug, Clone, Hash, PartialEq, Eq, Default)]
pub struct Login {
// meta fields
pub id: String,
pub time_created: i64,
pub time_password_changed: i64,
pub time_last_used: i64,
pub times_used: i64,
// breach alerts
pub time_last_breach_alert_dismissed: Option<i64>,
// login fields
pub origin: String,
pub form_action_origin: Option<String>,
pub http_realm: Option<String>,
pub username_field: String,
pub password_field: String,
// secure fields
pub username: String,
pub password: String,
}
impl Login {
pub fn new(meta: LoginMeta, fields: LoginFields, sec_fields: SecureLoginFields) -> Self {
Self {
id: meta.id,
time_created: meta.time_created,
time_password_changed: meta.time_password_changed,
time_last_used: meta.time_last_used,
times_used: meta.times_used,
time_last_breach_alert_dismissed: meta.time_last_breach_alert_dismissed,
origin: fields.origin,
form_action_origin: fields.form_action_origin,
http_realm: fields.http_realm,
username_field: fields.username_field,
password_field: fields.password_field,
username: sec_fields.username,
password: sec_fields.password,
}
}
#[inline]
pub fn guid(&self) -> Guid {
Guid::from_string(self.id.clone())
}
pub fn entry(&self) -> LoginEntry {
LoginEntry {
origin: self.origin.clone(),
form_action_origin: self.form_action_origin.clone(),
http_realm: self.http_realm.clone(),
username_field: self.username_field.clone(),
password_field: self.password_field.clone(),
username: self.username.clone(),
password: self.password.clone(),
}
}
pub fn encrypt(self, encdec: &dyn EncryptorDecryptor) -> Result<EncryptedLogin> {
let sec_fields = SecureLoginFields {
username: self.username,
password: self.password,
}
.encrypt(encdec, &self.id)?;
Ok(EncryptedLogin {
meta: LoginMeta {
id: self.id,
time_created: self.time_created,
time_password_changed: self.time_password_changed,
time_last_used: self.time_last_used,
times_used: self.times_used,
time_last_breach_alert_dismissed: self.time_last_breach_alert_dismissed,
},
fields: LoginFields {
origin: self.origin,
form_action_origin: self.form_action_origin,
http_realm: self.http_realm,
username_field: self.username_field,
password_field: self.password_field,
},
sec_fields,
})
}
}
/// A login stored in the database
#[derive(Debug, Clone, Hash, PartialEq, Eq, Default)]
pub struct EncryptedLogin {
pub meta: LoginMeta,
pub fields: LoginFields,
pub sec_fields: String,
}
impl EncryptedLogin {
#[inline]
pub fn guid(&self) -> Guid {
Guid::from_string(self.meta.id.clone())
}
// TODO: Remove this: https://github.com/mozilla/application-services/issues/4185
#[inline]
pub fn guid_str(&self) -> &str {
&self.meta.id
}
pub fn decrypt(self, encdec: &dyn EncryptorDecryptor) -> Result<Login> {
let sec_fields = self.decrypt_fields(encdec)?;
Ok(Login::new(self.meta, self.fields, sec_fields))
}
pub fn decrypt_fields(&self, encdec: &dyn EncryptorDecryptor) -> Result<SecureLoginFields> {
SecureLoginFields::decrypt(&self.sec_fields, encdec, &self.meta.id)
}
pub(crate) fn from_row(row: &Row<'_>) -> Result<EncryptedLogin> {
let login = EncryptedLogin {
meta: LoginMeta {
id: row.get("guid")?,
time_created: row.get("timeCreated")?,
// Might be null
time_last_used: row
.get::<_, Option<i64>>("timeLastUsed")?
.unwrap_or_default(),
time_password_changed: row.get("timePasswordChanged")?,
times_used: row.get("timesUsed")?,
time_last_breach_alert_dismissed: row
.get::<_, Option<i64>>("timeLastBreachAlertDismissed")?,
},
fields: LoginFields {
origin: row.get("origin")?,
http_realm: row.get("httpRealm")?,
form_action_origin: row.get("formActionOrigin")?,
username_field: string_or_default(row, "usernameField")?,
password_field: string_or_default(row, "passwordField")?,
},
sec_fields: row.get("secFields")?,
};
// XXX - we used to perform a fixup here, but that seems heavy-handed
// and difficult - we now only do that on add/insert when we have the
// encryption key.
Ok(login)
}
}
fn string_or_default(row: &Row<'_>, col: &str) -> Result<String> {
Ok(row.get::<_, Option<String>>(col)?.unwrap_or_default())
}
pub trait ValidateAndFixup {
// Our validate and fixup functions.
fn check_valid(&self) -> Result<()>
where
Self: Sized,
{
self.validate_and_fixup(false)?;
Ok(())
}
fn fixup(self) -> Result<Self>
where
Self: Sized,
{
match self.maybe_fixup()? {
None => Ok(self),
Some(login) => Ok(login),
}
}
fn maybe_fixup(&self) -> Result<Option<Self>>
where
Self: Sized,
{
self.validate_and_fixup(true)
}
// validates, and optionally fixes, a struct. If fixup is false and there is a validation
// issue, an `Err` is returned. If fixup is true and a problem was fixed, and `Ok(Some<Self>)`
// is returned with the fixed version. If there was no validation problem, `Ok(None)` is
// returned.
fn validate_and_fixup(&self, fixup: bool) -> Result<Option<Self>>
where
Self: Sized;
}
impl ValidateAndFixup for LoginEntry {
fn validate_and_fixup(&self, fixup: bool) -> Result<Option<Self>> {
// XXX TODO: we've definitely got more validation and fixups to add here!
let mut maybe_fixed = None;
/// A little helper to magic a Some(self.clone()) into existence when needed.
macro_rules! get_fixed_or_throw {
($err:expr) => {
// This is a block expression returning a local variable,
// entirely so we can give it an explicit type declaration.
{
if !fixup {
return Err($err.into());
}
warn!("Fixing login record {:?}", $err);
let fixed: Result<&mut Self> =
Ok(maybe_fixed.get_or_insert_with(|| self.clone()));
fixed
}
};
}
if self.origin.is_empty() {
return Err(InvalidLogin::EmptyOrigin.into());
}
if self.form_action_origin.is_some() && self.http_realm.is_some() {
get_fixed_or_throw!(InvalidLogin::BothTargets)?.http_realm = None;
}
if self.form_action_origin.is_none() && self.http_realm.is_none() {
return Err(InvalidLogin::NoTarget.into());
}
let form_action_origin = self.form_action_origin.clone().unwrap_or_default();
let http_realm = maybe_fixed
.as_ref()
.unwrap_or(self)
.http_realm
.clone()
.unwrap_or_default();
let field_data = [
("form_action_origin", &form_action_origin),
("http_realm", &http_realm),
("origin", &self.origin),
("username_field", &self.username_field),
("password_field", &self.password_field),
];
for (field_name, field_value) in &field_data {
// Nuls are invalid.
if field_value.contains('\0') {
return Err(InvalidLogin::IllegalFieldValue {
field_info: format!("`{}` contains Nul", field_name),
}
.into());
}
// Newlines are invalid in Desktop for all the fields here.
if field_value.contains('\n') || field_value.contains('\r') {
return Err(InvalidLogin::IllegalFieldValue {
field_info: format!("`{}` contains newline", field_name),
}
.into());
}
}
// Desktop doesn't like fields with the below patterns
if self.username_field == "." {
return Err(InvalidLogin::IllegalFieldValue {
field_info: "`username_field` is a period".into(),
}
.into());
}
// Check we can parse the origin, then use the normalized version of it.
if let Some(fixed) = Self::validate_and_fixup_origin(&self.origin)? {
get_fixed_or_throw!(InvalidLogin::IllegalFieldValue {
field_info: "Origin is not normalized".into()
})?
.origin = fixed;
}
match &maybe_fixed.as_ref().unwrap_or(self).form_action_origin {
None => {
if !self.username_field.is_empty() {
get_fixed_or_throw!(InvalidLogin::IllegalFieldValue {
field_info: "username_field must be empty when form_action_origin is null"
.into()
})?
.username_field
.clear();
}
if !self.password_field.is_empty() {
get_fixed_or_throw!(InvalidLogin::IllegalFieldValue {
field_info: "password_field must be empty when form_action_origin is null"
.into()
})?
.password_field
.clear();
}
}
Some(href) => {
// "", ".", and "javascript:" are special cases documented at the top of this file.
if href == "." {
// A bit of a special case - if we are being asked to fixup, we replace
// "." with an empty string - but if not fixing up we don't complain.
if fixup {
maybe_fixed
.get_or_insert_with(|| self.clone())
.form_action_origin = Some("".into());
}
} else if !href.is_empty() && href != "javascript:" {
match Self::validate_and_normalize_form_action_origin(href) {
Ok(Some(fixed)) => {
get_fixed_or_throw!(InvalidLogin::IllegalFieldValue {
field_info: "form_action_origin is not normalized".into()
})?
.form_action_origin = Some(fixed);
}
Ok(None) => {}
Err(e) => return Err(e),
}
}
}
}
// secure fields
//
// \r\n chars are valid in desktop for some reason, so we allow them here too.
if self.username.contains('\0') {
return Err(InvalidLogin::IllegalFieldValue {
field_info: "`username` contains Nul".into(),
}
.into());
}
// The `allow_empty_passwords` feature flag is used on desktop during the migration phase
// to allow existing logins with empty passwords to be imported.
#[cfg(not(feature = "allow_empty_passwords"))]
if self.password.is_empty() {
return Err(InvalidLogin::EmptyPassword.into());
}
if self.password.contains('\0') {
return Err(InvalidLogin::IllegalFieldValue {
field_info: "`password` contains Nul".into(),
}
.into());
}
Ok(maybe_fixed)
}
}
#[cfg(test)]
pub mod test_utils {
use super::*;
use crate::encryption::test_utils::encrypt_struct;
// Factory function to make a new login
//
// It uses the guid to create a unique origin/form_action_origin
pub fn enc_login(id: &str, password: &str) -> EncryptedLogin {
let sec_fields = SecureLoginFields {
username: "user".to_string(),
password: password.to_string(),
};
EncryptedLogin {
meta: LoginMeta {
id: id.to_string(),
..Default::default()
},
fields: LoginFields {
form_action_origin: Some(format!("https://{}.example.com", id)),
origin: format!("https://{}.example.com", id),
..Default::default()
},
// TODO: fixme
sec_fields: encrypt_struct(&sec_fields),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_url_fixups() -> Result<()> {
// Start with URLs which are all valid and already normalized.
for input in &[
// The list of valid origins documented at the top of this file.
"https://site.com",
"http://site.com:1234",
"ftp://ftp.site.com",
"moz-proxy://127.0.0.1:8888",
"chrome://MyLegacyExtension",
"file://",
"https://[::1]",
] {
assert_eq!(LoginEntry::validate_and_fixup_origin(input)?, None);
}
// And URLs which get normalized.
for (input, output) in &[
("https://site.com/", "https://site.com"),
("http://site.com:1234/", "http://site.com:1234"),
("http://example.com/foo?query=wtf#bar", "http://example.com"),
("http://example.com/foo#bar", "http://example.com"),
(
"http://username:password@example.com/",
"http://example.com",
),
("http://😍.com/", "http://xn--r28h.com"),
("https://[0:0:0:0:0:0:0:1]", "https://[::1]"),
// All `file://` URLs normalize to exactly `file://`. See #2384 for
// why we might consider changing that later.
("file:///", "file://"),
("file://foo/bar", "file://"),
("file://foo/bar/", "file://"),
("moz-proxy://127.0.0.1:8888/", "moz-proxy://127.0.0.1:8888"),
(
"moz-proxy://127.0.0.1:8888/foo",
"moz-proxy://127.0.0.1:8888",
),
("chrome://MyLegacyExtension/", "chrome://MyLegacyExtension"),
(
"chrome://MyLegacyExtension/foo",
"chrome://MyLegacyExtension",
),
] {
assert_eq!(
LoginEntry::validate_and_fixup_origin(input)?,
Some((*output).into())
);
}
// Finally, look at some invalid logins
{