-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathcontent_script.js
960 lines (849 loc) · 31 KB
/
content_script.js
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
/**
* @license
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Receives keyboard events and sends keyboard events to
* background.js via sendMessage.
* @author [email protected] (Drew Hintz)
*/
'use strict';
goog.module('passwordalert.content_script');
const GoogFormatEmailAddress = goog.require('goog.format.EmailAddress');
const googString = goog.require('goog.string');
const googUriUtils = goog.require('goog.uri.utils');
let passwordalert = {};
goog.exportSymbol('passwordalert', passwordalert); // for tests only.
/**
* URL prefix for the SSO/login page.
* @private {string}
*/
passwordalert.sso_url_;
/**
* Selector for the form element on the SSO login page.
* @private {string}
*/
passwordalert.sso_form_selector_;
/**
* Selector for the password input element on the SSO login page.
* @private {string}
*/
passwordalert.sso_password_selector_;
/**
* Selector for the username input element on the SSO login page.
* @private {string}
*/
passwordalert.sso_username_selector_;
/**
* The corp email domain, e.g. "company.com".
* Can also be a list of domains, such as "1.example.com,2.example.com".
* @private {string}
*/
passwordalert.corp_email_domain_;
/**
* URL prefix for the GAIA login page.
* @private {string}
* @const
*/
passwordalert.GAIA_URL_ = 'https://accounts.google.com/';
// TODO(adhintz) See if /SecondFactor and /b/0/VerifiedPhoneInterstitial URLs
// are still used and if not, then delete them.
/**
* URL prefixes under GAIA_URL_ that indicate a correct password.
* @private {!Array.<string>}
* @const
*/
passwordalert.GAIA_CORRECT_ = [
'https://accounts.google.com/SecondFactor',
'https://accounts.google.com/b/0/VerifiedPhoneInterstitial',
'https://accounts.google.com/signin/newfeatures',
'https://accounts.google.com/signin/selectchallenge',
'https://accounts.google.com/signin/challenge',
'https://accounts.google.com/signin/privacyreminder',
'https://accounts.google.com/signin/v2/challenge/ipp'
];
/**
* URL prefixes under GAIA_URL_ that indicate a *not* correct password.
* We only need entries that are within GAIA_CORRECT_ prefixes.
* @private {!Array.<string>}
* @const
*/
passwordalert.GAIA_INCORRECT_ = [
'https://accounts.google.com/signin/challenge/sl/password',
'https://accounts.google.com/signin/challenge/pwd/1'
];
/**
* URL prefix for changing GAIA password.
* @private {string}
* @const
*/
passwordalert.CHANGE_PASSWORD_URL_ =
'https://myaccount.google.com/signinoptions/password';
/**
* URL prefix for enforced changing GAIA password.
* @private {string}
* @const
*/
passwordalert.ENFORCED_CHANGE_PASSWORD_URL_ =
'https://accounts.google.com/speedbump/changepassword';
/**
* YouTube check connection page.
* @private {string}
* @const
*/
passwordalert.YOUTUBE_CHECK_URL_ =
'https://accounts.youtube.com/accounts/CheckConnection';
/**
* Namespace for chrome's managed storage.
* @private {string}
* @const
*/
passwordalert.MANAGED_STORAGE_NAMESPACE_ = 'managed';
/**
* HTML snippets from corp login pages. Default values are for consumers.
* @private {!Array.<string>}
*/
passwordalert.corp_html_ = [
'One account. All of Google.', 'Sign in with your Google Account',
'<title>Sign in - Google Accounts',
'//ssl.gstatic.com/accounts/ui/logo_2x.png'
];
/**
* HTML snippets from corp login pages that are more specific. Default
* values are for consumers.
* @private {!Array.<string>}
*/
passwordalert.corp_html_tight_ = [
// From https://accounts.google.com/ServiceLogin
('<input id="Passwd" name="Passwd" placeholder="Password" class="" ' +
'type="password">'),
('<input id="Passwd" name="Passwd" type="password" placeholder="Password" ' +
'class="">'),
'<input id="signIn" name="signIn" class="rc-button rc-button-submit" ',
// From https://accounts.google.com/b/0/EditPasswd?hl=en
'<div class="editpasswdpage main content clearfix">'
];
/**
* If the current page looks like corp_html_. undefined means not checked yet.
* @private {boolean}
*/
passwordalert.looks_like_google;
/**
* Email address of the security admin.
* @private {string}
*/
passwordalert.security_email_address_;
/**
* Allowlist of domain suffixes that are not phishing or checked for password.
* Default values are for Google login pages. https is not specified, however
* these default domains are preloaded HSTS in Chrome.
* @private {!Array.<string>}
*/
passwordalert.allowlist_top_domains_ =
['accounts.google.com', 'login.corp.google.com', 'myaccount.google.com'];
/**
* List of domains which may generate an alert as 'report_only'
* @private {!Array.<string>}
*/
passwordalert.report_only_domains_ = [];
/**
* If Password Alert is running on the current page.
* @private {boolean}
*/
passwordalert.isRunning_ = false;
/**
* Is password alert used in enterprise environment. If false, then it's
* used by individual consumer.
* @private {boolean}
*/
passwordalert.enterpriseMode_ = false;
/**
* Indicates that the managed policy has been set. Required to complete init.
* @private {boolean}
*/
passwordalert.policyLoaded_ = false;
/**
* Indicates the DOM has been loaded. Required to complete initialization.
* @private {boolean}
*/
passwordalert.domContentLoaded_ = false;
/**
* Key for the allowed hosts object in chrome storage.
* @private {string}
* @const
*/
passwordalert.ALLOWED_HOSTS_KEY_ = 'allowed_hosts';
/**
* Set the managed policy values into the configurable variables.
* @param {function()} callback Executed after policy values have been set.
* @private
*/
passwordalert.setManagedPolicyValuesIntoConfigurableVariables_ = function(
callback) {
chrome.storage.managed.get(function(managedPolicy) {
if (Object.keys(managedPolicy).length == 0) {
passwordalert.enterpriseMode_ = false;
} else {
passwordalert.enterpriseMode_ = true;
passwordalert.corp_email_domain_ =
managedPolicy['corp_email_domain'].replace(/@/g, '').toLowerCase();
passwordalert.security_email_address_ =
managedPolicy['security_email_address'];
passwordalert.sso_form_selector_ = managedPolicy['sso_form_selector'];
passwordalert.sso_password_selector_ =
managedPolicy['sso_password_selector'];
passwordalert.sso_url_ = managedPolicy['sso_url'];
passwordalert.sso_username_selector_ =
managedPolicy['sso_username_selector'];
// For the policies below, we want to append the user-provided policies
// to the extension-provided defaults.
if (managedPolicy['allowlist_top_domains']) {
Array.prototype.push.apply(
passwordalert.allowlist_top_domains_,
// filter empty values
managedPolicy['allowlist_top_domains'].filter(String));
}
// Included for backwards compatibility.
// The intention is to give a warning period then to remove this value.
if (managedPolicy['whitelist_top_domains']) {
console.debug("[Password Alert] The managed policy value 'whitelist_top_domains' is deprecated. Please move to 'allowlist_top_domains' immediately.");
Array.prototype.push.apply(
passwordalert.allowlist_top_domains_,
// filter empty values
managedPolicy['whitelist_top_domains'].filter(String));
}
if (managedPolicy['corp_html']) {
Array.prototype.push.apply(
passwordalert.corp_html_, managedPolicy['corp_html']);
}
if (managedPolicy['corp_html_tight']) {
Array.prototype.push.apply(
passwordalert.corp_html_tight_, managedPolicy['corp_html_tight']);
}
if (managedPolicy['report_only_domains']) {
Array.prototype.push.apply(
passwordalert.report_only_domains_,
managedPolicy['report_only_domains'].filter(String));
}
}
passwordalert.policyLoaded_ = true;
callback();
});
};
// This switch style is a bit verbose with lots of properties. Perhaps it
// would be cleaner to have a list of allowed properties and do something like
// if (changedPolicy in listOfPolicies)
// passwordalert[changedPolicy + '_'] = newPolicyValue;
/**
* Handle managed policy changes by updating the configurable variables.
* @param {!Object} changedPolicies Object mapping each policy to its
* new values. Policies that have not changed will not be present.
* For example:
* {
* report_url: {
* newValue: "https://passwordalert222.example.com/report/"
* oldValue: "https://passwordalert111.example.com/report/"
* }
* }
* @param {string} storageNamespace The name of the storage area
* ("sync", "local" or "managed") the changes are for.
* @private
*/
passwordalert.handleManagedPolicyChanges_ = function(
changedPolicies, storageNamespace) {
if (storageNamespace == passwordalert.MANAGED_STORAGE_NAMESPACE_) {
const subtractArray = function(currentPolicyArray, oldPolicyArray) {
return currentPolicyArray.filter(function(val) {
return oldPolicyArray.indexOf(val) < 0;
});
};
let changedPolicy;
for (changedPolicy in changedPolicies) {
if (!passwordalert.enterpriseMode_) {
passwordalert.enterpriseMode_ = true;
}
const newPolicyValue = changedPolicies[changedPolicy]['newValue'];
const oldPolicyValue = changedPolicies[changedPolicy]['oldValue'];
switch (changedPolicy) {
case 'corp_email_domain':
passwordalert.corp_email_domain_ =
newPolicyValue.replace(/@/g, '').toLowerCase();
break;
case 'corp_html':
// Remove the old values before appending new ones.
passwordalert.corp_html_ =
subtractArray(passwordalert.corp_html_, oldPolicyValue);
Array.prototype.push.apply(passwordalert.corp_html_, newPolicyValue);
break;
case 'corp_html_tight':
passwordalert.corp_html_tight_ =
subtractArray(passwordalert.corp_html_tight_, oldPolicyValue);
Array.prototype.push.apply(
passwordalert.corp_html_tight_, newPolicyValue);
break;
case 'security_email_address':
passwordalert.security_email_address_ = newPolicyValue;
break;
case 'sso_form_selector':
passwordalert.sso_form_selector_ = newPolicyValue;
break;
case 'sso_password_selector':
passwordalert.sso_password_selector_ = newPolicyValue;
break;
case 'sso_url':
passwordalert.sso_url_ = newPolicyValue;
break;
case 'sso_username_selector':
passwordalert.sso_username_selector_ = newPolicyValue;
break;
case 'allowlist_top_domains':
passwordalert.allowlist_top_domains_ = subtractArray(
passwordalert.allowlist_top_domains_,
oldPolicyValue.filter(String)); // filter empty values
Array.prototype.push.apply(
passwordalert.allowlist_top_domains_,
newPolicyValue.filter(String)); // filter empty values
break;
case 'whitelist_top_domains':
passwordalert.allowlist_top_domains_ = subtractArray(
passwordalert.allowlist_top_domains_,
oldPolicyValue.filter(String)); // filter empty values
Array.prototype.push.apply(
passwordalert.allowlist_top_domains_,
newPolicyValue.filter(String)); // filter empty values
break;
case 'report_only_domains':
passwordalert.report_only_domains_ = subtractArray(passwordalert.report_only_domains_, oldPolicyValue.filter(String));
Array.prototype.push.apply(
passwordalert.report_only_domains_,
newPolicyValue.filter(String));
break;
}
}
}
};
/**
* Complete page initialization. This is executed after managed policy values
* have been set.
*
* Save or delete any existing passwords. Listen for form submissions on
* corporate login pages.
* @private
*/
passwordalert.completePageInitializationIfReady_ = function() {
if (!passwordalert.policyLoaded_ || !passwordalert.domContentLoaded_) {
return;
}
// Ignore YouTube login CheckConnection because the login page makes requests
// to it, but that does not mean the user has successfully authenticated.
if (googString.startsWith(
passwordalert.url_(), passwordalert.YOUTUBE_CHECK_URL_)) {
return;
}
if (passwordalert.sso_url_ &&
googString.startsWith(passwordalert.url_(), passwordalert.sso_url_)) {
const loginForm = document.querySelector(passwordalert.sso_form_selector_);
if (loginForm) { // null if the user gets a Password Change Warning.
loginForm.addEventListener(
'submit', passwordalert.saveSsoPassword_, true);
} else {
// This handles the case where user is redirected to a page that starts
// with sso url upon a successful sso login.
chrome.runtime.sendMessage({action: 'savePossiblePassword', context: 'sso_url_ without login form', url: passwordalert.url_()});
}
} else if (googString.startsWith(
passwordalert.url_(),
passwordalert.ENFORCED_CHANGE_PASSWORD_URL_)) {
// This change password page does not have any email information.
// So we fallback to the email already set in service_worker.js because users
// will be prompted to login before arriving here.
const changePasswordForm =
document.getElementById('gaia_changepasswordform');
changePasswordForm.addEventListener('submit', function() {
chrome.runtime.sendMessage({
action: 'setPossiblePasswordWithoutEmail',
password: changePasswordForm.Passwd.value,
context: 'change password',
url: passwordalert.url_()
});
}, true);
} else if (googString.startsWith(
passwordalert.url_(), passwordalert.GAIA_URL_)) {
if (passwordalert.is_gaia_correct_(passwordalert.url_())) {
chrome.runtime.sendMessage({action: 'savePossiblePassword', context: 'gaia correct', url: passwordalert.url_()});
} else {
const loginForm = document.querySelector('#view_container > form');
// The chooser is no longer a gaia_loginform, so verify we're on a
// password entry page by finding a form in a view_container.
if (loginForm && document.getElementById('Email')) {
loginForm.addEventListener(
'submit', passwordalert.saveGaiaPassword_, true);
} else if (
document.getElementById('hiddenEmail') &&
document.getElementsByName('Passwd')) {
window.onbeforeunload = passwordalert.saveGaia2Password_;
}
}
} else if (googString.startsWith(
passwordalert.url_(), passwordalert.CHANGE_PASSWORD_URL_)) {
// Need to wait until the change password page has finished loading
// before listener can be added.
window.onload = function() {
const allButtons = document.querySelectorAll('div[role=button]');
const changePasswordButton = allButtons[allButtons.length - 1];
changePasswordButton.addEventListener(
'click', passwordalert.saveChangedPassword_, true);
// Pressing spacebar on the change password button will trigger save.
changePasswordButton.addEventListener('keydown', function(evt) {
if (evt.key == 'Space') {
passwordalert.saveChangedPassword_();
}
}, true);
// Pressing enter anywhere on the change password page will trigger save.
document.addEventListener('keydown', function(evt) {
if (evt.key == 'Enter') {
passwordalert.saveChangedPassword_();
}
}, true);
};
} else { // Not a Google login URL.
if (!passwordalert.allowlistUrl_() &&
passwordalert.looksLikeGooglePageTight_()) {
chrome.runtime.sendMessage({
action: 'looksLikeGoogle',
url: passwordalert.url_(),
referer: passwordalert.referrer_(),
securityEmailAddress: passwordalert.security_email_address_,
context: 'possible phish'
});
}
chrome.runtime.sendMessage({action: 'savePossiblePassword', context: 'default', url: passwordalert.url_()}, _ => {
if(chrome.runtime.lastError){
console.debug('[Password Alert] completePageInitializationIfReady_ ', chrome.runtime.lastError);
}
});
}
chrome.runtime.sendMessage({action: 'statusRequest', context: 'default', url: passwordalert.url_()}, function(response) {
passwordalert.stop_();
passwordalert.start_(response);
});
};
/**
* Returns true if the URL indicates that the password is correct.
* @param {string} url The page's URL.
* @return {boolean} True if the URL indicates the password is correct.
* @private
*/
passwordalert.is_gaia_correct_ = function(url) {
let ret = false;
passwordalert.GAIA_CORRECT_.forEach(function(prefix) {
if (googString.startsWith(url, prefix)) {
ret = true;
}
});
if (ret) { // Filter out exceptions which indicate password is not correct.
passwordalert.GAIA_INCORRECT_.forEach(function(prefix) {
if (googString.startsWith(url, prefix)) {
ret = false;
}
});
}
return ret;
};
/**
* Sets variables to enable watching for passwords being typed. Called when
* a message from the options_subscriber arrives.
* @param {string} msg JSON object containing password lengths and OTP mode.
* @private
*/
passwordalert.start_ = function(msg) {
try {
const state = JSON.parse(msg);
if (!state['passwordStored']) {
passwordalert.stop_(); // no passwords, so no need to watch
return;
}
} catch (e) {
} // Silently swallow any parser errors.
if ((passwordalert.sso_url_ &&
googString.startsWith(passwordalert.url_(), passwordalert.sso_url_)) ||
googString.startsWith(passwordalert.url_(), passwordalert.GAIA_URL_) ||
passwordalert.allowlistUrl_()) {
passwordalert.stop_(); // safe URL, so no need to watch it
return;
}
passwordalert.isRunning_ = true;
// If the current site is marked as Always Ignore, then passwordalert.stop_().
if (!passwordalert.enterpriseMode_) {
chrome.storage.local.get(
passwordalert.ALLOWED_HOSTS_KEY_, function(allowedHosts) {
const currentHost = window.location.origin;
if (Object.keys(allowedHosts).length > 0 &&
allowedHosts[passwordalert.ALLOWED_HOSTS_KEY_][currentHost]) {
passwordalert.stop_();
}
});
}
passwordalert.looksLikeGooglePage_(); // Run here so that it's cached.
};
/**
* Disables watching on the current page.
* @private
*/
passwordalert.stop_ = function() {
passwordalert.isRunning_ = false;
};
/**
* Called on each key press. Checks the most recent possible characters.
* @param {!Event} evt Key press event.
* @export
*/
passwordalert.handleKeypress = function(evt) {
if (!passwordalert.isRunning_) return;
if (!evt.isTrusted) return; // Verify event generated by a user.
chrome.runtime.sendMessage({
action: 'handleKeypress',
keyCode: evt.charCode,
typedTimeStamp: evt.timeStamp,
url: passwordalert.url_(),
referer: passwordalert.referrer_(),
looksLikeGoogle: passwordalert.looksLikeGooglePage_(),
context: 'key press handler'
});
};
/**
* Called on each key down. Checks the most recent possible characters.
* @param {!Event} evt Key down event.
* @export
*/
passwordalert.handleKeydown = function(evt) {
if (!passwordalert.isRunning_) return;
if (!evt.isTrusted) return; // Verify event generated by a user.
chrome.runtime.sendMessage({
action: 'handleKeydown',
keyCode: evt.keyCode,
shiftKey: evt.shiftKey,
typedTimeStamp: evt.timeStamp,
url: passwordalert.url_(),
referer: passwordalert.referrer_(),
looksLikeGoogle: passwordalert.looksLikeGooglePage_(),
context: 'key down handler'
});
};
/**
* Called on each paste. Checks the entire pasted string to save on cpu cycles.
* @param {!Event} evt Paste event.
* @export
*/
passwordalert.handlePaste = function(evt) {
if (!passwordalert.isRunning_) return;
if (!evt.isTrusted) return; // Verify event generated by a user.
chrome.runtime.sendMessage({
action: 'checkString',
password: evt.clipboardData.getData('text/plain').trim(),
url: passwordalert.url_(),
referer: passwordalert.referrer_(),
looksLikeGoogle: passwordalert.looksLikeGooglePage_(),
context: 'paste handler'
});
};
/**
* Called when SSO login page is submitted. Sends possible password to
* background.js.
* @param {!Event} evt Form submit event that triggered this. Not used.
* @private
*/
passwordalert.saveSsoPassword_ = function(evt) {
if (passwordalert.validateSso_()) {
let username =
document.querySelector(passwordalert.sso_username_selector_).value;
const password =
document.querySelector(passwordalert.sso_password_selector_).value;
if (username.indexOf('@') == -1) {
username += '@' + passwordalert.corp_email_domain_.split(',')[0].trim();
}
chrome.runtime.sendMessage(
{action: 'setPossiblePassword', email: username, password: password, context: 'set password from sso', url: passwordalert.url_()});
}
};
// TODO(adhintz) See if the old GAIA login page is used any where.
// If not, delete this function.
/**
* Called when the GAIA page is submitted. Sends possible
* password to background.js.
* @param {!Event} evt Form submit event that triggered this. Not used.
* @private
*/
passwordalert.saveGaiaPassword_ = function(evt) {
const loginForm = document.getElementById('gaia_loginform');
const email = loginForm.Email ?
googString.trim(loginForm.Email.value.toLowerCase()) :
'';
const password = loginForm.Passwd ? loginForm.Passwd.value : '';
if ((passwordalert.enterpriseMode_ &&
!passwordalert.isEmailInDomain_(email)) ||
googString.isEmptyString(googString.makeSafe(password))) {
return; // Ignore generic @gmail.com logins or for other domains.
}
chrome.runtime.sendMessage(
{action: 'setPossiblePassword', email: email, password: password, context: 'set password from gaia', url: passwordalert.url_()});
};
/**
* Called when the new GAIA page is unloaded. Sends possible
* password to background.js.
* @param {?Event} evt BeforeUnloadEvent that triggered this. Not used.
* @private
*/
passwordalert.saveGaia2Password_ = function(evt) {
const emailInput = document.getElementById('hiddenEmail');
const email =
emailInput ? googString.trim(emailInput.value.toLowerCase()) : '';
const passwordInputs = document.getElementsByName('Passwd');
if (!passwordInputs || passwordInputs.length != 1) {
return;
}
const password = passwordInputs[0].value;
if (!email || !password) {
return;
}
if ((passwordalert.enterpriseMode_ &&
!passwordalert.isEmailInDomain_(email)) ||
googString.isEmptyString(googString.makeSafe(password))) {
return; // Ignore generic @gmail.com logins or for other domains.
}
chrome.runtime.sendMessage(
{action: 'setPossiblePassword', email: email, password: password, context: 'set password from gaia 2', url: passwordalert.url_()});
};
/**
* Called when GAIA password is changed. Sends possible password to
* background.js.
* @private
*/
passwordalert.saveChangedPassword_ = function() {
// To ensure that only a valid password is saved, wait and see if we
// navigate away from the change password page. If we stay on the
// same page, then the password is not valid and should not be saved.
const passwordChangeStartTime = Date.now();
window.onbeforeunload = function() {
if ((Date.now() - passwordChangeStartTime) > 1000) {
return;
}
const dataConfig =
document.querySelector('div[data-config]').getAttribute('data-config');
const start = dataConfig.indexOf('",["') + 4;
const end = dataConfig.indexOf('"', start);
const email = dataConfig.substring(start, end);
if (GoogFormatEmailAddress.isValidAddress(email)) {
chrome.runtime.sendMessage({
action: 'setPossiblePassword',
email: email,
password:
document.querySelector('input[aria-label="New password"]').value,
context: 'set changed gaia password',
url: passwordalert.url_()
});
return;
}
console.debug('[Password Alert] Parsed email on change password page is not valid: %s', email);
};
};
/**
* Checks if the email address is for an enterprise mode configured domain.
* @param {string} email Email address to check.
* @return {boolean} True if email address is for a configured corporate domain.
* @private
*/
passwordalert.isEmailInDomain_ = function(email) {
const domains = passwordalert.corp_email_domain_.split(',');
for (let i = 0; i < domains.length; i++) {
if (googString.endsWith(email, '@' + domains[i].trim())) {
return true;
}
}
return false;
};
/**
* Checks if the sso login page is filled in.
* @return {boolean} Whether the sso login page is filled in.
* @private
*/
passwordalert.validateSso_ = function() {
const username = document.querySelector(passwordalert.sso_username_selector_);
const password = document.querySelector(passwordalert.sso_password_selector_);
if ((username && !username.value) || (password && !password.value)) {
console.debug('[Password Alert] SSO data is not filled in.');
return false;
}
return true;
};
/**
* Detects if this page looks like a Google login page.
* For example, a phishing page would return true.
* Cached so it only runs once per content_script load.
* @return {boolean} True if this page looks like a Google login page.
* @private
*/
passwordalert.looksLikeGooglePage_ = function() {
if (passwordalert.looks_like_google_ == true ||
passwordalert.looks_like_google_ == false) {
return passwordalert.looks_like_google_;
}
const allHtml = document.documentElement.innerHTML.slice(0, 120000);
for (let i = 0; i < passwordalert.corp_html_.length; i++) {
if (allHtml.indexOf(passwordalert.corp_html_[i]) >= 0) {
passwordalert.looks_like_google_ = true;
return true;
}
}
passwordalert.looks_like_google_ = false;
return false;
};
/**
* Detects if this page looks like a Google login page, but with a more
* strict set of rules to reduce false positives.
* For example, a phishing page would return true.
* @return {boolean} True if this page looks like a Google login page.
* @private
*/
passwordalert.looksLikeGooglePageTight_ = function() {
// Only look in the first 120,000 characters of a page to avoid
// impacting performance for large pages. Although an attacker could use this
// to avoid detection, they could obfuscate the HTML just as easily.
const allHtml = document.documentElement.innerHTML.slice(0, 120000);
for (let i = 0; i < passwordalert.corp_html_tight_.length; i++) {
if (allHtml.indexOf(passwordalert.corp_html_tight_[i]) >= 0) {
return true;
}
}
return false;
};
/**
* Check if the current tab is in the supplied list of domains.
*
* @param {!Array<string>} domains List of domains to check.
* @return {boolean} True if this page is in domain list.
* @private
*/
passwordalert.isTabInDomains_ = function(domains) {
const tab_domain = googUriUtils.getDomain(passwordalert.url_()) || '';
for (let i = 0; i < domains.length; i++) {
const domain = domains[i];
if (domain == tab_domain) {
return true;
}
let domain_as_suffix = domain;
if (!googString.startsWith(domain_as_suffix, '.')) {
domain_as_suffix = '.' + domain_as_suffix;
}
if (googString.endsWith(tab_domain, domain_as_suffix)) {
return true;
}
}
return false;
};
/**
* Detects if the page is allowlisted as not a phishing page or for password
* typing.
*
* Make sure if user allowlists example.com, then evilexample.com
* will not pass the allowlist.
*
* @return {boolean} True if this page is allowlisted.
* @private
*/
passwordalert.allowlistUrl_ = function() {
return passwordalert.isTabInDomains_(passwordalert.allowlist_top_domains_);
};
/**
* Check if the current tab is a report only url.
*
* @return {boolean} True if the domain is a report only URL.
* @private
*/
passwordalert.reportOnlyUrl_ = function() {
return passwordalert.isTabInDomains_(passwordalert.report_only_domains_);
};
/**
* Called when the DOM has loaded. Sets up observers the dynamic login page.
*
* @private
*/
passwordalert.domReadyCheck_ = function() {
passwordalert.domContentLoaded_ = true;
if ((googString.startsWith(passwordalert.url_(), passwordalert.GAIA_URL_)) ||
(passwordalert.sso_url_ &&
googString.startsWith(passwordalert.url_(), passwordalert.sso_url_))) {
const config =
{attributes: true, subtree: true, childList: true, characterData: true};
const observer =
new MutationObserver(passwordalert.completePageInitializationIfReady_);
observer.observe(document.body, config);
}
passwordalert.completePageInitializationIfReady_();
};
/**
* Called to get the url of the current page
*
* If we're in an iframe get the parent's href.
* @return {string} The url of the current page.
* @private
*/
passwordalert.url_ = function() {
const url = location.href.toString();
if (url == 'about:blank') {
return window.parent.location.href;
} else {
return url;
}
};
/**
* Called to get the referrer of the current page
*
* If we're in an iframe return nothing.
* @return {string} The referrer if any.
* @private
*/
passwordalert.referrer_ = function() {
const url = location.href.toString();
if (url == 'about:blank') {
return '';
} else {
return document.referrer.toString();
}
};
// Listen for policy changes and then set initial managed policy:
chrome.storage.onChanged.addListener(passwordalert.handleManagedPolicyChanges_);
passwordalert.setManagedPolicyValuesIntoConfigurableVariables_(
passwordalert.completePageInitializationIfReady_);
window.addEventListener('keypress', passwordalert.handleKeypress, true);
window.addEventListener('keydown', passwordalert.handleKeydown, true);
window.addEventListener('paste', passwordalert.handlePaste, true);
chrome.runtime.onMessage.addListener(
/**
* @param {string} msg JSON object containing valid password lengths.
* @param {!MessageSender} unusedSender the unused sender
* @param {function(string)} sendResponse The function which sends the response
*/
function(msg, unusedSender, sendResponse) {
passwordalert.stop_();
passwordalert.start_(msg);
sendResponse("ok");
});
document.addEventListener('DOMContentLoaded', passwordalert.domReadyCheck_);
// Check to see if we already missed DOMContentLoaded:
if (document.readyState == 'interactive' || document.readyState == 'complete' ||
document.readyState == 'loaded') {
passwordalert.domReadyCheck_();
}