-
Notifications
You must be signed in to change notification settings - Fork 9
/
sslmate
executable file
·1821 lines (1558 loc) · 56.2 KB
/
sslmate
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
#
# Copyright (c) 2014 Opsmate, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# Except as contained in this notice, the name(s) of the above copyright
# holders shall not be used in advertising or otherwise to promote the
# sale, use or other dealings in this Software without prior written
# authorization.
#
#
# This program is designed to be used with the online SSLMate service at
# <https://sslmate.com/>. Use of the SSLMate service is governed by the
# Terms and Conditions available online at <https://sslmate.com/terms>.
#
use 5.010; # 5.10
use strict;
use warnings;
use Errno;
use Fcntl;
use POSIX ":sys_wait_h";
use Cwd qw(realpath);
use Digest::SHA qw(sha256_hex);
use File::Basename;
use File::Temp;
use IO::Handle;
use IPC::Open2;
# Debian/Ubuntu package RHEL/CentOS package
# --------------------------------------------------
# WWW::Curl::Easy # libwww-curl-perl perl-WWW-Curl
use URI::Escape; # liburi-perl perl-URI
use JSON::PP; # core in 5.13.9+ # libjson-perl perl-JSON
use Term::ReadKey; # libterm-readkey-perl perl-TermReadKey
our $has_curl = eval { require WWW::Curl::Easy; 1 };
use version; our $VERSION = version->declare('0.5.0');
our $API_ENDPOINT = 'https://sslmate.com/api/v1';
our $config_profile;
our %global_config;
our %personal_config;
our %ephemeral_config;
our $curl;
sub print_usage {
my ($out) = @_;
# |--------------------------------------------------------------------------------| 80 chars
print $out "Usage: sslmate [OPTIONS] COMMAND [ARGS]\n";
print $out "\n";
print $out "Commands:\n";
print $out " sslmate buy HOSTNAME Buy a certificate for the given hostname\n";
print $out " sslmate renew HOSTNAME Renew the certificate for the given hostname\n";
print $out " sslmate reissue HOSTNAME Reissue the certificate for given hostname\n";
print $out " sslmate revoke [-a] HOSTNAME Revoke the certificate for given hostname\n";
print $out " sslmate download HOSTNAME Download the certificate for given hostname\n";
#print $out " sslmate import KEYFILE CERTFILE Import this certificate to your account\n";
print $out " sslmate link Link this system with your SSLMate account\n";
print $out " sslmate help Display help\n";
print $out " sslmate version Print the version of SSLMate that's installed\n";
print $out "\n";
print $out "Valid options:\n";
print $out " -p, --profile=NAME Use the given configuration profile\n";
print $out "\n";
print $out "Run 'sslmate help COMMAND' for more information on a specific command.\n";
}
sub new_curl {
my $curl = WWW::Curl::Easy->new;
$curl->setopt(WWW::Curl::Easy::CURLOPT_PROTOCOLS(), 3); # Only safe protocols (HTTP and HTTPS, not SMTP, SSH, etc.)
$curl->setopt(WWW::Curl::Easy::CURLOPT_FOLLOWLOCATION(), 1); # Follow redirects
$curl->setopt(WWW::Curl::Easy::CURLOPT_MAXREDIRS(), 20); # Allow at most 20 redirections
$curl->setopt(WWW::Curl::Easy::CURLOPT_SSL_VERIFYPEER(), 1); # Check certificates
$curl->setopt(WWW::Curl::Easy::CURLOPT_SSL_VERIFYHOST(), 2); # Check certificates (2 is not a typo)
$curl->setopt(WWW::Curl::Easy::CURLOPT_USERAGENT(), "SSLMate/$VERSION");
return $curl;
}
sub prompt_user {
my ($message) = @_;
print $message;
my $answer = <STDIN>;
die "Error: Input ended prematurely.\n" unless defined($answer);
chomp $answer;
return $answer;
}
sub prompt_yesno {
while (defined(my $answer = prompt_user("Enter yes or no: "))) {
if ($answer eq 'yes') {
return 1;
} elsif ($answer eq 'no') {
return 0;
} else {
print "I did not understand that.\n";
}
}
}
sub prompt_password {
my ($message) = @_;
print $message;
my $password = '';
ReadMode(4);
my %ctrl = GetControlChars;
while (defined(my $key = ReadKey(0))) {
if ($key eq "\n" || $key eq "\r" || $key eq $ctrl{EOF}) { # e.g. Ctrl+D
print "\n";
last;
} elsif ($key eq $ctrl{INTERRUPT}) { # e.g. Ctrl+C
$password = undef;
last;
} elsif ($key eq $ctrl{ERASE}) {
if ($password ne '') {
chop $password;
print "\b \b";
}
} elsif ($key eq $ctrl{KILL} || $key eq $ctrl{ERASEWORD}) { # e.g. Ctrl+U, Ctrl+W
while ($password ne '') {
chop $password;
print "\b \b";
}
} else {
$password = $password . $key;
print "*";
}
}
ReadMode(0);
return $password;
}
sub config_has {
my ($name) = @_;
return defined $ephemeral_config{$name} || defined $personal_config{$name} || defined $global_config{$name};
}
sub get_config {
my ($name, $default_value) = @_;
return $ephemeral_config{$name} if defined $ephemeral_config{$name};
return $personal_config{$name} if defined $personal_config{$name};
return $global_config{$name} if defined $global_config{$name};
return $default_value;
}
sub migrate_config_option {
my ($config_ref, $old_name, $new_name) = @_;
if (exists $config_ref->{$old_name}) {
$config_ref->{$new_name} = $config_ref->{$old_name} unless exists $config_ref->{$new_name};
delete $config_ref->{$old_name};
}
}
sub read_config_file {
my ($filename) = @_;
open(my $config_fh, '<', $filename) or die "Error: Unable to open $filename for reading: $!\n";
my %config_hash = map { my @f = split(' ', $_, 2); $f[0] => $f[1] } grep(/^[^#]/, map { chomp; $_ } <$config_fh>);
close($config_fh);
migrate_config_option(\%config_hash, 'api-endpoint', 'api_endpoint');
migrate_config_option(\%config_hash, 'account-id', 'account_id');
migrate_config_option(\%config_hash, 'api-key', 'api_key');
return %config_hash;
}
sub write_config_file {
my ($filename, $config_ref) = @_;
sysopen(my $config_fh, $filename, O_WRONLY | O_TRUNC | O_CREAT, 0600) or die "Error: Unable to open $filename for writing: $!\n";
for my $param_name (keys %$config_ref) {
print $config_fh $param_name . ' ' . $config_ref->{$param_name} . "\n";
}
close($config_fh);
}
sub get_personal_config_path {
return $ENV{'SSLMATE_CONFIG'} if $ENV{'SSLMATE_CONFIG'};
return $ENV{'HOME'} . '/.sslmate' . ($config_profile ? "-$config_profile" : "") if $ENV{'HOME'};
die "Error: Neither \$SSLMATE_CONFIG nor \$HOME environment variables set.\n";
}
sub get_global_config_path {
return '/etc/sslmate' . ($config_profile ? "-$config_profile" : "") . '.conf';
}
sub load_config {
# Personal config
%personal_config = ();
my $personal_config_path = get_personal_config_path;
if (-e $personal_config_path) {
%personal_config = read_config_file($personal_config_path);
}
# Global config
%global_config = ();
my $global_config_path = get_global_config_path;
# global config file might be readable only by root, so only attempt
# to access if it's readable.
if (-r $global_config_path) {
%global_config = read_config_file($global_config_path);
}
}
sub save_config {
write_config_file(get_personal_config_path, \%personal_config);
}
sub is_linked {
return config_has('account_id') && config_has('api_key');
}
sub init_default_paths {
if (!config_has("key_directory") && !config_has("cert_directory")) {
if ($> == 0) {
my $default_directory = '/etc/sslmate' . ($config_profile ? "-$config_profile" : "");
if (!mkdir($default_directory, 0755)) {
die "Error: Unable to create $default_directory: $!\n" unless $!{EEXIST};
}
$global_config{'key_directory'} = $default_directory;
$global_config{'cert_directory'} = $default_directory;
}
}
unless (get_config('honor_umask', 'no') eq 'yes') {
umask 0022;
}
}
sub file_contents_are {
my ($filename, $contents) = @_;
open(my $fh, '<', $filename) or return 0;
my $actual_contents = do { local $/; <$fh> };
return $actual_contents eq $contents;
}
sub read_first_crt {
my ($fh) = @_;
my $crt = '';
while (defined(my $line = <$fh>)) {
chomp $line;
$crt .= $line;
$crt .= "\n";
last if $line eq '-----END CERTIFICATE-----';
}
return $crt;
}
sub make_openssl_req_cnf {
my ($dn) = @_;
my $tempfile = File::Temp->new();
print $tempfile <<EOF;
[ req ]
distinguished_name = req_distinguished_name
prompt = no
[ req_distinguished_name ]
EOF
for my $component (qw/C ST L O OU CN/) {
print $tempfile $component . " = " . $dn->{$component} . "\n" if defined $dn->{$component};
}
close $tempfile;
return $tempfile;
}
sub get_cert_paths {
my ($cn, $key_too) = @_;
my $key_directory = config_has("key_directory") ? get_config("key_directory") . "/" : "";
my $cert_directory = config_has("cert_directory") ? get_config("cert_directory") . "/" : "";
my $paths = {};
if ($key_too) {
$paths->{key_filename} = $key_directory . $cn . ".key";
}
$paths->{crt_filename} = $cert_directory . $cn . ".crt";
$paths->{chain_crt_filename} = $cert_directory . $cn . ".chain.crt";
$paths->{chained_crt_filename} = $cert_directory . $cn . ".chained.crt";
return $paths;
}
sub check_for_existing_files {
my @filenames = @_;
my $already_exists = 0;
for my $filename (@filenames) {
if (defined $filename && -e $filename) {
print STDERR "Error: a file named '$filename' already exists.\n";
$already_exists++;
}
}
if ($already_exists) {
die "Please move/remove " . ($already_exists == 1 ? "this file" : "these files") . (!config_has("key_directory") && !config_has("cert_directory") ? " or run sslmate from a different directory" : "") . ".\n";
}
}
sub open_key_file {
my ($filename, $overwrite) = @_;
my $flags = O_WRONLY | O_CREAT;
$flags |= O_EXCL unless $overwrite;
my $fh;
sysopen($fh, $filename, $flags, 0600)
or die "Error: unable to open '$filename' for writing: $!\n";
return $fh;
}
sub write_cert_files {
my ($paths, $new_key_filename, $crt, $chain) = @_;
# write .crt file
my $crt_file = File::Temp->new(DIR => dirname($paths->{crt_filename}), TEMPLATE => '.sslmate.XXXXXX');
chmod(0666 & ~umask, $crt_file);
print $crt_file $crt;
close $crt_file;
# write .chain.crt file
my $chain_crt_file = File::Temp->new(DIR => dirname($paths->{crt_filename}), TEMPLATE => '.sslmate.XXXXXX');
chmod(0666 & ~umask, $chain_crt_file);
print $chain_crt_file $chain;
close $chain_crt_file;
# write .chained.crt file
my $chained_crt_file = File::Temp->new(DIR => dirname($paths->{crt_filename}), TEMPLATE => '.sslmate.XXXXXX');
chmod(0666 & ~umask, $chained_crt_file);
print $chained_crt_file $crt;
print $chained_crt_file $chain;
close $chained_crt_file;
# Rename the new files on top of the old files:
if (defined $new_key_filename && $new_key_filename ne $paths->{key_filename}) {
rename($new_key_filename, $paths->{key_filename})
or die "Error: " . $paths->{key_filename} . ': ' . $! . "\n";
}
rename($crt_file->filename, $paths->{crt_filename})
or die "Error: " . $paths->{crt_filename} . ': ' . $! . "\n";
$crt_file->unlink_on_destroy(0);
rename($chain_crt_file->filename, $paths->{chain_crt_filename})
or die "Error: " . $paths->{chain_crt_filename} . ': ' . $! . "\n";
$chain_crt_file->unlink_on_destroy(0);
rename($chained_crt_file->filename, $paths->{chained_crt_filename})
or die "Error: " . $paths->{chained_crt_filename} . ': ' . $! . "\n";
$chained_crt_file->unlink_on_destroy(0);
}
sub qs_escape {
my ($str) = @_;
return uri_escape_utf8($str, '^A-Za-z0-9\-\._');
}
sub native_api_call {
my ($method, $command, $request_data) = @_;
$curl //= new_curl;
if ($method eq 'GET') {
$command .= "?$request_data" if $request_data;
$curl->setopt(WWW::Curl::Easy::CURLOPT_HTTPGET(), 1);
} elsif ($method eq 'POST') {
$curl->setopt(WWW::Curl::Easy::CURLOPT_POSTFIELDS(), $request_data);
$curl->setopt(WWW::Curl::Easy::CURLOPT_POSTFIELDSIZE(), length $request_data);
}
$curl->setopt(WWW::Curl::Easy::CURLOPT_URL(), (get_config('api_endpoint') // $API_ENDPOINT) . $command);
my $response_data = '';
open(my $response_fh, '>', \$response_data);
$curl->setopt(WWW::Curl::Easy::CURLOPT_WRITEDATA(), $response_fh);
my $result = $curl->perform;
close($response_fh);
if ($result != 0) {
print STDERR "Error: unable to contact SSLMate server: " . $curl->strerror($result) . "\n";
undef $curl;
return undef;
}
my $http_status = $curl->getinfo(WWW::Curl::Easy::CURLINFO_HTTP_CODE());
my $content_type = $curl->getinfo(WWW::Curl::Easy::CURLINFO_CONTENT_TYPE());
return ($http_status, $content_type, \$response_data);
}
sub escape_curl_param {
my ($param) = @_;
$param =~ s/\\/\\\\/g;
$param =~ s/\"/\\\"/g;
$param =~ s/\t/\\t/g;
$param =~ s/\n/\\n/g;
$param =~ s/\r/\\r/g;
$param =~ s/\v/\\v/g;
return $param;
}
sub decode_curl_error {
my ($exit_code) = @_;
return "Unable to resolve server address" if $exit_code == 6;
return "Unable to connect to server" if $exit_code == 7;
return "Timeout" if $exit_code == 28;
return "SSL handshake failed" if $exit_code == 35;
return "SSL certificate error" if $exit_code == 51;
return "SSL certificate cannot be authenticated" if $exit_code == 60;
return "curl exited with status $exit_code";
}
sub external_api_call {
my ($method, $command, $request_data) = @_;
local $SIG{PIPE} = 'IGNORE';
if ($method eq 'GET') {
$command .= "?$request_data" if $request_data;
}
my ($response_fh, $config_fh);
my $curl_pid = eval { open2($response_fh, $config_fh, 'curl', '-K', '-') };
die "Error: Unable to execute the 'curl' command - is curl installed?\n" unless defined($curl_pid);
print $config_fh "user-agent = \"" . escape_curl_param("SSLMate-external/$VERSION") . "\"\n";
print $config_fh "silent\n";
print $config_fh "include\n";
print $config_fh "url = \"" . escape_curl_param((get_config('api_endpoint') // $API_ENDPOINT) . $command) . "\"\n";
if ($method eq 'POST') {
print $config_fh "data = \"" . escape_curl_param($request_data) . "\"\n";
}
close($config_fh);
my ($http_status, $content_type, $response_data);
if (!eof($response_fh)) {
do {
# HTTP/1.1 200 OK
my $http_status_line = <$response_fh>;
$http_status_line =~ s/\r?\n$//;
(undef, $http_status, undef) = split(' ', $http_status_line);
# Content-Type: application/json
$content_type = undef;
while (defined(my $line = <$response_fh>)) {
$line =~ s/\r?\n$//;
last if $line eq ''; # end of headers
if ($line =~ /^Content-Type:\s*(.*)$/i) {
$content_type = $1;
}
}
} while ($http_status == 100);
$response_data = do { local $/; <$response_fh> };
}
close($response_fh);
waitpid($curl_pid, 0) or die "waitpid failed: $!";
if ($? != 0) {
if (WIFEXITED($?)) {
print STDERR "Error: unable to contact SSLMate server: " . decode_curl_error(WEXITSTATUS($?)) . "\n";
} else {
print STDERR "Error: unable to contact SSLMate server: curl terminated with status $?\n";
}
return undef;
}
if (not $http_status) {
print STDERR "Error: unable to contact SSLMate server: curl produced unexpected output\n";
return undef;
}
return ($http_status, $content_type, \$response_data);
}
sub api_call {
my ($method, $command, $request_data) = @_;
if (ref($request_data) eq 'HASH') {
# Convert into a query string
$request_data = join('&', map { defined($request_data->{$_}) ? qs_escape($_) . '=' . qs_escape($request_data->{$_}) : () } keys %$request_data);
}
my ($http_status, $content_type, $response_data) = $has_curl ?
native_api_call($method, $command, $request_data) :
external_api_call($method, $command, $request_data);
return undef unless defined($http_status);
$content_type //= '';
if ($content_type ne 'application/json') {
print STDERR "Error: received unexpected response from SSLMate server: response not JSON (content-type=$content_type; status=$http_status)\n";
return undef;
}
my $response_obj = eval { decode_json($$response_data) };
if (!defined($response_obj)) {
chomp $@;
print STDERR "Error: received malformed response from SSLMate server: $@\n";
return undef;
}
if (!defined($response_obj->{status})) {
print STDERR "Error: received invalid response from SSLMate server: no status field\n";
return undef;
}
return $response_obj;
}
sub openssl_genrsa {
my ($key_file, $nbits) = @_;
print STDERR "Generating private key... ";
STDERR->flush;
my $openssl_pid = fork;
die "Error: fork failed: $!" unless defined $openssl_pid;
if ($openssl_pid == 0) {
open(STDIN, '<', '/dev/null');
open(STDOUT, '>&', $key_file) or die "Error: dup failed: $!";
exec('openssl', 'genrsa', $nbits);
die "Error: Unable to run 'openssl genrsa' command: " . ($!{ENOENT} ? 'openssl command not found' : $!) . "\n";
}
waitpid($openssl_pid, 0) or die "waitpid failed: $!";
die "Error: 'openssl genrsa' command failed.\n" unless $? == 0;
print STDERR "Done.\n";
}
sub openssl_req {
my ($key_filename, $dn) = @_;
print STDERR "Generating CSR... ";
STDERR->flush;
my $openssl_req_cnf = make_openssl_req_cnf($dn);
pipe(my $openssl_reader, my $openssl_writer) or die "Error: pipe failed: $!";
my $openssl_pid = fork;
die "Error: fork failed: $!" unless defined $openssl_pid;
if ($openssl_pid == 0) {
open(STDIN, '<', '/dev/null');
open(STDOUT, '>&', $openssl_writer) or die "Error: dup failed: $!";
close($openssl_reader);
exec('openssl', 'req', '-new', '-key', $key_filename, '-config', $openssl_req_cnf->filename);
die "Error: Unable to run 'openssl req' command: " . ($!{ENOENT} ? 'openssl command not found' : $!) . "\n";
}
close($openssl_writer);
my $csr_data = do { local $/; <$openssl_reader> };
close($openssl_reader);
waitpid($openssl_pid, 0) or die "Error: waitpid failed: $!";
die "Error: 'openssl req' command failed - is $key_filename a valid key file?\n" unless $? == 0;
print STDERR "Done.\n";
return $csr_data;
}
sub extract_cn_from_crt {
my ($crt_filename) = @_;
pipe(my $openssl_reader, my $openssl_writer) or die "Error: pipe failed: $!";
my $openssl_pid = fork;
die "Error: fork failed: $!" unless defined $openssl_pid;
if ($openssl_pid == 0) {
open(STDIN, '<', '/dev/null');
open(STDOUT, '>&', $openssl_writer) or die "Error: dup failed: $!";
close($openssl_reader);
exec('openssl', 'x509', '-in', $crt_filename, '-noout', '-subject');
die "Error: Unable to run 'openssl x509' command: " . ($!{ENOENT} ? 'openssl command not found' : $!) . "\n";
}
close($openssl_writer);
my $cn = undef;
while (defined(my $line = <$openssl_reader>)) {
chomp $line;
if ($line =~ /^subject=\s*(.*\/)?CN=([^\/,]+)/) {
$cn = $2;
}
}
close($openssl_reader);
waitpid($openssl_pid, 0) or die "waitpid failed: $!";
die "Error: 'openssl x509' command failed - is $crt_filename a valid certificate file?\n" unless $? == 0;
return $cn;
}
sub extract_pubkey_from_key {
my ($key_filename) = @_;
pipe(my $openssl_reader, my $openssl_writer) or die "Error: pipe failed: $!";
my $openssl_pid = fork;
die "Error: fork failed: $!" unless defined $openssl_pid;
if ($openssl_pid == 0) {
open(STDIN, '<', '/dev/null');
open(STDOUT, '>&', $openssl_writer) or die "Error: dup failed: $!";
open(STDERR, '>', '/dev/null');
close($openssl_reader);
exec('openssl', 'rsa', '-in', $key_filename, '-pubout', '-outform', 'DER');
die "Error: Unable to run 'openssl rsa' command: " . ($!{ENOENT} ? 'openssl command not found' : $!) . "\n";
}
close($openssl_writer);
my $pubkey = do { local $/; <$openssl_reader> };
close($openssl_reader);
waitpid($openssl_pid, 0) or die "waitpid failed: $!";
die "Error: 'openssl rsa' command failed - is $key_filename a valid private key file?\n" unless $? == 0;
return $pubkey;
}
sub wait_for_cert {
my ($cert_instance_id) = @_;
my $start_time = time;
my $warn_after = $start_time + 180;
my $timeout_after = $start_time + 600;
my $warned = 0;
while (1) {
my $now = time;
my $poll = 0;
if ($now < $warn_after) {
$poll = $warn_after - $now;
} elsif ($now < $timeout_after) {
$poll = $timeout_after - $now;
}
$poll = 180 if $poll > 180; # upper bound of 180 seconds
my $response = api_call('GET', "/download/$cert_instance_id", { account_id => get_config('account_id'), api_key => get_config('api_key'), poll => $poll });
return unless defined $response; # TODO: repeat ? b/c this could be a timeout situation
if ($response->{status} eq 'success') {
return ($response->{crt}, $response->{chain});
} elsif ($response->{status} eq 'not_ready') {
my $now = time;
my $retry_after = $response->{retry_after};
if ($now < $warn_after) {
$retry_after = 1 if $retry_after < 1; # lower bound of 1 second
} elsif ($now < $timeout_after) {
if (not $warned) {
print STDERR "Sorry, your certificate isn't ready yet. I'll keep waiting, but if you'd rather do this later, you can hit Ctrl+C and we'll send you an email when it's ready.\n";
$warned = 1;
}
$retry_after = 10 if $retry_after < 10; # lower bound of 10 seconds
} else {
# Timed out
print STDERR "Sorry, your certificate still isn't ready. We'll send you an email when it's ready.\n";
return;
}
sleep($retry_after);
} elsif ($response->{status} eq 'error') {
print STDERR "Error: " . $response->{message} . "\n";
return;
} else {
print STDERR "Error: unknown response from server.\n";
return;
}
}
}
sub format_money {
my ($amount) = @_;
return sprintf("%.2f", $amount / 100);
}
sub prompt_for_approver_email {
my ($approver_emails) = @_;
my $num_emails = int(@$approver_emails);
my $i = 1;
for my $email (@$approver_emails) {
print "$i. $email\n";
$i++;
}
my $mesg = "Enter 1-$num_emails (or q to quit): ";
while (1) {
my $answer = prompt_user($mesg);
if ($answer eq 'q') {
return undef;
} elsif ($answer =~ /^\d+$/ and $answer >= 1 and $answer <= $num_emails) {
return $approver_emails->[$answer - 1];
} else {
print "That is not a number between 1 and $num_emails.\n";
}
}
}
sub prompt_for_order_confirmation {
my ($data) = @_;
print "\n";
print "============ Order summary ============\n";
print " Host Name: " . $data->{cn};
if ($data->{cn} =~ /^www\.(.*)$/) {
print " and $1";
}
print "\n";
if ($data->{years} == 1) {
print " Product: 1 Year " . ($data->{is_wildcard} ? "Wildcard SSL" : "Standard SSL") . "\n";
print " Price: " . format_money($data->{price}) . "\n";
} else {
print " Product: " . ($data->{is_wildcard} ? "Wildcard SSL" : "Standard SSL") . "\n";
print " Price: " . format_money($data->{price}) . " / year\n";
print " Years: " . $data->{years} . "\n";
}
if (defined $data->{auto_renew}) {
print " Auto-Renew: " . ($data->{auto_renew} ? "Yes" : "No") . "\n";
}
if (defined $data->{approver_email}) {
print "Approver Email: " . $data->{approver_email} . "\n";
}
print "\n";
print "=========== Payment details ===========\n";
if ($data->{amount_due}) {
print " Credit Card: " . $data->{cc_type} . " ending in " . $data->{cc_last4} . "\n";
}
if ($data->{coupon_discount}) {
print " Discount: " . format_money($data->{coupon_discount}) . " (USD)\n";
}
print " Amount Due: " . format_money($data->{amount_due}) . " (USD)\n";
print "\n";
while (1) {
my $answer = prompt_user('Press ENTER to confirm order (or q to quit): ');
if ($answer eq '') {
return 1;
} elsif ($answer eq 'q') {
return 0;
}
}
}
sub get_dn_from_server {
my ($cn) = @_;
my $response = api_call('GET', "/distinguished_name/$cn",
{ account_id => get_config('account_id'),
api_key => get_config('api_key') });
return undef unless defined $response;
if ($response->{status} eq 'success') {
return $response->{distinguished_name};
} elsif ($response->{status} eq 'error') {
print STDERR "Error: " . $response->{message} . "\n";
return undef;
} else {
print STDERR "Error: unknown response from server.\n";
return undef;
}
}
sub do_link {
my ($persistent) = @_;
print "If you don't have an account yet, visit https://sslmate.com/signup\n";
my $username = prompt_user("Enter your SSLMate username: ");
my $password = prompt_password("Enter your SSLMate password: ");
return 0 if not defined $password;
print "Linking account... ";
STDOUT->flush;
my $response = api_call('POST', '/link', { account_username => $username, account_password => $password });
return 0 if not defined $response;
if ($response->{status} eq 'success') {
if (not defined $response->{api_key} || not defined $response->{country_code}) {
print STDERR "Error: your account does not have contact details on file. Please visit https://sslmate.com/account to set your contact details.\n";
return 0;
}
if ($persistent) {
$personal_config{"account_id"} = $response->{account_id};
$personal_config{"api_key"} = $response->{api_key};
save_config;
} else {
$ephemeral_config{"account_id"} = $response->{account_id};
$ephemeral_config{"api_key"} = $response->{api_key};
}
print "Done.\n";
return 1;
} elsif ($response->{status} eq 'error') {
print STDERR "Error: " . $response->{message} . "\n";
return 0;
} else {
print STDERR "Error: unknown response from server.\n";
return 0;
}
}
sub command_link {
my @args = @_;
if (@args >= 1 && $args[0] eq "-?") {
print "Usage: sslmate link\n";
return 0;
} elsif (@args > 0) {
print STDERR "Error: sslmate link takes no arguments.\n";
print STDERR "Usage: sslmate link\n";
return 2;
}
load_config;
print STDERR "Note: sslmate has already been linked with an account.\nContinue to link it with a different account, or press Ctrl+C to exit.\n" if is_linked;
do_link(1) or return 1;
return 0;
}
sub do_wait_for_cert {
my ($response, $no_wait, $files, $new_key_filename) = @_;
print "You will soon receive an email at " . $response->{approver_email} . " from " . $response->{approval_from} . ". Follow the instructions in the email to verify your ownership of your domain.\n\n";
if ($no_wait) {
print "Once you've verified ownership, you will be able to download your certificate with the 'sslmate download' command.\n";
return 0;
} else {
print "Once you've verified ownership, your certificate will be automatically downloaded. If you'd rather do this later, press Ctrl+C and download your certificate with the 'sslmate download' command instead.\n\n";
}
print "Waiting for ownership confirmation...\n";
my ($crt, $chain_crt) = wait_for_cert($response->{cert_instance_id}) or exit 1;
$chain_crt //= '';
write_cert_files($files, $new_key_filename, $crt, $chain_crt);
print "\n";
print "Your certificate is ready for use!\n\n";
print " Private key file: " . $files->{key_filename} . "\n" if defined $new_key_filename;
print " Certificate file: " . $files->{crt_filename} . "\n";
print " Certificate chain file: " . $files->{chain_crt_filename} . "\n";
print "Certificate with chain file: " . $files->{chained_crt_filename} . "\n";
#print "\n";
#print "(" . $files->{chained_crt_filename} . " is the concatenation of " . $files->{crt_filename} . " and " . $files->{chain_crt_filename} . "; consult your program's documentation to determine whether you specify the certificate and chain in separate files or in one file.)\n";
}
sub do_buy {
my ($cn, $years, $force, $no_wait, $auto_renew, $coupon_code, $batch, $approver_email) = @_;
my $dn = get_dn_from_server($cn) or exit 1;
# Future TODO: support reusing key file if one already exists
my $files = get_cert_paths($cn, 1);
check_for_existing_files(@{$files}{qw{key_filename crt_filename chain_crt_filename chained_crt_filename}}) unless $force;
# Open the key file
$files->{key_file} = open_key_file($files->{key_filename}, $force);
my $exit_with_error = sub {
unlink($files->{key_filename});
exit 1;
};
# 1. Generate an RSA key
truncate($files->{key_file}, 0);
openssl_genrsa($files->{key_file}, 2048);
close($files->{key_file});
# 2. Generate the CSR
my $csr = openssl_req($files->{key_filename}, $dn);
# 3. Buy the certificate from SSLMate
my $request = { account_id => get_config('account_id'),
api_key => get_config('api_key'),
csr => $csr,
years => $years,
auto_renew => $auto_renew,
coupon_code => $coupon_code,
approver_email => $batch ? $approver_email : undef };
print STDERR "Submitting order...\n";
my $response = api_call('POST', '/buy', $request) or $exit_with_error->();
while (not($batch) && $response->{status} eq 'need_confirmation') {
if ($response->{currency} ne "USD") {
print STDERR "Error: this version of the sslmate command does not support non-USD currencies. Please download a new version as per the instructions at https://sslmate.com.\n";
$exit_with_error->();
}
if ($response->{cn_is_bare_domain}) {
my $www_cn = "www.$cn";
print STDERR "\n";
print STDERR "WARNING: This certificate will not be valid for $www_cn.\n";
print STDERR "Would you rather generate a certificate that will work with both $www_cn AND $cn?\n\n";
if (prompt_yesno) {
unlink($files->{key_filename});
return do_buy($www_cn, $years, $force, $no_wait, $auto_renew, $coupon_code, $batch, $approver_email);
}
}
unless (defined $approver_email) {
# Prompt user to choose an approver email and to confirm the order:
print "\n";
print "We need to send you an email to verify that you own this domain.\n";
print "Where should we send this email?\n";
print "\n";
$approver_email = prompt_for_approver_email($response->{approver_emails}) or $exit_with_error->();
}
prompt_for_order_confirmation($response) or $exit_with_error->();
# Repeat /buy call with confirmed price and approver email address
$request->{authorized_charge} = $response->{amount_due};
$request->{authorized_charge_currency} = $response->{currency};
$request->{approver_email} = $approver_email;
print STDERR "Placing order...\n";
$response = api_call('POST', '/buy', $request) or $exit_with_error->();
}
if ($response->{status} eq 'error') {
print STDERR "Error: " . $response->{message} . "\n";
$exit_with_error->();
} elsif ($response->{status} ne 'success') {
print STDERR "Error: unknown response from server\n";
$exit_with_error->();
}
print "Order complete.\n\n";
return do_wait_for_cert($response, $no_wait, $files, $files->{key_filename});
}
sub command_buy {
my @args = @_;
if (@args >= 1 && $args[0] eq "-?") {
print "Usage: sslmate buy [OPTIONS] HOSTNAME\n\n";
print "Example: sslmate buy www.example.com\n";
print " sslmate buy '*.example.com'\n";
print "\n";
print "Valid options:\n";
print " -f, --force overwrite existing files\n";
print " --auto-renew automatically renew this certificate before it expires\n";
print " --no-auto-renew don't automatically renew this certificate\n";
print " --batch don't prompt for confirmation\n";
print " --email=ADDRESS use the given approver email address\n";
print " --no-wait return immediately; don't wait for cert to be issued\n";
print " --coupon=CODE use the given coupon code for a discount\n";
return 0;
}
my $auto_renew = undef;
my $coupon_code = undef;
my $force = 0;
my $batch = 0;
my $approver_email = undef;
my $no_wait = 0;
while (@args >= 1) {
if ($args[0] eq "-f" || $args[0] eq "--force") {
$force = 1;
shift @args;
} elsif ($args[0] eq "--auto-renew") {
$auto_renew = 1;
shift @args;
} elsif ($args[0] eq "--no-auto-renew") {
$auto_renew = 0;
shift @args;
} elsif ($args[0] =~ /^--coupon=(.*)$/) {
$coupon_code = $1;
shift @args;
} elsif ($args[0] eq "--batch") {
$batch = 1;
shift @args;
} elsif ($args[0] =~ /^--email=(.*)$/) {
$approver_email = $1;
shift @args;
} elsif ($args[0] eq "--no-wait") {
$no_wait = 1;
shift @args;
} else {
last;
}
}
if (@args != 1 && @args != 2) {
print STDERR "Error: you must specify the hostname for the certificate.\n";
print STDERR "Example: sslmate buy www.example.com\n";
print STDERR " or: sslmate buy '*.example.com'\n";
print STDERR "See 'sslmate help buy' for help.\n";
return 2;