ssl.c

来自「OpenVPN -- A Secure tunneling daemon」· C语言 代码 · 共 2,515 行 · 第 1/5 页

C
2,515 行
字号
		{		  msg (D_TLS_ERRORS,		       "TLS Error: Error reading data channel key from plaintext buffer");		  goto error;		}	      if (!check_key (&key, &session->opt->key_type))		{		  msg (D_TLS_ERRORS, "TLS Error: Bad decrypting key received from peer");		  goto error;		}	      ASSERT (buf->len > 0);	      if (!session->opt->disable_occ &&		  !options_cmp_equal ((const char *)BPTR (buf),				      session->opt->options, buf->len))		{		  msg (D_TLS_ERRORS | M_WARN,		       "WARNING: TLS Error: Local ('%s') and Remote ('%s') options are incompatible -- NOTE: use --disable-occ to suppress this error",		       session->opt->options, BPTR (buf));#if 0		  /* enable this line to make options incompatibility		     a handshake-fatal error */		  status = 0;#endif		}	      buf_clear (buf);	      if (status == 1)		{		  init_key_ctx (&ks->key.decrypt, &key, &session->opt->key_type,				DO_DECRYPT, "Data Channel Decrypt");		}	      CLEAR (key);	      if (status == 0)		goto error;	      state_change = true;	      msg (D_TLS_DEBUG_MED, "STATE S_GOT_KEY");	      ks->state = S_GOT_KEY;	    }	  /* Write outgoing plaintext to TLS object */	  buf = &ks->plaintext_write_buf;	  if (buf->len)	    {	      int status = key_state_write_plaintext (ks, buf);	      if (status == -1)		{		  msg (D_TLS_ERRORS,		       "TLS ERROR: Outgoing Plaintext -> TLS object write error");		  goto error;		}	      if (status == 1)		{		  state_change = true;		  msg (D_TLS_DEBUG, "Outgoing Plaintext -> TLS");		}	    }	  /* Outgoing Ciphertext to reliable buffer */	  if (ks->state >= S_START)	    {	      buf = reliable_get_buf_output_sequenced (&ks->send_reliable);	      if (buf)		{		  int status = key_state_read_ciphertext (ks, buf, PAYLOAD_SIZE_DYNAMIC (&multi->opt.frame));		  if (status == -1)		    {		      msg (D_TLS_ERRORS,			   "TLS Error: Ciphertext -> reliable UDP transport read error");		      goto error;		    }		  if (status == 1)		    {		      reliable_mark_active_outgoing (&ks->send_reliable, buf, P_CONTROL_V1);		      INCR_GENERATED;		      state_change = true;		      msg (D_TLS_DEBUG, "Outgoing Ciphertext -> Reliable");		    }		}	    }	}      mutex_cycle (L_TLS);     }  while (state_change);  current = time (NULL);#ifdef TLS_AGGREGATE_ACK  /* Send 1 or more ACKs (each received control packet gets one ACK) */  if (!to_udp->len && !reliable_ack_empty (&ks->rec_ack))    {      buf = &ks->ack_write_buf;      ASSERT (buf_init (buf, EXTRA_FRAME (&multi->opt.frame)));      write_control_auth (session, ks, buf, to_udp_addr, P_ACK_V1,			  RELIABLE_ACK_SIZE, false, current);      *to_udp = *buf;      generated_output = true;      state_change = true;      msg (D_TLS_DEBUG, "Dedicated ACK -> UDP");    }#endif  /* When should we wake up again? */  {    if (ks->state >= S_INITIAL && ks->state < S_NORMAL)      {	compute_earliest_wakeup (wakeup, reliable_send_timeout (&ks->send_reliable, current));		if (ks->must_negotiate)	  compute_earliest_wakeup (wakeup, ks->must_negotiate - current);      }    if (ks->established && session->opt->renegotiate_seconds)      compute_earliest_wakeup (wakeup, ks->established + session->opt->renegotiate_seconds - current);    if (*wakeup)      msg (D_TLS_DEBUG, "tls_process: timeout set to %d", *wakeup);    return generated_output;  }error:  ks->state = S_ERROR;  msg (D_TLS_ERRORS, "TLS Error: TLS handshake failed");  INCR_ERROR;  return false;}#undef ks#undef ks_lame/* * Called at the top of the event loop in openvpn.c. * * Basically decides if we should call tls_process for * the active or untrusted sessions. */booltls_multi_process (struct tls_multi *multi,		   struct buffer *to_udp,		   struct sockaddr_in *to_udp_addr,		   struct udp_socket *to_udp_socket,		   interval_t *wakeup,		   time_t current){  int i;  bool generated_output = false;  mutex_lock (L_TLS);  /*   * Process each session object having state of S_INITIAL or greater,   * and which has a defined remote IP addr.   */  for (i = 0; i < TM_SIZE; ++i)    {      struct tls_session *session = &multi->session[i];      struct key_state *ks = &session->key[KS_PRIMARY];      struct key_state *ks_lame = &session->key[KS_LAME_DUCK];      /* set initial remote address */      if (i == TM_ACTIVE && ks->state == S_INITIAL && addr_defined (&to_udp_socket->addr->actual))	ks->remote_addr = to_udp_socket->addr->actual;      msg (D_TLS_DEBUG,	   "tls_multi_process: i=%d state=%s, mysid=%s, stored-sid=%s, stored-ip=%s",	   i,	   state_name (ks->state),	   session_id_print (&session->session_id),	   session_id_print (&ks->session_id_remote),	   print_sockaddr (&ks->remote_addr));      if (ks->state >= S_INITIAL && addr_defined (&ks->remote_addr))	{	  current = time (NULL);	  if (tls_process (multi, session, to_udp, to_udp_addr, to_udp_socket, wakeup, current))	    generated_output = true;	  /*	   * If tls_process hits an error:	   * (1) If the session has an unexpired lame duck key, preserve it.	   * (2) Reinitialize the session.	   */	  if (ks->state == S_ERROR)	    {	      if (i == TM_ACTIVE && ks_lame->state >= S_ACTIVE)		move_session (multi, TM_LAME_DUCK, TM_ACTIVE, true);	      else		reset_session (multi, session);	    }	}      mutex_cycle (L_TLS);    }  current = time (NULL);  /*   * If lame duck session expires, kill it.   */  if (lame_duck_must_die (&multi->session[TM_LAME_DUCK], wakeup, current)) {    tls_session_free(&multi->session[TM_LAME_DUCK], true);    msg (D_TLS_DEBUG_LOW, "TLS: tls_multi_process: killed expiring key");  }  /*   * If untrusted session achieves TLS authentication,   * move it to active session, usurping any prior session.   */  if (DECRYPT_KEY_ENABLED (multi, &multi->session[TM_UNTRUSTED].key[KS_PRIMARY])) {    move_session (multi, TM_ACTIVE, TM_UNTRUSTED, true);    msg (D_TLS_DEBUG_LOW, "TLS: tls_multi_process: untrusted session promoted to trusted");  }  mutex_unlock (L_TLS);  return generated_output;}/* * When OpenVPN is built in pthread-mode, thread_func * will periodically call tls_multi_process. */#ifdef USE_PTHREAD/* * Main thread <-> TLS thread communication. * Errors are fatal if they are of these types. */static inline boollocal_sock_fatal (int status){  return status < 0 && (errno == ENOTCONN || errno == ECONNREFUSED);}/* * This routine is the TLS work thread. */static void *thread_func (void *arg){  const int gc_level = gc_new_level ();  const struct thread_parms *parm = (struct thread_parms*) arg;#if 0  /*   * Under Linux, Posix threads appear to inherit mlockall state   * from parent.  This is good news, since mlockall will fail   * if we restart after having downgraded privileges with   * --user or group.   */  if (parm->mlock) /* should we disable paging? */    do_mlockall (true);  #endif  /* change thread priority if requested */  set_nice (parm->nice);  /* event loop */  while (true)    {      int stat;      interval_t wakeup;      struct tt_ret ret;      struct buffer buf;      fd_set reads;      msg (D_TLS_THREAD_DEBUG, "TLS_THREAD: thread event loop");      /*       * Call tls_multi_process repeatedly as long       * as it has data to forward to the UDP port.       */      do {		time_t current = time (NULL);		CLEAR (ret);	CLEAR (buf);	wakeup = TLS_MULTI_REFRESH;   /* maximum timeout */	/* do one SSL/TLS process pass */	if (tls_multi_process (parm->multi, &buf, &ret.to_udp_addr,			       parm->udp_socket, &wakeup, current))	  {	    /* wait for foreground thread to be ready to accept data */	    {	      fd_set writes;	      struct timeval tv;	      tv.tv_sec = TLS_MULTI_THREAD_SEND_TIMEOUT;	      tv.tv_usec = 0;	      FD_ZERO (&writes);	      FD_SET (parm->sd[TLS_THREAD_WORKER], &writes);	      stat = select (parm->sd[TLS_THREAD_WORKER] + 1, NULL, &writes, NULL, &tv);	      if (!stat) /* timeout? */		break;	    }	    /* make a fresh copy of buf in ret */	    ret.to_udp = clone_buf (&buf);	    /* send buffer to foreground where it will be forwarded to remote */	    {	      int fatal;	      stat = write (parm->sd[TLS_THREAD_WORKER], &ret, sizeof (ret));	      fatal = local_sock_fatal (stat);	      check_status (stat, "write to foreground", NULL);	      if (stat < 0)		free_buf (&ret.to_udp);	      if (fatal)		goto exit;	      msg (D_TLS_THREAD_DEBUG, "TLS_THREAD: write to TLS_THREAD_WORKER");	    }	  }      } while (ret.to_udp.len);      /* do a quick garbage collect */      gc_collect (gc_level);      /* wait on select */      {	struct timeval tv;	tv.tv_sec = wakeup;	tv.tv_usec = 0;	FD_ZERO (&reads);	FD_SET (parm->sd[TLS_THREAD_WORKER], &reads);	stat = select (parm->sd[TLS_THREAD_WORKER] + 1, &reads, NULL, NULL, &tv);	/* received a message from foreground */	check_status (stat, "select", NULL);      }      /* timeout? */      if (!stat)	continue;      /* process message(s) from foreground */      if (stat > 0 && FD_ISSET (parm->sd[TLS_THREAD_WORKER], &reads))	{	  int err;	  do {	    struct tt_cmd tc;	    int fatal;	    stat = read (parm->sd[TLS_THREAD_WORKER], &tc, sizeof (tc));	    err = errno;	    fatal = local_sock_fatal (stat);	    check_status (stat, "read from foreground", NULL);	    if (stat == sizeof (tc))	      {		if (tc.cmd == TTCMD_PROCESS)		  {		    msg (D_TLS_THREAD_DEBUG, "TLS_THREAD: TTCMD_PROCESS");		  }		else if (tc.cmd == TTCMD_EXIT)		  {		    msg (D_TLS_THREAD_DEBUG, "TLS_THREAD: TTCMD_EXIT");		    goto exit;		  }		else		  msg (D_TLS_THREAD_DEBUG, "TLS_THREAD: Unknown TTCMD code: %d", tc.cmd);	      }	    else if (fatal)	      goto exit;	  } while (stat > 0);	}    } exit:  close (parm->sd[TLS_THREAD_WORKER]);  gc_free_level (gc_level);  return NULL;}/* * All tls_thread functions below this point operate in the context of the main * thread. *//* * Send a command to TLS thread. */static inttls_thread_send_command (struct thread_parms *state, int cmd, bool wait_if_necessary){  struct tt_cmd tc;  int stat;  bool fatal;  tc.cmd = cmd;  while (true)    {      stat = write (state->sd[TLS_THREAD_MAIN], &tc, sizeof (tc));      if (wait_if_necessary && stat < 0 && errno == EAGAIN)	{	  msg (D_TLS_THREAD_DEBUG, "TLS_THREAD: tls_thread_send_command WAIT");	  sleep (1);	}      else	break;    }  fatal = local_sock_fatal (stat);  check_status (stat, "write command to tls thread", NULL);  if (stat == sizeof (tc))    return 1;  else if (fatal)    return -1;  else    return 0;}/* * Create the TLS thread. */voidtls_thread_create (struct thread_parms *state,		   struct tls_multi *multi,		   struct udp_socket *udp_socket,		   int nice, bool mlock){  CLEAR (*state);  state->multi = multi;  state->udp_socket = udp_socket;  state->nice = nice;  state->mlock = mlock;  /*   * Make a socket for foreground and background threads   * to communicate.  The background thread will set its   * end to blocking, while the foreground will set its   * end to non-blocking.   */  if (socketpair (PF_UNIX, SOCK_DGRAM, 0, state->sd) == -1)    msg (M_ERR, "socketpair call failed");  set_nonblock (state->sd[TLS_THREAD_MAIN]);  set_nonblock (state->sd[TLS_THREAD_WORKER]);  set_cloexec (state->sd[TLS_THREAD_MAIN]);  set_cloexec (state->sd[TLS_THREAD_WORKER]);  work_thread_create (thread_func, (void*)state);}/* * Send a command to TLS thread telling it to cycle * through tls_multi_process() as long as there * is data to process. */inttls_thread_process (struct thread_parms *state){  return tls_thread_send_command (state, TTCMD_PROCESS, false);}/* free any unprocessed buffers sent from background to foreground */static voidtls_thread_flush (struct thread_parms *state){  struct tt_ret ttr;  while (tls_thread_rec_buf (state, &ttr, false) == 1)    {      free_buf (&ttr.to_udp);    }}/* * Close the TLS thread */voidtls_thread_close (struct thread_parms *state){  tls_thread_send_command (state, TTCMD_EXIT, true);  work_thread_join ();  tls_thread_flush (state);  close (state->sd[TLS_THREAD_MAIN]);}/* * Receive an object from the TLS thread which * normally contains a buffer to be sent to * the remote peer over the UDP port. * * Return: *  1 if ok *  0 if non-fatal error *  -1 if fatal error */inttls_thread_rec_buf (struct thread_parms *state, struct tt_ret* ttr, bool do_check_status){  int stat;  bool fatal;  stat = read (state->sd[TLS_THREAD_MAIN], ttr, sizeof (*ttr));  fatal = local_sock_fatal (stat);  if (do_check_status)    check_status (stat, "read buffer from tls thread", NULL);  if (stat == sizeof (*ttr))    return 1;  else if (fatal)    return -1;  else

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?