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,196 @@ 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 - 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 - identify certificates that contain a particular public key.
-
subjectAltName list
-
List of all of the alternative domain names, sub domains, +
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 as hex string. This value matches the SKI + value of the Intermediate CA certificate.
+
subjectKeyIdentifier string
+
(SKI) Hash of the public key inside the certificate as hex + string. Used to identify certificates that contain a particular + public key.
+
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 Online Certificate Status Protocol (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 boolean
+
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 is configured as a server (1) or client (0).
+
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 binary_string
+
Unique session id for use in resuming the session.
+
session_ticket binary_string
+
Unique session ticket for use in resuming the session.
+
ticket_app_data binary_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.
@@ -426,11 +431,12 @@

CALLBACK OPTIONS

As indicated above, individual channels can be given their own callbacks to handle intermediate processing by the OpenSSL library, using the --command and -password options passed to either of +-command, -password, and +-validate_command options passed to either of tls::socket or tls::import.

@@ -437,80 +443,51 @@
-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:

- alpn protocol -
-
- For servers, this form of callback is invoked when the client ALPN - header is received and the first -alpn specified protocol common - to the both the client and server is selected. If none, the first - 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 + error channel message +
+
+ The message argument contains an error message generated + by the OpenSSL function ERR_reason_error_string(). +
+ +
+ +
+ 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. +
    +
  • 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 @@ -517,86 +494,119 @@ 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.
- -
- -
- sni servername -
-
- 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. -
- -
-
- -
- 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 - 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 - to those returned by - tls::status. -
- The status argument is an integer representing the - current validity of the 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(). -
-
- 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. + 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 validate the provided value(s). + 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. + +
+
+ +
+ +
+ alpn protocol +
+
+ For servers, this form of callback is invoked when the client ALPN + extension is received and the first -alpn specified protocol common + to the both the client and server is selected. If none, the first + client specified protocol is used. +
+ +
+ +
+ hello servername +
+
+ For servers, this form of callback is invoked during client hello + message processing. It is 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. +
+ +
+ +
+ sni servername +
+
+ For servers, this form of callback is invoked when the SNI extension + from the client is received. This is used when a server supports multiple + 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 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 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 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().
  • +
+
+
+
+

Reference implementations of these callbacks are provided in the -distribution as tls::callback and -tls::password respectively. Note that these are +distribution as tls::callback, tls::password, +and tls::validate_command respectively. Note that these are sample implementations only. In a more realistic deployment -you would specify your own callback scripts on each TLS channel -using the -command and -password options. +you would specify your own callback scripts on each TLS channel using the +-command, -password, and -validate_command options.

-The default behavior when the -command option is not specified is for -TLS to process the associated library callbacks internally. -The default behavior when the -password option is not specified is for -TLS to process the associated library callbacks by attempting to call -tls::password. +The default behavior when the -command and -validate_command +options are not specified is for TLS to process the associated library callbacks +internally. The default behavior when the -password option is not +specified is for TLS to process the associated library callbacks by attempting +to call tls::password. The difference between these two behaviors is a consequence of maintaining compatibility with earlier implementations.

@@ -607,13 +617,13 @@ certificate, even when it is invalid.

-The use of the reference callbacks tls::callback and -tls::password is not recommended. They may be removed -from future releases. +The use of the reference callbacks tls::callback, +tls::password, and tls::validate_command +is not recommended. They may be removed from future releases.

@@ -624,11 +634,13 @@

DEBUG

TLS key logging can be enabled by setting the environment variable SSLKEYLOGFILE to the name of the file to log to. Then whenever TLS -key material is generated or received it will be logged to the file. +key material is generated or received it will be logged to the file. This +is useful for logging key data for network logging tools to use to +decrypt the data.

HTTPS EXAMPLE

This example uses a sample server.pem provided with the TLS release, courtesy of the OpenSSL project.

@@ -642,22 +654,15 @@ set tok [http::geturl https://www.tcl.tk/]

SPECIAL CONSIDERATIONS

-

The capabilities of this package can vary enormously based -upon how your OpenSSL library was configured and built. At the -most macro-level OpenSSL supports a "no patents" build, -which disables RSA, IDEA, RC(2,4,5) and SSL2 - if your OpenSSL is -configured this way then you will need to build TLS with the --DNO_PATENTS option - and the resultant module will function -correctly and also support ADH certificate-less encryption, -however you will be unable to utilize this to speak to normal Web -Servers, which typically require RSA support. Please see http://www.openssl.org/ for -more information on the whole issue of patents and US export -restrictions.

+

The capabilities of this package can vary enormously based upon how your +OpenSSL library was configured and built. New versions may obsolete older +protocol versions, add or remove ciphers, change default values, etc. Use the +tls::ciphers and tls::protocols commands to +obtain the supported versions.

SEE ALSO

socket, fileevent, OpenSSL

Index: generic/tls.c ================================================================== --- generic/tls.c +++ generic/tls.c @@ -93,14 +93,60 @@ static int locksCount = 0; static Tcl_Mutex init_mx; #endif /* OPENSSL_THREADS */ #endif /* TCL_THREADS */ + /********************/ /* Callbacks */ /********************/ +/* + *------------------------------------------------------------------- + * + * 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 -- @@ -110,10 +156,11 @@ * Results: * None * * Side effects: * Calls callback (if defined) + * *------------------------------------------------------------------- */ static void InfoCallback(const SSL *ssl, int where, int ret) { State *statePtr = (State*)SSL_get_app_data((SSL *)ssl); @@ -124,21 +171,10 @@ 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,193 +190,161 @@ else if (where & SSL_CB_LOOP) minor = "loop"; else if (where & SSL_CB_EXIT) minor = "exit"; else minor = "unknown"; } + /* Create command to eval */ + 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)); - if (where & (SSL_CB_LOOP|SSL_CB_EXIT)) { + if (where & SSL_CB_ALERT) { + Tcl_ListObjAppendElement(interp, cmdPtr, + Tcl_NewStringObj(SSL_alert_desc_string_long(ret), -1)); Tcl_ListObjAppendElement(interp, cmdPtr, - Tcl_NewStringObj(SSL_state_string_long(ssl), -1)); - } else if (where & SSL_CB_ALERT) { - const char *cp = (char *) SSL_alert_desc_string_long(ret); - - Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj(cp, -1)); + Tcl_NewStringObj(SSL_alert_type_string_long(ret), -1)); } 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 */ + 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); + /* Prevent I/O while callback is in progress */ + /* statePtr->flags |= TLS_TCL_CALLBACK; */ - 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. */ + /* statePtr->flags &= ~(TLS_TCL_CALLBACK); */ + return(ok); /* By default, leave verification unchanged. */ } /* *------------------------------------------------------------------- * * Tls_Error -- * - * Calls callback with $fd and $msg - so the callback can decide - * what to do with errors. + * Calls callback with list of errors. * * Side effects: * The err field of the currently operative State is set * to a string describing the SSL negotiation failure reason + * *------------------------------------------------------------------- */ void Tls_Error(State *statePtr, char *msg) { Tcl_Interp *interp = statePtr->interp; - Tcl_Obj *cmdPtr; - int code; - - dprintf("Called"); - - if (msg && *msg) { - Tcl_SetErrorCode(interp, "SSL", msg, (char *)NULL); - } else { - msg = Tcl_GetStringFromObj(Tcl_GetObjResult(interp), NULL); - } + Tcl_Obj *cmdPtr, *listPtr; + unsigned long err; statePtr->err = msg; - if (statePtr->callback == (Tcl_Obj*)NULL) { - char buf[BUFSIZ]; - sprintf(buf, "SSL channel \"%s\": error: %s", - Tcl_GetChannelName(statePtr->self), msg); - Tcl_SetResult(interp, buf, TCL_VOLATILE); -#if (TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION < 6) - Tcl_BackgroundError(interp); -#else - Tcl_BackgroundException(interp, TCL_ERROR); -#endif + dprintf("Called"); + + if (statePtr->callback == (Tcl_Obj*)NULL) return; - } + + /* Create command to eval */ 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)); + if (msg != NULL) { + Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj(msg, -1)); + /* Tcl_SetErrorCode(interp, "SSL", msg, (char *)NULL); */ - Tcl_Preserve((ClientData) interp); - Tcl_Preserve((ClientData) statePtr); + } else if ((msg = Tcl_GetStringFromObj(Tcl_GetObjResult(interp), NULL)) != NULL) { + Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj(msg, -1)); + } else { + listPtr = Tcl_NewListObj(0, NULL); + while ((err = ERR_get_error()) != 0) { + Tcl_ListObjAppendElement(interp, listPtr, Tcl_NewStringObj(ERR_reason_error_string(err), -1)); + } + Tcl_ListObjAppendElement(interp, cmdPtr, listPtr); + } + + /* 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); } /* *------------------------------------------------------------------- * @@ -348,15 +352,19 @@ * * Write received key data to log file. * * Side effects: * none + * *------------------------------------------------------------------- */ void KeyLogCallback(const SSL *ssl, const char *line) { char *str = getenv(SSLKEYLOGFILE); FILE *fd; + + dprintf("Called"); + if (str) { fd = fopen(str, "a"); fprintf(fd, "%s\n",line); fclose(fd); } @@ -368,10 +376,11 @@ * Password Callback -- * * Called when a password is needed to unpack RSA and PEM keys. * Evals any bound password script and returns the result as * the password string. + * *------------------------------------------------------------------- */ static int PasswordCallback(char *buf, int size, int verify, void *udata) { State *statePtr = (State *) udata; @@ -379,10 +388,11 @@ Tcl_Obj *cmdPtr; int code; dprintf("Called"); + /* If no callback, use default callback */ if (statePtr->password == NULL) { if (Tcl_EvalEx(interp, "tls::password", -1, TCL_EVAL_GLOBAL) == TCL_OK) { char *ret = (char *) Tcl_GetStringResult(interp); strncpy(buf, ret, (size_t) size); return (int)strlen(ret); @@ -389,15 +399,17 @@ } else { return -1; } } + /* Create command to eval */ 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 +461,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 +472,11 @@ return SSL_TLSEXT_ERR_OK; } else if (ssl == NULL) { return SSL_TLSEXT_ERR_NOACK; } + /* Create command to eval */ cmdPtr = Tcl_DuplicateObj(statePtr->callback); Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj("session", -1)); /* Session id */ session_id = SSL_SESSION_get_id(session, &ulen); @@ -476,35 +488,25 @@ /* 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 -- + * ALPN Callback for Servers and NPN Callback for Clients -- * - * Perform server-side protocol (http/1.1, h2, h3, etc.) selection for the - * incoming connection. Called after Hello and server callbacks + * 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. * * Results: * None * * Side effects: @@ -527,55 +529,96 @@ Tcl_Obj *cmdPtr; int code, res; dprintf("Called"); - if (statePtr->callback == (Tcl_Obj*)NULL) { - return SSL_TLSEXT_ERR_OK; - } else if (ssl == NULL) { + if (ssl == NULL || arg == NULL) { return SSL_TLSEXT_ERR_NOACK; } /* 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 first client protocol used */ + /* OPENSSL_NPN_NO_OVERLAP = No overlap, so use first item from client protocol list */ res = SSL_TLSEXT_ERR_NOACK; } - cmdPtr = Tcl_DuplicateObj(statePtr->callback); + if (statePtr->vcmd == (Tcl_Obj*)NULL) { + return res; + } + + /* Create command to eval */ + 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 Next Protocol Negotiation (NPN) in ServerHello -- + * + * called when a TLS server needs a list of supported protocols for Next + * Protocol Negotiation. + * + * Results: + * None + * + * Side effects: + * + * Return codes: + * SSL_TLSEXT_ERR_OK: NPN protocol selected. The connection continues. + * SSL_TLSEXT_ERR_NOACK: NPN protocol not selected. The connection continues. + * + *------------------------------------------------------------------- + */ +#ifdef USE_NPN +static int +NPNCallback(const SSL *ssl, const unsigned char **out, unsigned int *outlen, void *arg) { + State *statePtr = (State*)arg; + + dprintf("Called"); + + if (ssl == NULL || arg == NULL) { + return SSL_TLSEXT_ERR_NOACK; + } + + /* Set protocols list */ + if (statePtr->protos != NULL) { + *out = statePtr->protos; + *outlen = statePtr->protos_len; + } else { + *out = NULL; + *outlen = 0; + return SSL_TLSEXT_ERR_NOACK; + } + return SSL_TLSEXT_ERR_OK; +} +#endif + +/* + *------------------------------------------------------------------- + * * SNI Callback for Servers -- * - * Perform server-side SNI hostname selection after receiving SNI header. - * Called after hello callback but before ALPN callback. + * Perform server-side SNI hostname selection after receiving SNI extension + * in Client Hello. Called after hello callback but before ALPN callback. * * Results: * None * * Side effects: @@ -584,11 +627,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. * *------------------------------------------------------------------- */ @@ -595,144 +638,147 @@ 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 (statePtr->callback == (Tcl_Obj*)NULL) { - return SSL_TLSEXT_ERR_OK; - } else if (ssl == NULL) { + if (ssl == NULL || arg == NULL) { + return SSL_TLSEXT_ERR_NOACK; + } + + /* Only works for TLS 1.2 and earlier */ + servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name); + if (!servername || servername[0] == '\0') { return SSL_TLSEXT_ERR_NOACK; } - servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name); - if (!servername || servername[0] == '\0') { - return SSL_TLSEXT_ERR_NOACK; + if (statePtr->vcmd == (Tcl_Obj*)NULL) { + return SSL_TLSEXT_ERR_OK; } - cmdPtr = Tcl_DuplicateObj(statePtr->callback); + /* Create command to eval */ + 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) { + } 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) { - return SSL_CLIENT_HELLO_ERROR; + *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) { - return SSL_CLIENT_HELLO_ERROR; + *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) { - return SSL_CLIENT_HELLO_ERROR; + *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) { - return SSL_CLIENT_HELLO_ERROR; + *alert = SSL_R_TLSV1_ALERT_INTERNAL_ERROR; + return SSL_CLIENT_HELLO_ERROR; } len = (*(p++) << 8); len += *(p++); if (len + 2 > remaining) { - return SSL_CLIENT_HELLO_ERROR; + *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 */ + 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 */ /********************/ @@ -827,11 +873,11 @@ #if defined(NO_TLS1_3) || defined(OPENSSL_NO_TLS1_3) Tcl_AppendResult(interp, protocols[index], ": protocol not supported", NULL); return TCL_ERROR; #else ctx = SSL_CTX_new(TLS_method()); - SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION); + SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION); SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION); break; #endif default: break; @@ -918,26 +964,28 @@ if (objc != 1) { Tcl_WrongNumArgs(interp, 1, objv, ""); return TCL_ERROR; } + + ERR_clear_error(); objPtr = Tcl_NewListObj(0, NULL); #if OPENSSL_VERSION_NUMBER < 0x10100000L && !defined(NO_SSL2) && !defined(OPENSSL_NO_SSL2) Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj(protocols[TLS_SSL2], -1)); #endif -#if !defined(NO_SSL3) && !defined(OPENSSL_NO_SSL3) +#if !defined(NO_SSL3) && !defined(OPENSSL_NO_SSL3) && !defined(OPENSSL_NO_SSL3_METHOD) Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj(protocols[TLS_SSL3], -1)); #endif -#if !defined(NO_TLS1) && !defined(OPENSSL_NO_TLS1) +#if !defined(NO_TLS1) && !defined(OPENSSL_NO_TLS1) && !defined(OPENSSL_NO_TLS1_METHOD) Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj(protocols[TLS_TLS1], -1)); #endif -#if !defined(NO_TLS1_1) && !defined(OPENSSL_NO_TLS1_1) +#if !defined(NO_TLS1_1) && !defined(OPENSSL_NO_TLS1_1) && !defined(OPENSSL_NO_TLS1_1_METHOD) Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj(protocols[TLS_TLS1_1], -1)); #endif -#if !defined(NO_TLS1_2) && !defined(OPENSSL_NO_TLS1_2) +#if !defined(NO_TLS1_2) && !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_TLS1_2_METHOD) Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj(protocols[TLS_TLS1_2], -1)); #endif #if !defined(NO_TLS1_3) && !defined(OPENSSL_NO_TLS1_3) Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj(protocols[TLS_TLS1_3], -1)); #endif @@ -974,10 +1022,12 @@ if (objc != 2) { Tcl_WrongNumArgs(interp, 1, objv, "channel"); return(TCL_ERROR); } + + ERR_clear_error(); chan = Tcl_GetChannel(interp, Tcl_GetStringFromObj(objv[1], NULL), NULL); if (chan == (Tcl_Channel) NULL) { return(TCL_ERROR); } @@ -1044,10 +1094,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; @@ -1093,10 +1144,12 @@ if (objc < 2) { Tcl_WrongNumArgs(interp, 1, objv, "channel ?options?"); return TCL_ERROR; } + + ERR_clear_error(); chan = Tcl_GetChannel(interp, Tcl_GetStringFromObj(objv[1], NULL), NULL); if (chan == (Tcl_Channel) NULL) { return TCL_ERROR; } @@ -1108,46 +1161,48 @@ char *opt = Tcl_GetStringFromObj(objv[idx], NULL); if (opt[0] != '-') break; + OPTOBJ("-alpn", alpn); OPTSTR("-cadir", CAdir); OPTSTR("-cafile", CAfile); + OPTBYTE("-cert", cert, cert_len); OPTSTR("-certfile", certfile); OPTSTR("-cipher", ciphers); OPTSTR("-ciphers", ciphers); OPTSTR("-ciphersuites", ciphersuites); OPTOBJ("-command", script); OPTSTR("-dhparams", DHparams); + OPTBYTE("-key", key, key_len); OPTSTR("-keyfile", keyfile); OPTSTR("-model", model); OPTOBJ("-password", password); OPTBOOL("-post_handshake", post_handshake); - OPTBOOL("-require", require); OPTBOOL("-request", request); + OPTBOOL("-require", require); 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); - OPTBYTE("-cert", cert, cert_len); - OPTBYTE("-key", key, key_len); + OPTOBJ("-validatecommand", vcmd); + OPTOBJ("-vcmd", vcmd); - 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, -post_handshake, -request, -require, -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; - if (request && post_handshake) verify |= SSL_VERIFY_POST_HANDSHAKE; - if (verify == 0) verify = SSL_VERIFY_NONE; + if (request) verify |= SSL_VERIFY_CLIENT_ONCE | SSL_VERIFY_PEER; + if (request && require) verify |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT; + if (request && post_handshake) verify |= SSL_VERIFY_POST_HANDSHAKE; + if (verify == 0) verify = SSL_VERIFY_NONE; proto |= (ssl2 ? TLS_PROTO_SSL2 : 0); proto |= (ssl3 ? TLS_PROTO_SSL3 : 0); proto |= (tls1 ? TLS_PROTO_TLS1 : 0); proto |= (tls1_1 ? TLS_PROTO_TLS1_1 : 0); @@ -1189,10 +1244,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); @@ -1265,23 +1329,24 @@ 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 */ + /* Per RFC 6066, hostname is a ASCII encoded string. */ 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; - } + Tls_Free((char *) statePtr); + return TCL_ERROR; + } /* Configure server host name checks in the SSL client. Set DNS hostname to name for peer certificate checks. SSL_set1_host has limitations. */ if (!SSL_add1_host(statePtr->ssl, servername)) { Tcl_AppendResult(interp, "setting DNS host name failed", (char *) NULL); - Tls_Free((char *) statePtr); - return TCL_ERROR; + Tls_Free((char *) statePtr); + return TCL_ERROR; } } /* Resume session id */ if (session_id && strlen(session_id) <= SSL_MAX_SID_CTX_LENGTH) { @@ -1292,11 +1357,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; @@ -1346,40 +1411,58 @@ /* * 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()); if (server) { /* Server callbacks */ - SSL_CTX_set_alpn_select_cb(statePtr->ctx, ALPNCallback, (void *)statePtr); SSL_CTX_set_tlsext_servername_arg(statePtr->ctx, (void *)statePtr); SSL_CTX_set_tlsext_servername_callback(statePtr->ctx, SNICallback); SSL_CTX_set_client_hello_cb(statePtr->ctx, HelloCallback, (void *)statePtr); + if (statePtr->protos != NULL) { + SSL_CTX_set_alpn_select_cb(statePtr->ctx, ALPNCallback, (void *)statePtr); +#ifdef USE_NPN + if (tls1_2 == 0 && tls1_3 == 0) { + SSL_CTX_set_next_protos_advertised_cb(statePtr->ctx, NPNCallback, (void *)statePtr); + } +#endif + } /* Enable server to send cert request after handshake (TLS 1.3 only) */ + /* A write operation must take place for the Certificate Request to be + sent to the client, this can be done with SSL_do_handshake(). */ if (request && post_handshake) { SSL_verify_client_post_handshake(statePtr->ssl); } + /* Set server mode */ statePtr->flags |= TLS_TCL_SERVER; SSL_set_accept_state(statePtr->ssl); } else { + /* Client callbacks */ +#ifdef USE_NPN + if (statePtr->protos != NULL && tls1_2 == 0 && tls1_3 == 0) { + SSL_CTX_set_next_proto_select_cb(statePtr->ctx, ALPNCallback, (void *)statePtr); + } +#endif + /* Session caching */ SSL_CTX_set_session_cache_mode(statePtr->ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE); SSL_CTX_sess_set_new_cb(statePtr->ctx, SessionCallback); /* Enable post handshake Authentication extension. TLS 1.3 only, not http/2. */ if (request && post_handshake) { SSL_set_post_handshake_auth(statePtr->ssl, 1); } + /* Set client mode */ SSL_set_connect_state(statePtr->ssl); } SSL_set_bio(statePtr->ssl, statePtr->p_bio, statePtr->p_bio); BIO_set_ssl(statePtr->bio, statePtr->ssl, BIO_NOCLOSE); @@ -1566,12 +1649,12 @@ #endif break; } ERR_clear_error(); + ctx = SSL_CTX_new(method); - if (!ctx) { return(NULL); } if (getenv(SSLKEYLOGFILE)) { @@ -1592,24 +1675,24 @@ SSL_CTX_set_app_data(ctx, (void*)interp); /* remember the interpreter */ SSL_CTX_set_options(ctx, SSL_OP_ALL); /* all SSL bug workarounds */ SSL_CTX_set_options(ctx, off); /* disable protocol versions */ #if OPENSSL_VERSION_NUMBER < 0x10101000L - SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY); /* handle new handshakes in background */ + SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY); /* handle new handshakes in background. On by default in OpenSSL 1.1.1. */ #endif SSL_CTX_sess_set_cache_size(ctx, 128); /* Set user defined ciphers, cipher suites, and security level */ if ((ciphers != NULL) && !SSL_CTX_set_cipher_list(ctx, ciphers)) { - Tcl_AppendResult(interp, "Set ciphers failed: No valid ciphers", (char *) NULL); - SSL_CTX_free(ctx); - return NULL; + Tcl_AppendResult(interp, "Set ciphers failed: No valid ciphers", (char *) NULL); + SSL_CTX_free(ctx); + return NULL; } if ((ciphersuites != NULL) && !SSL_CTX_set_ciphersuites(ctx, ciphersuites)) { - Tcl_AppendResult(interp, "Set cipher suites failed: No valid ciphers", (char *) NULL); - SSL_CTX_free(ctx); - return NULL; + Tcl_AppendResult(interp, "Set cipher suites failed: No valid ciphers", (char *) NULL); + SSL_CTX_free(ctx); + return NULL; } /* Set security level */ if (level > -1 && level < 6) { /* SSL_set_security_level */ @@ -1822,10 +1905,12 @@ Tcl_AppendResult(interp, "bad channel \"", Tcl_GetChannelName(chan), "\": not a TLS channel", NULL); return TCL_ERROR; } statePtr = (State *) Tcl_GetChannelInstanceData(chan); + + /* Get certificate for peer or self */ if (objc == 2) { peer = SSL_get_peer_certificate(statePtr->ssl); } else { peer = SSL_get_certificate(statePtr->ssl); } @@ -1850,11 +1935,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, @@ -1975,11 +2060,11 @@ Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj("bits", -1)); Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewIntObj(bits)); Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj("secret_bits", -1)); Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewIntObj(alg_bits)); /* alg_bits is actual key secret bits. If use bits and secret (algorithm) bits differ, - the rest of the bits are fixed, i.e. for limited export ciphers (bits < 56) */ + the rest of the bits are fixed, i.e. for limited export ciphers (bits < 56) */ Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj("min_version", -1)); Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj(SSL_CIPHER_get_version(cipher), -1)); /* Get OpenSSL-specific ID, not IANA ID */ Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj("id", -1)); @@ -2002,10 +2087,17 @@ /* Report the selected protocol as a result of the ALPN negotiation */ SSL_SESSION_get0_alpn_selected(session, &proto, &len2); Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj("alpn", -1)); Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj((char *)proto, (int) len2)); + + /* Report the selected protocol as a result of the NPN negotiation */ +#ifdef USE_NPN + SSL_get0_next_proto_negotiated(ssl, &proto, &ulen); + Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj("npn", -1)); + Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj((char *)proto, (int) ulen)); +#endif /* Resumable session */ Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj("resumable", -1)); Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewIntObj(SSL_SESSION_is_resumable(session))); @@ -2137,10 +2229,12 @@ return TCL_ERROR; } if (Tcl_GetIndexFromObj(interp, objv[1], commands, "command", 0,&cmd) != TCL_OK) { return TCL_ERROR; } + + ERR_clear_error(); isStr = (cmd == C_STRREQ); switch ((enum command) cmd) { case C_REQ: case C_STRREQ: { @@ -2406,10 +2500,14 @@ } if (statePtr->password) { Tcl_DecrRefCount(statePtr->password); statePtr->password = NULL; } + if (statePtr->vcmd) { + Tcl_DecrRefCount(statePtr->vcmd); + statePtr->vcmd = NULL; + } dprintf("Returning"); } /* @@ -2516,39 +2614,39 @@ #if defined(OPENSSL_THREADS) && defined(TCL_THREADS) size_t num_locks; #endif if (uninitialize) { - if (!initialized) { - dprintf("Asked to uninitialize, but we are not initialized"); - - return(TCL_OK); - } - - dprintf("Asked to uninitialize"); - -#if defined(OPENSSL_THREADS) && defined(TCL_THREADS) - Tcl_MutexLock(&init_mx); - - if (locks) { - free(locks); - locks = NULL; - locksCount = 0; - } -#endif - initialized = 0; - -#if defined(OPENSSL_THREADS) && defined(TCL_THREADS) - Tcl_MutexUnlock(&init_mx); -#endif - - return(TCL_OK); + if (!initialized) { + dprintf("Asked to uninitialize, but we are not initialized"); + + return(TCL_OK); + } + + dprintf("Asked to uninitialize"); + +#if defined(OPENSSL_THREADS) && defined(TCL_THREADS) + Tcl_MutexLock(&init_mx); + + if (locks) { + free(locks); + locks = NULL; + locksCount = 0; + } +#endif + initialized = 0; + +#if defined(OPENSSL_THREADS) && defined(TCL_THREADS) + Tcl_MutexUnlock(&init_mx); +#endif + + return(TCL_OK); } if (initialized) { - dprintf("Called, but using cached value"); - return(status); + dprintf("Called, but using cached value"); + return(status); } dprintf("Called"); #if defined(OPENSSL_THREADS) && defined(TCL_THREADS) Index: generic/tlsIO.c ================================================================== --- generic/tlsIO.c +++ generic/tlsIO.c @@ -16,10 +16,11 @@ * SSLtcl (Peter Antman) * */ #include "tlsInt.h" +#include /* * Forward declarations */ static void TlsChannelHandlerTimer(ClientData clientData); @@ -34,12 +35,13 @@ * * TlsBlockModeProc -- * * This procedure is invoked by the generic IO level * to set blocking and nonblocking modes + * * Results: - * 0 if successful, errno when failed. + * 0 if successful or POSIX error code if failed. * * Side effects: * Sets the device into blocking or nonblocking mode. * *------------------------------------------------------------------- @@ -65,11 +67,11 @@ * is closed. * * Note: we leave the underlying socket alone, is this right? * * Results: - * 0 if successful, the value of Tcl_GetErrno() if failed. + * 0 if successful or POSIX error code if failed. * * Side effects: * Closes the socket of the channel. * *------------------------------------------------------------------- @@ -85,41 +87,48 @@ /* Interp is unused. */ interp = interp; } -static int TlsCloseProc2(ClientData instanceData, Tcl_Interp *interp, int flags) { +static int TlsCloseProc2(ClientData instanceData, /* The socket state. */ + Tcl_Interp *interp, /* For errors - can be NULL. */ + int flags) /* Flags to close read and/or write side of channel */ +{ + State *statePtr = (State *) instanceData; + + dprintf("TlsCloseProc2(%p)", (void *) statePtr); + if ((flags & (TCL_CLOSE_READ|TCL_CLOSE_WRITE)) == 0) { return TlsCloseProc(instanceData, interp); } return EINVAL; } /* *------------------------------------------------------* * - * Tls_WaitForConnect -- + * Tls_WaitForConnect -- * - * Side effects: - * Issues SSL_accept or SSL_connect + * Result: + * 0 if successful, -1 if failed. * - * Result: - * None. + * Side effects: + * Issues SSL_accept or SSL_connect * *------------------------------------------------------* */ int Tls_WaitForConnect(State *statePtr, int *errorCodePtr, int handshakeFailureIsPermanent) { unsigned long backingError; int err, rc; int bioShouldRetry; + *errorCodePtr = 0; dprintf("WaitForConnect(%p)", (void *) statePtr); dprintFlags(statePtr); if (!(statePtr->flags & TLS_TCL_INIT)) { dprintf("Tls_WaitForConnect called on already initialized channel -- returning with immediate success"); - *errorCodePtr = 0; return(0); } if (statePtr->flags & TLS_TCL_HANDSHAKE_FAILED) { /* @@ -193,19 +202,19 @@ dprintf("We have either completely established the session or completely failed it -- there is no more need to ever retry it though"); break; } - *errorCodePtr = EINVAL; - switch (rc) { case SSL_ERROR_NONE: /* The connection is up, we are done here */ dprintf("The connection is up"); + *errorCodePtr = 0; break; case SSL_ERROR_ZERO_RETURN: - dprintf("SSL_ERROR_ZERO_RETURN: Connect returned an invalid value...") + dprintf("SSL_ERROR_ZERO_RETURN: Connect returned an invalid value..."); + *errorCodePtr = EINVAL; return(-1); case SSL_ERROR_SYSCALL: backingError = ERR_get_error(); if (backingError == 0 && err == 0) { @@ -276,13 +285,12 @@ * * This procedure is invoked by the generic IO level * to read input from a SSL socket based channel. * * Results: - * The number of bytes read is returned or -1 on error. An output - * argument contains the POSIX error code on error, or zero if no - * error occurred. + * Returns the number of bytes read or -1 on error. Sets errorCodePtr + * to a POSIX error code if an error occurred, or 0 if none. * * Side effects: * Reads input from the input device of the channel. * *------------------------------------------------------------------- @@ -306,10 +314,11 @@ dprintf("Calling Tls_WaitForConnect"); tlsConnect = Tls_WaitForConnect(statePtr, errorCodePtr, 0); if (tlsConnect < 0) { dprintf("Got an error waiting to connect (tlsConnect = %i, *errorCodePtr = %i)", tlsConnect, *errorCodePtr); + Tls_Error(statePtr, strerror(*errorCodePtr)); bytesRead = -1; if (*errorCodePtr == ECONNRESET) { dprintf("Got connection reset"); /* Soft EOF */ @@ -393,10 +402,13 @@ *errorCodePtr = 0; bytesRead = 0; break; } + if (*errorCodePtr < 0) { + Tls_Error(statePtr, strerror(*errorCodePtr)); + } dprintf("Input(%d) -> %d [%d]", bufSize, bytesRead, *errorCodePtr); return(bytesRead); } /* @@ -406,12 +418,12 @@ * * This procedure is invoked by the generic IO level * to write output to a SSL socket based channel. * * Results: - * The number of bytes written is returned. An output argument is - * set to a POSIX error code if an error occurred, or zero. + * Returns the number of bytes written or -1 on error. Sets errorCodePtr + * to a POSIX error code if an error occurred, or 0 if none. * * Side effects: * Writes output on the output device of the channel. * *------------------------------------------------------------------- @@ -436,10 +448,11 @@ dprintf("Calling Tls_WaitForConnect"); tlsConnect = Tls_WaitForConnect(statePtr, errorCodePtr, 1); if (tlsConnect < 0) { dprintf("Got an error waiting to connect (tlsConnect = %i, *errorCodePtr = %i)", tlsConnect, *errorCodePtr); + Tls_Error(statePtr, strerror(*errorCodePtr)); written = -1; if (*errorCodePtr == ECONNRESET) { dprintf("Got connection reset"); /* Soft EOF */ @@ -536,29 +549,30 @@ default: dprintf(" unknown err: %d", err); break; } + if (*errorCodePtr < 0) { + Tls_Error(statePtr, strerror(*errorCodePtr)); + } dprintf("Output(%d) -> %d", toWrite, written); return(written); } /* *------------------------------------------------------------------- * * TlsSetOptionProc -- * - * Computes an option value for a SSL socket based channel, or a + * Sets an option value for a SSL socket based channel, or a * list of all options and their values. * * Results: - * A standard Tcl result. The value of the specified option or a - * list of all options and their values is returned in the - * supplied DString. + * TCL_OK if successful or TCL_ERROR if failed. * * Side effects: - * None. + * Updates channel option to new value. * *------------------------------------------------------------------- */ static int TlsSetOptionProc(ClientData instanceData, /* Socket state. */ @@ -582,24 +596,24 @@ return TCL_OK; } /* * Request for a specific option has to fail, we don't have any. */ - return TCL_ERROR; + return Tcl_BadChannelOption(interp, optionName, ""); } /* *------------------------------------------------------------------- * * TlsGetOptionProc -- * - * Computes an option value for a SSL socket based channel, or a + * Gets an option value for a SSL socket based channel, or a * list of all options and their values. * * Results: * A standard Tcl result. The value of the specified option or a - * list of all options and their values is returned in the + * list of all options and their values is returned in the * supplied DString. * * Side effects: * None. * @@ -608,30 +622,30 @@ static int TlsGetOptionProc(ClientData instanceData, /* Socket state. */ Tcl_Interp *interp, /* For errors - can be NULL. */ const char *optionName, /* Name of the option to retrieve the value for, or * NULL to get all options and their values. */ - Tcl_DString *dsPtr) /* Where to store the computed value initialized by caller. */ + Tcl_DString *optionValue) /* Where to store the computed value initialized by caller. */ { State *statePtr = (State *) instanceData; Tcl_Channel downChan = Tls_GetParent(statePtr, TLS_TCL_FASTPATH); Tcl_DriverGetOptionProc *getOptionProc; getOptionProc = Tcl_ChannelGetOptionProc(Tcl_GetChannelType(downChan)); if (getOptionProc != NULL) { - return (*getOptionProc)(Tcl_GetChannelInstanceData(downChan), interp, optionName, dsPtr); + return (*getOptionProc)(Tcl_GetChannelInstanceData(downChan), interp, optionName, optionValue); } else if (optionName == (char*) NULL) { /* * Request is query for all options, this is ok. */ return TCL_OK; } /* * Request for a specific option has to fail, we don't have any. */ - return TCL_ERROR; + return Tcl_BadChannelOption(interp, optionName, ""); } /* *------------------------------------------------------------------- * @@ -648,12 +662,12 @@ * *------------------------------------------------------------------- */ static void TlsWatchProc(ClientData instanceData, /* The socket state. */ - int mask) /* Events of interest; an OR-ed combination of - * TCL_READABLE, TCL_WRITABLE and TCL_EXCEPTION. */ + int mask) /* Events of interest; an OR-ed combination of + * TCL_READABLE, TCL_WRITABLE and TCL_EXCEPTION. */ { Tcl_Channel downChan; State *statePtr = (State *) instanceData; dprintf("TlsWatchProc(0x%x)", mask); @@ -699,16 +713,16 @@ statePtr->timer = (Tcl_TimerToken) NULL; } if ((mask & TCL_READABLE) && ((Tcl_InputBuffered(statePtr->self) > 0) || (BIO_ctrl_pending(statePtr->bio) > 0))) { - /* - * There is interest in readable events and we actually have - * data waiting, so generate a timer to flush that. - */ - dprintf("Creating a new timer since data appears to be waiting"); - statePtr->timer = Tcl_CreateTimerHandler(TLS_TCL_DELAY, TlsChannelHandlerTimer, (ClientData) statePtr); + /* + * There is interest in readable events and we actually have + * data waiting, so generate a timer to flush that. + */ + dprintf("Creating a new timer since data appears to be waiting"); + statePtr->timer = Tcl_CreateTimerHandler(TLS_TCL_DELAY, TlsChannelHandlerTimer, (ClientData) statePtr); } } /* *------------------------------------------------------------------- @@ -717,18 +731,21 @@ * * Called from Tcl_GetChannelFile to retrieve o/s file handler * from the SSL socket based channel. * * Results: - * The appropriate Tcl_File or NULL if not present. + * The appropriate Tcl_File handle or NULL if none. * * Side effects: * None. * *------------------------------------------------------------------- */ -static int TlsGetHandleProc(ClientData instanceData, int direction, ClientData *handlePtr) { +static int TlsGetHandleProc(ClientData instanceData, /* Socket state. */ + int direction, /* TCL_READABLE or TCL_WRITABLE */ + ClientData *handlePtr) /* Handle associated with the channel */ +{ State *statePtr = (State *) instanceData; return(Tcl_GetChannelHandle(Tls_GetParent(statePtr, TLS_TCL_FASTPATH), direction, handlePtr)); } @@ -739,18 +756,21 @@ * * Handler called by Tcl to inform us of activity * on the underlying channel. * * Results: - * None. + * Type of event or 0 if failed * * Side effects: * May process the incoming event by itself. * *------------------------------------------------------------------- */ -static int TlsNotifyProc(ClientData instanceData, int mask) { +static int TlsNotifyProc(ClientData instanceData, /* Socket state. */ + int mask) /* type of event that occurred: + * OR-ed combination of TCL_READABLE or TCL_WRITABLE */ +{ State *statePtr = (State *) instanceData; int errorCode; /* * An event occurred in the underlying channel. This @@ -775,10 +795,11 @@ } dprintf("Calling Tls_WaitForConnect"); errorCode = 0; if (Tls_WaitForConnect(statePtr, &errorCode, 1) < 0) { + Tls_Error(statePtr, strerror(errorCode)); if (errorCode == EAGAIN) { dprintf("Async flag could be set (didn't check) and errorCode == EAGAIN: Returning 0"); return 0; } @@ -811,11 +832,11 @@ * None. * *------------------------------------------------------* */ static void -TlsChannelHandler (ClientData clientData, int mask) { +TlsChannelHandler(ClientData clientData, int mask) { State *statePtr = (State *) clientData; dprintf("HANDLER(0x%x)", mask); Tcl_Preserve((ClientData)statePtr); 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 @@ -30,10 +30,11 @@ variable socketOptionRules { {0 -async sopts 0} {* -myaddr sopts 1} {0 -myport sopts 1} {* -type sopts 1} + {* -alpn iopts 1} {* -cadir iopts 1} {* -cafile iopts 1} {* -cert iopts 1} {* -certfile iopts 1} {* -cipher iopts 1} @@ -41,23 +42,26 @@ {* -command iopts 1} {* -dhparams iopts 1} {* -key iopts 1} {* -keyfile iopts 1} {* -password iopts 1} + {* -post_handshake iopts 1} {* -request iopts 1} {* -require iopts 1} {* -securitylevel iopts 1} {* -autoservername discardOpts 1} + {* -server iopts 1} {* -servername iopts 1} {* -session_id iopts 1} - {* -alpn iopts 1} {* -ssl2 iopts 1} {* -ssl3 iopts 1} {* -tls1 iopts 1} {* -tls1.1 iopts 1} {* -tls1.2 iopts 1} {* -tls1.3 iopts 1} + {* -validatecommand iopts 1} + {* -vcmd iopts 1} } # tls::socket and tls::init options as a humane readable string variable socketOptionsNoServer variable socketOptionsServer @@ -307,10 +311,11 @@ error $err $::errorInfo $::errorCode } else { log 2 "tls::_accept - called \"$callback\" succeeded" } } + # # Sample callback for hooking: - # # error # verify @@ -320,16 +325,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 +396,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