当前位置:   article > 正文

SSL连接建立过程分析(3)_ssl_accept

ssl_accept
SSL连接建立过程分析(3)
 
本文档的Copyleft归yfydz所有,使用GPL发布,可以自由拷贝,转载,转载时请保持文档的完整性,严禁用于任何商业用途。
msn: yfydz_no1@hotmail.com
来源: http://yfydz.cublog.cn

2.12 SSL_accept
 
SSL_accept()函数完成SSL协商的服务器端操作:
/* ssl/ssl_lib.c */
int SSL_accept(SSL *s)
 {
 if (s->handshake_func == 0)
  /* Not properly initialized yet */
  SSL_set_accept_state(s);
 return(s->method->ssl_accept(s));
 }
 
其中SSL_set_accept_state(s)函数初始化SSL协商处理:
void SSL_set_accept_state(SSL *s)
 {
// 服务器端
 s->server=1;
 s->shutdown=0;
// 初始化服务器端状态值
 s->state=SSL_ST_ACCEPT|SSL_ST_BEFORE;
// 握手函数即是ssl_accept函数
 s->handshake_func=s->method->ssl_accept;
 /* clear the current cipher */
// 清除SSL读写加密算法上下文
 ssl_clear_cipher_ctx(s);
 }
 
因此最重要的就是ssl_accept()这个成员函数,是前面SSLv[2][3]_server_method()中定义的,如对于SSLv23方法,处理函数分别为ssl23_accept()函数,其它SSLv2和SSLv3方法分别对应ssl2_accept()和ssl3_accept(),后两者就没有协商过程了,ssl23_accept()实际在协商确定协议版本后也是调用ssl2[3]_accept()。

SSL很多状态都分A,B两种,A状态表示刚进入该状态还没有收发数据,B状态表示进行的收发数据处理但还没完成善后操作。

/* ssl/s23_srvr.c */
int ssl23_accept(SSL *s)
 {
 BUF_MEM *buf;
 unsigned long Time=time(NULL);
 void (*cb)(const SSL *ssl,int type,int val)=NULL;
 int ret= -1;
 int new_state,state;
// 用当前时间作为随机种子
 RAND_add(&Time,sizeof(Time),0);
 ERR_clear_error();
 clear_sys_error();
// 在SSL_new()函数中,s->info_callback并没有定义
// 是通过SSL_set_info_callback()函数单独定义的
 if (s->info_callback != NULL)
  cb=s->info_callback;
// SSL_CTX_new()函数中,ctx->info_callback也没定义
// 是通过SSL_CTX_set_info_callback()宏单独定义的
 else if (s->ctx->info_callback != NULL)
  cb=s->ctx->info_callback;
// 握手计数
 s->in_handshake++;
// 如果SSL已用,清除SSL原来的值
 if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
 for (;;)
  {
// 保存SSL当前状态
  state=s->state;
// 在SSL_set_accept_state中s->state被初始化为SSL_ST_ACCEPT|SSL_ST_BEFORE
  switch(s->state)
   {
  case SSL_ST_BEFORE:
  case SSL_ST_ACCEPT:
  case SSL_ST_BEFORE|SSL_ST_ACCEPT:
  case SSL_ST_OK|SSL_ST_ACCEPT:
   s->server=1;
   if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
   /* s->version=SSL3_VERSION; */
   s->type=SSL_ST_ACCEPT;
   if (s->init_buf == NULL)
    {
// 生成一个SSL缓冲区
    if ((buf=BUF_MEM_new()) == NULL)
     {
     ret= -1;
     goto end;
     }
    if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
     {
     ret= -1;
     goto end;
     }
    s->init_buf=buf;
    }
// 初始化认证码MAC
   ssl3_init_finished_mac(s);
// SSL状态设置为SSL23_ST_SR_CLNT_HELLO_A,进入客户端的HELLO A状态
   s->state=SSL23_ST_SR_CLNT_HELLO_A;
// 接受的SSL会话统计
   s->ctx->stats.sess_accept++;
   s->init_num=0;
// 重新进行循环接收客户端数据
   break;
  case SSL23_ST_SR_CLNT_HELLO_A:
  case SSL23_ST_SR_CLNT_HELLO_B:
   s->shutdown=0;
// 获取对方的HELLO信息,也就是进行SSL握手协议
   ret=ssl23_get_client_hello(s);
   if (ret >= 0) cb=NULL;
   goto end;
   /* break; */
  default:
   SSLerr(SSL_F_SSL23_ACCEPT,SSL_R_UNKNOWN_STATE);
   ret= -1;
   goto end;
   /* break; */
   }
// 如果SSL状态改变,而又定义了信息回调函数,执行之
  if ((cb != NULL) && (s->state != state))
   {
   new_state=s->state;
   s->state=state;
   cb(s,SSL_CB_ACCEPT_LOOP,1);
   s->state=new_state;
   }
  }
end:
 s->in_handshake--;
 if (cb != NULL)
  cb(s,SSL_CB_ACCEPT_EXIT,ret);
 return(ret);
 }

可见,SSL握手协议是在ssl23_get_client_hello(s)函数中完成,也算个很复杂的函数:

int ssl23_get_client_hello(SSL *s)
 {
//
// SSL握手协议头首部空间,11字节
// 客户端发出的HELLO,如果第一字节最高位为1
// 头两字节是包长度,不包括第一字节的第一位;
// 第3字节是握手类型类型,取值如下:
// enum {
//        hello_request(0), client_hello(1), server_hello(2),
//        certificate(11), server_key_exchange (12), certificate_request(13),
//        server_done(14), certificate_verify(15), client_key_exchange(16),
//        finished(20), (255)
// } HandshakeType;
// 第4,5字节是版本类型,TLS1为0301,SSL3为0300,SSL2为0002
// 第6,7字节是加密算法部分(cipher_specs)信息长度
// 第8,9字节是会话ID(session id)
// 第10,11字节是挑战信息长度(challenge)
//
//
// 如果第一字节最高位不为1或者非客户端发出的HELLO
// 第一字节为类型,取值为:
// enum {
//        change_cipher_spec(20), alert(21), handshake(22),
//        application_data(23), (255)
// } ContentType
// 第2,3字节是服务器端SSL版本类型,TLS1为0301,SSL3为0300,SSL2为0002
// 第4,5字节为握手部分长度
// 第6字节为消息类型
// 第7,8,9字节为握手信息长度
// 第10,11字节为客户端SSL版本
//
// 本函数的主要功能是识别客户端SSL版本,根据服务器自身支持的SSL版本,选定合适的SSL
// 版本进行下一步的accept,即ssl2_accept或ssl3_accept
//
 char buf_space[11]; /* Request this many bytes in initial read.
                      * We can detect SSL 3.0/TLS 1.0 Client Hellos
                      * ('type == 3') correctly only when the following
                      * is in a single record, which is not guaranteed by
                      * the protocol specification:
                      * Byte  Content
                      *  0     type            /
                      *  1/2   version          > record header
                      *  3/4   length          /
                      *  5     msg_type        /
                      *  6-8   length           > Client Hello message
                      *  9/10  client_version  /
                      */
 char *buf= &(buf_space[0]);
 unsigned char *p,*d,*d_len,*dd;
 unsigned int i;
 unsigned int csl,sil,cl;
 int n=0,j;
 int type=0;
 int v[2];
#ifndef OPENSSL_NO_RSA
 int use_sslv2_strong=0;
#endif
 if (s->state == SSL23_ST_SR_CLNT_HELLO_A)
  {
  /* read the initial header */
  v[0]=v[1]=0;
  if (!ssl3_setup_buffers(s)) goto err;
// 读取首部空间长度的数据
  n=ssl23_read_bytes(s, sizeof buf_space);
  if (n != sizeof buf_space) return(n); /* n == -1 || n == 0 */
// 数据保存在s->packet缓冲区中
  p=s->packet;
// 拷贝到buf_space
  memcpy(buf,p,n);
  if ((p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO))
   {
   /*
    * SSLv2 header
    */
   if ((p[3] == 0x00) && (p[4] == 0x02))
    {
// 客户端为SSLv2
    v[0]=p[3]; v[1]=p[4];
    /* SSLv2 */
    if (!(s->options & SSL_OP_NO_SSLv2))
     type=1;
    }
   else if (p[3] == SSL3_VERSION_MAJOR)
    {
// 客户端主版本SSLv3
    v[0]=p[3]; v[1]=p[4];
    /* SSLv3/TLSv1 */
    if (p[4] >= TLS1_VERSION_MINOR)
     {
// 次版本表明是客户端TLS1.0, 服务器为SSL3或TLS1时type设为2,为SSL2时设为1
     if (!(s->options & SSL_OP_NO_TLSv1))
      {
// 服务器支持TLS1.0,SSL类型设置为TLS1
      s->version=TLS1_VERSION;
      /* type=2; */ /* done later to survive restarts */
      s->state=SSL23_ST_SR_CLNT_HELLO_B;
      }
     else if (!(s->options & SSL_OP_NO_SSLv3))
      {
// 服务器不支持TLS,支持SSL3,SSL类型设置为SSL3
      s->version=SSL3_VERSION;
      /* type=2; */
      s->state=SSL23_ST_SR_CLNT_HELLO_B;
      }
     else if (!(s->options & SSL_OP_NO_SSLv2))
      {
// 服务器这边不支持SSL3,TLS1,协商为SSL2, type为1
      type=1;
      }
     }
    else if (!(s->options & SSL_OP_NO_SSLv3))
     {
// 次版本号表明客户端是SSLv3
     s->version=SSL3_VERSION;
     /* type=2; */
     s->state=SSL23_ST_SR_CLNT_HELLO_B;
     }
    else if (!(s->options & SSL_OP_NO_SSLv2))
     type=1;
    }
   }
  else if ((p[0] == SSL3_RT_HANDSHAKE) &&
// p[1]为SSL3主版本号
    (p[1] == SSL3_VERSION_MAJOR) &&
// p[5]为消息类型
    (p[5] == SSL3_MT_CLIENT_HELLO) &&
// p[3],p[4]为握手部分长度,如果只是记录头部分,长度小于5,
    ((p[3] == 0 && p[4] < 5 /* silly record length? */)
// p[9]是客户端主版本号
    || (p[9] == p[1])))
   {
   /*
    * SSLv3 or tls1 header
    */
// 主版本为SSL3   
   v[0]=p[1]; /* major version (= SSL3_VERSION_MAJOR) */
 /* We must look at client_version inside the Client Hello message
  * to get the correct minor version.
  * However if we have only a pathologically small fragment of the
  * Client Hello message, this would be difficult, and we'd have
  * to read more records to find out.
  * No known SSL 3.0 client fragments ClientHello like this,
  * so we simply assume TLS 1.0 to avoid protocol version downgrade
  * attacks. */
   if (p[3] == 0 && p[4] < 6)
    {
// 如果握手长度小于6认为就是TLS1
#if 0
    SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_SMALL);
    goto err;
#else
    v[1] = TLS1_VERSION_MINOR;
#endif
    }
   else
    v[1]=p[10]; /* minor version according to client_version */
   if (v[1] >= TLS1_VERSION_MINOR)
    {
// 客户端为TLS1.0,按上面相同的方法设置服务器端的版本
// 注意这时的type设置为3
    if (!(s->options & SSL_OP_NO_TLSv1))
     {
     s->version=TLS1_VERSION;
     type=3;
     }
    else if (!(s->options & SSL_OP_NO_SSLv3))
     {
     s->version=SSL3_VERSION;
     type=3;
     }
    }
   else
    {
    /* client requests SSL 3.0 */
// 客户端为SSL3,设置服务器段SSL版本
// type为3
    if (!(s->options & SSL_OP_NO_SSLv3))
     {
     s->version=SSL3_VERSION;
     type=3;
     }
    else if (!(s->options & SSL_OP_NO_TLSv1))
     {
     /* we won't be able to use TLS of course,
      * but this will send an appropriate alert */
     s->version=TLS1_VERSION;
     type=3;
     }
    }
   }
  else if ((strncmp("GET ", (char *)p,4) == 0) ||
    (strncmp("POST ",(char *)p,5) == 0) ||
    (strncmp("HEAD ",(char *)p,5) == 0) ||
    (strncmp("PUT ", (char *)p,4) == 0))
   {
// 在SSL通道中走HTTP的明文数据,出错
   SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTP_REQUEST);
   goto err;
   }
  else if (strncmp("CONNECT",(char *)p,7) == 0)
   {
   SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTPS_PROXY_REQUEST);
   goto err;
   }
  }
// 进入HELLO B状态,也就是客户端数据是SSL3或TLS,而且(p[0] & 0x80) &&
// (p[2] == SSL2_MT_CLIENT_HELLO),已经找出服务器端的对应版本
 if (s->state == SSL23_ST_SR_CLNT_HELLO_B)
  {
  /* we have SSLv3/TLSv1 in an SSLv2 header
   * (other cases skip this state) */
// 服务器是SSL3或TLS1,类型为2
  type=2;
  p=s->packet;
  v[0] = p[3]; /* == SSL3_VERSION_MAJOR */
  v[1] = p[4];
// p[0],p[1]是HELLO包长
  n=((p[0]&0x7f)<<8)|p[1];
  if (n > (1024*4))
  {
// 一个SSL段不能超过4096字节
  SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_LARGE);
  goto err;
  }
// 读取整个包长数据,"2"是因为p[0],p[1]表示包长不包括自身长度(2字节)
// 这个读操作数据初始指针是不移动的,注意前面已经用这函数读了11字节了
  j=ssl23_read_bytes(s,n+2);
  if (j <= 0) return(j);
// MAC认证
  ssl3_finish_mac(s, s->packet+2, s->packet_length-2);
  if (s->msg_callback)
   s->msg_callback(0, SSL2_VERSION, 0, s->packet+2, s->packet_length-2, s, s->msg_callback_arg); /* CLIENT-HELLO */

// 回到数据头
  p=s->packet;
// 跳过前面的5字节,长度、类型、版本信息
  p+=5;
// cipher_specs的长度
  n2s(p,csl);
// session id
  n2s(p,sil);
// challenge长度
  n2s(p,cl);
// SSL缓冲区头
  d=(unsigned char *)s->init_buf->data;
  if ((csl+sil+cl+11) != s->packet_length)
   {
// 检查包长是否正确
   SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH);
   goto err;
   }
// 以下开始填充作为ssl3_accept定义的客户端SSL握手包
  /* record header: msg_type ... */
// 数据类型
  *(d++) = SSL3_MT_CLIENT_HELLO;
  /* ... and length (actual value will be written later) */
  d_len = d;
// 数据类型1字节,长度2字节
  d += 3;
  /* client_version */
// 版本号
  *(d++) = SSL3_VERSION_MAJOR; /* == v[0] */
  *(d++) = v[1];
  /* lets populate the random area */
  /* get the challenge_length */
// 拷贝挑战信息,最多SSL3_RANDOM_SIZE(32)
  i=(cl > SSL3_RANDOM_SIZE)?SSL3_RANDOM_SIZE:cl;
  memset(d,0,SSL3_RANDOM_SIZE);
// 如果挑战信息长度不到SSL3_RANDOM_SIZE,相当于前面多余字节补0,不是在后面
  memcpy(&(d[SSL3_RANDOM_SIZE-i]),&(p[csl+sil]),i);
  d+=SSL3_RANDOM_SIZE;
  /* no session-id reuse */
// 会话ID没用
  *(d++)=0;
  /* ciphers */
// cipher_specs域
  j=0;
// 头指针备份
  dd=d;
// 留出长度空间
  d+=2;
  for (i=0; i<csl; i+=3)
   {
// p[0]位置现在是收到包中cipher_specs数据头
   if (p[i] != 0) continue;
// 每3字节为一个单位,拷贝后两字节,第1字节忽略
   *(d++)=p[i+1];
   *(d++)=p[i+2];
   j+=2;
   }
// 写cipher_specs长度,网络序
  s2n(j,dd);
  /* COMPRESSION */
  *(d++)=1;
  *(d++)=0;
// 实际数据长度
  i = (d-(unsigned char *)s->init_buf->data) - 4;
  l2n3((long)i, d_len);
  /* get the data reused from the init_buf */
  s->s3->tmp.reuse_message=1;
  s->s3->tmp.message_type=SSL3_MT_CLIENT_HELLO;
  s->s3->tmp.message_size=i;
  }
 /* imaginary new state (for program structure): */
 /* s->state = SSL23_SR_CLNT_HELLO_C */
 if (type == 1)
  {
// 服务器只支持SSL2的情况,实际已经很少见了
#ifdef OPENSSL_NO_SSL2
  SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL);
  goto err;
#else
  /* we are talking sslv2 */
  /* we need to clean up the SSLv3/TLSv1 setup and put in the
   * sslv2 stuff. */
  if (s->s2 == NULL)
   {
// 新分配一个SSL2结构
   if (!ssl2_new(s))
    goto err;
   }
  else
   ssl2_clear(s);
// 释放SSL3结构
  if (s->s3 != NULL) ssl3_free(s);
// 将缓冲区扩到SSL2的最大记录情况
  if (!BUF_MEM_grow_clean(s->init_buf,
   SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER))
   {
   goto err;
   }
// 这个状态是"SSL2_ST"系列(SSL2服务器端)的
  s->state=SSL2_ST_GET_CLIENT_HELLO_A;
  if ((s->options & SSL_OP_MSIE_SSLV2_RSA_PADDING) ||
   use_sslv2_strong ||
   (s->options & SSL_OP_NO_TLSv1 && s->options & SSL_OP_NO_SSLv3))
   s->s2->ssl2_rollback=0;
  else
   /* reject SSL 2.0 session if client supports SSL 3.0 or TLS 1.0
    * (SSL 3.0 draft/RFC 2246, App. E.2) */
   s->s2->ssl2_rollback=1;
  /* setup the n bytes we have read so we get them from
   * the sslv2 buffer */
  s->rstate=SSL_ST_READ_HEADER;
  s->packet_length=n;
  s->packet= &(s->s2->rbuf[0]);
// buf是接收数据缓冲区头,n正常的话是11
  memcpy(s->packet,buf,n);
  s->s2->rbuf_left=n;
  s->s2->rbuf_offs=0;
// SSL封装方法是SSL2
  s->method=SSLv2_server_method();
// 实际函数为ssl2_accept
  s->handshake_func=s->method->ssl_accept;
#endif
  }
 if ((type == 2) || (type == 3))
  {
// 服务器自身可以支持SSL3或TLS1
  /* we have SSLv3/TLSv1 (type 2: SSL2 style, type 3: SSL3/TLS style) */
// 初始化写缓冲区
  if (!ssl_init_wbio_buffer(s,1)) goto err;
  /* we are in this state */
// SSL3_ST类,SSL3服务器收到客户端的HELLO的A状态
  s->state=SSL3_ST_SR_CLNT_HELLO_A;
// 进行一些初始化操作
  if (type == 3)
   {
   /* put the 'n' bytes we have read into the input buffer
    * for SSLv3 */
   s->rstate=SSL_ST_READ_HEADER;
   s->packet_length=n;
   s->packet= &(s->s3->rbuf.buf[0]);
   memcpy(s->packet,buf,n);
   s->s3->rbuf.left=n;
   s->s3->rbuf.offset=0;
   }
  else
   {
   s->packet_length=0;
   s->s3->rbuf.left=0;
   s->s3->rbuf.offset=0;
   }
  if (s->version == TLS1_VERSION)
// 实际上TLS1中的accept方法也就是ssl3_accept
   s->method = TLSv1_server_method();
  else
// 就是ssl3_accept
   s->method = SSLv3_server_method();
  s->handshake_func=s->method->ssl_accept;
  }
 
 if ((type < 1) || (type > 3))
  {
  /* bad, very bad */
  SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNKNOWN_PROTOCOL);
  goto err;
  }
 s->init_num=0;
 if (buf != buf_space) OPENSSL_free(buf);
 s->first_packet=1;
// 递归调用SSL_accept(),这时方法是固定的,就是调用ssl2_accept()或ssl3_accept()
 return(SSL_accept(s));
err:
 if (buf != buf_space) OPENSSL_free(buf);
 return(-1);
 }
ssl23_get_client_hello()函数最后就是确定了服务器端的方法类型,然后再进行SSL_accept(),实际就是调用ssl2_accept()或ssl3_accept()。

举例ssl3_accept()函数定义如下,ssl2_accept()就不分析了:
/* ssl/s3_srvr.c */
int ssl3_accept(SSL *s)
 {
 BUF_MEM *buf;
 unsigned long l,Time=time(NULL);
 void (*cb)(const SSL *ssl,int type,int val)=NULL;
 long num1;
 int ret= -1;
 int new_state,state,skip=0;
// 和前面ssl23_accpet一样进行初始化
 RAND_add(&Time,sizeof(Time),0);
 ERR_clear_error();
 clear_sys_error();
 if (s->info_callback != NULL)
  cb=s->info_callback;
 else if (s->ctx->info_callback != NULL)
  cb=s->ctx->info_callback;
 /* init things to blank */
 s->in_handshake++;
 if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
 if (s->cert == NULL)
  {
  SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_NO_CERTIFICATE_SET);
  return(-1);
  }
 for (;;)
  {
  state=s->state;
  switch (s->state)
   {
  case SSL_ST_RENEGOTIATE:
   s->new_session=1;
   /* s->state=SSL_ST_ACCEPT; */
  case SSL_ST_BEFORE:
  case SSL_ST_ACCEPT:
  case SSL_ST_BEFORE|SSL_ST_ACCEPT:
  case SSL_ST_OK|SSL_ST_ACCEPT:
// 这些是客户端服务器固定就用SSL3进行连接时进入的初始状态,如果是从ssl23_accpet
// 过来的是进不到这状态的
// 下面是ssl23_accept时类似的初始化
   s->server=1;
   if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
   if ((s->version>>8) != 3)
    {
    SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
    return -1;
    }
   s->type=SSL_ST_ACCEPT;
   if (s->init_buf == NULL)
    {
    if ((buf=BUF_MEM_new()) == NULL)
     {
     ret= -1;
     goto end;
     }
    if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
     {
     ret= -1;
     goto end;
     }
    s->init_buf=buf;
    }
   if (!ssl3_setup_buffers(s))
    {
    ret= -1;
    goto end;
    }
   s->init_num=0;
   if (s->state != SSL_ST_RENEGOTIATE)
    {
    /* Ok, we now need to push on a buffering BIO so that
     * the output is sent in a way that TCP likes :-)
     */
    if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; }
    
    ssl3_init_finished_mac(s);
    s->state=SSL3_ST_SR_CLNT_HELLO_A;
    s->ctx->stats.sess_accept++;
    }
   else
    {
    /* s->state == SSL_ST_RENEGOTIATE,
     * we will just send a HelloRequest */
    s->ctx->stats.sess_accept_renegotiate++;
    s->state=SSL3_ST_SW_HELLO_REQ_A;
    }
   break;
  case SSL3_ST_SW_HELLO_REQ_A:
  case SSL3_ST_SW_HELLO_REQ_B:
// 此状态是是写服务器端的回应的HELLO请求信息
   s->shutdown=0;
// 发送服务器端的HELLO
   ret=ssl3_send_hello_request(s);
   if (ret <= 0) goto end;
// 转入REQ_C状态
   s->s3->tmp.next_state=SSL3_ST_SW_HELLO_REQ_C;
   s->state=SSL3_ST_SW_FLUSH;
   s->init_num=0;
   ssl3_init_finished_mac(s);
   break;
  case SSL3_ST_SW_HELLO_REQ_C:
   s->state=SSL_ST_OK;
   break;
// 从ssl23_accept过来时的状态是SSL3_ST_SR_CLNT_HELLO_A,属于读数据状态
  case SSL3_ST_SR_CLNT_HELLO_A:
  case SSL3_ST_SR_CLNT_HELLO_B:
  case SSL3_ST_SR_CLNT_HELLO_C:
   s->shutdown=0;
// 读取客户端数据,如果是ssl23_accept过来的话数据是由ssl23_get_client_hello()
// 函数自己构造的,而不是实际收到的
   ret=ssl3_get_client_hello(s);
   if (ret <= 0) goto end;
   s->new_session = 2;
// 状态转为服务器准备写HELLO的A状态
   s->state=SSL3_ST_SW_SRVR_HELLO_A;
   s->init_num=0;
   break;
  case SSL3_ST_SW_SRVR_HELLO_A:
  case SSL3_ST_SW_SRVR_HELLO_B:
// 此状态是是写服务器端的HELLO信息
   ret=ssl3_send_server_hello(s);
   if (ret <= 0) goto end;
// s->hit用来标志该ssl会话是否是重用(reuse)的,在ssl3_get_client_hello()函数
// 中检查客户端的hello信息后设置
   if (s->hit)
// 如果会话是reuse的,状态为CHANGE
    s->state=SSL3_ST_SW_CHANGE_A;
   else
// 否则为新SSL会话,进入证书处理A状态
    s->state=SSL3_ST_SW_CERT_A;
   s->init_num=0;
   break;
  case SSL3_ST_SW_CERT_A:
  case SSL3_ST_SW_CERT_B:
// 该状态下进行证书交换,用来计算连接共享密钥
   /* Check if it is anon DH */
   if (!(s->s3->tmp.new_cipher->algorithms & SSL_aNULL))
    {
// 非NULL加密的话发送服务器端的证书
    ret=ssl3_send_server_certificate(s);
    if (ret <= 0) goto end;
    }
   else
    skip=1;
// 进入密钥交换状态
   s->state=SSL3_ST_SW_KEY_EXCH_A;
   s->init_num=0;
   break;
  case SSL3_ST_SW_KEY_EXCH_A:
  case SSL3_ST_SW_KEY_EXCH_B:
// 该状态下进行数据加密密钥的交换操作
// 算法类型,由一个常数表示
   l=s->s3->tmp.new_cipher->algorithms;
   /* clear this, it may get reset by
    * send_server_key_exchange */
   if ((s->options & SSL_OP_EPHEMERAL_RSA)
#ifndef OPENSSL_NO_KRB5
    && !(l & SSL_KRB5)
#endif /* OPENSSL_NO_KRB5 */
    )
// 临时性RSA密钥交换
   /* option SSL_OP_EPHEMERAL_RSA sends temporary RSA key
    * even when forbidden by protocol specs
    * (handshake may fail as clients are not required to
    * be able to handle this) */
    s->s3->tmp.use_rsa_tmp=1;
   else
    s->s3->tmp.use_rsa_tmp=0;
   /* only send if a DH key exchange, fortezza or
    * RSA but we have a sign only certificate */
   if (s->s3->tmp.use_rsa_tmp
       || (l & (SSL_DH|SSL_kFZA))
       || ((l & SSL_kRSA)
    && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
        || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
     && EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
     )
        )
    )
       )
    {
// 进行RSA密钥交换
    ret=ssl3_send_server_key_exchange(s);
    if (ret <= 0) goto end;
    }
   else
    skip=1;
// 转入证书请求阶段
   s->state=SSL3_ST_SW_CERT_REQ_A;
   s->init_num=0;
   break;
  case SSL3_ST_SW_CERT_REQ_A:
  case SSL3_ST_SW_CERT_REQ_B:
// 此阶段进入对方证书请求
   if (/* don't request cert unless asked for it: */
    !(s->verify_mode & SSL_VERIFY_PEER) ||
   /* if SSL_VERIFY_CLIENT_ONCE is set,
    * don't request cert during re-negotiation: */
    ((s->session->peer != NULL) &&
     (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
   /* never request cert in anonymous ciphersuites
    * (see section "Certificate request" in SSL 3 drafts
    * and in RFC 2246): */
    ((s->s3->tmp.new_cipher->algorithms & SSL_aNULL) &&
   /* ... except when the application insists on verification
    * (against the specs, but s3_clnt.c accepts this for SSL 3) */
     !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
                              /* never request cert in Kerberos ciphersuites */
                                (s->s3->tmp.new_cipher->algorithms & SSL_aKRB5))
    {
// 在大多数情况下不需要客户端的证书
// 如果想认证对方,只要以上条件之一不满足就可以认证对方
// CTX的verify_mode则通过SSL_CTX_set_verify()来修改
// s->verify_mode可通过函数SSL_set_verify()来修改,
// s->verify_mode的初始值是ctx->verify_mode赋予的
    /* no cert request */
    skip=1;
    s->s3->tmp.cert_request=0;
// 服务器端协商发送结束
    s->state=SSL3_ST_SW_SRVR_DONE_A;
    }
   else
    {
// 发送要获取对方证书的请求
    s->s3->tmp.cert_request=1;
    ret=ssl3_send_certificate_request(s);
    if (ret <= 0) goto end;
#ifndef NETSCAPE_HANG_BUG
// 没预定义HANG_BUG的话服务器端协商写数据应该完成了
    s->state=SSL3_ST_SW_SRVR_DONE_A;
#else
// 否则进入清除写缓冲状态
// 下一个状态是准备接收证书A
    s->state=SSL3_ST_SW_FLUSH;
    s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
#endif
    s->init_num=0;
    }
   break;
  case SSL3_ST_SW_SRVR_DONE_A:
  case SSL3_ST_SW_SRVR_DONE_B:
// 发送服务器协商数据完成信息
   ret=ssl3_send_server_done(s);
   if (ret <= 0) goto end;
// 下一个状态将是接收证书A状态
   s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
// 转入写缓冲清除状态
   s->state=SSL3_ST_SW_FLUSH;
   s->init_num=0;
   break;
  
  case SSL3_ST_SW_FLUSH:
// 清除写缓冲区
   /* number of bytes to be flushed */
   num1=BIO_ctrl(s->wbio,BIO_CTRL_INFO,0,NULL);
   if (num1 > 0)
    {
    s->rwstate=SSL_WRITING;
    num1=BIO_flush(s->wbio);
    if (num1 <= 0) { ret= -1; goto end; }
    s->rwstate=SSL_NOTHING;
    }
// 进入预先保存的下一状态
   s->state=s->s3->tmp.next_state;
   break;
  case SSL3_ST_SR_CERT_A:
  case SSL3_ST_SR_CERT_B:
// 此状态下接收对方证书
   /* Check for second client hello (MS SGC) */
// 检查对方的HELLO信息
   ret = ssl3_check_client_hello(s);
   if (ret <= 0)
    goto end;
   if (ret == 2)
    s->state = SSL3_ST_SR_CLNT_HELLO_C;
   else {
    /* could be sent for a DH cert, even if we
     * have not asked for it :-) */
// 获取对方证书
    ret=ssl3_get_client_certificate(s);
    if (ret <= 0) goto end;
    s->init_num=0;
// 准备进入密钥交换状态
    s->state=SSL3_ST_SR_KEY_EXCH_A;
   }
   break;
  case SSL3_ST_SR_KEY_EXCH_A:
  case SSL3_ST_SR_KEY_EXCH_B:
// 该状态处理密钥交换
   ret=ssl3_get_client_key_exchange(s);
   if (ret <= 0) goto end;
// 准备进入证书验证状态
   s->state=SSL3_ST_SR_CERT_VRFY_A;
   s->init_num=0;
   /* We need to get hashes here so if there is
    * a client cert, it can be verified */
// 验证证书的MAC码
   s->method->ssl3_enc->cert_verify_mac(s,
    &(s->s3->finish_dgst1),
    &(s->s3->tmp.cert_verify_md[0]));
   s->method->ssl3_enc->cert_verify_mac(s,
    &(s->s3->finish_dgst2),
    &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]));
   break;
  case SSL3_ST_SR_CERT_VRFY_A:
  case SSL3_ST_SR_CERT_VRFY_B:
// 验证证书
   /* we should decide if we expected this one */
   ret=ssl3_get_cert_verify(s);
   if (ret <= 0) goto end;
// 状态转为接收结束A状态
   s->state=SSL3_ST_SR_FINISHED_A;
   s->init_num=0;
   break;
  case SSL3_ST_SR_FINISHED_A:
  case SSL3_ST_SR_FINISHED_B:
// 本状态为服务器端接收结束
// 获取结束信息
   ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A,
    SSL3_ST_SR_FINISHED_B);
   if (ret <= 0) goto end;
   if (s->hit)
// 如果会话是reuse的, 连接已经建立
    s->state=SSL_ST_OK;
   else
// 转CHANGE_A
    s->state=SSL3_ST_SW_CHANGE_A;
   s->init_num=0;
   break;
  case SSL3_ST_SW_CHANGE_A:
  case SSL3_ST_SW_CHANGE_B:
// 本状态为服务器发送修改信息
// SSL加密算法
   s->session->cipher=s->s3->tmp.new_cipher;
   if (!s->method->ssl3_enc->setup_key_block(s))
    { ret= -1; goto end; }
// 发送修改加密算法信息
   ret=ssl3_send_change_cipher_spec(s,
    SSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B);
   if (ret <= 0) goto end;
// 转发送结束
   s->state=SSL3_ST_SW_FINISHED_A;
   s->init_num=0;
   if (!s->method->ssl3_enc->change_cipher_state(s,
    SSL3_CHANGE_CIPHER_SERVER_WRITE))
    {
    ret= -1;
    goto end;
    }
   break;
  case SSL3_ST_SW_FINISHED_A:
  case SSL3_ST_SW_FINISHED_B:
// 服务器发送结束,SSL握手完成
   ret=ssl3_send_finished(s,
    SSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B,
    s->method->ssl3_enc->server_finished_label,
    s->method->ssl3_enc->server_finished_label_len);
   if (ret <= 0) goto end;
// 清除SSL写缓冲
   s->state=SSL3_ST_SW_FLUSH;
   if (s->hit)
// 如果会话是reuse的,状态转为接收结束
    s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;
   else
// SSL连接成功完成
    s->s3->tmp.next_state=SSL_ST_OK;
   s->init_num=0;
   break;
  case SSL_ST_OK:
// 清除连接过程中分配的资源
   /* clean a few things up */
   ssl3_cleanup_key_block(s);
   BUF_MEM_free(s->init_buf);
   s->init_buf=NULL;
   /* remove buffering on output */
   ssl_free_wbio_buffer(s);
   s->init_num=0;
   if (s->new_session == 2) /* skipped if we just sent a HelloRequest */
    {
  /* actually not necessarily a 'new' session unless
   * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION is set */
    
    s->new_session=0;
    
    ssl_update_cache(s,SSL_SESS_CACHE_SERVER);
    
    s->ctx->stats.sess_accept_good++;
    /* s->server=1; */
    s->handshake_func=ssl3_accept;
    if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
    }
   
   ret = 1;
   goto end;
   /* break; */
  default:
   SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_UNKNOWN_STATE);
   ret= -1;
   goto end;
   /* break; */
   }
  
  if (!s->s3->tmp.reuse_message && !skip)
   {
   if (s->debug)
    {
    if ((ret=BIO_flush(s->wbio)) <= 0)
     goto end;
    }

   if ((cb != NULL) && (s->state != state))
    {
    new_state=s->state;
    s->state=state;
    cb(s,SSL_CB_ACCEPT_LOOP,1);
    s->state=new_state;
    }
   }
  skip=0;
  }
end:
 /* BIO_flush(s->wbio); */
// accept结束, ret=1
 s->in_handshake--;
 if (cb != NULL)
  cb(s,SSL_CB_ACCEPT_EXIT,ret);
 return(ret);
 }
 
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/210541
推荐阅读
相关标签
  

闽ICP备14008679号