|
SharkSSL C/C++ Reference
TLS, cryptography, certificates, and PSA integration
|
This subset lets a TLS application inspect the peer certificate's retained names, IP subject alternative names, serial bytes, version and validity dates. Applications that pin public keys can also retain the leaf certificate's encoded SubjectPublicKeyInfo. The adapter copies these fields into an immutable reference-counted object.
Include <openssl/ssl.h> or <openssl/x509.h> from the adapter include directory. Link src/SharkSslOsslX509.c with the existing TLS/BIO/ERR sources and native SharkSSL. The basic inspection API requires no extra configuration; public-key retention and typed common-name matching have the options described below.
On Windows, define WIN32_LEAN_AND_MEAN before including Windows.h when using these headers. Otherwise its implicit Wincrypt.h include defines an unrelated X509_NAME macro that conflicts with the OpenSSL type. The Win32 ThreadX simulator also needs this setting because its port includes Windows.h. An application that explicitly needs Wincrypt.h must manage that name collision in its own include boundary.
SSL_get0_peer_certificate(const SSL*) returns a borrowed X509* after successful wrapper handshake completion, or NULL when unavailable. It creates and caches the snapshot on first use. Repeated successful calls return the same pointer. Do not free the borrowed reference; it belongs to the SSL object.
SSL_get1_peer_certificate(const SSL*) returns that same snapshot with an additional reference. Release it with X509_free. It remains valid after shutdown, SSL destruction and context destruction. X509_up_ref acquires another reference and returns one on success. X509_free(NULL) is harmless.
The first query allocates one block for the object and retained bytes. Failure returns NULL, records ERR_R_MALLOC_FAILURE, and leaves the connection's last I/O result and cached-certificate state unchanged; a later query can retry. Connections that never inspect a certificate allocate no wrapper snapshot. Serialize first access and all other SSL operations as required by the TLS contract. Once obtained, immutable X509 fields can be read concurrently while each caller holds a live reference. Reference updates use the existing atomics.
These getters return NULL before wrapper handshake success and after a rejected handshake, including certificate-verification rejection. This is narrower than OpenSSL's availability during failed or incomplete handshakes. Servers without client authentication, or with an absent optional client certificate, return NULL. Initial mutual TLS uses the same getters for the client's certificate on the server. Session resumption and renegotiation remain outside the TLS subset.
A certificate returned when verification was disabled does not prove peer identity. Inspect the configured verification policy and SSL_get_verify_result separately. Metadata inspection adds no trust, date, purpose or hostname checks. The existing 24-hour notBefore allowance remains unchanged.
Compile SharkSSL, the adapter and every consumer of the native certificate headers with SHARKSSL_ENABLE_CERT_SPKI=1. The default is 0. Enabling the option adds a pointer and a byte count to SharkSslCertInfo. The native clone stores the original DER SubjectPublicKeyInfo bytes for the peer leaf. An adapter snapshot of that leaf owns a second copy, so an owned X509* keeps its key encoding after SSL_free. Issuer snapshots omit the key.
X509_get_X509_PUBKEY(const X509* cert) returns a borrowed X509_PUBKEY* that lives as long as the certificate. It returns NULL when the encoding is unavailable, including in the default build. An application requiring a pin must reject the connection if it cannot obtain and match the key. Perform the comparison before sending application data and keep the usual chain and hostname verification enabled.
i2d_X509_PUBKEY(const X509_PUBKEY* key, unsigned char** out) returns the encoded length in bytes as an int, or a negative value on error.
| Output argument | Result |
|---|---|
out == NULL | Query the required length. |
*out != NULL | Copy into caller storage of at least that length and advance *out past the bytes. |
*out == NULL | Allocate the output and return its base through *out. Release it with OPENSSL_free. |
The encoding includes the algorithm identifier, its parameters and the key bits, as required for curl's sha256// or public-key file pins. curl pin formats ยท OpenSSL encoding conventions
Include <openssl/x509v3.h>. Use X509_check_ip_asc(cert, address, 0) for a text literal, or X509_check_ip(cert, bytes, length, 0) for a 4-byte IPv4 or 16-byte IPv6 address in network byte order. Both compare only against the certificate's IP subject alternative names. An IPv4-mapped IPv6 address matches its 16-byte form. An owned certificate supports both calls after SSL_free.
The return value is 1 for a match, 0 for a mismatch, -2 for a NULL argument or invalid text literal, and -1 if the SAN list cannot be decoded. A non-NULL binary address of any other length returns 0. Pass a bare address, without brackets, a zone, or a port. IPv4 uses four decimal octets without extra leading zeroes. IPv6 supports zero compression and an IPv4 tail. The IP checks allocate no memory and use no socket services. OpenSSL certificate matching
Use X509_check_host from <openssl/x509v3.h> to compare a DNS name with the peer leaf certificate. Only a return value of 1 means the name matched. The call inspects a certificate you already hold. Use the TLS verification settings for trust and hostname enforcement during the handshake.
Pass an X509*, the reference name as a const char*, a size_t byte length, unsigned int flags, and an optional char** peername. A zero length selects a NUL-terminated string. An explicit length may include one final terminator. On success, a caller requesting peername owns a copy of the matched certificate name, including its original case and any wildcard. Release it with OPENSSL_free. It survives X509_free.
DNS subject alternative names (SANs) take precedence. With flags set to zero, matching ignores ASCII case and permits a wildcard at either end of the first label in a name with at least three labels. Use an ASCII A-label for an internationalized domain. For an IP address, use the IP functions above.
| Flag | Effect |
|---|---|
X509_CHECK_FLAG_NO_WILDCARDS | Compare certificate names literally. A reference name beginning with a dot can still select subdomains. |
X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS | Allow a wildcard only as the entire first label. |
X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS | Allow a whole-label wildcard to span multiple labels. |
X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS | Limit a leading-dot reference such as .example.org to one subdomain label. |
X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT | Try the subject common names after the DNS SANs have failed to match. |
X509_CHECK_FLAG_NEVER_CHECK_SUBJECT | Skip subject fallback. This takes precedence when both subject flags are set. |
For common-name fallback, compile SharkSSL, the adapter and its native consumers with SHARKSSL_ENABLE_CERT_COMMON_NAMES=1. This adds a pointer and byte count to SharkSslCertInfo. Each native certificate clone stores its encoded subject Name, and the adapter copies the leaf subject into its existing X509 allocation. This preserves repeated common names, their order and their ASN.1 string types. With the default value of zero, the DNS SAN checks work and a check requiring common-name fallback returns -1.
The function returns 0 for a mismatch, -2 for a NULL certificate or name or an embedded NUL in the reference, and -1 for unavailable or undecodable name data or failure to allocate the requested peer name. OpenSSL hostname matching
| Interface | Result |
|---|---|
X509_get_version | Native zero-based version: 2 means X.509 v3 |
X509_get0_serialNumber | Borrowed const ASN1_INTEGER* containing retained serial bytes |
X509_get0_notBefore, X509_get0_notAfter | Borrowed const ASN1_TIME* containing the original retained date bytes |
X509_get_subject_name, X509_get_issuer_name | Borrowed X509_NAME* views of the supported fields |
X509_NAME_entry_count | Number of retained fields in that name |
X509_NAME_get_index_by_NID | Next matching index after lastpos; start at -1; -1 means absent, -2 means unsupported NID |
X509_NAME_get_entry | Borrowed entry for an index, or NULL outside the name's range |
X509_NAME_ENTRY_get_data | Borrowed byte-string view of an entry |
ASN1_STRING_length, ASN1_STRING_get0_data | Byte count and borrowed data pointer for names, dates or serials |
All returned fields are immutable despite the non-const pointer signatures required by these OpenSSL 3 interfaces. Their lifetime follows their owning X509 object, not an independent field reference. Do not free or alter them. Embedded NUL and non-ASCII bytes are preserved. Data pointers must be used with their explicit lengths; no encoding conversion is performed.
The supported NIDs are NID_commonName, NID_countryName, NID_localityName, NID_stateOrProvinceName, NID_organizationName and NID_organizationalUnitName. These name getters recognize only those six identifiers. Other NIDs return -2, even when openssl/obj_mac.h defines them for another API.
For NULL inputs, field getters return NULL, entry counts and string lengths return zero, version returns -1, and X509_up_ref returns zero. Name lookup returns -1 for a supported NID on a NULL name. These defensive results are explicit subset behavior, not a promise for every OpenSSL NULL-input case.
The public name inspection getters expose one value per supported field. Repeated attributes collapse to the native parser's selected value. The snapshot orders the present fields as common name, country, locality, state, organization and organizational unit; these indices are not original DER/RDN positions. Query by NID when comparing with another implementation. Original RDN grouping, ordering, repeated entries and ASN.1 string-type tags are unavailable through these getters. Standalone hostname matching can use the optional subject Name.
No ASN1_STRING_type or UTF-8 conversion API is exposed. The email-address pointers are not part of the native clone's owned storage, so the wrapper never reads or exposes them. Other attributes, SAN objects and chain inspection are not included in this subset.
Serial bytes follow native integer parsing, which removes a leading DER sign padding zero. Valid nonnegative certificate serials can be inspected as unsigned bytes. Negative ASN.1 integers and their sign cannot be reconstructed from this metadata; signed/numeric integer conversion is intentionally absent. Dates retain their native UTC/GeneralizedTime byte strings, not libc time values.
The optional DER export covers the leaf SubjectPublicKeyInfo. Whole-certificate DER, certificate fingerprints, signatures, general extension enumeration, certificate mutation and standalone PEM/X509 constructors remain outside the snapshot API.
References: peer ownership, name lookup, byte-string access, and serial getter.