1 /*
2  *  OpenVPN -- An application to securely tunnel IP networks
3  *             over a single TCP/UDP port, with support for SSL/TLS-based
4  *             session authentication and key exchange,
5  *             packet encryption, packet authentication, and
6  *             packet compression.
7  *
8  *  Copyright (C) 2002-2018 OpenVPN Inc <sales@openvpn.net>
9  *  Copyright (C) 2010-2018 Fox Crypto B.V. <openvpn@fox-it.com>
10  *
11  *  This program is free software; you can redistribute it and/or modify
12  *  it under the terms of the GNU General Public License version 2
13  *  as published by the Free Software Foundation.
14  *
15  *  This program is distributed in the hope that it will be useful,
16  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *  GNU General Public License for more details.
19  *
20  *  You should have received a copy of the GNU General Public License along
21  *  with this program; if not, write to the Free Software Foundation, Inc.,
22  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23  */
24 
25 /**
26  * @file Control Channel Verification Module
27  */
28 
29 #ifdef HAVE_CONFIG_H
30 #include "config.h"
31 #elif defined(_MSC_VER)
32 #include "config-msvc.h"
33 #endif
34 
35 #include "syshead.h"
36 
37 #include "base64.h"
38 #include "manage.h"
39 #include "otime.h"
40 #include "run_command.h"
41 #include "ssl_verify.h"
42 #include "ssl_verify_backend.h"
43 
44 #ifdef ENABLE_CRYPTO_OPENSSL
45 #include "ssl_verify_openssl.h"
46 #endif
47 #include "auth_token.h"
48 #include "push.h"
49 #include "ssl_util.h"
50 
51 /** Maximum length of common name */
52 #define TLS_USERNAME_LEN 64
53 
54 static void
string_mod_remap_name(char * str)55 string_mod_remap_name(char *str)
56 {
57     string_mod(str, CC_PRINT, CC_CRLF, '_');
58 }
59 
60 /*
61  * Export the untrusted IP address and port to the environment
62  */
63 static void
setenv_untrusted(struct tls_session * session)64 setenv_untrusted(struct tls_session *session)
65 {
66     setenv_link_socket_actual(session->opt->es, "untrusted", &session->untrusted_addr, SA_IP_PORT);
67 }
68 
69 /*
70  * Remove authenticated state from all sessions in the given tunnel
71  */
72 static void
tls_deauthenticate(struct tls_multi * multi)73 tls_deauthenticate(struct tls_multi *multi)
74 {
75     if (multi)
76     {
77         wipe_auth_token(multi);
78         for (int i = 0; i < TM_SIZE; ++i)
79         {
80             for (int j = 0; j < KS_SIZE; ++j)
81             {
82                 multi->session[i].key[j].authenticated = KS_AUTH_FALSE;
83             }
84         }
85     }
86 }
87 
88 /*
89  * Set the given session's common_name
90  */
91 static void
set_common_name(struct tls_session * session,const char * common_name)92 set_common_name(struct tls_session *session, const char *common_name)
93 {
94     if (session->common_name)
95     {
96         free(session->common_name);
97         session->common_name = NULL;
98 #ifdef ENABLE_PF
99         session->common_name_hashval = 0;
100 #endif
101     }
102     if (common_name)
103     {
104         /* FIXME: Last alloc will never be freed */
105         session->common_name = string_alloc(common_name, NULL);
106 #ifdef ENABLE_PF
107         {
108             const uint32_t len = (uint32_t) strlen(common_name);
109             if (len)
110             {
111                 session->common_name_hashval = hash_func((const uint8_t *)common_name, len+1, 0);
112             }
113             else
114             {
115                 session->common_name_hashval = 0;
116             }
117         }
118 #endif
119     }
120 }
121 
122 /*
123  * Retrieve the common name for the given tunnel's active session. If the
124  * common name is NULL or empty, return NULL if null is true, or "UNDEF" if
125  * null is false.
126  */
127 const char *
tls_common_name(const struct tls_multi * multi,const bool null)128 tls_common_name(const struct tls_multi *multi, const bool null)
129 {
130     const char *ret = NULL;
131     if (multi)
132     {
133         ret = multi->session[TM_ACTIVE].common_name;
134     }
135     if (ret && strlen(ret))
136     {
137         return ret;
138     }
139     else if (null)
140     {
141         return NULL;
142     }
143     else
144     {
145         return "UNDEF";
146     }
147 }
148 
149 /*
150  * Lock the common name for the given tunnel.
151  */
152 void
tls_lock_common_name(struct tls_multi * multi)153 tls_lock_common_name(struct tls_multi *multi)
154 {
155     const char *cn = multi->session[TM_ACTIVE].common_name;
156     if (cn && !multi->locked_cn)
157     {
158         multi->locked_cn = string_alloc(cn, NULL);
159     }
160 }
161 
162 /*
163  * Lock the username for the given tunnel
164  */
165 static bool
tls_lock_username(struct tls_multi * multi,const char * username)166 tls_lock_username(struct tls_multi *multi, const char *username)
167 {
168     if (multi->locked_username)
169     {
170         if (!username || strcmp(username, multi->locked_username))
171         {
172             msg(D_TLS_ERRORS, "TLS Auth Error: username attempted to change from '%s' to '%s' -- tunnel disabled",
173                 multi->locked_username,
174                 np(username));
175 
176             /* disable the tunnel */
177             tls_deauthenticate(multi);
178             return false;
179         }
180     }
181     else
182     {
183         if (username)
184         {
185             multi->locked_username = string_alloc(username, NULL);
186         }
187     }
188     return true;
189 }
190 
191 const char *
tls_username(const struct tls_multi * multi,const bool null)192 tls_username(const struct tls_multi *multi, const bool null)
193 {
194     const char *ret = NULL;
195     if (multi)
196     {
197         ret = multi->locked_username;
198     }
199     if (ret && strlen(ret))
200     {
201         return ret;
202     }
203     else if (null)
204     {
205         return NULL;
206     }
207     else
208     {
209         return "UNDEF";
210     }
211 }
212 
213 void
cert_hash_remember(struct tls_session * session,const int error_depth,const struct buffer * cert_hash)214 cert_hash_remember(struct tls_session *session, const int error_depth,
215                    const struct buffer *cert_hash)
216 {
217     if (error_depth >= 0 && error_depth < MAX_CERT_DEPTH)
218     {
219         if (!session->cert_hash_set)
220         {
221             ALLOC_OBJ_CLEAR(session->cert_hash_set, struct cert_hash_set);
222         }
223         if (!session->cert_hash_set->ch[error_depth])
224         {
225             ALLOC_OBJ(session->cert_hash_set->ch[error_depth], struct cert_hash);
226         }
227 
228         struct cert_hash *ch = session->cert_hash_set->ch[error_depth];
229         ASSERT(sizeof(ch->sha256_hash) == BLEN(cert_hash));
230         memcpy(ch->sha256_hash, BPTR(cert_hash), sizeof(ch->sha256_hash));
231     }
232 }
233 
234 void
cert_hash_free(struct cert_hash_set * chs)235 cert_hash_free(struct cert_hash_set *chs)
236 {
237     if (chs)
238     {
239         int i;
240         for (i = 0; i < MAX_CERT_DEPTH; ++i)
241         {
242             free(chs->ch[i]);
243         }
244         free(chs);
245     }
246 }
247 
248 bool
cert_hash_compare(const struct cert_hash_set * chs1,const struct cert_hash_set * chs2)249 cert_hash_compare(const struct cert_hash_set *chs1, const struct cert_hash_set *chs2)
250 {
251     if (chs1 && chs2)
252     {
253         int i;
254         for (i = 0; i < MAX_CERT_DEPTH; ++i)
255         {
256             const struct cert_hash *ch1 = chs1->ch[i];
257             const struct cert_hash *ch2 = chs2->ch[i];
258 
259             if (!ch1 && !ch2)
260             {
261                 continue;
262             }
263             else if (ch1 && ch2 && !memcmp(ch1->sha256_hash, ch2->sha256_hash,
264                                            sizeof(ch1->sha256_hash)))
265             {
266                 continue;
267             }
268             else
269             {
270                 return false;
271             }
272         }
273         return true;
274     }
275     else if (!chs1 && !chs2)
276     {
277         return true;
278     }
279     else
280     {
281         return false;
282     }
283 }
284 
285 static struct cert_hash_set *
cert_hash_copy(const struct cert_hash_set * chs)286 cert_hash_copy(const struct cert_hash_set *chs)
287 {
288     struct cert_hash_set *dest = NULL;
289     if (chs)
290     {
291         int i;
292         ALLOC_OBJ_CLEAR(dest, struct cert_hash_set);
293         for (i = 0; i < MAX_CERT_DEPTH; ++i)
294         {
295             const struct cert_hash *ch = chs->ch[i];
296             if (ch)
297             {
298                 ALLOC_OBJ(dest->ch[i], struct cert_hash);
299                 memcpy(dest->ch[i]->sha256_hash, ch->sha256_hash,
300                        sizeof(dest->ch[i]->sha256_hash));
301             }
302         }
303     }
304     return dest;
305 }
306 void
tls_lock_cert_hash_set(struct tls_multi * multi)307 tls_lock_cert_hash_set(struct tls_multi *multi)
308 {
309     const struct cert_hash_set *chs = multi->session[TM_ACTIVE].cert_hash_set;
310     if (chs && !multi->locked_cert_hash_set)
311     {
312         multi->locked_cert_hash_set = cert_hash_copy(chs);
313     }
314 }
315 
316 /*
317  * Returns the string associated with the given certificate type.
318  */
319 static const char *
print_nsCertType(int type)320 print_nsCertType(int type)
321 {
322     switch (type)
323     {
324         case NS_CERT_CHECK_SERVER:
325             return "SERVER";
326 
327         case NS_CERT_CHECK_CLIENT:
328             return "CLIENT";
329 
330         default:
331             return "?";
332     }
333 }
334 
335 /*
336  * Verify the peer's certificate fields.
337  *
338  * @param opt the tls options to verify against
339  * @param peer_cert the peer's certificate
340  * @param subject the peer's extracted subject name
341  * @param subject the peer's extracted common name
342  */
343 static result_t
verify_peer_cert(const struct tls_options * opt,openvpn_x509_cert_t * peer_cert,const char * subject,const char * common_name)344 verify_peer_cert(const struct tls_options *opt, openvpn_x509_cert_t *peer_cert,
345                  const char *subject, const char *common_name)
346 {
347     /* verify certificate nsCertType */
348     if (opt->ns_cert_type != NS_CERT_CHECK_NONE)
349     {
350         if (SUCCESS == x509_verify_ns_cert_type(peer_cert, opt->ns_cert_type))
351         {
352             msg(D_HANDSHAKE, "VERIFY OK: nsCertType=%s",
353                 print_nsCertType(opt->ns_cert_type));
354         }
355         else
356         {
357             msg(D_HANDSHAKE, "VERIFY nsCertType ERROR: %s, require nsCertType=%s",
358                 subject, print_nsCertType(opt->ns_cert_type));
359             return FAILURE;             /* Reject connection */
360         }
361     }
362 
363     /* verify certificate ku */
364     if (opt->remote_cert_ku[0] != 0)
365     {
366         if (SUCCESS == x509_verify_cert_ku(peer_cert, opt->remote_cert_ku, MAX_PARMS))
367         {
368             msg(D_HANDSHAKE, "VERIFY KU OK");
369         }
370         else
371         {
372             msg(D_HANDSHAKE, "VERIFY KU ERROR");
373             return FAILURE;             /* Reject connection */
374         }
375     }
376 
377     /* verify certificate eku */
378     if (opt->remote_cert_eku != NULL)
379     {
380         if (SUCCESS == x509_verify_cert_eku(peer_cert, opt->remote_cert_eku))
381         {
382             msg(D_HANDSHAKE, "VERIFY EKU OK");
383         }
384         else
385         {
386             msg(D_HANDSHAKE, "VERIFY EKU ERROR");
387             return FAILURE;             /* Reject connection */
388         }
389     }
390 
391     /* verify X509 name or username against --verify-x509-[user]name */
392     if (opt->verify_x509_type != VERIFY_X509_NONE)
393     {
394         if ( (opt->verify_x509_type == VERIFY_X509_SUBJECT_DN
395               && strcmp(opt->verify_x509_name, subject) == 0)
396              || (opt->verify_x509_type == VERIFY_X509_SUBJECT_RDN
397                  && strcmp(opt->verify_x509_name, common_name) == 0)
398              || (opt->verify_x509_type == VERIFY_X509_SUBJECT_RDN_PREFIX
399                  && strncmp(opt->verify_x509_name, common_name,
400                             strlen(opt->verify_x509_name)) == 0) )
401         {
402             msg(D_HANDSHAKE, "VERIFY X509NAME OK: %s", subject);
403         }
404         else
405         {
406             msg(D_HANDSHAKE, "VERIFY X509NAME ERROR: %s, must be %s",
407                 subject, opt->verify_x509_name);
408             return FAILURE;             /* Reject connection */
409         }
410     }
411 
412     return SUCCESS;
413 }
414 
415 /*
416  * Export the subject, common_name, and raw certificate fields to the
417  * environment for later verification by scripts and plugins.
418  */
419 static void
verify_cert_set_env(struct env_set * es,openvpn_x509_cert_t * peer_cert,int cert_depth,const char * subject,const char * common_name,const struct x509_track * x509_track)420 verify_cert_set_env(struct env_set *es, openvpn_x509_cert_t *peer_cert, int cert_depth,
421                     const char *subject, const char *common_name,
422                     const struct x509_track *x509_track)
423 {
424     char envname[64];
425     char *serial = NULL;
426     struct gc_arena gc = gc_new();
427 
428     /* Save X509 fields in environment */
429     if (x509_track)
430     {
431         x509_setenv_track(x509_track, es, cert_depth, peer_cert);
432     }
433     else
434     {
435         x509_setenv(es, cert_depth, peer_cert);
436     }
437 
438     /* export subject name string as environmental variable */
439     openvpn_snprintf(envname, sizeof(envname), "tls_id_%d", cert_depth);
440     setenv_str(es, envname, subject);
441 
442 #if 0
443     /* export common name string as environmental variable */
444     openvpn_snprintf(envname, sizeof(envname), "tls_common_name_%d", cert_depth);
445     setenv_str(es, envname, common_name);
446 #endif
447 
448     /* export X509 cert fingerprints */
449     {
450         struct buffer sha1 = x509_get_sha1_fingerprint(peer_cert, &gc);
451         struct buffer sha256 = x509_get_sha256_fingerprint(peer_cert, &gc);
452 
453         openvpn_snprintf(envname, sizeof(envname), "tls_digest_%d", cert_depth);
454         setenv_str(es, envname,
455                    format_hex_ex(BPTR(&sha1), BLEN(&sha1), 0, 1, ":", &gc));
456 
457         openvpn_snprintf(envname, sizeof(envname), "tls_digest_sha256_%d",
458                          cert_depth);
459         setenv_str(es, envname,
460                    format_hex_ex(BPTR(&sha256), BLEN(&sha256), 0, 1, ":", &gc));
461     }
462 
463     /* export serial number as environmental variable */
464     serial = backend_x509_get_serial(peer_cert, &gc);
465     openvpn_snprintf(envname, sizeof(envname), "tls_serial_%d", cert_depth);
466     setenv_str(es, envname, serial);
467 
468     /* export serial number in hex as environmental variable */
469     serial = backend_x509_get_serial_hex(peer_cert, &gc);
470     openvpn_snprintf(envname, sizeof(envname), "tls_serial_hex_%d", cert_depth);
471     setenv_str(es, envname, serial);
472 
473     gc_free(&gc);
474 }
475 
476 /*
477  * call --tls-verify plug-in(s)
478  */
479 static result_t
verify_cert_call_plugin(const struct plugin_list * plugins,struct env_set * es,int cert_depth,openvpn_x509_cert_t * cert,char * subject)480 verify_cert_call_plugin(const struct plugin_list *plugins, struct env_set *es,
481                         int cert_depth, openvpn_x509_cert_t *cert, char *subject)
482 {
483     if (plugin_defined(plugins, OPENVPN_PLUGIN_TLS_VERIFY))
484     {
485         int ret;
486         struct argv argv = argv_new();
487 
488         argv_printf(&argv, "%d %s", cert_depth, subject);
489 
490         ret = plugin_call_ssl(plugins, OPENVPN_PLUGIN_TLS_VERIFY, &argv, NULL, es, cert_depth, cert);
491 
492         argv_free(&argv);
493 
494         if (ret == OPENVPN_PLUGIN_FUNC_SUCCESS)
495         {
496             msg(D_HANDSHAKE, "VERIFY PLUGIN OK: depth=%d, %s",
497                 cert_depth, subject);
498         }
499         else
500         {
501             msg(D_HANDSHAKE, "VERIFY PLUGIN ERROR: depth=%d, %s",
502                 cert_depth, subject);
503             return FAILURE;             /* Reject connection */
504         }
505     }
506     return SUCCESS;
507 }
508 
509 static const char *
verify_cert_export_cert(openvpn_x509_cert_t * peercert,const char * tmp_dir,struct gc_arena * gc)510 verify_cert_export_cert(openvpn_x509_cert_t *peercert, const char *tmp_dir, struct gc_arena *gc)
511 {
512     FILE *peercert_file;
513     const char *peercert_filename = "";
514 
515     /* create tmp file to store peer cert */
516     if (!tmp_dir
517         || !(peercert_filename = platform_create_temp_file(tmp_dir, "pcf", gc)))
518     {
519         msg(M_NONFATAL, "Failed to create peer cert file");
520         return NULL;
521     }
522 
523     /* write peer-cert in tmp-file */
524     peercert_file = fopen(peercert_filename, "w+");
525     if (!peercert_file)
526     {
527         msg(M_NONFATAL|M_ERRNO, "Failed to open temporary file: %s",
528             peercert_filename);
529         return NULL;
530     }
531 
532     if (SUCCESS != x509_write_pem(peercert_file, peercert))
533     {
534         msg(M_NONFATAL, "Error writing PEM file containing certificate");
535         (void) platform_unlink(peercert_filename);
536         peercert_filename = NULL;
537     }
538 
539     fclose(peercert_file);
540     return peercert_filename;
541 }
542 
543 
544 /*
545  * run --tls-verify script
546  */
547 static result_t
verify_cert_call_command(const char * verify_command,struct env_set * es,int cert_depth,openvpn_x509_cert_t * cert,char * subject,const char * verify_export_cert)548 verify_cert_call_command(const char *verify_command, struct env_set *es,
549                          int cert_depth, openvpn_x509_cert_t *cert, char *subject, const char *verify_export_cert)
550 {
551     const char *tmp_file = NULL;
552     int ret;
553     struct gc_arena gc = gc_new();
554     struct argv argv = argv_new();
555 
556     setenv_str(es, "script_type", "tls-verify");
557 
558     if (verify_export_cert)
559     {
560         tmp_file = verify_cert_export_cert(cert, verify_export_cert, &gc);
561         if (!tmp_file)
562         {
563             ret = false;
564             goto cleanup;
565         }
566         setenv_str(es, "peer_cert", tmp_file);
567     }
568 
569     argv_parse_cmd(&argv, verify_command);
570     argv_printf_cat(&argv, "%d %s", cert_depth, subject);
571 
572     argv_msg_prefix(D_TLS_DEBUG, &argv, "TLS: executing verify command");
573     ret = openvpn_run_script(&argv, es, 0, "--tls-verify script");
574 
575     if (verify_export_cert)
576     {
577         if (tmp_file)
578         {
579             platform_unlink(tmp_file);
580         }
581     }
582 
583 cleanup:
584     gc_free(&gc);
585     argv_free(&argv);
586 
587     if (ret)
588     {
589         msg(D_HANDSHAKE, "VERIFY SCRIPT OK: depth=%d, %s",
590             cert_depth, subject);
591         return SUCCESS;
592     }
593 
594     msg(D_HANDSHAKE, "VERIFY SCRIPT ERROR: depth=%d, %s",
595         cert_depth, subject);
596     return FAILURE;             /* Reject connection */
597 }
598 
599 /*
600  * check peer cert against CRL directory
601  */
602 static result_t
verify_check_crl_dir(const char * crl_dir,openvpn_x509_cert_t * cert,const char * subject,int cert_depth)603 verify_check_crl_dir(const char *crl_dir, openvpn_x509_cert_t *cert,
604                      const char *subject, int cert_depth)
605 {
606     result_t ret = FAILURE;
607     char fn[256];
608     int fd = -1;
609     struct gc_arena gc = gc_new();
610 
611     char *serial = backend_x509_get_serial(cert, &gc);
612     if (!serial)
613     {
614         msg(D_HANDSHAKE, "VERIFY CRL: depth=%d, %s, serial number is not available",
615             cert_depth, subject);
616         goto cleanup;
617     }
618 
619     if (!openvpn_snprintf(fn, sizeof(fn), "%s%c%s", crl_dir, PATH_SEPARATOR, serial))
620     {
621         msg(D_HANDSHAKE, "VERIFY CRL: filename overflow");
622         goto cleanup;
623     }
624     fd = platform_open(fn, O_RDONLY, 0);
625     if (fd >= 0)
626     {
627         msg(D_HANDSHAKE, "VERIFY CRL: depth=%d, %s, serial=%s is revoked",
628             cert_depth, subject, serial);
629         goto cleanup;
630     }
631 
632     ret = SUCCESS;
633 
634 cleanup:
635 
636     if (fd != -1)
637     {
638         close(fd);
639     }
640     gc_free(&gc);
641     return ret;
642 }
643 
644 result_t
verify_cert(struct tls_session * session,openvpn_x509_cert_t * cert,int cert_depth)645 verify_cert(struct tls_session *session, openvpn_x509_cert_t *cert, int cert_depth)
646 {
647     result_t ret = FAILURE;
648     char *subject = NULL;
649     const struct tls_options *opt;
650     struct gc_arena gc = gc_new();
651 
652     opt = session->opt;
653     ASSERT(opt);
654 
655     session->verified = false;
656 
657     /* get the X509 name */
658     subject = x509_get_subject(cert, &gc);
659     if (!subject)
660     {
661         msg(D_TLS_ERRORS, "VERIFY ERROR: depth=%d, could not extract X509 "
662             "subject string from certificate", cert_depth);
663         goto cleanup;
664     }
665 
666     /* enforce character class restrictions in X509 name */
667     string_mod_remap_name(subject);
668     string_replace_leading(subject, '-', '_');
669 
670     /* extract the username (default is CN) */
671     struct buffer buf = alloc_buf_gc(256, &gc);
672     for (int i = 0; opt->x509_username_field[i] != NULL; i++)
673     {
674         char username[TLS_USERNAME_LEN+1] = {0}; /* null-terminated */
675 
676         if (SUCCESS != backend_x509_get_username(username, sizeof(username),
677                                                  opt->x509_username_field[i], cert))
678         {
679             if (!cert_depth)
680             {
681                 msg(D_TLS_ERRORS, "VERIFY ERROR: could not extract %s from X509 "
682                     "subject string ('%s') -- note that the field length is "
683                     "limited to %d characters",
684                     opt->x509_username_field[i],
685                     subject,
686                     TLS_USERNAME_LEN);
687                 goto cleanup;
688             }
689             break;
690         }
691         if (!buf_printf(&buf, i ? "_%s" : "%s", username))
692         {
693             if (!cert_depth)
694             {
695                 msg(D_TLS_ERRORS, "VERIFY ERROR: could not append %s from X509 "
696                     "certificate -- note that the username length is "
697                     "limited to %d characters",
698                     opt->x509_username_field[i],
699                     buf.capacity - 1);
700                 goto cleanup;
701             }
702             break;
703         }
704     }
705 
706     char *common_name = BSTR(&buf);
707     if (!common_name)
708     {
709         msg(D_TLS_ERRORS, "VERIFY ERROR: depth=%d, could not extract X509 "
710             "username string from certificate", cert_depth);
711         goto cleanup;
712     }
713 
714     /* enforce character class restrictions in common name */
715     string_mod_remap_name(common_name);
716 
717     /* warn if cert chain is too deep */
718     if (cert_depth >= MAX_CERT_DEPTH)
719     {
720         msg(D_TLS_ERRORS, "TLS Error: Convoluted certificate chain detected with depth [%d] greater than %d", cert_depth, MAX_CERT_DEPTH);
721         goto cleanup;                   /* Reject connection */
722     }
723 
724     if (cert_depth == opt->verify_hash_depth && opt->verify_hash)
725     {
726         struct buffer cert_fp = {0};
727 
728         switch (opt->verify_hash_algo)
729         {
730             case MD_SHA1:
731                 cert_fp = x509_get_sha1_fingerprint(cert, &gc);
732                 break;
733 
734             case MD_SHA256:
735                 cert_fp = x509_get_sha256_fingerprint(cert, &gc);
736                 break;
737 
738             default:
739                 /* This should normally not happen at all; the algorithm used
740                  * is parsed by add_option() [options.c] and set to a predefined
741                  * value in an enumerated type.  So if this unlikely scenario
742                  * happens, consider this a failure
743                  */
744                 msg(M_WARN, "Unexpected invalid algorithm used with "
745                     "--verify-hash (%i)", opt->verify_hash_algo);
746                 ret = FAILURE;
747                 goto cleanup;
748         }
749 
750         struct verify_hash_list *current_hash = opt->verify_hash;
751 
752         while (current_hash)
753         {
754             if (memcmp_constant_time(BPTR(&cert_fp), current_hash->hash,
755                                      BLEN(&cert_fp)) == 0)
756             {
757                 break;
758             }
759             current_hash = current_hash->next;
760         }
761 
762         if (!current_hash)
763         {
764             const char *hex_fp = format_hex_ex(BPTR(&cert_fp), BLEN(&cert_fp),
765                                                0, 1, ":", &gc);
766             msg(D_TLS_ERRORS, "TLS Error: --tls-verify/--peer-fingerprint"
767                 "certificate hash verification failed. (got "
768                 "fingerprint: %s", hex_fp);
769             goto cleanup;
770         }
771     }
772 
773     /* save common name in session object */
774     if (cert_depth == 0)
775     {
776         set_common_name(session, common_name);
777     }
778 
779     session->verify_maxlevel = max_int(session->verify_maxlevel, cert_depth);
780 
781     /* export certificate values to the environment */
782     verify_cert_set_env(opt->es, cert, cert_depth, subject, common_name,
783                         opt->x509_track);
784 
785     /* export current untrusted IP */
786     setenv_untrusted(session);
787 
788     /* If this is the peer's own certificate, verify it */
789     if (cert_depth == 0 && SUCCESS != verify_peer_cert(opt, cert, subject, common_name))
790     {
791         goto cleanup;
792     }
793 
794     /* call --tls-verify plug-in(s), if registered */
795     if (SUCCESS != verify_cert_call_plugin(opt->plugins, opt->es, cert_depth, cert, subject))
796     {
797         goto cleanup;
798     }
799 
800     /* run --tls-verify script */
801     if (opt->verify_command && SUCCESS != verify_cert_call_command(opt->verify_command,
802                                                                    opt->es, cert_depth, cert, subject, opt->verify_export_cert))
803     {
804         goto cleanup;
805     }
806 
807     /* check peer cert against CRL */
808     if (opt->crl_file)
809     {
810         if (opt->ssl_flags & SSLF_CRL_VERIFY_DIR)
811         {
812             if (SUCCESS != verify_check_crl_dir(opt->crl_file, cert, subject, cert_depth))
813             {
814                 goto cleanup;
815             }
816         }
817         else
818         {
819             if (tls_verify_crl_missing(opt))
820             {
821                 msg(D_TLS_ERRORS, "VERIFY ERROR: CRL not loaded");
822                 goto cleanup;
823             }
824         }
825     }
826 
827     msg(D_HANDSHAKE, "VERIFY OK: depth=%d, %s", cert_depth, subject);
828     session->verified = true;
829     ret = SUCCESS;
830 
831 cleanup:
832 
833     if (ret != SUCCESS)
834     {
835         tls_clear_error(); /* always? */
836         session->verified = false; /* double sure? */
837     }
838     gc_free(&gc);
839 
840     return ret;
841 }
842 
843 /* ***************************************************************************
844 * Functions for the management of deferred authentication when using
845 * user/password authentication.
846 *************************************************************************** */
847 
848 void
auth_set_client_reason(struct tls_multi * multi,const char * client_reason)849 auth_set_client_reason(struct tls_multi *multi, const char *client_reason)
850 {
851     free(multi->client_reason);
852     multi->client_reason = NULL;
853 
854     if (client_reason && strlen(client_reason))
855     {
856         multi->client_reason = string_alloc(client_reason, NULL);
857     }
858 }
859 
860 #ifdef ENABLE_MANAGEMENT
861 
862 static inline enum auth_deferred_result
man_def_auth_test(const struct key_state * ks)863 man_def_auth_test(const struct key_state *ks)
864 {
865     if (management_enable_def_auth(management))
866     {
867         return ks->mda_status;
868     }
869     else
870     {
871         return ACF_DISABLED;
872     }
873 }
874 #endif /* ifdef ENABLE_MANAGEMENT */
875 
876 /**
877  *  Removes auth_pending file from the file system
878  *  and key_state structure
879  */
880 static void
key_state_rm_auth_pending_file(struct auth_deferred_status * ads)881 key_state_rm_auth_pending_file(struct auth_deferred_status *ads)
882 {
883     if (ads && ads->auth_pending_file)
884     {
885         platform_unlink(ads->auth_pending_file);
886         free(ads->auth_pending_file);
887         ads->auth_pending_file = NULL;
888     }
889 }
890 
891 /**
892  * Check peer_info if the client supports the requested pending auth method
893  */
894 static bool
check_auth_pending_method(const char * peer_info,const char * method)895 check_auth_pending_method(const char *peer_info, const char *method)
896 {
897     struct gc_arena gc = gc_new();
898 
899     char *iv_sso = extract_var_peer_info(peer_info, "IV_SSO=", &gc);
900     if (!iv_sso)
901     {
902         gc_free(&gc);
903         return false;
904     }
905 
906     const char *client_method = strtok(iv_sso, ",");
907     bool supported = false;
908 
909     while (client_method)
910     {
911         if (0 == strcmp(client_method, method))
912         {
913             supported = true;
914             break;
915         }
916         client_method = strtok(NULL, ",");
917     }
918 
919     gc_free(&gc);
920     return supported;
921 }
922 
923 /**
924  *  Checks if the deferred state should also send auth pending
925  *  request to the client. Also removes the auth_pending control file
926  *
927  *  @returns true   if file was either processed sucessfully or did not
928  *                  exist at all
929  *  @returns false  The file had an invlaid format or another error occured
930  */
931 static bool
key_state_check_auth_pending_file(struct auth_deferred_status * ads,struct tls_multi * multi)932 key_state_check_auth_pending_file(struct auth_deferred_status *ads,
933                                   struct tls_multi *multi)
934 {
935     bool ret = true;
936     if (ads->auth_pending_file)
937     {
938         struct buffer_list *lines = buffer_list_file(ads->auth_pending_file,
939                                                      1024);
940         if (lines && lines->head)
941         {
942             /* Must have at least three lines. further lines are ignored for
943              * forward compatibility */
944             if (!lines->head || !lines->head->next || !lines->head->next->next)
945             {
946                 msg(M_WARN, "auth pending control file is not at least "
947                             "three lines long.");
948                 buffer_list_free(lines);
949                 return false;
950             }
951             struct buffer *timeout_buf = &lines->head->buf;
952             struct buffer *iv_buf = &lines->head->next->buf;
953             struct buffer *extra_buf = &lines->head->next->next->buf;
954 
955             /* Remove newline chars at the end of the lines */
956             buf_chomp(timeout_buf);
957             buf_chomp(iv_buf);
958             buf_chomp(extra_buf);
959 
960             long timeout = strtol(BSTR(timeout_buf), NULL, 10);
961             if (timeout == 0)
962             {
963                 msg(M_WARN, "could not parse auth pending file timeout");
964                 buffer_list_free(lines);
965                 return false;
966             }
967 
968             const char* pending_method = BSTR(iv_buf);
969             if (!check_auth_pending_method(multi->peer_info, pending_method))
970             {
971                 char buf[128];
972                 openvpn_snprintf(buf, sizeof(buf),
973                                  "Authentication failed, required pending auth "
974                                  "method '%s' not supported", pending_method);
975                 auth_set_client_reason(multi, buf);
976                 msg(M_INFO, "Client does not supported auth pending method "
977                             "'%s'", pending_method);
978                 ret = false;
979             }
980             else
981             {
982                 send_auth_pending_messages(multi, BSTR(extra_buf), timeout);
983             }
984         }
985 
986         buffer_list_free(lines);
987     }
988     key_state_rm_auth_pending_file(ads);
989     return ret;
990 }
991 
992 
993 /**
994  *  Removes auth_pending and auth_control files from file system
995  *  and key_state structure
996  */
997 void
key_state_rm_auth_control_files(struct auth_deferred_status * ads)998 key_state_rm_auth_control_files(struct auth_deferred_status *ads)
999 {
1000     if (ads->auth_control_file)
1001     {
1002         platform_unlink(ads->auth_control_file);
1003         free(ads->auth_control_file);
1004         ads->auth_control_file = NULL;
1005     }
1006     key_state_rm_auth_pending_file(ads);
1007 }
1008 
1009 /**
1010  * Generates and creates the control files used for deferred authentification
1011  * in the temporary directory.
1012  *
1013  * @return  true if file creation was successful
1014  */
1015 static bool
key_state_gen_auth_control_files(struct auth_deferred_status * ads,const struct tls_options * opt)1016 key_state_gen_auth_control_files(struct auth_deferred_status *ads,
1017                                  const struct tls_options *opt)
1018 {
1019     struct gc_arena gc = gc_new();
1020 
1021     key_state_rm_auth_control_files(ads);
1022     const char *acf = platform_create_temp_file(opt->tmp_dir, "acf", &gc);
1023     const char *apf = platform_create_temp_file(opt->tmp_dir, "apf", &gc);
1024 
1025     if (acf && apf)
1026     {
1027         ads->auth_control_file = string_alloc(acf, NULL);
1028         ads->auth_pending_file = string_alloc(apf, NULL);
1029         setenv_str(opt->es, "auth_control_file", ads->auth_control_file);
1030         setenv_str(opt->es, "auth_pending_file", ads->auth_pending_file);
1031     }
1032 
1033     gc_free(&gc);
1034     return (acf && apf);
1035 }
1036 
1037 /**
1038  * Checks the auth control status from a file. The function will try
1039  * to read and update the cached status if the status is still pending
1040  * and the parameter cached is false.
1041  * The function returns the most recent known status.
1042  *
1043  * @param ads       deferred status control structure
1044  * @param cached    Return only cached status
1045  * @return          ACF_* as per enum
1046  */
1047 static enum auth_deferred_result
key_state_test_auth_control_file(struct auth_deferred_status * ads,bool cached)1048 key_state_test_auth_control_file(struct auth_deferred_status *ads, bool cached)
1049 {
1050     if (ads->auth_control_file)
1051     {
1052         unsigned int ret = ads->auth_control_status;
1053         if (ret == ACF_PENDING && !cached)
1054         {
1055             FILE *fp = fopen(ads->auth_control_file, "r");
1056             if (fp)
1057             {
1058                 const int c = fgetc(fp);
1059                 if (c == '1')
1060                 {
1061                     ret = ACF_SUCCEEDED;
1062                 }
1063                 else if (c == '0')
1064                 {
1065                     ret = ACF_FAILED;
1066                 }
1067                 fclose(fp);
1068                 ads->auth_control_status = ret;
1069             }
1070         }
1071         return ret;
1072     }
1073     return ACF_DISABLED;
1074 }
1075 
1076 /**
1077  * The minimum times to have passed to update the cache. Older versions
1078  * of OpenVPN had code path that did not do any caching, so we start
1079  * with no caching (0) here as well to have the same super quick initial
1080  * reaction.
1081  */
1082 static time_t cache_intervals[] = {0, 0, 0, 0, 0, 1, 1, 2, 2, 4, 8};
1083 
1084 /**
1085  * uses cache_intervals times to determine if we should update the
1086  * cache.
1087  */
1088 static bool
tls_authentication_status_use_cache(struct tls_multi * multi)1089 tls_authentication_status_use_cache(struct tls_multi *multi)
1090 {
1091     unsigned int idx = min_uint(multi->tas_cache_num_updates, SIZE(cache_intervals) - 1);
1092     time_t latency = cache_intervals[idx];
1093     return multi->tas_cache_last_update + latency >= now;
1094 }
1095 
1096 enum tls_auth_status
tls_authentication_status(struct tls_multi * multi)1097 tls_authentication_status(struct tls_multi *multi)
1098 {
1099     bool deferred = false;
1100 
1101     /* at least one valid key has successfully completed authentication */
1102     bool success = false;
1103 
1104     /* at least one key is enabled for decryption */
1105     int active = 0;
1106 
1107     /* at least one key already failed authentication */
1108     bool failed_auth = false;
1109 
1110     bool cached = tls_authentication_status_use_cache(multi);
1111 
1112     for (int i = 0; i < KEY_SCAN_SIZE; ++i)
1113     {
1114         struct key_state *ks = get_key_scan(multi, i);
1115         if (TLS_AUTHENTICATED(multi, ks))
1116         {
1117             active++;
1118             if (ks->authenticated == KS_AUTH_FALSE)
1119             {
1120                 failed_auth = true;
1121             }
1122             else
1123             {
1124                 enum auth_deferred_result auth_plugin = ACF_DISABLED;
1125                 enum auth_deferred_result auth_script = ACF_DISABLED;
1126                 enum auth_deferred_result auth_man = ACF_DISABLED;
1127                 auth_plugin = key_state_test_auth_control_file(&ks->plugin_auth, cached);
1128                 auth_script = key_state_test_auth_control_file(&ks->script_auth, cached);
1129 #ifdef ENABLE_MANAGEMENT
1130                 auth_man = man_def_auth_test(ks);
1131 #endif
1132                 ASSERT(auth_plugin < 4 && auth_script < 4 && auth_man < 4);
1133 
1134                 if (auth_plugin == ACF_FAILED || auth_script == ACF_FAILED
1135                    || auth_man == ACF_FAILED)
1136                 {
1137                     ks->authenticated = KS_AUTH_FALSE;
1138                     failed_auth = true;
1139                 }
1140                 else if (auth_plugin == ACF_PENDING
1141                          || auth_script == ACF_PENDING
1142                          || auth_man == ACF_PENDING)
1143                 {
1144                     if (now < ks->auth_deferred_expire)
1145                     {
1146                         deferred = true;
1147                     }
1148                 }
1149                 else
1150                 {
1151                     /* all auth states (auth_plugin, auth_script, auth_man)
1152                      * are either ACF_DISABLED or ACF_SUCCEDED now, which
1153                      * translates to "not checked" or "auth succeeded"
1154                      */
1155                     success = true;
1156                     ks->authenticated = KS_AUTH_TRUE;
1157                 }
1158             }
1159         }
1160     }
1161 
1162     /* we did not rely on a cached result, remember the cache update time */
1163     if (!cached)
1164     {
1165         multi->tas_cache_last_update = now;
1166         multi->tas_cache_num_updates++;
1167     }
1168 
1169 #if 0
1170     dmsg(D_TLS_ERRORS, "TAS: a=%d s=%d d=%d f=%d", active, success, deferred, failed_auth);
1171 #endif
1172     if (failed_auth)
1173     {
1174         /* We have at least one session that failed authentication. There
1175          * might be still another session with valid keys.
1176          * Although our protocol allows keeping the VPN session alive
1177          * with the other session (and we actually did that in earlier
1178          * version, this behaviour is really strange from a user (admin)
1179          * experience */
1180         return TLS_AUTHENTICATION_FAILED;
1181     }
1182     else if (success)
1183     {
1184         return TLS_AUTHENTICATION_SUCCEEDED;
1185     }
1186     else if (active == 0 || deferred)
1187     {
1188         /* We have a deferred authentication and no currently active key
1189          * (first auth, no renegotiation)  */
1190         return TLS_AUTHENTICATION_DEFERRED;
1191     }
1192     else
1193     {
1194         /* at least one key is active but none is fully authenticated (!success)
1195          * and all active are either failed authed or expired deferred auth */
1196         return TLS_AUTHENTICATION_FAILED;
1197     }
1198 }
1199 
1200 #ifdef ENABLE_MANAGEMENT
1201 /*
1202  * For deferred auth, this is where the management interface calls (on server)
1203  * to indicate auth failure/success.
1204  */
1205 bool
tls_authenticate_key(struct tls_multi * multi,const unsigned int mda_key_id,const bool auth,const char * client_reason)1206 tls_authenticate_key(struct tls_multi *multi, const unsigned int mda_key_id, const bool auth, const char *client_reason)
1207 {
1208     bool ret = false;
1209     if (multi)
1210     {
1211         int i;
1212         auth_set_client_reason(multi, client_reason);
1213         for (i = 0; i < KEY_SCAN_SIZE; ++i)
1214         {
1215             struct key_state *ks = get_key_scan(multi, i);
1216             if (ks->mda_key_id == mda_key_id)
1217             {
1218                 ks->mda_status = auth ? ACF_SUCCEEDED : ACF_FAILED;
1219                 ret = true;
1220             }
1221         }
1222     }
1223     return ret;
1224 }
1225 #endif /* ifdef ENABLE_MANAGEMENT */
1226 
1227 
1228 /* ****************************************************************************
1229  * Functions to verify username and password
1230  *
1231  * Authenticate a client using username/password.
1232  * Runs on server.
1233  *
1234  * If you want to add new authentication methods,
1235  * this is the place to start.
1236  *************************************************************************** */
1237 
1238 /*
1239  * Verify the user name and password using a script
1240  */
1241 static int
verify_user_pass_script(struct tls_session * session,struct tls_multi * multi,const struct user_pass * up)1242 verify_user_pass_script(struct tls_session *session, struct tls_multi *multi,
1243                         const struct user_pass *up)
1244 {
1245     struct gc_arena gc = gc_new();
1246     struct argv argv = argv_new();
1247     const char *tmp_file = "";
1248     int retval = OPENVPN_PLUGIN_FUNC_ERROR;
1249     struct key_state *ks = &session->key[KS_PRIMARY];      /* primary key */
1250 
1251     /* Set environmental variables prior to calling script */
1252     setenv_str(session->opt->es, "script_type", "user-pass-verify");
1253 
1254     /* format command line */
1255     argv_parse_cmd(&argv, session->opt->auth_user_pass_verify_script);
1256 
1257     if (session->opt->auth_user_pass_verify_script_via_file)
1258     {
1259         struct status_output *so;
1260 
1261         tmp_file = platform_create_temp_file(session->opt->tmp_dir, "up",
1262                                              &gc);
1263         if (tmp_file)
1264         {
1265             so = status_open(tmp_file, 0, -1, NULL, STATUS_OUTPUT_WRITE);
1266             status_printf(so, "%s", up->username);
1267             status_printf(so, "%s", up->password);
1268             if (!status_close(so))
1269             {
1270                 msg(D_TLS_ERRORS, "TLS Auth Error: could not write username/password to file: %s",
1271                     tmp_file);
1272                 goto done;
1273             }
1274             /* pass temp file name to script */
1275             argv_printf_cat(&argv, "%s", tmp_file);
1276         }
1277     }
1278     else
1279     {
1280         setenv_str(session->opt->es, "username", up->username);
1281         setenv_str(session->opt->es, "password", up->password);
1282     }
1283 
1284     /* generate filename for deferred auth control file */
1285     if (!key_state_gen_auth_control_files(&ks->script_auth, session->opt))
1286     {
1287         msg(D_TLS_ERRORS, "TLS Auth Error (%s): "
1288                           "could not create deferred auth control file", __func__);
1289         return OPENVPN_PLUGIN_FUNC_ERROR;
1290     }
1291 
1292     /* call command */
1293     int script_ret = openvpn_run_script(&argv, session->opt->es, S_EXITCODE,
1294                                         "--auth-user-pass-verify");
1295     switch (script_ret)
1296     {
1297        case 0:
1298            retval = OPENVPN_PLUGIN_FUNC_SUCCESS;
1299            break;
1300        case 2:
1301            retval = OPENVPN_PLUGIN_FUNC_DEFERRED;
1302            break;
1303        default:
1304            retval = OPENVPN_PLUGIN_FUNC_ERROR;
1305            break;
1306     }
1307     if (retval == OPENVPN_PLUGIN_FUNC_DEFERRED)
1308     {
1309         /* Check if we the plugin has written the pending auth control
1310          * file and send the pending auth to the client */
1311         if(!key_state_check_auth_pending_file(&ks->script_auth,
1312                                               multi))
1313         {
1314             retval = OPENVPN_PLUGIN_FUNC_ERROR;
1315             key_state_rm_auth_control_files(&ks->script_auth);
1316         }
1317 
1318     }
1319     else
1320     {
1321         /* purge auth control filename (and file itself) for non-deferred returns */
1322         key_state_rm_auth_control_files(&ks->script_auth);
1323     }
1324     if (!session->opt->auth_user_pass_verify_script_via_file)
1325     {
1326         setenv_del(session->opt->es, "password");
1327     }
1328 
1329 done:
1330     if (tmp_file && strlen(tmp_file) > 0)
1331     {
1332         platform_unlink(tmp_file);
1333     }
1334 
1335     argv_free(&argv);
1336     gc_free(&gc);
1337     return retval;
1338 }
1339 
1340 /*
1341  * Verify the username and password using a plugin
1342  */
1343 static int
verify_user_pass_plugin(struct tls_session * session,struct tls_multi * multi,const struct user_pass * up)1344 verify_user_pass_plugin(struct tls_session *session, struct tls_multi *multi,
1345                         const struct user_pass *up)
1346 {
1347     int retval = OPENVPN_PLUGIN_FUNC_ERROR;
1348     struct key_state *ks = &session->key[KS_PRIMARY];      /* primary key */
1349 
1350     /* set password in private env space */
1351     setenv_str(session->opt->es, "password", up->password);
1352 
1353     /* generate filename for deferred auth control file */
1354     if (!key_state_gen_auth_control_files(&ks->plugin_auth, session->opt))
1355     {
1356         msg(D_TLS_ERRORS, "TLS Auth Error (%s): "
1357             "could not create deferred auth control file", __func__);
1358         return retval;
1359     }
1360 
1361     /* call command */
1362     retval = plugin_call(session->opt->plugins, OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY, NULL, NULL, session->opt->es);
1363 
1364     if (retval == OPENVPN_PLUGIN_FUNC_DEFERRED)
1365     {
1366         /* Check if the plugin has written the pending auth control
1367          * file and send the pending auth to the client */
1368         if(!key_state_check_auth_pending_file(&ks->plugin_auth, multi))
1369         {
1370             retval = OPENVPN_PLUGIN_FUNC_ERROR;
1371             key_state_rm_auth_control_files(&ks->plugin_auth);
1372         }
1373     }
1374     else
1375     {
1376         /* purge auth control filename (and file itself) for non-deferred returns */
1377         key_state_rm_auth_control_files(&ks->plugin_auth);
1378     }
1379 
1380     setenv_del(session->opt->es, "password");
1381 
1382     return retval;
1383 }
1384 
1385 
1386 #ifdef ENABLE_MANAGEMENT
1387 /*
1388  * management deferred internal ssl_verify.c status codes
1389  */
1390 #define KMDA_ERROR   0
1391 #define KMDA_SUCCESS 1
1392 #define KMDA_UNDEF   2
1393 #define KMDA_DEF     3
1394 
1395 static int
verify_user_pass_management(struct tls_session * session,struct tls_multi * multi,const struct user_pass * up)1396 verify_user_pass_management(struct tls_session *session,
1397                             struct tls_multi *multi,
1398                             const struct user_pass *up)
1399 {
1400     int retval = KMDA_ERROR;
1401     struct key_state *ks = &session->key[KS_PRIMARY];      /* primary key */
1402 
1403     /* set username/password in private env space */
1404     setenv_str(session->opt->es, "password", up->password);
1405 
1406     if (management)
1407     {
1408         management_notify_client_needing_auth(management, ks->mda_key_id, session->opt->mda_context, session->opt->es);
1409     }
1410 
1411     setenv_del(session->opt->es, "password");
1412 
1413     retval = KMDA_SUCCESS;
1414 
1415     return retval;
1416 }
1417 #endif /* ifdef ENABLE_MANAGEMENT */
1418 
1419 static bool
set_verify_user_pass_env(struct user_pass * up,struct tls_multi * multi,struct tls_session * session)1420 set_verify_user_pass_env(struct user_pass *up, struct tls_multi *multi,
1421                          struct tls_session *session)
1422 {
1423     /* Is username defined? */
1424     if ((session->opt->ssl_flags & SSLF_AUTH_USER_PASS_OPTIONAL) || strlen(up->username))
1425     {
1426         setenv_str(session->opt->es, "username", up->username);
1427 
1428         /* setenv incoming cert common name for script */
1429         setenv_str(session->opt->es, "common_name", session->common_name);
1430 
1431         /* setenv client real IP address */
1432         setenv_untrusted(session);
1433 
1434         /*
1435          * if we are using auth-gen-token, send also the session id of auth gen token to
1436          * allow the management to figure out if it is a new session or a continued one
1437          */
1438         add_session_token_env(session, multi, up);
1439         return true;
1440     }
1441     else
1442     {
1443         msg(D_TLS_ERRORS, "TLS Auth Error: peer provided a blank username");
1444         return false;
1445     }
1446 }
1447 
1448 /**
1449  * Main username/password verification entry point
1450  *
1451  * Will set session->ks[KS_PRIMARY].authenticated according to
1452  * result of the username/password verification
1453  */
1454 void
verify_user_pass(struct user_pass * up,struct tls_multi * multi,struct tls_session * session)1455 verify_user_pass(struct user_pass *up, struct tls_multi *multi,
1456                  struct tls_session *session)
1457 {
1458     struct key_state *ks = &session->key[KS_PRIMARY];      /* primary key */
1459 
1460 #ifdef ENABLE_MANAGEMENT
1461     int man_def_auth = KMDA_UNDEF;
1462 
1463     if (management_enable_def_auth(management))
1464     {
1465         man_def_auth = KMDA_DEF;
1466     }
1467 #endif
1468 
1469     /* enforce character class restrictions in username/password */
1470     string_mod_remap_name(up->username);
1471     string_mod(up->password, CC_PRINT, CC_CRLF, '_');
1472 
1473     /*
1474      * If auth token succeeds we skip the auth
1475      * methods unless otherwise specified
1476      */
1477     bool skip_auth = false;
1478 
1479     /*
1480      * If server is configured with --auth-gen-token and the client sends
1481      * something that looks like an authentication token, this
1482      * round will be done internally using the token instead of
1483      * calling any external authentication modules.
1484      */
1485     if (session->opt->auth_token_generate && is_auth_token(up->password))
1486     {
1487         multi->auth_token_state_flags = verify_auth_token(up, multi, session);
1488         if (session->opt->auth_token_call_auth)
1489         {
1490             /*
1491              * we do not care about the result here because it is
1492              * the responsibility of the external authentication to
1493              * decide what to do with the result
1494              */
1495         }
1496         else if (multi->auth_token_state_flags == AUTH_TOKEN_HMAC_OK)
1497         {
1498             /*
1499              * We do not want the EXPIRED or EMPTY USER flags here so check
1500              * for equality with AUTH_TOKEN_HMAC_OK
1501              */
1502             msg(M_WARN, "TLS: Username/auth-token authentication "
1503                 "succeeded for username '%s'",
1504                 up->username);
1505             skip_auth = true;
1506         }
1507         else
1508         {
1509             wipe_auth_token(multi);
1510             ks->authenticated = KS_AUTH_FALSE;
1511             msg(M_WARN, "TLS: Username/auth-token authentication "
1512                 "failed for username '%s'", up->username);
1513             return;
1514         }
1515     }
1516 
1517     int plugin_status = OPENVPN_PLUGIN_FUNC_SUCCESS;
1518     int script_status = OPENVPN_PLUGIN_FUNC_SUCCESS;
1519     /* Set the environment variables used by all auth variants */
1520     if (!set_verify_user_pass_env(up, multi, session))
1521     {
1522         skip_auth = true;
1523         plugin_status = OPENVPN_PLUGIN_FUNC_ERROR;
1524     }
1525 
1526     /* call plugin(s) and/or script */
1527     if (!skip_auth)
1528     {
1529 #ifdef ENABLE_MANAGEMENT
1530         if (man_def_auth == KMDA_DEF)
1531         {
1532             man_def_auth = verify_user_pass_management(session, multi, up);
1533         }
1534 #endif
1535         if (plugin_defined(session->opt->plugins, OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY))
1536         {
1537             plugin_status = verify_user_pass_plugin(session, multi, up);
1538         }
1539 
1540         if (session->opt->auth_user_pass_verify_script)
1541         {
1542             script_status = verify_user_pass_script(session, multi, up);
1543         }
1544     }
1545 
1546     /* check sizing of username if it will become our common name */
1547     if ((session->opt->ssl_flags & SSLF_USERNAME_AS_COMMON_NAME)
1548         && strlen(up->username)>TLS_USERNAME_LEN)
1549     {
1550         msg(D_TLS_ERRORS,
1551             "TLS Auth Error: --username-as-common name specified and username is longer than the maximum permitted Common Name length of %d characters",
1552             TLS_USERNAME_LEN);
1553         plugin_status = OPENVPN_PLUGIN_FUNC_ERROR;
1554         script_status = OPENVPN_PLUGIN_FUNC_ERROR;
1555     }
1556     /* auth succeeded? */
1557     bool plugin_ok = plugin_status == OPENVPN_PLUGIN_FUNC_SUCCESS
1558         || plugin_status == OPENVPN_PLUGIN_FUNC_DEFERRED;
1559 
1560     bool script_ok =  script_status == OPENVPN_PLUGIN_FUNC_SUCCESS
1561         || script_status ==  OPENVPN_PLUGIN_FUNC_DEFERRED;
1562 
1563     if (script_ok && plugin_ok && tls_lock_username(multi, up->username)
1564 #ifdef ENABLE_MANAGEMENT
1565         && man_def_auth != KMDA_ERROR
1566 #endif
1567         )
1568     {
1569         ks->authenticated = KS_AUTH_TRUE;
1570         if (plugin_status == OPENVPN_PLUGIN_FUNC_DEFERRED
1571             || script_status == OPENVPN_PLUGIN_FUNC_DEFERRED)
1572         {
1573             ks->authenticated = KS_AUTH_DEFERRED;
1574         }
1575 #ifdef ENABLE_MANAGEMENT
1576         if (man_def_auth != KMDA_UNDEF)
1577         {
1578             ks->authenticated = KS_AUTH_DEFERRED;
1579         }
1580 #endif
1581         if ((session->opt->ssl_flags & SSLF_USERNAME_AS_COMMON_NAME))
1582         {
1583             set_common_name(session, up->username);
1584         }
1585 
1586         if ((session->opt->auth_token_generate))
1587         {
1588             /*
1589              * If we accepted a (not expired) token, i.e.
1590              * initial auth via token on new connection, we need
1591              * to store the auth-token in multi->auth_token, so
1592              * the initial timestamp and session id can be extracted from it
1593              */
1594             if (!multi->auth_token
1595                 && (multi->auth_token_state_flags & AUTH_TOKEN_HMAC_OK)
1596                 && !(multi->auth_token_state_flags & AUTH_TOKEN_EXPIRED))
1597             {
1598                 multi->auth_token = strdup(up->password);
1599             }
1600 
1601             /*
1602              * Server is configured with --auth-gen-token. Generate or renew
1603              * the token.
1604              */
1605             generate_auth_token(up, multi);
1606         }
1607         /*
1608          * Auth token already sent to client, update auth-token on client.
1609          * The initial auth-token is sent as part of the push message, for this
1610          * update we need to schedule an extra push message.
1611          *
1612          * Otherwise the auth-token get pushed out as part of the "normal"
1613          * push-reply
1614          */
1615         if (multi->auth_token_initial)
1616         {
1617             /*
1618              * We do not explicitly schedule the sending of the
1619              * control message here but control message are only
1620              * postponed when the control channel  is not yet fully
1621              * established and furthermore since this is called in
1622              * the middle of authentication, there are other messages
1623              * (new data channel keys) that are sent anyway and will
1624              * trigger schedueling
1625              */
1626             send_push_reply_auth_token(multi);
1627         }
1628         msg(D_HANDSHAKE, "TLS: Username/Password authentication %s for username '%s' %s",
1629             (ks->authenticated == KS_AUTH_DEFERRED) ? "deferred" : "succeeded",
1630             up->username,
1631             (session->opt->ssl_flags & SSLF_USERNAME_AS_COMMON_NAME) ? "[CN SET]" : "");
1632     }
1633     else
1634     {
1635         ks->authenticated = KS_AUTH_FALSE;
1636         msg(D_TLS_ERRORS, "TLS Auth Error: Auth Username/Password verification failed for peer");
1637     }
1638 }
1639 
1640 void
verify_final_auth_checks(struct tls_multi * multi,struct tls_session * session)1641 verify_final_auth_checks(struct tls_multi *multi, struct tls_session *session)
1642 {
1643     struct key_state *ks = &session->key[KS_PRIMARY];      /* primary key */
1644 
1645     /* While it shouldn't really happen, don't allow the common name to be NULL */
1646     if (!session->common_name)
1647     {
1648         set_common_name(session, "");
1649     }
1650 
1651     /* Don't allow the CN to change once it's been locked */
1652     if (ks->authenticated > KS_AUTH_FALSE && multi->locked_cn)
1653     {
1654         const char *cn = session->common_name;
1655         if (cn && strcmp(cn, multi->locked_cn))
1656         {
1657             msg(D_TLS_ERRORS, "TLS Auth Error: TLS object CN attempted to change from '%s' to '%s' -- tunnel disabled",
1658                 multi->locked_cn,
1659                 cn);
1660 
1661             /* change the common name back to its original value and disable the tunnel */
1662             set_common_name(session, multi->locked_cn);
1663             tls_deauthenticate(multi);
1664         }
1665     }
1666 
1667     /* Don't allow the cert hashes to change once they have been locked */
1668     if (ks->authenticated > KS_AUTH_FALSE && multi->locked_cert_hash_set)
1669     {
1670         const struct cert_hash_set *chs = session->cert_hash_set;
1671         if (chs && !cert_hash_compare(chs, multi->locked_cert_hash_set))
1672         {
1673             msg(D_TLS_ERRORS, "TLS Auth Error: TLS object CN=%s client-provided SSL certs unexpectedly changed during mid-session reauth",
1674                 session->common_name);
1675 
1676             /* disable the tunnel */
1677             tls_deauthenticate(multi);
1678         }
1679     }
1680 
1681     /* verify --client-config-dir based authentication */
1682     if (ks->authenticated > KS_AUTH_FALSE && session->opt->client_config_dir_exclusive)
1683     {
1684         struct gc_arena gc = gc_new();
1685 
1686         const char *cn = session->common_name;
1687         const char *path = platform_gen_path(session->opt->client_config_dir_exclusive,
1688                                              cn, &gc);
1689         if (!cn || !strcmp(cn, CCD_DEFAULT) || !platform_test_file(path))
1690         {
1691             ks->authenticated = KS_AUTH_FALSE;
1692             wipe_auth_token(multi);
1693             msg(D_TLS_ERRORS, "TLS Auth Error: --client-config-dir authentication failed for common name '%s' file='%s'",
1694                 session->common_name,
1695                 path ? path : "UNDEF");
1696         }
1697 
1698         gc_free(&gc);
1699     }
1700 }
1701 
1702 void
tls_x509_clear_env(struct env_set * es)1703 tls_x509_clear_env(struct env_set *es)
1704 {
1705     struct env_item *item = es->list;
1706     while (item)
1707     {
1708         struct env_item *next = item->next;
1709         if (item->string
1710             && 0 == strncmp("X509_", item->string, strlen("X509_")))
1711         {
1712             env_set_del(es, item->string);
1713         }
1714         item = next;
1715     }
1716 }
1717