### Lua HTTPS Request Example Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-0.6 Demonstrates how to use the `https.request` function to make an HTTPS GET request. It shows how to handle the returned values: response body, status code, headers, and status line. This example assumes a string URL is provided. ```lua local res, code, headers, status = https.request("https://www.site.com.br") ``` -------------------------------- ### Get Peer Verification State (Lua) Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-0.9 Returns the verification status of the peer's certificate chain. ```lua local verification_state = conn:getpeerverification() ``` -------------------------------- ### Get Peer Verification Status - Lua Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-1.1.0 Returns the verification status of the peer's certificate chain. ```lua local verification_status = conn:getpeerverification() print("Peer Verification:", verification_status) ``` -------------------------------- ### Get Connection Statistics (Lua) Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-0.9 Returns connection statistics including bytes received, bytes sent, and connection age in seconds. ```lua local bytes_received, bytes_sent, age = conn:getstats() ``` -------------------------------- ### Lua HTTPS Request with Table Configuration Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-0.6 Illustrates using `https.request` with a table for detailed configuration, including specifying the sink, protocol, options, and verification level. This example shows how the response body is replaced by `1` when a table configuration is used. ```lua local one, code, headers, status = https.request { url = "https://www.site.com.br", sink = ltn12.sink.file(io.stdout), protocol = "tlsv1", options = "all", verify = "none", } ``` -------------------------------- ### Get Connection Information - Lua Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-1.1.0 Returns a table of detailed information about the secure connection or a specific field's value if specified. Information includes cipher, protocol, encryption, and more. ```lua -- Get all connection info local info_table = conn:info() for key, value in pairs(info_table) do print(key, value) end -- Get specific info (e.g., cipher) local cipher = conn:info("cipher") print("Cipher:", cipher) ``` -------------------------------- ### LuaSec: Get Certificate Public Key Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-1.3.x Returns the public key associated with the certificate in PEM format. ```lua local public_key_pem = cert:pubkey() ``` -------------------------------- ### LuaSec Server TLS/SSL Communication Example Source: https://github.com/lunarmodules/luasec/wiki/Home This Lua code snippet illustrates the server-side implementation for TLS/SSL communication using LuaSec. It sets up a TCP server, accepts incoming connections, and then wraps the connection with SSL, performing a handshake to establish a secure session. The server sends a line of text back to the client over the secure channel. This example requires the 'socket' and 'ssl' modules. ```lua require("socket") require("ssl") -- TLS/SSL server parameters (omitted) local params local server = socket.tcp() server:bind("127.0.0.1", 8888) server:listen() local conn = server:accept() -- TLS/SSL initialization conn = ssl.wrap(conn, params) conn:dohandshake() -- conn:send("one line\n") conn:close() ``` -------------------------------- ### LuaSec Client TLS/SSL Communication Example Source: https://github.com/lunarmodules/luasec/wiki/Home This Lua code snippet demonstrates how to establish a secure TLS/SSL client connection using LuaSec. It wraps an existing TCP socket connection with SSL parameters and performs the necessary handshake to initiate secure communication. This example requires the 'socket' and 'ssl' modules and assumes valid parameters for SSL initialization. ```lua require("socket") require("ssl") -- TLS/SSL client parameters (omitted) local params local conn = socket.tcp() conn:connect("127.0.0.1", 8888) -- TLS/SSL initialization conn = ssl.wrap(conn, params) conn:dohandshake() -- print(conn:receive("*l")) conn:close() ``` -------------------------------- ### Get Secure Connection Info (Lua) Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-0.6 Retrieves information about the secure connection. Can return a table of all fields or a specific field's value. ```lua local info_table = conn:info() local cipher_info = conn:info('cipher') ``` -------------------------------- ### Get Connection Information Field (Lua) Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-0.9 Retrieves specific information about the SSL/TLS connection, such as cipher, protocol, or encryption details. ```lua local info_table = conn:info() local cipher_name = conn:info('cipher') print(info_table.protocol, cipher_name) ``` -------------------------------- ### Get Connection Statistics - Lua Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-1.1.0 Retrieves accounting information for a secure connection, including bytes received, bytes sent, and connection age in seconds. Useful for monitoring and bandwidth management. ```lua local bytes_received, bytes_sent, age = conn:getstats() print(string.format("Received: %d, Sent: %d, Age: %.2f seconds", bytes_received, bytes_sent, age)) ``` -------------------------------- ### Get Connection Information with conn:info Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-0.5 The conn:info function retrieves details about the secure connection. When called without arguments, it returns a table containing various security-related fields like cipher, protocol, and authentication. If a specific field name is provided, its value is returned directly. ```lua local info = conn:info() print("Cipher:", info.cipher) print("Protocol:", info.protocol) local bits = conn:info("bits") print("Key bits:", bits) ``` -------------------------------- ### Get Certificate Validity Start Date in LuaSec Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-0.5 The cert:notbefore function returns the "not before" date of an X.509 certificate. This date indicates the earliest time at which the certificate is considered valid. ```lua local valid_from = cert:notbefore() ``` -------------------------------- ### Create SSL Contexts in Lua Source: https://context7.com/lunarmodules/luasec/llms.txt Demonstrates creating SSL contexts for client and server modes using LuaSec. It shows how to specify parameters like protocol, certificates, verification options, and cipher suites. Ensure correct paths for certificate and key files. ```lua local ssl = require("ssl") local socket = require("socket") -- Create a context with client parameters local params = { mode = "client", protocol = "tlsv1_2", key = "client-key.pem", certificate = "client-cert.pem", cafile = "ca-bundle.pem", verify = {"peer", "fail_if_no_peer_cert"}, options = {"all", "no_sslv2", "no_sslv3"}, ciphers = "HIGH:!aNULL:!MD5" } local ctx, err = ssl.newcontext(params) if not ctx then print("Context creation failed: " .. err) os.exit(1) end -- Server context example local server_params = { mode = "server", protocol = "any", key = "server-key.pem", certificate = "server-cert.pem", cafile = "ca-bundle.pem", verify = {"peer", "fail_if_no_peer_cert"}, options = "all", depth = 3 -- Max certificate chain depth } local server_ctx = ssl.newcontext(server_params) ``` -------------------------------- ### LuaSec: Get Certificate Signature Name Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-1.3.x Retrieves the name of the signature algorithm used in the certificate. ```lua local signature_name = cert:getsignaturename() ``` -------------------------------- ### Get Peer Certificate Chain - Lua Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-1.1.0 Retrieves the chain of certificates presented by the peer during the TLS/SSL handshake. ```lua local cert_chain = conn:getpeerchain() print("Peer Certificate Chain:", cert_chain) ``` -------------------------------- ### conn:want Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-0.4 Sets or retrieves the desired SSL/TLS state for the connection. ```APIDOC ## conn:want ### Description Sets or retrieves the desired SSL/TLS state for the connection. This is often used to control renegotiation or specific SSL operations. ### Method `connection:want(s)` ### Parameters #### Query Parameters - **s** (string | nil) - The desired state. Common values include `"io"` (for I/O operations) or `"no"` (to indicate no specific state is wanted). ### Response #### Success Response - Returns the current desired state string if `s` is `nil`. - Returns `true` if the state was successfully set. #### Error Response - Returns `nil` and an error message string if setting the state fails. ``` -------------------------------- ### ssl.newcontext Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-0.4 Creates a context used for wrapping TCP connections with SSL/TLS. It takes a table of parameters to configure the context, such as mode, protocol, certificates, and verification options. ```APIDOC ## ssl.newcontext ### Description Creates a context that is used to wrap a TCP connection. In case of errors, the function returns nil, followed by an error message. ### Method `ssl.newcontext(params)` ### Parameters #### Request Body (params table) - **mode** (string) - Required - Use "client" or "server". - **protocol** (string) - Required - "tlsv1", "sslv3", or "sslv23". - **key** (string) - Optional - Path to the file that contains the key (in PEM format). - **password** (string | function) - Optional - Password of the encrypted key, or a callback function that returns it. - **certificate** (string) - Optional - Path to the file that contains the chain certificates (in PEM format). - **cafile** (string) - Optional - Path to the file that contains a set of trusting certificates (in PEM format). - **capath** (string) - Optional - Path to the directory that constains a set of files with trusting certificates. - **verify** (string | table) - Optional - Options used to verify the certificates. Supports: none, peer, client_once, fail_if_no_peer_cert. - **options** (string | table) - Optional - Options to change the behaviour of the OpenSSL library. Supports a wide range of OpenSSL options. - **ciphers** (string) - Optional - The list of ciphers to be used in the connection. - **depth** (number) - Optional - Maximum depth in the certificate chain verification. ### Response #### Success Response - **context** (object) - The created SSL context. #### Error Response - **nil** - **error_message** (string) - Description of the error. ``` -------------------------------- ### Get Peer Certificate Chain (Lua) Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-0.9 Retrieves the certificate chain sent by the peer during the TLS/SSL handshake. ```lua local cert_chain = conn:getpeerchain() ``` -------------------------------- ### Creating SSL Contexts Source: https://context7.com/lunarmodules/luasec/llms.txt This section demonstrates how to create SSL contexts for both client and server modes using LuaSec. ```APIDOC ## Creating SSL Contexts ### Description This section demonstrates how to create SSL contexts for both client and server modes using LuaSec. ### Method `ssl.newcontext(params)` ### Parameters #### Request Body (params table) - **mode** (string) - Required - 'client' or 'server' - **protocol** (string) - Optional - e.g., 'tlsv1_2', 'any' - **key** (string) - Optional (required for server) - Path to the private key file. - **certificate** (string) - Optional (required for server) - Path to the certificate file. - **cafile** (string) - Optional - Path to the CA bundle file. - **verify** (string or table) - Optional - Verification mode (e.g., 'peer', {'peer', 'fail_if_no_peer_cert'}). - **options** (string or table) - Optional - SSL options (e.g., 'all', {'all', 'no_sslv2'}). - **depth** (number) - Optional (server mode) - Maximum certificate chain depth. ### Request Example ```lua -- Client context example local params = { mode = "client", protocol = "tlsv1_2", key = "client-key.pem", certificate = "client-cert.pem", cafile = "ca-bundle.pem", verify = {"peer", "fail_if_no_peer_cert"}, options = {"all", "no_sslv2", "no_sslv3"}, ciphers = "HIGH:!aNULL:!MD5" } local ctx, err = ssl.newcontext(params) -- Server context example local server_params = { mode = "server", protocol = "any", key = "server-key.pem", certificate = "server-cert.pem", cafile = "ca-bundle.pem", verify = {"peer", "fail_if_no_peer_cert"}, options = "all", depth = 3 } local server_ctx = ssl.newcontext(server_params) ``` ### Response #### Success Response (200) - **ctx** (object) - The created SSL context. - **err** (string) - Error message if creation failed (nil on success). #### Response Example ```lua -- On success, ctx will be a valid context object. -- On failure, err will contain an error message. ``` ``` -------------------------------- ### ssl.loadcertificate Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-1.3.x Loads an X509 certificate from a string representation. ```APIDOC ## ssl.loadcertificate(str) ### Description Loads an X509 certificate from a string representation. This function is related to retrieving certificate details, potentially via `cert:pem()`. ### Method N/A (Function) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **str** (string) - Required - The string representation of the X509 certificate. ### Request Example ```json { "certificate_string": "-----BEGIN CERTIFICATE-----\nMIIC...\n-----END CERTIFICATE-----" } ``` ### Response #### Success Response (N/A) Returns a certificate object (details depend on LuaSec's internal representation). #### Response Example ```json { "certificate_object": "" } ``` ``` -------------------------------- ### Load Certificate from String Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-0.8 Loads an X509 certificate from its string representation. This function is useful for dynamically loading certificates. ```APIDOC ## Load Certificate from String ### Description Loads an X509 certificate from a string representation. Refer to `cert:pem()` for information on string formatting. ### Method `ssl.loadcertificate(str)` ### Endpoint `/ssl.loadcertificate` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **str** (string) - Required - The string representation of the X509 certificate. ### Request Example ```lua local cert_string = "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----" local certificate = ssl.loadcertificate(cert_string) ``` ### Response #### Success Response (200) - **certificate** (object) - An object representing the loaded X509 certificate. #### Response Example ```lua -- Returns a certificate object -- Example structure (actual object may vary): -- { -- subject = "CN=example.com", -- issuer = "CN=Test CA" -- } ``` ``` -------------------------------- ### Get ALPN Protocol - Lua Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-1.1.0 Returns the Application-Layer Protocol Negotiation (ALPN) protocol selected during the TLS/SSL handshake. ```lua local alpn_protocol = conn:getalpn() print("ALPN Protocol:", alpn_protocol) ``` -------------------------------- ### Get SNI Name - Lua Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-1.1.0 Retrieves the Server Name Indication (SNI) value specified during the TLS/SSL handshake. ```lua local sni_name = conn:getsniname() print("SNI Name:", sni_name) ``` -------------------------------- ### Wrap TCP Connection with SSL/TLS using ssl.wrap Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-0.5 The ssl.wrap function establishes a secure TLS/SSL session over a given TCP connection. It requires a context object or parameters to create one, which defines security settings like protocol and certificates. This function invalidates the original socket to prevent premature closure. Errors are indicated by returning nil and an error message. ```lua local ssl = require("ssl") local socket = require("socket") local tcp_sock = socket.tcp("example.com", 443) if tcp_sock then local params = { protocol = "tlsv1.2", -- other parameters like cert, key etc. } local secure_conn = ssl.wrap(tcp_sock, params) if not secure_conn then print("SSL wrap failed:", secure_conn) else print("SSL connection established.") -- Use secure_conn for secure communication end else print("Failed to create TCP socket.") end ``` -------------------------------- ### Get ALPN Selected Protocol (Lua) Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-0.9 Retrieves the application-layer protocol negotiated during the TLS handshake using ALPN. ```lua local alpn_protocol = conn:getalpn() ``` -------------------------------- ### conn:send Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-1.3.x Sends data through the connection. Allows sending a substring of the data by specifying start and end indices. ```APIDOC ## conn:send(data [, i [, j]]) ### Description Sends the specified string data through the connection. The optional arguments i and j allow for sending a substring of data, similar to string.sub. ### Method POST (conceptual) ### Endpoint N/A (This is a method of a connection object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **data** (string) - The string data to be sent. - **i** (number) - Optional. The starting index of the substring to send. Defaults to 1. - **j** (number) - Optional. The ending index of the substring to send. Defaults to the end of the string. ### Request Example ```lua local success, err, sent_index = conn:send("Hello, world!") local partial_success, partial_err, partial_index = conn:send("Some data", 1, 4) -- Sends "Some" ``` ### Response #### Success Response (200) - **last_sent_index** (number) - The index of the last byte within the sent portion ([i, j]) that was successfully transmitted. If i is 1 or absent, this is the total number of bytes sent. #### Response Example ```lua -- If "Hello, world!" is sent successfully: -- last_sent_index might be 13 -- If "Some" (from "Some data") is sent successfully: -- last_sent_index might be 4 ``` ### Error Handling - Returns nil, an error message, and the index of the last byte sent within [i, j] in case of error. - Common error messages include "closed", "wantread", and "wantwrite". ``` -------------------------------- ### Get Latest Finished Message - Lua Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-1.1.0 Returns the latest "Finished" message sent out during the TLS/SSL handshake. ```lua local finished_sent = conn:getfinished() print("Finished Message Sent:", finished_sent) ``` -------------------------------- ### ssl.config Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-1.3.x Provides configuration options for OpenSSL, including algorithms, curves, protocols, and capabilities. ```APIDOC ## ssl.config ### Description Provides configuration options for OpenSSL, including algorithms, curves, protocols, and capabilities. ### Method N/A (Table) ### Endpoint N/A ### Parameters N/A ### Request Example ```json { "ssl_config": "See documentation for details on accessing configuration tables." } ``` ### Response #### Success Response (N/A) N/A #### Response Example N/A ``` -------------------------------- ### Perform TLS/SSL Handshake (Lua) Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-0.9 Initiates the TLS/SSL handshake to secure a connection. Can return 'wantread' or 'wantwrite' if a timeout is set, requiring subsequent calls after waiting for socket readiness. ```lua local socket = require('socket') local succ, msg conn:settimeout(0) -- Non-blocking handshake while not succ do succ, msg = conn:dohandshake() if msg == "wantread" then socket.select({conn}, nil) -- Wait for read readiness elseif msg == "wantwrite" then socket.select(nil, {conn}) -- Wait for write readiness else -- Handle other errors break end end ``` -------------------------------- ### Perform TLS/SSL Handshake (Lua) Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-0.6 Initiates and completes the TLS/SSL handshake for a secure connection. Handles partial handshakes due to timeouts by allowing re-attempts after waiting for socket readiness. ```lua local succ, msg = conn:dohandshake() if not succ then if msg == "wantread" or msg == "wantwrite" then -- wait for socket readiness and retry socket.select({conn}, nil) -- or socket.select(nil, {conn}) conn:dohandshake() else -- handle other errors end end ``` -------------------------------- ### Connection Methods Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-0.8 Provides methods for managing an established SSL connection, including closing, performing handshakes, and retrieving connection information. ```APIDOC ## Connection Methods ### conn:close() #### Description Closes the SSL connection. #### Method `conn:close()` ### conn:dohandshake() #### Description Performs the TLS/SSL handshake to establish the secure connection. It can return 'wantread' or 'wantwrite' if the handshake is not yet complete, requiring the use of `socket.select`. #### Method `conn:dohandshake()` #### Response - `true` on success. - `false`, followed by an error message on failure. - `false`, followed by `'wantread'` or `'wantwrite'` if the handshake is ongoing and requires waiting for socket readiness. ### conn:receive([pattern][, prefix]) #### Description Reads data from the SSL connection according to the specified pattern. Handles various read modes ('*a', '*l', number) and supports an optional prefix. Returns partial results on errors like 'closed', 'wantread', or 'wantwrite'. #### Method `conn:receive([pattern][, prefix])` #### Parameters - **pattern** (string, optional) - The read pattern ('*a' for all, '*l' for line, number for bytes). Defaults to '*l'. - **prefix** (string, optional) - A string to prepend to the received data. #### Response - The received data string on success. - `nil`, followed by an error message string on failure. - `nil`, followed by partial data and an error message ('closed', 'wantread', 'wantwrite') on specific errors. ### conn:getalpn() #### Description Returns the selected Application-Layer Protocol Negotiation (ALPN) protocol. #### Method `conn:getalpn()` ### conn:getfinished() #### Description Returns the latest "Finished" message sent out during the TLS handshake. #### Method `conn:getfinished()` ### conn:getpeercertificate([n]) #### Description Returns the nth certificate in the peer's certificate chain. Defaults to the first certificate (n=1). #### Method `conn:getpeercertificate([n])` #### Parameters - **n** (number, optional) - The index of the certificate to retrieve. ### conn:getpeerchain() #### Description Returns the entire certificate chain from the peer. #### Method `conn:getpeerchain()` ### conn:getpeerverification() #### Description Returns the verification status of the peer's certificate chain. #### Method `conn:getpeerverification()` ### conn:getpeerfinished() #### Description Returns the latest "Finished" message received from the peer during the TLS handshake. #### Method `conn:getpeerfinished()` ### conn:getsniname() #### Description Returns the Server Name Indication (SNI) value specified during the handshake. #### Method `conn:getsniname()` ### conn:getstats() #### Description Returns accounting information for the connection, including bytes received, bytes sent, and connection age in seconds. #### Method `conn:getstats()` #### Response - A table containing `received`, `sent`, and `age` values. ### conn:info([field]) #### Description Returns a table with detailed information about the SSL connection (e.g., cipher, protocol, encryption) if no field is specified. If a specific field is provided, its value is returned. #### Method `conn:info([field])` #### Parameters - **field** (string, optional) - The specific information field to retrieve (e.g., 'cipher', 'protocol'). #### Response - A table with connection information if `field` is omitted. - The value of the specified `field` if provided. ``` -------------------------------- ### Get Certificate Not After Date Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-1.2.0 Retrieves the expiration date ('not after') of a certificate. This function is part of the certificate object and does not require any input parameters. ```lua local expiration_date = cert:notafter() ``` -------------------------------- ### conn:receive() Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-0.4 Reads data from the connection using a specified pattern ('*a', '*l', or a number of bytes). It can also prepend an optional string to the received data. Errors include 'closed', 'wantread', and 'wantwrite', often returning partial results. ```APIDOC ## conn:receive([pattern][, prefix]) ### Description Reads data from the connection `conn` according to the specified read pattern. ### Method `CONN:RECEIVE` ### Parameters - **pattern** (string) - Optional. The pattern to use for reading. Defaults to '*l'. - `'*a'`: Reads until the connection is closed. - `'*l'`: Reads a line terminated by LF (optionally preceded by CR). CR characters are ignored. - `number`: Reads a specified number of bytes. - **prefix** (string) - Optional. A string to prepend to the received data. ### Request Example ```lua -- Read a line local line = conn:receive('*l') -- Read 1024 bytes and prepend 'header:' local data = conn:receive(1024, 'header:') -- Read until connection closed local all_data = conn:receive('*a') ``` ### Response #### Success Response - `received_data` (string) - The data read from the connection, potentially with the prefix. #### Failure Response - `nil` (nil) - `error_message` (string) - Describes the error ('closed', 'wantread', 'wantwrite'). - `partial_result` (string) - The partial data received before the error occurred. ``` -------------------------------- ### Get SNI Name from Handshake (Lua) Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-0.9 Retrieves the Server Name Indication (SNI) value provided by the client during the TLS handshake. ```lua local sni_name = conn:getsniname() ``` -------------------------------- ### conn:exportkeyingmaterial Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-1.2.0 Retrieves keying material used during the TLS connection establishment. ```APIDOC ## conn:exportkeyingmaterial ### Description Returns some keying material used in the TLS connection creation. ### Method conn:exportkeyingmaterial() ### Endpoint N/A (Method of a connection object) ### Parameters None ### Request Example ```lua local keying_material = secure_connection:exportkeyingmaterial() ``` ### Response #### Success Response (200) - **keying_material** (string) - The exported keying material. #### Response Example ```lua local km = secure_connection:exportkeyingmaterial() print('Keying Material:', km) ``` ``` -------------------------------- ### Get Latest Peer Finished Message - Lua Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-1.1.0 Returns the latest "Finished" message received from the peer during the TLS/SSL handshake. ```lua local finished_received = conn:getpeerfinished() print("Finished Message Received:", finished_received) ``` -------------------------------- ### Wrap TCP Socket with SSL Parameters in Lua Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-1.3.x Wraps a given TCP socket 'sock' to establish a secure session using provided parameters. The 'params' argument can be an existing context or a table of parameters for creating a new context via ssl.newcontext(). The original socket is invalidated after wrapping. ```lua local secure_conn = ssl.wrap(sock, params) ``` -------------------------------- ### Get Specific Peer Certificate - Lua Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-1.1.0 Retrieves a specific certificate from the peer's chain. Defaults to the first certificate (index 1). ```lua local first_cert = conn:getpeercertificate() local second_cert = conn:getpeercertificate(2) print("First Peer Cert:", first_cert) print("Second Peer Cert:", second_cert) ``` -------------------------------- ### Perform TLS/SSL Handshake with conn:dohandshake Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-0.5 The conn:dohandshake method completes the TLS/SSL handshake to establish a secure connection. It returns true on success, or false and an error message otherwise. If a timeout is set, it might return 'wantread' or 'wantwrite', requiring the use of socket.select to wait for I/O readiness before retrying. ```lua local succ, msg conn:settimeout(0) -- Non-blocking handshake while not succ do succ, msg = conn:dohandshake() if not succ then if msg == "wantread" then socket.select({conn}, nil) elseif msg == "wantwrite" then socket.select(nil, {conn}) else print("Handshake error:", msg) break end end end if succ then print("Handshake successful.") end ``` -------------------------------- ### conn:getpeerchain Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-1.2.0 Retrieves the entire certificate chain from the connected peer. ```APIDOC ## conn:getpeerchain ### Description Returns the chain certificate from the peer that we are connected with. ### Method conn:getpeerchain() ### Endpoint N/A (Method of a connection object) ### Parameters None ### Request Example ```lua local cert_chain = secure_connection:getpeerchain() ``` ### Response #### Success Response (200) - **certificate_chain** (string) - A string containing all certificates in the peer's chain, typically in PEM format. #### Response Example ```lua local chain = secure_connection:getpeerchain() print('Peer Certificate Chain:\n', chain) ``` ``` -------------------------------- ### Get Certificate Serial Number Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-0.9 Returns the serial number of the certificate. This is a unique identifier for the certificate. The function returns a string representing the serial number. ```lua cert:serial() ``` -------------------------------- ### Get Certificate Validity Period (Not After) in LuaSec Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-0.6 Returns the 'not after' date from an X.509 certificate. This date indicates the latest time the certificate is considered valid. ```lua local not_after_date = cert:notafter() print("Valid until: " .. tostring(not_after_date)) ``` -------------------------------- ### Certificate Loading Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-1.1.0 Loads an X509 certificate from a string. This function is useful for dynamically loading certificates into your application. ```APIDOC ## ssl.loadcertificate(str) ### Description Loads an X509 certificate from a string representation. This is typically used for certificates provided in PEM format. ### Method `ssl.loadcertificate(str)` ### Endpoint N/A (Lua function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **str** (string) - Required - The string containing the certificate in PEM format. ### Request Example ```lua local cert_string = "-----BEGIN CERTIFICATE-----\nMIIDGTCC...\n-----END CERTIFICATE-----" local certificate = ssl.loadcertificate(cert_string) if certificate then print("Certificate loaded successfully") end ``` ### Response #### Success Response (200) - **certificate** (object) - A certificate object representing the loaded X509 certificate. #### Response Example ```lua -- Assuming successful load, returns a certificate object that can be used with other ssl functions -- Example of checking certificate details (not a direct response, but usage): -- local subject = certificate:subject() -- print(subject) ``` ``` -------------------------------- ### Export Keying Material in Lua Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-1.2.0 The conn:exportkeyingmaterial() function retrieves keying material generated during the TLS connection setup. This material can be used for various cryptographic purposes. ```lua local keying_material = conn:exportkeyingmaterial() if keying_material then print('Keying material exported') end ``` -------------------------------- ### Server-Side SSL Connection in Lua Source: https://context7.com/lunarmodules/luasec/llms.txt Illustrates setting up a secure server connection using LuaSec. This involves creating an SSL context, binding a TCP server, accepting a client connection, wrapping it with SSL, performing the handshake, and then communicating securely. Ensure certificate and key files are correctly configured. ```lua local socket = require("socket") local ssl = require("ssl") -- Create SSL context local params = { mode = "server", protocol = "any", key = "server-key.pem", certificate = "server-cert.pem", cafile = "ca-bundle.pem", verify = {"peer", "fail_if_no_peer_cert"}, options = "all" } local ctx = assert(ssl.newcontext(params)) -- Create TCP server local server = socket.tcp() server:setoption('reuseaddr', true) assert(server:bind("127.0.0.1", 8888)) server:listen() -- Accept connection local client = server:accept() -- Wrap with SSL client = assert(ssl.wrap(client, ctx)) assert(client:dohandshake()) -- Communicate securely client:send("Hello from secure server\n") local data = client:receive("*l") print("Received: " .. data) client:close() ``` -------------------------------- ### Wrap TCP Socket with SSL/TLS in Lua Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-1.2.0 The ssl.wrap function takes a TCP socket and optional parameters to establish a secure SSL/TLS session. It requires a context for parameters like protocol and certificates. If a context is not provided, it's created using ssl.newcontext. The original socket is invalidated after wrapping. ```lua local sock = socket.tcp() -- ... connect sock ... local params = { protocol = 'any', cafile = '/path/to/ca.crt', -- other parameters like certfile, keyfile, etc. } local secure_conn = ssl.wrap(sock, params) if not secure_conn then -- Handle error print('SSL wrap failed:', msg) else -- Use secure_conn for secure communication print('SSL connection established') end ``` -------------------------------- ### Get Peer Certificate Chain in Lua Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-1.2.0 The conn:getpeerchain() function returns the entire certificate chain provided by the peer during the TLS handshake. This allows for validation of the trust path. ```lua local peer_chain = conn:getpeerchain() if peer_chain then print('Peer certificate chain obtained') end ``` -------------------------------- ### HTTPS Requests Source: https://context7.com/lunarmodules/luasec/llms.txt This section covers making HTTPS requests using the `ssl.https` module, including GET, POST, and advanced configurations. ```APIDOC ## HTTPS Requests ### Description This section covers making HTTPS requests using the `ssl.https` module, including simple GET/POST and advanced configurations with custom options. ### Method `https.request(url, postdata, options)` ### Parameters #### Path Parameters - **url** (string) - Required - The URL to request (including the scheme, e.g., 'https://example.com'). - **postdata** (string) - Optional - Data to send in the request body (for POST requests). - **options** (table) - Optional - A table of advanced options for the request. Can include: - `method` (string): HTTP method (e.g., 'GET', 'POST'). - `headers` (table): Custom request headers. - `source` (ltn12 source): Data source for the request body. - `sink` (ltn12 sink): Data sink for the response body. - SSL/TLS options (same as `ssl.newcontext` or `ssl.wrap`, e.g., `protocol`, `verify`, `cafile`, `options`). ### Request Example ```lua -- Simple HTTPS GET request local body, code, headers, status = https.request("https://www.example.com") -- HTTPS POST request local response, code, headers, status = https.request( "https://api.example.com/data", "param1=value1¶m2=value2" ) -- Advanced HTTPS request with custom configuration local ltn12 = require("ltn12") local result_table = {} local success, code, headers, status = https.request{ url = "https://www.example.com/api", method = "POST", headers = { ["Content-Type"] = "application/json", ["Authorization"] = "Bearer token123" }, source = ltn12.source.string('{"key":"value"}'), sink = ltn12.sink.table(result_table), protocol = "tlsv1_2", options = {"all", "no_sslv2", "no_sslv3"}, verify = "peer", cafile = "/etc/ssl/certs/ca-bundle.crt" } ``` ### Response #### Success Response (200) - **body** (string) - The response body (if sink is not specified). - **code** (number) - The HTTP status code. - **headers** (table) - A table of response headers. - **status** (string) - The status line (e.g., 'OK'). #### Response Example ```lua -- For simple requests: print("Status: " .. code) print("Body: " .. body) -- For advanced requests with ltn12 sink: if success then print("Response: " .. table.concat(result_table)) end ``` ``` -------------------------------- ### Retrieve Public Key in PEM Format Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-0.9 Retrieves the public key associated with the certificate and returns it in PEM format. This function requires a valid certificate object. The output is a string containing the public key. ```lua cert:pubkey() ``` -------------------------------- ### ssl.wrap Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-0.4 Wraps an existing TCP connection socket with SSL/TLS, returning a new object for establishing a secure session. It can either accept a pre-created context or create one using provided parameters. ```APIDOC ## ssl.wrap ### Description Wraps the TCP connection `sock` and returns a new object that is used to establish a secure session. In case of error, the function returns nil, followed by an error message. ### Method `ssl.wrap(sock, params)` ### Parameters #### Path Parameters - **sock** (object) - The TCP connection socket to wrap. #### Request Body (params table - optional) - **context** (object) - An already created SSL context. - If `context` is not provided, `params` is a table with parameters to create the context (see `ssl.newcontext`). ### Response #### Success Response - **secure_connection** (object) - The new secure connection object. #### Error Response - **nil** - **error_message** (string) - Description of the error. ``` -------------------------------- ### Get Certificate Expiry Date in LuaSec Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-0.5 The cert:notafter function returns the "not after" date of an X.509 certificate. This date indicates the latest time at which the certificate is considered valid. ```lua local valid_until = cert:notafter() ``` -------------------------------- ### conn:dohandshake Source: https://github.com/lunarmodules/luasec/wiki/LuaSec-0.4 Performs the SSL/TLS handshake to establish a secure session. ```APIDOC ## conn:dohandshake ### Description Performs the SSL/TLS handshake to establish a secure session over the wrapped connection. This should be called after wrapping the socket. ### Method `connection:dohandshake()` ### Parameters None ### Response #### Success Response - Returns `true` on successful handshake. #### Error Response - Returns `nil` and an error message string if the handshake fails. ```