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 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 struct auth_deferred_status
149 {
150     char *auth_control_file;
151     char *auth_pending_file;
152     unsigned int auth_control_status;
153 };
154 
155 /* key_state_test_auth_control_file return values, these specify the
156  * current status of a deferred authentication */
157 enum auth_deferred_result {
158     ACF_PENDING,      /**< deferred auth still pending */
159     ACF_SUCCEEDED,    /**< deferred auth has suceeded */
160     ACF_DISABLED,     /**< deferred auth is not used */
161     ACF_FAILED        /**< deferred auth has failed */
162 };
163 
164 /**
165  * Security parameter state of one TLS and data channel %key session.
166  * @ingroup control_processor
167  *
168  * This structure represents one security parameter session between
169  * OpenVPN peers.  It includes the control channel TLS state and the data
170  * channel crypto state.  It also contains the reliability layer
171  * structures used for control channel messages.
172  *
173  * A new \c key_state structure is initialized for each hard or soft
174  * reset.
175  *
176  * @see
177  *  - This structure should be initialized using the \c key_state_init()
178  *    function.
179  *  - This structure should be cleaned up using the \c key_state_free()
180  *    function.
181  */
182 struct key_state
183 {
184     int state;
185 
186     /**
187      * Key id for this key_state,  inherited from struct tls_session.
188      * @see tls_session::key_id.
189      */
190     int key_id;
191 
192     struct key_state_ssl ks_ssl; /* contains SSL object and BIOs for the control channel */
193 
194     time_t initial;             /* when we created this session */
195     time_t established;         /* when our state went S_ACTIVE */
196     time_t must_negotiate;      /* key negotiation times out if not finished before this time */
197     time_t must_die;            /* this object is destroyed at this time */
198     time_t peer_last_packet;    /* Last time we received a packet in this control session */
199 
200     int initial_opcode;         /* our initial P_ opcode */
201     struct session_id session_id_remote; /* peer's random session ID */
202     struct link_socket_actual remote_addr; /* peer's IP addr */
203 
204     struct crypto_options crypto_options;/* data channel crypto options */
205 
206     struct key_source2 *key_src;       /* source entropy for key expansion */
207 
208     struct buffer plaintext_read_buf;
209     struct buffer plaintext_write_buf;
210     struct buffer ack_write_buf;
211 
212     struct reliable *send_reliable; /* holds a copy of outgoing packets until ACK received */
213     struct reliable *rec_reliable; /* order incoming ciphertext packets before we pass to TLS */
214     struct reliable_ack *rec_ack; /* buffers all packet IDs we want to ACK back to sender */
215 
216     struct buffer_list *paybuf;
217 
218     counter_type n_bytes;                /* how many bytes sent/recvd since last key exchange */
219     counter_type n_packets;              /* how many packets sent/recvd since last key exchange */
220 
221     /*
222      * If bad username/password, TLS connection will come up but 'authenticated' will be false.
223      */
224     enum ks_auth_state authenticated;
225     time_t auth_deferred_expire;
226 
227 #ifdef ENABLE_MANAGEMENT
228     unsigned int mda_key_id;
229     enum auth_deferred_result mda_status;
230 #endif
231     time_t acf_last_mod;
232 
233     struct auth_deferred_status plugin_auth;
234     struct auth_deferred_status script_auth;
235 };
236 
237 /** Control channel wrapping (--tls-auth/--tls-crypt) context */
238 struct tls_wrap_ctx
239 {
240     enum {
241         TLS_WRAP_NONE = 0, /**< No control channel wrapping */
242         TLS_WRAP_AUTH,  /**< Control channel authentication */
243         TLS_WRAP_CRYPT, /**< Control channel encryption and authentication */
244     } mode;                     /**< Control channel wrapping mode */
245     struct crypto_options opt;  /**< Crypto state */
246     struct buffer work;         /**< Work buffer (only for --tls-crypt) */
247     struct key_ctx tls_crypt_v2_server_key;  /**< Decrypts client keys */
248     const struct buffer *tls_crypt_v2_wkc;   /**< Wrapped client key,
249                                               *   sent to server */
250     struct buffer tls_crypt_v2_metadata;     /**< Received from client */
251     bool cleanup_key_ctx;                    /**< opt.key_ctx_bi is owned by
252                                               *   this context */
253 };
254 
255 /*
256  * Our const options, obtained directly or derived from
257  * command line options.
258  */
259 struct tls_options
260 {
261     /* our master TLS context from which all SSL objects derived */
262     struct tls_root_ctx ssl_ctx;
263 
264     /* data channel cipher, hmac, and key lengths */
265     struct key_type key_type;
266 
267     /* true if we are a TLS server, client otherwise */
268     bool server;
269 
270     /* if true, don't xmit until first packet from peer is received */
271     bool xmit_hold;
272 
273     /* local and remote options strings
274      * that must match between client and server */
275     const char *local_options;
276     const char *remote_options;
277 
278     /* from command line */
279     bool replay;
280     bool single_session;
281     bool disable_occ;
282     int mode;
283     bool pull;
284     int push_peer_info_detail;
285     int transition_window;
286     int handshake_window;
287     interval_t packet_timeout;
288     int renegotiate_bytes;
289     int renegotiate_packets;
290     interval_t renegotiate_seconds;
291 
292     /* cert verification parms */
293     const char *verify_command;
294     const char *verify_export_cert;
295     int verify_x509_type;
296     const char *verify_x509_name;
297     const char *crl_file;
298     bool crl_file_inline;
299     int ns_cert_type;
300     unsigned remote_cert_ku[MAX_PARMS];
301     const char *remote_cert_eku;
302     struct verify_hash_list *verify_hash;
303     int verify_hash_depth;
304     bool verify_hash_no_ca;
305     hash_algo_type verify_hash_algo;
306 #ifdef ENABLE_X509ALTUSERNAME
307     char *x509_username_field[MAX_PARMS];
308 #else
309     char *x509_username_field[2];
310 #endif
311 
312     /* struct crypto_option flags */
313     unsigned int crypto_flags;
314 
315     int replay_window;                 /* --replay-window parm */
316     int replay_time;                   /* --replay-window parm */
317     bool tcp_mode;
318 
319     const char *config_ciphername;
320     const char *config_ncp_ciphers;
321     bool ncp_enabled;
322 
323     bool tls_crypt_v2;
324     const char *tls_crypt_v2_verify_script;
325 
326     /** TLS handshake wrapping state */
327     struct tls_wrap_ctx tls_wrap;
328 
329     struct frame frame;
330 
331     /* used for username/password authentication */
332     const char *auth_user_pass_verify_script;
333     bool auth_user_pass_verify_script_via_file;
334     const char *tmp_dir;
335     const char *auth_user_pass_file;
336 
337     bool auth_token_generate;   /**< Generate auth-tokens on successful
338                                  * user/pass auth,seet via
339                                  * options->auth_token_generate. */
340     bool auth_token_call_auth; /**< always call normal authentication */
341     unsigned int auth_token_lifetime;
342 
343     struct key_ctx auth_token_key;
344 
345     /* use the client-config-dir as a positive authenticator */
346     const char *client_config_dir_exclusive;
347 
348     /* instance-wide environment variable set */
349     struct env_set *es;
350     openvpn_net_ctx_t *net_ctx;
351     const struct plugin_list *plugins;
352 
353     /* compression parms */
354 #ifdef USE_COMP
355     struct compress_options comp_options;
356 #endif
357 
358     /* configuration file SSL-related boolean and low-permutation options */
359 #define SSLF_CLIENT_CERT_NOT_REQUIRED (1<<0)
360 #define SSLF_CLIENT_CERT_OPTIONAL     (1<<1)
361 #define SSLF_USERNAME_AS_COMMON_NAME  (1<<2)
362 #define SSLF_AUTH_USER_PASS_OPTIONAL  (1<<3)
363 #define SSLF_OPT_VERIFY               (1<<4)
364 #define SSLF_CRL_VERIFY_DIR           (1<<5)
365 #define SSLF_TLS_VERSION_MIN_SHIFT    6
366 #define SSLF_TLS_VERSION_MIN_MASK     0xF  /* (uses bit positions 6 to 9) */
367 #define SSLF_TLS_VERSION_MAX_SHIFT    10
368 #define SSLF_TLS_VERSION_MAX_MASK     0xF  /* (uses bit positions 10 to 13) */
369 #define SSLF_TLS_DEBUG_ENABLED        (1<<14)
370     unsigned int ssl_flags;
371 
372 #ifdef ENABLE_MANAGEMENT
373     struct man_def_auth_context *mda_context;
374 #endif
375 
376     const struct x509_track *x509_track;
377 
378 #ifdef ENABLE_MANAGEMENT
379     const struct static_challenge_info *sci;
380 #endif
381 
382     /* --gremlin bits */
383     int gremlin;
384 
385     /* Keying Material Exporter [RFC 5705] parameters */
386     const char *ekm_label;
387     size_t ekm_label_size;
388     size_t ekm_size;
389 };
390 
391 /** @addtogroup control_processor
392  *  @{ */
393 /** @name Index of key_state objects within a tls_session structure
394  *
395  *  This is the index of \c tls_session.key
396  *
397  *  @{ */
398 #define KS_PRIMARY    0         /**< Primary %key state index. */
399 #define KS_LAME_DUCK  1         /**< %Key state index that will retire
400                                  *   soon. */
401 #define KS_SIZE       2         /**< Size of the \c tls_session.key array. */
402 /** @} name Index of key_state objects within a tls_session structure */
403 /** @} addtogroup control_processor */
404 
405 /**
406  * Security parameter state of a single session within a VPN tunnel.
407  * @ingroup control_processor
408  *
409  * This structure represents an OpenVPN peer-to-peer control channel
410  * session.
411  *
412  * A \c tls_session remains over soft resets, but a new instance is
413  * initialized for each hard reset.
414  *
415  * @see
416  *  - This structure should be initialized using the \c tls_session_init()
417  *    function.
418  *  - This structure should be cleaned up using the \c tls_session_free()
419  *    function.
420  */
421 struct tls_session
422 {
423     /* const options and config info */
424     struct tls_options *opt;
425 
426     /* during hard reset used to control burst retransmit */
427     bool burst;
428 
429     /* authenticate control packets */
430     struct tls_wrap_ctx tls_wrap;
431 
432     int initial_opcode;         /* our initial P_ opcode */
433     struct session_id session_id; /* our random session ID */
434 
435     /**
436      * The current active key id, used to keep track of renegotiations.
437      * key_id increments with each soft reset to KEY_ID_MASK then recycles back
438      * to 1.  This way you know that if key_id is 0, it is the first key.
439      */
440     int key_id;
441 
442     int limit_next;             /* used for traffic shaping on the control channel */
443 
444     int verify_maxlevel;
445 
446     char *common_name;
447 
448     struct cert_hash_set *cert_hash_set;
449 
450 #ifdef ENABLE_PF
451     uint32_t common_name_hashval;
452 #endif
453 
454     bool verified;              /* true if peer certificate was verified against CA */
455 
456     /* not-yet-authenticated incoming client */
457     struct link_socket_actual untrusted_addr;
458 
459     struct key_state key[KS_SIZE];
460 };
461 
462 /** @addtogroup control_processor
463  *  @{ */
464 /** @name Index of tls_session objects within a tls_multi structure
465  *
466  *  This is the index of \c tls_multi.session
467  *
468  *  Normally three tls_session objects are maintained by an active openvpn
469  *  session.  The first is the current, TLS authenticated session, the
470  *  second is used to process connection requests from a new client that
471  *  would usurp the current session if successfully authenticated, and the
472  *  third is used as a repository for a "lame-duck" %key in the event that
473  *  the primary session resets due to error while the lame-duck %key still
474  *  has time left before its expiration.  Lame duck keys are used to
475  *  maintain the continuity of the data channel connection while a new %key
476  *  is being negotiated.
477  *
478  *  @{ */
479 #define TM_ACTIVE    0          /**< Active \c tls_session. */
480 #define TM_UNTRUSTED 1          /**< As yet un-trusted \c tls_session
481                                  *   being negotiated. */
482 #define TM_LAME_DUCK 2          /**< Old \c tls_session. */
483 #define TM_SIZE      3          /**< Size of the \c tls_multi.session
484                                  *   array. */
485 /** @} name Index of tls_session objects within a tls_multi structure */
486 /** @} addtogroup control_processor */
487 
488 
489 /*
490  * The number of keys we will scan on encrypt or decrypt.  The first
491  * is the "active" key.  The second is the lame_duck or retiring key
492  * associated with the active key's session ID.  The third is a detached
493  * lame duck session that only occurs in situations where a key renegotiate
494  * failed on the active key, but a lame duck key was still valid.  By
495  * preserving the lame duck session, we can be assured of having a data
496  * channel key available even when network conditions are so bad that
497  * we can't negotiate a new key within the time allotted.
498  */
499 #define KEY_SCAN_SIZE 3
500 
501 
502 /* client authentication state, CAS_SUCCEEDED must be 0 since
503  * non multi code path still checks this variable but does not initialise it
504  * so the code depends on zero initialisation */
505 enum client_connect_status {
506     CAS_SUCCEEDED=0,
507     CAS_PENDING,
508     CAS_PENDING_DEFERRED,
509     CAS_PENDING_DEFERRED_PARTIAL,   /**< at least handler succeeded, no result yet*/
510     CAS_FAILED,
511 };
512 
513 
514 /**
515  * Security parameter state for a single VPN tunnel.
516  * @ingroup control_processor
517  *
518  * An active VPN tunnel running with TLS enabled has one \c tls_multi
519  * object, in which it stores all control channel and data channel
520  * security parameter state.  This structure can contain multiple,
521  * possibly simultaneously active, \c tls_context objects to allow for
522  * interruption-less transitions during session renegotiations.  Each \c
523  * tls_context represents one control channel session, which can span
524  * multiple data channel security parameter sessions stored in \c
525  * key_state structures.
526  */
527 struct tls_multi
528 {
529     /* used to coordinate access between main thread and TLS thread */
530     /*MUTEX_PTR_DEFINE (mutex);*/
531 
532     /* const options and config info */
533     struct tls_options opt;
534 
535     /*
536      * used by tls_pre_encrypt to communicate the encrypt key
537      * to tls_post_encrypt()
538      */
539     struct key_state *save_ks;  /* temporary pointer used between pre/post routines */
540 
541     /*
542      * Used to return outgoing address from
543      * tls_multi_process.
544      */
545     struct link_socket_actual to_link_addr;
546 
547     int n_sessions;             /**< Number of sessions negotiated thus
548                                  *   far. */
549     enum client_connect_status multi_state;
550 
551     /*
552      * Number of errors.
553      */
554     int n_hard_errors; /* errors due to TLS negotiation failure */
555     int n_soft_errors; /* errors due to unrecognized or failed-to-authenticate incoming packets */
556 
557     /*
558      * Our locked common name, username, and cert hashes (cannot change during the life of this tls_multi object)
559      */
560     char *locked_cn;
561     char *locked_username;
562     struct cert_hash_set *locked_cert_hash_set;
563 
564     /** Time of last when we updated the cached state of
565      * tls_authentication_status deferred files */
566     time_t tas_cache_last_update;
567 
568     /** The number of times we updated the cache */
569     unsigned int tas_cache_num_updates;
570 
571     /*
572      * An error message to send to client on AUTH_FAILED
573      */
574     char *client_reason;
575 
576     /*
577      * A multi-line string of general-purpose info received from peer
578      * over control channel.
579      */
580     char *peer_info;
581     char *auth_token;    /**< If server sends a generated auth-token,
582                           *   this is the token to use for future
583                           *   user/pass authentications in this session.
584                           */
585     char *auth_token_initial;
586     /**< The first auth-token we sent to a client, for clients that do
587      * not update their auth-token (older OpenVPN3 core versions)
588      */
589 #define  AUTH_TOKEN_HMAC_OK              (1<<0)
590     /**< Auth-token sent from client has valid hmac */
591 #define  AUTH_TOKEN_EXPIRED              (1<<1)
592     /**< Auth-token sent from client has expired */
593 #define  AUTH_TOKEN_VALID_EMPTYUSER      (1<<2)
594     /**<
595      * Auth-token is only valid for an empty username
596      * and not the username actually supplied from the client
597      *
598      * OpenVPN 3 clients sometimes wipes or replaces the username with a
599      * username hint from their config.
600      */
601     int auth_token_state_flags;
602     /**< The state of the auth-token sent from the client last time */
603 
604     /* For P_DATA_V2 */
605     uint32_t peer_id;
606     bool use_peer_id;
607 
608     char *remote_ciphername;    /**< cipher specified in peer's config file */
609     bool remote_usescomp;       /**< remote announced comp-lzo in OCC string */
610 
611     /*
612      * Our session objects.
613      */
614     struct tls_session session[TM_SIZE];
615     /**< Array of \c tls_session objects
616      *   representing control channel
617      *   sessions with the remote peer. */
618 };
619 
620 /**  gets an item  of \c key_state objects in the
621  *   order they should be scanned by data
622  *   channel modules. */
623 static inline struct key_state *
get_key_scan(struct tls_multi * multi,int index)624 get_key_scan(struct tls_multi *multi, int index)
625 {
626     switch (index)
627     {
628         case 0:
629             return &multi->session[TM_ACTIVE].key[KS_PRIMARY];
630         case 1:
631             return &multi->session[TM_ACTIVE].key[KS_LAME_DUCK];
632         case 2:
633             return &multi->session[TM_LAME_DUCK].key[KS_LAME_DUCK];
634         default:
635             ASSERT(false);
636             return NULL; /* NOTREACHED */
637     }
638 }
639 
640 /**  gets an item  of \c key_state objects in the
641  *   order they should be scanned by data
642  *   channel modules. */
643 static inline const struct key_state *
get_primary_key(const struct tls_multi * multi)644 get_primary_key(const struct tls_multi *multi)
645 {
646         return &multi->session[TM_ACTIVE].key[KS_PRIMARY];
647 }
648 
649 #endif /* SSL_COMMON_H_ */
650