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
8 * Copyright (C) 2002-2023 OpenVPN Inc <sales@openvpn.net>
9 * Copyright (C) 2010-2021 Fox Crypto B.V. <openvpn@foxcrypto.com>
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.
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.
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.
26 * @file Control Channel Common Data Structures
32 #include "session_id.h"
34 #include "packet_id.h"
38 #include "ssl_backend.h"
41 #define UP_TYPE_AUTH "Auth"
42 #define UP_TYPE_PRIVATE_KEY "Private Key"
44 /** @addtogroup control_processor
47 * @name Control channel negotiation states
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.
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
65 * -# \c S_GOT_KEY, have received remote part of \c key_source2 random
67 * -# \c S_ACTIVE, control channel successfully established
68 * -# \c S_GENERATED_KEYS, the data channel keys have been generated
70 * Servers follow the same order, except for \c S_SENT_KEY and \c
71 * S_GOT_KEY being reversed, because the server first receives the
72 * client's \c key_source2 random material before generating and sending
77 #define S_ERROR -1 /**< Error state. */
78 #define S_UNDEF 0 /**< Undefined state, used after a \c
79 * key_state is cleaned up. */
80 #define S_INITIAL 1 /**< Initial \c key_state state after
81 * initialization by \c key_state_init()
82 * before start of three-way handshake. */
83 #define S_PRE_START 2 /**< Waiting for the remote OpenVPN peer
84 * to acknowledge during the initial
85 * three-way handshake. */
86 #define S_START 3 /**< Three-way handshake is complete,
87 * start of key exchange. */
88 #define S_SENT_KEY 4 /**< Local OpenVPN process has sent its
89 * part of the key material. */
90 #define S_GOT_KEY 5 /**< Local OpenVPN process has received
91 * the remote's part of the key
93 #define S_ACTIVE 6 /**< Operational \c key_state state
94 * immediately after negotiation has
95 * completed while still within the
96 * handshake window. Deferred auth and
97 * client connect can still be pending. */
98 #define S_GENERATED_KEYS 7 /**< The data channel keys have been generated
99 * The TLS session is fully authenticated
100 * when reaching this state. */
102 /* Note that earlier versions also had a S_OP_NORMAL state that was
103 * virtually identical with S_ACTIVE and the code still assumes everything
104 * >= S_ACTIVE to be fully operational */
105 /** @} name Control channel negotiation states */
106 /** @} addtogroup control_processor */
109 * Container for one half of random material to be used in %key method 2
110 * \ref key_generation "data channel key generation".
111 * @ingroup control_processor
114 uint8_t pre_master
[48]; /**< Random used for master secret
115 * generation, provided only by client
117 uint8_t random1
[32]; /**< Seed used for master secret
118 * generation, provided by both client
120 uint8_t random2
[32]; /**< Seed used for key expansion, provided
121 * by both client and server. */
126 * Container for both halves of random material to be used in %key method
127 * 2 \ref key_generation "data channel key generation".
128 * @ingroup control_processor
131 struct key_source client
; /**< Random provided by client. */
132 struct key_source server
; /**< Random provided by server. */
137 * This reflects the (server side) authentication state after the TLS
138 * session has been established and key_method_2_read is called. If async auth
139 * is enabled the state will first move to KS_AUTH_DEFERRED before eventually
140 * being set to KS_AUTH_TRUE or KS_AUTH_FALSE
141 * Only KS_AUTH_TRUE is fully authenticated
144 KS_AUTH_FALSE
, /**< Key state is not authenticated */
145 KS_AUTH_DEFERRED
, /**< Key state authentication is being deferred,
147 KS_AUTH_TRUE
/**< Key state is authenticated. TLS and user/pass
148 * succeeded. This includes AUTH_PENDING/OOB
149 * authentication as those hold the
150 * connection artificially in KS_AUTH_DEFERRED
154 struct auth_deferred_status
156 char *auth_control_file
;
157 char *auth_pending_file
;
158 char *auth_failed_reason_file
;
159 unsigned int auth_control_status
;
162 /* key_state_test_auth_control_file return values, these specify the
163 * current status of a deferred authentication */
164 enum auth_deferred_result
{
165 ACF_PENDING
, /**< deferred auth still pending */
166 ACF_SUCCEEDED
, /**< deferred auth has suceeded */
167 ACF_DISABLED
, /**< deferred auth is not used */
168 ACF_FAILED
/**< deferred auth has failed */
171 enum dco_key_status
{
173 DCO_INSTALLED_PRIMARY
,
174 DCO_INSTALLED_SECONDARY
178 * Security parameter state of one TLS and data channel %key session.
179 * @ingroup control_processor
181 * This structure represents one security parameter session between
182 * OpenVPN peers. It includes the control channel TLS state and the data
183 * channel crypto state. It also contains the reliability layer
184 * structures used for control channel messages.
186 * A new \c key_state structure is initialized for each hard or soft
190 * - This structure should be initialized using the \c key_state_init()
192 * - This structure should be cleaned up using the \c key_state_free()
198 /** The state of the auth-token sent from the client */
199 unsigned int auth_token_state_flags
;
202 * Key id for this key_state, inherited from struct tls_session.
203 * @see tls_session::key_id.
208 * Key id for this key_state, inherited from struct tls_session.
209 * @see tls_multi::peer_id.
213 struct key_state_ssl ks_ssl
; /* contains SSL object and BIOs for the control channel */
215 time_t initial
; /* when we created this session */
216 time_t established
; /* when our state went S_ACTIVE */
217 time_t must_negotiate
; /* key negotiation times out if not finished before this time */
218 time_t must_die
; /* this object is destroyed at this time */
219 time_t peer_last_packet
; /* Last time we received a packet in this control session */
221 int initial_opcode
; /* our initial P_ opcode */
222 struct session_id session_id_remote
; /* peer's random session ID */
223 struct link_socket_actual remote_addr
; /* peer's IP addr */
225 struct crypto_options crypto_options
;/* data channel crypto options */
227 struct key_source2
*key_src
; /* source entropy for key expansion */
229 struct buffer plaintext_read_buf
;
230 struct buffer plaintext_write_buf
;
231 struct buffer ack_write_buf
;
233 struct reliable
*send_reliable
; /* holds a copy of outgoing packets until ACK received */
234 struct reliable
*rec_reliable
; /* order incoming ciphertext packets before we pass to TLS */
235 struct reliable_ack
*rec_ack
; /* buffers all packet IDs we want to ACK back to sender */
236 struct reliable_ack
*lru_acks
; /* keeps the most recently acked packages*/
238 /** Holds outgoing message for the control channel until ks->state reaches
240 struct buffer_list
*paybuf
;
241 counter_type n_bytes
; /* how many bytes sent/recvd since last key exchange */
242 counter_type n_packets
; /* how many packets sent/recvd since last key exchange */
245 * If bad username/password, TLS connection will come up but 'authenticated' will be false.
247 enum ks_auth_state authenticated
;
248 time_t auth_deferred_expire
;
250 #ifdef ENABLE_MANAGEMENT
251 unsigned int mda_key_id
;
252 enum auth_deferred_result mda_status
;
256 struct auth_deferred_status plugin_auth
;
257 struct auth_deferred_status script_auth
;
259 enum dco_key_status dco_status
;
262 /** Control channel wrapping (--tls-auth/--tls-crypt) context */
266 TLS_WRAP_NONE
= 0, /**< No control channel wrapping */
267 TLS_WRAP_AUTH
, /**< Control channel authentication */
268 TLS_WRAP_CRYPT
, /**< Control channel encryption and authentication */
269 } mode
; /**< Control channel wrapping mode */
270 struct crypto_options opt
; /**< Crypto state */
271 struct buffer work
; /**< Work buffer (only for --tls-crypt) */
272 struct key_ctx tls_crypt_v2_server_key
; /**< Decrypts client keys */
273 const struct buffer
*tls_crypt_v2_wkc
; /**< Wrapped client key,
275 struct buffer tls_crypt_v2_metadata
; /**< Received from client */
276 bool cleanup_key_ctx
; /**< opt.key_ctx_bi is owned by
278 /** original key data to be xored in to the key for dynamic tls-crypt.
280 * We keep the original key data to ensure that the newly generated key
281 * for the dynamic tls-crypt has the same level of quality by using
282 * xor with the original key. This gives us the same same entropy/randomness
283 * as the original tls-crypt key to ensure the post-quantum use case of
284 * tls-crypt still holds true
286 struct key2 original_wrap_keydata
;
290 * Our const options, obtained directly or derived from
291 * command line options.
295 /* our master TLS context from which all SSL objects derived */
296 struct tls_root_ctx ssl_ctx
;
298 /* data channel cipher, hmac, and key lengths */
299 struct key_type key_type
;
301 /* true if we are a TLS server, client otherwise */
304 /* if true, don't xmit until first packet from peer is received */
307 /* local and remote options strings
308 * that must match between client and server */
309 const char *local_options
;
310 const char *remote_options
;
312 /* from command line */
318 * The detail of info we push in peer info
320 * 0 - nothing at all, P2MP server only
321 * 1 - only the most basic information to negotiate cipher and features
323 * 2 - normal setting for clients
324 * 3 - full information including "sensitive data" like IV_HWADDR
325 * enabled by --push-peer-info
327 int push_peer_info_detail
;
328 int transition_window
;
329 int handshake_window
;
330 interval_t packet_timeout
;
331 int renegotiate_bytes
;
332 int renegotiate_packets
;
333 interval_t renegotiate_seconds
;
335 /* cert verification parms */
336 const char *verify_command
;
337 int verify_x509_type
;
338 const char *verify_x509_name
;
339 const char *crl_file
;
340 bool crl_file_inline
;
342 unsigned remote_cert_ku
[MAX_PARMS
];
343 const char *remote_cert_eku
;
344 struct verify_hash_list
*verify_hash
;
345 int verify_hash_depth
;
346 bool verify_hash_no_ca
;
347 hash_algo_type verify_hash_algo
;
348 #ifdef ENABLE_X509ALTUSERNAME
349 char *x509_username_field
[MAX_PARMS
];
351 char *x509_username_field
[2];
354 /* struct crypto_option flags */
355 unsigned int crypto_flags
;
357 int replay_window
; /* --replay-window parm */
358 int replay_time
; /* --replay-window parm */
361 const char *config_ciphername
;
362 const char *config_ncp_ciphers
;
365 const char *tls_crypt_v2_verify_script
;
367 /** TLS handshake wrapping state */
368 struct tls_wrap_ctx tls_wrap
;
372 /* used for username/password authentication */
373 const char *auth_user_pass_verify_script
;
374 const char *client_crresponse_script
;
375 bool auth_user_pass_verify_script_via_file
;
377 const char *export_peer_cert_dir
;
378 const char *auth_user_pass_file
;
379 bool auth_user_pass_file_inline
;
381 bool auth_token_generate
; /**< Generate auth-tokens on successful
382 * user/pass auth,seet via
383 * options->auth_token_generate. */
384 bool auth_token_call_auth
; /**< always call normal authentication */
385 unsigned int auth_token_lifetime
;
386 unsigned int auth_token_renewal
;
388 struct key_ctx auth_token_key
;
390 /* use the client-config-dir as a positive authenticator */
391 const char *client_config_dir_exclusive
;
393 /* instance-wide environment variable set */
395 openvpn_net_ctx_t
*net_ctx
;
396 const struct plugin_list
*plugins
;
398 /* compression parms */
400 struct compress_options comp_options
;
403 /* configuration file SSL-related boolean and low-permutation options */
404 #define SSLF_CLIENT_CERT_NOT_REQUIRED (1<<0)
405 #define SSLF_CLIENT_CERT_OPTIONAL (1<<1)
406 #define SSLF_USERNAME_AS_COMMON_NAME (1<<2)
407 #define SSLF_AUTH_USER_PASS_OPTIONAL (1<<3)
408 #define SSLF_OPT_VERIFY (1<<4)
409 #define SSLF_CRL_VERIFY_DIR (1<<5)
410 #define SSLF_TLS_VERSION_MIN_SHIFT 6
411 #define SSLF_TLS_VERSION_MIN_MASK 0xF /* (uses bit positions 6 to 9) */
412 #define SSLF_TLS_VERSION_MAX_SHIFT 10
413 #define SSLF_TLS_VERSION_MAX_MASK 0xF /* (uses bit positions 10 to 13) */
414 #define SSLF_TLS_DEBUG_ENABLED (1<<14)
415 unsigned int ssl_flags
;
417 #ifdef ENABLE_MANAGEMENT
418 struct man_def_auth_context
*mda_context
;
421 const struct x509_track
*x509_track
;
423 #ifdef ENABLE_MANAGEMENT
424 const struct static_challenge_info
*sci
;
430 /* Keying Material Exporter [RFC 5705] parameters */
431 const char *ekm_label
;
432 size_t ekm_label_size
;
435 bool dco_enabled
; /**< Whether keys have to be installed in DCO or not */
438 /** @addtogroup control_processor
440 /** @name Index of key_state objects within a tls_session structure
442 * This is the index of \c tls_session.key
445 #define KS_PRIMARY 0 /**< Primary %key state index. */
446 #define KS_LAME_DUCK 1 /**< %Key state index that will retire
448 #define KS_SIZE 2 /**< Size of the \c tls_session.key array. */
449 /** @} name Index of key_state objects within a tls_session structure */
450 /** @} addtogroup control_processor */
453 * Security parameter state of a single session within a VPN tunnel.
454 * @ingroup control_processor
456 * This structure represents an OpenVPN peer-to-peer control channel
459 * A \c tls_session remains over soft resets, but a new instance is
460 * initialized for each hard reset.
463 * - This structure should be initialized using the \c tls_session_init()
465 * - This structure should be cleaned up using the \c tls_session_free()
470 /* const options and config info */
471 struct tls_options
*opt
;
473 /* during hard reset used to control burst retransmit */
476 /* authenticate control packets */
477 struct tls_wrap_ctx tls_wrap
;
479 /* Specific tls-crypt for renegotiations, if this is valid,
480 * tls_wrap_reneg.mode is TLS_WRAP_CRYPT, otherwise ignore it */
481 struct tls_wrap_ctx tls_wrap_reneg
;
483 int initial_opcode
; /* our initial P_ opcode */
484 struct session_id session_id
; /* our random session ID */
487 * The current active key id, used to keep track of renegotiations.
488 * key_id increments with each soft reset to KEY_ID_MASK then recycles back
489 * to 1. This way you know that if key_id is 0, it is the first key.
493 int limit_next
; /* used for traffic shaping on the control channel */
499 struct cert_hash_set
*cert_hash_set
;
501 bool verified
; /* true if peer certificate was verified against CA */
503 /* not-yet-authenticated incoming client */
504 struct link_socket_actual untrusted_addr
;
506 struct key_state key
[KS_SIZE
];
509 /** @addtogroup control_processor
511 /** @name Index of tls_session objects within a tls_multi structure
513 * This is the index of \c tls_multi.session
515 * Normally three tls_session objects are maintained by an active openvpn
516 * session. The first is the current, TLS authenticated session, the
517 * second is used to process connection requests from a new client that
518 * would usurp the current session if successfully authenticated, and the
519 * third is used as a repository for a "lame-duck" %key in the event that
520 * the primary session resets due to error while the lame-duck %key still
521 * has time left before its expiration. Lame duck keys are used to
522 * maintain the continuity of the data channel connection while a new %key
523 * is being negotiated.
526 #define TM_ACTIVE 0 /**< Active \c tls_session. */
527 #define TM_INITIAL 1 /**< As yet un-trusted \c tls_session
528 * being negotiated. */
529 #define TM_LAME_DUCK 2 /**< Old \c tls_session. */
530 #define TM_SIZE 3 /**< Size of the \c tls_multi.session
532 /** @} name Index of tls_session objects within a tls_multi structure */
533 /** @} addtogroup control_processor */
537 * The number of keys we will scan on encrypt or decrypt. The first
538 * is the "active" key. The second is the lame_duck or retiring key
539 * associated with the active key's session ID. The third is a detached
540 * lame duck session that only occurs in situations where a key renegotiate
541 * failed on the active key, but a lame duck key was still valid. By
542 * preserving the lame duck session, we can be assured of having a data
543 * channel key available even when network conditions are so bad that
544 * we can't negotiate a new key within the time allotted.
546 #define KEY_SCAN_SIZE 3
549 /* multi state (originally client authentication state (=CAS))
550 * CAS_NOT_CONNECTED must be 0 since non multi code paths still check
551 * this variable but do not explicitly initialise it and depend
552 * on zero initialisation */
554 /* CAS_NOT_CONNECTED is the initial state for every context. When the *first*
555 * tls_session reaches S_ACTIVE, this state machine moves to CAS_PENDING (server)
556 * or CAS_CONNECT_DONE (client/p2p) as clients skip the stages associated with
557 * connect scripts/plugins */
560 CAS_WAITING_AUTH
, /**< Initial TLS connection established but deferred auth is not yet finished */
561 CAS_PENDING
, /**< Options import (Connect script/plugin, ccd,...) */
562 CAS_PENDING_DEFERRED
, /**< Waiting on an async option import handler */
563 CAS_PENDING_DEFERRED_PARTIAL
, /**< at least handler succeeded but another is still pending */
564 CAS_FAILED
, /**< Option import failed or explicitly denied the client */
565 CAS_WAITING_OPTIONS_IMPORT
, /**< client with pull or p2p waiting for first time options import */
566 CAS_RECONNECT_PENDING
, /**< session has already successful established (CAS_CONNECT_DONE)
567 * but has a reconnect and needs to redo some initialisation, this state is
568 * similar CAS_WAITING_OPTIONS_IMPORT but skips a few things. The normal connection
569 * skips this step. */
575 * Security parameter state for a single VPN tunnel.
576 * @ingroup control_processor
578 * An active VPN tunnel running with TLS enabled has one \c tls_multi
579 * object, in which it stores all control channel and data channel
580 * security parameter state. This structure can contain multiple,
581 * possibly simultaneously active, \c tls_context objects to allow for
582 * interruption-less transitions during session renegotiations. Each \c
583 * tls_context represents one control channel session, which can span
584 * multiple data channel security parameter sessions stored in \c
585 * key_state structures.
589 /* used to coordinate access between main thread and TLS thread */
590 /*MUTEX_PTR_DEFINE (mutex);*/
592 /* const options and config info */
593 struct tls_options opt
;
596 * used by tls_pre_encrypt to communicate the encrypt key
597 * to tls_post_encrypt()
599 struct key_state
*save_ks
; /* temporary pointer used between pre/post routines */
602 * Used to return outgoing address from
605 struct link_socket_actual to_link_addr
;
607 int n_sessions
; /**< Number of sessions negotiated thus
609 enum multi_status multi_state
;
614 int n_hard_errors
; /* errors due to TLS negotiation failure */
615 int n_soft_errors
; /* errors due to unrecognized or failed-to-authenticate incoming packets */
618 * Our locked common name, username, and cert hashes (cannot change during the life of this tls_multi object)
621 char *locked_username
;
622 struct cert_hash_set
*locked_cert_hash_set
;
624 /** Time of last when we updated the cached state of
625 * tls_authentication_status deferred files */
626 time_t tas_cache_last_update
;
628 /** The number of times we updated the cache */
629 unsigned int tas_cache_num_updates
;
632 * An error message to send to client on AUTH_FAILED
637 * A multi-line string of general-purpose info received from peer
638 * over control channel.
641 char *auth_token
; /**< If server sends a generated auth-token,
642 * this is the token to use for future
643 * user/pass authentications in this session.
645 char *auth_token_initial
;
646 /**< The first auth-token we sent to a client. We use this to remember
647 * the session ID and initial timestamp when generating new auth-token.
649 #define AUTH_TOKEN_HMAC_OK (1<<0)
650 /**< Auth-token sent from client has valid hmac */
651 #define AUTH_TOKEN_EXPIRED (1<<1)
652 /**< Auth-token sent from client has expired */
653 #define AUTH_TOKEN_VALID_EMPTYUSER (1<<2)
655 * Auth-token is only valid for an empty username
656 * and not the username actually supplied from the client
658 * OpenVPN 3 clients sometimes wipes or replaces the username with a
659 * username hint from their config.
666 char *remote_ciphername
; /**< cipher specified in peer's config file */
667 bool remote_usescomp
; /**< remote announced comp-lzo in OCC string */
670 * Our session objects.
672 struct tls_session session
[TM_SIZE
];
673 /**< Array of \c tls_session objects
674 * representing control channel
675 * sessions with the remote peer. */
677 /* Only used when DCO is used to remember how many keys we installed
678 * for this session */
679 int dco_keys_installed
;
681 * This is the handle that DCO uses to identify this session with the
684 * We keep this separate as the normal peer_id can change during
685 * p2p NCP and we need to track the id that is really used.
692 /** gets an item of \c key_state objects in the
693 * order they should be scanned by data
694 * channel modules. */
695 static inline struct key_state
*
696 get_key_scan(struct tls_multi
*multi
, int index
)
701 return &multi
->session
[TM_ACTIVE
].key
[KS_PRIMARY
];
704 return &multi
->session
[TM_ACTIVE
].key
[KS_LAME_DUCK
];
707 return &multi
->session
[TM_LAME_DUCK
].key
[KS_LAME_DUCK
];
711 return NULL
; /* NOTREACHED */
715 /** gets an item of \c key_state objects in the
716 * order they should be scanned by data
717 * channel modules. */
718 static inline const struct key_state
*
719 get_primary_key(const struct tls_multi
*multi
)
721 return &multi
->session
[TM_ACTIVE
].key
[KS_PRIMARY
];
724 #endif /* SSL_COMMON_H_ */