### Start gnutls-serv with all parameters Source: https://www.gnutls.org/manual/html_node/gnutls_002dserv-Invocation.html Final example combining all earlier parameters: ECDSA and RSA certificates, SRP, PSK, and raw public keys. This is the complete command to run the server with all supported authentication methods. ```bash gnutls-serv --http --priority NORMAL:+PSK:+SRP:+CTYPE-CLI-RAWPK:+CTYPE-SRV-RAWPK \ --x509cafile x509-ca.pem \ --x509keyfile x509-server-key.pem \ --x509certfile x509-server.pem \ --x509keyfile x509-server-key-ecc.pem \ --x509certfile x509-server-ecc.pem \ --srppasswdconf srp-tpasswd.conf \ --srppasswd srp-passwd.txt \ --pskpasswd psk-passwd.txt \ --rawpkfile srv.rawpk.pem \ --rawpkkeyfile srv.key.pem ``` -------------------------------- ### Server setup with anti-replay protection and early data handling Source: https://www.gnutls.org/manual/html_node/Anti_002dreplay-protection.html This example shows the complete server setup for using early data with anti-replay protection. It defines a database add function and a handshake hook to retrieve early data. The main function initializes the anti-replay measure, sets the database back-end, enables early data, and attaches the anti-replay measure to the session. ```c #define MAX_EARLY_DATA_SIZE 16384 static int db_add_func(void *dbf, gnutls_datum_t key, gnutls_datum_t data) { /* Return GNUTLS_E_DB_ENTRY_EXISTS, if KEY is found in the database. * Otherwise, store it and return 0. */ } static int handshake_hook_func(gnutls_session_t session, unsigned int htype, unsigned when, unsigned int incoming, const gnutls_datum_t *msg) { int ret; char buf[MAX_EARLY_DATA_SIZE]; assert(htype == GNUTLS_HANDSHAKE_END_OF_EARLY_DATA); assert(when == GNUTLS_HOOK_POST); if (gnutls_session_get_flags(session) & GNUTLS_SFLAGS_EARLY_DATA) { ret = gnutls_record_recv_early_data(session, buf, sizeof(buf)); assert(ret >= 0); } return ret; } int main(void) { ... /* Initialize anti-replay measure, which can be shared * among multiple sessions. */ gnutls_anti_replay_init(&anti_replay); /* Set the database back-end function for the anti-replay data. */ gnutls_anti_replay_set_add_function(anti_replay, db_add_func); gnutls_anti_replay_set_ptr(anti_replay, NULL); ... gnutls_init(&server, GNUTLS_SERVER | GNUTLS_ENABLE_EARLY_DATA); gnutls_record_set_max_early_data_size(server, MAX_EARLY_DATA_SIZE); ... /* Set the anti-replay measure to the session. */ gnutls_anti_replay_enable(server, anti_replay); ... /* Retrieve early data in a handshake hook; * you can also do that after handshake. */ gnutls_handshake_set_hook_function(server, GNUTLS_HANDSHAKE_END_OF_EARLY_DATA, GNUTLS_HOOK_POST, handshake_hook_func); ... } ``` -------------------------------- ### Start gnutls-serv with PSK support Source: https://www.gnutls.org/manual/html_node/gnutls_002dserv-Invocation.html Starts the server with HTTP and PSK authentication. Requires a password file created with psktool. ```bash gnutls-serv --http --priority NORMAL:+ECDHE-PSK:+PSK \ --pskpasswd psk-passwd.txt ``` -------------------------------- ### Start gnutls-serv with raw public-key support Source: https://www.gnutls.org/manual/html_node/gnutls_002dserv-Invocation.html Starts the server with raw public-key certificates. Note that no identity information is linked to these keys, and raw public-key certificates must be explicitly enabled via priority strings. ```bash gnutls-serv --http --priority NORMAL:+CTYPE-CLI-RAWPK:+CTYPE-SRV-RAWPK \ --rawpkfile srv.rawpk.pem \ --rawpkkeyfile srv.key.pem ``` -------------------------------- ### Start gnutls-serv with SRP support Source: https://www.gnutls.org/manual/html_node/gnutls_002dserv-Invocation.html Starts the server with HTTP and SRP authentication enabled. Requires an SRP password file created with srptool. ```bash gnutls-serv --http --priority NORMAL:+SRP-RSA:+SRP \ --srppasswdconf srp-tpasswd.conf \ --srppasswd srp-passwd.txt ``` -------------------------------- ### Start gnutls-serv HTTP server with X.509 certificates Source: https://www.gnutls.org/manual/html_node/gnutls_002dserv-Invocation.html Starts the gnutls-serv HTTP server using the previously generated CA, server key, and server certificate. This enables X.509 authentication. ```bash $ gnutls-serv --http \ --x509cafile x509-ca.pem \ --x509keyfile x509-server-key.pem \ --x509certfile x509-server.pem ``` -------------------------------- ### Example implementation of supplemental data receive and send functions Source: https://www.gnutls.org/manual/html_node/TLS-Hello-Extension-Handling.html Example code showing how to send a "Hello World" string in the supplemental data handshake message. The receive function allocates memory, copies the data, and frees it; the send function appends the string to the buffer. ```c int _foobar_supp_recv_params(gnutls_session_t session, const opaque *data, size_t _data_size) { uint8_t len = _data_size; unsigned char *msg; msg = gnutls_malloc(len); if (msg == NULL) return GNUTLS_E_MEMORY_ERROR; memcpy(msg, data, len); msg[len]='\0'; /* do something with msg */ gnutls_free(msg); return len; } int _foobar_supp_send_params(gnutls_session_t session, gnutls_buffer_t buf) { unsigned char *msg = "hello world"; int len = strlen(msg); if (gnutls_buffer_append_data(buf, msg, len) < 0) abort(); return len; } ``` -------------------------------- ### SRP TLS client example in C Source: https://www.gnutls.org/manual/html_node/Client-example-with-SRP-authentication.html This example connects to a server using SRP authentication with a username and password. It also loads a CA file to verify the server's certificate if presented. Requires GnuTLS 3.1.4 or later and defines helper functions (check_alert, tcp_connect, tcp_close) elsewhere. ```C /* This example code is placed in the public domain. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include /* Those functions are defined in other examples. */ extern void check_alert(gnutls_session_t session, int ret); extern int tcp_connect(void); extern void tcp_close(int sd); #define MAX_BUF 1024 #define USERNAME "user" #define PASSWORD "pass" #define CAFILE "/etc/ssl/certs/ca-certificates.crt" #define MSG "GET / HTTP/1.0\r\n\r\n" int main(void) { int ret; int sd, ii; gnutls_session_t session; char buffer[MAX_BUF + 1]; gnutls_srp_client_credentials_t srp_cred; gnutls_certificate_credentials_t cert_cred; if (gnutls_check_version("3.1.4") == NULL) { fprintf(stderr, "GnuTLS 3.1.4 or later is required for this example\n"); exit(1); } /* for backwards compatibility with gnutls < 3.3.0 */ gnutls_global_init(); gnutls_srp_allocate_client_credentials(&srp_cred); gnutls_certificate_allocate_credentials(&cert_cred); gnutls_certificate_set_x509_trust_file(cert_cred, CAFILE, GNUTLS_X509_FMT_PEM); gnutls_srp_set_client_credentials(srp_cred, USERNAME, PASSWORD); /* connects to server */ sd = tcp_connect(); /* Initialize TLS session */ gnutls_init(&session, GNUTLS_CLIENT); /* Set the priorities. */ gnutls_priority_set_direct(session, "NORMAL:+SRP:+SRP-RSA:+SRP-DSS", NULL); /* put the SRP credentials to the current session */ gnutls_credentials_set(session, GNUTLS_CRD_SRP, srp_cred); gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, cert_cred); gnutls_transport_set_int(session, sd); gnutls_handshake_set_timeout(session, GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT); /* Perform the TLS handshake */ do { ret = gnutls_handshake(session); } while (ret < 0 && gnutls_error_is_fatal(ret) == 0); if (ret < 0) { fprintf(stderr, "*** Handshake failed\n"); gnutls_perror(ret); goto end; } else { char *desc; desc = gnutls_session_get_desc(session); printf("- Session info: %s\n", desc); gnutls_free(desc); } gnutls_record_send(session, MSG, strlen(MSG)); ret = gnutls_record_recv(session, buffer, MAX_BUF); if (gnutls_error_is_fatal(ret) != 0 || ret == 0) { if (ret == 0) { printf("- Peer has closed the GnuTLS connection\n"); goto end; } else { fprintf(stderr, "*** Error: %s\n", gnutls_strerror(ret)); goto end; } } else check_alert(session, ret); if (ret > 0) { printf("- Received %d bytes: ", ret); for (ii = 0; ii < ret; ii++) { fputc(buffer[ii], stdout); } fputs("\n", stdout); } gnutls_bye(session, GNUTLS_SHUT_RDWR); end: tcp_close(sd); gnutls_deinit(session); gnutls_srp_free_client_credentials(srp_cred); gnutls_certificate_free_credentials(cert_cred); gnutls_global_deinit(); return 0; } ``` -------------------------------- ### PSK TLS client example in C Source: https://www.gnutls.org/manual/html_node/Client-example-with-PSK-authentication.html A complete C program that connects to a server using PSK authentication. It requires GnuTLS 3.6.3 or later and uses the functions gnutls_psk_allocate_client_credentials, gnutls_psk_set_client_credentials, gnutls_set_default_priority_append, and gnutls_handshake. The example includes a comment showing an alternative for pre-3.6.3 versions using gnutls_priority_set_direct. ```c /* This example code is placed in the public domain. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include #include #include /* A very basic TLS client, with PSK authentication. */ #define CHECK(x) assert((x) >= 0) #define LOOP_CHECK(rval, cmd) \ do { \ rval = cmd; \ } while (rval == GNUTLS_E_AGAIN || rval == GNUTLS_E_INTERRUPTED); \ assert(rval >= 0) #define MAX_BUF 1024 #define MSG "GET / HTTP/1.0\r\n\r\n" extern int tcp_connect(void); extern void tcp_close(int sd); int main(void) { int ret, sd, ii; gnutls_session_t session; char buffer[MAX_BUF + 1]; const char *err; gnutls_psk_client_credentials_t pskcred; const gnutls_datum_t key = { (void *)"DEADBEEF", 8 }; if (gnutls_check_version("3.6.3") == NULL) { fprintf(stderr, "GnuTLS 3.6.3 or later is required for this example\n"); exit(1); } CHECK(gnutls_global_init()); CHECK(gnutls_psk_allocate_client_credentials(&pskcred)); CHECK(gnutls_psk_set_client_credentials(pskcred, "test", &key, GNUTLS_PSK_KEY_HEX)); /* Initialize TLS session */ CHECK(gnutls_init(&session, GNUTLS_CLIENT)); ret = gnutls_set_default_priority_append( session, "-KX-ALL:+ECDHE-PSK:+DHE-PSK:+PSK", &err, 0); /* Alternative for pre-3.6.3 versions: * gnutls_priority_set_direct(session, "NORMAL:+ECDHE-PSK:+DHE-PSK:+PSK", &err) */ if (ret < 0) { if (ret == GNUTLS_E_INVALID_REQUEST) { fprintf(stderr, "Syntax error at: %s\n", err); } exit(1); } /* put the x509 credentials to the current session */ CHECK(gnutls_credentials_set(session, GNUTLS_CRD_PSK, pskcred)); /* connect to the peer */ sd = tcp_connect(); gnutls_transport_set_int(session, sd); gnutls_handshake_set_timeout(session, GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT); /* Perform the TLS handshake */ do { ret = gnutls_handshake(session); } while (ret < 0 && gnutls_error_is_fatal(ret) == 0); if (ret < 0) { fprintf(stderr, "*** Handshake failed\n"); gnutls_perror(ret); goto end; } else { char *desc; desc = gnutls_session_get_desc(session); printf("- Session info: %s\n", desc); gnutls_free(desc); } LOOP_CHECK(ret, gnutls_record_send(session, MSG, strlen(MSG))); LOOP_CHECK(ret, gnutls_record_recv(session, buffer, MAX_BUF)); if (ret == 0) { printf("- Peer has closed the TLS connection\n"); goto end; } else if (ret < 0 && gnutls_error_is_fatal(ret) == 0) { fprintf(stderr, "*** Warning: %s\n", gnutls_strerror(ret)); } else if (ret < 0) { fprintf(stderr, "*** Error: %s\n", gnutls_strerror(ret)); goto end; } if (ret > 0) { printf("- Received %d bytes: ", ret); for (ii = 0; ii < ret; ii++) { fputc(buffer[ii], stdout); } fputs("\n", stdout); } CHECK(gnutls_bye(session, GNUTLS_SHUT_RDWR)); end: tcp_close(sd); gnutls_deinit(session); gnutls_psk_free_client_credentials(pskcred); gnutls_global_deinit(); return 0; } ``` -------------------------------- ### Legacy TLS client with X.509 certificate verification (GnuTLS 3.1.x API) Source: https://www.gnutls.org/manual/html_node/Legacy-client-example-with-X_002e509-certificate-support.html A complete C client example using GnuTLS 3.1.x APIs. It requires GnuTLS 3.1.4 or later, loads trusted CA certificates from /etc/ssl/certs/ca-certificates.crt, and uses a custom verification callback to check the server certificate and hostname. The example sends an HTTP GET request and prints the response. ```c /* This example code is placed in the public domain. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include "examples.h" /* A very basic TLS client, with X.509 authentication and server certificate * verification utilizing the GnuTLS 3.1.x API. * Note that error recovery is minimal for simplicity. */ #define CHECK(x) assert((x) >= 0) #define LOOP_CHECK(rval, cmd) \ do { \ rval = cmd; \ } while (rval == GNUTLS_E_AGAIN || rval == GNUTLS_E_INTERRUPTED); \ assert(rval >= 0) #define MAX_BUF 1024 #define CAFILE "/etc/ssl/certs/ca-certificates.crt" #define MSG "GET / HTTP/1.0\r\n\r\n" extern int tcp_connect(void); extern void tcp_close(int sd); static int _verify_certificate_callback(gnutls_session_t session); int main(void) { int ret, sd, ii; gnutls_session_t session; char buffer[MAX_BUF + 1]; gnutls_certificate_credentials_t xcred; if (gnutls_check_version("3.1.4") == NULL) { fprintf(stderr, "GnuTLS 3.1.4 or later is required for this example\n"); exit(1); } CHECK(gnutls_global_init()); /* X509 stuff */ CHECK(gnutls_certificate_allocate_credentials(&xcred)); /* sets the trusted cas file */ CHECK(gnutls_certificate_set_x509_trust_file(xcred, CAFILE, GNUTLS_X509_FMT_PEM)); gnutls_certificate_set_verify_function(xcred, _verify_certificate_callback); /* If client holds a certificate it can be set using the following: * gnutls_certificate_set_x509_key_file (xcred, "cert.pem", "key.pem", GNUTLS_X509_FMT_PEM); */ /* Initialize TLS session */ CHECK(gnutls_init(&session, GNUTLS_CLIENT)); gnutls_session_set_ptr(session, (void *)"www.example.com"); gnutls_server_name_set(session, GNUTLS_NAME_DNS, "www.example.com", strlen("www.example.com")); /* use default priorities */ CHECK(gnutls_set_default_priority(session)); #if 0 /* if more fine-graned control is required */ ret = gnutls_priority_set_direct(session, "NORMAL", &err); if (ret < 0) { if (ret == GNUTLS_E_INVALID_REQUEST) { fprintf(stderr, "Syntax error at: %s\n", err); } exit(1); } #endif /* put the x509 credentials to the current session */ CHECK(gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, xcred)); /* connect to the peer */ sd = tcp_connect(); gnutls_transport_set_int(session, sd); gnutls_handshake_set_timeout(session, GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT); /* Perform the TLS handshake */ do { ret = gnutls_handshake(session); } while (ret < 0 && gnutls_error_is_fatal(ret) == 0); if (ret < 0) { fprintf(stderr, "*** Handshake failed\n"); gnutls_perror(ret); goto end; } else { char *desc; desc = gnutls_session_get_desc(session); printf("- Session info: %s\n", desc); gnutls_free(desc); } LOOP_CHECK(ret, gnutls_record_send(session, MSG, strlen(MSG))); LOOP_CHECK(ret, gnutls_record_recv(session, buffer, MAX_BUF)); if (ret == 0) { printf("- Peer has closed the TLS connection\n"); goto end; } else if (ret < 0 && gnutls_error_is_fatal(ret) == 0) { fprintf(stderr, "*** Warning: %s\n", gnutls_strerror(ret)); } else if (ret < 0) { fprintf(stderr, "*** Error: %s\n", gnutls_strerror(ret)); goto end; } if (ret > 0) { printf("- Received %d bytes: ", ret); for (ii = 0; ii < ret; ii++) { fputc(buffer[ii], stdout); } fputs("\n", stdout); } CHECK(gnutls_bye(session, GNUTLS_SHUT_RDWR)); end: tcp_close(sd); gnutls_deinit(session); gnutls_certificate_free_credentials(xcred); gnutls_global_deinit(); return 0; } /* This function will verify the peer's certificate, and check * if the hostname matches, as well as the activation, expiration dates. */ static int _verify_certificate_callback(gnutls_session_t session) { unsigned int status; int type; const char *hostname; gnutls_datum_t out; /* read hostname */ hostname = gnutls_session_get_ptr(session); /* This verification function uses the trusted CAs in the credentials * structure. So you must have installed one or more CA certificates. */ CHECK(gnutls_certificate_verify_peers3(session, hostname, &status)); type = gnutls_certificate_type_get(session); CHECK(gnutls_certificate_verification_status_print(status, type, &out, 0)); printf("%s", out.data); gnutls_free(out.data); if (status != 0) /* Certificate is not trusted */ return GNUTLS_E_CERTIFICATE_ERROR; /* notify gnutls to continue handshake normally */ return 0; } ``` -------------------------------- ### Starter template for extension functions (_gnutls_foobar_recv_params, _gnutls_foobar_send_params, _gnutls_foobar_pack, _gnutls_foobar_unpack) Source: https://www.gnutls.org/manual/html_node/TLS-Hello-Extension-Handling.html Basic skeleton for the four required extension functions. recv_params parses incoming data, send_params formats data for the wire, pack/unpack handle session resumption storage. Return 0 on success, use GNUTLS_E_UNEXPECTED_PACKET_LENGTH for length mismatches, GNUTLS_E_RECEIVED_ILLEGAL_PARAMETER for invalid data, and GNUTLS_E_INT_RET_0 to send a zero-byte extension. ```c int _gnutls_foobar_recv_params (gnutls_session_t session, const uint8_t * data, size_t data_size) { return 0; } int _gnutls_foobar_send_params (gnutls_session_t session, gnutls_buffer_st* data) { return 0; } int _gnutls_foobar_pack (extension_priv_data_t epriv, gnutls_buffer_st * ps) { /* Append the extension's internal state to buffer */ return 0; } int _gnutls_foobar_unpack (gnutls_buffer_st * ps, extension_priv_data_t * epriv) { /* Read the internal state from buffer */ return 0; } ``` -------------------------------- ### TLS client using PKCS #11 URIs for smart card authentication Source: https://www.gnutls.org/manual/html_node/Client-using-a-smart-card-with-TLS.html Complete C program that loads a certificate and private key from a PKCS #11 token using URIs, registers a PIN callback, and performs a TLS handshake. Requires GnuTLS 3.1.4 or later and a PKCS #11 token with the specified object URLs. The example sends a simple HTTP GET request and prints the response. ```c /* This example code is placed in the public domain. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* for getpass() */ /* A TLS client that loads the certificate and key. */ #define CHECK(x) assert((x) >= 0) #define MAX_BUF 1024 #define MSG "GET / HTTP/1.0\r\n\r\n" #define MIN(x, y) (((x) < (y)) ? (x) : (y)) #define CAFILE "/etc/ssl/certs/ca-certificates.crt" /* The URLs of the objects can be obtained * using p11tool --list-all --login */ #define KEY_URL \ "pkcs11:manufacturer=SomeManufacturer;object=Private%20Key" \ ";objecttype=private;id=%db%5b%3e%b5%72%33" #define CERT_URL \ "pkcs11:manufacturer=SomeManufacturer;object=Certificate;" \ "objecttype=cert;id=db%5b%3e%b5%72%33" extern int tcp_connect(void); extern void tcp_close(int sd); static int pin_callback(void *user, int attempt, const char *token_url, const char *token_label, unsigned int flags, char *pin, size_t pin_max) { const char *password; int len; printf("PIN required for token '%s' with URL '%s'\n", token_label, token_url); if (flags & GNUTLS_PIN_FINAL_TRY) printf("*** This is the final try before locking!\n"); if (flags & GNUTLS_PIN_COUNT_LOW) printf("*** Only few tries left before locking!\n"); if (flags & GNUTLS_PIN_WRONG) printf("*** Wrong PIN\n"); password = getpass("Enter pin: "); /* FIXME: ensure that we are in UTF-8 locale */ if (password == NULL || password[0] == 0) { fprintf(stderr, "No password given\n"); exit(1); } len = MIN(pin_max - 1, strlen(password)); memcpy(pin, password, len); pin[len] = 0; return 0; } int main(void) { int ret, sd, ii; gnutls_session_t session; char buffer[MAX_BUF + 1]; gnutls_certificate_credentials_t xcred; /* Allow connections to servers that have OpenPGP keys as well. */ if (gnutls_check_version("3.1.4") == NULL) { fprintf(stderr, "GnuTLS 3.1.4 or later is required for this example\n"); exit(1); } /* for backwards compatibility with gnutls < 3.3.0 */ CHECK(gnutls_global_init()); /* The PKCS11 private key operations may require PIN. * Register a callback. */ gnutls_pkcs11_set_pin_function(pin_callback, NULL); /* X509 stuff */ CHECK(gnutls_certificate_allocate_credentials(&xcred)); /* sets the trusted cas file */ CHECK(gnutls_certificate_set_x509_trust_file(xcred, CAFILE, GNUTLS_X509_FMT_PEM)); CHECK(gnutls_certificate_set_x509_key_file(xcred, CERT_URL, KEY_URL, GNUTLS_X509_FMT_DER)); /* Note that there is no server certificate verification in this example */ /* Initialize TLS session */ CHECK(gnutls_init(&session, GNUTLS_CLIENT)); /* Use default priorities */ CHECK(gnutls_set_default_priority(session)); /* put the x509 credentials to the current session */ CHECK(gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, xcred)); /* connect to the peer */ sd = tcp_connect(); gnutls_transport_set_int(session, sd); /* Perform the TLS handshake */ ret = gnutls_handshake(session); if (ret < 0) { fprintf(stderr, "*** Handshake failed\n"); gnutls_perror(ret); goto end; } else { char *desc; desc = gnutls_session_get_desc(session); printf("- Session info: %s\n", desc); gnutls_free(desc); } CHECK(gnutls_record_send(session, MSG, strlen(MSG))); ret = gnutls_record_recv(session, buffer, MAX_BUF); if (ret == 0) { printf("- Peer has closed the TLS connection\n"); goto end; } else if (ret < 0) { fprintf(stderr, "*** Error: %s\n", gnutls_strerror(ret)); goto end; } printf("- Received %d bytes: ", ret); for (ii = 0; ii < ret; ii++) { fputc(buffer[ii], stdout); } fputs("\n", stdout); CHECK(gnutls_bye(session, GNUTLS_SHUT_RDWR)); end: tcp_close(sd); gnutls_deinit(session); gnutls_certificate_free_credentials(xcred); gnutls_global_deinit(); return 0; } ``` -------------------------------- ### List all available PKCS #11 tokens Source: https://www.gnutls.org/manual/html_node/Reading-objects.html Example that initializes GnuTLS, iterates over all tokens using gnutls_pkcs11_token_get_url, prints each URL, and stops when GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE is returned. Exits on other errors and cleans up with gnutls_global_deinit. ```c int i; char* url; gnutls_global_init(); for (i=0;;i++) { ret = gnutls_pkcs11_token_get_url(i, &url); if (ret == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) break; if (ret < 0) exit(1); fprintf(stdout, "Token[%d]: URL: %s\n", i, url); gnutls_free(url); } gnutls_global_deinit(); ``` -------------------------------- ### gnutls_cipher_suite_info Source: https://www.gnutls.org/manual/html_node/Core-TLS-API.html Get information about supported cipher suites. Use the function iteratively to get information about all supported cipher suites. ```APIDOC ## gnutls_cipher_suite_info ### Description Get information about supported cipher suites. Use the function iteratively to get information about all supported cipher suites. Call with idx=0 to get information about first cipher suite, then idx=1 and so on until the function returns NULL. ### Function Signature `const char *gnutls_cipher_suite_info(size_t idx, unsigned char *cs_id, gnutls_kx_algorithm_t *kx, gnutls_cipher_algorithm_t *cipher, gnutls_mac_algorithm_t *mac, gnutls_protocol_t *min_version)` ### Parameters - **idx** (size_t) - Required - Index of cipher suite to get information about, starts on 0. - **cs_id** (unsigned char *) - Required - Output buffer with room for 2 bytes, indicating cipher suite value - **kx** (gnutls_kx_algorithm_t *) - Optional - Output variable indicating key exchange algorithm, or `NULL`. - **cipher** (gnutls_cipher_algorithm_t *) - Optional - Output variable indicating cipher, or `NULL`. - **mac** (gnutls_mac_algorithm_t *) - Optional - Output variable indicating MAC algorithm, or `NULL`. - **min_version** (gnutls_protocol_t *) - Optional - Output variable indicating TLS protocol version, or `NULL`. ### Returns The name of `idx` cipher suite, and set the information about the cipher suite in the output variables. If `idx` is out of bounds, `NULL` is returned. ``` -------------------------------- ### Example certtool template file Source: https://www.gnutls.org/manual/html_node/certtool-Invocation.html Example certtool template file (cert.cfg) for generating a certificate request or self-signed certificate. It defines DN options, serial number, and expiration days. ```ini # X.509 Certificate options # # DN options # The organization of the subject. organization = "Koko inc." # The organizational unit of the subject. unit = "sleeping dept." # The locality of the subject. # locality = # The state of the certificate owner. state = "Attiki" # The country of the subject. Two letter code. country = GR # The common name of the certificate owner. cn = "Cindy Lauper" # A user id of the certificate owner. #uid = "clauper" # Set domain components #dc = "name" #dc = "domain" # If the supported DN OIDs are not adequate you can set # any OID here. # For example set the X.520 Title and the X.520 Pseudonym # by using OID and string pairs. #dn_oid = "2.5.4.12 Dr." #dn_oid = "2.5.4.65 jackal" # This is deprecated and should not be used in new # certificates. # pkcs9_email = "none@none.org" # An alternative way to set the certificate's distinguished name directly # is with the "dn" option. The attribute names allowed are: # C (country), street, O (organization), OU (unit), title, CN (common name), # L (locality), ST (state), placeOfBirth, gender, countryOfCitizenship, # countryOfResidence, serialNumber, telephoneNumber, surName, initials, # generationQualifier, givenName, pseudonym, dnQualifier, postalCode, name, # businessCategory, DC, UID, jurisdictionOfIncorporationLocalityName, # jurisdictionOfIncorporationStateOrProvinceName, # jurisdictionOfIncorporationCountryName, XmppAddr, and numeric OIDs. #dn = "cn = Nikos,st = New\, Something,C=GR,surName=Mavrogiannopoulos,2.5.4.9=Arkadias" # The serial number of the certificate # The value is in decimal (i.e. 1963) or hex (i.e. 0x07ab). # Comment the field for a random serial number. serial = 007 # In how many days, counting from today, this certificate will expire. # Use -1 if there is no expiration date. expiration_days = 700 ``` -------------------------------- ### Configure PKCS#11 module as cryptographic backend in [provider] section Source: https://www.gnutls.org/manual/html_node/Using-PKCS_002311-module-as-cryptographic-backend.html Example configuration for the [provider] section. The module must be initialized first. The 'url' specifies the PKCS#11 module URL, and 'pin' is the PIN for logging into the token. ```ini [provider] url = pkcs11:model=v1;manufacturer=Kryoptic%20Project;token=Kryoptic%20Token pin = 1234 ``` -------------------------------- ### Connect using a PKCS #11 token with gnutls-cli Source: https://www.gnutls.org/manual/html_node/gnutls_002dcli-Invocation.html Connects to a server using a certificate and private key stored in a PKCS #11 token. First, list available tokens with p11tool --list-tokens, then list certificates in the token with p11tool --login --list-certs. Set the certificate and key URLs as environment variables and pass them to gnutls-cli via --x509keyfile and --x509certfile. The private key URL differs from the certificate only in the type field. ```bash $ p11tool --list-tokens Token 0: URL: pkcs11:model=PKCS15;manufacturer=MyMan;serial=1234;token=Test Label: Test Manufacturer: EnterSafe Model: PKCS15 Serial: 1234 ``` ```bash $ p11tool --login --list-certs "pkcs11:model=PKCS15;manufacturer=MyMan;serial=1234;token=Test" Object 0: URL: pkcs11:model=PKCS15;manufacturer=MyMan;serial=1234;token=Test;object=client;type=cert Type: X.509 Certificate Label: client ID: 2a:97:0d:58:d1:51:3c:23:07:ae:4e:0d:72:26:03:7d:99:06:02:6a ``` ```bash $ MYCERT="pkcs11:model=PKCS15;manufacturer=MyMan;serial=1234;token=Test;object=client;type=cert" $ MYKEY="pkcs11:model=PKCS15;manufacturer=MyMan;serial=1234;token=Test;object=client;type=private" $ export MYCERT MYKEY ``` ```bash $ gnutls-cli www.example.com --x509keyfile $MYKEY --x509certfile $MYCERT ``` -------------------------------- ### gnutls_privkey_get_type Source: https://www.gnutls.org/manual/html_node/Abstract-private-keys.html Gets the type of a private key. ```APIDOC ## gnutls_privkey_get_type ### Description Gets the type of a private key. ### Function Signature gnutls_privkey_type_t gnutls_privkey_get_type (gnutls_privkey_t key) ### Parameters - **key** (gnutls_privkey_t) - Required - The private key. ### Returns The type of the private key. ``` -------------------------------- ### gnutls_x509_ext_ct_scts_init Source: https://www.gnutls.org/manual/html_node/X509-certificate-API.html Initializes a Certificate Transparency SCT list. Returns GNUTLS_E_SUCCESS on success or a negative error value. ```APIDOC ## gnutls_x509_ext_ct_scts_init ### Description This function will initialize a Certificate Transparency SCT list. ### Function Signature `int gnutls_x509_ext_ct_scts_init(gnutls_x509_ct_scts_t * scts)` ### Parameters - **scts** (gnutls_x509_ct_scts_t *) - Required - The SCT list. ### Returns `GNUTLS_E_SUCCESS` (0) on success, otherwise a negative error value. ``` -------------------------------- ### psktool example: add user and view key file Source: https://www.gnutls.org/manual/html_node/psktool-Invocation.html Shows how to add a user 'psk_identity' to keys.psk using psktool, then display the generated key file. The command creates keys.psk if it does not exist and stores the key in hexadecimal format. ```bash $ ./psktool -u psk_identity -p keys.psk Generating a random key for user 'psk_identity' Key stored to keys.psk $ cat keys.psk psk_identity:88f3824b3e5659f52d00e959bacab954b6540344 $ ``` -------------------------------- ### gnutls_srtp_get_profile_name Source: https://www.gnutls.org/manual/html_node/Core-TLS-API.html Gets the corresponding name for an SRTP protection profile. ```APIDOC ## gnutls_srtp_get_profile_name ### Description Allows you to get the corresponding name for an SRTP protection profile. ### Function Signature `const char * gnutls_srtp_get_profile_name(gnutls_srtp_profile_t profile)` ### Parameters - **profile** (gnutls_srtp_profile_t) - Required - The profile to look up a string for. ### Returns On success, the name of an SRTP profile as a string, otherwise NULL. ### Since 3.1.4 ``` -------------------------------- ### gnutls_x509_privkey_init Source: https://www.gnutls.org/manual/html_node/X509-certificate-API.html Initializes a private key type. ```APIDOC ## gnutls_x509_privkey_init ### Description Initializes a private key type. ### Function Signature `int gnutls_x509_privkey_init(gnutls_x509_privkey_t * key)` ### Parameters - **key** (gnutls_x509_privkey_t *) - A pointer to the type to be initialized. ### Details This function will initialize a private key type. ### Returns On success, `GNUTLS_E_SUCCESS` (0) is returned, otherwise a negative error value. ``` -------------------------------- ### gnutls_cipher_get Source: https://www.gnutls.org/manual/html_node/Core-TLS-API.html Gets the currently used cipher for a given session. ```APIDOC ## gnutls_cipher_get ### Description Gets the currently used cipher for the session. ### Function Signature `gnutls_cipher_algorithm_t gnutls_cipher_get(gnutls_session_t session)` ### Parameters - **session** (gnutls_session_t) - Required - A gnutls_session_t type. ### Returns The currently used cipher, a `gnutls_cipher_algorithm_t` type. ``` -------------------------------- ### Connect to STARTTLS service with gnutls-cli Source: https://www.gnutls.org/manual/html_node/gnutls_002dcli-Invocation.html Connects to a service that supports STARTTLS, using the SMTP protocol on port 25. The --starttls-proto option specifies the protocol to use for STARTTLS negotiation. ```bash $ gnutls-cli --starttls-proto smtp --port 25 localhost ``` -------------------------------- ### gnutls_privkey_get_pk_algorithm Source: https://www.gnutls.org/manual/html_node/Abstract-private-keys.html Gets the public key algorithm of a private key. ```APIDOC ## gnutls_privkey_get_pk_algorithm ### Description Gets the public key algorithm of a private key. ### Function Signature int gnutls_privkey_get_pk_algorithm (gnutls_privkey_t key, unsigned int * bits) ### Parameters - **key** (gnutls_privkey_t) - Required - The private key. - **bits** (unsigned int *) - Optional - If non-NULL, will hold the number of bits of the key. ### Returns The public key algorithm, or a negative error value on failure. ``` -------------------------------- ### Start basic gnutls-serv HTTP server with anonymous ciphersuites Source: https://www.gnutls.org/manual/html_node/gnutls_002dserv-Invocation.html Starts a simple HTTPS server using gnutls-serv with the --http option and a priority string that enables anonymous ECDH and DH ciphersuites. Only anonymous ciphersuites are supported, which many TLS clients refuse to use. ```bash gnutls-serv --http --priority "NORMAL:+ANON-ECDH:+ANON-DH" ``` -------------------------------- ### gnutls_x509_tlsfeatures_get Source: https://www.gnutls.org/manual/html_node/X509-certificate-API.html Gets a feature from the X.509 TLS features extension structure. ```APIDOC ## gnutls_x509_tlsfeatures_get ### Description This function will get a feature from the X.509 TLS features extension structure. ### Function Signature `int gnutls_x509_tlsfeatures_get(gnutls_x509_tlsfeatures_t f, unsigned idx, unsigned int * feature)` ### Parameters - **f** (gnutls_x509_tlsfeatures_t) - Required - The TLS features - **idx** (unsigned) - Required - The index of the feature to get - **feature** (unsigned int *) - Required - If the function succeeds, the feature will be stored in this variable ### Returns On success, `GNUTLS_E_SUCCESS` (0) is returned, otherwise a negative error value. ### Since 3.5.1 ``` -------------------------------- ### gnutls_x509_spki_init Source: https://www.gnutls.org/manual/html_node/X509-certificate-API.html Initializes a SubjectPublicKeyInfo structure used in PKIX. ```APIDOC ## gnutls_x509_spki_init ### Description Initializes a SubjectPublicKeyInfo structure used in PKIX. The structure is used to set additional parameters in the public key information field of a certificate. ### Function `int gnutls_x509_spki_init(gnutls_x509_spki_t * spki)` ### Parameters - **spki** (gnutls_x509_spki_t *) - Required - A pointer to the type to be initialized. ### Returns On success, `GNUTLS_E_SUCCESS` (0) is returned, otherwise a negative error value. ### Since 3.6.0 ``` -------------------------------- ### gnutls_certificate_client_get_request_status Source: https://www.gnutls.org/manual/html_node/Core-TLS-API.html Gets whether client certificate was requested on the last handshake. ```APIDOC ## gnutls_certificate_client_get_request_status ### Description Get whether client certificate was requested on the last handshake or not. ### Function Signature `unsigned gnutls_certificate_client_get_request_status(gnutls_session_t session)` ### Parameters - **session** (gnutls_session_t) - Input - Is a gnutls session. ### Returns 0 if the peer (server) did not request client authentication or 1 otherwise. ``` -------------------------------- ### gnutls_x509_key_purpose_init Source: https://www.gnutls.org/manual/html_node/X509-certificate-API.html Initializes a key purposes type. ```APIDOC ## gnutls_x509_key_purpose_init ### Description This function will initialize an alternative names type. ### Function Signature `int gnutls_x509_key_purpose_init(gnutls_x509_key_purposes_t * p)` ### Parameters - **p** (gnutls_x509_key_purposes_t *) - Required - The key purposes. ### Returns On success, `GNUTLS_E_SUCCESS` (0) is returned, otherwise a negative error value. ### Since 3.3.0 ``` -------------------------------- ### gnutls_pkcs7_init Source: https://www.gnutls.org/manual/html_node/Cryptographic-Message-Syntax-_002f-PKCS7.html Initializes a PKCS #7 structure. ```APIDOC ## gnutls_pkcs7_init ### Description Initializes a PKCS #7 structure. ### Function Signature `int gnutls_pkcs7_init (gnutls_pkcs7_t * pkcs7)` ### Parameters - **pkcs7** (gnutls_pkcs7_t *) - Required - A pointer to the structure to initialize. ### Returns On success, `GNUTLS_E_SUCCESS` (0) is returned, otherwise a negative error value. ``` -------------------------------- ### Connect with raw public-key authentication using gnutls-cli Source: https://www.gnutls.org/manual/html_node/gnutls_002dcli-Invocation.html Connects to a server using raw public-key authentication. Requires enabling raw public-key negotiation via priority strings (e.g., NORMAL:-CTYPE-CLI-ALL:+CTYPE-CLI-RAWPK) and providing the raw public key and private key files. The output shows the handshake details and certificate information. ```bash $ ./gnutls-cli -p 5556 localhost --priority NORMAL:-CTYPE-CLI-ALL:+CTYPE-CLI-RAWPK \ --rawpkkeyfile cli.key.pem \ --rawpkfile cli.rawpk.pem Processed 1 client raw public key pair... Resolving 'localhost'... Connecting to '127.0.0.1:5556'... - Successfully sent 1 certificate(s) to server. - Server has requested a certificate. - Certificate type: X.509 - Got a certificate list of 1 certificates. - Certificate[0] info: - skipped - Description: (TLS1.3-Raw Public Key-X.509)-(ECDHE-SECP256R1)-(RSA-PSS-RSAE-SHA256)-(AES-256-GCM) - Options: - Handshake was completed - Simple Client Mode: ```