-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnshmailx.cpp
More file actions
3056 lines (2342 loc) · 76.2 KB
/
Copy pathnshmailx.cpp
File metadata and controls
3056 lines (2342 loc) · 76.2 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
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
/*
###########################################################################
# NashCom SMTP mail test/send tool (nshmailx) #
# Version 1.2.6 10.03.2026 #
# (C) Copyright Daniel Nashed/NashCom 2025-2026 #
# #
# This application can be used to troubleshoot and test SMTP connections. #
# #
# The application is based on OpenSSL and also show how to #
# #
# - STARTTLS connections via OpenSSL #
# - Send SMTP mail crafting the RFC821 and RFC822 part of a message #
# - Lookup MX records and pick the one with the lowest priority #
# - Create a simple MIME encoded mail with a base64 encoded attachment #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License. #
# You may obtain a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.#
# See the License for the specific language governing permissions and #
# limitations under the License. #
# #
# #
###########################################################################
*/
/*
Change History
0.9.1 04.01.2024
Add from phrase support (e.g. "John Doe" <jd@acme.com>)
0.9.2 05.01.2024
Add basic support for LibreSSL on MacOS
0.9.3 07.01.2024
Basic bsd-mailx compatibility
0.9.4 07.01.2024
More mailx compatibility and basic -cc and -bcc support
0.9.5 08.01.2024
Dump key and certificate information via OpenSSL code
0.9.6 20.02.2024
- Dump received and verified chain with verbose output
- New -pem option to dump certificate/key PEM data
0.9.7 09.03.2024
- Print OpenSSL Error
0.9.8 15.03.2024
- Add support for specifying a OpenSSL cipher string
0.9.9 04.07.2024
- New -trace option
1.0.0 20.07.2024
- Change MX lookup code to work also on Alpine
1.0.1 31.07.2024
- Add configuration file (/etc/nshmailx.cfg)
- Add -silent mode (only log errors)
- Set default mailer to "nshmailx"
1.0.2 28.09.2024
- Add handshake debugging
1.0.4 01.10.2024
- Add -NoTLS13 option
1.0.5 02.10.2024
- Dump TLS/SSL version and correct cipher information
1.0.6 27.05.2025
- Add bsd-mail option -a
- Makefile changes and Alpine build support
1.0.7 01.06.2025
- Add allowed recipients settings cfg and documentation
1.0.8 05.07.2025
- Add port option
1.0.9 12.07.2025
- Add options to send test mails
1.1.0 30.07.2025
- Moved to separate GitHub repository and standardized build & release with Alpine based GitHub build flow
1.2.0 08.12.2025
- Message-ID with timestamp
- Basic support for S/MIME
1.2.1 12.12.2025
- Support for -encrypt command
- New csv file for S/MIME keys and restricted recipients list
1.2.2 14.12.2025
- Basic support for SFTP put
- Source code restructuring (lib.cpp and new sftp.cpp)
1.2.3 14.12.2025
- SFTP hash print and validation support
- SFTP password options (env, file, prompt)
- SFTP more paranoid and early error checking
- SFTP don't overwrite local file on -sget
- SFTP performance improvements
- SFTP performance and size output in result
1.2.4 01.03.2026
- Make SFTP optional and remove dependency for libssh2 if compiled without SFTP
1.2.5 01.03.2026
- Improve EHLO response parsing to work correctly with STARTTLS logic
1.2.6 10.03.2026
- Improved status code return waiting for the right '2xx ' stauts code
1.2.7 10.0.2026
- Add Priority and Importance
*/
#define VERSION "1.2.7"
#define COPYRIGHT "Copyright 2024-2026, Nash!Com, Daniel Nashed"
/* C++ includes */
#include <regex>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <resolv.h>
#include <pwd.h>
#include <openssl/opensslv.h>
#include <openssl/bio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/evp.h>
#include <openssl/x509v3.h>
#include <openssl/cms.h>
#include <openssl/pem.h>
#ifdef WITH_SFTP_SUPPORT
#include <libssh2.h>
#endif
#ifdef LIBRESSL_VERSION_NUMBER
#else
#include <openssl/core_names.h>
#endif
#include "nshmailx.hpp"
#include "lib.hpp"
#include "sftp.hpp"
#include "testing.hpp"
#ifdef WITH_SFTP_SUPPORT
#include "sftp.hpp"
#endif
#define MAX_BUFFER_LEN 65535
#define MAX_STR 1024
#define CRLF "\r\n"
#define CR "\r"
#define LF "\n"
/* Globals */
BIO *g_pBio = NULL;
BIO *g_pBioSMIME = NULL;
SSL *g_pSSL = NULL;
SSL_CTX *g_pCtxSSL = NULL;
char g_ProgramName[] = "nshmailx";
char g_szConfigFile[] = "/etc/nshmailx.cfg";
char g_szBuffer[MAX_BUFFER_LEN+1] = {0};
char g_szErrorBuffer[4096] = {0};
char g_szRecipientFile[4096] = "/etc/nshmailx.csv";
char g_Delim = ',';
int g_Verbose = 0;
int g_Trace = 0;
int g_DumpPEM = 0;
int g_Port = 25;
size_t g_Options = 0;
bool g_bSilent = false;
char g_szMailer[MAX_STR] = "nshmailx";
char g_szFrom[MAX_STR] = {0};
char g_szFromName[MAX_STR] = {0};
char g_szHostname[MAX_STR] = {0};
char g_szSmtpServerAddress[MAX_STR] = {0};
char g_szCipherList[MAX_STR] = {0};
char g_szAllowedRecptsRegx[MAX_STR] = {0};
void PrintVersion()
{
fprintf (stderr, "\nNash!Com SMTP Mail Tool %s\n", VERSION);
fprintf (stderr, "%s\n", COPYRIGHT);
#ifdef WITH_SFTP_SUPPORT
fprintf (stderr, "LibSSH2 %s\n", LIBSSH2_VERSION);
#endif
fprintf (stderr, "%s\n", OpenSSL_version(OPENSSL_VERSION));
fprintf (stderr, "(Build on: %s)\n", OPENSSL_VERSION_TEXT);
}
void PrintHelpText (char *pszName)
{
PrintVersion ();
fprintf (stderr, "\nUsage: %s [Options]\n\n", pszName);
fprintf (stderr, "-server <FQDN/IP> SMTP server DNS name or IP (Can be a relay host. By default MX record of the recipient's domain is used)\n");
fprintf (stderr, "-host <FQDN> Hostname to send in EHLO (by default use server's hostname)\n");
fprintf (stderr, "-port <number> Port of SMTP server (Default: 25)\n");
fprintf (stderr, "-from <email> From address\n");
fprintf (stderr, "-name <real name> Name to add to the from address as a phrase\n");
fprintf (stderr, "-to <email> Send to recipient address\n");
fprintf (stderr, "-cc <email> Copy to recipient address\n");
fprintf (stderr, "-bcc <email> Blind copy to recipient address\n");
fprintf (stderr, "-subject <text> Subject of message\n");
fprintf (stderr, "-body <text> Body of message\n");
fprintf (stderr, "-file <filepath> File send as body (specify '-' to write stdin to the UTF-8 formatted body)\n");
fprintf (stderr, "-att <filepath> Attachment to send (specify '-' for attaching stdin to a file)\n");
fprintf (stderr, "-attname <filename> File name for file to attach\n");
fprintf (stderr, "-mailer <name> Mailer Name\n");
fprintf (stderr, "-high High message priority/importance\n");
fprintf (stderr, "-low Low message priority/importance\n");
fprintf (stderr, "-cipher <cipher list> OpenSSL cipher list string (colon separated) used for a connection\n");
fprintf (stderr, "-NoTLS Disable TLS/SSL\n");
fprintf (stderr, "-NoTLS13 Disable TLS 1.3\n");
fprintf (stderr, "-Verify Verify TLS certificate\n");
fprintf (stderr, "-v Verbose logging (specify twice for more verbose logging)\n");
fprintf (stderr, "-silent Only log errors to stderr\n");
fprintf (stderr, "-trace Show input and output with client/server tags)\n");
fprintf (stderr, "-pem Dump pem data with cert/key info (specify twice for PEM of certificate chain)\n");
fprintf (stderr, "-encrypt Encrypt message with S/MIME\n");
fprintf (stderr, "-smime S/MIME file with PEM or raw Base64 DER certificate\n");
fprintf (stderr, "-version Print full version including OpenSSL version\n");
fprintf (stderr, "--version Only print program version without any headers and newline\n");
fprintf (stderr, "\n");
fprintf (stderr, "-TestMessages Number of test messages to send\n");
fprintf (stderr, "-TestBodySize <bytes> Bytes to sent for each test message body\n");
fprintf (stderr, "-TestAttSize <bytes> Size of test attachment in bytes\n");
fprintf (stderr, "\n\n");
fprintf (stderr, "SFTP Options [Only supports user/password. For key authentication use scp.]\n\n");
fprintf (stderr, "-sput <host> SFTP Put (specify host name or IP).\n");
fprintf (stderr, "-sget <host> SFTP Get.(specify host name or IP).\n");
fprintf (stderr, "-user <username> SFTP user name\n");
fprintf (stderr, "-password <password> User password\n");
fprintf (stderr, "-password:env <var> Get user password from environment var\n");
fprintf (stderr, "-password:file <path> Get user password from file\n");
fprintf (stderr, "-password:promt Prompt for user password\n");
fprintf (stderr, "-local <filepath> Local file to sget/sput\n");
fprintf (stderr, "-remote <filepath> Remote file to sget/sput\n");
fprintf (stderr, "-hostkey <base64> SSH compatible expected host key in Base64 without trailing =\n");
fprintf (stderr, "-hostkey:env <var> Read SSH compatible expected host key from environment var (Base64 without trailing =)\n");
fprintf (stderr, "-hostkey:file Read SSH compatible expected host key from file (Base64 without trailing =)\n");
fprintf (stderr, "-sha Calculate SHA256 hash for upload/download\n");
fprintf (stderr, "-hash <expected hash> Hash to verify. Hash type is derived from string (SHA1, SHA256, SHA384, SHA512)\n");
fprintf (stderr, "\nNote: Also supports Linux BSD mailx command line sending options\n\n");
fprintf (stderr, "Configuration file: %s\n\n", g_szConfigFile);
fprintf (stderr, "from=<addr> Standard from address\n");
fprintf (stderr, "fromname=<addr> Standard from name\n");
fprintf (stderr, "mailer=<str> Mail agent\n");
fprintf (stderr, "hostname=<std> Override default hostname\n");
fprintf (stderr, "serveraddress=<addr> Set server address/relay host\n");
fprintf (stderr, "cipherlist=<list> OpenSSL cipher list string (colon separated) used for a connection\n");
fprintf (stderr, "rcptallowed=<regex> Regex expression to define allowed recipients. Or specify 'file' for only allow entries from -reptfile\n");
fprintf (stderr, "rcptfile=<file> File name of recipients file (default: %s)\n", g_szRecipientFile);
fprintf (stderr, "tls=0|1 Use TLS (enabled by default, can be disabled via tls=0\n");
fprintf (stderr, "notls13=0|1 Disable TLS 1.3\n");
fprintf (stderr, "verify=0|1 Verify certificate chain\n");
fprintf (stderr, "ecdsa=0|1 Use ECDSA instead of RSA\n");
fprintf (stderr, "utf8=0|1 Use UTF8\n");
fprintf (stderr, "silent=0|1 Run silent. Only log errors to stderr\n");
fprintf (stderr, "\n");
}
size_t RecvBuffer()
{
int ret = 0;
size_t readbytes = 0;
if (g_pSSL)
{
ret = SSL_read_ex (g_pSSL, g_szBuffer, MAX_BUFFER_LEN, &readbytes);
if (ret < 0)
readbytes = 0;
}
else
{
ret = BIO_read (g_pBio, g_szBuffer, MAX_BUFFER_LEN);
if (ret < 0)
readbytes = 0;
else
readbytes = ret;
}
if (readbytes < 0)
*g_szBuffer = '\0';
else
*(g_szBuffer+readbytes) = '\0';
if (g_Verbose > 1)
printf ("%s", g_szBuffer);
return readbytes;
}
int ResponseCode (const char *pszBuffer)
{
if (NULL == pszBuffer)
return -1;
if ('\0' == *pszBuffer)
return 0;
if (!isdigit(pszBuffer[0]) ||
!isdigit(pszBuffer[1]) ||
!isdigit(pszBuffer[2]))
return 0;
if (' ' != pszBuffer[3])
return 0;
return atoi (pszBuffer);
}
int GetReturnCode()
{
int rc = 0;
size_t len = 0;
char *p = NULL;
while (!rc)
{
len = RecvBuffer();
if (len <= 0)
return 1;
if (g_Trace)
printf("S:%s", g_szBuffer);
p = g_szBuffer;
while (*p)
{
rc = ResponseCode(p);
if (rc)
break;
p = strstr(p, "\r\n");
if (!p)
break;
p += 2;
}
}
if (rc >= 200 && rc < 400)
return 0;
return 1;
}
int SendBuffer (const char *pszBuffer)
{
int ret = 0;
size_t byteswritten = 0;
if (NULL == pszBuffer)
return 0;
if (g_Trace)
printf ("C:%s", pszBuffer);
if (g_pBioSMIME)
{
ret = BIO_puts (g_pBioSMIME, pszBuffer);
}
else if (g_pSSL)
{
ret = SSL_write_ex (g_pSSL, pszBuffer, strlen (pszBuffer), &byteswritten);
}
else
{
ret = BIO_puts (g_pBio, pszBuffer);
}
return ret;
}
int CheckLocalAvailableCiphers()
{
const char *pStr = NULL;
int priority = 0;
if (NULL == g_pSSL)
return 0;
if (g_Verbose > 1)
{
printf ("\nLocal available ciphers offered\n-------------------------------\n");
}
while (priority < 1000)
{
pStr = SSL_get_cipher_list (g_pSSL, priority);
if (NULL == pStr)
break;
if (g_Verbose > 1)
printf ("%s\n", pStr);
priority++;
}
if (g_Verbose > 1)
{
printf ("\n");
}
return priority;
}
int CopyFromToBio (BIO *pBioIn, BIO *pBioOut)
{
int readbytes = 0;
int writebytes = 0;
if (!pBioIn || !pBioOut)
return 0;
while (1)
{
readbytes = BIO_read(pBioIn, g_szBuffer, sizeof(g_szBuffer));
if (readbytes <= 0)
break; /* EOF or no more data */
writebytes = BIO_write(pBioOut, g_szBuffer, readbytes);
if (writebytes != readbytes)
return 0; /* write failure */
}
return 1; /* success */
}
size_t GetMxRecord (const char *pszDomain, size_t MaxBuffer, char *retpszBuffer, int *retpPriority)
{
unsigned char Buffer[32000] = {0};
char Result[1024] = {0};
int LowestPriority = 0;
int Priority = 0;
int ret = 0;
int len = 0;
int count = 0;
int found = 0;
int i = 0;
ns_msg nsMsg = {0};
ns_rr rr = {{0}};
if (MaxBuffer && retpszBuffer)
*retpszBuffer = '\0';
if (retpPriority)
*retpPriority = 0;
ret = res_init ();
if (ret)
{
LogError ("error initializing resolver");
goto Done;
}
len = res_query (pszDomain, ns_c_in, ns_t_mx, Buffer, sizeof(Buffer));
if (len <= 0)
{
LogError ("DNS did not return any MX");
goto Done;
}
ret = ns_initparse (Buffer, len, &nsMsg);
if (ret)
{
LogError ("Cannot init NS parser");
goto Done;
}
count = ns_msg_count (nsMsg, ns_s_an);
for (i=0; i<count; i++)
{
ret = ns_parserr (&nsMsg, ns_s_an, i, &rr);
if (ret)
{
LogError ("Cannot parse NS result");
goto Done;
}
Priority = ns_get16 (ns_rr_rdata (rr));
dn_expand (ns_msg_base (nsMsg), ns_msg_base (nsMsg) + ns_msg_size (nsMsg), ns_rr_rdata (rr) + NS_INT16SZ, Result, sizeof(Result));
if (g_Verbose)
printf ("%02d MX: [%s]\n", Priority, Result);
if ((0 == LowestPriority) || (Priority < LowestPriority))
{
if (MaxBuffer && retpszBuffer)
{
snprintf (retpszBuffer, MaxBuffer, "%s", Result);
}
if (retpPriority)
*retpPriority = Priority;
LowestPriority = Priority;
}
found++;
} /* for */
Done:
return found;
}
#ifdef LIBRESSL_VERSION_NUMBER
/* LibreSSL isn't the same as OpenSSL and would need more work to provide the same functionality.
The recommended target environment on MacOS is statically linked OpenSSL.
The basic functionality of nshmailx works on LibreSSL as well.
But specific TLS/SSL session information is not checked on LibreSSL.
The following is a basic routine to dump the Cipher at least.
*/
int LogChainInfos (SSL *pSSL)
{
int ret = 0;
X509 *pCert = NULL;
return ret;
}
int LogSSLInfos (SSL *pSSL)
{
const char *pStr = NULL;
if (NULL == pSSL)
goto Done;
pStr = SSL_get_version (pSSL);
if (pStr)
printf("TLS version: %s\n", pStr);
/* For some reason LibreSSL does always return TLSv1/SSLv3. But the connection is still a TLS V1.2 connection */
pStr = SSL_get_cipher_version (pSSL);
if (pStr)
printf ("TLS Cipher Version: [%s]\n", pStr);
pStr = SSL_get_cipher (pSSL);
if (pStr)
printf ("TLS Cipher Version: [%s]\n", pStr);
Done:
return 0;
}
#else
int GetX509Names (const X509 *pCert, int nid, int type, int RetBufferLen, char *pszRetBuffer)
{
GENERAL_NAMES *pNames = NULL;
GENERAL_NAME *pEntry = NULL;
unsigned char *pUtf8 = NULL;
char *pBuffer = pszRetBuffer;
int LenUtf8 = 0;
int LenSan = 0;
int CountSan = 0;
int i = 0;
int count = 0;
if (NULL == pszRetBuffer)
return 0;
if (0 == RetBufferLen)
return 0;
*pszRetBuffer = '\0';
if (!pCert)
goto Done;
pNames = (GENERAL_NAMES *) X509_get_ext_d2i (pCert, nid, NULL, NULL);
if (NULL == pNames)
{
goto Done;
}
count = sk_GENERAL_NAME_num (pNames);
if (0 == count)
goto Done;
for( i=0; i<count; ++i )
{
pEntry = sk_GENERAL_NAME_value (pNames, i);
if (!pEntry)
{
continue;
}
if (type == pEntry->type)
{
LenUtf8 = 0;
LenSan = -1;
pUtf8 = NULL;
LenUtf8 = ASN1_STRING_to_UTF8 (&pUtf8, pEntry->d.dNSName);
if (pUtf8)
LenSan = (int) strlen((const char*)pUtf8);
if (LenUtf8 != LenSan)
{
LogError ("ASN1_STRING as incorrect size");
goto Done;
}
if (pUtf8 && LenUtf8 && LenSan && (LenUtf8 == LenSan))
{
if (pBuffer - pszRetBuffer + LenSan + 2 >= RetBufferLen)
{
goto Done;
}
if (CountSan)
{
*pBuffer++ = ',';
*pBuffer++ = ' ';
}
memcpy (pBuffer, pUtf8, LenSan);
pBuffer += LenSan;
*pBuffer = '\0'; /* always terminate buffer */
CountSan++;
}
if (pUtf8)
{
OPENSSL_free (pUtf8);
pUtf8 = NULL;
}
}
} /* for */
Done:
if (pNames)
GENERAL_NAMES_free (pNames);
if (pUtf8)
OPENSSL_free (pUtf8);
return CountSan;
}
#define X509_GET_NOT_BEFORE 1
#define X509_GET_NOT_AFTER 2
int AsnTimeGetDate (const ASN1_TIME *pTM, int wRetBufferLen, char *pszRetBuffer, struct tm *pretTM)
{
struct tm tTime = {0};
if (pszRetBuffer && wRetBufferLen)
*pszRetBuffer = '\0';
if (pretTM)
memset (pretTM, 0, sizeof (struct tm));
if (pTM)
{
if (0 == ASN1_TIME_to_tm (pTM, &tTime))
goto Done;
if (pretTM)
{
memcpy (pretTM, &tTime, sizeof (struct tm));
}
if (pszRetBuffer && wRetBufferLen)
{
snprintf (pszRetBuffer, wRetBufferLen, "%04u.%02u.%02u %02u:%02u:%02u",
tTime.tm_year+1900,
tTime.tm_mon+1,
tTime.tm_mday,
tTime.tm_hour,
tTime.tm_min,
tTime.tm_sec);
}
}
Done:
return 0;
}
int X509GetDate (const X509 *pX509, int NameType, int wRetBufferLen, char *pszRetBuffer, struct tm *pretTM)
{
ASN1_TIME const *pTM = NULL;
if (pszRetBuffer && wRetBufferLen)
*pszRetBuffer = '\0';
if (pretTM)
memset (pretTM, 0, sizeof (struct tm));
switch (NameType)
{
case X509_GET_NOT_BEFORE:
pTM = X509_get0_notBefore (pX509);
break;
case X509_GET_NOT_AFTER:
pTM = X509_get0_notAfter (pX509);
break;
default:
return 0;
} /* switch */
AsnTimeGetDate (pTM, wRetBufferLen, pszRetBuffer, pretTM);
return 0;
}
int LogKeyInfos (const char *pszHeader, EVP_PKEY *pKey, X509 *pCert, bool bDumpPEM)
{
int ret = 0;
int KeyType = 0;
int Bits = 0;
size_t len = 0;
char szBuffer [1024] = {0};
if (NULL == pszHeader)
return 0;
/* If no key is specified, get public key from cert */
if (NULL == pKey)
{
if (NULL == pCert)
goto Done;
pKey = X509_get0_pubkey (pCert); /* Don't free the key returned from this call! */
if (NULL == pKey)
goto Done;
}
KeyType = EVP_PKEY_base_id (pKey);
if (0 == KeyType)
goto Done;
Bits = EVP_PKEY_bits (pKey);
switch (KeyType)
{
case NID_ED25519:
printf ("%s: Ed25519 %d bit\n", pszHeader, Bits);
break;
case NID_ED448:
printf ("%s: Ed448 %d bit\n", pszHeader, Bits);
break;
case NID_X25519:
printf ("%s: X25519 %d bit\n", pszHeader, Bits);
break;
case NID_X448:
printf ("%s: X448 %d bit\n", pszHeader, Bits);
break;
case EVP_PKEY_RSA:
printf ("%s: RSA %d bit\n", pszHeader, Bits);
break;
case EVP_PKEY_RSA_PSS:
printf ("%s: RSA PSS %d bit\n", pszHeader, Bits);
break;
case EVP_PKEY_EC:
ret = EVP_PKEY_get_utf8_string_param (pKey, OSSL_PKEY_PARAM_GROUP_NAME, szBuffer, sizeof (szBuffer), &len);
if (ret)
printf ("%s: ECDSA %s\n", pszHeader, szBuffer);
break;
default:
printf ("%s: Unknown key type %d\n", pszHeader, KeyType);
break;
} /* switch */
if (bDumpPEM)
{
printf ("\n");
PEM_write_PUBKEY (stdout, pKey);
}
printf ("\n");
Done:
return 0;
}
int LogCertInfos (const char *pszHeader, const X509 *pCert, bool bDumpPEM)
{
int ret = 0;
const char *pStr = NULL;
char szBuffer [10240] = {0};
if (NULL == pszHeader)
return 0;
printf ("--- %s ---\n", pszHeader);
if (NULL == pCert)
return 0;
GetX509Names (pCert, NID_subject_alt_name, GEN_DNS, sizeof(szBuffer)-1, szBuffer);
if (*szBuffer)
printf ("SAN : %s\n", szBuffer);
pStr = X509_NAME_oneline (X509_get_subject_name (pCert), szBuffer, sizeof (szBuffer)-1);
if (pStr)
printf ("Subject : %s\n", szBuffer);
pStr = X509_NAME_oneline (X509_get_issuer_name (pCert), szBuffer, sizeof (szBuffer)-1);
if (pStr)
printf ("Issuer : %s\n", szBuffer);
X509GetDate (pCert, X509_GET_NOT_BEFORE, sizeof (szBuffer), szBuffer, NULL);
if (*szBuffer)
printf ("Not before : %s\n", szBuffer);
X509GetDate (pCert, X509_GET_NOT_AFTER, sizeof (szBuffer), szBuffer, NULL);
if (*szBuffer)
printf ("Not after : %s\n", szBuffer);
/* Dump the leaf certificate */
if (bDumpPEM)
{
printf ("\n");
PEM_write_X509 (stdout, pCert);
}
printf ("\n");
return ret;
}
int LogChain (const char *pszHeader, STACK_OF(X509) *pChain)
{
int ret = 0;
int i = 0;
int count = 0;
X509 *pCert = NULL;
char szBuffer [1024] = {0};
if (NULL == pszHeader)
return 0;
if (NULL == pChain)
return 0;
count = sk_X509_num (pChain);
if (g_Verbose < 1)
{
printf ("%s(%d)\n", pszHeader, count);
return 0;
}
for (i=0; i<count; ++i)
{
snprintf (szBuffer, sizeof (szBuffer), "%s #%d", pszHeader, i);
pCert = sk_X509_value (pChain, i);
LogCertInfos (szBuffer, pCert, g_DumpPEM > 1 ? true : false);
}
return ret;
}
int LogChainInfos (SSL *pSSL)
{
int ret = 0;
STACK_OF(X509) *pChain;
if (NULL == pSSL)
return 0;
pChain = SSL_get_peer_cert_chain (pSSL);
LogChain ("Received Chain", pChain);
pChain = SSL_get0_verified_chain (pSSL);
LogChain ("Verified Chain", pChain);
return ret;
}
int LogSSLInfos (SSL *pSSL)