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-2022 OpenVPN Inc <sales@openvpn.net>
9  *  Copyright (C) 2010-2021 Fox Crypto B.V. <openvpn@foxcrypto.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 Common Data Structures
27  */
28 
29 #ifndef SSL_COMMON_H_
30 #define SSL_COMMON_H_
31 
32 #include "session_id.h"
33 #include "socket.h"
34 #include "packet_id.h"
35 #include "crypto.h"
36 #include "options.h"
37 
38 #include "ssl_backend.h"
39 
40 /* passwords */
41 #define UP_TYPE_AUTH        "Auth"
42 #define UP_TYPE_PRIVATE_KEY "Private Key"
43 
44 /** @addtogroup control_processor
45  *  @{ */
46 /**
47  * @name Control channel negotiation states
48  *
49  * These states represent the different phases of control channel
50  * negotiation between OpenVPN peers.  OpenVPN servers and clients
51  * progress through the states in a different order, because of their
52  * different roles during exchange of random material.  The references to
53  * the \c key_source2 structure in the list below is only valid if %key
54  * method 2 is being used.  See the \link key_generation data channel key
55  * generation\endlink related page for more information.
56  *
57  * Clients follow this order:
58  *   -# \c S_INITIAL, ready to begin three-way handshake and control
59  *      channel negotiation.
60  *   -# \c S_PRE_START, have started three-way handshake, waiting for
61  *      acknowledgment from remote.
62  *   -# \c S_START, initial three-way handshake complete.
63  *   -# \c S_SENT_KEY, have sent local part of \c key_source2 random
64  *      material.
65  *   -# \c S_GOT_KEY, have received remote part of \c key_source2 random
66  *      material.
67  *   -# \c S_ACTIVE, normal operation
68  *
69  * Servers follow the same order, except for \c S_SENT_KEY and \c
70  * S_GOT_KEY being reversed, because the server first receives the
71  * client's \c key_source2 random material before generating and sending
72  * its own.
73  *
74  * @{
75  */
76 #define S_ERROR          -1     /**< Error state.  */
77 #define S_UNDEF           0     /**< Undefined state, used after a \c
78                                  *   key_state is cleaned up. */
79 #define S_INITIAL         1     /**< Initial \c key_state state after
80                                  *   initialization by \c key_state_init()
81                                  *   before start of three-way handshake. */
82 #define S_PRE_START       2     /**< Waiting for the remote OpenVPN peer
83                                  *   to acknowledge during the initial
84                                  *   three-way handshake. */
85 #define S_START           3     /**< Three-way handshake is complete,
86                                  *   start of key exchange. */
87 #define S_SENT_KEY        4     /**< Local OpenVPN process has sent its
88                                  *   part of the key material. */
89 #define S_GOT_KEY         5     /**< Local OpenVPN process has received
90                                  *   the remote's part of the key
91                                  *   material. */
92 #define S_ACTIVE          6     /**< Operational \c key_state state
93                                  *   immediately after negotiation has
94                                  *   completed while still within the
95                                  *   handshake window. */
96 /* Note that earlier versions also had a S_OP_NORMAL state that was
97  * virtually identical with S_ACTIVE and the code still assumes everything
98  * >= S_ACTIVE to be fully operational */
99 /** @} name Control channel negotiation states */
100 /** @} addtogroup control_processor */
101 
102 /**
103  * Container for one half of random material to be used in %key method 2
104  * \ref key_generation "data channel key generation".
105  * @ingroup control_processor
106  */
107 struct key_source {
108     uint8_t pre_master[48];     /**< Random used for master secret
109                                  *   generation, provided only by client
110                                  *   OpenVPN peer. */
111     uint8_t random1[32];        /**< Seed used for master secret
112                                  *   generation, provided by both client
113                                  *   and server. */
114     uint8_t random2[32];        /**< Seed used for key expansion, provided
115                                  *   by both client and server. */
116 };
117 
118 
119 /**
120  * Container for both halves of random material to be used in %key method
121  * 2 \ref key_generation "data channel key generation".
122  * @ingroup control_processor
123  */
124 struct key_source2 {
125     struct key_source client;   /**< Random provided by client. */
126     struct key_source server;   /**< Random provided by server. */
127 };
128 
129 
130 /**
131  * This reflects the (server side) authentication state after the TLS
132  * session has been established and key_method_2_read is called. If async auth
133  * is enabled the state will first move to KS_AUTH_DEFERRED before eventually
134  * being set to KS_AUTH_TRUE or KS_AUTH_FALSE
135  * Only KS_AUTH_TRUE is fully authenticated
136  */
137 enum ks_auth_state {
138   KS_AUTH_FALSE,              /**< Key state is not authenticated  */
139   KS_AUTH_DEFERRED,           /**< Key state authentication is being deferred,
140                                 * by async auth */
141   KS_AUTH_TRUE                /**< Key state is authenticated. TLS and user/pass
142                                 * succeeded. This includes AUTH_PENDING/OOB
143                                 * authentication as those hold the
144                                 * connection artificially in KS_AUTH_DEFERRED
145                                 */
146 };
147 
148 /**
149  * Security parameter state of one TLS and data channel %key session.
150  * @ingroup control_processor
151  *
152  * This structure represents one security parameter session between
153  * OpenVPN peers.  It includes the control channel TLS state and the data
154  * channel crypto state.  It also contains the reliability layer
155  * structures used for control channel messages.
156  *
157  * A new \c key_state structure is initialized for each hard or soft
158  * reset.
159  *
160  * @see
161  *  - This structure should be initialized using the \c key_state_init()
162  *    function.
163  *  - This structure should be cleaned up using the \c key_state_free()
164  *    function.
165  */
166 struct key_state
167 {
168     int state;
169     /** The state of the auth-token sent from the client */
170     int auth_token_state_flags;
171 
172     /**
173      * Key id for this key_state,  inherited from struct tls_session.
174      * @see tls_session::key_id.
175      */
176     int key_id;
177 
178     struct key_state_ssl ks_ssl; /* contains SSL object and BIOs for the control channel */
179 
180     time_t established;         /* when our state went S_ACTIVE */
181     time_t must_negotiate;      /* key negotiation times out if not finished before this time */
182     time_t must_die;            /* this object is destroyed at this time */
183 
184     int initial_opcode;         /* our initial P_ opcode */
185     struct session_id session_id_remote; /* peer's random session ID */
186     struct link_socket_actual remote_addr; /* peer's IP addr */
187 
188     struct crypto_options crypto_options;/* data channel crypto options */
189 
190     struct key_source2 *key_src;       /* source entropy for key expansion */
191 
192     struct buffer plaintext_read_buf;
193     struct buffer plaintext_write_buf;
194     struct buffer ack_write_buf;
195 
196     struct reliable *send_reliable; /* holds a copy of outgoing packets until ACK received */
197     struct reliable *rec_reliable; /* order incoming ciphertext packets before we pass to TLS */
198     struct reliable_ack *rec_ack; /* buffers all packet IDs we want to ACK back to sender */
199 
200     struct buffer_list *paybuf;
201 
202     counter_type n_bytes;                /* how many bytes sent/recvd since last key exchange */
203     counter_type n_packets;              /* how many packets sent/recvd since last key exchange */
204 
205     /*
206      * If bad username/password, TLS connection will come up but 'authenticated' will be false.
207      */
208     enum ks_auth_state authenticated;
209     time_t auth_deferred_expire;
210 
211 #ifdef MANAGEMENT_DEF_AUTH
212     unsigned int mda_key_id;
213     unsigned int mda_status;
214 #endif
215 #ifdef PLUGIN_DEF_AUTH
216     unsigned int auth_control_status;
217     time_t acf_last_mod;
218     char *auth_control_file;
219 #endif
220 };
221 
222 /** Control channel wrapping (--tls-auth/--tls-crypt) context */
223 struct tls_wrap_ctx
224 {
225     enum {
226         TLS_WRAP_NONE = 0, /**< No control channel wrapping */
227         TLS_WRAP_AUTH,  /**< Control channel authentication */
228         TLS_WRAP_CRYPT, /**< Control channel encryption and authentication */
229     } mode;                     /**< Control channel wrapping mode */
230     struct crypto_options opt;  /**< Crypto state */
231     struct buffer work;         /**< Work buffer (only for --tls-crypt) */
232     struct key_ctx tls_crypt_v2_server_key;  /**< Decrypts client keys */
233     const struct buffer *tls_crypt_v2_wkc;   /**< Wrapped client key,
234                                               *   sent to server */
235     struct buffer tls_crypt_v2_metadata;     /**< Received from client */
236     bool cleanup_key_ctx;                    /**< opt.key_ctx_bi is owned by
237                                               *   this context */
238 };
239 
240 /*
241  * Our const options, obtained directly or derived from
242  * command line options.
243  */
244 struct tls_options
245 {
246     /* our master TLS context from which all SSL objects derived */
247     struct tls_root_ctx ssl_ctx;
248 
249     /* data channel cipher, hmac, and key lengths */
250     struct key_type key_type;
251 
252     /* true if we are a TLS server, client otherwise */
253     bool server;
254 
255     /* if true, don't xmit until first packet from peer is received */
256     bool xmit_hold;
257 
258     /* local and remote options strings
259      * that must match between client and server */
260     const char *local_options;
261     const char *remote_options;
262 
263     /* from command line */
264     bool replay;
265     bool single_session;
266     bool disable_occ;
267     int mode;
268     bool pull;
269     int push_peer_info_detail;
270     int transition_window;
271     int handshake_window;
272     interval_t packet_timeout;
273     int renegotiate_bytes;
274     int renegotiate_packets;
275     interval_t renegotiate_seconds;
276 
277     /* cert verification parms */
278     const char *verify_command;
279     const char *verify_export_cert;
280     int verify_x509_type;
281     const char *verify_x509_name;
282     const char *crl_file;
283     bool crl_file_inline;
284     int ns_cert_type;
285     unsigned remote_cert_ku[MAX_PARMS];
286     const char *remote_cert_eku;
287     uint8_t *verify_hash;
288     hash_algo_type verify_hash_algo;
289     char *x509_username_field;
290 
291     /* allow openvpn config info to be
292      * passed over control channel */
293     bool pass_config_info;
294 
295     /* struct crypto_option flags */
296     unsigned int crypto_flags;
297 
298     int replay_window;                 /* --replay-window parm */
299     int replay_time;                   /* --replay-window parm */
300     bool tcp_mode;
301 
302     const char *config_ciphername;
303     const char *config_ncp_ciphers;
304     bool ncp_enabled;
305 
306     bool tls_crypt_v2;
307     const char *tls_crypt_v2_verify_script;
308 
309     /** TLS handshake wrapping state */
310     struct tls_wrap_ctx tls_wrap;
311 
312     struct frame frame;
313 
314     /* used for username/password authentication */
315     const char *auth_user_pass_verify_script;
316     bool auth_user_pass_verify_script_via_file;
317     const char *tmp_dir;
318     const char *auth_user_pass_file;
319 
320     bool auth_token_generate;   /**< Generate auth-tokens on successful
321                                  * user/pass auth,seet via
322                                  * options->auth_token_generate. */
323     bool auth_token_call_auth; /**< always call normal authentication */
324     unsigned int auth_token_lifetime;
325 
326     struct key_ctx auth_token_key;
327 
328     /* use the client-config-dir as a positive authenticator */
329     const char *client_config_dir_exclusive;
330 
331     /* instance-wide environment variable set */
332     struct env_set *es;
333     openvpn_net_ctx_t *net_ctx;
334     const struct plugin_list *plugins;
335 
336     /* compression parms */
337 #ifdef USE_COMP
338     struct compress_options comp_options;
339 #endif
340 
341     /* configuration file SSL-related boolean and low-permutation options */
342 #define SSLF_CLIENT_CERT_NOT_REQUIRED (1<<0)
343 #define SSLF_CLIENT_CERT_OPTIONAL     (1<<1)
344 #define SSLF_USERNAME_AS_COMMON_NAME  (1<<2)
345 #define SSLF_AUTH_USER_PASS_OPTIONAL  (1<<3)
346 #define SSLF_OPT_VERIFY               (1<<4)
347 #define SSLF_CRL_VERIFY_DIR           (1<<5)
348 #define SSLF_TLS_VERSION_MIN_SHIFT    6
349 #define SSLF_TLS_VERSION_MIN_MASK     0xF  /* (uses bit positions 6 to 9) */
350 #define SSLF_TLS_VERSION_MAX_SHIFT    10
351 #define SSLF_TLS_VERSION_MAX_MASK     0xF  /* (uses bit positions 10 to 13) */
352 #define SSLF_TLS_DEBUG_ENABLED        (1<<14)
353     unsigned int ssl_flags;
354 
355 #ifdef MANAGEMENT_DEF_AUTH
356     struct man_def_auth_context *mda_context;
357 #endif
358 
359     const struct x509_track *x509_track;
360 
361 #ifdef ENABLE_MANAGEMENT
362     const struct static_challenge_info *sci;
363 #endif
364 
365     /* --gremlin bits */
366     int gremlin;
367 
368     /* Keying Material Exporter [RFC 5705] parameters */
369     const char *ekm_label;
370     size_t ekm_label_size;
371     size_t ekm_size;
372 };
373 
374 /** @addtogroup control_processor
375  *  @{ */
376 /** @name Index of key_state objects within a tls_session structure
377  *
378  *  This is the index of \c tls_session.key
379  *
380  *  @{ */
381 #define KS_PRIMARY    0         /**< Primary %key state index. */
382 #define KS_LAME_DUCK  1         /**< %Key state index that will retire
383                                  *   soon. */
384 #define KS_SIZE       2         /**< Size of the \c tls_session.key array. */
385 /** @} name Index of key_state objects within a tls_session structure */
386 /** @} addtogroup control_processor */
387 
388 /**
389  * Security parameter state of a single session within a VPN tunnel.
390  * @ingroup control_processor
391  *
392  * This structure represents an OpenVPN peer-to-peer control channel
393  * session.
394  *
395  * A \c tls_session remains over soft resets, but a new instance is
396  * initialized for each hard reset.
397  *
398  * @see
399  *  - This structure should be initialized using the \c tls_session_init()
400  *    function.
401  *  - This structure should be cleaned up using the \c tls_session_free()
402  *    function.
403  */
404 struct tls_session
405 {
406     /* const options and config info */
407     struct tls_options *opt;
408 
409     /* during hard reset used to control burst retransmit */
410     bool burst;
411 
412     /* authenticate control packets */
413     struct tls_wrap_ctx tls_wrap;
414 
415     int initial_opcode;         /* our initial P_ opcode */
416     struct session_id session_id; /* our random session ID */
417 
418     /**
419      * The current active key id, used to keep track of renegotiations.
420      * key_id increments with each soft reset to KEY_ID_MASK then recycles back
421      * to 1.  This way you know that if key_id is 0, it is the first key.
422      */
423     int key_id;
424 
425     int limit_next;             /* used for traffic shaping on the control channel */
426 
427     int verify_maxlevel;
428 
429     char *common_name;
430 
431     struct cert_hash_set *cert_hash_set;
432 
433 #ifdef ENABLE_PF
434     uint32_t common_name_hashval;
435 #endif
436 
437     bool verified;              /* true if peer certificate was verified against CA */
438 
439     /* not-yet-authenticated incoming client */
440     struct link_socket_actual untrusted_addr;
441 
442     struct key_state key[KS_SIZE];
443 };
444 
445 /** @addtogroup control_processor
446  *  @{ */
447 /** @name Index of tls_session objects within a tls_multi structure
448  *
449  *  This is the index of \c tls_multi.session
450  *
451  *  Normally three tls_session objects are maintained by an active openvpn
452  *  session.  The first is the current, TLS authenticated session, the
453  *  second is used to process connection requests from a new client that
454  *  would usurp the current session if successfully authenticated, and the
455  *  third is used as a repository for a "lame-duck" %key in the event that
456  *  the primary session resets due to error while the lame-duck %key still
457  *  has time left before its expiration.  Lame duck keys are used to
458  *  maintain the continuity of the data channel connection while a new %key
459  *  is being negotiated.
460  *
461  *  @{ */
462 #define TM_ACTIVE    0          /**< Active \c tls_session. */
463 #define TM_UNTRUSTED 1          /**< As yet un-trusted \c tls_session
464                                  *   being negotiated. */
465 #define TM_LAME_DUCK 2          /**< Old \c tls_session. */
466 #define TM_SIZE      3          /**< Size of the \c tls_multi.session
467                                  *   array. */
468 /** @} name Index of tls_session objects within a tls_multi structure */
469 /** @} addtogroup control_processor */
470 
471 
472 /*
473  * The number of keys we will scan on encrypt or decrypt.  The first
474  * is the "active" key.  The second is the lame_duck or retiring key
475  * associated with the active key's session ID.  The third is a detached
476  * lame duck session that only occurs in situations where a key renegotiate
477  * failed on the active key, but a lame duck key was still valid.  By
478  * preserving the lame duck session, we can be assured of having a data
479  * channel key available even when network conditions are so bad that
480  * we can't negotiate a new key within the time allotted.
481  */
482 #define KEY_SCAN_SIZE 3
483 
484 
485 /* client authentication state, CAS_SUCCEEDED must be 0 since
486  * non multi code path still checks this variable but does not initialise it
487  * so the code depends on zero initialisation */
488 enum client_connect_status {
489     CAS_SUCCEEDED=0,
490     CAS_PENDING,
491     CAS_PENDING_DEFERRED,
492     CAS_PENDING_DEFERRED_PARTIAL,   /**< at least handler succeeded, no result yet*/
493     CAS_FAILED,
494 };
495 
496 
497 /**
498  * Security parameter state for a single VPN tunnel.
499  * @ingroup control_processor
500  *
501  * An active VPN tunnel running with TLS enabled has one \c tls_multi
502  * object, in which it stores all control channel and data channel
503  * security parameter state.  This structure can contain multiple,
504  * possibly simultaneously active, \c tls_context objects to allow for
505  * interruption-less transitions during session renegotiations.  Each \c
506  * tls_context represents one control channel session, which can span
507  * multiple data channel security parameter sessions stored in \c
508  * key_state structures.
509  */
510 struct tls_multi
511 {
512     /* used to coordinate access between main thread and TLS thread */
513     /*MUTEX_PTR_DEFINE (mutex);*/
514 
515     /* const options and config info */
516     struct tls_options opt;
517 
518     struct key_state *key_scan[KEY_SCAN_SIZE];
519     /**< List of \c key_state objects in the
520      *   order they should be scanned by data
521      *   channel modules. */
522 
523     /*
524      * used by tls_pre_encrypt to communicate the encrypt key
525      * to tls_post_encrypt()
526      */
527     struct key_state *save_ks;  /* temporary pointer used between pre/post routines */
528 
529     /*
530      * Used to return outgoing address from
531      * tls_multi_process.
532      */
533     struct link_socket_actual to_link_addr;
534 
535     int n_sessions;             /**< Number of sessions negotiated thus
536                                  *   far. */
537     enum client_connect_status multi_state;
538 
539     /*
540      * Number of errors.
541      */
542     int n_hard_errors; /* errors due to TLS negotiation failure */
543     int n_soft_errors; /* errors due to unrecognized or failed-to-authenticate incoming packets */
544 
545     /*
546      * Our locked common name, username, and cert hashes (cannot change during the life of this tls_multi object)
547      */
548     char *locked_cn;
549     char *locked_username;
550     struct cert_hash_set *locked_cert_hash_set;
551 
552 #ifdef ENABLE_DEF_AUTH
553     /* Time of last call to tls_authentication_status */
554     time_t tas_last;
555 #endif
556 
557     /*
558      * An error message to send to client on AUTH_FAILED
559      */
560     char *client_reason;
561 
562     /*
563      * A multi-line string of general-purpose info received from peer
564      * over control channel.
565      */
566     char *peer_info;
567     char *auth_token;    /**< If server sends a generated auth-token,
568                           *   this is the token to use for future
569                           *   user/pass authentications in this session.
570                           */
571     char *auth_token_initial;
572     /**< The first auth-token we sent to a client, for clients that do
573      * not update their auth-token (older OpenVPN3 core versions)
574      */
575 #define  AUTH_TOKEN_HMAC_OK              (1<<0)
576     /**< Auth-token sent from client has valid hmac */
577 #define  AUTH_TOKEN_EXPIRED              (1<<1)
578     /**< Auth-token sent from client has expired */
579 #define  AUTH_TOKEN_VALID_EMPTYUSER      (1<<2)
580     /**<
581      * Auth-token is only valid for an empty username
582      * and not the username actually supplied from the client
583      *
584      * OpenVPN 3 clients sometimes wipes or replaces the username with a
585      * username hint from their config.
586      */
587 
588     /* For P_DATA_V2 */
589     uint32_t peer_id;
590     bool use_peer_id;
591 
592     char *remote_ciphername;    /**< cipher specified in peer's config file */
593 
594     /*
595      * Our session objects.
596      */
597     struct tls_session session[TM_SIZE];
598     /**< Array of \c tls_session objects
599      *   representing control channel
600      *   sessions with the remote peer. */
601 };
602 
603 #endif /* SSL_COMMON_H_ */
604