Example #1
0
static void
tls_print_session_info(const host_addr_t addr, uint16 port,
                       gnutls_session session, bool incoming)
{
    const char *proto, *cert, *kx, *ciph, *mac, *comp;

    g_return_if_fail(session);

    proto = gnutls_protocol_get_name(gnutls_protocol_get_version(session));
    cert = gnutls_certificate_type_get_name(
               gnutls_certificate_type_get(session));
    kx = gnutls_kx_get_name(gnutls_kx_get(session));
    comp = gnutls_compression_get_name(gnutls_compression_get(session));
    ciph = gnutls_cipher_get_name(gnutls_cipher_get(session));
    mac = gnutls_mac_get_name(gnutls_mac_get (session));

    g_debug(
        "TLS session info (%s):\n"
        "    Host:         %s\n"
        "    Protocol:     %s\n"
        "    Certificate:  %s\n"
        "    Key Exchange: %s\n"
        "    Cipher:       %s\n"
        "    MAC:          %s\n"
        "    Compression:  %s",
        incoming ? "incoming" : "outgoing",
        host_addr_port_to_string(addr, port),
        NULL_STRING(proto),
        NULL_STRING(cert),
        NULL_STRING(kx),
        NULL_STRING(ciph),
        NULL_STRING(mac),
        NULL_STRING(comp)
    );
}
Example #2
0
const char *dtls_gnutls_get_cipher(struct conn *conn, char *dst)
{
	struct dtls_gnutls_data * d;
	const char *comp, *cipher, *mac, *proto, *kxname, *auth;
	gnutls_kx_algorithm_t kx;
	gnutls_credentials_type_t cred;
	
	if (!conn->dtls_data){
		sprintf(dst, "%s","None");
		return dst;
	}

	d = (struct dtls_gnutls_data*)conn->dtls_data;
	if ( !d->session ){
		sprintf(dst, "%s","None");
		return dst;
	}
	kx = gnutls_kx_get(d->session);
	kxname = gnutls_kx_get_name(kx);

	cred = gnutls_auth_get_type(d->session);

	proto = gnutls_protocol_get_name(gnutls_protocol_get_version(d->session));
	comp = gnutls_compression_get_name(gnutls_compression_get(d->session));
	cipher = gnutls_cipher_get_name(gnutls_cipher_get(d->session));
	mac = gnutls_mac_get_name(gnutls_mac_get(d->session));
	sprintf(dst,"cipher: %s/%s/%s/%s/%s",proto,kxname,cipher,mac,comp);

	return dst;
}
Example #3
0
File: ssl.c Project: ezc/elinks
unsigned char *
get_ssl_connection_cipher(struct socket *socket)
{
	ssl_t *ssl = socket->ssl;
	struct string str;

	if (!init_string(&str)) return NULL;

#ifdef USE_OPENSSL
	add_format_to_string(&str, "%ld-bit %s %s",
		SSL_get_cipher_bits(ssl, NULL),
		SSL_get_cipher_version(ssl),
		SSL_get_cipher_name(ssl));
#elif defined(CONFIG_GNUTLS)
	/* XXX: How to get other relevant parameters? */
	add_format_to_string(&str, "%s - %s - %s - %s - %s (compr: %s)",
		gnutls_protocol_get_name(gnutls_protocol_get_version(*ssl)),
		gnutls_kx_get_name(gnutls_kx_get(*ssl)),
		gnutls_cipher_get_name(gnutls_cipher_get(*ssl)),
		gnutls_mac_get_name(gnutls_mac_get(*ssl)),
		gnutls_certificate_type_get_name(gnutls_certificate_type_get(*ssl)),
		gnutls_compression_get_name(gnutls_compression_get(*ssl)));
#endif

	return str.source;
}
Example #4
0
/* This function will log some details of the given session. */
static void
logtlsinfo (gnutls_session_t session)
{
  gnutls_credentials_type_t cred;
  const char *protocol =
    gnutls_protocol_get_name (gnutls_protocol_get_version (session));
  gnutls_kx_algorithm_t kx = gnutls_kx_get (session);
  const char *keyexchange = gnutls_kx_get_name (kx);
  const char *certtype =
    gnutls_certificate_type_get_name (gnutls_certificate_type_get (session));
  const char *cipher = gnutls_cipher_get_name (gnutls_cipher_get (session));
  const char *mac = gnutls_mac_get_name (gnutls_mac_get (session));
  const char *compression =
    gnutls_compression_get_name (gnutls_compression_get (session));
  int resumedp = gnutls_session_is_resumed (session);

  /* This message can arguably belong to LOG_AUTH.  */
  syslog (LOG_INFO, "TLS handshake negotiated protocol `%s', "
	  "key exchange `%s', certficate type `%s', cipher `%s', "
	  "mac `%s', compression `%s', %s",
	  protocol ? protocol : "N/A",
	  keyexchange ? keyexchange : "N/A",
	  certtype ? certtype : "N/A",
	  cipher ? cipher : "N/A",
	  mac ? mac : "N/A", compression ? compression : "N/A",
	  resumedp ? "resumed session" : "session not resumed");

  cred = gnutls_auth_get_type (session);
  switch (cred)
    {
    case GNUTLS_CRD_ANON:
      syslog (LOG_INFO | LOG_DAEMON,
	      "TLS anonymous authentication with %d bit Diffie-Hellman",
	      gnutls_dh_get_prime_bits (session));
      break;

    case GNUTLS_CRD_CERTIFICATE:
      if (kx == GNUTLS_KX_DHE_RSA || kx == GNUTLS_KX_DHE_DSS)
	syslog (LOG_INFO | LOG_DAEMON,
		"TLS certificate authentication with %d bits "
		"ephemeral Diffie-Hellman",
		gnutls_dh_get_prime_bits (session));
      logcertinfo (session);
      break;

    case GNUTLS_CRD_SRP:
    case GNUTLS_CRD_PSK:
    case GNUTLS_CRD_IA:
    default:
      syslog (LOG_ERR | LOG_DAEMON, "Unknown TLS authentication (%d)", cred);
      break;
    }
}
Example #5
0
  void GnuTLSClientAnon::getCertInfo()
  {
    m_certInfo.status = CertOk;

    const char* info;
    info = gnutls_compression_get_name( gnutls_compression_get( *m_session ) );
    if( info )
      m_certInfo.compression = info;

    info = gnutls_mac_get_name( gnutls_mac_get( *m_session ) );
    if( info )
      m_certInfo.mac = info;

    info = gnutls_cipher_get_name( gnutls_cipher_get( *m_session ) );
    if( info )
      m_certInfo.cipher = info;

    info = gnutls_protocol_get_name( gnutls_protocol_get_version( *m_session ) );
    if( info )
      m_certInfo.protocol = info;

    m_valid = true;
  }
Example #6
0
         void gtlsGeneric::logSessionInfo(LogWrapperType _logwrapper,
                                          gnutls_session_t _session)
         {
            const char *tmp;
            gnutls_credentials_type_t cred;
            gnutls_kx_algorithm_t kx;

            // print the key exchange's algorithm name
            kx = gnutls_kx_get(_session);
            tmp = gnutls_kx_get_name(kx);
            BTG_NOTICE(_logwrapper, "- Key Exchange: " << tmp);

            // Check the authentication type used and switch
            // to the appropriate.
            cred = gnutls_auth_get_type(_session);
            switch (cred)
               {
               case GNUTLS_CRD_SRP:
                  {
                     BTG_NOTICE(_logwrapper, "- SRP session");
                     break;
                  }

               case GNUTLS_CRD_ANON:
                  {
                     BTG_NOTICE(_logwrapper, "- Anonymous DH using prime of " << gnutls_dh_get_prime_bits (_session) << " bits");
                     break;
                  }
               case GNUTLS_CRD_CERTIFICATE:
                  {
                     // Check if we have been using ephemeral Diffie Hellman.

                     if (kx == GNUTLS_KX_DHE_RSA || kx == GNUTLS_KX_DHE_DSS)
                        {
                           BTG_NOTICE(_logwrapper, "- Ephemeral DH using prime of " << gnutls_dh_get_prime_bits(_session) << " bits");
                        }

                     /* if the certificate list is available, then
                      * print some information about it.
                      */
                     gtlsGeneric::logX509CertificateInfo(_logwrapper, _session);
                     break;
                  }
               default:
                  {
                     BTG_NOTICE(_logwrapper, "Unknown cred.");
                  }
               }

            /* print the protocol's name (ie TLS 1.0)
             */
            tmp = gnutls_protocol_get_name(gnutls_protocol_get_version(_session));
            BTG_NOTICE(_logwrapper, "- Protocol: " << tmp);

            /* print the certificate type of the peer.
             * ie X.509
             */
            tmp = gnutls_certificate_type_get_name(gnutls_certificate_type_get(_session));

            BTG_NOTICE(_logwrapper, "- Certificate Type: " << tmp);

            /* print the compression algorithm (if any)
             */
            tmp = gnutls_compression_get_name(gnutls_compression_get(_session));
            BTG_NOTICE(_logwrapper, "- Compression: " << tmp);

            /* print the name of the cipher used.
             * ie 3DES.
             */
            tmp = gnutls_cipher_get_name(gnutls_cipher_get(_session));
            BTG_NOTICE(_logwrapper, "- Cipher: " << tmp);

            /* Print the MAC algorithms name.
             * ie SHA1
             */
            tmp = gnutls_mac_get_name(gnutls_mac_get(_session));
            BTG_NOTICE(_logwrapper, "- MAC: " << tmp);
         }
Example #7
0
static CURLcode
gtls_connect_step3(struct connectdata *conn,
                   int sockindex)
{
  unsigned int cert_list_size;
  const gnutls_datum *chainp;
  unsigned int verify_status;
  gnutls_x509_crt x509_cert,x509_issuer;
  gnutls_datum issuerp;
  char certbuf[256]; /* big enough? */
  size_t size;
  unsigned int algo;
  unsigned int bits;
  time_t certclock;
  const char *ptr;
  struct SessionHandle *data = conn->data;
  gnutls_session session = conn->ssl[sockindex].session;
  int rc;
  int incache;
  void *ssl_sessionid;
  CURLcode result = CURLE_OK;

  /* This function will return the peer's raw certificate (chain) as sent by
     the peer. These certificates are in raw format (DER encoded for
     X.509). In case of a X.509 then a certificate list may be present. The
     first certificate in the list is the peer's certificate, following the
     issuer's certificate, then the issuer's issuer etc. */

  chainp = gnutls_certificate_get_peers(session, &cert_list_size);
  if(!chainp) {
    if(data->set.ssl.verifypeer ||
       data->set.ssl.verifyhost ||
       data->set.ssl.issuercert) {
#ifdef USE_TLS_SRP
      if(data->set.ssl.authtype == CURL_TLSAUTH_SRP
         && data->set.ssl.username != NULL
         && !data->set.ssl.verifypeer
         && gnutls_cipher_get(session)) {
        /* no peer cert, but auth is ok if we have SRP user and cipher and no
           peer verify */
      }
      else {
#endif
        failf(data, "failed to get server cert");
        return CURLE_PEER_FAILED_VERIFICATION;
#ifdef USE_TLS_SRP
      }
#endif
    }
    infof(data, "\t common name: WARNING couldn't obtain\n");
  }

  if(data->set.ssl.verifypeer) {
    /* This function will try to verify the peer's certificate and return its
       status (trusted, invalid etc.). The value of status should be one or
       more of the gnutls_certificate_status_t enumerated elements bitwise
       or'd. To avoid denial of service attacks some default upper limits
       regarding the certificate key size and chain size are set. To override
       them use gnutls_certificate_set_verify_limits(). */

    rc = gnutls_certificate_verify_peers2(session, &verify_status);
    if(rc < 0) {
      failf(data, "server cert verify failed: %d", rc);
      return CURLE_SSL_CONNECT_ERROR;
    }

    /* verify_status is a bitmask of gnutls_certificate_status bits */
    if(verify_status & GNUTLS_CERT_INVALID) {
      if(data->set.ssl.verifypeer) {
        failf(data, "server certificate verification failed. CAfile: %s "
              "CRLfile: %s", data->set.ssl.CAfile?data->set.ssl.CAfile:"none",
              data->set.ssl.CRLfile?data->set.ssl.CRLfile:"none");
        return CURLE_SSL_CACERT;
      }
      else
        infof(data, "\t server certificate verification FAILED\n");
    }
    else
      infof(data, "\t server certificate verification OK\n");
  }
  else {
    infof(data, "\t server certificate verification SKIPPED\n");
    goto after_server_cert_verification;
  }

  /* initialize an X.509 certificate structure. */
  gnutls_x509_crt_init(&x509_cert);

  /* convert the given DER or PEM encoded Certificate to the native
     gnutls_x509_crt_t format */
  gnutls_x509_crt_import(x509_cert, chainp, GNUTLS_X509_FMT_DER);

  if(data->set.ssl.issuercert) {
    gnutls_x509_crt_init(&x509_issuer);
    issuerp = load_file(data->set.ssl.issuercert);
    gnutls_x509_crt_import(x509_issuer, &issuerp, GNUTLS_X509_FMT_PEM);
    rc = gnutls_x509_crt_check_issuer(x509_cert,x509_issuer);
    unload_file(issuerp);
    if(rc <= 0) {
      failf(data, "server certificate issuer check failed (IssuerCert: %s)",
            data->set.ssl.issuercert?data->set.ssl.issuercert:"none");
      return CURLE_SSL_ISSUER_ERROR;
    }
    infof(data,"\t server certificate issuer check OK (Issuer Cert: %s)\n",
          data->set.ssl.issuercert?data->set.ssl.issuercert:"none");
  }

  size=sizeof(certbuf);
  rc = gnutls_x509_crt_get_dn_by_oid(x509_cert, GNUTLS_OID_X520_COMMON_NAME,
                                     0, /* the first and only one */
                                     FALSE,
                                     certbuf,
                                     &size);
  if(rc) {
    infof(data, "error fetching CN from cert:%s\n",
          gnutls_strerror(rc));
  }

  /* This function will check if the given certificate's subject matches the
     given hostname. This is a basic implementation of the matching described
     in RFC2818 (HTTPS), which takes into account wildcards, and the subject
     alternative name PKIX extension. Returns non zero on success, and zero on
     failure. */
  rc = gnutls_x509_crt_check_hostname(x509_cert, conn->host.name);

  if(!rc) {
    if(data->set.ssl.verifyhost) {
      failf(data, "SSL: certificate subject name (%s) does not match "
            "target host name '%s'", certbuf, conn->host.dispname);
      gnutls_x509_crt_deinit(x509_cert);
      return CURLE_PEER_FAILED_VERIFICATION;
    }
    else
      infof(data, "\t common name: %s (does not match '%s')\n",
            certbuf, conn->host.dispname);
  }
  else
    infof(data, "\t common name: %s (matched)\n", certbuf);

  /* Check for time-based validity */
  certclock = gnutls_x509_crt_get_expiration_time(x509_cert);

  if(certclock == (time_t)-1) {
    failf(data, "server cert expiration date verify failed");
    return CURLE_SSL_CONNECT_ERROR;
  }

  if(certclock < time(NULL)) {
    if(data->set.ssl.verifypeer) {
      failf(data, "server certificate expiration date has passed.");
      return CURLE_PEER_FAILED_VERIFICATION;
    }
    else
      infof(data, "\t server certificate expiration date FAILED\n");
  }
  else
    infof(data, "\t server certificate expiration date OK\n");

  certclock = gnutls_x509_crt_get_activation_time(x509_cert);

  if(certclock == (time_t)-1) {
    failf(data, "server cert activation date verify failed");
    return CURLE_SSL_CONNECT_ERROR;
  }

  if(certclock > time(NULL)) {
    if(data->set.ssl.verifypeer) {
      failf(data, "server certificate not activated yet.");
      return CURLE_PEER_FAILED_VERIFICATION;
    }
    else
      infof(data, "\t server certificate activation date FAILED\n");
  }
  else
    infof(data, "\t server certificate activation date OK\n");

  /* Show:

  - ciphers used
  - subject
  - start date
  - expire date
  - common name
  - issuer

  */

  /* public key algorithm's parameters */
  algo = gnutls_x509_crt_get_pk_algorithm(x509_cert, &bits);
  infof(data, "\t certificate public key: %s\n",
        gnutls_pk_algorithm_get_name(algo));

  /* version of the X.509 certificate. */
  infof(data, "\t certificate version: #%d\n",
        gnutls_x509_crt_get_version(x509_cert));


  size = sizeof(certbuf);
  gnutls_x509_crt_get_dn(x509_cert, certbuf, &size);
  infof(data, "\t subject: %s\n", certbuf);

  certclock = gnutls_x509_crt_get_activation_time(x509_cert);
  showtime(data, "start date", certclock);

  certclock = gnutls_x509_crt_get_expiration_time(x509_cert);
  showtime(data, "expire date", certclock);

  size = sizeof(certbuf);
  gnutls_x509_crt_get_issuer_dn(x509_cert, certbuf, &size);
  infof(data, "\t issuer: %s\n", certbuf);

  gnutls_x509_crt_deinit(x509_cert);

after_server_cert_verification:

  /* compression algorithm (if any) */
  ptr = gnutls_compression_get_name(gnutls_compression_get(session));
  /* the *_get_name() says "NULL" if GNUTLS_COMP_NULL is returned */
  infof(data, "\t compression: %s\n", ptr);

  /* the name of the cipher used. ie 3DES. */
  ptr = gnutls_cipher_get_name(gnutls_cipher_get(session));
  infof(data, "\t cipher: %s\n", ptr);

  /* the MAC algorithms name. ie SHA1 */
  ptr = gnutls_mac_get_name(gnutls_mac_get(session));
  infof(data, "\t MAC: %s\n", ptr);

  conn->ssl[sockindex].state = ssl_connection_complete;
  conn->recv[sockindex] = gtls_recv;
  conn->send[sockindex] = gtls_send;

  {
    /* we always unconditionally get the session id here, as even if we
       already got it from the cache and asked to use it in the connection, it
       might've been rejected and then a new one is in use now and we need to
       detect that. */
    void *connect_sessionid;
    size_t connect_idsize;

    /* get the session ID data size */
    gnutls_session_get_data(session, NULL, &connect_idsize);
    connect_sessionid = malloc(connect_idsize); /* get a buffer for it */

    if(connect_sessionid) {
      /* extract session ID to the allocated buffer */
      gnutls_session_get_data(session, connect_sessionid, &connect_idsize);

      incache = !(Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL));
      if(incache) {
        /* there was one before in the cache, so instead of risking that the
           previous one was rejected, we just kill that and store the new */
        Curl_ssl_delsessionid(conn, ssl_sessionid);
      }

      /* store this session id */
      result = Curl_ssl_addsessionid(conn, connect_sessionid, connect_idsize);
      if(result) {
        free(connect_sessionid);
        result = CURLE_OUT_OF_MEMORY;
      }
    }
    else
      result = CURLE_OUT_OF_MEMORY;
  }

  return result;
}
Example #8
0
static void main_texinfo (void)
{
  {
    size_t i;
    const char *name;
    char id[2];
    gnutls_kx_algorithm_t kx;
    gnutls_cipher_algorithm_t cipher;
    gnutls_mac_algorithm_t mac;
    gnutls_protocol_t version;

    printf ("@heading Ciphersuites\n");
    printf ("@multitable @columnfractions .60 .20 .20\n");
    printf("@headitem Ciphersuite name @tab TLS ID @tab Since\n");
    for (i = 0; (name = gnutls_cipher_suite_info
                 (i, id, &kx, &cipher, &mac, &version)); i++)
      {
        printf ("@item %s\n@tab 0x%02X 0x%02X\n@tab %s\n",
                escape_texi_string(name, buffer, sizeof(buffer)),
                (unsigned char) id[0], (unsigned char) id[1],
                gnutls_protocol_get_name (version));
      }
    printf ("@end multitable\n");

  }

  {
    const gnutls_certificate_type_t *p = gnutls_certificate_type_list ();

    printf ("\n\n@heading Certificate types\n");
    printf ("@table @code\n");
    for (; *p; p++)
      {
        printf ("@item %s\n", gnutls_certificate_type_get_name (*p));
      }
    printf ("@end table\n");
  }

  {
    const gnutls_protocol_t *p = gnutls_protocol_list ();

    printf ("\n@heading Protocols\n@table @code\n");
    for (; *p; p++)
      {
        printf ("@item %s\n", gnutls_protocol_get_name (*p));
      }
    printf ("@end table\n");
  }

  {
    const gnutls_cipher_algorithm_t *p = gnutls_cipher_list ();

    printf ("\n@heading Ciphers\n@table @code\n");
    for (; *p; p++)
      {
        printf ("@item %s\n", gnutls_cipher_get_name (*p));
      }
    printf ("@end table\n");
  }

  {
    const gnutls_mac_algorithm_t *p = gnutls_mac_list ();

    printf ("\n@heading MAC algorithms\n@table @code\n");
    for (; *p; p++)
      {
        printf ("@item %s\n", gnutls_mac_get_name (*p));
      }
    printf ("@end table\n");
  }

  {
    const gnutls_kx_algorithm_t *p = gnutls_kx_list ();

    printf ("\n@heading Key exchange methods\n@table @code\n");
    for (; *p; p++)
      {
        printf ("@item %s\n", gnutls_kx_get_name (*p));
      }
    printf ("@end table\n");
  }

  {
    const gnutls_pk_algorithm_t *p = gnutls_pk_list ();

    printf ("\n@heading Public key algorithms\n@table @code\n");
    for (; *p; p++)
      {
        printf ("@item %s\n", gnutls_pk_get_name (*p));
      }
    printf ("@end table\n");
  }

  {
    const gnutls_sign_algorithm_t *p = gnutls_sign_list ();

    printf ("\n@heading Public key signature algorithms\n@table @code\n");
    for (; *p; p++)
      {
        printf ("@item %s\n", gnutls_sign_get_name (*p));
      }
    printf ("@end table\n");
  }

  {
    const gnutls_ecc_curve_t *p = gnutls_ecc_curve_list ();

    printf ("\n@heading Elliptic curves\n@table @code\n");
    for (; *p; p++)
      {
        printf ("@item %s\n", gnutls_ecc_curve_get_name (*p));
      }
    printf ("@end table\n");
  }


  {
    const gnutls_compression_method_t *p = gnutls_compression_list ();

    printf ("\n@heading Compression methods\n@table @code\n");
    for (; *p; p++)
      {
        printf ("@item %s\n", gnutls_compression_get_name (*p));
      }
    printf ("@end table\n");
  }
}
Example #9
0
gboolean
_lm_ssl_begin (LmSSL *ssl, gint fd, const gchar *server, GError **error)
{
    int ret;
    LmSSLBase *base;
    gboolean auth_ok = TRUE;

    base = LM_SSL_BASE(ssl);
    gnutls_init (&ssl->gnutls_session, GNUTLS_CLIENT);
    if (base->cipher_list) {
        gnutls_priority_set_direct (ssl->gnutls_session, base->cipher_list, NULL);
    } else {
        gnutls_priority_set_direct (ssl->gnutls_session, "NORMAL", NULL);
    }
    if (base->ca_path) {
        _lm_ssl_set_ca(ssl, base->ca_path);
    } else {
        gnutls_certificate_set_x509_system_trust(ssl->gnutls_xcred);
    }
    gnutls_credentials_set (ssl->gnutls_session,
                            GNUTLS_CRD_CERTIFICATE,
                            ssl->gnutls_xcred);

    gnutls_transport_set_ptr (ssl->gnutls_session,
                              (gnutls_transport_ptr_t)(glong) fd);

    ret = gnutls_handshake (ssl->gnutls_session);

    if (ret >= 0) {
        auth_ok = ssl_verify_certificate (ssl, server);
    }

    if (ret < 0 || !auth_ok) {
        char *errmsg;

        if (!auth_ok) {
            errmsg = "authentication error";
        } else {
            errmsg = "handshake failed";
        }

        g_set_error (error,
                     LM_ERROR, LM_ERROR_CONNECTION_OPEN,
                     "*** GNUTLS %s: %s",
                     errmsg, gnutls_strerror (ret));

        return FALSE;
    }

    lm_verbose ("GNUTLS negotiated cipher suite: %s",
                gnutls_cipher_suite_get_name(gnutls_kx_get(ssl->gnutls_session),
                                             gnutls_cipher_get(ssl->gnutls_session),
                                             gnutls_mac_get(ssl->gnutls_session)));
    lm_verbose ("GNUTLS negotiated compression: %s",
                gnutls_compression_get_name (gnutls_compression_get
                                             (ssl->gnutls_session)));

    ssl->started = TRUE;

    return TRUE;
}
Example #10
0
int
connect_ssl(char *host, char *port,
	    int reconnect,
	    int use_sessionid, int use_ticket,
      int delay,
      const char *client_cert,
      const char *client_key) {
  struct addrinfo* addr;
  int err, s;
  char buffer[256];
  gnutls_anon_client_credentials_t anoncred;
  gnutls_certificate_credentials_t xcred;
  gnutls_session_t                 session;
  char                            *session_data = NULL;
  size_t                           session_data_size = 0;
  char                            *session_id = NULL;
  size_t                           session_id_size = 0;
  char                            *session_id_hex = NULL;
  char                            *session_id_p = NULL;
  unsigned                         session_id_idx;
  const char                      *hex = "0123456789ABCDEF";

  start("Initialize GNU TLS library");
  if ((err = gnutls_global_init()))
    fail("Unable to initialize GNU TLS:\n%s",
	 gnutls_strerror(err));
  if ((err = gnutls_anon_allocate_client_credentials(&anoncred)))
    fail("Unable to allocate anonymous client credentials:\n%s",
	 gnutls_strerror(err));
  if ((err = gnutls_certificate_allocate_credentials(&xcred)))
    fail("Unable to allocate X509 credentials:\n%s",
	 gnutls_strerror(err));

#ifdef DEBUG
  gnutls_global_set_log_function(debug);
  gnutls_global_set_log_level(10);
#endif

  addr = solve(host, port);
  do {
    start("Initialize TLS session");
    if ((err = gnutls_init(&session, GNUTLS_CLIENT)))
      fail("Unable to initialize the current session:\n%s",
	   gnutls_strerror(err));
    if ((err = gnutls_priority_set_direct(session, "PERFORMANCE:NORMAL:EXPORT", NULL)))
      fail("Unable to initialize cipher suites:\n%s",
	   gnutls_strerror(err));
    gnutls_dh_set_prime_bits(session, 512);
    if (client_cert == NULL) {
      if ((err = gnutls_credentials_set(session, GNUTLS_CRD_ANON, anoncred)))
        fail("Unable to set anonymous credentials for session:\n%s",
	     gnutls_strerror(err));
    } else {
      if ((err = gnutls_certificate_set_x509_key_file(xcred, client_cert, client_key, GNUTLS_X509_FMT_PEM))) {
        fail("failed to load x509 certificate from file %s or key from %s: %s",client_cert,client_key,gnutls_strerror(err));
      }
    }
    if ((err = gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE, xcred)))
      fail("Unable to set credentials for session:\n%s",
	   gnutls_strerror(err));
    
    if (use_ticket) {
      start("Enable use of session tickets (RFC 5077)");
      if (gnutls_session_ticket_enable_client(session))
	fail("Unable to enable session tickets:\n%s",
	     gnutls_strerror(err));
    }

    if (session_data) {
      start("Copy old session");
      if ((err = gnutls_session_set_data(session, session_data, session_data_size)))
	fail("Unable to set session to previous one:\n%s",
	     gnutls_strerror(err));
    }

    s = connect_socket(addr, host, port);
    start("Start TLS renegotiation");
    gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t)(uintptr_t)s);
    if ((err = gnutls_handshake(session))) {
      fail("Unable to start TLS renegotiation:\n%s",
	   gnutls_strerror(err));
    }

    start("Check if session was reused");
    if (!gnutls_session_is_resumed(session) && session_data)
      warn("No session was reused.");
    else if (gnutls_session_is_resumed(session) && !session_data)
      warn("Session was reused.");
    else if (gnutls_session_is_resumed(session))
      end("SSL session correctly reused");
    else
      end("SSL session was not used");

    start("Get current session");
    if (session_data) {
      free(session_data); session_data = NULL;
    }
    session_data_size = 8192;
    if ((err = gnutls_session_get_data(session, NULL, &session_data_size)))
      warn("No session available:\n%s",
          gnutls_strerror(err));
    else {
      session_data = malloc(session_data_size);
      if (!session_data) fail("No memory available");
      gnutls_session_get_data(session, session_data, &session_data_size);

      if ((err = gnutls_session_get_id( session, NULL, &session_id_size)))
         warn("No session id available:\n%s",
             gnutls_strerror(err));
      session_id = malloc(session_id_size);
      if (!session_id) fail("No memory available");
      else {
        if ((err = gnutls_session_get_id( session, session_id, &session_id_size)))
          warn("No session id available:\n%s",
            gnutls_strerror(err));
        session_id_hex = malloc(session_id_size * 2 + 1);
        if (!session_id_hex) fail("No memory available");
        else {
          for (session_id_p = session_id_hex, session_id_idx = 0;
               session_id_idx < session_id_size;
               ++session_id_idx) {
            *session_id_p++ = hex[ (session_id[session_id_idx] >> 4) & 0xf];
            *session_id_p++ = hex[ session_id[session_id_idx] & 0xf];
          }
          *session_id_p = '\0';

          end("Session context:\nProtocol : %s\nCipher : %s\nKx : %s\nCompression : %s\nPSK : %s\nID : %s",
            gnutls_protocol_get_name( gnutls_protocol_get_version(session) ),
            gnutls_cipher_get_name( gnutls_cipher_get(session) ),
            gnutls_kx_get_name( gnutls_kx_get(session) ),
            gnutls_compression_get_name( gnutls_compression_get(session)),
            gnutls_psk_server_get_username(session),
            session_id_hex
            );
          free(session_id_hex);
        }
        free(session_id);
      }
        
    }
    if (!use_sessionid && !use_ticket) {
      free(session_data); session_data = NULL;
    }

    start("Send HTTP GET");
    err = snprintf(buffer, sizeof(buffer),
		   "GET / HTTP/1.0\r\n"
		   "Host: %s\r\n"
		   "\r\n", host);
    if (err == -1 || err >= sizeof(buffer))
      fail("Unable to build request to send");
    if (gnutls_record_send(session, buffer, strlen(buffer)) < 0)
      fail("SSL write request failed:\n%s",
	   gnutls_strerror(err));

    start("Get HTTP answer");
    if ((err = gnutls_record_recv(session, buffer, sizeof(buffer) - 1)) <= 0)
      fail("SSL read request failed:\n%s",
	   gnutls_strerror(err));
    buffer[err] = '\0';
    if (strchr(buffer, '\r'))
      *strchr(buffer, '\r') = '\0';
    end("%s", buffer);

    start("End TLS connection");
    gnutls_bye(session, GNUTLS_SHUT_RDWR);
    close(s);
    gnutls_deinit (session);
    --reconnect;
    if (reconnect < 0) break;
    else {
      start("waiting %d seconds",delay);
      sleep(delay);
    }
  } while (1);

  if (session_data) free(session_data);
  gnutls_anon_free_client_credentials(anoncred);
  gnutls_global_deinit();
  return 0;
}
Example #11
0
int
print_info (gnutls_session_t session, int print_cert)
{
    const char *tmp;
    gnutls_credentials_type_t cred;
    gnutls_kx_algorithm_t kx;
    unsigned char session_id[33];
    size_t session_id_size = sizeof (session_id);

    /* print session ID */
    gnutls_session_get_id (session, session_id, &session_id_size);
    printf ("- Session ID: %s\n",
            raw_to_string (session_id, session_id_size));

    /* print the key exchange's algorithm name
     */
    kx = gnutls_kx_get (session);

    cred = gnutls_auth_get_type (session);
    switch (cred)
      {
#ifdef ENABLE_ANON
      case GNUTLS_CRD_ANON:
          if (kx == GNUTLS_KX_ANON_ECDH)
              print_ecdh_info (session, "Anonymous ");
          else
              print_dh_info (session, "Anonymous ", verbose);
          break;
#endif
#ifdef ENABLE_SRP
      case GNUTLS_CRD_SRP:
          /* This should be only called in server
           * side.
           */
          if (gnutls_srp_server_get_username (session) != NULL)
              printf ("- SRP authentication. Connected as '%s'\n",
                      gnutls_srp_server_get_username (session));
          break;
#endif
#ifdef ENABLE_PSK
      case GNUTLS_CRD_PSK:
          /* This returns NULL in server side.
           */
          if (gnutls_psk_client_get_hint (session) != NULL)
              printf ("- PSK authentication. PSK hint '%s'\n",
                      gnutls_psk_client_get_hint (session));
          /* This returns NULL in client side.
           */
          if (gnutls_psk_server_get_username (session) != NULL)
              printf ("- PSK authentication. Connected as '%s'\n",
                      gnutls_psk_server_get_username (session));
          if (kx == GNUTLS_KX_DHE_PSK)
              print_dh_info (session, "Ephemeral ", verbose);
          if (kx == GNUTLS_KX_ECDHE_PSK)
              print_ecdh_info (session, "Ephemeral ");
          break;
#endif
      case GNUTLS_CRD_IA:
          printf ("- TLS/IA authentication\n");
          break;
      case GNUTLS_CRD_CERTIFICATE:
          {
              char dns[256];
              size_t dns_size = sizeof (dns);
              unsigned int type;

              /* This fails in client side */
              if (gnutls_server_name_get
                  (session, dns, &dns_size, &type, 0) == 0)
                {
                    printf ("- Given server name[%d]: %s\n", type, dns);
                }
          }

          print_cert_info (session, 
                           verbose?GNUTLS_CRT_PRINT_FULL:GNUTLS_CRT_PRINT_COMPACT, 
                           print_cert);

          if (kx == GNUTLS_KX_DHE_RSA || kx == GNUTLS_KX_DHE_DSS)
              print_dh_info (session, "Ephemeral ", verbose);
          else if (kx == GNUTLS_KX_ECDHE_RSA
                   || kx == GNUTLS_KX_ECDHE_ECDSA)
              print_ecdh_info (session, "Ephemeral ");
      }

    tmp =
        SU (gnutls_protocol_get_name
            (gnutls_protocol_get_version (session)));
    printf ("- Version: %s\n", tmp);

    tmp = SU (gnutls_kx_get_name (kx));
    printf ("- Key Exchange: %s\n", tmp);

    tmp = SU (gnutls_cipher_get_name (gnutls_cipher_get (session)));
    printf ("- Cipher: %s\n", tmp);

    tmp = SU (gnutls_mac_get_name (gnutls_mac_get (session)));
    printf ("- MAC: %s\n", tmp);

    tmp =
        SU (gnutls_compression_get_name
            (gnutls_compression_get (session)));
    printf ("- Compression: %s\n", tmp);

    if (verbose)
      {
          gnutls_datum_t cb;
          int rc;

          rc = gnutls_session_channel_binding (session,
                                               GNUTLS_CB_TLS_UNIQUE, &cb);
          if (rc)
              fprintf (stderr, "Channel binding error: %s\n",
                       gnutls_strerror (rc));
          else
            {
                size_t i;

                printf ("- Channel binding 'tls-unique': ");
                for (i = 0; i < cb.size; i++)
                    printf ("%02x", cb.data[i]);
                printf ("\n");
            }
      }

    /* Warning: Do not print anything more here. The 'Compression:'
       output MUST be the last non-verbose output.  This is used by
       Emacs starttls.el code. */

    fflush (stdout);

    return 0;
}
Example #12
0
/* This function will print some details of the
 * given session.
 */
int
print_info (gnutls_session_t session)
{
  const char *tmp;
  gnutls_credentials_type_t cred;
  gnutls_kx_algorithm_t kx;

  /* print the key exchange's algorithm name
   */
  kx = gnutls_kx_get (session);
  tmp = gnutls_kx_get_name (kx);
  printf ("- Key Exchange: %s\n", tmp);

  /* Check the authentication type used and switch
   * to the appropriate.
   */
  cred = gnutls_auth_get_type (session);
  switch (cred)
    {
    case GNUTLS_CRD_IA:
      printf ("- TLS/IA session\n");
      break;


#ifdef ENABLE_SRP
    case GNUTLS_CRD_SRP:
      printf ("- SRP session with username %s\n",
	      gnutls_srp_server_get_username (session));
      break;
#endif

    case GNUTLS_CRD_PSK:
      /* This returns NULL in server side.
       */
      if (gnutls_psk_client_get_hint (session) != NULL)
	printf ("- PSK authentication. PSK hint '%s'\n",
		gnutls_psk_client_get_hint (session));
      /* This returns NULL in client side.
       */
      if (gnutls_psk_server_get_username (session) != NULL)
	printf ("- PSK authentication. Connected as '%s'\n",
		gnutls_psk_server_get_username (session));
      break;

    case GNUTLS_CRD_ANON:	/* anonymous authentication */

      printf ("- Anonymous DH using prime of %d bits\n",
	      gnutls_dh_get_prime_bits (session));
      break;

    case GNUTLS_CRD_CERTIFICATE:	/* certificate authentication */

      /* Check if we have been using ephemeral Diffie-Hellman.
       */
      if (kx == GNUTLS_KX_DHE_RSA || kx == GNUTLS_KX_DHE_DSS)
	{
	  printf ("\n- Ephemeral DH using prime of %d bits\n",
		  gnutls_dh_get_prime_bits (session));
	}

      /* if the certificate list is available, then
       * print some information about it.
       */
      print_x509_certificate_info (session);

    }				/* switch */

  /* print the protocol's name (ie TLS 1.0) 
   */
  tmp = gnutls_protocol_get_name (gnutls_protocol_get_version (session));
  printf ("- Protocol: %s\n", tmp);

  /* print the certificate type of the peer.
   * ie X.509
   */
  tmp =
    gnutls_certificate_type_get_name (gnutls_certificate_type_get (session));

  printf ("- Certificate Type: %s\n", tmp);

  /* print the compression algorithm (if any)
   */
  tmp = gnutls_compression_get_name (gnutls_compression_get (session));
  printf ("- Compression: %s\n", tmp);

  /* print the name of the cipher used.
   * ie 3DES.
   */
  tmp = gnutls_cipher_get_name (gnutls_cipher_get (session));
  printf ("- Cipher: %s\n", tmp);

  /* Print the MAC algorithms name.
   * ie SHA1
   */
  tmp = gnutls_mac_get_name (gnutls_mac_get (session));
  printf ("- MAC: %s\n", tmp);

  return 0;
}
/**
 * @brief Get info pertaining to a socket.
 * @naslfn{get_sock_info}
 *
 * This function is used to retrieve various information about an
 * active socket.  It requires the NASL socket number and a string to
 * select the information to retrieve.
 *
 * Supported keywords are:
 *
 * - @a dport Return the destination port.  This is an integer.  NOTE:
 *   Not yet implemented.
 *
 * - @a sport Return the source port.  This is an integer.  NOTE: Not
 *   yet implemented.
 *
 * - @a encaps Return the encapsulation of the socket.  Example
 *   output: "TLScustom".
 *
 * - @a tls-proto Return a string with the actual TLS protocol in use.
 *   n/a" is returned if no SSL/TLS session is active.  Example
 *   output: "TLSv1".
 *
 * - @a tls-kx Return a string describing the key exchange algorithm.
 *   Example output: "RSA".
 *
 * - @a tls-certtype Return the type of the certificate in use by the
 *   session.  Example output: "X.509"
 *
 * - @a tls-cipher Return the cipher algorithm in use by the session;
 *   Example output: "AES-256-CBC".
 *
 * - @a tls-mac Return the message authentication algorithms used by
 *   the session.  Example output: "SHA1".
 *
 * - @a tls-comp Return the compression algorithms in use by the
 *   session.  Example output: "DEFLATE".
 *
 * - @a tls-auth Return the peer's authentication type.  Example
 *   output: "CERT".
 *
 * - @a tls-cert Return the peer's certificates for an SSL or TLS
 *   connection.  This is an array of binary strings or NULL if no
 *   certificate is known.
 *
 * @nasluparam
 *
 * - A NASL socket
 *
 * - A string keyword; see above.
 *
 * @naslnparam
 *
 * - @a asstring If true return a human readable string instead of
 *   an integer.  Used only with these keywords: encaps.
 *
 * @naslret An integer or a string or NULL on error.
 *
 * @param[in] lexic  Lexical context of the NASL interpreter.
 *
 * @return A tree cell.
 */
tree_cell *
nasl_get_sock_info (lex_ctxt * lexic)
{
  int sock;
  int type;
  int err;
  const char *keyword, *s;
  tree_cell *retc;
  int as_string;
  int transport;
  gnutls_session_t tls_session;
  char *strval;
  int intval;

  sock = get_int_var_by_num (lexic, 0, -1);
  if (sock <= 0)
    {
      nasl_perror (lexic, "error: socket %d is not valid\n");
      return NULL;
    }

  keyword = get_str_var_by_num (lexic, 1);
  if (!keyword || !((type = get_var_type_by_num (lexic, 1)) == VAR2_STRING
                    || type == VAR2_DATA))
    {
      nasl_perror (lexic, "error: second argument is not of type string\n");
      return NULL;
    }

  as_string = !!get_int_local_var_by_name (lexic, "asstring", 0);

  transport = 0;
  strval = NULL;
  intval = 0;
  retc = FAKE_CELL; /* Dummy value to detect retc == NULL.  */

  {
    void *tmp = NULL;
    err = get_sock_infos (sock, &transport, &tmp);
    tls_session = tmp;
  }
  if (err)
    {
      nasl_perror (lexic, "error retrieving infos for socket %d: %s\n",
                   sock, strerror (err));
      retc = NULL;
    }
  else if (!strcmp (keyword, "encaps"))
    {
      if (as_string)
        strval = estrdup (get_encaps_name (transport));
      else
        intval = transport;
    }
  else if (!strcmp (keyword, "tls-proto"))
    {
      if (!tls_session)
        s = "n/a";
      else
        s = gnutls_protocol_get_name
          (gnutls_protocol_get_version (tls_session));
      strval = estrdup (s?s:"[?]");
    }
  else if (!strcmp (keyword, "tls-kx"))
    {
      if (!tls_session)
        s = "n/a";
      else
        s = gnutls_kx_get_name (gnutls_kx_get (tls_session));
      strval = estrdup (s?s:"");
    }
  else if (!strcmp (keyword, "tls-certtype"))
    {
      if (!tls_session)
        s = "n/a";
      else
        s = gnutls_certificate_type_get_name
          (gnutls_certificate_type_get (tls_session));
      strval = estrdup (s?s:"");
    }
  else if (!strcmp (keyword, "tls-cipher"))
    {
      if (!tls_session)
        s = "n/a";
      else
        s = gnutls_cipher_get_name (gnutls_cipher_get (tls_session));
      strval = estrdup (s?s:"");
    }
  else if (!strcmp (keyword, "tls-mac"))
    {
      if (!tls_session)
        s = "n/a";
      else
        s = gnutls_mac_get_name (gnutls_mac_get (tls_session));
      strval = estrdup (s?s:"");
    }
  else if (!strcmp (keyword, "tls-comp"))
    {
      if (!tls_session)
        s = "n/a";
      else
        s = gnutls_compression_get_name
          (gnutls_compression_get (tls_session));
      strval = estrdup (s?s:"");
    }
  else if (!strcmp (keyword, "tls-auth"))
    {
      if (!tls_session)
        s = "n/a";
      else
        {
          switch (gnutls_auth_get_type (tls_session))
            {
            case GNUTLS_CRD_ANON:        s = "ANON"; break;
            case GNUTLS_CRD_CERTIFICATE: s = "CERT"; break;
            case GNUTLS_CRD_PSK:         s = "PSK";  break;
            case GNUTLS_CRD_SRP:         s = "SRP";  break;
            default:                     s = "[?]";  break;
            }
        }
      strval = estrdup (s?s:"");
    }
  else if (!strcmp (keyword, "tls-cert"))
    {
      /* We only support X.509 for now.  GNUTLS also allows for
         OpenPGP, but we are not prepared for that.  */
      if (!tls_session
          || gnutls_certificate_type_get (tls_session) != GNUTLS_CRT_X509)
        s = "n/a";
      else
        {
          const gnutls_datum_t *list;
          unsigned int nlist = 0;
          int i;
          nasl_array *a;
          anon_nasl_var v;

          list = gnutls_certificate_get_peers (tls_session, &nlist);
          if (!list)
            retc = NULL;  /* No certificate or other error.  */
          else
            {
              retc = alloc_tree_cell (0, NULL);
              retc->type = DYN_ARRAY;
              retc->x.ref_val = a = emalloc (sizeof *a);

              for (i=0; i < nlist; i++)
                {
                  memset (&v, 0, sizeof v);
                  v.var_type = VAR2_DATA;
                  v.v.v_str.s_val = list[i].data;
                  v.v.v_str.s_siz = list[i].size;
                  add_var_to_list (a, i, &v);
                }
            }
        }
    }
  else
    {
      nasl_perror (lexic, "unknown keyword '%s'\n", keyword);
      retc = NULL;
    }

  if (!retc)
    ;
  else if (retc != FAKE_CELL)
    ; /* Already allocated.  */
  else if (strval)
    {
      retc = alloc_typed_cell (CONST_STR);
      retc->x.str_val = strval;
      retc->size = strlen (strval);
    }
  else
    {
      retc = alloc_typed_cell (CONST_INT);
      retc->x.i_val = intval;
    }

  return retc;
}
Example #14
0
int
main (void)
{
  {
    size_t i;
    const char *name;
    char id[2];
    gnutls_kx_algorithm_t kx;
    gnutls_cipher_algorithm_t cipher;
    gnutls_mac_algorithm_t mac;
    gnutls_protocol_t version;

    printf ("Available cipher suites:\n");
    printf ("@multitable @columnfractions .60 .20 .20\n");
    for (i = 0; (name = gnutls_cipher_suite_info
		 (i, id, &kx, &cipher, &mac, &version)); i++)
      {
	printf ("@item %s\n@tab 0x%02x 0x%02x\n@tab %s\n",
		name,
		(unsigned char) id[0], (unsigned char) id[1],
		gnutls_protocol_get_name (version));
      }
    printf ("@end multitable\n");
  }

  {
    const gnutls_certificate_type_t *p = gnutls_certificate_type_list ();

    printf ("\n\nAvailable certificate types:\n@itemize\n");
    for (; *p; p++)
      {
	printf ("@item %s\n", gnutls_certificate_type_get_name (*p));
      }
    printf ("@end itemize\n");
  }

  {
    const gnutls_protocol_t *p = gnutls_protocol_list ();

    printf ("\nAvailable protocols:\n@itemize\n");
    for (; *p; p++)
      {
	printf ("@item %s\n", gnutls_protocol_get_name (*p));
      }
    printf ("@end itemize\n");
  }

  {
    const gnutls_cipher_algorithm_t *p = gnutls_cipher_list ();

    printf ("\nAvailable ciphers:\n@itemize\n");
    for (; *p; p++)
      {
	printf ("@item %s\n", gnutls_cipher_get_name (*p));
      }
    printf ("@end itemize\n");
  }

  {
    const gnutls_mac_algorithm_t *p = gnutls_mac_list ();

    printf ("\nAvailable MAC algorithms:\n@itemize\n");
    for (; *p; p++)
      {
	printf ("@item %s\n", gnutls_mac_get_name (*p));
      }
    printf ("@end itemize\n");
  }

  {
    const gnutls_kx_algorithm_t *p = gnutls_kx_list ();

    printf ("\nAvailable key exchange methods:\n@itemize\n");
    for (; *p; p++)
      {
	printf ("@item %s\n", gnutls_kx_get_name (*p));
      }
    printf ("@end itemize\n");
  }

  {
    const gnutls_pk_algorithm_t *p = gnutls_pk_list ();

    printf ("\nAvailable public key algorithms:\n@itemize\n");
    for (; *p; p++)
      {
	printf ("@item %s\n", gnutls_pk_get_name (*p));
      }
    printf ("@end itemize\n");
  }

  {
    const gnutls_sign_algorithm_t *p = gnutls_sign_list ();

    printf ("\nAvailable public key signature algorithms:\n@itemize\n");
    for (; *p; p++)
      {
	printf ("@item %s\n", gnutls_sign_get_name (*p));
      }
    printf ("@end itemize\n");
  }

  {
    const gnutls_compression_method_t *p = gnutls_compression_list ();

    printf ("\nAvailable compression methods:\n@itemize\n");
    for (; *p; p++)
      {
	printf ("@item %s\n", gnutls_compression_get_name (*p));
      }
    printf ("@end itemize\n");
  }
}
Example #15
0
File: common.c Project: sqs/gnutls
void
print_list (int verbose)
{
  {
    size_t i;
    const char *name;
    char id[2];
    gnutls_kx_algorithm_t kx;
    gnutls_cipher_algorithm_t cipher;
    gnutls_mac_algorithm_t mac;
    gnutls_protocol_t version;

    printf ("Cipher suites:\n");
    for (i = 0; (name = gnutls_cipher_suite_info
                 (i, id, &kx, &cipher, &mac, &version)); i++)
      {
        printf ("%-50s\t0x%02x, 0x%02x\t%s\n",
                name,
                (unsigned char) id[0], (unsigned char) id[1],
                gnutls_protocol_get_name (version));
        if (verbose)
          printf ("\tKey exchange: %s\n\tCipher: %s\n\tMAC: %s\n\n",
                  gnutls_kx_get_name (kx),
                  gnutls_cipher_get_name (cipher), gnutls_mac_get_name (mac));
      }
  }

  {
    const gnutls_certificate_type_t *p = gnutls_certificate_type_list ();

    printf ("Certificate types: ");
    for (; *p; p++)
      {
        printf ("%s", gnutls_certificate_type_get_name (*p));
        if (*(p + 1))
          printf (", ");
        else
          printf ("\n");
      }
  }

  {
    const gnutls_protocol_t *p = gnutls_protocol_list ();

    printf ("Protocols: ");
    for (; *p; p++)
      {
        printf ("%s", gnutls_protocol_get_name (*p));
        if (*(p + 1))
          printf (", ");
        else
          printf ("\n");
      }
  }

  {
    const gnutls_cipher_algorithm_t *p = gnutls_cipher_list ();

    printf ("Ciphers: ");
    for (; *p; p++)
      {
        printf ("%s", gnutls_cipher_get_name (*p));
        if (*(p + 1))
          printf (", ");
        else
          printf ("\n");
      }
  }

  {
    const gnutls_mac_algorithm_t *p = gnutls_mac_list ();

    printf ("MACs: ");
    for (; *p; p++)
      {
        printf ("%s", gnutls_mac_get_name (*p));
        if (*(p + 1))
          printf (", ");
        else
          printf ("\n");
      }
  }

  {
    const gnutls_kx_algorithm_t *p = gnutls_kx_list ();

    printf ("Key exchange algorithms: ");
    for (; *p; p++)
      {
        printf ("%s", gnutls_kx_get_name (*p));
        if (*(p + 1))
          printf (", ");
        else
          printf ("\n");
      }
  }

  {
    const gnutls_compression_method_t *p = gnutls_compression_list ();

    printf ("Compression: ");
    for (; *p; p++)
      {
        printf ("%s", gnutls_compression_get_name (*p));
        if (*(p + 1))
          printf (", ");
        else
          printf ("\n");
      }
  }

  {
    const gnutls_pk_algorithm_t *p = gnutls_pk_list ();

    printf ("Public Key Systems: ");
    for (; *p; p++)
      {
        printf ("%s", gnutls_pk_algorithm_get_name (*p));
        if (*(p + 1))
          printf (", ");
        else
          printf ("\n");
      }
  }

  {
    const gnutls_sign_algorithm_t *p = gnutls_sign_list ();

    printf ("PK-signatures: ");
    for (; *p; p++)
      {
        printf ("%s", gnutls_sign_algorithm_get_name (*p));
        if (*(p + 1))
          printf (", ");
        else
          printf ("\n");
      }
  }
}
Example #16
0
/*
 * This function is called after the TCP connect has completed. Setup the TLS
 * layer and do all necessary magic.
 */
CURLcode
Curl_gtls_connect(struct connectdata *conn,
                  int sockindex)

{
    const int cert_type_priority[] = { GNUTLS_CRT_X509, 0 };
    struct SessionHandle *data = conn->data;
    gnutls_session session;
    int rc;
    unsigned int cert_list_size;
    const gnutls_datum *chainp;
    unsigned int verify_status;
    gnutls_x509_crt x509_cert;
    char certbuf[256]; /* big enough? */
    size_t size;
    unsigned int algo;
    unsigned int bits;
    time_t clock;
    const char *ptr;
    void *ssl_sessionid;
    size_t ssl_idsize;

    /* GnuTLS only supports TLSv1 (and SSLv3?) */
    if(data->set.ssl.version == CURL_SSLVERSION_SSLv2) {
        failf(data, "GnuTLS does not support SSLv2");
        return CURLE_SSL_CONNECT_ERROR;
    }

    /* allocate a cred struct */
    rc = gnutls_certificate_allocate_credentials(&conn->ssl[sockindex].cred);
    if(rc < 0) {
        failf(data, "gnutls_cert_all_cred() failed: %s", gnutls_strerror(rc));
        return CURLE_SSL_CONNECT_ERROR;
    }

    if(data->set.ssl.CAfile) {
        /* set the trusted CA cert bundle file */
        gnutls_certificate_set_verify_flags(conn->ssl[sockindex].cred,
                                            GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT);

        rc = gnutls_certificate_set_x509_trust_file(conn->ssl[sockindex].cred,
                data->set.ssl.CAfile,
                GNUTLS_X509_FMT_PEM);
        if(rc < 0) {
            infof(data, "error reading ca cert file %s (%s)\n",
                  data->set.ssl.CAfile, gnutls_strerror(rc));
            if (data->set.ssl.verifypeer)
                return CURLE_SSL_CACERT_BADFILE;
        }
        else
            infof(data, "found %d certificates in %s\n",
                  rc, data->set.ssl.CAfile);
    }

    /* Initialize TLS session as a client */
    rc = gnutls_init(&conn->ssl[sockindex].session, GNUTLS_CLIENT);
    if(rc) {
        failf(data, "gnutls_init() failed: %d", rc);
        return CURLE_SSL_CONNECT_ERROR;
    }

    /* convenient assign */
    session = conn->ssl[sockindex].session;

    /* Use default priorities */
    rc = gnutls_set_default_priority(session);
    if(rc < 0)
        return CURLE_SSL_CONNECT_ERROR;

    /* Sets the priority on the certificate types supported by gnutls. Priority
       is higher for types specified before others. After specifying the types
       you want, you must append a 0. */
    rc = gnutls_certificate_type_set_priority(session, cert_type_priority);
    if(rc < 0)
        return CURLE_SSL_CONNECT_ERROR;

    if(data->set.cert) {
        if( gnutls_certificate_set_x509_key_file(
                    conn->ssl[sockindex].cred, data->set.cert,
                    data->set.key != 0 ? data->set.key : data->set.cert,
                    do_file_type(data->set.cert_type) ) ) {
            failf(data, "error reading X.509 key or certificate file");
            return CURLE_SSL_CONNECT_ERROR;
        }
    }

    /* put the credentials to the current session */
    rc = gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE,
                                conn->ssl[sockindex].cred);

    /* set the connection handle (file descriptor for the socket) */
    gnutls_transport_set_ptr(session,
                             (gnutls_transport_ptr)conn->sock[sockindex]);

    /* register callback functions to send and receive data. */
    gnutls_transport_set_push_function(session, Curl_gtls_push);
    gnutls_transport_set_pull_function(session, Curl_gtls_pull);

    /* lowat must be set to zero when using custom push and pull functions. */
    gnutls_transport_set_lowat(session, 0);

    /* This might be a reconnect, so we check for a session ID in the cache
       to speed up things */

    if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, &ssl_idsize)) {
        /* we got a session id, use it! */
        gnutls_session_set_data(session, ssl_sessionid, ssl_idsize);

        /* Informational message */
        infof (data, "SSL re-using session ID\n");
    }

    rc = handshake(conn, session, sockindex, TRUE);
    if(rc)
        /* handshake() sets its own error message with failf() */
        return rc;

    /* This function will return the peer's raw certificate (chain) as sent by
       the peer. These certificates are in raw format (DER encoded for
       X.509). In case of a X.509 then a certificate list may be present. The
       first certificate in the list is the peer's certificate, following the
       issuer's certificate, then the issuer's issuer etc. */

    chainp = gnutls_certificate_get_peers(session, &cert_list_size);
    if(!chainp) {
        if(data->set.ssl.verifyhost) {
            failf(data, "failed to get server cert");
            return CURLE_SSL_PEER_CERTIFICATE;
        }
        infof(data, "\t common name: WARNING couldn't obtain\n");
    }

    /* This function will try to verify the peer's certificate and return its
       status (trusted, invalid etc.). The value of status should be one or more
       of the gnutls_certificate_status_t enumerated elements bitwise or'd. To
       avoid denial of service attacks some default upper limits regarding the
       certificate key size and chain size are set. To override them use
       gnutls_certificate_set_verify_limits(). */

    rc = gnutls_certificate_verify_peers2(session, &verify_status);
    if (rc < 0) {
        failf(data, "server cert verify failed: %d", rc);
        return CURLE_SSL_CONNECT_ERROR;
    }

    /* verify_status is a bitmask of gnutls_certificate_status bits */
    if(verify_status & GNUTLS_CERT_INVALID) {
        if (data->set.ssl.verifypeer) {
            failf(data, "server certificate verification failed. CAfile: %s",
                  data->set.ssl.CAfile?data->set.ssl.CAfile:"none");
            return CURLE_SSL_CACERT;
        }
        else
            infof(data, "\t server certificate verification FAILED\n");
    }
    else
        infof(data, "\t server certificate verification OK\n");

    /* initialize an X.509 certificate structure. */
    gnutls_x509_crt_init(&x509_cert);

    /* convert the given DER or PEM encoded Certificate to the native
       gnutls_x509_crt_t format */
    gnutls_x509_crt_import(x509_cert, chainp, GNUTLS_X509_FMT_DER);

    size=sizeof(certbuf);
    rc = gnutls_x509_crt_get_dn_by_oid(x509_cert, GNUTLS_OID_X520_COMMON_NAME,
                                       0, /* the first and only one */
                                       FALSE,
                                       certbuf,
                                       &size);
    if(rc) {
        infof(data, "error fetching CN from cert:%s\n",
              gnutls_strerror(rc));
    }

    /* This function will check if the given certificate's subject matches the
       given hostname. This is a basic implementation of the matching described
       in RFC2818 (HTTPS), which takes into account wildcards, and the subject
       alternative name PKIX extension. Returns non zero on success, and zero on
       failure. */
    rc = gnutls_x509_crt_check_hostname(x509_cert, conn->host.name);

    if(!rc) {
        if (data->set.ssl.verifyhost > 1) {
            failf(data, "SSL: certificate subject name (%s) does not match "
                  "target host name '%s'", certbuf, conn->host.dispname);
            gnutls_x509_crt_deinit(x509_cert);
            return CURLE_SSL_PEER_CERTIFICATE;
        }
        else
            infof(data, "\t common name: %s (does not match '%s')\n",
                  certbuf, conn->host.dispname);
    }
    else
        infof(data, "\t common name: %s (matched)\n", certbuf);

    /* Show:

    - ciphers used
    - subject
    - start date
    - expire date
    - common name
    - issuer

    */

    /* public key algorithm's parameters */
    algo = gnutls_x509_crt_get_pk_algorithm(x509_cert, &bits);
    infof(data, "\t certificate public key: %s\n",
          gnutls_pk_algorithm_get_name(algo));

    /* version of the X.509 certificate. */
    infof(data, "\t certificate version: #%d\n",
          gnutls_x509_crt_get_version(x509_cert));


    size = sizeof(certbuf);
    gnutls_x509_crt_get_dn(x509_cert, certbuf, &size);
    infof(data, "\t subject: %s\n", certbuf);

    clock = gnutls_x509_crt_get_activation_time(x509_cert);
    showtime(data, "start date", clock);

    clock = gnutls_x509_crt_get_expiration_time(x509_cert);
    showtime(data, "expire date", clock);

    size = sizeof(certbuf);
    gnutls_x509_crt_get_issuer_dn(x509_cert, certbuf, &size);
    infof(data, "\t issuer: %s\n", certbuf);

    gnutls_x509_crt_deinit(x509_cert);

    /* compression algorithm (if any) */
    ptr = gnutls_compression_get_name(gnutls_compression_get(session));
    /* the *_get_name() says "NULL" if GNUTLS_COMP_NULL is returned */
    infof(data, "\t compression: %s\n", ptr);

    /* the name of the cipher used. ie 3DES. */
    ptr = gnutls_cipher_get_name(gnutls_cipher_get(session));
    infof(data, "\t cipher: %s\n", ptr);

    /* the MAC algorithms name. ie SHA1 */
    ptr = gnutls_mac_get_name(gnutls_mac_get(session));
    infof(data, "\t MAC: %s\n", ptr);

    if(!ssl_sessionid) {
        /* this session was not previously in the cache, add it now */

        /* get the session ID data size */
        gnutls_session_get_data(session, NULL, &ssl_idsize);
        ssl_sessionid = malloc(ssl_idsize); /* get a buffer for it */

        if(ssl_sessionid) {
            /* extract session ID to the allocated buffer */
            gnutls_session_get_data(session, ssl_sessionid, &ssl_idsize);

            /* store this session id */
            return Curl_ssl_addsessionid(conn, ssl_sessionid, ssl_idsize);
        }
    }

    return CURLE_OK;
}
Example #17
0
static CURLcode
gtls_connect_step3(struct connectdata *conn,
                   int sockindex)
{
  unsigned int cert_list_size;
  const gnutls_datum_t *chainp;
  unsigned int verify_status = 0;
  gnutls_x509_crt_t x509_cert, x509_issuer;
  gnutls_datum_t issuerp;
  char certbuf[256] = ""; /* big enough? */
  size_t size;
  unsigned int algo;
  unsigned int bits;
  time_t certclock;
  const char *ptr;
  struct SessionHandle *data = conn->data;
  gnutls_session_t session = conn->ssl[sockindex].session;
  int rc;
  bool incache;
  void *ssl_sessionid;
#ifdef HAS_ALPN
  gnutls_datum_t proto;
#endif
  CURLcode result = CURLE_OK;

  gnutls_protocol_t version = gnutls_protocol_get_version(session);

  /* the name of the cipher suite used, e.g. ECDHE_RSA_AES_256_GCM_SHA384. */
  ptr = gnutls_cipher_suite_get_name(gnutls_kx_get(session),
                                     gnutls_cipher_get(session),
                                     gnutls_mac_get(session));

  infof(data, "SSL connection using %s / %s\n",
        gnutls_protocol_get_name(version), ptr);

  /* This function will return the peer's raw certificate (chain) as sent by
     the peer. These certificates are in raw format (DER encoded for
     X.509). In case of a X.509 then a certificate list may be present. The
     first certificate in the list is the peer's certificate, following the
     issuer's certificate, then the issuer's issuer etc. */

  chainp = gnutls_certificate_get_peers(session, &cert_list_size);
  if(!chainp) {
    if(data->set.ssl.verifypeer ||
       data->set.ssl.verifyhost ||
       data->set.ssl.issuercert) {
#ifdef USE_TLS_SRP
      if(data->set.ssl.authtype == CURL_TLSAUTH_SRP
         && data->set.ssl.username != NULL
         && !data->set.ssl.verifypeer
         && gnutls_cipher_get(session)) {
        /* no peer cert, but auth is ok if we have SRP user and cipher and no
           peer verify */
      }
      else {
#endif
        failf(data, "failed to get server cert");
        return CURLE_PEER_FAILED_VERIFICATION;
#ifdef USE_TLS_SRP
      }
#endif
    }
    infof(data, "\t common name: WARNING couldn't obtain\n");
  }

  if(data->set.ssl.certinfo && chainp) {
    unsigned int i;

    result = Curl_ssl_init_certinfo(data, cert_list_size);
    if(result)
      return result;

    for(i = 0; i < cert_list_size; i++) {
      const char *beg = (const char *) chainp[i].data;
      const char *end = beg + chainp[i].size;

      result = Curl_extract_certinfo(conn, i, beg, end);
      if(result)
        return result;
    }
  }

  if(data->set.ssl.verifypeer) {
    /* This function will try to verify the peer's certificate and return its
       status (trusted, invalid etc.). The value of status should be one or
       more of the gnutls_certificate_status_t enumerated elements bitwise
       or'd. To avoid denial of service attacks some default upper limits
       regarding the certificate key size and chain size are set. To override
       them use gnutls_certificate_set_verify_limits(). */

    rc = gnutls_certificate_verify_peers2(session, &verify_status);
    if(rc < 0) {
      failf(data, "server cert verify failed: %d", rc);
      return CURLE_SSL_CONNECT_ERROR;
    }

    /* verify_status is a bitmask of gnutls_certificate_status bits */
    if(verify_status & GNUTLS_CERT_INVALID) {
      if(data->set.ssl.verifypeer) {
        failf(data, "server certificate verification failed. CAfile: %s "
              "CRLfile: %s", data->set.ssl.CAfile?data->set.ssl.CAfile:"none",
              data->set.ssl.CRLfile?data->set.ssl.CRLfile:"none");
        return CURLE_SSL_CACERT;
      }
      else
        infof(data, "\t server certificate verification FAILED\n");
    }
    else
      infof(data, "\t server certificate verification OK\n");
  }
  else
    infof(data, "\t server certificate verification SKIPPED\n");

#ifdef HAS_OCSP
  if(data->set.ssl.verifystatus) {
    if(gnutls_ocsp_status_request_is_checked(session, 0) == 0) {
      gnutls_datum_t status_request;
      gnutls_ocsp_resp_t ocsp_resp;

      gnutls_ocsp_cert_status_t status;
      gnutls_x509_crl_reason_t reason;

      rc = gnutls_ocsp_status_request_get(session, &status_request);

      infof(data, "\t server certificate status verification FAILED\n");

      if(rc == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {
        failf(data, "No OCSP response received");
        return CURLE_SSL_INVALIDCERTSTATUS;
      }

      if(rc < 0) {
        failf(data, "Invalid OCSP response received");
        return CURLE_SSL_INVALIDCERTSTATUS;
      }

      gnutls_ocsp_resp_init(&ocsp_resp);

      rc = gnutls_ocsp_resp_import(ocsp_resp, &status_request);
      if(rc < 0) {
        failf(data, "Invalid OCSP response received");
        return CURLE_SSL_INVALIDCERTSTATUS;
      }

      rc = gnutls_ocsp_resp_get_single(ocsp_resp, 0, NULL, NULL, NULL, NULL,
                                       &status, NULL, NULL, NULL, &reason);

      switch(status) {
      case GNUTLS_OCSP_CERT_GOOD:
        break;

      case GNUTLS_OCSP_CERT_REVOKED: {
        const char *crl_reason;

        switch(reason) {
          default:
          case GNUTLS_X509_CRLREASON_UNSPECIFIED:
            crl_reason = "unspecified reason";
            break;

          case GNUTLS_X509_CRLREASON_KEYCOMPROMISE:
            crl_reason = "private key compromised";
            break;

          case GNUTLS_X509_CRLREASON_CACOMPROMISE:
            crl_reason = "CA compromised";
            break;

          case GNUTLS_X509_CRLREASON_AFFILIATIONCHANGED:
            crl_reason = "affiliation has changed";
            break;

          case GNUTLS_X509_CRLREASON_SUPERSEDED:
            crl_reason = "certificate superseded";
            break;

          case GNUTLS_X509_CRLREASON_CESSATIONOFOPERATION:
            crl_reason = "operation has ceased";
            break;

          case GNUTLS_X509_CRLREASON_CERTIFICATEHOLD:
            crl_reason = "certificate is on hold";
            break;

          case GNUTLS_X509_CRLREASON_REMOVEFROMCRL:
            crl_reason = "will be removed from delta CRL";
            break;

          case GNUTLS_X509_CRLREASON_PRIVILEGEWITHDRAWN:
            crl_reason = "privilege withdrawn";
            break;

          case GNUTLS_X509_CRLREASON_AACOMPROMISE:
            crl_reason = "AA compromised";
            break;
        }

        failf(data, "Server certificate was revoked: %s", crl_reason);
        break;
      }

      default:
      case GNUTLS_OCSP_CERT_UNKNOWN:
        failf(data, "Server certificate status is unknown");
        break;
      }

      gnutls_ocsp_resp_deinit(ocsp_resp);

      return CURLE_SSL_INVALIDCERTSTATUS;
    }
    else
      infof(data, "\t server certificate status verification OK\n");
  }
  else
    infof(data, "\t server certificate status verification SKIPPED\n");
#endif

  /* initialize an X.509 certificate structure. */
  gnutls_x509_crt_init(&x509_cert);

  if(chainp)
    /* convert the given DER or PEM encoded Certificate to the native
       gnutls_x509_crt_t format */
    gnutls_x509_crt_import(x509_cert, chainp, GNUTLS_X509_FMT_DER);

  if(data->set.ssl.issuercert) {
    gnutls_x509_crt_init(&x509_issuer);
    issuerp = load_file(data->set.ssl.issuercert);
    gnutls_x509_crt_import(x509_issuer, &issuerp, GNUTLS_X509_FMT_PEM);
    rc = gnutls_x509_crt_check_issuer(x509_cert, x509_issuer);
    gnutls_x509_crt_deinit(x509_issuer);
    unload_file(issuerp);
    if(rc <= 0) {
      failf(data, "server certificate issuer check failed (IssuerCert: %s)",
            data->set.ssl.issuercert?data->set.ssl.issuercert:"none");
      gnutls_x509_crt_deinit(x509_cert);
      return CURLE_SSL_ISSUER_ERROR;
    }
    infof(data, "\t server certificate issuer check OK (Issuer Cert: %s)\n",
          data->set.ssl.issuercert?data->set.ssl.issuercert:"none");
  }

  size=sizeof(certbuf);
  rc = gnutls_x509_crt_get_dn_by_oid(x509_cert, GNUTLS_OID_X520_COMMON_NAME,
                                     0, /* the first and only one */
                                     FALSE,
                                     certbuf,
                                     &size);
  if(rc) {
    infof(data, "error fetching CN from cert:%s\n",
          gnutls_strerror(rc));
  }

  /* This function will check if the given certificate's subject matches the
     given hostname. This is a basic implementation of the matching described
     in RFC2818 (HTTPS), which takes into account wildcards, and the subject
     alternative name PKIX extension. Returns non zero on success, and zero on
     failure. */
  rc = gnutls_x509_crt_check_hostname(x509_cert, conn->host.name);
#if GNUTLS_VERSION_NUMBER < 0x030306
  /* Before 3.3.6, gnutls_x509_crt_check_hostname() didn't check IP
     addresses. */
  if(!rc) {
#ifdef ENABLE_IPV6
    #define use_addr in6_addr
#else
    #define use_addr in_addr
#endif
    unsigned char addrbuf[sizeof(struct use_addr)];
    unsigned char certaddr[sizeof(struct use_addr)];
    size_t addrlen = 0, certaddrlen;
    int i;
    int ret = 0;

    if(Curl_inet_pton(AF_INET, conn->host.name, addrbuf) > 0)
      addrlen = 4;
#ifdef ENABLE_IPV6
    else if(Curl_inet_pton(AF_INET6, conn->host.name, addrbuf) > 0)
      addrlen = 16;
#endif

    if(addrlen) {
      for(i=0; ; i++) {
        certaddrlen = sizeof(certaddr);
        ret = gnutls_x509_crt_get_subject_alt_name(x509_cert, i, certaddr,
                                                   &certaddrlen, NULL);
        /* If this happens, it wasn't an IP address. */
        if(ret == GNUTLS_E_SHORT_MEMORY_BUFFER)
          continue;
        if(ret < 0)
          break;
        if(ret != GNUTLS_SAN_IPADDRESS)
          continue;
        if(certaddrlen == addrlen && !memcmp(addrbuf, certaddr, addrlen)) {
          rc = 1;
          break;
        }
      }
    }
  }
#endif
  if(!rc) {
    if(data->set.ssl.verifyhost) {
      failf(data, "SSL: certificate subject name (%s) does not match "
            "target host name '%s'", certbuf, conn->host.dispname);
      gnutls_x509_crt_deinit(x509_cert);
      return CURLE_PEER_FAILED_VERIFICATION;
    }
    else
      infof(data, "\t common name: %s (does not match '%s')\n",
            certbuf, conn->host.dispname);
  }
  else
    infof(data, "\t common name: %s (matched)\n", certbuf);

  /* Check for time-based validity */
  certclock = gnutls_x509_crt_get_expiration_time(x509_cert);

  if(certclock == (time_t)-1) {
    if(data->set.ssl.verifypeer) {
      failf(data, "server cert expiration date verify failed");
      gnutls_x509_crt_deinit(x509_cert);
      return CURLE_SSL_CONNECT_ERROR;
    }
    else
      infof(data, "\t server certificate expiration date verify FAILED\n");
  }
  else {
    if(certclock < time(NULL)) {
      if(data->set.ssl.verifypeer) {
        failf(data, "server certificate expiration date has passed.");
        gnutls_x509_crt_deinit(x509_cert);
        return CURLE_PEER_FAILED_VERIFICATION;
      }
      else
        infof(data, "\t server certificate expiration date FAILED\n");
    }
    else
      infof(data, "\t server certificate expiration date OK\n");
  }

  certclock = gnutls_x509_crt_get_activation_time(x509_cert);

  if(certclock == (time_t)-1) {
    if(data->set.ssl.verifypeer) {
      failf(data, "server cert activation date verify failed");
      gnutls_x509_crt_deinit(x509_cert);
      return CURLE_SSL_CONNECT_ERROR;
    }
    else
      infof(data, "\t server certificate activation date verify FAILED\n");
  }
  else {
    if(certclock > time(NULL)) {
      if(data->set.ssl.verifypeer) {
        failf(data, "server certificate not activated yet.");
        gnutls_x509_crt_deinit(x509_cert);
        return CURLE_PEER_FAILED_VERIFICATION;
      }
      else
        infof(data, "\t server certificate activation date FAILED\n");
    }
    else
      infof(data, "\t server certificate activation date OK\n");
  }

  ptr = data->set.str[STRING_SSL_PINNEDPUBLICKEY];
  if(ptr) {
    result = pkp_pin_peer_pubkey(data, x509_cert, ptr);
    if(result != CURLE_OK) {
      failf(data, "SSL: public key does not match pinned public key!");
      gnutls_x509_crt_deinit(x509_cert);
      return result;
    }
  }

  /* Show:

  - subject
  - start date
  - expire date
  - common name
  - issuer

  */

  /* public key algorithm's parameters */
  algo = gnutls_x509_crt_get_pk_algorithm(x509_cert, &bits);
  infof(data, "\t certificate public key: %s\n",
        gnutls_pk_algorithm_get_name(algo));

  /* version of the X.509 certificate. */
  infof(data, "\t certificate version: #%d\n",
        gnutls_x509_crt_get_version(x509_cert));


  size = sizeof(certbuf);
  gnutls_x509_crt_get_dn(x509_cert, certbuf, &size);
  infof(data, "\t subject: %s\n", certbuf);

  certclock = gnutls_x509_crt_get_activation_time(x509_cert);
  showtime(data, "start date", certclock);

  certclock = gnutls_x509_crt_get_expiration_time(x509_cert);
  showtime(data, "expire date", certclock);

  size = sizeof(certbuf);
  gnutls_x509_crt_get_issuer_dn(x509_cert, certbuf, &size);
  infof(data, "\t issuer: %s\n", certbuf);

  gnutls_x509_crt_deinit(x509_cert);

  /* compression algorithm (if any) */
  ptr = gnutls_compression_get_name(gnutls_compression_get(session));
  /* the *_get_name() says "NULL" if GNUTLS_COMP_NULL is returned */
  infof(data, "\t compression: %s\n", ptr);

#ifdef HAS_ALPN
  if(data->set.ssl_enable_alpn) {
    rc = gnutls_alpn_get_selected_protocol(session, &proto);
    if(rc == 0) {
      infof(data, "ALPN, server accepted to use %.*s\n", proto.size,
          proto.data);

#ifdef USE_NGHTTP2
      if(proto.size == NGHTTP2_PROTO_VERSION_ID_LEN &&
         !memcmp(NGHTTP2_PROTO_VERSION_ID, proto.data,
                 NGHTTP2_PROTO_VERSION_ID_LEN)) {
        conn->negnpn = CURL_HTTP_VERSION_2;
      }
      else
#endif
      if(proto.size == ALPN_HTTP_1_1_LENGTH &&
         !memcmp(ALPN_HTTP_1_1, proto.data, ALPN_HTTP_1_1_LENGTH)) {
        conn->negnpn = CURL_HTTP_VERSION_1_1;
      }
    }
    else
      infof(data, "ALPN, server did not agree to a protocol\n");
  }
#endif

  conn->ssl[sockindex].state = ssl_connection_complete;
  conn->recv[sockindex] = gtls_recv;
  conn->send[sockindex] = gtls_send;

  {
    /* we always unconditionally get the session id here, as even if we
       already got it from the cache and asked to use it in the connection, it
       might've been rejected and then a new one is in use now and we need to
       detect that. */
    void *connect_sessionid;
    size_t connect_idsize = 0;

    /* get the session ID data size */
    gnutls_session_get_data(session, NULL, &connect_idsize);
    connect_sessionid = malloc(connect_idsize); /* get a buffer for it */

    if(connect_sessionid) {
      /* extract session ID to the allocated buffer */
      gnutls_session_get_data(session, connect_sessionid, &connect_idsize);

      incache = !(Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL));
      if(incache) {
        /* there was one before in the cache, so instead of risking that the
           previous one was rejected, we just kill that and store the new */
        Curl_ssl_delsessionid(conn, ssl_sessionid);
      }

      /* store this session id */
      result = Curl_ssl_addsessionid(conn, connect_sessionid, connect_idsize);
      if(result) {
        free(connect_sessionid);
        result = CURLE_OUT_OF_MEMORY;
      }
    }
    else
      result = CURLE_OUT_OF_MEMORY;
  }

  return result;
}
Example #18
0
void
print_list (const char *priorities, int verbose)
{
    size_t i;
    int ret;
    unsigned int idx;
    const char *name;
    const char *err;
    unsigned char id[2];
    gnutls_kx_algorithm_t kx;
    gnutls_cipher_algorithm_t cipher;
    gnutls_mac_algorithm_t mac;
    gnutls_protocol_t version;
    gnutls_priority_t pcache;
    const unsigned int *list;

    if (priorities != NULL)
      {
          printf ("Cipher suites for %s\n", priorities);

          ret = gnutls_priority_init (&pcache, priorities, &err);
          if (ret < 0)
            {
                fprintf (stderr, "Syntax error at: %s\n", err);
                exit (1);
            }

          for (i = 0;; i++)
            {
                ret =
                    gnutls_priority_get_cipher_suite_index (pcache, i,
                                                            &idx);
                if (ret == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
                    break;
                if (ret == GNUTLS_E_UNKNOWN_CIPHER_SUITE)
                    continue;

                name =
                    gnutls_cipher_suite_info (idx, id, NULL, NULL, NULL,
                                              &version);

                if (name != NULL)
                    printf ("%-50s\t0x%02x, 0x%02x\t%s\n",
                            name, (unsigned char) id[0],
                            (unsigned char) id[1],
                            gnutls_protocol_get_name (version));
            }

          printf("\n");
          {
              ret = gnutls_priority_certificate_type_list (pcache, &list);

              printf ("Certificate types: ");
              if (ret == 0) printf("none\n");
              for (i = 0; i < (unsigned)ret; i++)
                {
                    printf ("CTYPE-%s",
                            gnutls_certificate_type_get_name (list[i]));
                    if (i+1!=(unsigned)ret)
                        printf (", ");
                    else
                        printf ("\n");
                }
          }

          {
              ret = gnutls_priority_protocol_list (pcache, &list);

              printf ("Protocols: ");
              if (ret == 0) printf("none\n");
              for (i = 0; i < (unsigned)ret; i++)
                {
                    printf ("VERS-%s", gnutls_protocol_get_name (list[i]));
                    if (i+1!=(unsigned)ret)
                        printf (", ");
                    else
                        printf ("\n");
                }
          }

          {
              ret = gnutls_priority_compression_list (pcache, &list);

              printf ("Compression: ");
              if (ret == 0) printf("none\n");
              for (i = 0; i < (unsigned)ret; i++)
                {
                    printf ("COMP-%s",
                            gnutls_compression_get_name (list[i]));
                    if (i+1!=(unsigned)ret)
                        printf (", ");
                    else
                        printf ("\n");
                }
          }

          {
              ret = gnutls_priority_ecc_curve_list (pcache, &list);

              printf ("Elliptic curves: ");
              if (ret == 0) printf("none\n");
              for (i = 0; i < (unsigned)ret; i++)
                {
                    printf ("CURVE-%s",
                            gnutls_ecc_curve_get_name (list[i]));
                    if (i+1!=(unsigned)ret)
                        printf (", ");
                    else
                        printf ("\n");
                }
          }

          {
              ret = gnutls_priority_sign_list (pcache, &list);

              printf ("PK-signatures: ");
              if (ret == 0) printf("none\n");
              for (i = 0; i < (unsigned)ret; i++)
                {
                    printf ("SIGN-%s",
                            gnutls_sign_algorithm_get_name (list[i]));
                    if (i+1!=(unsigned)ret)
                        printf (", ");
                    else
                        printf ("\n");
                }
          }

          return;
      }

    printf ("Cipher suites:\n");
    for (i = 0; (name = gnutls_cipher_suite_info
                 (i, id, &kx, &cipher, &mac, &version)); i++)
      {
          printf ("%-50s\t0x%02x, 0x%02x\t%s\n",
                  name,
                  (unsigned char) id[0], (unsigned char) id[1],
                  gnutls_protocol_get_name (version));
          if (verbose)
              printf ("\tKey exchange: %s\n\tCipher: %s\n\tMAC: %s\n\n",
                      gnutls_kx_get_name (kx),
                      gnutls_cipher_get_name (cipher),
                      gnutls_mac_get_name (mac));
      }

    printf("\n");
    {
        const gnutls_certificate_type_t *p =
            gnutls_certificate_type_list ();

        printf ("Certificate types: ");
        for (; *p; p++)
          {
              printf ("CTYPE-%s", gnutls_certificate_type_get_name (*p));
              if (*(p + 1))
                  printf (", ");
              else
                  printf ("\n");
          }
    }

    {
        const gnutls_protocol_t *p = gnutls_protocol_list ();

        printf ("Protocols: ");
        for (; *p; p++)
          {
              printf ("VERS-%s", gnutls_protocol_get_name (*p));
              if (*(p + 1))
                  printf (", ");
              else
                  printf ("\n");
          }
    }

    {
        const gnutls_cipher_algorithm_t *p = gnutls_cipher_list ();

        printf ("Ciphers: ");
        for (; *p; p++)
          {
              printf ("%s", gnutls_cipher_get_name (*p));
              if (*(p + 1))
                  printf (", ");
              else
                  printf ("\n");
          }
    }

    {
        const gnutls_mac_algorithm_t *p = gnutls_mac_list ();

        printf ("MACs: ");
        for (; *p; p++)
          {
              printf ("%s", gnutls_mac_get_name (*p));
              if (*(p + 1))
                  printf (", ");
              else
                  printf ("\n");
          }
    }

    {
        const gnutls_kx_algorithm_t *p = gnutls_kx_list ();

        printf ("Key exchange algorithms: ");
        for (; *p; p++)
          {
              printf ("%s", gnutls_kx_get_name (*p));
              if (*(p + 1))
                  printf (", ");
              else
                  printf ("\n");
          }
    }

    {
        const gnutls_compression_method_t *p = gnutls_compression_list ();

        printf ("Compression: ");
        for (; *p; p++)
          {
              printf ("COMP-%s", gnutls_compression_get_name (*p));
              if (*(p + 1))
                  printf (", ");
              else
                  printf ("\n");
          }
    }

    {
        const gnutls_ecc_curve_t *p = gnutls_ecc_curve_list ();

        printf ("Elliptic curves: ");
        for (; *p; p++)
          {
              printf ("CURVE-%s", gnutls_ecc_curve_get_name (*p));
              if (*(p + 1))
                  printf (", ");
              else
                  printf ("\n");
          }
    }

    {
        const gnutls_pk_algorithm_t *p = gnutls_pk_list ();

        printf ("Public Key Systems: ");
        for (; *p; p++)
          {
              printf ("%s", gnutls_pk_algorithm_get_name (*p));
              if (*(p + 1))
                  printf (", ");
              else
                  printf ("\n");
          }
    }

    {
        const gnutls_sign_algorithm_t *p = gnutls_sign_list ();

        printf ("PK-signatures: ");
        for (; *p; p++)
          {
              printf ("SIGN-%s", gnutls_sign_algorithm_get_name (*p));
              if (*(p + 1))
                  printf (", ");
              else
                  printf ("\n");
          }
    }
}
Example #19
0
int
print_info (gnutls_session_t session, const char *hostname, int insecure)
{
  const char *tmp;
  gnutls_credentials_type_t cred;
  gnutls_kx_algorithm_t kx;


  /* print the key exchange's algorithm name
   */
  kx = gnutls_kx_get (session);

  cred = gnutls_auth_get_type (session);
  switch (cred)
    {
#ifdef ENABLE_ANON
    case GNUTLS_CRD_ANON:
      print_dh_info (session, "Anonymous ");
      break;
#endif
#ifdef ENABLE_SRP
    case GNUTLS_CRD_SRP:
      /* This should be only called in server
       * side.
       */
      if (gnutls_srp_server_get_username (session) != NULL)
	printf ("- SRP authentication. Connected as '%s'\n",
		gnutls_srp_server_get_username (session));
      break;
#endif
#ifdef ENABLE_PSK
    case GNUTLS_CRD_PSK:
      /* This returns NULL in server side.
       */
      if (gnutls_psk_client_get_hint (session) != NULL)
	printf ("- PSK authentication. PSK hint '%s'\n",
		gnutls_psk_client_get_hint (session));
      /* This returns NULL in client side.
       */
      if (gnutls_psk_server_get_username (session) != NULL)
	printf ("- PSK authentication. Connected as '%s'\n",
		gnutls_psk_server_get_username (session));
      if (kx == GNUTLS_KX_DHE_PSK)
	print_dh_info (session, "Ephemeral ");
      break;
#endif
    case GNUTLS_CRD_IA:
      printf ("- TLS/IA authentication\n");
      break;
    case GNUTLS_CRD_CERTIFICATE:
      {
	char dns[256];
	size_t dns_size = sizeof (dns);
	unsigned int type;

	/* This fails in client side */
	if (gnutls_server_name_get (session, dns, &dns_size, &type, 0) == 0)
	  {
	    printf ("- Given server name[%d]: %s\n", type, dns);
	  }
      }

      if (kx == GNUTLS_KX_DHE_RSA || kx == GNUTLS_KX_DHE_DSS)
	print_dh_info (session, "Ephemeral ");

      print_cert_info (session, hostname, insecure);

      print_cert_vrfy (session);

    }

  tmp = SU (gnutls_protocol_get_name (gnutls_protocol_get_version (session)));
  printf ("- Version: %s\n", tmp);

  tmp = SU (gnutls_kx_get_name (kx));
  printf ("- Key Exchange: %s\n", tmp);

  tmp = SU (gnutls_cipher_get_name (gnutls_cipher_get (session)));
  printf ("- Cipher: %s\n", tmp);

  tmp = SU (gnutls_mac_get_name (gnutls_mac_get (session)));
  printf ("- MAC: %s\n", tmp);

  tmp = SU (gnutls_compression_get_name (gnutls_compression_get (session)));
  printf ("- Compression: %s\n", tmp);

  if (verbose)
    {
      char id[32];
      size_t id_size = sizeof (id);
      gnutls_session_get_id (session, id, &id_size);
      printf ("- Session ID: %s\n", raw_to_string (id, id_size));
    }


  fflush (stdout);

  return 0;
}