-
Notifications
You must be signed in to change notification settings - Fork 0
/
getpaste
executable file
·1529 lines (1282 loc) · 32.1 KB
/
getpaste
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
#!/usr/bin/env perl
# getpaste - retrieves raw text from pastebins
#
# (c) 2010-2021 Mantas Mikulėnas <grawity@gmail.com>
# Released under the MIT License (dist/LICENSE.mit)
use v5.10;
use warnings;
use strict;
no locale;
use open qw(:std :utf8);
require Crypt::AuthEnc::CCM;
require Crypt::AuthEnc::GCM;
require Crypt::AuthEnc::OCB;
require Crypt::Cipher;
require Crypt::Cipher::AES;
require Crypt::Digest;
require Crypt::Digest::RIPEMD160;
require Crypt::Digest::SHA1;
require Crypt::Digest::SHA512;
require Crypt::KeyDerivation;
require Crypt::Mac::HMAC;
require Crypt::Mac::PMAC;
require Crypt::Mode::CBC;
require Crypt::Mode::OFB;
use Encode qw(decode encode);
use Getopt::Long qw(:config bundling no_ignore_case);
use HTML::Entities;
use JSON;
use LWP::UserAgent;
use MIME::Base64;
my $opt_insecure = 0;
my $opt_show_url = 0;
my $opt_batch = 0;
# generic utility functions {{{
BEGIN {
if (eval {require Nullroute::Lib}) {
Nullroute::Lib->import(qw(_trace _debug _warn _err _die));
} else {
$::arg0 = (split m!/!, $0)[-1];
$::debug = !!$ENV{DEBUG};
$::warnings = 0;
$::errors = 0;
sub _trace { warn "trace: @_\n" if $::debug; }
sub _debug { warn "debug: @_\n" if $::debug; }
sub _warn { warn "warning: @_\n"; ++$::warnings; }
sub _err { warn "error: @_\n"; ! ++$::errors; }
sub _die { _err(@_); exit 1; }
}
}
sub chunk {
my ($buf, $bs) = @_;
return unpack("(A$bs)*", $buf);
}
sub _dump {
use Data::Dumper;
return Data::Dumper->new(\@_)->Terse(1)->Indent(0)->Dump;
}
sub _db64 {
my ($buf) = @_;
return "[len ".length($buf)."] {".encode_base64($buf, "")."}";
}
sub _dhex {
my ($buf) = @_;
return "[len ".length($buf)."] <".encode_hex($buf).">";
}
sub _prompt {
my ($msg) = @_;
print STDERR "\e[1m$msg\e[m "; $|++;
chomp(my $resp = <STDIN>);
return $resp;
}
# }}}
# URL parsing functions {{{
my $URL_RE = qr{
(?: (?<scheme> [^:\/?\#]+) : )?
(?: // (?<host> [^/?#]*) )?
(?<path> [^?#]*)
(?: \? (?<query> [^#]*) )?
(?: \# (?<fragment> .*) )?
}x;
sub parse_url {
my ($url) = @_;
if ($url =~ $URL_RE) { return my %url = %+; }
}
sub unparse_url {
my (%url) = @_;
my $url = $url{scheme}."://".$url{host};
$url .= $url{path} if defined($url{path});
$url .= "?".$url{query} if defined($url{query});
$url .= "#".$url{fragment} if defined($url{fragment});
return $url;
}
# }}}
# translation database functions {{{
sub smart_match {
my ($str, $pattern) = @_;
if (!defined $str) {
return;
}
elsif (ref($pattern) eq "ARRAY") {
for (@$pattern) {
my @res = smart_match($str, $_);
return @res if @res;
}
}
elsif (ref($pattern) eq "Regexp" && $str =~ $pattern) {
# If $pattern has no capture groups, =~ will return an
# (1,) in list context since it needs a trueish value.
# This bit of linenoise works consistently in all cases.
return map {substr($str, $-[$_], $+[$_]-$-[$_])} 0..$#-;
#return @{^CAPTURE}; # new in 5.26
}
elsif (ref($pattern) eq "" && $str eq $pattern) {
return $str;
}
return;
}
my $EXPN_RE = qr/#(#|\d|\{\w+.\d+\})/;
sub expn {
my ($str, $data, $def) = @_;
for ($str) {
if ($_ eq "#") {
return $_;
} elsif ($def && /^(\d+)$/) {
return $data->{$def}->[$1] // "";
} elsif (/^\{(\w+).(\d+)\}$/) {
return $data->{$1}->[$2] // "";
} else {
_err("unknown expansion '#$_'");
return "\x{1F612}";
}
}
};
my @SITES;
sub translate_url {
my ($url) = @_;
my @fields = qw(scheme host path query fragment);
my %url = parse_url($url);
unless (%url && defined($url{host}) && defined($url{path})) {
_die("bad URL: $url");
}
_debug("scheme='".($url{scheme}//"")."'".
", host='".($url{host}//"")."'".
", path='".($url{path}//"")."'".
", query='".($url{query}//"")."'".
", frag='".($url{fragment}//"")."'");
SITE: for my $site (@SITES) {
use Data::Dumper;
my %match;
for (@fields) {
my $pat = $site->{"$_"} or next;
my @res = smart_match($url{$_}, $pat) or next SITE;
_debug("match $_ ~ "._dump($pat));
_debug(" -> "._dump(\@res));
$match{$_} = \@res;
}
next if !%match;
if ($site->{"note"}) { _debug($site->{"note"}); }
for (@fields) {
$match{$_} //= [$url{$_}];
}
for (@fields) {
my $fmt = $site->{"to_$_"} // next;
$fmt =~ s/$EXPN_RE/expn($1, \%match, $_)/ge;
$url{$_} = $fmt;
}
my $raw_url = unparse_url(%url);
my $func = $site->{"parser"};
if ($func) {
return ($raw_url, $func, $url{fragment});
} else {
return ($raw_url);
}
}
return;
}
sub retrieve_paste {
my ($url) = @_;
my ($raw_url, $handler, @hargs) = translate_url($url);
if ($opt_batch) {
if ($handler) {
print "$url [internal]\n";
} elsif ($raw_url) {
print "$url $raw_url\n";
} else {
print "$url [unknown]\n";
}
} elsif (!$raw_url && !$handler) {
_err("unknown pastebin: $url");
} elsif ($opt_show_url) {
if ($handler) {
_err("pastebin does not have raw URLs: $url");
} else {
print "$raw_url\n";
}
} else {
if ($handler) {
my $output = $handler->($raw_url, @hargs);
if (defined $output) {
utf8::decode($output);
print "$output\n";
} else {
_err("paste extraction failed");
}
} else {
getprint($raw_url);
}
}
}
sub dl_recursive {
my ($url) = @_;
my $target = follow($url);
return retrieve_paste($target);
}
# }}}
# HTTP client functions {{{
my $UA = LWP::UserAgent->new;
sub get {
my ($url) = @_;
_debug("fetching '$url'");
$UA->default_header("Referer" => $url);
my $resp = $UA->get($url);
if ($resp->is_success) {
_debug("fetch complete: '".$resp->status_line."'");
return $resp->decoded_content // $resp->content;
} else {
_err("fetch failed: '".$resp->status_line."'");
return;
}
}
sub getprint {
my ($url) = @_;
my $data = get($url);
if (defined $data) {
print $data;
}
}
sub post {
my ($url, %form) = @_;
_debug("posting to '$url'");
$UA->default_header("Referer" => $url);
my $resp = $UA->post($url, \%form);
if ($resp->is_success) {
_debug("post complete: '".$resp->status_line."'");
return $resp->decoded_content // $resp->content;
} else {
_err("post failed: '".$resp->status_line."'");
return;
}
}
sub follow {
my ($url) = @_;
_debug("following '$url'");
$UA->default_header("Referer" => $url);
my $resp = $UA->head($url);
if ($resp->is_success) {
_debug("fetch complete: '".$resp->status_line."'");
_debug(" -> '$_'") for map {$_->request->uri} ($resp->redirects, $resp);
return $resp->request->uri->as_string;
} else {
_err("fetch failed: '".$resp->status_line."'");
return;
}
}
# }}}
# decoders {{{
sub decode_base58 {
my ($str, $alpha) = @_;
# Source: https://metacpan.org/pod/Encode::Base58
use bigint;
use integer;
my @alpha = split(//, $alpha);
my $i = 0;
my %alpha = map { $_ => $i++ } @alpha;
my $decoded = 0;
my $multi = 1;
my $base = @alpha;
while (length $str > 0) {
my $digit = chop $str;
$decoded += $multi * $alpha{$digit};
$multi *= $base;
}
return $decoded->to_bytes;
}
sub decode_privatebin_base58 {
my ($str) = @_;
return decode_base58($str, "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
}
sub decode_sour_base64 {
my ($str) = @_;
$str =~ y!_-!/+!;
return decode_base64($str);
}
sub decode_cescape {
my ($str) = @_;
$str =~ s/\\x([0-9A-Fa-f]{2})/chr hex $1/ge;
return $str;
}
sub encode_hex {
my ($buf) = @_;
return unpack("H*", $buf);
}
sub decode_hex {
my ($str) = @_;
return pack("H*", $str);
}
sub decode_html {
my ($str) = @_;
$str =~ s/</</g;
$str =~ s/>/>/g;
$str =~ s/"/"/g;
$str =~ s/&/\&/g;
return $str;
}
sub try_decode_json {
my ($data) = @_;
return ref $data ? $data : decode_json($data);
}
# }}}
# decompressors {{{
sub decompress_zlib {
eval {
require Compress::Raw::Zlib;
} or _die("missing Perl package 'Compress::Raw::Zlib'");
my ($buf, %opt) = @_;
my $wbits;
my $stream;
my $status;
my $outbuf;
if ($opt{is_gzip_or_zlib}) {
# autodetect RFC 1950 (zlib) or 1952 (gzip)
$wbits = Compress::Raw::Zlib->WANT_GZIP_OR_ZLIB;
_trace("using WindowBits = $wbits (WANT_GZIP_OR_ZLIB, detect 1950/1952)");
}
elsif ($opt{is_gzip}) {
# expect RFC 1952 (gzip)
$wbits = Compress::Raw::Zlib->WANT_GZIP;
_trace("using WindowBits = $wbits (WANT_GZIP, expect 1952)");
}
elsif ($opt{is_deflate}) {
# expect RFC 1951 (deflate)
$wbits = -Compress::Raw::Zlib->MAX_WBITS;
_trace("using WindowBits = $wbits (-MAX_WBITS, expect 1951 deflate)");
}
elsif ($opt{is_zlib}) {
# expect RFC 1950 (zlib)
$wbits = 15;
_trace("using WindowBits = $wbits (expect 1950 zlib)");
}
else {
# mirror the zlib default
$wbits = Compress::Raw::Zlib->MAX_WBITS;
_trace("using WindowBits = $wbits (MAX_WBITS, default)");
}
($stream, $status) = Compress::Raw::Zlib::Inflate->new(-WindowBits => $wbits);
if ($status != Compress::Raw::Zlib->Z_OK) {
_die("inflateInit failed: $status");
}
$status = $stream->inflate($buf, $outbuf);
if ($status != Compress::Raw::Zlib->Z_OK &&
$status != Compress::Raw::Zlib->Z_STREAM_END) {
_die("inflate failed: $status (".$stream->msg.")");
}
return $outbuf;
}
sub decompress_deflate {
my ($buf) = @_;
return decompress_zlib($buf, is_deflate => 1);
}
sub decompress_gzip {
my ($buf) = @_;
return decompress_zlib($buf, is_gzip => 1);
}
sub decompress_lzw {
eval {
require Compress::LZW;
} or _die("missing Perl package 'Compress::LZW'");
my ($buf) = @_;
return Compress::LZW->decompress($buf);
}
sub decompress_inflate {
my ($buf) = @_;
require IO::Uncompress::Inflate;
my $outbuf;
my $stream = IO::Uncompress::Inflate->new(\$buf);
my $status = $stream->read($outbuf);
if ($status <= 0) {
_die("inflate failed: $IO::Uncompress::Inflate::InflateError");
}
return $outbuf;
}
sub decompress_rawinflate {
my ($buf) = @_;
require IO::Uncompress::RawInflate;
my $outbuf;
my $stream = IO::Uncompress::RawInflate->new(\$buf);
my $status = $stream->read($outbuf);
if ($status <= 0) {
_die("inflate failed: $IO::Uncompress::RawInflate::RawInflateError");
}
return $outbuf;
}
# }}}
# extra KDFs {{{
sub EVP_BytesToKey {
# Key+IV derivation used by 'openssl enc'
Crypt::Digest->import("digest_data");
my ($salt, $passphrase, $algo, $len) = @_;
my $hash = "";
my $buf = "";
while (length($buf) < $len) {
$hash = digest_data($algo, $hash, $passphrase, $salt);
$buf .= $hash;
}
return $buf;
}
# }}}
# extra ciphers {{{
sub ocb2_times2 {
my ($block) = @_;
my @block = unpack("C*", $block);
my $carry = ($block[0] >> 7) & 0x1;
for (my $i = 0; $i < $#block; $i++) {
$block[$i] = ($block[$i] << 1) | (($block[$i+1] >> 7) & 0x1);
}
$block[$#block] = ($block[$#block] << 1) ^ ($carry * 135);
return pack("C*", map {$_ & 0xFF} @block);
}
sub ocb2_decrypt_verify {
Crypt::Mac::PMAC->import("pmac");
my ($cipher, $key, $nonce, $aad, $ciphertext, $tag) = @_;
my $c = Crypt::Cipher->new($cipher, $key);
my $bs = $c->blocksize;
my $ts = 64 / 8;
my @ciphertext = chunk($ciphertext, $bs);
my $final = pop(@ciphertext);
my $nfinal = length($final);
my $pad = pack("N*", 0, 0, 0, $nfinal * 8);
my $delta = ocb2_times2($c->encrypt($nonce));
my $checksum = "\x00" x $bs;
my $output = "";
for my $block (@ciphertext) {
$block = $c->decrypt($block ^ $delta) ^ $delta;
$delta = ocb2_times2($delta);
$output .= $block;
$checksum ^= $block;
}
$final = $final ^ $c->encrypt($delta ^ $pad);
$output .= substr($final, 0, $nfinal);
$checksum ^= $final;
$checksum = $c->encrypt($checksum ^ $delta ^ ocb2_times2($delta));
$checksum ^= pmac($cipher, $key, $aad) if length($aad);
$checksum = substr($checksum, 0, $ts);
return if $checksum ne $tag;
return $output;
}
# }}}
# unwrappers {{{
#
# These functions parse an encrypted/wrapped package (obtaining cipher, salt,
# iterations, IV...) and return decrypted/unwrapped data.
sub unwrap_defuse {
Crypt::AuthEnc::OCB->import(":all");
Crypt::KeyDerivation->import("pbkdf2");
# serialization: custom [iter + salt + iv + data]
# key derivation: PBKDF2-SHA256
# encryption: AES128-OCB2
my ($data, $passwd) = @_;
my @data = split(/:/, $data);
return if @data != 4;
my $iter = int($data[0]);
my $salt = decode_hex($data[1]);
my $iv = decode_hex($data[2]);
my $ct = decode_hex($data[3]);
my $ks = 128 / 8;
my $ts = 64 / 8;
my $key = pbkdf2($passwd, $salt, $iter, "SHA256", $ks);
my $tag = substr($ct, -$ts, $ts, "");
return ocb2_decrypt_verify("AES", $key, $iv, "", $ct, $tag)
// _die("decryption failed");
}
sub unwrap_ezcrypt {
Crypt::KeyDerivation->import("pbkdf2");
# serialization: raw [salt + data]
# key derivation: PBKDF2-SHA1
# encryption: AES-256-OFB
my ($data, $passwd) = @_;
my $ks = Crypt::Cipher::AES->keysize;
my $bs = Crypt::Cipher::AES->blocksize;
my $salt = substr($data, 0, $bs, "");
my $iter = 1; # LOL
my $key = pbkdf2($passwd, $salt, $iter, "SHA1", $ks);
my $iv = $salt;
return Crypt::Mode::OFB->new("AES")->decrypt($data, $key, $iv);
}
sub unwrap_ncrypt {
my ($data, $passwd, $cipher) = @_;
# serialization: JSON {data: raw [salt + data], cipher}
# key derivation: PBKDF2-SHA1
# encryption: AES-256-OFB (usually?)
if ($cipher eq "AES-256-OFB") {
return unwrap_ezcrypt($data, $passwd);
} else {
_die("unknown cipher '$cipher' for this pastebin");
}
}
sub unwrap_openssl_aes {
# serialization: raw [magic + salt + data]
# key derivation: EVP_BytesToKey (usually MD5)
# encryption: AES-256-CBC
Crypt::KeyDerivation->import("pbkdf2");
my ($data, $passwd, %opt) = @_;
my $ks = Crypt::Cipher::AES->keysize;
my $bs = Crypt::Cipher::AES->blocksize;
my $magic = substr($data, 0, 8, "");
my $salt = substr($data, 0, 8, "");
if ($magic ne "Salted__") {
_die("bad magic value in encrypted data");
}
_debug("pass: ".$passwd);
_debug("salt: "._db64($salt));
_debug("salt: "._dhex($salt));
my $buf;
if ($opt{pbkdf2}) {
my $algo = uc($opt{kdf_algo} // "SHA256");
my $iter = $opt{kdf_iter} // 1000;
_debug("KDF: PBKDF2 (algo=$algo, iter=$iter)");
$buf = pbkdf2($passwd, $salt, $iter, $algo, $ks + $bs);
} else {
my $algo = uc($opt{kdf_algo} // "MD5");
_debug("KDF: EVP_BytesToKey (algo=$algo");
$buf = EVP_BytesToKey($salt, $passwd, $algo, $ks + $bs);
}
my $key = substr($buf, 0, $ks, "");
my $iv = substr($buf, 0, $bs, "");
_debug("Key: "._db64($key));
_debug("IV: "._db64($iv));
_debug("Key: "._dhex($key));
_debug("IV: "._dhex($iv));
return Crypt::Mode::CBC->new("AES")->decrypt($data, $key, $iv);
}
sub unwrap_pastesh {
Crypt::Mac::HMAC->import("hmac");
my ($vers, $data, $passwd, $atag) = @_;
_debug("password: $passwd");
if ($atag) {
_debug("atag: "._db64($atag));
my $mac1 = hmac("SHA512", "auth key", $passwd);
my $mac2 = hmac("SHA512", $mac1, $data);
if ($mac2 ne $atag) {
_debug("mac1: "._db64($mac1));
_debug("mac2: "._db64($mac2));
_due("bad HMAC");
}
}
if ($vers eq "v3") {
$data = unwrap_openssl_aes($data, $passwd, (
pbkdf2 => 1,
kdf_algo => "SHA512",
# yes, CryptoJS defaults to 1 in v2/v3
kdf_iter => 1));
} else {
$data = unwrap_openssl_aes($data, $passwd, (kdf_algo => "SHA512"));
}
return $data;
}
sub unwrap_privatebin_v2 {
Crypt::AuthEnc::GCM->import(":all");
Crypt::KeyDerivation->import("pbkdf2");
# serialization: JSON
# key derivation: PBKDF2-SHA256
# encryption: AES256-GCM
my ($data, $passwd) = @_;
if ($data->{v} != 2) {
_die("incorrect paste format version ".$data->{v});
}
my $cparams = $data->{adata}->[0];
my $ct = decode_base64($data->{ct});
my $iv = decode_base64($cparams->[0]);
my $salt = decode_base64($cparams->[1]);
my $iter = $cparams->[2];
my $ks = $cparams->[3] / 8;
my $ts = $cparams->[4] / 8;
my $cipher = $cparams->[5];
my $mode = $cparams->[6];
my $comp = $cparams->[7];
unless ($cipher eq "aes") {
_die("unsupported cipher ".$cipher);
}
unless ($mode eq "gcm") {
_die("unsupported cipher mode ".$mode);
}
unless ($comp =~ /^(none|zlib)$/) {
_die("unsupported compression ".$comp);
}
my $ikey = decode_privatebin_base58($passwd);
my $dkey = pbkdf2($ikey, $salt, $iter, "SHA256", $ks);
# note that this relies on the encoder producing the most compact output
# (or more precisely, behaving like JSON.stringify() in JavaScript)
my $hdr = encode_json($data->{adata});
my $tag = substr($ct, -$ts, $ts, "");
if ($mode eq "gcm") {
$data = gcm_decrypt_verify("AES", $dkey, $iv, $hdr, $ct, $tag)
// _die("decryption failed");
}
if ($comp eq "zlib") {
$data = decompress_deflate($data);
}
$data = decode_json($data)->{paste};
return $data;
}
sub unwrap_sjcl {
Crypt::AuthEnc::CCM->import(":all");
Crypt::AuthEnc::GCM->import(":all");
Crypt::KeyDerivation->import("pbkdf2");
# serialization: JSON
# key derivation: PBKDF2-SHA256
# encryption: AES128-CCM
my ($json, $passwd) = @_;
my $data = try_decode_json($json);
if (($data->{v} //= "1") != 1) {
_die("unsupported SJCL blob version ".$data->{v});
}
if (($data->{cipher} //= "aes") ne "aes") {
_die("unsupported cipher ".$data->{cipher});
}
my $mode = $data->{mode} // "ccm";
unless ($mode eq "ccm" || $mode eq "gcm") {
_die("unsupported cipher mode ".$mode);
}
my $salt = decode_base64($data->{salt} // "");
my $ct = decode_base64($data->{ct});
my $iv = decode_base64($data->{iv});
my $iter = int($data->{iter} || 1000),
my $ks = int($data->{ks} || 128) / 8; # key size
my $ts = int($data->{ts} || 64) / 8; # tag size
my $hdr = decode_base64($data->{adata} // "");
my $key = $salt ? pbkdf2($passwd, $salt, $iter, "SHA256", $ks) : $passwd;
my $tag = substr($ct, -$ts, $ts, "");
if ($mode eq "ccm") {
return ccm_decrypt_verify("AES", $key, $iv, $hdr, $ct, $tag)
// _die("decryption failed");
}
elsif ($mode eq "gcm") {
return gcm_decrypt_verify("AES", $key, $iv, $hdr, $ct, $tag)
// _die("decryption failed");
}
}
# }}}
# downloaders {{{
#
# These functions take an URL, extract the wrapped package from it, and call an
# apropriate unwrapper.
sub dl_0bin {
my ($url, $frag) = @_;
if (!length $frag) {
_die("cannot decrypt without key in URL fragment");
}
my $body = get($url);
$body =~ m{<code>\n\s*(\{.+\})\n\s*</code>} || return;
my $data = decode_html($1);
$data = unwrap_sjcl($data, $frag);
$data = decode_base64($data);
#$data = decompress_lzw($data);
return $data;
}
sub dl_nothingnet {
my ($url, $frag) = @_;
if (!length $frag) {
_die("cannot decrypt without key in URL fragment");
}
$frag =~ s/\$.*//;
$frag = decode_base64($frag);
my $body = get($url);
$body =~ m{>(\{".+\"\})<} || return;
my $data = decode_html($1);
$data = unwrap_sjcl($data, $frag);
return $data;
}
sub dl_cryptbin_do {
my ($url, $frag) = @_;
if (!length $frag) {
_die("cannot decrypt without key in URL fragment");
}
my $idx = 0;
$idx = int $1 if $frag =~ s/,(\d+)$//;
my $body = get($url);
$body =~ m{var message='(.+?)';} || return;
my $data = decode_base64($1);
$data = unwrap_openssl_aes($data, $frag);
$data = decode_json($data);
if (@$data > 1 && !$idx) {
_warn("only the first file of ".@$data." is shown");
} elsif (@$data <= $idx) {
_die("paste only has ".@$data." files");
}
$data = $data->[$idx]->{body};
return $data;
}
sub dl_cryptobin {
my ($url, $frag) = @_;
if (!length $frag) {
$frag = _prompt("password?");
}
if (!length $frag) {
_die("cannot decrypt without key/password");
}
my $body = get($url);
$body =~ m{<textarea name="cipher">(.+?)</textarea} || return;
my $data = decode_base64($1);
$data = unwrap_sjcl($data, $frag);
return $data;
}
sub dl_defuse {
my ($url, $frag) = @_;
my $body = get($url);
if ($body =~ m{<textarea id="paste"[^>]*>(.+?)</textarea>}) {
my $data = $1;
$data = decode_entities($data);
return $data;
}
if ($body =~ m{var encrypted = "(.+?)";$}m) {
if (!length $frag) {
$frag = _prompt("password?");
}
if (!length $frag) {
_die("cannot decrypt without key/password");
}
my $data = $1;
$data = decode_cescape($data);
$data = unwrap_defuse($data, $frag);
return $data;
}
return;
}
sub dl_dgl_pastesh {
my ($url, $frag) = @_;
my %url = parse_url($url);
$url{path} =~ m!^/([^.]+)!;
my $id = $1;
my $body = get($url) // return;
$body =~ m{name="content" value="([^"]*?)"} // return;
my $data = decode_base64($1);
$body =~ m{name="type" value="([^"]*?)"} // return;
my $vers = $1;
$body =~ m{name="etag" value="([^"]*?)"} // return;
my $atag = decode_base64($1);
$body =~ m{name="serverkey" value="([^"]*?)"} // return;
my $serverkey = $1;
my $passwd = $id . $serverkey . $frag . "https://paste.sh";
$data = unwrap_pastesh($vers, $data, $passwd, $atag);
if ($vers eq "v3") {
# Remove the "Subject:" line (or don't)
#$data =~ s/^.*?\n\n//m;
}
return $data;
}
sub dl_dpaste {
my ($url, $frag) = @_;
my $body = get($url);
if ($body =~ m{<textarea id="copySnippetSource">(.+?)</textarea>}s) {
return decode_entities($1);
}
return;
}
sub dl_ezcrypt {
Crypt::Digest::SHA1->import("sha1_hex");
my ($url, $frag) = @_;
if (!length $frag) {
_die("cannot decrypt without key in URL fragment");
}
my $password;
my $body;
my $data;
$body = get($url);
while ($body =~ /<div id="askpassword">/) {
if (-t 0) {
_debug("paste is password-protected");
$password = _prompt("password?");
} else {
_die("paste is password-protected");
}
$body = post($url, p => sha1_hex($password)) || return;
}
if ($body =~ /DOCTYPE/) {
$body =~ m{<input .+ id="data" value="(.+)" />}s || return;
$data = $1;
}
elsif ($body =~ /^\{/) {
$data = decode_json($body);
$data = $data->{data};
}
$data = decode_base64($data);
$data = unwrap_ezcrypt($data, $frag);
return $data;