Debian Codegraph @

firefox-passwords

raw
1 #! /usr/bin/perl
2
3 use strict;
4 use warnings;
5 use Getopt::Long();
6 use English qw( -no_match_vars );
7 use Firefox::Marionette();
8 use Firefox::Marionette::Profile();
9 use Text::CSV_XS();
10 use File::Temp();
11 use FileHandle();
12 use POSIX();
13 use XML::Parser();
14 use Term::ReadKey();
15 use charnames ':full';
16
17 our $VERSION = '1.70';
18
19 sub _NUMBER_OF_BYTES_FOR_ZIP_MAGIC_NUMBER { return 4 }
20
21 MAIN: {
22 my %options;
23 Getopt::Long::GetOptions(
24 \%options, 'help',
25 'version', 'binary:s',
26 'import:s', 'export:s',
27 'only-host-regex:s', 'only-user:s',
28 'visible', 'debug',
29 'console', 'profile-name:s',
30 'password', 'list-profile-names',
31 'check-only',
32 );
33 my %parameters = _check_options(%options);
34 my @logins;
35 if ( defined $options{'list-profile-names'} ) {
36 foreach my $name ( Firefox::Marionette::Profile->names() ) {
37 print "$name\n"
38 or die "Failed to print to STDOUT:$EXTENDED_OS_ERROR\n";
39 }
40 exit 0;
41 }
42 elsif ( defined $options{import} ) {
43 @logins = _handle_import(%options);
44 if ( $options{'check-only'} ) {
45 exit 0;
46 }
47 }
48 elsif ( !$options{export} ) {
49 $options{export} = q[];
50 }
51 my $firefox = Firefox::Marionette->new(%parameters);
52 if ( $firefox->pwd_mgr_needs_login() ) {
53 my $prompt =
54 'Firefox requires the primary password to unlock Password Manager from '
55 . ( $parameters{profile_copied_from} || $parameters{profile_name} )
56 . q[: ];
57 print "$prompt" or die "Failed to print to STDOUT:$EXTENDED_OS_ERROR\n";
58 Term::ReadKey::ReadMode(2); # noecho
59 my $password;
60 my $key = q[];
61 while ( $key ne "\n" ) {
62 $password .= $key;
63 $key = Term::ReadKey::ReadKey(0);
64 }
65 Term::ReadKey::ReadMode(0); # restore
66 print "\n" or die "Failed to print to STDOUT:$EXTENDED_OS_ERROR\n";
67 eval { $firefox->pwd_mgr_login($password); } or do {
68 chomp $EVAL_ERROR;
69 die "$EVAL_ERROR\n";
70 };
71 }
72 if (@logins) {
73 _add_or_modify_logins( $firefox, @logins );
74 }
75 if ( defined $options{export} ) {
76 my $export_handle;
77 if ( $options{export} ) {
78 open $export_handle, '>', $options{export}
79 or die "Failed to open $options{export}:$EXTENDED_OS_ERROR\n";
80 }
81 else {
82 $options{export} = 'STDOUT';
83 $export_handle = *{STDOUT};
84 }
85 _export_logins( $firefox, $export_handle, %options );
86 if ( $options{export} ne 'STDOUT' ) {
87 close $export_handle
88 or die "Failed to close $options{export}:$EXTENDED_OS_ERROR\n";
89 }
90 }
91 $firefox->quit();
92 }
93
94 sub _add_or_modify_logins {
95 my ( $firefox, @logins ) = @_;
96 my %form_auth_exists;
97 my %http_auth_exists;
98 foreach my $existing ( $firefox->logins() ) {
99 if ( $existing->realm() ) {
100 $http_auth_exists{ $existing->host() }{ $existing->realm() }
101 { $existing->user() } = $existing;
102 }
103 else {
104 $form_auth_exists{ $existing->host() }{ $existing->user() } =
105 $existing;
106 }
107 }
108 foreach my $login (@logins) {
109 if ( $login->realm() ) {
110 if ( my $existing =
111 $http_auth_exists{ $login->host() }{ $login->realm() }
112 { $login->user() } )
113 {
114 $firefox->delete_login($existing);
115 }
116 }
117 else {
118 if ( my $existing =
119 $form_auth_exists{ $login->host() }{ $login->user() } )
120 {
121 $firefox->delete_login($existing);
122 }
123 }
124 $firefox->add_login($login);
125 }
126 return;
127 }
128
129 sub _read_stdin_into_temp_file {
130 my $import_handle = File::Temp::tempfile(
131 File::Spec->catfile(
132 File::Spec->tmpdir(), 'firefox_password_import_stdin_XXXXXXXXXXX'
133 )
134 ) or die "Failed to open temporary file for writing:$EXTENDED_OS_ERROR\n";
135 while ( my $line = <> ) {
136 $import_handle->print($line)
137 or die "Failed to write to temporary file:$EXTENDED_OS_ERROR\n";
138 }
139 seek $import_handle, Fcntl::SEEK_SET(), 0
140 or die "Failed to seek to start of file:$EXTENDED_OS_ERROR\n";
141 return $import_handle;
142 }
143
144 sub _handle_import {
145 my (%options) = @_;
146 my @logins;
147 my $import_handle;
148 if ( $options{import} ) {
149 open $import_handle, '<', $options{import}
150 or die "Failed to open '$options{import}':$EXTENDED_OS_ERROR\n";
151 }
152 else {
153 $options{import} = 'STDIN';
154 $import_handle = _read_stdin_into_temp_file();
155 }
156 @logins = _read_logins($import_handle);
157 if ( $options{import} ne 'STDIN' ) {
158 close $import_handle
159 or die "Failed to close '$options{import}':$EXTENDED_OS_ERROR\n";
160 }
161 return @logins;
162 }
163
164 sub _read_logins {
165 my ($import_handle) = @_;
166 sysread $import_handle, my $magic_number,
167 _NUMBER_OF_BYTES_FOR_ZIP_MAGIC_NUMBER()
168 or die "Failed to read from file:$EXTENDED_OS_ERROR\n";
169 sysseek $import_handle, Fcntl::SEEK_SET(), 0
170 or die "Failed to seek to start of file:$EXTENDED_OS_ERROR\n";
171 foreach my $zip_magic_number (
172 "PK\N{END OF TEXT}\N{END OF TRANSMISSION}",
173 "PK\N{ENQUIRY}\N{ACKNOWLEDGE}",
174 "PK\N{ALERT}\N{BACKSPACE}"
175 )
176 {
177 if ( $magic_number eq $zip_magic_number ) {
178 return Firefox::Marionette->logins_from_zip($import_handle);
179 }
180 }
181 open my $duplicate_handle, q[>&], $import_handle
182 or die "Failed to duplicate import handle:$EXTENDED_OS_ERROR\n";
183 my $parser = XML::Parser->new();
184 my $xml = 1;
185 eval { $parser->parse($duplicate_handle); } or do {
186 $xml = 0;
187 };
188 close $duplicate_handle
189 or die "Failed to close temporary handle:$EXTENDED_OS_ERROR\n";
190 if ($xml) {
191 sysseek $import_handle, Fcntl::SEEK_SET(), 0
192 or die "Failed to seek to start of file:$EXTENDED_OS_ERROR\n";
193 return Firefox::Marionette->logins_from_xml($import_handle);
194 }
195 else {
196
197 return Firefox::Marionette->logins_from_csv($import_handle);
198 }
199 }
200
201 sub _export_logins {
202 my ( $firefox, $export_handle, %options ) = @_;
203 binmode $export_handle, ':encoding(utf8)';
204 my $csv =
205 Text::CSV_XS->new( { binary => 1, auto_diag => 1, always_quote => 1 } );
206 my $headers = [
207 qw(url username password httpRealm formActionOrigin guid timeCreated timeLastUsed timePasswordChanged)
208 ];
209 my @passwords;
210 my $count = 0;
211 foreach my $login ( $firefox->logins() ) {
212 if ( ( $options{'only-user'} )
213 && ( $login->user() ne $options{'only-user'} ) )
214 {
215 next;
216 }
217 if ( ( $options{'only-host-regex'} )
218 && ( $login->host() !~ /$options{'only-host-regex'}/smx ) )
219 {
220 next;
221 }
222 if ( $options{password} ) {
223 push @passwords, $login->password();
224 }
225 else {
226 if ( $count == 0 ) {
227 $csv->say( $export_handle, $headers );
228 }
229 my $row = [
230 $login->host(),
231 $login->user(),
232 $login->password(),
233 $login->realm(),
234 (
235 defined $login->origin()
236 ? $login->origin()
237 : ( defined $login->realm() ? undef : q[] )
238 ),
239 $login->guid(),
240 $login->creation_in_ms(),
241 $login->last_used_in_ms(),
242 $login->password_changed_in_ms()
243 ];
244 $csv->say( $export_handle, $row );
245 }
246 $count += 1;
247 }
248 if ( $options{password} ) {
249 my %different_passwords;
250 foreach my $password (@passwords) {
251 $different_passwords{$password} = 1;
252 }
253 if ( ( scalar keys %different_passwords ) == 1 ) {
254 print {$export_handle} "$passwords[0]\n"
255 or die "Failed to write password:$EXTENDED_OS_ERROR\n";
256 }
257 else {
258 die
259 "More than one password could be selected. Use --only-host-regex and --only-user to restrict the password selection\n";
260 }
261 }
262 return;
263 }
264
265 sub _check_options {
266 my (%options) = @_;
267 if ( $options{help} ) {
268 require Pod::Simple::Text;
269 my $parser = Pod::Simple::Text->new();
270 $parser->parse_from_file($PROGRAM_NAME);
271 exit 0;
272 }
273 elsif ( $options{version} ) {
274 print "$VERSION\n"
275 or die "Failed to print to STDOUT:$EXTENDED_OS_ERROR\n";
276 exit 0;
277 }
278 my %parameters = ( logins => {} );
279 foreach my $key (qw(visible debug console)) {
280 if ( $options{$key} ) {
281 $parameters{$key} = 1;
282 }
283 }
284 if ( $options{binary} ) {
285 $parameters{binary} = $options{binary};
286 }
287 if ( $options{'profile-name'} ) {
288 $parameters{profile_name} = $options{'profile-name'};
289 }
290 elsif ( !defined $options{import} ) {
291 my $profile_name = Firefox::Marionette::Profile->default_name();
292 $parameters{profile_copied_from} = $profile_name;
293 my $directory = Firefox::Marionette::Profile->directory($profile_name);
294 foreach my $name (qw(key3.db key4.db logins.json)) {
295 my $path = File::Spec->catfile( $directory, $name );
296 if ( my $handle = FileHandle->new( $path, Fcntl::O_RDONLY() ) ) {
297 push @{ $parameters{import_profile_paths} }, $path;
298 }
299 elsif ( $OS_ERROR == POSIX::ENOENT() ) {
300 }
301 else {
302 warn "Skipping $path:$EXTENDED_OS_ERROR\n";
303 }
304 }
305 }
306 return %parameters;
307 }
308
309 __END__
310 =head1 NAME
311
312 firefox-passwords - import and export passwords from firefox
313
314 =head1 VERSION
315
316 Version 1.70
317
318 =head1 USAGE
319
320 $ firefox-passwords >logins.csv # export from the default profile
321
322 $ firefox-passwords --export logins.csv # same thing but exporting directly to the file
323
324 $ firefox-passwords --list-profile-names # print out the available profile names
325
326 $ firefox-passwords --profile new --import logins.csv # imports logins from logins.csv into the new profile
327
328 $ firefox-passwords --profile new --import logins.csv --check-only # exit with a zero if the import file can be recognised. Do not import
329
330 $ firefox-passwords --export | firefox --import --profile-name new # export from the default profile into the new profile
331
332 $ firefox-passwords --export --only-host-regex "(pause|github)" # export logins with a host matching qr/(pause|github)/smx from the default profile
333
334 $ firefox-passwords --export --only-user "[email protected]" # export logins with user "[email protected]" from the default profile
335
336 $ firefox-passwords --only-user "[email protected]" --password # just print password for the [email protected] (assuming there is only one password)
337
338 =head1 DESCRIPTION
339
340 This program is intended to import and export passwords from firefox. It uses the L<Marionette protocol|https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/Protocol> and the L<nsILoginManager interface|https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsILoginManager> to access the L<Password Manager|https://support.mozilla.org/en-US/kb/password-manager-remember-delete-edit-logins?redirectslug=password-manager-remember-delete-change-and-import&redirectlocale=en-US>. This has been tested to work with Firefox 24 and above and has been designed to work with L<Firefox Sync|https://www.mozilla.org/en-US/firefox/sync/>
341
342 =head1 REQUIRED ARGUMENTS
343
344 Either --export, --import or --list-profile-names must be specified. If none of these is specified, --export is the assumed default
345
346 =head1 OPTIONS
347
348 Option names can be abbreviated to uniqueness and can be stated with singe or double dashes, and option values can be separated from the option name by a space or '=' (as with Getopt::Long). Option names are also case-
349 sensitive.
350
351 =over 4
352
353 =item * --help - This page.
354
355 =item * --version - Print the current version of this binary to STDOUT.
356
357 =item * --binary - Use this firefox binary instead of the default firefox instance
358
359 =item * --export - export passwords to STDOUT or the file name specified.
360
361 =item * --import - import passwords from STDIN or the file name specified.
362
363 =item * --check-only - when combined with --import, exit with a zero (0) exit code if the import file can be processed
364
365 =item * --list-profile-name - print out the available profile names
366
367 =item * --profile-name - specify the name of the profile to work with.
368
369 =item * --visible - allow firefox to be visible while exporting or importing logins
370
371 =item * --debug - turn on debug to show binary execution and network traffic during exporting or importing logins
372
373 =item * --console - make the browser javascript console appear during exporting or importing logins
374
375 =item * --only-host-regex - restrict the export of logins to those that have a hostname matching the supplied regex.
376
377 =item * --only-user - restrict the export of logins to those that have a user exactly matching the value.
378
379 =item * --password - when exporting only print the password, and only print the password if all passwords in the export match
380
381 =back
382
383 =head1 AUTOMATIC AND MANUAL PROFILE SELECTION
384
385 firefox-passwords will automatically work with the default L<Profile|https://support.mozilla.org/en-US/kb/profiles-where-firefox-stores-user-data>. You can select other profiles with the --profile-name option
386
387 =head1 PRIMARY PASSWORDS
388
389 firefox-passwords will request the L<Primary Password|https://support.mozilla.org/en-US/kb/use-primary-password-protect-stored-logins> if required when importing or exporting from the L<Password Manager|https://support.mozilla.org/en-US/kb/password-manager-remember-delete-edit-logins?redirectslug=password-manager-remember-delete-change-and-import&redirectlocale=en-US>.
390
391 =head1 EXPORTING AND IMPORTING TO GOOGLE CHROME OR MICROSOFT EDGE
392
393 firefox-passwords will natively read and write login csv files for Google Chrome and Microsoft Edge.
394
395 =head1 PASSWORD IMPORT/EXPORT FORMAT
396
397 firefox-passwords will export data in CSV with the following column headers
398
399 "url","username","password","httpRealm","formActionOrigin","guid","timeCreated","timeLastUsed","timePasswordChanged"
400
401 firefox-passwords will import data in CSV. It will recognise different formats for importing passwords, including the export format and the others listed below. Plrease let me know if other formats would be useful.
402
403 =head1 PASSWORD IMPORTING FROM BITWARDEN
404
405 firefox-passwords will also accept input data in L<Bitwarden csv format|https://bitwarden.com/help/article/condition-bitwarden-import/>, which includes the following column headers;
406
407 ...,"login_uri","login_username","login_password",...
408
409 =head1 PASSWORD IMPORTING FROM LASTPASS
410
411 firefox-passwords will also accept input data in L<LastPass CSV|https://support.logmeininc.com/lastpass/help/how-do-i-nbsp-export-stored-data-from-lastpass-using-a-generic-csv-file>, which includes the following column headers;
412
413 url,username,password,totp,extra,name,grouping,fav
414
415 The LastPass CSV export also can include an unusual "url" value of "http://sn" for server logins, database logins, etc. All logins with a "url" value of "http://sn" AND an "extra" value matching the regular expression /^NoteType:/ will be skipped (as there is no use for these types of login records in firefox.
416
417 =head1 PASSWORD IMPORTING FROM KEEPASS
418
419 firefox-passwords will also accept input data in L<KeePass CSV|https://keepass.info/help/base/importexport.html#csv>, which includes the following column headers;
420
421 ...,"Login Name","Password","Web Site",...
422
423 =head1 PASSWORD IMPORTING FROM 1PASSWORD
424
425 firefox-passwords will also accept the L<1Password Unencrypted Export format|https://support.1password.com/1pux-format/>
426
427 =head1 CONFIGURATION
428
429 firefox-passwords requires no configuration files or environment variables.
430
431 =head1 DEPENDENCIES
432
433 firefox-passwords requires the following non-core Perl modules
434
435 =over
436
437 =item *
438 L<Pod::Simple::Text|Pod::Simple::Text>
439
440 =item *
441 L<Text::CSV_XS|Text::CSV_XS>
442
443 =item *
444 L<XML::Parser|XML::Parser>
445
446 =back
447
448 =head1 DIAGNOSTICS
449
450 None.
451
452 =head1 INCOMPATIBILITIES
453
454 None known.
455
456 =head1 EXIT STATUS
457
458 This program will exit with a zero after successfully completing.
459
460 =head1 BUGS AND LIMITATIONS
461
462 To report a bug, or view the current list of bugs, please visit L<https://github.com/david-dick/firefox-marionette/issues>
463
464 =head1 AUTHOR
465
466 David Dick C<< <[email protected]> >>
467
468 =head1 LICENSE AND COPYRIGHT
469
470 Copyright (c) 2024, David Dick C<< <[email protected]> >>. All rights reserved.
471
472 This module is free software; you can redistribute it and/or
473 modify it under the same terms as Perl itself. See L<perlartistic/perlartistic>.
474
475 =head1 DISCLAIMER OF WARRANTY
476
477 BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
478 FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
479 OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
480 PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
481 EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
482 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
483 ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
484 YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
485 NECESSARY SERVICING, REPAIR, OR CORRECTION.
486
487 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
488 WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
489 REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
490 LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
491 OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
492 THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
493 RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
494 FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
495 SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
496 SUCH DAMAGES.