-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathga_cli.pl
More file actions
executable file
·669 lines (533 loc) · 21.7 KB
/
ga_cli.pl
File metadata and controls
executable file
·669 lines (533 loc) · 21.7 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
#!/usr/bin/perl
#=====================================================================#
# Program => ga_cli.pl (In Perl 5.0) version 1.0.0 #
#=====================================================================#
# Autor => Fernando "El Pop" Romo (pop@cofradia.org) #
# Creation date => 01/September/2022 #
#---------------------------------------------------------------------#
# Info => This program is a CLI version of the Google Authenticator #
# App. #
#---------------------------------------------------------------------#
# This code are released under the GPL 3.0 License. Any change must #
# be report to the authors #
# (c) 2022 - Fernando Romo #
#=====================================================================#
use strict;
use Auth::GoogleAuth; # Handle Google Authenticator account info
use Barcode::ZBar; # Read QR code
use Convert::Base32; # Base32 encoding/decoding
use File::Copy; # file cp or mv
use Getopt::Long; # Handle the arguments passed to the program
use Google::ProtocolBuffers; # Google Protocol buffers compiler
use Image::Magick; # Handle image info
use Imager::QRCode; # Generate QR images
use MIME::Base64; # MIME Encoding/Decoding
use Pod::Usage; # Perl documentation for help
# Constants
use constant {
# Header for QR messages on export
HEADERGA => 'otpauth-migration://offline',
HEADERTOTP => 'otpauth://totp/',
# Text Colors
FG_GREEN => "\033[32m",
FG_RED => "\033[31m",
RESET => "\033[0m",
};
# Work variables
my $work_dir = $ENV{'HOME'} . '/.ga_cli'; # keys directory
my %key_ring = ();
my %options = ();
# Command Line options
GetOptions(\%options,
'import=s@{1,}',
'export:s@{,}',
'add=s%{3}',
'remove=s%{2}',
'clear',
'list',
'verbose',
'help|?',
);
# Definition of the Protocol Buffers generated by Google Authenticator Export Accounts options
Google::ProtocolBuffers->parse("
syntax = \"proto2\";
message GA {
repeated Keys Index = 1;
message Keys {
required string pass = 1;
required string keyid = 2;
optional string issuer = 3;
optional Algorithm algorithm = 4;
optional DigitSize digits = 5;
optional OtpType type = 6;
enum Algorithm {
ALGO_UNSPECIFIED = 0;
SHA1 = 1;
SHA256 = 2;
SHA512 = 3;
MD5 = 4;
}
enum DigitSize {
DS_UNSPECIFIED = 0;
SIX = 1;
EIGHT = 2;
}
enum OtpType {
OT_UNSPECIFIED = 0;
HOTP = 1;
TOTP = 2;
}
}
optional int32 version = 2;
optional int32 QRCount = 3;
optional int32 QRIndex = 4;
}",
{create_accessors => 1}
);
#--------------------------#
# Write Keys configuration #
#--------------------------#
sub write_conf {
# create work directory if not exists
unless (-f $work_dir) {
mkdir($work_dir);
}
# make a backup (just in case).
if (-f "$work_dir\/keys") {
move("$work_dir\/keys", "$work_dir\/keys.back");
}
# Create and write a conf file called "keys"
open(CONF, ">:encoding(UTF-8)","$work_dir\/keys") or die "Can't create conf file: $!";
print CONF "(\n";
my $count = 0;
foreach my $issuer (sort { "\U$a" cmp "\U$b" } keys %key_ring) {
print CONF " '$issuer' => {\n";
foreach my $keyid (sort { "\U$a" cmp "\U$b" } keys %{$key_ring{$issuer}} ) {
$count++;
print CONF " '$keyid' => {\n";
# convert the passwords in octal notation
$key_ring{$issuer}{$keyid}{secret} =~ s/[\N{U+0000}-\N{U+FFFF}]/sprintf("\\%03o",ord($&))/eg;
print CONF " secret => \"$key_ring{$issuer}{$keyid}{secret}\",\n";
print CONF " algorithm => $key_ring{$issuer}{$keyid}{algorithm},\n";
print CONF " digits => $key_ring{$issuer}{$keyid}{digits},\n";
print CONF " type => $key_ring{$issuer}{$keyid}{type},\n";
print CONF " },\n";
}
print CONF " },\n";
}
print CONF ");\n";
close(CONF);
print "$count keys on key ring\n" if ($options{'verbose'});
} # End sub write_conf()
#-----------------------------------#
# Read the QR data and process keys #
#-----------------------------------#
sub import_qr {
my $qr_data = '';
my @images = grep {/\.(jpg|jpeg|png)$/} @{$options{'import'}}; # filter image files from command arguments
# Clean key_ring
%key_ring = () if ($options{'clear'});
#Internal function to process Data
sub _process_data {
my $qr_data_ref = shift;
# Check for "otpauth-migration://offline" in the QR info
if ($$qr_data_ref =~ /^${\HEADERGA}/) {
# only take the MIME Data on the QR message
my ($data) = $$qr_data_ref =~/data=(.*)/;
# URL Decode
$data =~ s/\%([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
# Decode Base64 Info
my $mime_data = decode_base64($data);
# Process Protocol Buffers from de MIME Base64 Data
my $protocol_buffer = GA->decode("$mime_data");
foreach my $ref (@{$protocol_buffer->{Index}}) {
# Assign values to the key ring
if ($ref->{issuer} ne '') {
$key_ring{$ref->{issuer}}{$ref->{keyid}}{secret} = $ref->{pass};
$key_ring{$ref->{issuer}}{$ref->{keyid}}{algorithm} = $ref->{algorithm};
$key_ring{$ref->{issuer}}{$ref->{keyid}}{digits} = $ref->{digits};
$key_ring{$ref->{issuer}}{$ref->{keyid}}{type} = $ref->{type};
print " $ref->{issuer}:$ref->{keyid}\n" if ($options{'verbose'});
}
}
}
# Check for "otpauth://totp/" in the QR info for add a single key
elsif ($$qr_data_ref =~ /^${\HEADERTOTP}/) {
# replace %3A = : and %40 = @
$$qr_data_ref =~ s/\%40/\@/g;
$$qr_data_ref =~ s/\%3A/\:/g;
# Obtain values
my ($keyid, $secret32, $issuer) = $$qr_data_ref =~ /totp\/.*?\:(.*)\?secret\=(.*)\&issuer=(.*)/;
# if have minimun info to add key
if ($keyid && $secret32) {
# Decode de Base32 pass
my $secret = decode_base32( $secret32);
# Assign values to the key ring
if ($issuer ne '') {
$key_ring{$issuer}{$keyid}{secret} = $secret;
$key_ring{$issuer}{$keyid}{algorithm} = 1;
$key_ring{$issuer}{$keyid}{digits} = 1;
$key_ring{$issuer}{$keyid}{type} = 2;
print " $issuer:$keyid\n" if ($options{'verbose'});
}
}
else {
print "Error: No account to add to key ring\n";
}
}
else {
print "Error: No Google Authenticator Export Data found\n";
}
} # end sub _process_data()
# Process if exists the argument with a image filename
if ($#images >=0) {
# Process images
foreach my $image (@images) {
print "$image\n" if ($options{'verbose'});
# Prepare to Read the QR using ZBar libs
my $scanner = Barcode::ZBar::ImageScanner->new();
$scanner->parse_config("enable");
# Use ImageMagick to obtain image properties
my $magick = Image::Magick->new();
$magick->Read($image) && die;
my $raw = $magick->ImageToBlob(magick => 'GRAY', depth => 8);
# Set ZBar reader and read image
my $image = Barcode::ZBar::Image->new();
$image->set_format('Y800');
$image->set_size($magick->Get(qw(columns rows)));
$image->set_data($raw);
my $n = $scanner->scan_image($image);
# Read QR Data
foreach my $symbol ($image->get_symbols()) {
($qr_data) = $symbol->get_data();
# Process the Protocol Buffer Data
_process_data(\$qr_data);
}
undef($image);
}
write_conf();
}
# If you don't give any file, print help
else {
print "Usage:\n";
print " ./ga_cli.pl -import \[image_file(.png|.jpg)\]\n";
}
} # End sub import_qr()
#--------------------------------------------------------#
# export all Keys to QR for load in Google Authenticator #
#--------------------------------------------------------#
sub export_qr {
# Date to put on export QR files
sub _date {
my ($year, $month, $day) = (localtime( time() ))[5,4,3];
$year = $year + 1900;
$month += 1;
return sprintf("%04d%02d%02d",$year,$month,$day);
} # End sub _date()
# if exists a list of issuers, create individual QR images
if ( @{$options{'export'}}[0] ne '' ) {
foreach my $for_export (@{$options{'export'}}) {
my ($issuer, $keyid) = split(':',$for_export);
# if exists a match, generate the QR image from the key ring
if ( exists($key_ring{$issuer}{$keyid}) ) {
my $qrcode = Imager::QRCode->new(
size => 4,
margin => 1,
version => 1,
level => 'M',
casesensitive => 1,
lightcolor => Imager::Color->new(255, 255, 255),
darkcolor => Imager::Color->new(0, 0, 0),
);
my $leyend = HEADERTOTP . $issuer . ':' . $keyid .
'?secret=' . encode_base32($key_ring{$issuer}{$keyid}{secret}) .'&issuer=' . $issuer;
$leyend =~ s/\s/\%20/g;
my $img = $qrcode->plot("$leyend");
$issuer =~ s/\s/\_/g;
$img->write(file => "qr_$issuer" . '_' . "$keyid.png");
print "qr_$issuer" . '_' . "$keyid.png\n" if ($options{'verbose'});
}
else {
print "Error: no issuer:keyid match\n";
}
}
}
# Create full QR backup to import into Google Authenticator
else {
# Obtain keys to process
my $total_keys = 0;
foreach my $issuer (sort { "\U$a" cmp "\U$b" } keys %key_ring) {
foreach my $keyid (sort { "\U$a" cmp "\U$b" } keys %{$key_ring{$issuer}} ) {
$total_keys++;
}
}
my $images_count = int($total_keys / 10);
my %export_ring = ( 'version' => 1,
'QRCount' => 1,
'QRIndex' => 0, );
my $key_counter = 0;
my $current = 1;
if ( ($total_keys % 10) > 0) {
$images_count++;
}
$export_ring{QRCount} = $images_count;
# If have keys to process
if ($total_keys > 0) {
# Load Protocol Buffer Array to process
foreach my $issuer (sort { "\U$a" cmp "\U$b" } keys %key_ring) {
foreach my $keyid (sort { "\U$a" cmp "\U$b" } keys %{$key_ring{$issuer}} ) {
$key_counter++;
push @{$export_ring{'Index'}},
({
'issuer' => "$issuer",
'keyid' => "$keyid",
'pass' => "$key_ring{$issuer}{$keyid}{secret}",
'algorithm' => $key_ring{$issuer}{$keyid}{algorithm},
'digits' => $key_ring{$issuer}{$keyid}{digits},
'type' => $key_ring{$issuer}{$keyid}{type},
});
# Generate QR each 10 keys
if ( ( ($key_counter % 10) == 0 )
|| ($key_counter == $total_keys) ) {
# Process Protocol Buffers from de MIME Base64 Data
my $protocol_buffer = GA->encode(\%export_ring);
# Encode MIME Base64
my $mime_data = encode_base64($protocol_buffer);
# URL Encode
$mime_data =~ s/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg;
$mime_data =~ s/\%0A//g; # avoid new line
# generate QR image
my $qrcode = Imager::QRCode->new(
size => 4,
margin => 1,
version => 1,
level => 'M',
casesensitive => 1,
lightcolor => Imager::Color->new(255, 255, 255),
darkcolor => Imager::Color->new(0, 0, 0),
);
my $img = $qrcode->plot( HEADERGA . "\?data=$mime_data");
my $qr_file = sprintf("export_keys_%08d_%02d_of_%02d.png", _date(), $current, $images_count);
$img->write(file => "$qr_file");
# Show progress
print "$qr_file\n" if ($options{'verbose'});
# Clean Up the hash for the next 10 keys
$export_ring{'Index'} = ();
$export_ring{QRIndex} = $current++; # Next batch number
}
}
}
# Clean key_ring
if ($options{'clear'}) {
%key_ring = ();
write_conf();
}
}
else {
print "Error: No keys to process\n";
}
}
} # End sub export_qr()
#-----------------------------------------------#
# Add manually a single account to the Key Ring #
#-----------------------------------------------#
sub add_key {
# if have values, proceed
if ( $options{'add'}{'issuer'}
&& $options{'add'}{'keyid'}
&& $options{'add'}{'secret'}) {
# Clean key_ring
%key_ring = () if ($options{'clear'});
# Add to key ring
$key_ring{$options{'add'}{'issuer'}}{$options{'add'}{'keyid'}}{secret} = $options{'add'}{'secret'};
$key_ring{$options{'add'}{'issuer'}}{$options{'add'}{'keyid'}}{algorithm} = 1;
$key_ring{$options{'add'}{'issuer'}}{$options{'add'}{'keyid'}}{digits} = 1;
$key_ring{$options{'add'}{'issuer'}}{$options{'add'}{'keyid'}}{type} = 2;
print "$options{'add'}{'issuer'}:$options{'add'}{'keyid'} key added\n" if ($options{'verbose'});
write_conf();
}
else {
print "Usage:\n";
print ' ./ga_cli.pl -add issuer=\'Some Company\' keyid=\'a@mail\' secret=\'A Passphrase\'' . "\n";
}
} # End add_key()
#-----------------------------------#
# Remove a single key from key ring #
#-----------------------------------#
sub remove_key {
# if has a value proceed
if ( $options{'remove'}{'issuer'} && $options{'remove'}{'keyid'}) {
# if exists a match remove the account from key ring
if ( exists($key_ring{$options{'remove'}{'issuer'}}{$options{'remove'}{'keyid'}}) ) {
delete $key_ring{"$options{'remove'}{'issuer'}"}{"$options{'remove'}{'keyid'}"};
write_conf()
}
else {
print "Error: no issuer match to remove\n";
}
}
else {
print "Usage:\n";
print ' ./ga_cli.pl -remove issuer=\'Some Company\'' . "\n";
}
} # End remove_key()
#----------------------------------------------------#
# Generate the OTP from the accounts on the key ring #
#----------------------------------------------------#
sub otp {
# Show Green or Red Text if the timer change
sub _semaphore {
my ($seconds) = (localtime( time() ))[0];
my $aux = $seconds % 30;
my $color = FG_RED;
if ($aux <= 25) {
$color = FG_GREEN;
}
return $color;
} # End sub _semaphore()
# Generate OTP
foreach my $issuer (sort { "\U$a" cmp "\U$b" } keys %key_ring) {
foreach my $keyid (sort { "\U$a" cmp "\U$b" } keys %{$key_ring{$issuer}} ) {
my $auth = Auth::GoogleAuth->new({
secret => "$key_ring{$issuer}{$keyid}{secret}",
issuer => "$issuer",
key_id => "$keyid",
});
$auth->secret32( encode_base32( $auth->secret() ) );
my $out = '';
# Only show issuer name if -list or -l option used
if ($options{'list'}) {
$out = "$issuer:$keyid\n";
}
else {
$out = sprintf('' . _semaphore() . " %06d" . RESET ." %-25s %-25s\n", $auth->code(), $issuer, $keyid );
}
# Filter output
if ($ARGV[0] ne '' ) {
if ($issuer =~ /$ARGV[0]/i) {
print $out;
}
}
else {
print $out;
}
$auth->clear();
}
}
} # End sub otp()
#-----------#
# Main body #
#-----------#
# Load config File
if (-f "$work_dir\/keys") {
%key_ring = do "$work_dir\/keys";
}
# Process options
if ($options{'help'}) {
pod2usage(-exitval => 0, -verbose => 1);
pod2usage(2);
}
elsif ($options{'import'}) {
import_qr();
}
elsif ($options{'export'}) {
export_qr();
}
elsif ($options{'add'}) {
add_key();
}
elsif ($options{'remove'}) {
remove_key();
}
# if have valid keys, process
elsif ( scalar(keys %key_ring) > 0 ) {
# Generate OTP
otp();
}
else {
print "Error: No keys found\n";
}
# End Main Body #
#-----------------------------------#
# Help info for use with Pod::Usage #
#-----------------------------------#
__END__
=head1 NAME
ga_cli.pl
=head1 DESCRIPTION
This program is a CLI version of the Google Authenticator App.
=head1 SYNOPSIS
ga_cli.pl [options] {file ...}
=head1 OPTIONS
=over 8
=item B<None>
Show the TOTP of each account.
ga_cli.pl
OpenEnchilada 972144
=item B<Word>
If you pass a value without '-', only shows the ones than contain your criteria (case insensitive):
ga_cli.pl bit
BITMAIN 067333
BitMEX 376455
Bitso 215278
This is equivalent to:
ga_cli.pl | grep -i bit
The following chars could be used on searchs:
'^' something starting with.
'$' something ending with.
'.*' wildcard character.
ga_cli.pl "^p.*m$"
pool.bitcoin.com 095968
=item B<-list or -l>
The -list or -l option only show the issuer name
ga_cli.pl -l
This is equivalent to:
ga_cli.pl | awk '{print $1}'
=item B<-import or -i>
Import given QR image file:
ga_cli.pl -import export_accounts_sample.jpg
The QR image can be the full Google Authenticator Export Set or a single account for add to the key ring
You can process multiple images when Google Authenticator make more than one QR:
ga_cli.pl -v -i qr_one.jpg qr_two.jpg ...
JPG and PNG formats are supported.
=item B<-export or -e>
Create QR images for export to Googla Authenticator App:
ga_cli.pl -export
The program take all the keys on the key ring and create a set of files
(depending of the keys quantity) named "export_keys_YYYYMMDD_XX_of_ZZ.png".
where YYYYMMDD is the date, XX is the sequence and ZZ the total images on the set.
Each QR contain 10 keys per image. For example, if you have 25 keys, we generate 3 QR files:
export_keys_20220908_01_of_03.png
export_keys_20220908_02_of_03.png
export_keys_20220908_03_of_03.png
Create a QR image for a single account to add to your authenticator app:
ga_cli.pl -e 'your issuer:your keyid'
The issuer name must have a exact match to proceed (Case sensitive). The image file is named qr_{issuer}_{keyid}.png
Could use a list of issuers:
ga_cli.pl -e 'Binance.com:johndoo' 'Bitso:bitso' ...
You can export all your keys in individual files with a simple bash script:
#!/bin/bash
issuers=""
for i in `ga_cli.pl -l`
do
issuers+=" $i"
done
ga_cli.pl -v -e $issuers
=item B<-add or -a>
Add a single account to key ring manually:
ga_cli.pl -add issuer='your issuer' keyid='me@something.com' secret='A random pass'
=item B<-remove or -r>
Remove a single account from the key ring manually:
ga_cli.pl -remove issuer='your issuer' keyid='your keyid'
The issuer name must have a exact match to proceed (Case sensitive)
=item B<-clear or -c>
Delete the key ring, works with -import, -add or -export options.
When use -import or -add, Init the key ring and set new values.
With -export, generate the QR images and delete the key ring.
Use with caution, you can lose all you keys.
=item B<-verbose or -v>
Show progress when using -import, -export, -add, and -remove options
=item B<-help or -h or -?>
Show this help
=back
=cut