HTTPServer Component
Properties Methods Events Configuration Settings Errors
The HTTPServer component offers server-side functionality for the HTTP/HTTPS protocols.
Syntax
TsbxHTTPServer
Remarks
Both plain (HTTP) and secure (HTTPS) connection types are supported.
Follow the below steps to set up and run the server in your code:
- Create an instance of the server component and set up the license, if assumed by the edition you are using:
var server =
new
Httpserver();
server.RuntimeLicense =
"5342..0000"
;
- Set up the listening port (make sure it is not in use):
server.Port = 443;
- Tell the component whether TLS connections should be enforced:
server.UseTLS =
true
;
// set to false to disable TLS and server plain HTTP requests
- Set up the document root (a directory where all static files are kept):
server.DocumentRoot =
"c:\\inetpub\\mywebserver"
;
- (TLS-enabled servers only) Configure TLS parameters. The exact way of doing that may vary for different scenarios and security requirements.
At the very least you need to set up the certificate chain that the server will use to authenticate itself to connecting clients. If you don't,
the component will generate a dummy certificate itself, however, that certificate is unlikely to pass any security requirements.
It will let you accept test connections though.
Below is an example of tuning up the TLS parameters of the server:
// *** Switching TLS on and enabling the implicit mode ***
server.UseTLS =
true
;
server.TLSSettings.TLSMode = smImplicitTLS;
// this must be implicit for HTTPS
// Loading the certificate chain
var mgr =
new
Certificatemanager();
mgr.RuntimeLicense =
"5342..0000"
;
// *** Setting up the host certificate ***
// - it should be issued in the name that matches the hostname (such as domain.com) or its IP address (1.2.3.4),
// - it must have an associated private key - so likely is provided in PFX or PEM format.
mgr.ImportFromFile(
"CertTLSServer.pfx"
,
"password"
);
server.ServerCertificates.Add(mgr.Certificate);
// The CA certificate: this is to help connecting clients validate the chain.
mgr.ImportFromFile(
"CertCA.cer"
,
""
);
server.ServerCertificates.Add(mgr.Certificate);
// *** Adjusting finer-grained TLS settings ***
// - session resumption (allows for faster handshakes for connections from the same origin)
server.TLSSettings.UseSessionResumption =
true
;
// - secure configuration
server.TLSSettings.BaseConfiguration = stpcHighlySecure;
// - disabling a ciphersuite we dislike (just because we can):
server.TLSSettings.Ciphersuites =
"-DHE_RSA_AES128_SHA"
// *** Configuring versions ***
// The default version setting at the time of writing (May 2021) is TLS 1.2 and TLS 1.3,
// but that may change in future versions. The following tune-up additionally activates TLS 1.1 and TLS 1.0,
// which weakens security, but may be necessary to accept connections from older clients:
server.TLSSettings.Versions = csbTLS1 | csbTLS11 | csbTLS12 | csbTLS13;
- Now that your server has been fully set up, activate it:
server.Start();
- Once the Start call completes, your server can accept connections from clients. Each accepted connection runs in a separate thread, not interfering with each other
or your own threads. The server communicates its ongoing activities to your application by throwing events. The lower-level events deal with the underlying network
connections:
- Accept notifies you about a new incoming connection. This event lets you accept or reject it.
- Connect notifies your code of an accepted connection. This event introduces a ConnectionID, a unique identifier that you can use to track the connection throughout its lifetime.
- Disconnect notifies you that a connection has been closed.
- TLSEstablished and TLSShutdown let you know that a TLS layer has been activated/deactivated.
- Error reports a protocol or other error.
- CertificateValidate communicates the client authentication event to your code. To access the certificate(s) provided by the authenticating client,
pin the client and use the PinnedClientChain property to access its chain:
server.PinClient(e.ConnectionID);
e.Accept = CheckCert(server.PinnedClientChain);
- GetRequest fires when a GET request is received from a connection.
- PostRequest notifies your code about a POST request. Similar events for other HTTP request types (e.g. DELETE) are also available.
- AuthAttempt fires when a connected client tries HTTP authentication (such as basic or digest) and let you accept or reject it.
Note: every such event is thrown from the respective connection thread, so make sure you use some synchronization mechanism when dispatching the events to your UI thread - for example, by updating UI controls by sending a Window Message rather than accessing the controls directly.
- Use GetRequestStream, GetRequestString, and GetRequestHeader methods inside your GetRequest and similar event handlers to access
request parameters and content supplied by the client. Use SetResponseHeader and SetResponseString method to supply the response content:
void
serverGetRequest(
object
sender, EventArgs e)
{
e.Handled =
true
;
// telling the Httpserver object that we will supply our own content
if
(e.URI ==
"/index.html"
)
{
server.SetResponseStatus(e.ConnectionID, 200);
server.SetResponseString(e.ConnectionID,
"<html><head></head><body>Hello!</body></html>"
,
"text/html"
);
}
else
if
(e.URI ==
"/secretfile"
)
{
server.SetResponseStatus(e.ConnectionID, 200);
server.SetResponseBytes(e.ConnectionID, m_secretData,
"application/pdf"
);
}
else
if
(e.URI.StartsWith(
"/static/"
))
{
e.Handled =
false
;
// letting the server process the content and flush the file from the home directory (c:\inetpub\mywebserver)
}
else
{
Flush404Page(e.ConnectionID);
}
}
- To stop the server, call Stop:
server.Stop();
HTTPServer and SSLLabs
Qualys SSLLabs (https://www.ssllabs.com/) has been long known as a comprehensive TLS site quality checking tool. It is now a de-facto standard and a sign of good taste to aspire for the best SSLLabs test result for your web presence. SecureBlackbox developers share that effort and want to help their customers build secure TLS endpoints that can be independently endorsed by third-party evaluators like SSLLabs.Having said that, when assessing SecureBlackbox TLS-capable servers that are configured to use their default setup, you will often end up with a lower SSLLabs score than you could have. There is a simple reason for that. Being a vendor of a library used by thousands of customers, we have to find a delicate balance between security, compatibility, and keeping class contracts rolling from one product build to another. This makes the default configuration of the components not the strongest possible. To put it simple, we could easily make the default component setup bulletproof - but having done that, we would have likely ended up with hundreds of customers stuck with legacy environments (and there are a lot of them around) losing their connectivity.
If you are looking at achieving the best score at SSLLabs, please read on. The below guidance aims to help you tune up the server component in the way that should give you an A score.
First, switch your server to the highly secure base configuration:
server.TLSSettings.BaseConfiguration = stpcHighlySecure;
Some warnings will still be included in the report. One of those is related to the session resumption. It is normally shown in orange:
Session resumption (caching): No (IDs assigned but not accepted)
This literally means that the server is not configured to re-use older sessions, which may put extra computational burden on clients and itself.
Use the following setting to enable session caching:
server.TLSSettings.UseSessionResumption =
true
;
Besides, the report may show that there are some weak ciphersuites. All of those should be shown in orange (there should not be any reds; if
there are - please let us know), which means they are only relatively weak. While switching them off may affect the interoperability level of
the server, you may still want to do that. By using the below approach you can disable individual ciphersuites selectively. For example, if
the report shows that TLS_DHE_RSA_WITH_AES128_CBC_SHA256 and TLS_DHE_RSA_WITH_AES256_CBC_SHA256 are weak (because of their CBC mode), you can
disable them in the following way:
server.TLSSettings.Ciphersuites =
'-DHE_RSA_AES128_SHA256;-DHE_RSA_AES256_SHA256'
;
Property List
The following is the full list of the properties of the component with short descriptions. Click on the links for further details.
Active | Indicates whether the server is active and is listening to new connections. |
AllowKeepAlive | Enables or disables keep-alive mode. |
AuthBasic | Enables or disables basic authentication. |
AuthDigest | Enables or disables digest authentication. |
AuthDigestExpire | Specifies digest expiration time for digest authentication. |
AuthRealm | Specifies authentication realm for digest and NTLM authentication. |
BoundPort | Indicates the bound listening port. |
CompressionLevel | The default compression level to use. |
DocumentRoot | The document root of the server. |
ErrorOrigin | Indicates the endpoint where the error originates from. |
ErrorSeverity | The severity of the error that happened. |
ExternalCrypto | Provides access to external signing and DC parameters. |
HandshakeTimeout | Specifies the handshake timeout in milliseconds. |
Host | The host to bind the listening port to. |
PinnedClient | Populates the pinned client details. |
PinnedClientChain | Contains the certificate chain of the pinned client. |
Port | Specifies the port number to listen for connections on. |
PortRangeFrom | Specifies the lower limit of the listening port range for incoming connections. |
PortRangeTo | Specifies the upper limit of the listening port range for incoming connections. |
ServerCertificates | The server's TLS certificates. |
SessionTimeout | Specifies the default session timeout value in milliseconds. |
SocketSettings | Manages network connection settings. |
TempDir | The temporary path to use. |
TLSSettings | Manages TLS layer settings. |
UseChunkedTransfer | Enables chunked transfer. |
UseCompression | Enables or disables server-side compression. |
Users | Provides a list of registered users. |
UseTLS | Enables or disables the TLS requirement. |
WebsiteName | Specifies the web site name to use in the certificate. |
Method List
The following is the full list of the methods of the component with short descriptions. Click on the links for further details.
Config | Sets or retrieves a configuration setting. |
DropClient | Terminates a client connection. |
GetRequestBytes | Returns the contents of the client's HTTP request. |
GetRequestHeader | Returns a request header value. |
GetRequestStream | Returns the contents of the client's HTTP request. |
GetRequestString | Returns the contents of the client's HTTP request. |
GetRequestUsername | Returns the username for a connection. |
ListClients | Enumerates the connected clients. |
PinClient | Takes a snapshot of the connection's properties. |
SetResponseBytes | Sets a byte array to be served as a response. |
SetResponseFile | Sets a file to be served as a response. |
SetResponseHeader | Sets a response header. |
SetResponseStatus | Sets an HTTP status to be sent with the response. |
SetResponseStream | Sets a stream to be served as a response. |
SetResponseString | Sets a string to be served as a response. |
Start | Starts the server. |
Stop | Stops the server. |
Event List
The following is the full list of the events fired by the component with short descriptions. Click on the links for further details.
Accept | Reports an incoming connection. |
AuthAttempt | Fires when a connected client makes an authentication attempt. |
CertificateValidate | Fires when a client certificate needs to be validated. |
Connect | Reports an accepted connection. |
CustomRequest | Reports a request of a non-standard type (method). |
Data | Supplies a data chunk received within a POST or PUT upload. |
DeleteRequest | Reports a DELETE request. |
Disconnect | Fires to report a disconnected client. |
Error | Information about errors during data delivery. |
ExternalSign | Handles remote or external signing initiated by the server protocol. |
FileError | Reports a file access error to the application. |
GetRequest | Reports a GET request. |
HeadRequest | Reports a HEAD request. |
Notification | This event notifies the application about an underlying control flow event. |
OptionsRequest | Reports an OPTIONS request. |
PatchRequest | Reports a PATCH request. |
PostRequest | Reports a POST request. |
PutRequest | Reports a PUT request. |
TLSEstablished | Reports the setup of a TLS session. |
TLSPSK | Requests a pre-shared key for TLS-PSK. |
TLSShutdown | Reports closure of a TLS session. |
TraceRequest | Reports a TRACE request. |
Configuration Settings
The following is a list of configuration settings for the component with short descriptions. Click on the links for further details.
AllowOptionsResponseWithoutAuth | Enables unauthenticated responses to OPTIONS requests. |
ClientAuth | Enables or disables certificate-based client authentication. |
DualStack | Allows the use of ip4 and ip6 simultaneously. |
HomePage | Specifies the home page resource name. |
Host | The host to bind to. |
RequestFilter | The request string modifier. |
ServerSSLDHKeyLength | Sets the size of the TLS DHE key exchange group. |
TLSExtensions | Provides access to TLS extensions. |
WebsiteName | The website name for the TLS certificate. |
CheckKeyIntegrityBeforeUse | Enables or disable private key integrity check before use. |
CookieCaching | Specifies whether a cookie cache should be used for HTTP(S) transports. |
Cookies | Gets or sets local cookies for the component (supported for HTTPClient, RESTClient and SOAPClient only). |
DefDeriveKeyIterations | Specifies the default key derivation algorithm iteration count. |
EnableClientSideSSLFFDHE | Enables or disables finite field DHE key exchange support in TLS clients. |
GlobalCookies | Gets or sets global cookies for all the HTTP transports. |
HttpUserAgent | Specifies the user agent name to be used by all HTTP clients. |
LogDestination | Specifies the debug log destination. |
LogDetails | Specifies the debug log details to dump. |
LogFile | Specifies the debug log filename. |
LogFilters | Specifies the debug log filters. |
LogFlushMode | Specifies the log flush mode. |
LogLevel | Specifies the debug log level. |
LogMaxEventCount | Specifies the maximum number of events to cache before further action is taken. |
LogRotationMode | Specifies the log rotation mode. |
MaxASN1BufferLength | Specifies the maximal allowed length for ASN.1 primitive tag data. |
MaxASN1TreeDepth | Specifies the maximal depth for processed ASN.1 trees. |
OCSPHashAlgorithm | Specifies the hash algorithm to be used to identify certificates in OCSP requests. |
UseOwnDNSResolver | Specifies whether the client components should use own DNS resolver. |
UseSharedSystemStorages | Specifies whether the validation engine should use a global per-process copy of the system certificate stores. |
UseSystemOAEPAndPSS | Enforces or disables the use of system-driven RSA OAEP and PSS computations. |
UseSystemRandom | Enables or disables the use of the OS PRNG. |