Index: doc/tls.html ================================================================== --- doc/tls.html +++ doc/tls.html @@ -12,31 +12,31 @@
NAME
-
tls - binding to OpenSSL toolkit.
+
tls - binding to OpenSSL toolkit.
SYNOPSIS
-
package require Tcl ?8.4?
-
package require tls
-
 
-
tls::init ?options?
-
tls::socket ?options? host port
-
tls::socket ?-server command? ?options? port
-
tls::handshake channel
-
tls::status ?-local? channel
-
tls::connection channel
-
tls::import channel ?options?
-
tls::unimport channel
-
 
-
tls::ciphers protocol ?verbose? ?supported?
-
tls::protocols
-
tls::version
-
+
package require Tcl ?8.4?
+
package require tls
+
 
+
tls::init ?options?
+
tls::socket ?options? host port
+
tls::socket ?-server command? ?options? port
+
tls::handshake channel
+
tls::status ?-local? channel
+
tls::connection channel
+
tls::import channel ?options?
+
tls::unimport channel
+
 
+
tls::ciphers protocol ?verbose? ?supported?
+
tls::protocols
+
tls::version
+
COMMANDS
CALLBACK OPTIONS
HTTPS EXAMPLE
SPECIAL CONSIDERATIONS
@@ -88,132 +88,136 @@
tls::init ?options?
Optional function to set the default options used by tls::socket. If you call tls::import - directly this routine has no effect. Any of the options - that tls::socket accepts can be set - using this command, though you should limit your options - to only TLS related ones.
+ directly this routine has no effect. Any of the options + that tls::socket accepts can be set + using this command, though you should limit your options + to only TLS related ones.
 
tls::socket ?options? - host port
+ host port
tls::socket ?-server command? ?options? port
This is a helper function that utilizes the underlying - commands (tls::import). It behaves - exactly the same as the native Tcl socket - command except that the options can include any of the - applicable tls:import - options with one additional option: + commands (tls::import). It behaves + exactly the same as the native Tcl socket + command except that the options can include any of the + applicable tls:import + options with one additional option:
-
-autoservername bool
-
Automatically send the -servername as the host argument - (default is false)
+
-autoservername bool
+
Automatically send the -servername as the host argument + (default is false)
tls::import channel - ?options?
+ ?options?
SSL-enable a regular Tcl channel - it need not be a - socket, but must provide bi-directional flow. Also - setting session parameters for SSL handshake.
+ socket, but must provide bi-directional flow. Also + setting session parameters for SSL handshake.
-
-alpn list
-
List of protocols to offer during Application-Layer +
-alpn list
+
List of protocols to offer during Application-Layer Protocol Negotiation (ALPN). For example: h2, http/1.1, etc.
-
-cadir dir
-
Specify the directory containing the CA certificates. The - default directory is platform specific and can be set at - compile time. This can be overridden via the SSL_CERT_DIR - environment variable.
-
-cafile filename
-
Specify the certificate authority (CA) file to use.
-
-certfile filename
-
Specify the filename containing the certificate to use. The - default name is cert.pem. This can be overridden via - the SSL_CERT_FILE environment variable.
-
-cert filename
-
Specify the contents of a certificate to use, as a DER +
-cadir dir
+
Set the CA certificates path. The default directory is platform + specific and can be set at compile time. This can be overridden + via the SSL_CERT_DIR environment variable.
+
-cafile filename
+
Set the certificate authority (CA) certificates file. The default + is the cert.pem file in the OpsnSSL directory. This can also be + overridden via the SSL_CERT_FILE environment variable.
+
-certfile filename
+
Specify the filename with the certificate to use.
+
-cert filename
+
Specify the contents of a certificate to use, as a DER encoded binary value (X.509 DER).
-
-cipher string
-
List of ciphers to use. String is a colon (":") separated list +
-cipher string
+
List of ciphers to use. String is a colon (":") separated list of ciphers or cipher suites. Cipher suites can be combined using the + character. Prefixes can be used to permanently remove ("!"), delete ("-"), or move a cypher to the end of the list ("+"). Keywords @STRENGTH (sort by algorithm key length), @SECLEVEL=n (set security level to n), and DEFAULT (use default cipher list, at start only) can also be specified. See OpenSSL documentation for the full list of valid values. (TLS 1.2 and earlier only)
-
-ciphersuites string
-
List of cipher suites to use. String is a colon (":") +
-ciphersuites string
+
List of cipher suites to use. String is a colon (":") separated list of cipher suite names. (TLS 1.3 only)
-
-command callback
-
Callback to invoke at several points during the handshake. +
-command callback
+
Callback to invoke at several points during the handshake. This is used to pass errors and tracing information, and it can allow Tcl scripts to perform their own certificate validation in place of the default validation provided by OpenSSL. See CALLBACK OPTIONS for further discussion.
-
-dhparams filename
-
Specify the Diffie-Hellman parameters file.
-
-keyfile filename
-
Specify the private key file. (default is - value of -certfile)
-
-key filename
-
Specify the private key to use as a DER encoded value (PKCS#1 DER)
-
-model channel
-
Force this channel to share the same SSL_CTX - structure as the specified channel, and - therefore share callbacks etc.
-
-password callback
-
Callback to invoke when OpenSSL needs to obtain a password, +
-dhparams filename
+
Specify the Diffie-Hellman parameters file.
+
-keyfile filename
+
Specify the private key file. (default is + value of -certfile)
+
-key filename
+
Specify the private key to use as a DER encoded value (PKCS#1 DER)
+
-model channel
+
Force this channel to share the same SSL_CTX + structure as the specified channel, and + therefore share callbacks etc.
+
-password callback
+
Callback to invoke when OpenSSL needs to obtain a password, typically to unlock the private key of a certificate. The - callback should return a string which represents the password - to be used. See CALLBACK OPTIONS + callback should return a string which represents the password + to be used. See CALLBACK OPTIONS for further discussion.
-post_handshake bool
Allow post-handshake ticket updates.
-
-request bool
-
Request a certificate from peer during SSL handshake. - (default is true)
-
-require bool
-
Require a valid certificate from peer during SSL handshake. +
-request bool
+
Request a certificate from peer during SSL handshake. + (default is true)
+
-require bool
+
Require a valid certificate from peer during SSL handshake. If this is set to true, then -request must - also be set to true. (default is false)
-
-securitylevel integer
-
Set security level. Must be 0 to 5. The security level affects + also be set to true. (default is false)
+
-securitylevel integer
+
Set security level. Must be 0 to 5. The security level affects cipher suite encryption algorithms, supported ECC curves, supported signature algorithms, DH parameter sizes, certificate key sizes and signature algorithms. The default is 1. Level 3 and higher disable support for session tickets and only accept cipher suites that provide forward secrecy.
-
-server bool
-
Handshake as server if true, else handshake as - client. (default is false)
-
-servername host
-
Specify server hostname. Only available if the OpenSSL library +
-server bool
+
Handshake as server if true, else handshake as + client. (default is false)
+
-servername host
+
Specify server hostname. Only available if the OpenSSL library the package is linked against supports the TLS hostname extension for 'Server Name Indication' (SNI). Use to name the logical host we are talking to and expecting a certificate for.
-
-session_id string
-
Session id to resume session.
-
-ssl2 bool
-
Enable use of SSL v2. (default is false)
-
-ssl3 bool
-
Enable use of SSL v3. (default is false)
-
-tls1 bool
-
Enable use of TLS v1. (default is true)
-
-tls1.1 bool
-
Enable use of TLS v1.1 (default is true)
-
-tls1.2 bool
-
Enable use of TLS v1.2 (default is true)
-
-tls1.3 bool
-
Enable use of TLS v1.3 (default is true)
+
-session_id string
+
Session id to resume session.
+
-ssl2 bool
+
Enable use of SSL v2. (default is false)
+
-ssl3 bool
+
Enable use of SSL v3. (default is false)
+
-tls1 bool
+
Enable use of TLS v1. (default is true)
+
-tls1.1 bool
+
Enable use of TLS v1.1 (default is true)
+
-tls1.2 bool
+
Enable use of TLS v1.2 (default is true)
+
-tls1.3 bool
+
Enable use of TLS v1.3 (default is true)
+
-validatecommand callback
+
Callback to invoke to verify or validate protocol config + parameters during the protocol negotiation phase. See + CALLBACK OPTIONS + for further discussion.
tls::unimport channel
Provided for symmetry to tls::import, this @@ -220,195 +224,195 @@ unstacks the SSL-enabling of a regular Tcl channel. An error is thrown if TLS is not the top stacked channel type.
 
tls::handshake channel
Forces handshake to take place, and returns 0 if - handshake is still in progress (non-blocking), or 1 if - the handshake was successful. If the handshake failed - this routine will throw an error.
+ handshake is still in progress (non-blocking), or 1 if + the handshake was successful. If the handshake failed + this routine will throw an error.
 
tls::status ?-local? channel
Returns the current status of the certificate for an SSL channel. The result is a list of key-value pairs describing the certificate. If the result is an empty list then the - SSL handshake has not yet completed. If -local is + SSL handshake has not yet completed. If -local is specified, then the local certificate is used.
SSL Status
-
alpn protocol
-
The protocol selected after Application-Layer Protocol +
alpn protocol
+
The protocol selected after Application-Layer Protocol Negotiation (ALPN).
-
cipher cipher
-
The current cipher in use between the client and - server channels.
-
peername name
-
The peername from the certificate.
-
protocol version
-
The protocol version used for the connection: +
cipher cipher
+
The current cipher in use between the client and + server channels.
+
peername name
+
The peername from the certificate.
+
protocol version
+
The protocol version used for the connection: SSL2, SSL3, TLS1, TLS1.1, TLS1.2, TLS1.3, or unknown.
-
sbits n
-
The number of bits used for the session key.
-
signatureHashAlgorithm algorithm
-
The signature hash algorithm.
-
signature_type type
-
The signature type value.
-
verification result
-
Certificate verification result.
-
ca_names list
-
List of the Certificate Authorities used to create the certificate.
+
sbits n
+
The number of bits used for the session key.
+
signatureHashAlgorithm algorithm
+
The signature hash algorithm.
+
signature_type type
+
The signature type value.
+
verification result
+
Certificate verification result.
+
ca_names list
+
List of the Certificate Authorities used to create the certificate.
Certificate Status
-
all string
-
Dump of all certificate info.
- -
version value
-
The certificate version.
-
serialNumber n
-
The serial number of the certificate as hex string.
-
signature algorithm
-
Cipher algorithm used for certificate signature.
-
issuer dn
-
The distinguished name (DN) of the certificate issuer.
-
notBefore date
-
The begin date for the validity of the certificate.
-
notAfter date
-
The expiration date for the certificate.
-
subject dn
-
The distinguished name (DN) of the certificate subject. +
all string
+
Dump of all certificate info.
+ +
version value
+
The certificate version.
+
serialNumber n
+
The serial number of the certificate as hex string.
+
signature algorithm
+
Cipher algorithm used for certificate signature.
+
issuer dn
+
The distinguished name (DN) of the certificate issuer.
+
notBefore date
+
The begin date for the validity of the certificate.
+
notAfter date
+
The expiration date for the certificate.
+
subject dn
+
The distinguished name (DN) of the certificate subject. Fields include: Common Name (CN), Organization (O), Locality or City (L), State or Province (S), and Country Name (C).
-
issuerUniqueID string
-
The issuer unique id.
-
subjectUniqueID string
-
The subject unique id.
- -
num_extensions n
-
Number of certificate extensions.
-
extensions list
-
List of certificate extension names.
-
authorityKeyIdentifier string
-
(AKI) Key identifier of the Issuing CA certificate that signed +
issuerUniqueID string
+
The issuer unique id.
+
subjectUniqueID string
+
The subject unique id.
+ +
num_extensions n
+
Number of certificate extensions.
+
extensions list
+
List of certificate extension names.
+
authorityKeyIdentifier string
+
(AKI) Key identifier of the Issuing CA certificate that signed the SSL certificate. This value matches the SKI value of the Intermediate CA certificate.
-
subjectKeyIdentifier string
-
(SKI) Hash of the public key inside the certificate. Used to +
subjectKeyIdentifier string
+
(SKI) Hash of the public key inside the certificate. Used to identify certificates that contain a particular public key.
-
subjectAltName list
-
List of all of the alternative domain names, sub domains, +
subjectAltName list
+
List of all of the alternative domain names, sub domains, and IP addresses that are secured by the certificate.
-
ocsp list
-
List of all OCSP URLs.
+
ocsp list
+
List of all OCSP URLs.
certificate cert
-
The PEM encoded certificate.
- -
signatureAlgorithm algorithm
-
Cipher algorithm used for certificate signature.
-
signatureValue string
-
Certificate signature as hex string.
-
signatureDigest version
-
Certificate signing digest.
-
publicKeyAlgorithm algorithm
-
Certificate signature public key algorithm.
-
publicKey string
-
Certificate signature public key as hex string.
-
bits n
-
Number of bits used for certificate signature key
-
self_signed boolean
-
Is certificate signature self signed.
- -
sha1_hash hash
-
The SHA1 hash of the certificate as hex string.
-
sha256_hash hash
-
The SHA256 hash of the certificate as hex string.
+
The PEM encoded certificate.
+ +
signatureAlgorithm algorithm
+
Cipher algorithm used for certificate signature.
+
signatureValue string
+
Certificate signature as hex string.
+
signatureDigest version
+
Certificate signing digest.
+
publicKeyAlgorithm algorithm
+
Certificate signature public key algorithm.
+
publicKey string
+
Certificate signature public key as hex string.
+
bits n
+
Number of bits used for certificate signature key
+
self_signed boolean
+
Is certificate signature self signed.
+ +
sha1_hash hash
+
The SHA1 hash of the certificate as hex string.
+
sha256_hash hash
+
The SHA256 hash of the certificate as hex string.
tls::connection channel
Returns the current connection status of an SSL channel. The - result is a list of key-value pairs describing the - connected peer.
+ result is a list of key-value pairs describing the + connected peer.
SSL Status
-
state state
-
State of the connection.
-
servername name
-
The name of the connected to server.
-
protocol version
-
The protocol version used for the connection: +
state state
+
State of the connection.
+
servername name
+
The name of the connected to server.
+
protocol version
+
The protocol version used for the connection: SSL2, SSL3, TLS1, TLS1.1, TLS1.2, TLS1.3, or unknown.
-
renegotiation state
-
Whether protocol renegotiation is supported or not.
-
securitylevel level
-
The security level used for selection of ciphers, key size, etc.
-
session_reused boolean
-
Whether the session has been reused or not.
-
is_server boolean
-
Whether the connection configured as a server or client (false).
-
compression mode
-
Compression method.
-
expansion mode
-
Expansion method.
+
renegotiation state
+
Whether protocol renegotiation is supported or not.
+
securitylevel level
+
The security level used for selection of ciphers, key size, etc.
+
session_reused boolean
+
Whether the session has been reused or not.
+
is_server boolean
+
Whether the connection configured as a server or client (false).
+
compression mode
+
Compression method.
+
expansion mode
+
Expansion method.
Cipher Info
-
cipher cipher
-
The current cipher in use for the connection.
-
standard_name name
-
The standard RFC name of cipher.
-
bits n
-
The number of processed bits used for cipher.
-
secret_bits n
-
The number of secret bits used for cipher.
-
min_version version
-
The minimum protocol version for cipher.
-
id id
-
The OpenSSL cipher id.
-
description string
-
A text description of the cipher.
+
cipher cipher
+
The current cipher in use for the connection.
+
standard_name name
+
The standard RFC name of cipher.
+
bits n
+
The number of processed bits used for cipher.
+
secret_bits n
+
The number of secret bits used for cipher.
+
min_version version
+
The minimum protocol version for cipher.
+
id id
+
The OpenSSL cipher id.
+
description string
+
A text description of the cipher.
Session Info
-
alpn protocol
-
The protocol selected after Application-Layer Protocol +
alpn protocol
+
The protocol selected after Application-Layer Protocol Negotiation (ALPN).
-
resumable boolean
-
Can the session be resumed or not.
-
start_time seconds
-
Time since session started in seconds since epoch.
-
timeout seconds
-
Max duration of session in seconds before time-out.
-
lifetime seconds
-
Session ticket lifetime hint in seconds.
-
session_id string
-
Unique session id for use in resuming the session.
-
session_ticket string
-
Unique session ticket for use in resuming the session.
-
ticket_app_data string
-
Unique session ticket application data.
-
master_key binary_string
-
Unique session master key.
-
session_cache_mode mode
-
Server cache mode (client, server, or both).
+
resumable boolean
+
Can the session be resumed or not.
+
start_time seconds
+
Time since session started in seconds since epoch.
+
timeout seconds
+
Max duration of session in seconds before time-out.
+
lifetime seconds
+
Session ticket lifetime hint in seconds.
+
session_id string
+
Unique session id for use in resuming the session.
+
session_ticket string
+
Unique session ticket for use in resuming the session.
+
ticket_app_data string
+
Unique session ticket application data.
+
master_key binary_string
+
Unique session master key.
+
session_cache_mode mode
+
Server cache mode (client, server, or both).
tls::ciphers protocol ?verbose? ?supported?
Returns a list of supported ciphers available for protocol, - where protocol must be one of ssl2, ssl3, tls1, tls1.1, + where protocol must be one of ssl2, ssl3, tls1, tls1.1, tls1.2, or tls1.3. If verbose is specified as true then a verbose, human readable list is returned with additional information on the cipher. If supported is specified as true, then only the ciphers supported for protocol will be listed.
@@ -437,15 +441,88 @@
-command callback
Invokes the specified callback script at several points during the OpenSSL handshake. - Except as indicated below, values returned from the - callback are ignored. + Values returned from the callback are ignored. Arguments appended to the script upon callback take one of the following forms: +
+
+ +
+ + + +
+ info channel major minor message type +
+
+ This form of callback is invoked by the OpenSSL function + SSL_CTX_set_info_callback(). +
+ The major and minor arguments are used to + represent the state information bitmask. +
    +
  • Possible values for major are: + handshake, alert, connect, accept.
  • +
  • Possible values for minor are: + start, done, read, write, loop, exit.
  • +
  • The message argument is a descriptive string which may + be generated either by SSL_state_string_long() or by + SSL_alert_desc_string_long(), depending on context.
  • +
  • For alerts, the possible values for type are: + warning, fatal, and unknown.
  • +
+
+ +
+ session session_id ticket lifetime +
+
+ This form of callback is invoked by the OpenSSL function + SSL_CTX_sess_set_new_cb(). + Where session_id is the current session identifier, + ticket is the session ticket info, and lifetime + is the the ticket lifetime in seconds. +
+ +
+
+ +
+ +
-password callback
+
+ Invokes the specified callback script when OpenSSL needs to + obtain a password. The callback should return the password as a string. + No arguments are appended to the script upon callback. +
+ +
+ + +
-validatecommand callback
+
+ Invokes the specified callback script during handshake in + order to verify/validate the provided value. + To reject the value and abort connection, the callback should return 0. + To accept the value, it should return 1. To reject the value, but + continue the connection, it should return 2. +

@@ -459,71 +536,18 @@ client specified protocol is used.

- -
hello servername
For servers, this form of callback is invoked during client hello - message processing. -
- -
- -
- info channel major minor message type -
-
- This form of callback is invoked by the OpenSSL function - SSL_CTX_set_info_callback(). -
- The major and minor arguments are used to - represent the state information bitmask. -
-
Possible values for major are:
-
handshake, alert, connect, accept.
-
Possible values for minor are:
-
start, done, read, write, loop, exit.
-
- The message argument is a descriptive string which may - be generated either by - SSL_state_string_long() or by - SSL_alert_desc_string_long(), - depending on context. -
For alerts, the possible values for type are:
-
-
warning, fatal, and unknown.
-
- - -
- -
- session session_id ticket lifetime -
-
- This form of callback is invoked by the OpenSSL function - SSL_CTX_sess_set_new_cb(). - Where session_id is the current session identifier, - ticket is the session ticket info, and lifetime - is the the ticket lifetime in seconds. + message processing. Used to select an appropriate certificate to + present, and make other configuration adjustments relevant to that + server name and its configuration. Called before SNI and ALPN callbacks.

@@ -531,58 +555,46 @@
For servers, this form of callback is invoked when the SNI header from the client is received. Where servername is the client specified servername. This is used when a server supports multiple - names, so the right certificate can be used. + names, so the right certificate can be used. Called after hello + callback but before ALPN callback.
-

verify channel depth cert status error
This form of callback is invoked by OpenSSL when a new certificate is received from the peer. It allows the client to check the - certificate verification result and choose whether to continue or not. -
- The depth argument is an integer representing the + certificate chain verification results and choose whether to continue or not. +
    +
  • The depth argument is an integer representing the current depth on the certificate chain, with - 0 as the subject certificate and higher values - denoting progressively more indirect issuer certificates. -
    - The cert argument is a list of key-value pairs similar + 0 as the peer certificate and higher values going + up to the Certificate Authority (CA).
  • +
  • The cert argument is a list of key-value pairs similar to those returned by - tls::status. -
    - The status argument is an integer representing the - current validity of the certificate. + tls::status.
  • +
  • The status argument is an boolean representing the + validity of the current certificate. A value of 0 means the certificate is deemed invalid. - A value of 1 means the certificate is deemed valid. -
    - The error argument supplies the message, if any, generated - by X509_STORE_CTX_get_error(). + A value of 1 means the certificate is deemed valid.
  • +
  • The error argument supplies the message, if any, generated + by X509_STORE_CTX_get_error().
  • +


The callback may override normal validation processing by explicitly returning one of the above status values.
- +
- -
- -
-password callback
-
- Invokes the specified callback script when OpenSSL needs to - obtain a password. The callback should return a string which - represents the password to be used. - No arguments are appended to the script upon callback. -

Reference implementations of these callbacks are provided in the Index: generic/tls.c ================================================================== --- generic/tls.c +++ generic/tls.c @@ -101,10 +101,56 @@ /* *------------------------------------------------------------------- * + * Eval Callback Command -- + * + * Eval callback command and catch any errors + * + * Results: + * 0 = Command returned fail or eval returned TCL_ERROR + * 1 = Command returned success or eval returned TCL_OK + * + * Side effects: + * Evaluates callback command + * + *------------------------------------------------------------------- + */ +static int +EvalCallback(Tcl_Interp *interp, State *statePtr, Tcl_Obj *cmdPtr) { + int code, ok; + + Tcl_Preserve((ClientData) interp); + Tcl_Preserve((ClientData) statePtr); + + /* Eval callback with success for ok or return value 1, fail for error or return value 0 */ + code = Tcl_EvalObjEx(interp, cmdPtr, TCL_EVAL_GLOBAL); + if (code == TCL_OK) { + /* Check result for return value */ + Tcl_Obj *result = Tcl_GetObjResult(interp); + if (result == NULL || Tcl_GetIntFromObj(interp, result, &ok) != TCL_OK) { + ok = 1; + } + } else { + /* Error - reject the certificate */ + ok = 0; +#if (TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION < 6) + Tcl_BackgroundError(interp); +#else + Tcl_BackgroundException(interp, code); +#endif + } + + Tcl_Release((ClientData) statePtr); + Tcl_Release((ClientData) interp); + return ok; +} + +/* + *------------------------------------------------------------------- + * * InfoCallback -- * * monitors SSL connection process * * Results: @@ -124,21 +170,20 @@ dprintf("Called"); if (statePtr->callback == (Tcl_Obj*)NULL) return; - cmdPtr = Tcl_DuplicateObj(statePtr->callback); - #if 0 if (where & SSL_CB_ALERT) { sev = SSL_alert_type_string_long(ret); if (strcmp(sev, "fatal")==0) { /* Map to error */ Tls_Error(statePtr, SSL_ERROR(ssl, 0)); return; } } #endif + if (where & SSL_CB_HANDSHAKE_START) { major = "handshake"; minor = "start"; } else if (where & SSL_CB_HANDSHAKE_DONE) { major = "handshake"; @@ -154,11 +199,12 @@ else if (where & SSL_CB_LOOP) minor = "loop"; else if (where & SSL_CB_EXIT) minor = "exit"; else minor = "unknown"; } - /* info channel major minor message type */ + /* Create command to eval from callback */ + cmdPtr = Tcl_DuplicateObj(statePtr->callback); Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj("info", -1)); Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj(Tcl_GetChannelName(statePtr->self), -1)); Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj(major, -1)); Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj(minor, -1)); @@ -171,111 +217,89 @@ } else { Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj(SSL_state_string_long(ssl), -1)); Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj("info", -1)); } - Tcl_Preserve((ClientData) interp); - Tcl_Preserve((ClientData) statePtr); + /* Eval callback command */ Tcl_IncrRefCount(cmdPtr); - (void) Tcl_EvalObjEx(interp, cmdPtr, TCL_EVAL_GLOBAL); + EvalCallback(interp, statePtr, cmdPtr); Tcl_DecrRefCount(cmdPtr); - - Tcl_Release((ClientData) statePtr); - Tcl_Release((ClientData) interp); } /* *------------------------------------------------------------------- * * VerifyCallback -- * - * Monitors SSL certificate validation process. - * This is called whenever a certificate is inspected - * or decided invalid. + * Monitors SSL certificate validation process. Used to control the + * behavior when the SSL_VERIFY_PEER flag is set. This is called + * whenever a certificate is inspected or decided invalid. + * + * Checks: + * certificate chain is checked starting with the deepest nesting level + * (the root CA certificate) and worked upward to the peer's certificate. + * All signatures are valid, current time is within first and last validity time. + * Check that the certificate is issued by the issuer certificate issuer. + * Check the revocation status for each certificate. + * Check the validity of the given CRL and the cert revocation status. + * Check the policies of all the certificates + * + * Args + * preverify_ok indicates whether the certificate verification passed (1) or not (0) * * Results: * A callback bound to the socket may return one of: - * 0 - the certificate is deemed invalid - * 1 - the certificate is deemed valid + * 0 - the certificate is deemed invalid, send verification + * failure alert to peer, and terminate handshake. + * 1 - the certificate is deemed valid, continue with handshake. * empty string - no change to certificate validation * * Side effects: * The err field of the currently operative State is set * to a string describing the SSL negotiation failure reason *------------------------------------------------------------------- */ static int VerifyCallback(int ok, X509_STORE_CTX *ctx) { - Tcl_Obj *cmdPtr, *result; - char *string; - int length; + Tcl_Obj *cmdPtr; SSL *ssl = (SSL*)X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()); X509 *cert = X509_STORE_CTX_get_current_cert(ctx); State *statePtr = (State*)SSL_get_app_data(ssl); Tcl_Interp *interp = statePtr->interp; int depth = X509_STORE_CTX_get_error_depth(ctx); int err = X509_STORE_CTX_get_error(ctx); - int code; dprintf("Verify: %d", ok); - if (statePtr->callback == (Tcl_Obj*)NULL) { + if (statePtr->vcmd == (Tcl_Obj*)NULL) { if (statePtr->vflags & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) { return ok; } else { return 1; } } - cmdPtr = Tcl_DuplicateObj(statePtr->callback); + /* Create command to eval from callback */ + cmdPtr = Tcl_DuplicateObj(statePtr->vcmd); Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj("verify", -1)); Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj(Tcl_GetChannelName(statePtr->self), -1)); Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewIntObj(depth)); Tcl_ListObjAppendElement(interp, cmdPtr, Tls_NewX509Obj(interp, cert)); Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewIntObj(ok)); Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj((char*)X509_verify_cert_error_string(err), -1)); - Tcl_Preserve((ClientData) interp); - Tcl_Preserve((ClientData) statePtr); - statePtr->flags |= TLS_TCL_CALLBACK; + /* Eval callback command */ Tcl_IncrRefCount(cmdPtr); - code = Tcl_EvalObjEx(interp, cmdPtr, TCL_EVAL_GLOBAL); - if (code != TCL_OK) { - /* It got an error - reject the certificate. */ -#if (TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION < 6) - Tcl_BackgroundError(interp); -#else - Tcl_BackgroundException(interp, code); -#endif - ok = 0; - } else { - result = Tcl_GetObjResult(interp); - string = Tcl_GetStringFromObj(result, &length); - /* An empty result leaves verification unchanged. */ - if (string != NULL && length > 0) { - code = Tcl_GetIntFromObj(interp, result, &ok); - if (code != TCL_OK) { -#if (TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION < 6) - Tcl_BackgroundError(interp); -#else - Tcl_BackgroundException(interp, code); -#endif - ok = 0; - } - } - } + ok = EvalCallback(interp, statePtr, cmdPtr); Tcl_DecrRefCount(cmdPtr); statePtr->flags &= ~(TLS_TCL_CALLBACK); - - Tcl_Release((ClientData) statePtr); - Tcl_Release((ClientData) interp); return(ok); /* By default, leave verification unchanged. */ } /* *------------------------------------------------------------------- @@ -292,13 +316,15 @@ */ void Tls_Error(State *statePtr, char *msg) { Tcl_Interp *interp = statePtr->interp; Tcl_Obj *cmdPtr; - int code; dprintf("Called"); + + if (statePtr->callback == (Tcl_Obj*)NULL) + return; if (msg && *msg) { Tcl_SetErrorCode(interp, "SSL", msg, (char *)NULL); } else { msg = Tcl_GetStringFromObj(Tcl_GetObjResult(interp), NULL); @@ -315,32 +341,22 @@ #else Tcl_BackgroundException(interp, TCL_ERROR); #endif return; } + + /* Create command to eval from callback */ cmdPtr = Tcl_DuplicateObj(statePtr->callback); - Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj("error", -1)); Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj(Tcl_GetChannelName(statePtr->self), -1)); Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj(msg, -1)); - Tcl_Preserve((ClientData) interp); - Tcl_Preserve((ClientData) statePtr); - + /* Eval callback command */ Tcl_IncrRefCount(cmdPtr); - code = Tcl_EvalObjEx(interp, cmdPtr, TCL_EVAL_GLOBAL); - if (code != TCL_OK) { -#if (TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION < 6) - Tcl_BackgroundError(interp); -#else - Tcl_BackgroundException(interp, code); -#endif - } + EvalCallback(interp, statePtr, cmdPtr); Tcl_DecrRefCount(cmdPtr); - Tcl_Release((ClientData) statePtr); - Tcl_Release((ClientData) interp); } /* *------------------------------------------------------------------- * @@ -389,15 +405,17 @@ } else { return -1; } } + /* Create command to eval from callback */ cmdPtr = Tcl_DuplicateObj(statePtr->password); Tcl_Preserve((ClientData) interp); Tcl_Preserve((ClientData) statePtr); + /* Eval callback and success for ok, abort for error, continue for continue */ Tcl_IncrRefCount(cmdPtr); code = Tcl_EvalObjEx(interp, cmdPtr, TCL_EVAL_GLOBAL); if (code != TCL_OK) { #if (TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION < 6) Tcl_BackgroundError(interp); @@ -449,11 +467,10 @@ State *statePtr = (State*)SSL_get_app_data((SSL *)ssl); Tcl_Interp *interp = statePtr->interp; Tcl_Obj *cmdPtr; const unsigned char *ticket; const unsigned char *session_id; - int code; size_t len2; unsigned int ulen; dprintf("Called"); @@ -461,10 +478,11 @@ return SSL_TLSEXT_ERR_OK; } else if (ssl == NULL) { return SSL_TLSEXT_ERR_NOACK; } + /* Create command to eval from callback */ cmdPtr = Tcl_DuplicateObj(statePtr->callback); Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj("session", -1)); /* Session id */ session_id = SSL_SESSION_get_id(session, &ulen); @@ -476,32 +494,21 @@ /* Lifetime - number of seconds */ Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewLongObj((long) SSL_SESSION_get_ticket_lifetime_hint(session))); - Tcl_Preserve((ClientData) interp); - Tcl_Preserve((ClientData) statePtr); - + /* Eval callback command */ Tcl_IncrRefCount(cmdPtr); - code = Tcl_EvalObjEx(interp, cmdPtr, TCL_EVAL_GLOBAL); - if (code != TCL_OK) { -#if (TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION < 6) - Tcl_BackgroundError(interp); -#else - Tcl_BackgroundException(interp, code); -#endif - } + EvalCallback(interp, statePtr, cmdPtr); Tcl_DecrRefCount(cmdPtr); - - Tcl_Release((ClientData) statePtr); - Tcl_Release((ClientData) interp); return 0; + return 0; } /* *------------------------------------------------------------------- * - * ALPN Callback for Servers and Clients -- + * ALPN Callback for Servers and NPN Callback for Clients -- * * Perform protocol (http/1.1, h2, h3, etc.) selection for the * incoming connection. Called after Hello and server callbacks. * Where 'out' is selected protocol and 'in' is the peer advertised list. * @@ -535,47 +542,43 @@ } /* Select protocol */ if (SSL_select_next_proto(out, outlen, statePtr->protos, statePtr->protos_len, in, inlen) == OPENSSL_NPN_NEGOTIATED) { + /* Match found */ res = SSL_TLSEXT_ERR_OK; } else { - /* No overlap, so use first client protocol */ + /* OPENSSL_NPN_NO_OVERLAP = No overlap, so use first item from client protocol list */ res = SSL_TLSEXT_ERR_NOACK; } - if (statePtr->callback == (Tcl_Obj*)NULL) { - return SSL_TLSEXT_ERR_OK; + if (statePtr->vcmd == (Tcl_Obj*)NULL) { + return res; } - cmdPtr = Tcl_DuplicateObj(statePtr->callback); + /* Create command to eval from callback */ + cmdPtr = Tcl_DuplicateObj(statePtr->vcmd); Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj("alpn", -1)); Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj(*out, -1)); - Tcl_Preserve((ClientData) interp); - Tcl_Preserve((ClientData) statePtr); - + /* Eval callback command */ Tcl_IncrRefCount(cmdPtr); - code = Tcl_EvalObjEx(interp, cmdPtr, TCL_EVAL_GLOBAL); - if (code != TCL_OK) { -#if (TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION < 6) - Tcl_BackgroundError(interp); -#else - Tcl_BackgroundException(interp, code); -#endif + if ((code = EvalCallback(interp, statePtr, cmdPtr)) > 1) { + res = SSL_TLSEXT_ERR_NOACK; + } else if (code == 1) { + res = SSL_TLSEXT_ERR_OK; + } else { + res = SSL_TLSEXT_ERR_ALERT_FATAL; } Tcl_DecrRefCount(cmdPtr); - - Tcl_Release((ClientData) statePtr); - Tcl_Release((ClientData) interp); return res; } /* *------------------------------------------------------------------- * - * Advertise Protocols Callback for Servers Next Protocol Negotiation -- + * Advertise Protocols Callback for Next Protocol Negotiation (NPN) in ServerHello -- * * called when a TLS server needs a list of supported protocols for Next * Protocol Negotiation. * * Results: @@ -630,11 +633,11 @@ * Return codes: * SSL_TLSEXT_ERR_OK: SNI hostname is accepted. The connection continues. * SSL_TLSEXT_ERR_ALERT_FATAL: SNI hostname is not accepted. The connection * is aborted. Default for alert is SSL_AD_UNRECOGNIZED_NAME. * SSL_TLSEXT_ERR_ALERT_WARNING: SNI hostname is not accepted, warning alert - * sent (not in TLSv1.3). The connection continues. + * sent (not supported in TLSv1.3). The connection continues. * SSL_TLSEXT_ERR_NOACK: SNI hostname is not accepted and not acknowledged, * e.g. if SNI has not been configured. The connection continues. * *------------------------------------------------------------------- */ @@ -641,11 +644,11 @@ static int SNICallback(const SSL *ssl, int *alert, void *arg) { State *statePtr = (State*)arg; Tcl_Interp *interp = statePtr->interp; Tcl_Obj *cmdPtr; - int code; + int code, res; char *servername = NULL; dprintf("Called"); if (ssl == NULL || arg == NULL) { @@ -655,132 +658,132 @@ servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name); if (!servername || servername[0] == '\0') { return SSL_TLSEXT_ERR_NOACK; } - if (statePtr->callback == (Tcl_Obj*)NULL) { + if (statePtr->vcmd == (Tcl_Obj*)NULL) { return SSL_TLSEXT_ERR_OK; } - cmdPtr = Tcl_DuplicateObj(statePtr->callback); + /* Create command to eval from callback */ + cmdPtr = Tcl_DuplicateObj(statePtr->vcmd); Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj("sni", -1)); Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj(servername , -1)); - Tcl_Preserve((ClientData) interp); - Tcl_Preserve((ClientData) statePtr); - + /* Eval callback command */ Tcl_IncrRefCount(cmdPtr); - code = Tcl_EvalObjEx(interp, cmdPtr, TCL_EVAL_GLOBAL); - if (code != TCL_OK) { -#if (TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION < 6) - Tcl_BackgroundError(interp); -#else - Tcl_BackgroundException(interp, code); -#endif + if ((code = EvalCallback(interp, statePtr, cmdPtr)) > 1) { + res = SSL_TLSEXT_ERR_ALERT_WARNING; + *alert = SSL_AD_UNRECOGNIZED_NAME; /* Not supported by TLS 1.3 */ + } else if (code == 1) { + res = SSL_TLSEXT_ERR_OK; + } else { + res = SSL_TLSEXT_ERR_ALERT_FATAL; + *alert = SSL_AD_UNRECOGNIZED_NAME; /* Not supported by TLS 1.3 */ } Tcl_DecrRefCount(cmdPtr); - - Tcl_Release((ClientData) statePtr); - Tcl_Release((ClientData) interp); - return SSL_TLSEXT_ERR_OK; + return res; } /* *------------------------------------------------------------------- * - * Hello Handshake Callback for Servers -- + * ClientHello Handshake Callback for Servers -- * * Used by server to examine the server name indication (SNI) extension * provided by the client in order to select an appropriate certificate to * present, and make other configuration adjustments relevant to that server * name and its configuration. This includes swapping out the associated * SSL_CTX pointer, modifying the server's list of permitted TLS versions, * changing the server's cipher list in response to the client's cipher list, etc. + * Called before SNI and ALPN callbacks. * * Results: * None * * Side effects: * Calls callback (if defined) * * Return codes: - * SSL_CLIENT_HELLO_RETRY = suspend the handshake, and the handshake function will return immediately - * SSL_CLIENT_HELLO_ERROR = failure, terminate connection. Set alert to error code. - * SSL_CLIENT_HELLO_SUCCESS = success + * SSL_CLIENT_HELLO_RETRY: suspend the handshake, and the handshake function will return immediately + * SSL_CLIENT_HELLO_ERROR: failure, terminate connection. Set alert to error code. + * SSL_CLIENT_HELLO_SUCCESS: success * *------------------------------------------------------------------- */ static int HelloCallback(const SSL *ssl, int *alert, void *arg) { State *statePtr = (State*)arg; Tcl_Interp *interp = statePtr->interp; Tcl_Obj *cmdPtr; - int code; + int code, res; const char *servername; const unsigned char *p; size_t len, remaining; dprintf("Called"); - if (statePtr->callback == (Tcl_Obj*)NULL) { + if (statePtr->vcmd == (Tcl_Obj*)NULL) { return SSL_CLIENT_HELLO_SUCCESS; } else if (ssl == NULL || arg == NULL) { return SSL_CLIENT_HELLO_ERROR; } /* Get names */ if (!SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &p, &remaining) || remaining <= 2) { + *alert = SSL_R_SSLV3_ALERT_ILLEGAL_PARAMETER; return SSL_CLIENT_HELLO_ERROR; } /* Extract the length of the supplied list of names. */ len = (*(p++) << 8); len += *(p++); if (len + 2 != remaining) { + *alert = SSL_R_SSLV3_ALERT_ILLEGAL_PARAMETER; return SSL_CLIENT_HELLO_ERROR; } remaining = len; /* The list in practice only has a single element, so we only consider the first one. */ if (remaining == 0 || *p++ != TLSEXT_NAMETYPE_host_name) { + *alert = SSL_R_TLSV1_ALERT_INTERNAL_ERROR; return SSL_CLIENT_HELLO_ERROR; } remaining--; /* Now we can finally pull out the byte array with the actual hostname. */ if (remaining <= 2) { + *alert = SSL_R_TLSV1_ALERT_INTERNAL_ERROR; return SSL_CLIENT_HELLO_ERROR; } len = (*(p++) << 8); len += *(p++); if (len + 2 > remaining) { + *alert = SSL_R_TLSV1_ALERT_INTERNAL_ERROR; return SSL_CLIENT_HELLO_ERROR; } remaining = len; servername = (const char *)p; - cmdPtr = Tcl_DuplicateObj(statePtr->callback); + /* Create command to eval from callback */ + cmdPtr = Tcl_DuplicateObj(statePtr->vcmd); Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj("hello", -1)); Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj(servername, (int) len)); - Tcl_Preserve((ClientData) interp); - Tcl_Preserve((ClientData) statePtr); - + /* Eval callback command */ Tcl_IncrRefCount(cmdPtr); - code = Tcl_EvalObjEx(interp, cmdPtr, TCL_EVAL_GLOBAL); - if (code != TCL_OK) { -#if (TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION < 6) - Tcl_BackgroundError(interp); -#else - Tcl_BackgroundException(interp, code); -#endif + if ((code = EvalCallback(interp, statePtr, cmdPtr)) > 1) { + res = SSL_CLIENT_HELLO_RETRY; + *alert = SSL_R_TLSV1_ALERT_USER_CANCELLED; + } else if (code == 1) { + res = SSL_CLIENT_HELLO_SUCCESS; + } else { + res = SSL_CLIENT_HELLO_ERROR; + *alert = SSL_R_TLSV1_ALERT_INTERNAL_ERROR; } Tcl_DecrRefCount(cmdPtr); - - Tcl_Release((ClientData) statePtr); - Tcl_Release((ClientData) interp); - return SSL_CLIENT_HELLO_SUCCESS; + return res; } /********************/ /* Commands */ /********************/ @@ -1092,10 +1095,11 @@ Tcl_Channel chan; /* The channel to set a mode on. */ State *statePtr; /* client state for ssl socket */ SSL_CTX *ctx = NULL; Tcl_Obj *script = NULL; Tcl_Obj *password = NULL; + Tcl_Obj *vcmd = NULL; Tcl_DString upperChannelTranslation, upperChannelBlocking, upperChannelEncoding, upperChannelEOFChar; int idx, len; int flags = TLS_TCL_INIT; int server = 0; /* is connection incoming or outgoing? */ char *keyfile = NULL; @@ -1156,10 +1160,11 @@ char *opt = Tcl_GetStringFromObj(objv[idx], NULL); if (opt[0] != '-') break; + OPTOBJ("-alpn", alpn); OPTSTR("-cadir", CAdir); OPTSTR("-cafile", CAfile); OPTSTR("-certfile", certfile); OPTSTR("-cipher", ciphers); OPTSTR("-ciphers", ciphers); @@ -1174,21 +1179,22 @@ OPTBOOL("-request", request); OPTINT("-securitylevel", level); OPTBOOL("-server", server); OPTSTR("-servername", servername); OPTSTR("-session_id", session_id); - OPTOBJ("-alpn", alpn); OPTBOOL("-ssl2", ssl2); OPTBOOL("-ssl3", ssl3); OPTBOOL("-tls1", tls1); OPTBOOL("-tls1.1", tls1_1); OPTBOOL("-tls1.2", tls1_2); OPTBOOL("-tls1.3", tls1_3); + OPTOBJ("-validatecommand", vcmd); + OPTOBJ("-vcmd", vcmd); OPTBYTE("-cert", cert, cert_len); OPTBYTE("-key", key, key_len); - OPTBAD("option", "-alpn, -cadir, -cafile, -cert, -certfile, -cipher, -ciphersuites, -command, -dhparams, -key, -keyfile, -model, -password, -require, -request, -securitylevel, -server, -servername, -session_id, -ssl2, -ssl3, -tls1, -tls1.1, -tls1.2, or -tls1.3"); + OPTBAD("option", "-alpn, -cadir, -cafile, -cert, -certfile, -cipher, -ciphersuites, -command, -dhparams, -key, -keyfile, -model, -password, -require, -request, -securitylevel, -server, -servername, -session_id, -ssl2, -ssl3, -tls1, -tls1.1, -tls1.2, -tls1.3, or -validatecommand"); return TCL_ERROR; } if (request) verify |= SSL_VERIFY_CLIENT_ONCE | SSL_VERIFY_PEER; if (request && require) verify |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT; @@ -1237,10 +1243,19 @@ if (len) { statePtr->password = password; Tcl_IncrRefCount(statePtr->password); } } + + /* allocate validate command */ + if (vcmd) { + (void) Tcl_GetStringFromObj(vcmd, &len); + if (len) { + statePtr->vcmd = vcmd; + Tcl_IncrRefCount(statePtr->vcmd); + } + } if (model != NULL) { int mode; /* Get the "model" context */ chan = Tcl_GetChannel(interp, model, &mode); @@ -1313,11 +1328,11 @@ return TCL_ERROR; } /* Set host server name */ if (servername) { - /* Sets the server name indication (SNI) ClientHello extension */ + /* Sets the server name indication (SNI) in ClientHello extension */ if (!SSL_set_tlsext_host_name(statePtr->ssl, servername) && require) { Tcl_AppendResult(interp, "setting TLS host name extension failed", (char *) NULL); Tls_Free((char *) statePtr); return TCL_ERROR; } @@ -1340,11 +1355,11 @@ return TCL_ERROR; } } if (alpn) { - /* Convert a Tcl list into a protocol-list in wire-format */ + /* Convert a TCL list into a protocol-list in wire-format */ unsigned char *protos, *p; unsigned int protos_len = 0; int i, len, cnt; Tcl_Obj **list; @@ -1394,11 +1409,11 @@ /* * SSL Callbacks */ SSL_set_app_data(statePtr->ssl, (void *)statePtr); /* point back to us */ SSL_set_verify(statePtr->ssl, verify, VerifyCallback); - SSL_CTX_set_info_callback(statePtr->ctx, InfoCallback); + SSL_set_info_callback(statePtr->ssl, InfoCallback); /* Create Tcl_Channel BIO Handler */ statePtr->p_bio = BIO_new_tcl(statePtr, BIO_NOCLOSE); statePtr->bio = BIO_new(BIO_f_ssl()); @@ -1909,11 +1924,11 @@ Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewIntObj(SSL_get_cipher_bits(statePtr->ssl, NULL))); ciphers = (char*)SSL_get_cipher(statePtr->ssl); if ((ciphers != NULL) && (strcmp(ciphers, "(NONE)") != 0)) { Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj("cipher", -1)); - Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj(SSL_get_cipher(statePtr->ssl), -1)); + Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj(ciphers, -1)); } /* Verify the X509 certificate presented by the peer */ Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj("verification", -1)); Tcl_ListObjAppendElement(interp, objPtr, @@ -2471,10 +2486,14 @@ statePtr->callback = NULL; } if (statePtr->password) { Tcl_DecrRefCount(statePtr->password); statePtr->password = NULL; + } + if (statePtr->vcmd) { + Tcl_DecrRefCount(statePtr->vcmd); + statePtr->vcmd = NULL; } dprintf("Returning"); } Index: generic/tlsInt.h ================================================================== --- generic/tlsInt.h +++ generic/tlsInt.h @@ -112,26 +112,27 @@ * This structure describes the per-instance state of an SSL channel. * * The SSL processing context is maintained here, in the ClientData */ typedef struct State { - Tcl_Channel self; /* this socket channel */ + Tcl_Channel self; /* this socket channel */ Tcl_TimerToken timer; - int flags; /* see State.flags above */ - int watchMask; /* current WatchProc mask */ - int mode; /* current mode of parent channel */ - - Tcl_Interp *interp; /* interpreter in which this resides */ - Tcl_Obj *callback; /* script called for tracing, verifying and errors */ - Tcl_Obj *password; /* script called for certificate password */ - - int vflags; /* verify flags */ - SSL *ssl; /* Struct for SSL processing */ - SSL_CTX *ctx; /* SSL Context */ - BIO *bio; /* Struct for SSL processing */ - BIO *p_bio; /* Parent BIO (that is layered on Tcl_Channel) */ + int flags; /* see State.flags above */ + int watchMask; /* current WatchProc mask */ + int mode; /* current mode of parent channel */ + + Tcl_Interp *interp; /* interpreter in which this resides */ + Tcl_Obj *callback; /* script called for tracing, info, and errors */ + Tcl_Obj *password; /* script called for certificate password */ + Tcl_Obj *vcmd; /* script called to verify or validate protocol config */ + + int vflags; /* verify flags */ + SSL *ssl; /* Struct for SSL processing */ + SSL_CTX *ctx; /* SSL Context */ + BIO *bio; /* Struct for SSL processing */ + BIO *p_bio; /* Parent BIO (that is layered on Tcl_Channel) */ char *protos; /* List of supported protocols in protocol format */ unsigned int protos_len; /* Length of protos */ char *err; Index: library/tls.tcl ================================================================== --- library/tls.tcl +++ library/tls.tcl @@ -320,16 +320,65 @@ variable debug #log 2 [concat $option $args] switch -- $option { - "error" { + "error" { foreach {chan msg} $args break log 0 "TLS/$chan: error: $msg" } - "verify" { + "info" { + # poor man's lassign + foreach {chan major minor state msg type} $args break + + if {$msg != ""} { + append state ": $msg" + } + # For tracing + upvar #0 tls::$chan cb + set cb($major) $minor + + log 2 "TLS/$chan: $major/$minor: $state" + } + "session" { + foreach {session_id ticket lifetime} $args break + + log 0 "TLS/$chan: error: $msg" + } + default { + return -code error "bad option \"$option\":\ + must be one of error, info, or session" + } + } +} + +# +# Sample callback when return value is needed +# +proc tls::validate_command {option args} { + variable debug + + #log 2 [concat $option $args] + + switch -- $option { + "alpn" { + foreach {protocol} $args break + + log 0 "TLS/$chan: alpn: $protocol" + } + "hello" { + foreach {servername} $args break + + log 0 "TLS/$chan: hello: $servername" + } + "sni" { + foreach {servername} $args break + + log 0 "TLS/$chan: sni: $servername" + } + "verify" { # poor man's lassign foreach {chan depth cert rc err} $args break array set c $cert @@ -342,28 +391,16 @@ return 1; # FORCE OK } else { return $rc } } - "info" { - # poor man's lassign - foreach {chan major minor state msg} $args break - - if {$msg != ""} { - append state ": $msg" - } - # For tracing - upvar #0 tls::$chan cb - set cb($major) $minor - - log 2 "TLS/$chan: $major/$minor: $state" - } default { return -code error "bad option \"$option\":\ - must be one of error, info, or verify" + must be one of alpn, info, or verify" } } + return 1 } proc tls::xhandshake {chan} { upvar #0 tls::$chan cb