1 /*
2  *  SSL client for SMTP servers
3  *
4  *  Copyright The Mbed TLS Contributors
5  *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
6  */
7 
8 /* Enable definition of gethostname() even when compiling with -std=c99. Must
9  * be set before mbedtls_config.h, which pulls in glibc's features.h indirectly.
10  * Harmless on other platforms. */
11 
12 #define _POSIX_C_SOURCE 200112L
13 #define _XOPEN_SOURCE 600
14 #define MBEDTLS_DECLARE_PRIVATE_IDENTIFIERS
15 
16 
17 #include "mbedtls/build_info.h"
18 
19 #include "mbedtls/platform.h"
20 
21 #if !defined(MBEDTLS_BIGNUM_C) || !defined(MBEDTLS_ENTROPY_C) ||  \
22     !defined(MBEDTLS_SSL_TLS_C) || !defined(MBEDTLS_SSL_CLI_C) || \
23     !defined(MBEDTLS_NET_C) || !defined(MBEDTLS_RSA_C) ||         \
24     !defined(MBEDTLS_CTR_DRBG_C) || !defined(MBEDTLS_X509_CRT_PARSE_C) || \
25     !defined(MBEDTLS_FS_IO)
main(void)26 int main(void)
27 {
28     mbedtls_printf("MBEDTLS_BIGNUM_C and/or MBEDTLS_ENTROPY_C and/or "
29                    "MBEDTLS_SSL_TLS_C and/or MBEDTLS_SSL_CLI_C and/or "
30                    "MBEDTLS_NET_C and/or MBEDTLS_RSA_C and/or "
31                    "MBEDTLS_CTR_DRBG_C and/or MBEDTLS_X509_CRT_PARSE_C "
32                    "not defined.\n");
33     mbedtls_exit(0);
34 }
35 #else
36 
37 #include "mbedtls/base64.h"
38 #include "mbedtls/error.h"
39 #include "mbedtls/net_sockets.h"
40 #include "mbedtls/ssl.h"
41 #include "mbedtls/entropy.h"
42 #include "mbedtls/ctr_drbg.h"
43 #include "test/certs.h"
44 #include "mbedtls/x509.h"
45 
46 #include <stdlib.h>
47 #include <string.h>
48 
49 #if !defined(_MSC_VER) || defined(EFIX64) || defined(EFI32)
50 #include <unistd.h>
51 #else
52 #include <io.h>
53 #endif
54 
55 #if defined(_WIN32) || defined(_WIN32_WCE)
56 #include <winsock2.h>
57 #include <windows.h>
58 
59 #if defined(_MSC_VER)
60 #if defined(_WIN32_WCE)
61 #pragma comment( lib, "ws2.lib" )
62 #else
63 #pragma comment( lib, "ws2_32.lib" )
64 #endif
65 #endif /* _MSC_VER */
66 #endif
67 
68 #define DFL_SERVER_NAME         "localhost"
69 #define DFL_SERVER_PORT         "465"
70 #define DFL_USER_NAME           "user"
71 #define DFL_USER_PWD            "password"
72 #define DFL_MAIL_FROM           ""
73 #define DFL_MAIL_TO             ""
74 #define DFL_DEBUG_LEVEL         0
75 #define DFL_CA_FILE             ""
76 #define DFL_CRT_FILE            ""
77 #define DFL_KEY_FILE            ""
78 #define DFL_FORCE_CIPHER        0
79 #define DFL_MODE                0
80 #define DFL_AUTHENTICATION      0
81 
82 #define MODE_SSL_TLS            0
83 #define MODE_STARTTLS           0
84 
85 #if defined(MBEDTLS_BASE64_C)
86 #define USAGE_AUTH \
87     "    authentication=%%d   default: 0 (disabled)\n"          \
88     "    user_name=%%s        default: \"" DFL_USER_NAME "\"\n" \
89                                                          "    user_pwd=%%s         default: \"" \
90     DFL_USER_PWD "\"\n"
91 #else
92 #define USAGE_AUTH \
93     "    authentication options disabled. (Require MBEDTLS_BASE64_C)\n"
94 #endif /* MBEDTLS_BASE64_C */
95 
96 #if defined(MBEDTLS_FS_IO)
97 #define USAGE_IO \
98     "    ca_file=%%s          default: \"\" (pre-loaded)\n" \
99     "    crt_file=%%s         default: \"\" (pre-loaded)\n" \
100     "    key_file=%%s         default: \"\" (pre-loaded)\n"
101 #else
102 #define USAGE_IO \
103     "    No file operations available (MBEDTLS_FS_IO not defined)\n"
104 #endif /* MBEDTLS_FS_IO */
105 
106 #define USAGE \
107     "\n usage: ssl_mail_client param=<>...\n"                 \
108     "\n acceptable parameters:\n"                             \
109     "    server_name=%%s      default: " DFL_SERVER_NAME "\n" \
110                                                          "    server_port=%%d      default: " \
111     DFL_SERVER_PORT "\n" \
112                     "    debug_level=%%d      default: 0 (disabled)\n"        \
113                     "    mode=%%d             default: 0 (SSL/TLS) (1 for STARTTLS)\n"  \
114     USAGE_AUTH                                                \
115     "    mail_from=%%s        default: \"\"\n"                \
116     "    mail_to=%%s          default: \"\"\n"                \
117     USAGE_IO                                                  \
118     "    force_ciphersuite=<name>    default: all enabled\n"  \
119     " acceptable ciphersuite names:\n"
120 
121 
122 /*
123  * global options
124  */
125 struct options {
126     const char *server_name;    /* hostname of the server (client only)     */
127     const char *server_port;    /* port on which the ssl service runs       */
128     int debug_level;            /* level of debugging                       */
129     int authentication;         /* if authentication is required            */
130     int mode;                   /* SSL/TLS (0) or STARTTLS (1)              */
131     const char *user_name;      /* username to use for authentication       */
132     const char *user_pwd;       /* password to use for authentication       */
133     const char *mail_from;      /* E-Mail address to use as sender          */
134     const char *mail_to;        /* E-Mail address to use as recipient       */
135     const char *ca_file;        /* the file with the CA certificate(s)      */
136     const char *crt_file;       /* the file with the client certificate     */
137     const char *key_file;       /* the file with the client key             */
138     int force_ciphersuite[2];   /* protocol/ciphersuite to use, or all      */
139 } opt;
140 
my_debug(void * ctx,int level,const char * file,int line,const char * str)141 static void my_debug(void *ctx, int level,
142                      const char *file, int line,
143                      const char *str)
144 {
145     ((void) level);
146 
147     mbedtls_fprintf((FILE *) ctx, "%s:%04d: %s", file, line, str);
148     fflush((FILE *) ctx);
149 }
150 
do_handshake(mbedtls_ssl_context * ssl)151 static int do_handshake(mbedtls_ssl_context *ssl)
152 {
153     int ret;
154     uint32_t flags;
155     unsigned char buf[1024];
156     memset(buf, 0, 1024);
157 
158     /*
159      * 4. Handshake
160      */
161     mbedtls_printf("  . Performing the SSL/TLS handshake...");
162     fflush(stdout);
163 
164     while ((ret = mbedtls_ssl_handshake(ssl)) != 0) {
165         if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
166 #if defined(MBEDTLS_ERROR_C)
167             mbedtls_strerror(ret, (char *) buf, 1024);
168 #endif
169             mbedtls_printf(" failed\n  ! mbedtls_ssl_handshake returned %d: %s\n\n", ret, buf);
170             return -1;
171         }
172     }
173 
174     mbedtls_printf(" ok\n    [ Ciphersuite is %s ]\n",
175                    mbedtls_ssl_get_ciphersuite(ssl));
176 
177     /*
178      * 5. Verify the server certificate
179      */
180     mbedtls_printf("  . Verifying peer X.509 certificate...");
181 
182     /* In real life, we probably want to bail out when ret != 0 */
183     if ((flags = mbedtls_ssl_get_verify_result(ssl)) != 0) {
184 #if !defined(MBEDTLS_X509_REMOVE_INFO)
185         char vrfy_buf[512];
186 #endif
187 
188         mbedtls_printf(" failed\n");
189 
190 #if !defined(MBEDTLS_X509_REMOVE_INFO)
191         mbedtls_x509_crt_verify_info(vrfy_buf, sizeof(vrfy_buf), "  ! ", flags);
192 
193         mbedtls_printf("%s\n", vrfy_buf);
194 #endif
195     } else {
196         mbedtls_printf(" ok\n");
197     }
198 
199 #if !defined(MBEDTLS_X509_REMOVE_INFO)
200     mbedtls_printf("  . Peer certificate information    ...\n");
201     mbedtls_x509_crt_info((char *) buf, sizeof(buf) - 1, "      ",
202                           mbedtls_ssl_get_peer_cert(ssl));
203     mbedtls_printf("%s\n", buf);
204 #endif
205 
206     return 0;
207 }
208 
write_ssl_data(mbedtls_ssl_context * ssl,unsigned char * buf,size_t len)209 static int write_ssl_data(mbedtls_ssl_context *ssl, unsigned char *buf, size_t len)
210 {
211     int ret;
212 
213     mbedtls_printf("\n%s", buf);
214     while (len && (ret = mbedtls_ssl_write(ssl, buf, len)) <= 0) {
215         if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
216             mbedtls_printf(" failed\n  ! mbedtls_ssl_write returned %d\n\n", ret);
217             return -1;
218         }
219     }
220 
221     return 0;
222 }
223 
write_ssl_and_get_response(mbedtls_ssl_context * ssl,unsigned char * buf,size_t len)224 static int write_ssl_and_get_response(mbedtls_ssl_context *ssl, unsigned char *buf, size_t len)
225 {
226     int ret;
227     unsigned char data[128];
228     char code[4];
229     size_t i, idx = 0;
230 
231     mbedtls_printf("\n%s", buf);
232     while (len && (ret = mbedtls_ssl_write(ssl, buf, len)) <= 0) {
233         if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
234             mbedtls_printf(" failed\n  ! mbedtls_ssl_write returned %d\n\n", ret);
235             return -1;
236         }
237     }
238 
239     do {
240         len = sizeof(data) - 1;
241         memset(data, 0, sizeof(data));
242         ret = mbedtls_ssl_read(ssl, data, len);
243 
244         if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
245             continue;
246         }
247 
248         if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
249             return -1;
250         }
251 
252         if (ret <= 0) {
253             mbedtls_printf("failed\n  ! mbedtls_ssl_read returned %d\n\n", ret);
254             return -1;
255         }
256 
257         mbedtls_printf("\n%s", data);
258         len = ret;
259         for (i = 0; i < len; i++) {
260             if (data[i] != '\n') {
261                 if (idx < 4) {
262                     code[idx++] = data[i];
263                 }
264                 continue;
265             }
266 
267             if (idx == 4 && code[0] >= '0' && code[0] <= '9' && code[3] == ' ') {
268                 code[3] = '\0';
269                 return atoi(code);
270             }
271 
272             idx = 0;
273         }
274     } while (1);
275 }
276 
write_and_get_response(mbedtls_net_context * sock_fd,unsigned char * buf,size_t len)277 static int write_and_get_response(mbedtls_net_context *sock_fd, unsigned char *buf, size_t len)
278 {
279     int ret;
280     unsigned char data[128];
281     char code[4];
282     size_t i, idx = 0;
283 
284     mbedtls_printf("\n%s", buf);
285     if (len && (ret = mbedtls_net_send(sock_fd, buf, len)) <= 0) {
286         mbedtls_printf(" failed\n  ! mbedtls_net_send returned %d\n\n", ret);
287         return -1;
288     }
289 
290     do {
291         len = sizeof(data) - 1;
292         memset(data, 0, sizeof(data));
293         ret = mbedtls_net_recv(sock_fd, data, len);
294 
295         if (ret <= 0) {
296             mbedtls_printf("failed\n  ! mbedtls_net_recv returned %d\n\n", ret);
297             return -1;
298         }
299 
300         data[len] = '\0';
301         mbedtls_printf("\n%s", data);
302         len = ret;
303         for (i = 0; i < len; i++) {
304             if (data[i] != '\n') {
305                 if (idx < 4) {
306                     code[idx++] = data[i];
307                 }
308                 continue;
309             }
310 
311             if (idx == 4 && code[0] >= '0' && code[0] <= '9' && code[3] == ' ') {
312                 code[3] = '\0';
313                 return atoi(code);
314             }
315 
316             idx = 0;
317         }
318     } while (1);
319 }
320 
main(int argc,char * argv[])321 int main(int argc, char *argv[])
322 {
323     int ret = 1, len;
324     int exit_code = MBEDTLS_EXIT_FAILURE;
325     mbedtls_net_context server_fd;
326 #if defined(MBEDTLS_BASE64_C)
327     unsigned char base[1024];
328     /* buf is used as the destination buffer for printing base with the format:
329      * "%s\r\n". Hence, the size of buf should be at least the size of base
330      * plus 2 bytes for the \r and \n characters.
331      */
332     unsigned char buf[sizeof(base) + 2];
333 #else
334     unsigned char buf[1024];
335 #endif
336     char hostname[32];
337     const char *pers = "ssl_mail_client";
338 
339     mbedtls_entropy_context entropy;
340     mbedtls_ctr_drbg_context ctr_drbg;
341     mbedtls_ssl_context ssl;
342     mbedtls_ssl_config conf;
343     mbedtls_x509_crt cacert;
344     mbedtls_x509_crt clicert;
345     mbedtls_pk_context pkey;
346     int i;
347     size_t n;
348     char *p, *q;
349     const int *list;
350 
351     /*
352      * Make sure memory references are valid in case we exit early.
353      */
354     mbedtls_net_init(&server_fd);
355     mbedtls_ssl_init(&ssl);
356     mbedtls_ssl_config_init(&conf);
357     memset(&buf, 0, sizeof(buf));
358     mbedtls_x509_crt_init(&cacert);
359     mbedtls_x509_crt_init(&clicert);
360     mbedtls_pk_init(&pkey);
361     mbedtls_ctr_drbg_init(&ctr_drbg);
362     mbedtls_entropy_init(&entropy);
363 
364     psa_status_t status = psa_crypto_init();
365     if (status != PSA_SUCCESS) {
366         mbedtls_fprintf(stderr, "Failed to initialize PSA Crypto implementation: %d\n",
367                         (int) status);
368         goto exit;
369     }
370 
371     if (argc < 2) {
372 usage:
373         mbedtls_printf(USAGE);
374 
375         list = mbedtls_ssl_list_ciphersuites();
376         while (*list) {
377             mbedtls_printf("    %s\n", mbedtls_ssl_get_ciphersuite_name(*list));
378             list++;
379         }
380         mbedtls_printf("\n");
381         goto exit;
382     }
383 
384     opt.server_name         = DFL_SERVER_NAME;
385     opt.server_port         = DFL_SERVER_PORT;
386     opt.debug_level         = DFL_DEBUG_LEVEL;
387     opt.authentication      = DFL_AUTHENTICATION;
388     opt.mode                = DFL_MODE;
389     opt.user_name           = DFL_USER_NAME;
390     opt.user_pwd            = DFL_USER_PWD;
391     opt.mail_from           = DFL_MAIL_FROM;
392     opt.mail_to             = DFL_MAIL_TO;
393     opt.ca_file             = DFL_CA_FILE;
394     opt.crt_file            = DFL_CRT_FILE;
395     opt.key_file            = DFL_KEY_FILE;
396     opt.force_ciphersuite[0] = DFL_FORCE_CIPHER;
397 
398     for (i = 1; i < argc; i++) {
399         p = argv[i];
400         if ((q = strchr(p, '=')) == NULL) {
401             goto usage;
402         }
403         *q++ = '\0';
404 
405         if (strcmp(p, "server_name") == 0) {
406             opt.server_name = q;
407         } else if (strcmp(p, "server_port") == 0) {
408             opt.server_port = q;
409         } else if (strcmp(p, "debug_level") == 0) {
410             opt.debug_level = atoi(q);
411             if (opt.debug_level < 0 || opt.debug_level > 65535) {
412                 goto usage;
413             }
414         } else if (strcmp(p, "authentication") == 0) {
415             opt.authentication = atoi(q);
416             if (opt.authentication < 0 || opt.authentication > 1) {
417                 goto usage;
418             }
419         } else if (strcmp(p, "mode") == 0) {
420             opt.mode = atoi(q);
421             if (opt.mode < 0 || opt.mode > 1) {
422                 goto usage;
423             }
424         } else if (strcmp(p, "user_name") == 0) {
425             opt.user_name = q;
426         } else if (strcmp(p, "user_pwd") == 0) {
427             opt.user_pwd = q;
428         } else if (strcmp(p, "mail_from") == 0) {
429             opt.mail_from = q;
430         } else if (strcmp(p, "mail_to") == 0) {
431             opt.mail_to = q;
432         } else if (strcmp(p, "ca_file") == 0) {
433             opt.ca_file = q;
434         } else if (strcmp(p, "crt_file") == 0) {
435             opt.crt_file = q;
436         } else if (strcmp(p, "key_file") == 0) {
437             opt.key_file = q;
438         } else if (strcmp(p, "force_ciphersuite") == 0) {
439             opt.force_ciphersuite[0] = -1;
440 
441             opt.force_ciphersuite[0] = mbedtls_ssl_get_ciphersuite_id(q);
442 
443             if (opt.force_ciphersuite[0] <= 0) {
444                 goto usage;
445             }
446 
447             opt.force_ciphersuite[1] = 0;
448         } else {
449             goto usage;
450         }
451     }
452 
453     /*
454      * 0. Initialize the RNG and the session data
455      */
456     mbedtls_printf("\n  . Seeding the random number generator...");
457     fflush(stdout);
458 
459     if ((ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy,
460                                      (const unsigned char *) pers,
461                                      strlen(pers))) != 0) {
462         mbedtls_printf(" failed\n  ! mbedtls_ctr_drbg_seed returned %d\n", ret);
463         goto exit;
464     }
465 
466     mbedtls_printf(" ok\n");
467 
468     /*
469      * 1.1. Load the trusted CA
470      */
471     mbedtls_printf("  . Loading the CA root certificate ...");
472     fflush(stdout);
473 
474 #if defined(MBEDTLS_FS_IO)
475     if (strlen(opt.ca_file)) {
476         ret = mbedtls_x509_crt_parse_file(&cacert, opt.ca_file);
477     } else
478 #endif
479 #if defined(MBEDTLS_PEM_PARSE_C)
480     ret = mbedtls_x509_crt_parse(&cacert, (const unsigned char *) mbedtls_test_cas_pem,
481                                  mbedtls_test_cas_pem_len);
482 #else
483     {
484         mbedtls_printf("MBEDTLS_PEM_PARSE_C not defined.");
485         goto exit;
486     }
487 #endif
488     if (ret < 0) {
489         mbedtls_printf(" failed\n  !  mbedtls_x509_crt_parse returned %d\n\n", ret);
490         goto exit;
491     }
492 
493     mbedtls_printf(" ok (%d skipped)\n", ret);
494 
495     /*
496      * 1.2. Load own certificate and private key
497      *
498      * (can be skipped if client authentication is not required)
499      */
500     mbedtls_printf("  . Loading the client cert. and key...");
501     fflush(stdout);
502 
503 #if defined(MBEDTLS_FS_IO)
504     if (strlen(opt.crt_file)) {
505         ret = mbedtls_x509_crt_parse_file(&clicert, opt.crt_file);
506     } else
507 #endif
508     ret = mbedtls_x509_crt_parse(&clicert, (const unsigned char *) mbedtls_test_cli_crt,
509                                  mbedtls_test_cli_crt_len);
510     if (ret != 0) {
511         mbedtls_printf(" failed\n  !  mbedtls_x509_crt_parse returned %d\n\n", ret);
512         goto exit;
513     }
514 
515 #if defined(MBEDTLS_FS_IO)
516     if (strlen(opt.key_file)) {
517         ret = mbedtls_pk_parse_keyfile(&pkey, opt.key_file, "");
518     } else
519 #endif
520 #if defined(MBEDTLS_PEM_PARSE_C)
521     {
522         ret = mbedtls_pk_parse_key(&pkey,
523                                    (const unsigned char *) mbedtls_test_cli_key,
524                                    mbedtls_test_cli_key_len,
525                                    NULL,
526                                    0);
527     }
528 #else
529     {
530         mbedtls_printf("MBEDTLS_PEM_PARSE_C not defined.");
531         goto exit;
532     }
533 #endif
534     if (ret != 0) {
535         mbedtls_printf(" failed\n  !  mbedtls_pk_parse_key returned %d\n\n", ret);
536         goto exit;
537     }
538 
539     mbedtls_printf(" ok\n");
540 
541     /*
542      * 2. Start the connection
543      */
544     mbedtls_printf("  . Connecting to tcp/%s/%s...", opt.server_name,
545                    opt.server_port);
546     fflush(stdout);
547 
548     if ((ret = mbedtls_net_connect(&server_fd, opt.server_name,
549                                    opt.server_port, MBEDTLS_NET_PROTO_TCP)) != 0) {
550         mbedtls_printf(" failed\n  ! mbedtls_net_connect returned %d\n\n", ret);
551         goto exit;
552     }
553 
554     mbedtls_printf(" ok\n");
555 
556     /*
557      * 3. Setup stuff
558      */
559     mbedtls_printf("  . Setting up the SSL/TLS structure...");
560     fflush(stdout);
561 
562     if ((ret = mbedtls_ssl_config_defaults(&conf,
563                                            MBEDTLS_SSL_IS_CLIENT,
564                                            MBEDTLS_SSL_TRANSPORT_STREAM,
565                                            MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
566         mbedtls_printf(" failed\n  ! mbedtls_ssl_config_defaults returned %d\n\n", ret);
567         goto exit;
568     }
569 
570     /* OPTIONAL is not optimal for security,
571      * but makes interop easier in this simplified example */
572     mbedtls_ssl_conf_authmode(&conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
573 
574     mbedtls_ssl_conf_dbg(&conf, my_debug, stdout);
575 
576     if (opt.force_ciphersuite[0] != DFL_FORCE_CIPHER) {
577         mbedtls_ssl_conf_ciphersuites(&conf, opt.force_ciphersuite);
578     }
579 
580     mbedtls_ssl_conf_ca_chain(&conf, &cacert, NULL);
581     if ((ret = mbedtls_ssl_conf_own_cert(&conf, &clicert, &pkey)) != 0) {
582         mbedtls_printf(" failed\n  ! mbedtls_ssl_conf_own_cert returned %d\n\n", ret);
583         goto exit;
584     }
585 
586     if ((ret = mbedtls_ssl_setup(&ssl, &conf)) != 0) {
587         mbedtls_printf(" failed\n  ! mbedtls_ssl_setup returned %d\n\n", ret);
588         goto exit;
589     }
590 
591     if ((ret = mbedtls_ssl_set_hostname(&ssl, opt.server_name)) != 0) {
592         mbedtls_printf(" failed\n  ! mbedtls_ssl_set_hostname returned %d\n\n", ret);
593         goto exit;
594     }
595 
596     mbedtls_ssl_set_bio(&ssl, &server_fd, mbedtls_net_send, mbedtls_net_recv, NULL);
597 
598     mbedtls_printf(" ok\n");
599 
600     if (opt.mode == MODE_SSL_TLS) {
601         if (do_handshake(&ssl) != 0) {
602             goto exit;
603         }
604 
605         mbedtls_printf("  > Get header from server:");
606         fflush(stdout);
607 
608         ret = write_ssl_and_get_response(&ssl, buf, 0);
609         if (ret < 200 || ret > 299) {
610             mbedtls_printf(" failed\n  ! server responded with %d\n\n", ret);
611             goto exit;
612         }
613 
614         mbedtls_printf(" ok\n");
615 
616         mbedtls_printf("  > Write EHLO to server:");
617         fflush(stdout);
618 
619         gethostname(hostname, 32);
620         len = sprintf((char *) buf, "EHLO %s\r\n", hostname);
621         ret = write_ssl_and_get_response(&ssl, buf, len);
622         if (ret < 200 || ret > 299) {
623             mbedtls_printf(" failed\n  ! server responded with %d\n\n", ret);
624             goto exit;
625         }
626     } else {
627         mbedtls_printf("  > Get header from server:");
628         fflush(stdout);
629 
630         ret = write_and_get_response(&server_fd, buf, 0);
631         if (ret < 200 || ret > 299) {
632             mbedtls_printf(" failed\n  ! server responded with %d\n\n", ret);
633             goto exit;
634         }
635 
636         mbedtls_printf(" ok\n");
637 
638         mbedtls_printf("  > Write EHLO to server:");
639         fflush(stdout);
640 
641         gethostname(hostname, 32);
642         len = sprintf((char *) buf, "EHLO %s\r\n", hostname);
643         ret = write_and_get_response(&server_fd, buf, len);
644         if (ret < 200 || ret > 299) {
645             mbedtls_printf(" failed\n  ! server responded with %d\n\n", ret);
646             goto exit;
647         }
648 
649         mbedtls_printf(" ok\n");
650 
651         mbedtls_printf("  > Write STARTTLS to server:");
652         fflush(stdout);
653 
654         gethostname(hostname, 32);
655         len = sprintf((char *) buf, "STARTTLS\r\n");
656         ret = write_and_get_response(&server_fd, buf, len);
657         if (ret < 200 || ret > 299) {
658             mbedtls_printf(" failed\n  ! server responded with %d\n\n", ret);
659             goto exit;
660         }
661 
662         mbedtls_printf(" ok\n");
663 
664         if (do_handshake(&ssl) != 0) {
665             goto exit;
666         }
667     }
668 
669 #if defined(MBEDTLS_BASE64_C)
670     if (opt.authentication) {
671         mbedtls_printf("  > Write AUTH LOGIN to server:");
672         fflush(stdout);
673 
674         len = sprintf((char *) buf, "AUTH LOGIN\r\n");
675         ret = write_ssl_and_get_response(&ssl, buf, len);
676         if (ret < 200 || ret > 399) {
677             mbedtls_printf(" failed\n  ! server responded with %d\n\n", ret);
678             goto exit;
679         }
680 
681         mbedtls_printf(" ok\n");
682 
683         mbedtls_printf("  > Write username to server: %s", opt.user_name);
684         fflush(stdout);
685 
686         ret = mbedtls_base64_encode(base, sizeof(base), &n, (const unsigned char *) opt.user_name,
687                                     strlen(opt.user_name));
688 
689         if (ret != 0) {
690             mbedtls_printf(" failed\n  ! mbedtls_base64_encode returned %d\n\n", ret);
691             goto exit;
692         }
693         len = sprintf((char *) buf, "%s\r\n", base);
694         ret = write_ssl_and_get_response(&ssl, buf, len);
695         if (ret < 300 || ret > 399) {
696             mbedtls_printf(" failed\n  ! server responded with %d\n\n", ret);
697             goto exit;
698         }
699 
700         mbedtls_printf(" ok\n");
701 
702         mbedtls_printf("  > Write password to server: %s", opt.user_pwd);
703         fflush(stdout);
704 
705         ret = mbedtls_base64_encode(base, sizeof(base), &n, (const unsigned char *) opt.user_pwd,
706                                     strlen(opt.user_pwd));
707 
708         if (ret != 0) {
709             mbedtls_printf(" failed\n  ! mbedtls_base64_encode returned %d\n\n", ret);
710             goto exit;
711         }
712         len = sprintf((char *) buf, "%s\r\n", base);
713         ret = write_ssl_and_get_response(&ssl, buf, len);
714         if (ret < 200 || ret > 399) {
715             mbedtls_printf(" failed\n  ! server responded with %d\n\n", ret);
716             goto exit;
717         }
718 
719         mbedtls_printf(" ok\n");
720     }
721 #endif
722 
723     mbedtls_printf("  > Write MAIL FROM to server:");
724     fflush(stdout);
725 
726     len = mbedtls_snprintf((char *) buf, sizeof(buf), "MAIL FROM:<%s>\r\n", opt.mail_from);
727     if (len < 0 || (size_t) len >= sizeof(buf)) {
728         mbedtls_printf(" failed\n  ! mbedtls_snprintf encountered error or truncated output\n\n");
729         goto exit;
730     }
731     ret = write_ssl_and_get_response(&ssl, buf, len);
732     if (ret < 200 || ret > 299) {
733         mbedtls_printf(" failed\n  ! server responded with %d\n\n", ret);
734         goto exit;
735     }
736 
737     mbedtls_printf(" ok\n");
738 
739     mbedtls_printf("  > Write RCPT TO to server:");
740     fflush(stdout);
741 
742     len = mbedtls_snprintf((char *) buf, sizeof(buf), "RCPT TO:<%s>\r\n", opt.mail_to);
743     if (len < 0 || (size_t) len >= sizeof(buf)) {
744         mbedtls_printf(" failed\n  ! mbedtls_snprintf encountered error or truncated output\n\n");
745         goto exit;
746     }
747     ret = write_ssl_and_get_response(&ssl, buf, len);
748     if (ret < 200 || ret > 299) {
749         mbedtls_printf(" failed\n  ! server responded with %d\n\n", ret);
750         goto exit;
751     }
752 
753     mbedtls_printf(" ok\n");
754 
755     mbedtls_printf("  > Write DATA to server:");
756     fflush(stdout);
757 
758     len = sprintf((char *) buf, "DATA\r\n");
759     ret = write_ssl_and_get_response(&ssl, buf, len);
760     if (ret < 300 || ret > 399) {
761         mbedtls_printf(" failed\n  ! server responded with %d\n\n", ret);
762         goto exit;
763     }
764 
765     mbedtls_printf(" ok\n");
766 
767     mbedtls_printf("  > Write content to server:");
768     fflush(stdout);
769 
770     len = mbedtls_snprintf((char *) buf, sizeof(buf),
771                            "From: %s\r\nSubject: Mbed TLS Test mail\r\n\r\n"
772                            "This is a simple test mail from the "
773                            "Mbed TLS mail client example.\r\n"
774                            "\r\n"
775                            "Enjoy!", opt.mail_from);
776     if (len < 0 || (size_t) len >= sizeof(buf)) {
777         mbedtls_printf(" failed\n  ! mbedtls_snprintf encountered error or truncated output\n\n");
778         goto exit;
779     }
780     ret = write_ssl_data(&ssl, buf, len);
781 
782     len = sprintf((char *) buf, "\r\n.\r\n");
783     ret = write_ssl_and_get_response(&ssl, buf, len);
784     if (ret < 200 || ret > 299) {
785         mbedtls_printf(" failed\n  ! server responded with %d\n\n", ret);
786         goto exit;
787     }
788 
789     mbedtls_printf(" ok\n");
790 
791     mbedtls_ssl_close_notify(&ssl);
792 
793     exit_code = MBEDTLS_EXIT_SUCCESS;
794 
795 exit:
796 
797     mbedtls_net_free(&server_fd);
798     mbedtls_x509_crt_free(&clicert);
799     mbedtls_x509_crt_free(&cacert);
800     mbedtls_pk_free(&pkey);
801     mbedtls_ssl_free(&ssl);
802     mbedtls_ssl_config_free(&conf);
803     mbedtls_ctr_drbg_free(&ctr_drbg);
804     mbedtls_entropy_free(&entropy);
805     mbedtls_psa_crypto_free();
806 
807     mbedtls_exit(exit_code);
808 }
809 #endif /* MBEDTLS_BIGNUM_C && MBEDTLS_ENTROPY_C && MBEDTLS_SSL_TLS_C &&
810           MBEDTLS_SSL_CLI_C && MBEDTLS_NET_C && MBEDTLS_RSA_C **
811           MBEDTLS_CTR_DRBG_C */
812