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>
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License version 2
12 * as published by the Free Software Foundation.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
41 #include "ssl_verify.h"
43 #include "auth_token.h"
49 counter_type link_read_bytes_global
; /* GLOBAL */
50 counter_type link_write_bytes_global
; /* GLOBAL */
52 /* show event wait debugging info */
57 wait_status_string(struct context
*c
, struct gc_arena
*gc
)
59 struct buffer out
= alloc_buf_gc(64, gc
);
60 buf_printf(&out
, "I/O WAIT %s|%s|%s|%s %s",
61 tun_stat(c
->c1
.tuntap
, EVENT_READ
, gc
),
62 tun_stat(c
->c1
.tuntap
, EVENT_WRITE
, gc
),
63 socket_stat(c
->c2
.link_socket
, EVENT_READ
, gc
),
64 socket_stat(c
->c2
.link_socket
, EVENT_WRITE
, gc
),
65 tv_string(&c
->c2
.timeval
, gc
));
70 show_wait_status(struct context
*c
)
72 struct gc_arena gc
= gc_new();
73 dmsg(D_EVENT_WAIT
, "%s", wait_status_string(c
, &gc
));
77 #endif /* ifdef ENABLE_DEBUG */
80 check_tls_errors_co(struct context
*c
)
82 msg(D_STREAM_ERRORS
, "Fatal TLS error (check_tls_errors_co), restarting");
83 register_signal(c
->sig
, c
->c2
.tls_exit_signal
, "tls-error"); /* SOFT-SIGUSR1 -- TLS error */
87 check_tls_errors_nco(struct context
*c
)
89 register_signal(c
->sig
, c
->c2
.tls_exit_signal
, "tls-error"); /* SOFT-SIGUSR1 -- TLS error */
93 * TLS errors are fatal in TCP mode.
94 * Also check for --tls-exit trigger.
97 check_tls_errors(struct context
*c
)
99 if (c
->c2
.tls_multi
&& c
->c2
.tls_exit_signal
)
101 if (link_socket_connection_oriented(c
->c2
.link_socket
))
103 if (c
->c2
.tls_multi
->n_soft_errors
)
105 check_tls_errors_co(c
);
110 if (c
->c2
.tls_multi
->n_hard_errors
)
112 check_tls_errors_nco(c
);
119 * Set our wakeup to 0 seconds, so we will be rescheduled
123 context_immediate_reschedule(struct context
*c
)
125 c
->c2
.timeval
.tv_sec
= 0; /* ZERO-TIMEOUT */
126 c
->c2
.timeval
.tv_usec
= 0;
130 context_reschedule_sec(struct context
*c
, int sec
)
136 if (sec
< c
->c2
.timeval
.tv_sec
)
138 c
->c2
.timeval
.tv_sec
= sec
;
139 c
->c2
.timeval
.tv_usec
= 0;
144 check_dco_key_status(struct context
*c
)
146 /* DCO context is not yet initialised or enabled */
147 if (!dco_enabled(&c
->options
))
152 /* no active peer (p2p tls-server mode) */
153 if (c
->c2
.tls_multi
->dco_peer_id
== -1)
158 if (!dco_update_keys(&c
->c1
.tuntap
->dco
, c
->c2
.tls_multi
))
160 /* Something bad happened. Kill the connection to
161 * be able to recover. */
162 register_signal(c
->sig
, SIGUSR1
, "dco update keys error");
167 * In TLS mode, let TLS level respond to any control-channel
168 * packets which were received, or prepare any packets for
171 * tmp_int is purely an optimization that allows us to call
172 * tls_multi_process less frequently when there's not much
173 * traffic on the control-channel.
177 check_tls(struct context
*c
)
179 interval_t wakeup
= BIG_TIMEOUT
;
181 if (interval_test(&c
->c2
.tmp_int
))
183 const int tmp_status
= tls_multi_process
184 (c
->c2
.tls_multi
, &c
->c2
.to_link
, &c
->c2
.to_link_addr
,
185 get_link_socket_info(c
), &wakeup
);
187 if (tmp_status
== TLSMP_RECONNECT
)
189 event_timeout_init(&c
->c2
.wait_for_connect
, 1, now
);
190 reset_coarse_timers(c
);
193 if (tmp_status
== TLSMP_ACTIVE
|| tmp_status
== TLSMP_RECONNECT
)
196 interval_action(&c
->c2
.tmp_int
);
198 else if (tmp_status
== TLSMP_KILL
)
200 if (c
->options
.mode
== MODE_SERVER
)
202 send_auth_failed(c
, c
->c2
.tls_multi
->client_reason
);
206 register_signal(c
->sig
, SIGTERM
, "auth-control-exit");
210 interval_future_trigger(&c
->c2
.tmp_int
, wakeup
);
213 interval_schedule_wakeup(&c
->c2
.tmp_int
, &wakeup
);
216 * Our current code has no good hooks in the TLS machinery to update
217 * DCO keys. So we check the key status after the whole TLS machinery
218 * has been completed and potentially update them
220 * We have a hidden state transition from secondary to primary key based
221 * on ks->auth_deferred_expire that DCO needs to check that the normal
222 * TLS state engine does not check. So we call the \c check_dco_key_status
223 * function even if tmp_status does not indicate that something has changed.
225 check_dco_key_status(c
);
229 context_reschedule_sec(c
, wakeup
);
234 * Handle incoming configuration
235 * messages on the control channel.
238 check_incoming_control_channel(struct context
*c
)
240 int len
= tls_test_payload_len(c
->c2
.tls_multi
);
241 /* We should only be called with len >0 */
244 struct gc_arena gc
= gc_new();
245 struct buffer buf
= alloc_buf_gc(len
, &gc
);
246 if (tls_rec_payload(c
->c2
.tls_multi
, &buf
))
248 /* force null termination of message */
249 buf_null_terminate(&buf
);
251 /* enforce character class restrictions */
252 string_mod(BSTR(&buf
), CC_PRINT
, CC_CRLF
, 0);
254 if (buf_string_match_head_str(&buf
, "AUTH_FAILED"))
256 receive_auth_failed(c
, &buf
);
258 else if (buf_string_match_head_str(&buf
, "PUSH_"))
260 incoming_push_message(c
, &buf
);
262 else if (buf_string_match_head_str(&buf
, "RESTART"))
264 server_pushed_signal(c
, &buf
, true, 7);
266 else if (buf_string_match_head_str(&buf
, "HALT"))
268 server_pushed_signal(c
, &buf
, false, 4);
270 else if (buf_string_match_head_str(&buf
, "INFO_PRE"))
272 server_pushed_info(c
, &buf
, 8);
274 else if (buf_string_match_head_str(&buf
, "INFO"))
276 server_pushed_info(c
, &buf
, 4);
278 else if (buf_string_match_head_str(&buf
, "CR_RESPONSE"))
280 receive_cr_response(c
, &buf
);
282 else if (buf_string_match_head_str(&buf
, "AUTH_PENDING"))
284 receive_auth_pending(c
, &buf
);
286 else if (buf_string_match_head_str(&buf
, "EXIT"))
288 receive_exit_message(c
);
292 msg(D_PUSH_ERRORS
, "WARNING: Received unknown control message: %s", BSTR(&buf
));
297 msg(D_PUSH_ERRORS
, "WARNING: Receive control message failed");
304 * Periodically resend PUSH_REQUEST until PUSH message received
307 check_push_request(struct context
*c
)
309 send_push_request(c
);
311 /* if no response to first push_request, retry at PUSH_REQUEST_INTERVAL second intervals */
312 event_timeout_modify_wakeup(&c
->c2
.push_request_interval
, PUSH_REQUEST_INTERVAL
);
316 * Things that need to happen immediately after connection initiation should go here.
318 * Options like --up-delay need to be triggered by this function which
319 * checks for connection establishment.
321 * Note: The process_incoming_push_reply currently assumes that this function
322 * only sets up the pull request timer when pull is enabled.
325 check_connection_established(struct context
*c
)
327 if (connection_established(c
))
329 /* if --pull was specified, send a push request to server */
330 if (c
->c2
.tls_multi
&& c
->options
.pull
)
332 #ifdef ENABLE_MANAGEMENT
335 management_set_state(management
,
336 OPENVPN_STATE_GET_CONFIG
,
344 /* fire up push request right away (already 1s delayed) */
345 /* We might receive a AUTH_PENDING request before we armed this
346 * timer. In that case we don't change the value */
347 if (c
->c2
.push_request_timeout
< now
)
349 c
->c2
.push_request_timeout
= now
+ c
->options
.handshake_window
;
351 event_timeout_init(&c
->c2
.push_request_interval
, 0, now
);
352 reset_coarse_timers(c
);
356 if (!do_up(c
, false, 0))
358 register_signal(c
->sig
, SIGUSR1
, "connection initialisation failed");
362 event_timeout_clear(&c
->c2
.wait_for_connect
);
367 send_control_channel_string_dowork(struct tls_session
*session
,
368 const char *str
, int msglevel
)
370 struct gc_arena gc
= gc_new();
374 struct key_state
*ks
= &session
->key
[KS_PRIMARY
];
376 /* buffered cleartext write onto TLS control channel */
377 stat
= tls_send_payload(ks
, (uint8_t *) str
, strlen(str
) + 1);
379 msg(msglevel
, "SENT CONTROL [%s]: '%s' (status=%d)",
380 session
->common_name
? session
->common_name
: "UNDEF",
381 sanitize_control_message(str
, &gc
),
389 reschedule_multi_process(struct context
*c
)
391 interval_action(&c
->c2
.tmp_int
);
392 context_immediate_reschedule(c
); /* ZERO-TIMEOUT */
396 send_control_channel_string(struct context
*c
, const char *str
, int msglevel
)
400 struct tls_session
*session
= &c
->c2
.tls_multi
->session
[TM_ACTIVE
];
401 bool ret
= send_control_channel_string_dowork(session
, str
, msglevel
);
402 reschedule_multi_process(c
);
413 check_add_routes_action(struct context
*c
, const bool errors
)
415 bool route_status
= do_route(&c
->options
, c
->c1
.route_list
, c
->c1
.route_ipv6_list
,
416 c
->c1
.tuntap
, c
->plugins
, c
->c2
.es
, &c
->net_ctx
);
418 int flags
= (errors
? ISC_ERRORS
: 0);
419 flags
|= (!route_status
? ISC_ROUTE_ERRORS
: 0);
422 event_timeout_clear(&c
->c2
.route_wakeup
);
423 event_timeout_clear(&c
->c2
.route_wakeup_expire
);
424 initialization_sequence_completed(c
, flags
); /* client/p2p --route-delay was defined */
428 check_add_routes(struct context
*c
)
430 if (test_routes(c
->c1
.route_list
, c
->c1
.tuntap
))
432 check_add_routes_action(c
, false);
434 else if (event_timeout_trigger(&c
->c2
.route_wakeup_expire
, &c
->c2
.timeval
, ETT_DEFAULT
))
436 check_add_routes_action(c
, true);
440 msg(D_ROUTE
, "Route: Waiting for TUN/TAP interface to come up...");
443 if (!tun_standby(c
->c1
.tuntap
))
445 register_signal(c
->sig
, SIGHUP
, "ip-fail");
446 c
->persist
.restart_sleep_seconds
= 10;
448 show_routes(M_INFO
|M_NOPREFIX
);
449 show_adapters(M_INFO
|M_NOPREFIX
);
454 if (c
->c2
.route_wakeup
.n
!= 1)
456 event_timeout_init(&c
->c2
.route_wakeup
, 1, now
);
458 event_timeout_reset(&c
->c2
.ping_rec_interval
);
463 * Should we exit due to inactivity timeout?
465 * In the non-dco case, the timeout is reset via register_activity()
466 * whenever there is sufficient activity on tun or link, so this function
467 * is only ever called to raise the TERM signal.
469 * With DCO, OpenVPN does not see incoming or outgoing data packets anymore
470 * and the logic needs to change - we permit the event to trigger and check
471 * kernel DCO counters here, returning and rearming the timer if there was
472 * sufficient traffic.
475 check_inactivity_timeout(struct context
*c
)
477 if (dco_enabled(&c
->options
) && dco_get_peer_stats(c
) == 0)
479 int64_t tot_bytes
= c
->c2
.tun_read_bytes
+ c
->c2
.tun_write_bytes
;
480 int64_t new_bytes
= tot_bytes
- c
->c2
.inactivity_bytes
;
482 if (new_bytes
> c
->options
.inactivity_minimum_bytes
)
484 c
->c2
.inactivity_bytes
= tot_bytes
;
485 event_timeout_reset(&c
->c2
.inactivity_interval
);
491 msg(M_INFO
, "Inactivity timeout (--inactive), exiting");
492 register_signal(c
->sig
, SIGTERM
, "inactive");
496 get_server_poll_remaining_time(struct event_timeout
*server_poll_timeout
)
499 int remaining
= event_timeout_remaining(server_poll_timeout
);
500 return max_int(0, remaining
);
504 check_server_poll_timeout(struct context
*c
)
506 event_timeout_reset(&c
->c2
.server_poll_interval
);
507 ASSERT(c
->c2
.tls_multi
);
508 if (!tls_initial_packet_received(c
->c2
.tls_multi
))
510 msg(M_INFO
, "Server poll timeout, restarting");
511 register_signal(c
->sig
, SIGUSR1
, "server_poll");
512 c
->persist
.restart_sleep_seconds
= -1;
517 * Schedule a signal n_seconds from now.
520 schedule_exit(struct context
*c
, const int n_seconds
, const int signal
)
522 tls_set_single_session(c
->c2
.tls_multi
);
524 reset_coarse_timers(c
);
525 event_timeout_init(&c
->c2
.scheduled_exit
, n_seconds
, now
);
526 c
->c2
.scheduled_exit_signal
= signal
;
527 msg(D_SCHED_EXIT
, "Delayed exit in %d seconds", n_seconds
);
534 check_scheduled_exit(struct context
*c
)
536 register_signal(c
->sig
, c
->c2
.scheduled_exit_signal
, "delayed-exit");
540 * Should we write timer-triggered status file.
543 check_status_file(struct context
*c
)
545 if (c
->c1
.status_output
)
547 print_status(c
, c
->c1
.status_output
);
551 #ifdef ENABLE_FRAGMENT
553 * Should we deliver a datagram fragment to remote?
556 check_fragment(struct context
*c
)
558 struct link_socket_info
*lsi
= get_link_socket_info(c
);
561 if (lsi
->mtu_changed
&& lsi
->lsa
)
563 frame_adjust_path_mtu(c
);
564 lsi
->mtu_changed
= false;
567 if (fragment_outgoing_defined(c
->c2
.fragment
))
569 if (!c
->c2
.to_link
.len
)
571 /* encrypt a fragment for output to TCP/UDP port */
572 ASSERT(fragment_ready_to_send(c
->c2
.fragment
, &c
->c2
.buf
, &c
->c2
.frame_fragment
));
573 encrypt_sign(c
, false);
577 fragment_housekeeping(c
->c2
.fragment
, &c
->c2
.frame_fragment
, &c
->c2
.timeval
);
579 #endif /* ifdef ENABLE_FRAGMENT */
582 * Buffer reallocation, for use with null encryption.
585 buffer_turnover(const uint8_t *orig_buf
, struct buffer
*dest_stub
, struct buffer
*src_stub
, struct buffer
*storage
)
587 if (orig_buf
== src_stub
->data
&& src_stub
->data
!= storage
->data
)
589 buf_assign(storage
, src_stub
);
590 *dest_stub
= *storage
;
594 *dest_stub
= *src_stub
;
599 * Compress, fragment, encrypt and HMAC-sign an outgoing packet.
601 * Output: c->c2.to_link
604 encrypt_sign(struct context
*c
, bool comp_frag
)
606 struct context_buffers
*b
= c
->c2
.buffers
;
607 const uint8_t *orig_buf
= c
->c2
.buf
.data
;
608 struct crypto_options
*co
= NULL
;
610 if (dco_enabled(&c
->options
))
612 msg(M_WARN
, "Attempting to send data packet while data channel offload is in use. "
618 * Drop non-TLS outgoing packet if client-connect script/plugin
619 * has not yet succeeded. In non-TLS tls_multi mode is not defined
620 * and we always pass packets.
622 if (c
->c2
.tls_multi
&& c
->c2
.tls_multi
->multi_state
< CAS_CONNECT_DONE
)
630 /* Compress the packet. */
631 if (c
->c2
.comp_context
)
633 (*c
->c2
.comp_context
->alg
.compress
)(&c
->c2
.buf
, b
->compress_buf
, c
->c2
.comp_context
, &c
->c2
.frame
);
636 #ifdef ENABLE_FRAGMENT
639 fragment_outgoing(c
->c2
.fragment
, &c
->c2
.buf
, &c
->c2
.frame_fragment
);
644 /* initialize work buffer with buf.headroom bytes of prepend capacity */
645 ASSERT(buf_init(&b
->encrypt_buf
, c
->c2
.frame
.buf
.headroom
));
649 /* Get the key we will use to encrypt the packet. */
650 tls_pre_encrypt(c
->c2
.tls_multi
, &c
->c2
.buf
, &co
);
651 /* If using P_DATA_V2, prepend the 1-byte opcode and 3-byte peer-id to the
652 * packet before openvpn_encrypt(), so we can authenticate the opcode too.
654 if (c
->c2
.buf
.len
> 0 && c
->c2
.tls_multi
->use_peer_id
)
656 tls_prepend_opcode_v2(c
->c2
.tls_multi
, &b
->encrypt_buf
);
661 co
= &c
->c2
.crypto_options
;
664 /* Encrypt and authenticate the packet */
665 openvpn_encrypt(&c
->c2
.buf
, b
->encrypt_buf
, co
);
667 /* Do packet administration */
670 if (c
->c2
.buf
.len
> 0 && !c
->c2
.tls_multi
->use_peer_id
)
672 tls_prepend_opcode_v1(c
->c2
.tls_multi
, &c
->c2
.buf
);
674 tls_post_encrypt(c
->c2
.tls_multi
, &c
->c2
.buf
);
678 * Get the address we will be sending the packet to.
680 link_socket_get_outgoing_addr(&c
->c2
.buf
, get_link_socket_info(c
),
681 &c
->c2
.to_link_addr
);
683 /* if null encryption, copy result to read_tun_buf */
684 buffer_turnover(orig_buf
, &c
->c2
.to_link
, &c
->c2
.buf
, &b
->read_tun_buf
);
688 * Should we exit due to session timeout?
691 check_session_timeout(struct context
*c
)
693 if (c
->options
.session_timeout
694 && event_timeout_trigger(&c
->c2
.session_interval
, &c
->c2
.timeval
,
697 msg(M_INFO
, "Session timeout, exiting");
698 register_signal(c
->sig
, SIGTERM
, "session-timeout");
703 * Coarse timers work to 1 second resolution.
706 process_coarse_timers(struct context
*c
)
708 /* flush current packet-id to file once per 60
709 * seconds if --replay-persist was specified */
710 if (packet_id_persist_enabled(&c
->c1
.pid_persist
)
711 && event_timeout_trigger(&c
->c2
.packet_id_persist_interval
, &c
->c2
.timeval
, ETT_DEFAULT
))
713 packet_id_persist_save(&c
->c1
.pid_persist
);
716 /* Should we write timer-triggered status file */
717 if (c
->c1
.status_output
718 && event_timeout_trigger(&c
->c1
.status_output
->et
, &c
->c2
.timeval
, ETT_DEFAULT
))
720 check_status_file(c
);
723 /* process connection establishment items */
724 if (event_timeout_trigger(&c
->c2
.wait_for_connect
, &c
->c2
.timeval
, ETT_DEFAULT
))
726 check_connection_established(c
);
729 /* see if we should send a push_request (option --pull) */
730 if (event_timeout_trigger(&c
->c2
.push_request_interval
, &c
->c2
.timeval
, ETT_DEFAULT
))
732 check_push_request(c
);
735 /* process --route options */
736 if (event_timeout_trigger(&c
->c2
.route_wakeup
, &c
->c2
.timeval
, ETT_DEFAULT
))
741 /* check if we want to refresh the auth-token */
742 if (event_timeout_trigger(&c
->c2
.auth_token_renewal_interval
, &c
->c2
.timeval
, ETT_DEFAULT
))
744 check_send_auth_token(c
);
747 /* possibly exit due to --inactive */
748 if (c
->options
.inactivity_timeout
749 && event_timeout_trigger(&c
->c2
.inactivity_interval
, &c
->c2
.timeval
, ETT_DEFAULT
))
751 check_inactivity_timeout(c
);
754 if (c
->sig
->signal_received
)
759 /* kill session if time is over */
760 check_session_timeout(c
);
761 if (c
->sig
->signal_received
)
766 /* restart if ping not received */
767 check_ping_restart(c
);
768 if (c
->sig
->signal_received
)
775 if (c
->options
.ce
.connect_timeout
776 && event_timeout_trigger(&c
->c2
.server_poll_interval
, &c
->c2
.timeval
, ETT_DEFAULT
))
778 check_server_poll_timeout(c
);
780 if (c
->sig
->signal_received
)
784 if (event_timeout_trigger(&c
->c2
.scheduled_exit
, &c
->c2
.timeval
, ETT_DEFAULT
))
786 check_scheduled_exit(c
);
788 if (c
->sig
->signal_received
)
794 /* Should we send an OCC_REQUEST message? */
795 check_send_occ_req(c
);
797 /* Should we send an MTU load test? */
798 check_send_occ_load_test(c
);
800 /* Should we send an OCC_EXIT message to remote? */
801 if (c
->c2
.explicit_exit_notification_time_wait
)
803 process_explicit_exit_notification_timer_wakeup(c
);
806 /* Should we ping the remote? */
809 #ifdef ENABLE_MANAGEMENT
812 management_check_bytecount(c
, management
, &c
->c2
.timeval
);
814 #endif /* ENABLE_MANAGEMENT */
818 check_coarse_timers(struct context
*c
)
820 if (now
< c
->c2
.coarse_timer_wakeup
)
822 context_reschedule_sec(c
, c
->c2
.coarse_timer_wakeup
- now
);
826 const struct timeval save
= c
->c2
.timeval
;
827 c
->c2
.timeval
.tv_sec
= BIG_TIMEOUT
;
828 c
->c2
.timeval
.tv_usec
= 0;
829 process_coarse_timers(c
);
830 c
->c2
.coarse_timer_wakeup
= now
+ c
->c2
.timeval
.tv_sec
;
832 dmsg(D_INTERVAL
, "TIMER: coarse timer wakeup %" PRIi64
" seconds", (int64_t)c
->c2
.timeval
.tv_sec
);
834 /* Is the coarse timeout NOT the earliest one? */
835 if (c
->c2
.timeval
.tv_sec
> save
.tv_sec
)
837 c
->c2
.timeval
= save
;
842 check_timeout_random_component_dowork(struct context
*c
)
844 const int update_interval
= 10; /* seconds */
845 c
->c2
.update_timeout_random_component
= now
+ update_interval
;
846 c
->c2
.timeout_random_component
.tv_usec
= (time_t) get_random() & 0x0003FFFF;
847 c
->c2
.timeout_random_component
.tv_sec
= 0;
849 dmsg(D_INTERVAL
, "RANDOM USEC=%ld", (long) c
->c2
.timeout_random_component
.tv_usec
);
853 check_timeout_random_component(struct context
*c
)
855 if (now
>= c
->c2
.update_timeout_random_component
)
857 check_timeout_random_component_dowork(c
);
859 if (c
->c2
.timeval
.tv_sec
>= 1)
861 tv_add(&c
->c2
.timeval
, &c
->c2
.timeout_random_component
);
866 * Handle addition and removal of the 10-byte Socks5 header
871 socks_postprocess_incoming_link(struct context
*c
)
873 if (c
->c2
.link_socket
->socks_proxy
&& c
->c2
.link_socket
->info
.proto
== PROTO_UDP
)
875 socks_process_incoming_udp(&c
->c2
.buf
, &c
->c2
.from
);
880 socks_preprocess_outgoing_link(struct context
*c
,
881 struct link_socket_actual
**to_addr
,
884 if (c
->c2
.link_socket
->socks_proxy
&& c
->c2
.link_socket
->info
.proto
== PROTO_UDP
)
886 *size_delta
+= socks_process_outgoing_udp(&c
->c2
.to_link
, c
->c2
.to_link_addr
);
887 *to_addr
= &c
->c2
.link_socket
->socks_relay
;
891 /* undo effect of socks_preprocess_outgoing_link */
893 link_socket_write_post_size_adjust(int *size
,
897 if (size_delta
> 0 && *size
> size_delta
)
900 if (!buf_advance(buf
, size_delta
))
912 read_incoming_link(struct context
*c
)
915 * Set up for recvfrom call to read datagram
916 * sent to our TCP/UDP port.
920 /*ASSERT (!c->c2.to_tun.len);*/
922 perf_push(PERF_READ_IN_LINK
);
924 c
->c2
.buf
= c
->c2
.buffers
->read_link_buf
;
925 ASSERT(buf_init(&c
->c2
.buf
, c
->c2
.frame
.buf
.headroom
));
927 status
= link_socket_read(c
->c2
.link_socket
,
931 if (socket_connection_reset(c
->c2
.link_socket
, status
))
934 if (port_share
&& socket_foreign_protocol_detected(c
->c2
.link_socket
))
936 const struct buffer
*fbuf
= socket_foreign_protocol_head(c
->c2
.link_socket
);
937 const int sd
= socket_foreign_protocol_sd(c
->c2
.link_socket
);
938 port_share_redirect(port_share
, fbuf
, sd
);
939 register_signal(c
->sig
, SIGTERM
, "port-share-redirect");
944 /* received a disconnect from a connection-oriented protocol */
945 if (event_timeout_defined(&c
->c2
.explicit_exit_notification_interval
))
947 msg(D_STREAM_ERRORS
, "Connection reset during exit notification period, ignoring [%d]", status
);
952 register_signal(c
->sig
, SIGUSR1
, "connection-reset"); /* SOFT-SIGUSR1 -- TCP connection reset */
953 msg(D_STREAM_ERRORS
, "Connection reset, restarting [%d]", status
);
960 /* check_status() call below resets last-error code */
961 bool dco_win_timeout
= tuntap_is_dco_win_timeout(c
->c1
.tuntap
, status
);
963 /* check recvfrom status */
964 check_status(status
, "read", c
->c2
.link_socket
, NULL
);
968 trigger_ping_timeout_signal(c
);
971 /* Remove socks header if applicable */
972 socks_postprocess_incoming_link(c
);
978 process_incoming_link_part1(struct context
*c
, struct link_socket_info
*lsi
, bool floated
)
980 struct gc_arena gc
= gc_new();
981 bool decrypt_status
= false;
983 if (c
->c2
.buf
.len
> 0)
985 c
->c2
.link_read_bytes
+= c
->c2
.buf
.len
;
986 link_read_bytes_global
+= c
->c2
.buf
.len
;
987 #ifdef ENABLE_MEMSTATS
990 mmap_stats
->link_read_bytes
= link_read_bytes_global
;
993 c
->c2
.original_recv_size
= c
->c2
.buf
.len
;
994 #ifdef ENABLE_MANAGEMENT
997 management_bytes_client(management
, c
->c2
.buf
.len
, 0);
998 management_bytes_server(management
, &c
->c2
.link_read_bytes
, &c
->c2
.link_write_bytes
, &c
->c2
.mda_context
);
1004 c
->c2
.original_recv_size
= 0;
1008 /* take action to corrupt packet if we are in gremlin test mode */
1009 if (c
->options
.gremlin
)
1011 if (!ask_gremlin(c
->options
.gremlin
))
1015 corrupt_gremlin(&c
->c2
.buf
, c
->options
.gremlin
);
1019 /* log incoming packet */
1021 if (c
->c2
.log_rw
&& c
->c2
.buf
.len
> 0)
1023 fprintf(stderr
, "R");
1026 msg(D_LINK_RW
, "%s READ [%d] from %s: %s",
1027 proto2ascii(lsi
->proto
, lsi
->af
, true),
1029 print_link_socket_actual(&c
->c2
.from
, &gc
),
1030 PROTO_DUMP(&c
->c2
.buf
, &gc
));
1033 * Good, non-zero length packet received.
1034 * Commence multi-stage processing of packet,
1035 * such as authenticate, decrypt, decompress.
1036 * If any stage fails, it sets buf.len to 0 or -1,
1037 * telling downstream stages to ignore the packet.
1039 if (c
->c2
.buf
.len
> 0)
1041 struct crypto_options
*co
= NULL
;
1042 const uint8_t *ad_start
= NULL
;
1043 if (!link_socket_verify_incoming_addr(&c
->c2
.buf
, lsi
, &c
->c2
.from
))
1045 link_socket_bad_incoming_addr(&c
->c2
.buf
, lsi
, &c
->c2
.from
);
1048 if (c
->c2
.tls_multi
)
1050 uint8_t opcode
= *BPTR(&c
->c2
.buf
) >> P_OPCODE_SHIFT
;
1053 * If DCO is enabled, the kernel drivers require that the
1054 * other end only sends P_DATA_V2 packets. V1 are unknown
1055 * to kernel and passed to userland, but we cannot handle them
1056 * either because crypto context is missing - so drop the packet.
1058 * This can only happen with particular old (2.4.0-2.4.4) servers.
1060 if ((opcode
== P_DATA_V1
) && dco_enabled(&c
->options
))
1063 "Data Channel Offload doesn't support DATA_V1 packets. "
1064 "Upgrade your server to 2.4.5 or newer.");
1069 * If tls_pre_decrypt returns true, it means the incoming
1070 * packet was a good TLS control channel packet. If so, TLS code
1071 * will deal with the packet and set buf.len to 0 so downstream
1074 * If the packet is a data channel packet, tls_pre_decrypt
1075 * will load crypto_options with the correct encryption key
1078 if (tls_pre_decrypt(c
->c2
.tls_multi
, &c
->c2
.from
, &c
->c2
.buf
, &co
,
1079 floated
, &ad_start
))
1081 interval_action(&c
->c2
.tmp_int
);
1083 /* reset packet received timer if TLS packet */
1084 if (c
->options
.ping_rec_timeout
)
1086 event_timeout_reset(&c
->c2
.ping_rec_interval
);
1092 co
= &c
->c2
.crypto_options
;
1096 * Drop non-TLS packet if client-connect script/plugin and cipher selection
1097 * has not yet succeeded. In non-TLS mode tls_multi is not defined
1098 * and we always pass packets.
1100 if (c
->c2
.tls_multi
&& c
->c2
.tls_multi
->multi_state
< CAS_CONNECT_DONE
)
1105 /* authenticate and decrypt the incoming packet */
1106 decrypt_status
= openvpn_decrypt(&c
->c2
.buf
, c
->c2
.buffers
->decrypt_buf
,
1107 co
, &c
->c2
.frame
, ad_start
);
1109 if (!decrypt_status
&& link_socket_connection_oriented(c
->c2
.link_socket
))
1111 /* decryption errors are fatal in TCP mode */
1112 register_signal(c
->sig
, SIGUSR1
, "decryption-error"); /* SOFT-SIGUSR1 -- decryption error in TCP mode */
1113 msg(D_STREAM_ERRORS
, "Fatal decryption error (process_incoming_link), restarting");
1118 buf_reset(&c
->c2
.to_tun
);
1122 return decrypt_status
;
1126 process_incoming_link_part2(struct context
*c
, struct link_socket_info
*lsi
, const uint8_t *orig_buf
)
1128 if (c
->c2
.buf
.len
> 0)
1130 #ifdef ENABLE_FRAGMENT
1133 fragment_incoming(c
->c2
.fragment
, &c
->c2
.buf
, &c
->c2
.frame_fragment
);
1138 /* decompress the incoming packet */
1139 if (c
->c2
.comp_context
)
1141 (*c
->c2
.comp_context
->alg
.decompress
)(&c
->c2
.buf
, c
->c2
.buffers
->decompress_buf
, c
->c2
.comp_context
, &c
->c2
.frame
);
1145 #ifdef PACKET_TRUNCATION_CHECK
1146 /* if (c->c2.buf.len > 1) --c->c2.buf.len; */
1147 ipv4_packet_size_verify(BPTR(&c
->c2
.buf
),
1149 TUNNEL_TYPE(c
->c1
.tuntap
),
1151 &c
->c2
.n_trunc_post_decrypt
);
1155 * Set our "official" outgoing address, since
1156 * if buf.len is non-zero, we know the packet
1157 * authenticated. In TLS mode we do nothing
1158 * because TLS mode takes care of source address
1161 * Also, update the persisted version of our packet-id.
1163 if (!TLS_MODE(c
) && c
->c2
.buf
.len
> 0)
1165 link_socket_set_outgoing_addr(lsi
, &c
->c2
.from
, NULL
, c
->c2
.es
);
1168 /* reset packet received timer */
1169 if (c
->options
.ping_rec_timeout
&& c
->c2
.buf
.len
> 0)
1171 event_timeout_reset(&c
->c2
.ping_rec_interval
);
1174 /* increment authenticated receive byte count */
1175 if (c
->c2
.buf
.len
> 0)
1177 c
->c2
.link_read_bytes_auth
+= c
->c2
.buf
.len
;
1178 c
->c2
.max_recv_size_local
= max_int(c
->c2
.original_recv_size
, c
->c2
.max_recv_size_local
);
1181 /* Did we just receive an openvpn ping packet? */
1182 if (is_ping_msg(&c
->c2
.buf
))
1184 dmsg(D_PING
, "RECEIVED PING PACKET");
1185 c
->c2
.buf
.len
= 0; /* drop packet */
1188 /* Did we just receive an OCC packet? */
1189 if (is_occ_msg(&c
->c2
.buf
))
1191 process_received_occ_msg(c
);
1194 buffer_turnover(orig_buf
, &c
->c2
.to_tun
, &c
->c2
.buf
, &c
->c2
.buffers
->read_link_buf
);
1196 /* to_tun defined + unopened tuntap can cause deadlock */
1197 if (!tuntap_defined(c
->c1
.tuntap
))
1199 c
->c2
.to_tun
.len
= 0;
1204 buf_reset(&c
->c2
.to_tun
);
1209 process_incoming_link(struct context
*c
)
1211 perf_push(PERF_PROC_IN_LINK
);
1213 struct link_socket_info
*lsi
= get_link_socket_info(c
);
1214 const uint8_t *orig_buf
= c
->c2
.buf
.data
;
1216 process_incoming_link_part1(c
, lsi
, false);
1217 process_incoming_link_part2(c
, lsi
, orig_buf
);
1223 process_incoming_dco(struct context
*c
)
1225 #if defined(ENABLE_DCO) && (defined(TARGET_LINUX) || defined(TARGET_FREEBSD))
1226 dco_context_t
*dco
= &c
->c1
.tuntap
->dco
;
1230 /* FreeBSD currently sends us removal notifcation with the old peer-id in
1231 * p2p mode with the ping timeout reason, so ignore that one to not shoot
1232 * ourselves in the foot and removing the just established session */
1233 if (dco
->dco_message_peer_id
!= c
->c2
.tls_multi
->dco_peer_id
)
1235 msg(D_DCO_DEBUG
, "%s: received message for mismatching peer-id %d, "
1236 "expected %d", __func__
, dco
->dco_message_peer_id
,
1237 c
->c2
.tls_multi
->dco_peer_id
);
1241 switch (dco
->dco_message_type
)
1243 case OVPN_CMD_DEL_PEER
:
1244 if (dco
->dco_del_peer_reason
== OVPN_DEL_PEER_REASON_EXPIRED
)
1246 msg(D_DCO_DEBUG
, "%s: received peer expired notification of for peer-id "
1247 "%d", __func__
, dco
->dco_message_peer_id
);
1248 trigger_ping_timeout_signal(c
);
1253 case OVPN_CMD_SWAP_KEYS
:
1254 msg(D_DCO_DEBUG
, "%s: received key rotation notification for peer-id %d",
1255 __func__
, dco
->dco_message_peer_id
);
1256 tls_session_soft_reset(c
->c2
.tls_multi
);
1260 msg(D_DCO_DEBUG
, "%s: received message of type %u - ignoring", __func__
,
1261 dco
->dco_message_type
);
1265 #endif /* if defined(ENABLE_DCO) && (defined(TARGET_LINUX) || defined(TARGET_FREEBSD)) */
1273 read_incoming_tun(struct context
*c
)
1276 * Setup for read() call on TUN/TAP device.
1278 /*ASSERT (!c->c2.to_link.len);*/
1280 perf_push(PERF_READ_IN_TUN
);
1282 c
->c2
.buf
= c
->c2
.buffers
->read_tun_buf
;
1285 if (c
->c1
.tuntap
->windows_driver
== WINDOWS_DRIVER_WINTUN
)
1287 read_wintun(c
->c1
.tuntap
, &c
->c2
.buf
);
1288 if (c
->c2
.buf
.len
== -1)
1290 register_signal(c
->sig
, SIGHUP
, "tun-abort");
1291 c
->persist
.restart_sleep_seconds
= 1;
1292 msg(M_INFO
, "Wintun read error, restarting");
1299 sockethandle_t sh
= { .is_handle
= true, .h
= c
->c1
.tuntap
->hand
};
1300 sockethandle_finalize(sh
, &c
->c1
.tuntap
->reads
, &c
->c2
.buf
, NULL
);
1302 #else /* ifdef _WIN32 */
1303 ASSERT(buf_init(&c
->c2
.buf
, c
->c2
.frame
.buf
.headroom
));
1304 ASSERT(buf_safe(&c
->c2
.buf
, c
->c2
.frame
.buf
.payload_size
));
1305 c
->c2
.buf
.len
= read_tun(c
->c1
.tuntap
, BPTR(&c
->c2
.buf
), c
->c2
.frame
.buf
.payload_size
);
1306 #endif /* ifdef _WIN32 */
1308 #ifdef PACKET_TRUNCATION_CHECK
1309 ipv4_packet_size_verify(BPTR(&c
->c2
.buf
),
1311 TUNNEL_TYPE(c
->c1
.tuntap
),
1313 &c
->c2
.n_trunc_tun_read
);
1316 /* Was TUN/TAP interface stopped? */
1317 if (tuntap_stop(c
->c2
.buf
.len
))
1319 register_signal(c
->sig
, SIGTERM
, "tun-stop");
1320 msg(M_INFO
, "TUN/TAP interface has been stopped, exiting");
1325 /* Was TUN/TAP I/O operation aborted? */
1326 if (tuntap_abort(c
->c2
.buf
.len
))
1328 register_signal(c
->sig
, SIGHUP
, "tun-abort");
1329 c
->persist
.restart_sleep_seconds
= 10;
1330 msg(M_INFO
, "TUN/TAP I/O operation aborted, restarting");
1335 /* Check the status return from read() */
1336 check_status(c
->c2
.buf
.len
, "read from TUN/TAP", NULL
, c
->c1
.tuntap
);
1342 * Drops UDP packets which OS decided to route via tun.
1344 * On Windows and OS X when netwotk adapter is disabled or
1345 * disconnected, platform starts to use tun as external interface.
1346 * When packet is sent to tun, it comes to openvpn, encapsulated
1347 * and sent to routing table, which sends it again to tun.
1350 drop_if_recursive_routing(struct context
*c
, struct buffer
*buf
)
1353 struct openvpn_sockaddr tun_sa
;
1354 int ip_hdr_offset
= 0;
1356 if (c
->c2
.to_link_addr
== NULL
) /* no remote addr known */
1361 tun_sa
= c
->c2
.to_link_addr
->dest
;
1363 int proto_ver
= get_tun_ip_ver(TUNNEL_TYPE(c
->c1
.tuntap
), &c
->c2
.buf
, &ip_hdr_offset
);
1367 const struct openvpn_iphdr
*pip
;
1369 /* make sure we got whole IP header */
1370 if (BLEN(buf
) < ((int) sizeof(struct openvpn_iphdr
) + ip_hdr_offset
))
1375 /* skip ipv4 packets for ipv6 tun */
1376 if (tun_sa
.addr
.sa
.sa_family
!= AF_INET
)
1381 pip
= (struct openvpn_iphdr
*) (BPTR(buf
) + ip_hdr_offset
);
1383 /* drop packets with same dest addr as gateway */
1384 if (tun_sa
.addr
.in4
.sin_addr
.s_addr
== pip
->daddr
)
1389 else if (proto_ver
== 6)
1391 const struct openvpn_ipv6hdr
*pip6
;
1393 /* make sure we got whole IPv6 header */
1394 if (BLEN(buf
) < ((int) sizeof(struct openvpn_ipv6hdr
) + ip_hdr_offset
))
1399 /* skip ipv6 packets for ipv4 tun */
1400 if (tun_sa
.addr
.sa
.sa_family
!= AF_INET6
)
1405 /* drop packets with same dest addr as gateway */
1406 pip6
= (struct openvpn_ipv6hdr
*) (BPTR(buf
) + ip_hdr_offset
);
1407 if (IN6_ARE_ADDR_EQUAL(&tun_sa
.addr
.in6
.sin6_addr
, &pip6
->daddr
))
1415 struct gc_arena gc
= gc_new();
1419 msg(D_LOW
, "Recursive routing detected, drop tun packet to %s",
1420 print_link_socket_actual(c
->c2
.to_link_addr
, &gc
));
1427 * Output: c->c2.to_link
1431 process_incoming_tun(struct context
*c
)
1433 struct gc_arena gc
= gc_new();
1435 perf_push(PERF_PROC_IN_TUN
);
1437 if (c
->c2
.buf
.len
> 0)
1439 c
->c2
.tun_read_bytes
+= c
->c2
.buf
.len
;
1443 if (c
->c2
.log_rw
&& c
->c2
.buf
.len
> 0)
1445 fprintf(stderr
, "r");
1449 /* Show packet content */
1450 dmsg(D_TUN_RW
, "TUN READ [%d]", BLEN(&c
->c2
.buf
));
1452 if (c
->c2
.buf
.len
> 0)
1454 if ((c
->options
.mode
== MODE_POINT_TO_POINT
) && (!c
->options
.allow_recursive_routing
))
1456 drop_if_recursive_routing(c
, &c
->c2
.buf
);
1459 * The --passtos and --mssfix options require
1460 * us to examine the IP header (IPv4 or IPv6).
1462 unsigned int flags
= PIPV4_PASSTOS
| PIP_MSSFIX
| PIPV4_CLIENT_NAT
1463 | PIPV6_ICMP_NOHOST_CLIENT
;
1464 process_ip_header(c
, flags
, &c
->c2
.buf
);
1466 #ifdef PACKET_TRUNCATION_CHECK
1467 /* if (c->c2.buf.len > 1) --c->c2.buf.len; */
1468 ipv4_packet_size_verify(BPTR(&c
->c2
.buf
),
1470 TUNNEL_TYPE(c
->c1
.tuntap
),
1472 &c
->c2
.n_trunc_pre_encrypt
);
1476 if (c
->c2
.buf
.len
> 0)
1478 encrypt_sign(c
, true);
1482 buf_reset(&c
->c2
.to_link
);
1489 * Forges a IPv6 ICMP packet with a no route to host error code from the
1490 * IPv6 packet in buf and sends it directly back to the client via the tun
1491 * device when used on a client and via the link if used on the server.
1493 * @param buf - The buf containing the packet for which the icmp6
1494 * unreachable should be constructed.
1496 * @param client - determines whether to the send packet back via tun or link
1499 ipv6_send_icmp_unreachable(struct context
*c
, struct buffer
*buf
, bool client
)
1501 #define MAX_ICMPV6LEN 1280
1502 struct openvpn_icmp6hdr icmp6out
;
1506 * Get a buffer to the ip packet, is_ipv6 automatically forwards
1507 * the buffer to the ip packet
1509 struct buffer inputipbuf
= *buf
;
1511 is_ipv6(TUNNEL_TYPE(c
->c1
.tuntap
), &inputipbuf
);
1513 if (BLEN(&inputipbuf
) < (int)sizeof(struct openvpn_ipv6hdr
))
1518 const struct openvpn_ipv6hdr
*pip6
= (struct openvpn_ipv6hdr
*)BPTR(&inputipbuf
);
1520 /* Copy version, traffic class, flow label from input packet */
1521 struct openvpn_ipv6hdr pip6out
= *pip6
;
1523 pip6out
.version_prio
= pip6
->version_prio
;
1524 pip6out
.daddr
= pip6
->saddr
;
1527 * Use the IPv6 remote address if we have one, otherwise use a fake one
1528 * using the remote address is preferred since it makes debugging and
1529 * understanding where the ICMPv6 error originates easier
1531 if (c
->options
.ifconfig_ipv6_remote
)
1533 inet_pton(AF_INET6
, c
->options
.ifconfig_ipv6_remote
, &pip6out
.saddr
);
1537 inet_pton(AF_INET6
, "fe80::7", &pip6out
.saddr
);
1540 pip6out
.nexthdr
= OPENVPN_IPPROTO_ICMPV6
;
1543 * The ICMPv6 unreachable code worked best in my (arne) tests with Windows,
1544 * Linux and Android. Windows did not like the administratively prohibited
1545 * return code (no fast fail)
1547 icmp6out
.icmp6_type
= OPENVPN_ICMP6_DESTINATION_UNREACHABLE
;
1548 icmp6out
.icmp6_code
= OPENVPN_ICMP6_DU_NOROUTE
;
1550 int icmpheader_len
= sizeof(struct openvpn_ipv6hdr
)
1551 + sizeof(struct openvpn_icmp6hdr
);
1552 int totalheader_len
= icmpheader_len
;
1554 if (TUNNEL_TYPE(c
->c1
.tuntap
) == DEV_TYPE_TAP
)
1556 totalheader_len
+= sizeof(struct openvpn_ethhdr
);
1560 * Calculate size for payload, defined in the standard that the resulting
1561 * frame should be <= 1280 and have as much as possible of the original
1564 int max_payload_size
= min_int(MAX_ICMPV6LEN
,
1565 c
->c2
.frame
.tun_mtu
- icmpheader_len
);
1566 int payload_len
= min_int(max_payload_size
, BLEN(&inputipbuf
));
1568 pip6out
.payload_len
= htons(sizeof(struct openvpn_icmp6hdr
) + payload_len
);
1570 /* Construct the packet as outgoing packet back to the client */
1571 struct buffer
*outbuf
;
1574 c
->c2
.to_tun
= c
->c2
.buffers
->aux_buf
;
1575 outbuf
= &(c
->c2
.to_tun
);
1579 c
->c2
.to_link
= c
->c2
.buffers
->aux_buf
;
1580 outbuf
= &(c
->c2
.to_link
);
1582 ASSERT(buf_init(outbuf
, totalheader_len
));
1584 /* Fill the end of the buffer with original packet */
1585 ASSERT(buf_safe(outbuf
, payload_len
));
1586 ASSERT(buf_copy_n(outbuf
, &inputipbuf
, payload_len
));
1588 /* ICMP Header, copy into buffer to allow checksum calculation */
1589 ASSERT(buf_write_prepend(outbuf
, &icmp6out
, sizeof(struct openvpn_icmp6hdr
)));
1591 /* Calculate checksum over the packet and write to header */
1593 uint16_t new_csum
= ip_checksum(AF_INET6
, BPTR(outbuf
), BLEN(outbuf
),
1594 (const uint8_t *)&pip6out
.saddr
,
1595 (uint8_t *)&pip6out
.daddr
, OPENVPN_IPPROTO_ICMPV6
);
1596 ((struct openvpn_icmp6hdr
*) BPTR(outbuf
))->icmp6_cksum
= htons(new_csum
);
1600 ASSERT(buf_write_prepend(outbuf
, &pip6out
, sizeof(struct openvpn_ipv6hdr
)));
1603 * Tap mode, we also need to create an Ethernet header.
1605 if (TUNNEL_TYPE(c
->c1
.tuntap
) == DEV_TYPE_TAP
)
1607 if (BLEN(buf
) < (int)sizeof(struct openvpn_ethhdr
))
1612 const struct openvpn_ethhdr
*orig_ethhdr
= (struct openvpn_ethhdr
*) BPTR(buf
);
1614 /* Copy frametype and reverse source/destination for the response */
1615 struct openvpn_ethhdr ethhdr
;
1616 memcpy(ethhdr
.source
, orig_ethhdr
->dest
, OPENVPN_ETH_ALEN
);
1617 memcpy(ethhdr
.dest
, orig_ethhdr
->source
, OPENVPN_ETH_ALEN
);
1618 ethhdr
.proto
= htons(OPENVPN_ETH_P_IPV6
);
1619 ASSERT(buf_write_prepend(outbuf
, ðhdr
, sizeof(struct openvpn_ethhdr
)));
1621 #undef MAX_ICMPV6LEN
1625 process_ip_header(struct context
*c
, unsigned int flags
, struct buffer
*buf
)
1627 if (!c
->options
.ce
.mssfix
)
1629 flags
&= ~PIP_MSSFIX
;
1631 #if PASSTOS_CAPABILITY
1632 if (!c
->options
.passtos
)
1634 flags
&= ~PIPV4_PASSTOS
;
1637 if (!c
->options
.client_nat
)
1639 flags
&= ~PIPV4_CLIENT_NAT
;
1641 if (!c
->options
.route_gateway_via_dhcp
)
1643 flags
&= ~PIPV4_EXTRACT_DHCP_ROUTER
;
1645 if (!c
->options
.block_ipv6
)
1647 flags
&= ~(PIPV6_ICMP_NOHOST_CLIENT
| PIPV6_ICMP_NOHOST_SERVER
);
1652 struct buffer ipbuf
= *buf
;
1653 if (is_ipv4(TUNNEL_TYPE(c
->c1
.tuntap
), &ipbuf
))
1655 #if PASSTOS_CAPABILITY
1656 /* extract TOS from IP header */
1657 if (flags
& PIPV4_PASSTOS
)
1659 link_socket_extract_tos(c
->c2
.link_socket
, &ipbuf
);
1663 /* possibly alter the TCP MSS */
1664 if (flags
& PIP_MSSFIX
)
1666 mss_fixup_ipv4(&ipbuf
, c
->c2
.frame
.mss_fix
);
1669 /* possibly do NAT on packet */
1670 if ((flags
& PIPV4_CLIENT_NAT
) && c
->options
.client_nat
)
1672 const int direction
= (flags
& PIP_OUTGOING
) ? CN_INCOMING
: CN_OUTGOING
;
1673 client_nat_transform(c
->options
.client_nat
, &ipbuf
, direction
);
1675 /* possibly extract a DHCP router message */
1676 if (flags
& PIPV4_EXTRACT_DHCP_ROUTER
)
1678 const in_addr_t dhcp_router
= dhcp_extract_router_msg(&ipbuf
);
1681 route_list_add_vpn_gateway(c
->c1
.route_list
, c
->c2
.es
, dhcp_router
);
1685 else if (is_ipv6(TUNNEL_TYPE(c
->c1
.tuntap
), &ipbuf
))
1687 /* possibly alter the TCP MSS */
1688 if (flags
& PIP_MSSFIX
)
1690 mss_fixup_ipv6(&ipbuf
, c
->c2
.frame
.mss_fix
);
1692 if (!(flags
& PIP_OUTGOING
) && (flags
1693 &(PIPV6_ICMP_NOHOST_CLIENT
| PIPV6_ICMP_NOHOST_SERVER
)))
1695 ipv6_send_icmp_unreachable(c
, buf
,
1696 (bool)(flags
& PIPV6_ICMP_NOHOST_CLIENT
));
1697 /* Drop the IPv6 packet */
1706 * Input: c->c2.to_link
1710 process_outgoing_link(struct context
*c
)
1712 struct gc_arena gc
= gc_new();
1715 perf_push(PERF_PROC_OUT_LINK
);
1717 if (c
->c2
.to_link
.len
> 0 && c
->c2
.to_link
.len
<= c
->c2
.frame
.buf
.payload_size
)
1720 * Setup for call to send/sendto which will send
1721 * packet to remote over the TCP/UDP port.
1724 ASSERT(link_socket_actual_defined(c
->c2
.to_link_addr
));
1727 /* In gremlin-test mode, we may choose to drop this packet */
1728 if (!c
->options
.gremlin
|| ask_gremlin(c
->options
.gremlin
))
1732 * Let the traffic shaper know how many bytes
1735 if (c
->options
.shaper
)
1737 int overhead
= datagram_overhead(c
->c2
.to_link_addr
->dest
.addr
.sa
.sa_family
,
1738 c
->options
.ce
.proto
);
1739 shaper_wrote_bytes(&c
->c2
.shaper
,
1740 BLEN(&c
->c2
.to_link
) + overhead
);
1744 * Let the pinger know that we sent a packet.
1746 if (c
->options
.ping_send_timeout
)
1748 event_timeout_reset(&c
->c2
.ping_send_interval
);
1751 #if PASSTOS_CAPABILITY
1753 link_socket_set_tos(c
->c2
.link_socket
);
1756 /* Log packet send */
1760 fprintf(stderr
, "W");
1763 msg(D_LINK_RW
, "%s WRITE [%d] to %s: %s",
1764 proto2ascii(c
->c2
.link_socket
->info
.proto
, c
->c2
.link_socket
->info
.af
, true),
1765 BLEN(&c
->c2
.to_link
),
1766 print_link_socket_actual(c
->c2
.to_link_addr
, &gc
),
1767 PROTO_DUMP(&c
->c2
.to_link
, &gc
));
1769 /* Packet send complexified by possible Socks5 usage */
1771 struct link_socket_actual
*to_addr
= c
->c2
.to_link_addr
;
1774 /* If Socks5 over UDP, prepend header */
1775 socks_preprocess_outgoing_link(c
, &to_addr
, &size_delta
);
1778 size
= link_socket_write(c
->c2
.link_socket
, &c
->c2
.to_link
, to_addr
);
1780 /* Undo effect of prepend */
1781 link_socket_write_post_size_adjust(&size
, size_delta
, &c
->c2
.to_link
);
1786 c
->c2
.max_send_size_local
= max_int(size
, c
->c2
.max_send_size_local
);
1787 c
->c2
.link_write_bytes
+= size
;
1788 link_write_bytes_global
+= size
;
1789 #ifdef ENABLE_MEMSTATS
1792 mmap_stats
->link_write_bytes
= link_write_bytes_global
;
1795 #ifdef ENABLE_MANAGEMENT
1798 management_bytes_client(management
, 0, size
);
1799 management_bytes_server(management
, &c
->c2
.link_read_bytes
, &c
->c2
.link_write_bytes
, &c
->c2
.mda_context
);
1805 /* Check return status */
1806 error_code
= openvpn_errno();
1807 check_status(size
, "write", c
->c2
.link_socket
, NULL
);
1811 /* Did we write a different size packet than we intended? */
1812 if (size
!= BLEN(&c
->c2
.to_link
))
1815 "TCP/UDP packet was truncated/expanded on write to %s (tried=%d,actual=%d)",
1816 print_link_socket_actual(c
->c2
.to_link_addr
, &gc
),
1817 BLEN(&c
->c2
.to_link
),
1822 /* if not a ping/control message, indicate activity regarding --inactive parameter */
1823 if (c
->c2
.buf
.len
> 0)
1825 register_activity(c
, size
);
1828 /* for unreachable network and "connecting" state switch to the next host */
1830 bool unreachable
= error_code
==
1836 if (size
< 0 && unreachable
&& c
->c2
.tls_multi
1837 && !tls_initial_packet_received(c
->c2
.tls_multi
) && c
->options
.mode
== MODE_POINT_TO_POINT
)
1839 msg(M_INFO
, "Network unreachable, restarting");
1840 register_signal(c
->sig
, SIGUSR1
, "network-unreachable");
1845 if (c
->c2
.to_link
.len
> 0)
1847 msg(D_LINK_ERRORS
, "TCP/UDP packet too large on write to %s (tried=%d,max=%d)",
1848 print_link_socket_actual(c
->c2
.to_link_addr
, &gc
),
1850 c
->c2
.frame
.buf
.payload_size
);
1854 buf_reset(&c
->c2
.to_link
);
1861 * Input: c->c2.to_tun
1865 process_outgoing_tun(struct context
*c
)
1868 * Set up for write() call to TUN/TAP
1871 if (c
->c2
.to_tun
.len
<= 0)
1876 perf_push(PERF_PROC_OUT_TUN
);
1879 * The --mssfix option requires
1880 * us to examine the IP header (IPv4 or IPv6).
1882 process_ip_header(c
,
1883 PIP_MSSFIX
| PIPV4_EXTRACT_DHCP_ROUTER
| PIPV4_CLIENT_NAT
| PIP_OUTGOING
,
1886 if (c
->c2
.to_tun
.len
<= c
->c2
.frame
.buf
.payload_size
)
1889 * Write to TUN/TAP device.
1896 fprintf(stderr
, "w");
1899 dmsg(D_TUN_RW
, "TUN WRITE [%d]", BLEN(&c
->c2
.to_tun
));
1901 #ifdef PACKET_TRUNCATION_CHECK
1902 ipv4_packet_size_verify(BPTR(&c
->c2
.to_tun
),
1903 BLEN(&c
->c2
.to_tun
),
1904 TUNNEL_TYPE(c
->c1
.tuntap
),
1906 &c
->c2
.n_trunc_tun_write
);
1910 size
= write_tun_buffered(c
->c1
.tuntap
, &c
->c2
.to_tun
);
1912 size
= write_tun(c
->c1
.tuntap
, BPTR(&c
->c2
.to_tun
), BLEN(&c
->c2
.to_tun
));
1917 c
->c2
.tun_write_bytes
+= size
;
1919 check_status(size
, "write to TUN/TAP", NULL
, c
->c1
.tuntap
);
1921 /* check written packet size */
1924 /* Did we write a different size packet than we intended? */
1925 if (size
!= BLEN(&c
->c2
.to_tun
))
1928 "TUN/TAP packet was destructively fragmented on write to %s (tried=%d,actual=%d)",
1929 c
->c1
.tuntap
->actual_name
,
1930 BLEN(&c
->c2
.to_tun
),
1934 /* indicate activity regarding --inactive parameter */
1935 register_activity(c
, size
);
1941 * This should never happen, probably indicates some kind
1944 msg(D_LINK_ERRORS
, "tun packet too large on write (tried=%d,max=%d)",
1946 c
->c2
.frame
.buf
.payload_size
);
1949 buf_reset(&c
->c2
.to_tun
);
1955 pre_select(struct context
*c
)
1957 /* make sure current time (now) is updated on function entry */
1960 * Start with an effectively infinite timeout, then let it
1961 * reduce to a timeout that reflects the component which
1962 * needs the earliest service.
1964 c
->c2
.timeval
.tv_sec
= BIG_TIMEOUT
;
1965 c
->c2
.timeval
.tv_usec
= 0;
1968 if (check_debug_level(D_TAP_WIN_DEBUG
))
1970 c
->c2
.timeval
.tv_sec
= 1;
1971 if (tuntap_defined(c
->c1
.tuntap
))
1973 tun_show_debug(c
->c1
.tuntap
);
1978 /* check coarse timers? */
1979 check_coarse_timers(c
);
1980 if (c
->sig
->signal_received
)
1985 /* If tls is enabled, do tls control channel packet processing. */
1986 if (c
->c2
.tls_multi
)
1991 /* In certain cases, TLS errors will require a restart */
1992 check_tls_errors(c
);
1993 if (c
->sig
->signal_received
)
1998 /* check for incoming control messages on the control channel like
1999 * push request/reply, or authentication failure and 2FA messages */
2000 if (tls_test_payload_len(c
->c2
.tls_multi
) > 0)
2002 check_incoming_control_channel(c
);
2005 /* Should we send an OCC message? */
2006 check_send_occ_msg(c
);
2008 #ifdef ENABLE_FRAGMENT
2009 /* Should we deliver a datagram fragment to remote? */
2016 /* Update random component of timeout */
2017 check_timeout_random_component(c
);
2021 * Wait for I/O events. Used for both TCP & UDP sockets
2022 * in point-to-point mode and for UDP sockets in
2023 * point-to-multipoint mode.
2027 io_wait_dowork(struct context
*c
, const unsigned int flags
)
2029 unsigned int socket
= 0;
2030 unsigned int tuntap
= 0;
2031 struct event_set_return esr
[4];
2033 /* These shifts all depend on EVENT_READ (=1) and EVENT_WRITE (=2)
2034 * and are added to the shift. Check openvpn.h for more details.
2036 static int socket_shift
= SOCKET_SHIFT
;
2037 static int tun_shift
= TUN_SHIFT
;
2038 static int err_shift
= ERR_SHIFT
;
2039 #ifdef ENABLE_MANAGEMENT
2040 static int management_shift
= MANAGEMENT_SHIFT
;
2042 #ifdef ENABLE_ASYNC_PUSH
2043 static int file_shift
= FILE_SHIFT
;
2045 #if defined(TARGET_LINUX) || defined(TARGET_FREEBSD)
2046 static int dco_shift
= DCO_SHIFT
; /* Event from DCO linux kernel module */
2050 * Decide what kind of events we want to wait for.
2052 event_reset(c
->c2
.event_set
);
2055 * On win32 we use the keyboard or an event object as a source
2056 * of asynchronous signals.
2058 if (flags
& IOW_WAIT_SIGNAL
)
2060 wait_signal(c
->c2
.event_set
, (void *)&err_shift
);
2064 * If outgoing data (for TCP/UDP port) pending, wait for ready-to-send
2065 * status from TCP/UDP port. Otherwise, wait for incoming data on
2068 if (flags
& IOW_TO_LINK
)
2070 if (flags
& IOW_SHAPER
)
2073 * If sending this packet would put us over our traffic shaping
2074 * quota, don't send -- instead compute the delay we must wait
2075 * until it will be OK to send the packet.
2079 /* set traffic shaping delay in microseconds */
2080 if (c
->options
.shaper
)
2082 delay
= max_int(delay
, shaper_delay(&c
->c2
.shaper
));
2087 socket
|= EVENT_WRITE
;
2091 shaper_soonest_event(&c
->c2
.timeval
, delay
);
2096 socket
|= EVENT_WRITE
;
2099 else if (!((flags
& IOW_FRAG
) && TO_LINK_FRAG(c
)))
2101 if (flags
& IOW_READ_TUN
)
2103 tuntap
|= EVENT_READ
;
2108 * If outgoing data (for TUN/TAP device) pending, wait for ready-to-send status
2109 * from device. Otherwise, wait for incoming data on TCP/UDP port.
2111 if (flags
& IOW_TO_TUN
)
2113 tuntap
|= EVENT_WRITE
;
2117 if (flags
& IOW_READ_LINK
)
2119 socket
|= EVENT_READ
;
2124 * outgoing bcast buffer waiting to be sent?
2126 if (flags
& IOW_MBUF
)
2128 socket
|= EVENT_WRITE
;
2132 * Force wait on TUN input, even if also waiting on TCP/UDP output
2134 if (flags
& IOW_READ_TUN_FORCE
)
2136 tuntap
|= EVENT_READ
;
2140 if (tuntap_is_wintun(c
->c1
.tuntap
))
2143 * With wintun we are only interested in read event. Ring buffer is
2144 * always ready for write, so we don't do wait.
2146 tuntap
= EVENT_READ
;
2151 * Configure event wait based on socket, tuntap flags.
2153 socket_set(c
->c2
.link_socket
, c
->c2
.event_set
, socket
, (void *)&socket_shift
, NULL
);
2154 tun_set(c
->c1
.tuntap
, c
->c2
.event_set
, tuntap
, (void *)&tun_shift
, NULL
);
2155 #if defined(TARGET_LINUX) || defined(TARGET_FREEBSD)
2156 if (socket
& EVENT_READ
&& c
->c2
.did_open_tun
)
2158 dco_event_set(&c
->c1
.tuntap
->dco
, c
->c2
.event_set
, (void *)&dco_shift
);
2162 #ifdef ENABLE_MANAGEMENT
2165 management_socket_set(management
, c
->c2
.event_set
, (void *)&management_shift
, NULL
);
2169 #ifdef ENABLE_ASYNC_PUSH
2170 /* arm inotify watcher */
2171 if (c
->options
.mode
== MODE_SERVER
)
2173 event_ctl(c
->c2
.event_set
, c
->c2
.inotify_fd
, EVENT_READ
, (void *)&file_shift
);
2178 * Possible scenarios:
2179 * (1) tcp/udp port has data available to read
2180 * (2) tcp/udp port is ready to accept more data to write
2181 * (3) tun dev has data available to read
2182 * (4) tun dev is ready to accept more data to write
2183 * (5) we received a signal (handler sets signal_received)
2184 * (6) timeout (tv) expired
2187 c
->c2
.event_set_status
= ES_ERROR
;
2189 if (!c
->sig
->signal_received
)
2191 if (!(flags
& IOW_CHECK_RESIDUAL
) || !socket_read_residual(c
->c2
.link_socket
))
2196 if (check_debug_level(D_EVENT_WAIT
))
2198 show_wait_status(c
);
2203 * Wait for something to happen.
2205 status
= event_wait(c
->c2
.event_set
, &c
->c2
.timeval
, esr
, SIZE(esr
));
2207 check_status(status
, "event_wait", NULL
, NULL
);
2212 c
->c2
.event_set_status
= 0;
2213 for (i
= 0; i
< status
; ++i
)
2215 const struct event_set_return
*e
= &esr
[i
];
2216 c
->c2
.event_set_status
|= ((e
->rwflags
& 3) << *((int *)e
->arg
));
2219 else if (status
== 0)
2221 c
->c2
.event_set_status
= ES_TIMEOUT
;
2226 c
->c2
.event_set_status
= SOCKET_READ
;
2230 /* 'now' should always be a reasonably up-to-date timestamp */
2233 /* set signal_received if a signal was received */
2234 if (c
->c2
.event_set_status
& ES_ERROR
)
2236 get_signal(&c
->sig
->signal_received
);
2239 dmsg(D_EVENT_WAIT
, "I/O WAIT status=0x%04x", c
->c2
.event_set_status
);
2243 process_io(struct context
*c
)
2245 const unsigned int status
= c
->c2
.event_set_status
;
2247 #ifdef ENABLE_MANAGEMENT
2248 if (status
& (MANAGEMENT_READ
|MANAGEMENT_WRITE
))
2251 management_io(management
);
2255 /* TCP/UDP port ready to accept write */
2256 if (status
& SOCKET_WRITE
)
2258 process_outgoing_link(c
);
2260 /* TUN device ready to accept write */
2261 else if (status
& TUN_WRITE
)
2263 process_outgoing_tun(c
);
2265 /* Incoming data on TCP/UDP port */
2266 else if (status
& SOCKET_READ
)
2268 read_incoming_link(c
);
2271 process_incoming_link(c
);
2274 /* Incoming data on TUN device */
2275 else if (status
& TUN_READ
)
2277 read_incoming_tun(c
);
2280 process_incoming_tun(c
);
2283 else if (status
& DCO_READ
)
2287 process_incoming_dco(c
);