### Example of X11 Tunnels Source: https://api.libssh.org/stable/libssh_tutor_forwarding.html Demonstrates the setup for X11 tunnels, enabling a remote application to display its graphical interface on a local X11 server. The SSH tunnel is established by the client. ```text Local display Graphical application (X11 server) (X11 client) ^ | | V SSH client <===== SSH server Legend: ----->: X11 connection through X11 display number =====>: SSH tunnel ``` -------------------------------- ### Enable and Start GitLab Runner Service Source: https://api.libssh.org/stable/md_README_8gitlab_8freebsd.html Configures the system to automatically start the GitLab Runner service on boot and then starts the service immediately. ```bash sysrc -f /etc/rc.conf "gitlab_runner_enable=YES" service gitlab_runner start ``` -------------------------------- ### Install Required Packages Source: https://api.libssh.org/stable/md_README_8gitlab_8freebsd.html Installs essential packages for building and running GitLab Runner, including development tools and dependencies. ```bash pkg install -y bash git gmake cmake cmocka openssl wget pkgconf ccache bash ``` -------------------------------- ### ChaCha Key Setup Function Source: https://api.libssh.org/stable/chacha_8h_source.html Initializes the ChaCha context with a given key. The key length in bits is specified by kbits. ```c void chacha_keysetup(struct chacha_ctx *x, const uint8_t *k, uint32_t kbits) #ifdef HAVE_GCC_BOUNDED_ATTRIBUTE __attribute__((__bounded__(__minbytes__, 2, CHACHA_MINKEYLEN))) #endif ; ``` -------------------------------- ### Password Authentication Example Source: https://api.libssh.org/stable/libssh_tutor_authentication.html Demonstrates how to authenticate a user using a password with libssh. Ensure the password is handled securely and deallocated properly. ```c int authenticate_password(ssh_session session) { char *password = NULL; int rc; password = getpass("Enter your password: "); rc = ssh_userauth_password(session, NULL, password); if (rc == SSH_AUTH_ERROR) { fprintf(stderr, "Authentication failed: %s\n", ssh_get_error(session)); return SSH_AUTH_ERROR; } return rc; } ``` -------------------------------- ### Download and Install gitlab-runner Binary Source: https://api.libssh.org/stable/md_README_8gitlab_8freebsd.html Fetches the latest GitLab Runner binary for FreeBSD amd64 architecture and makes it executable. ```bash wget -O /usr/local/bin/gitlab-runner https://gitlab-runner-downloads.s3.amazonaws.com/latest/binaries/gitlab-runner-freebsd-amd64 chmod +x /usr/local/bin/gitlab-runner ``` -------------------------------- ### sftp_fstatvfs Source: https://api.libssh.org/stable/sftp_8h_source.html Get information about a mounted file system. ```APIDOC ## sftp_fstatvfs ### Description Get information about a mounted file system. ### Signature `sftp_statvfs_t sftp_fstatvfs(sftp_file file)` ### Parameters #### Path Parameters - **file** (sftp_file) - The SFTP file handle. ``` -------------------------------- ### Channel::requestShell Source: https://api.libssh.org/stable/libsshpp_8hpp_source.html Requests a shell to be started on the remote server for this channel. ```APIDOC ## Channel::requestShell ### Description Requests a shell to be started on the remote server for this channel. ### Method `void_throwable requestShell()` ### Throws An exception if the shell request fails. ``` -------------------------------- ### ssh_client_gss_kex_init Source: https://api.libssh.org/stable/kex-gss_8h_source.html Initiates the GSSAPI key exchange process for an SSH client. This function should be called by the client to start the GSSAPI-based key exchange. ```APIDOC ## ssh_client_gss_kex_init ### Description Initiates the GSSAPI key exchange process for an SSH client. This function should be called by the client to start the GSSAPI-based key exchange. ### Function Signature `int ssh_client_gss_kex_init(ssh_session session);` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **session** (ssh_session) - The SSH session object. ``` -------------------------------- ### Enable FIDO2 Support during Build Source: https://api.libssh.org/stable/libssh_tutor_fido2.html Build libssh with the WITH_FIDO2 option enabled. Ensure libfido2 is installed for USB-HID support. ```bash cmake -DWITH_FIDO2=ON .. ``` -------------------------------- ### ssh_bind_listen Source: https://api.libssh.org/stable/group__libssh__server.html Starts listening on the configured socket for incoming SSH connections. This function makes the server ready to accept clients. ```APIDOC ## ssh_bind_listen ### Description Start listening to the socket. ### Function Signature `LIBSSH_API int | ssh_bind_listen (ssh_bind ssh_bind_o)` ``` -------------------------------- ### Get Available Authentication Methods Source: https://api.libssh.org/stable/libsshpp_8hpp_source.html Retrieves a list of authentication methods supported by the server for the current session. The result is a string containing methods separated by spaces. ```cpp int getAuthList(){ int ret=ssh_userauth_list(c_session, NULL); ssh_throw(ret); return ret; } ``` -------------------------------- ### Interactive Shell Session Example Source: https://api.libssh.org/stable/libssh_tutor_shell.html A basic terminal emulator that reads from the SSH channel and sends keyboard input to the remote computer. It uses nonblocking reads and writes. ```c int interactive_shell_session(ssh_channel channel) { /* Session and terminal initialization skipped */ ... char buffer[256]; int nbytes, nwritten; while (ssh_channel_is_open(channel) && !ssh_channel_is_eof(channel)) { nbytes = ssh_channel_read_nonblocking(channel, buffer, sizeof(buffer), 0); if (nbytes < 0) return SSH_ERROR; if (nbytes > 0) { nwritten = write(1, buffer, nbytes); if (nwritten != nbytes) return SSH_ERROR; if (!kbhit()) { usleep(50000L); // 0.05 second continue; } nbytes = read(0, buffer, sizeof(buffer)); if (nbytes < 0) return SSH_ERROR; if (nbytes > 0) { nwritten = ssh_channel_write(channel, buffer, nbytes); if (nwritten != nbytes) return SSH_ERROR; } } return rc; } ``` -------------------------------- ### Create Directory with SFTP Source: https://api.libssh.org/stable/libssh_tutor_sftp.html Creates a directory named 'helloworld' with owner-only read/write permissions. Handles the case where the directory already exists. ```c #include #include int sftp_helloworld(ssh_session session, sftp_session sftp) { int rc; rc = sftp_mkdir(sftp, "helloworld", S_IRWXU); if (rc != SSH_OK) { if (sftp_get_error(sftp) != SSH_FX_FILE_ALREADY_EXISTS) { fprintf(stderr, "Can't create directory: %s\n", ssh_get_error(session)); return rc; } } ... return SSH_OK; } ``` -------------------------------- ### sftp_init Source: https://api.libssh.org/stable/sftp_8h_source.html Initialize the sftp protocol with the server. ```APIDOC ## sftp_init ### Description Initialize the sftp protocol with the server. ### Signature `LIBSSH_API int sftp_init(sftp_session sftp)` ``` -------------------------------- ### Initialize and Free SFTP Session Source: https://api.libssh.org/stable/libssh_tutor_sftp.html Demonstrates the basic workflow for creating, initializing, and freeing an SFTP session. Ensure proper error handling after sftp_new and sftp_init calls. ```c #include int sftp_helloworld(ssh_session session) { sftp_session sftp; int rc; sftp = sftp_new(session); if (sftp == NULL) { fprintf(stderr, "Error allocating SFTP session: %s\n", ssh_get_error(session)); return SSH_ERROR; } rc = sftp_init(sftp); if (rc != SSH_OK) { fprintf(stderr, "Error initializing SFTP session: code %d.\n", sftp_get_error(sftp)); sftp_free(sftp); return rc; } ... sftp_free(sftp); return SSH_OK; } ``` -------------------------------- ### Example Corporate Copyright Message Source: https://api.libssh.org/stable/index.html This is an example of a copyright message that can be included in code contributed by an individual working for a company, following the libssh contribution guidelines. ```text (c) Example Corporation. ``` -------------------------------- ### PKCS#11 Provider Engine Handling Source: https://api.libssh.org/stable/libcrypto_8h_source.html Conditional definitions for loading a PKCS#11 provider or getting an engine, depending on build configurations like WITH_PKCS11_URI and WITH_PKCS11_PROVIDER. ```c #if defined(WITH_PKCS11_URI) #if defined(WITH_PKCS11_PROVIDER) int pki_load_pkcs11_provider(void); #else ENGINE *pki_get_engine(void); #endif #endif /* WITH_PKCS11_PROVIDER */ ``` -------------------------------- ### sftp_init Source: https://api.libssh.org/stable/sftp_8h_source.html Initializes an SFTP session. ```APIDOC ## sftp_init ### Description Initializes an SFTP session. ### Method `sftp_init(sftp_session sftp)` ### Parameters - **sftp** (sftp_session) - The SFTP session to initialize. ### Returns 0 on success, a negative value on error. ``` -------------------------------- ### ssh_get_log_level Source: https://api.libssh.org/stable/libssh_8h_source.html Get the log level of the library. ```APIDOC ## ssh_get_log_level ### Description Get the log level of the library. ### Signature ```c LIBSSH_API int ssh_get_log_level(void) ``` ``` -------------------------------- ### ssh_list_count Source: https://api.libssh.org/stable/group__libssh__misc.html Gets the number of elements in the list. ```APIDOC ## ssh_list_count ### Description Get the number of elements in the list. ### Signature size_t ssh_list_count (const struct ssh_list *list) ### Parameters * **list** (const struct ssh_list *) - The list to count elements from. ### Return Value The number of elements in the list. ``` -------------------------------- ### ssh_list_get_iterator Source: https://api.libssh.org/stable/group__libssh__misc.html Gets an iterator for traversing a list. ```APIDOC ## ssh_list_get_iterator ### Description Get an iterator for traversing a list. ### Signature struct ssh_iterator * ssh_list_get_iterator (const struct ssh_list *list) ### Parameters * **list** (const struct ssh_list *) - The list to get an iterator for. ### Return Value A pointer to an iterator for the list, or NULL if the list is empty or an error occurs. ``` -------------------------------- ### ssh_server_hybrid_mlkem_init Source: https://api.libssh.org/stable/hybrid__mlkem_8h_source.html Initializes the Hybrid ML-KEM mechanism for a server SSH session. This function is intended for server-side implementations and should be called during session setup. ```APIDOC ## ssh_server_hybrid_mlkem_init ### Description Initializes the Hybrid ML-KEM mechanism for a server SSH session. This function is intended for server-side implementations and should be called during session setup. ### Function Signature `void ssh_server_hybrid_mlkem_init(ssh_session session);` ### Parameters #### Path Parameters - **session** (ssh_session) - Required - The SSH session object for which to initialize the ML-KEM mechanism on the server side. ``` -------------------------------- ### Set SSH Session Options Source: https://api.libssh.org/stable/libssh_tutor_guided_tour.html Shows how to configure an SSH session by setting essential options such as host, port, and logging verbosity using ssh_options_set(). Remember to pass integer values as pointers. ```c #include #include int main() { ssh_session my_ssh_session = NULL; int verbosity = SSH_LOG_PROTOCOL; int port = 22; my_ssh_session = ssh_new(); if (my_ssh_session == NULL) exit(-1); ssh_options_set(my_ssh_session, SSH_OPTIONS_HOST, "localhost"); ssh_options_set(my_ssh_session, SSH_OPTIONS_LOG_VERBOSITY, &verbosity); ssh_options_set(my_ssh_session, SSH_OPTIONS_PORT, &port); ... ssh_free(my_ssh_session); } ``` -------------------------------- ### sftp_extensions_get_name Source: https://api.libssh.org/stable/sftp_8h_source.html Gets the name of an SFTP extension by its index. ```APIDOC ## sftp_extensions_get_name ### Description Gets the name of an SFTP extension by its index. ### Method `sftp_extensions_get_name(sftp_session sftp, unsigned int indexn)` ### Parameters - **sftp** (sftp_session) - The SFTP session. - **indexn** (unsigned int) - The index of the extension. ### Returns The name of the extension. ``` -------------------------------- ### Connect to SSH Server and Handle Errors Source: https://api.libssh.org/stable/libssh_tutor_guided_tour.html This snippet shows how to initialize an SSH session, connect to a server, and retrieve error messages if the connection fails. Ensure libssh is installed and configured. ```c #include #include #include int main() { ssh_session my_ssh_session = NULL; int rc; my_ssh_session = ssh_new(); if (my_ssh_session == NULL) exit(-1); ssh_options_set(my_ssh_session, SSH_OPTIONS_HOST, "localhost"); rc = ssh_connect(my_ssh_session); if (rc != SSH_OK) { fprintf(stderr, "Error connecting to localhost: %s\n", ssh_get_error(my_ssh_session)); exit(-1); } ... ssh_disconnect(my_ssh_session); ssh_free(my_ssh_session); } ``` -------------------------------- ### sftp_extensions_get_count Source: https://api.libssh.org/stable/sftp_8h_source.html Gets the number of supported SFTP extensions. ```APIDOC ## sftp_extensions_get_count ### Description Gets the number of supported SFTP extensions. ### Method `sftp_extensions_get_count(sftp_session sftp)` ### Parameters - **sftp** (sftp_session) - The SFTP session. ### Returns The number of extensions. ``` -------------------------------- ### Server Binding and Options Source: https://api.libssh.org/stable/server_8h_source.html Functions for creating a server bind context, setting various options, and parsing configuration files. ```APIDOC ## Server Binding Functions ### `ssh_bind_new` Creates a new server bind context. ### `ssh_bind_options_set` Sets a specific option for the server bind context. - **Parameters**: - `sshbind` (ssh_bind): The server bind context. - `type` (enum ssh_bind_options_e): The type of option to set. - `value` (const void*): The value of the option. ### `ssh_bind_options_parse_config` Parses SSH server configuration from a file. - **Parameters**: - `sshbind` (ssh_bind): The server bind context. - `filename` (const char*): The path to the configuration file. ### `ssh_bind_listen` Starts listening for incoming SSH connections on the configured bind address and port. - **Parameters**: - `ssh_bind_o` (ssh_bind): The server bind context. ### `ssh_bind_set_callbacks` Sets callback functions for handling server events, such as incoming connections. - **Parameters**: - `sshbind` (ssh_bind): The server bind context. - `callbacks` (ssh_bind_callbacks): A structure containing callback functions. - `userdata` (void*): User-defined data to be passed to callbacks. ### `ssh_bind_set_blocking` Sets the blocking mode for the server socket. - **Parameters**: - `ssh_bind_o` (ssh_bind): The server bind context. - `blocking` (int): 1 for blocking mode, 0 for non-blocking mode. ``` -------------------------------- ### ssh_scp_request_get_size (Deprecated) Source: https://api.libssh.org/stable/libssh_8h_source.html Gets the size of the file being pushed from the other party. ```APIDOC ## ssh_scp_request_get_size (Deprecated) ### Description Gets the size of the file being pushed from the other party. ### Function Signature ```c SSH_DEPRECATED LIBSSH_API size_t ssh_scp_request_get_size(ssh_scp scp) ``` ### Parameters * **scp** (ssh_scp) - The SCP session context. ### Return Value Returns the size of the file in bytes, or 0 on error. ``` -------------------------------- ### Get Session Source: https://api.libssh.org/stable/libsshpp_8hpp_source.html Returns a reference to the associated Session object. ```cpp Session &getSession(){ return *session; } ``` -------------------------------- ### ssh_server_init_kex Source: https://api.libssh.org/stable/group__libssh__server.html Initializes the key exchange, hostkey, ciphers, MACs, and compression algorithms for a given SSH session. This prepares the session for secure communication. ```APIDOC ## ssh_server_init_kex ### Description Initialize the set of key exchange, hostkey, ciphers, MACs, and compression algorithms for the given ssh_session. ### Function Signature `LIBSSH_API int | ssh_server_init_kex (ssh_session session)` ``` -------------------------------- ### sftp_extensions_get_data Source: https://api.libssh.org/stable/sftp_8h_source.html Gets the data associated with an SFTP extension by its index. ```APIDOC ## sftp_extensions_get_data ### Description Gets the data associated with an SFTP extension by its index. ### Method `sftp_extensions_get_data(sftp_session sftp, unsigned int indexn)` ### Parameters - **sftp** (sftp_session) - The SFTP session. - **indexn** (unsigned int) - The index of the extension. ### Returns The data of the extension. ``` -------------------------------- ### Initialize SFTP AIO Download Source: https://api.libssh.org/stable/libssh_tutor_sftp_aio.html Before starting the download, retrieve SFTP server limits to determine appropriate chunk sizes. Allocate a buffer for data transfer. This code assumes remote and local files are already opened and a queue for AIO handles is initialized. ```c sftp_aio aio = NULL; // Chunk size to use for the transfer size_t chunk_size; // For the limits structure that would be used // by the code to set the chunk size sftp_limits_t lim = NULL; // Max number of requests to keep outstanding at a time size_t in_flight_requests = 5; // Number of bytes for which requests have been sent size_t total_bytes_requested = 0; // Number of bytes which have been downloaded size_t bytes_downloaded = 0; // Buffer to use for the download char *buffer = NULL; // Helper variables size_t to_read; ssize_t bytes_requested; // Get the sftp limits lim = sftp_limits(sftp); if (lim == NULL) { // handle error } // Set the chunk size for download = the max limit for reading // The reason for this has been given in the "Capping applied by // the sftp aio API" section (Its to make the code simpler) // // Assigning a size_t type variable a uint64_t type value here, // theoretically could cause an overflow, but practically // max_read_length would never exceed SIZE_MAX so its okay. chunk_size = lim->max_read_length; buffer = malloc(chunk_size); if (buffer == NULL) { // handle error } ... // Code to open the remote file (to download) using sftp_open(). ... // Code to stat the remote file's file size. ... // Code to open the local file in which downloaded data is to be stored. ... // Code to initialize the queue which will be used to store sftp aio // handles. ``` -------------------------------- ### ssh_gssapi_init_ctx Source: https://api.libssh.org/stable/gssapi_8h_source.html Initializes a GSSAPI security context. ```APIDOC ## ssh_gssapi_init_ctx ### Description Initializes a GSSAPI security context. ### Parameters - **gssapi** (struct ssh_gssapi_struct *) - Pointer to the GSSAPI structure. - **input_token** (gss_buffer_desc *) - The input token buffer. - **output_token** (gss_buffer_desc *) - The output token buffer. - **ret_flags** (OM_uint32 *) - Pointer to store returned flags. ### Returns The major status code from the GSSAPI operation. ``` -------------------------------- ### ssh_pki_ctx_get_sk_attestation_buffer Source: https://api.libssh.org/stable/group__libssh__pki.html Get a copy of the attestation buffer from a PKI context. ```APIDOC ## ssh_pki_ctx_get_sk_attestation_buffer ### Description Get a copy of the attestation buffer from a PKI context. ### Function Signature ```c int ssh_pki_ctx_get_sk_attestation_buffer(const struct ssh_pki_ctx_struct *context, ssh_buffer *attestation_buffer) ``` ### Parameters * **context** (const struct ssh_pki_ctx_struct *) - The PKI context. * **attestation_buffer** (ssh_buffer *) - A pointer to an ssh_buffer to store the attestation data. ``` -------------------------------- ### sftp_server_init Source: https://api.libssh.org/stable/group__libssh__sftp.html Initializes an SFTP server session. (Deprecated) ```APIDOC ## sftp_server_init ### Description Initialize the sftp server. (Deprecated) ### Signature SSH_DEPRECATED LIBSSH_API int | sftp_server_init (sftp_session sftp) ``` -------------------------------- ### ssh_callbacks_iterate_end Source: https://api.libssh.org/stable/group__libssh__callbacks.html Marks the end of the callback iteration block started by ssh_callbacks_iterate. ```APIDOC ## ssh_callbacks_iterate_end This macro is used to close the iteration block initiated by `ssh_callbacks_iterate`. ### Usage ```c } } while(0) ``` ``` -------------------------------- ### ssh_scp_request_get_filename (Deprecated) Source: https://api.libssh.org/stable/libssh_8h_source.html Gets the name of the file or directory being pushed from the other party. ```APIDOC ## ssh_scp_request_get_filename (Deprecated) ### Description Gets the name of the directory or file being pushed from the other party. ### Function Signature ```c SSH_DEPRECATED LIBSSH_API const char * ssh_scp_request_get_filename(ssh_scp scp) ``` ### Parameters * **scp** (ssh_scp) - The SCP session context. ### Return Value Returns a pointer to the filename, or NULL on error. ``` -------------------------------- ### ssh_server_init_kex Source: https://api.libssh.org/stable/group__libssh__server.html Initializes the key exchange parameters for a server session. ```APIDOC ## ssh_server_init_kex() ### Description Initialize the set of key exchange, hostkey, ciphers, MACs, and compression algorithms for the given ssh_session. The selection of algorithms and keys used are determined by the options that are currently set in the given ssh_session structure. May only be called before the initial key exchange has begun. ### Parameters * session (ssh_session): The session structure to initialize. ### Returns * SSH_OK if initialization succeeds. ``` -------------------------------- ### ssh_scp_request_get_permissions (Deprecated) Source: https://api.libssh.org/stable/libssh_8h_source.html Gets the permissions of the file or directory being pushed from the other party. ```APIDOC ## ssh_scp_request_get_permissions (Deprecated) ### Description Gets the permissions of the file or directory being pushed from the other party. ### Function Signature ```c SSH_DEPRECATED LIBSSH_API int ssh_scp_request_get_permissions(ssh_scp scp) ``` ### Parameters * **scp** (ssh_scp) - The SCP session context. ### Return Value Returns the permissions on success, or a negative value on error. ``` -------------------------------- ### sftp_init Source: https://api.libssh.org/stable/libssh_tutor_sftp.html Initializes the SFTP protocol with the server. This function establishes the SFTP subsystem communication over the SSH channel. ```APIDOC ## sftp_init ### Description Initializes the SFTP protocol with the server. This function completes the setup of the SFTP subsystem, preparing it for file transfer operations. ### Signature ```c int sftp_init(sftp_session sftp) ``` ### Parameters #### Path Parameters - **sftp** (sftp_session) - Required - The SFTP session handle obtained from `sftp_new()`. ### Return Value - **SSH_OK** - If the SFTP session was successfully initialized. - **SSH_ERROR** or other non-zero value - If an error occurred during initialization. Use `sftp_get_error()` to retrieve the specific error code. ``` -------------------------------- ### Get Next Server Public Key Source: https://api.libssh.org/stable/dh_8h_source.html Retrieves the next server's public key object available for the session. Used when multiple keys might be offered. ```c ssh_key ssh_dh_get_next_server_publickey(ssh_session session); ``` -------------------------------- ### ssh_message_channel_request_open_destination Source: https://api.libssh.org/stable/group__libssh__server.html Gets the destination address from a channel open request message. ```APIDOC ## ssh_message_channel_request_open_destination() ### Description Get the destination address from the channel open message. ### Parameters * msg (ssh_message) - The message. ### Returns The destination address, or NULL. ``` -------------------------------- ### Opening and Closing a Channel Source: https://api.libssh.org/stable/libssh_tutor_shell.html Demonstrates the process of creating a new channel, opening a session on it, sending an end-of-file signal, closing the channel, and freeing associated resources. ```APIDOC ## Opening and Closing a Channel This section details the functions involved in managing SSH channels for remote shell sessions. ### Functions - **ssh_channel_new(ssh_session session)**: Allocates a new channel for an SSH session. - **ssh_channel_open_session(ssh_channel channel)**: Opens a session channel suitable for shells. - **ssh_channel_send_eof(ssh_channel channel)**: Sends an end-of-file signal on the channel. - **ssh_channel_close(ssh_channel channel)**: Closes the channel. - **ssh_channel_free(ssh_channel channel)**: Frees all resources associated with the channel. ### Code Example ```c int shell_session(ssh_session session) { ssh_channel channel = NULL; int rc; channel = ssh_channel_new(session); if (channel == NULL) return SSH_ERROR; rc = ssh_channel_open_session(channel); if (rc != SSH_OK) { ssh_channel_free(channel); return rc; } // ... further operations on the channel ... ssh_channel_close(channel); ssh_channel_send_eof(channel); ssh_channel_free(channel); return SSH_OK; } ``` ``` -------------------------------- ### SSH SCP Response Source: https://api.libssh.org/stable/group__libssh__scp.html Function to get a response from the SCP session. ```APIDOC ## ssh_scp_response ### Description Get a response from the SCP session. ### Signature int ssh_scp_response (ssh_scp scp, char **response) ### Parameters - **scp** (ssh_scp) - The SCP session. - **response** (char **) - Pointer to a buffer where the response will be stored. ``` -------------------------------- ### Set up X11 Forwarding Callback Source: https://api.libssh.org/stable/libssh_tutor_shell.html Declare a callback function to manage the channel open request for X11. This function is invoked when the remote side requests an X11 channel. ```c #include ssh_channel x11channel = NULL; ssh_channel x11_open_request_callback(ssh_session session, const char *shost, int sport, void *userdata) { x11channel = ssh_channel_new(session); return x11channel; } ``` -------------------------------- ### ssh_path_expand_tilde Source: https://api.libssh.org/stable/group__libssh__misc.html Expands a directory path that starts with a tilde ('~') to its full path. ```APIDOC ## ssh_path_expand_tilde ### Description Expand a directory starting with a tilde '~'. ### Signature char * ssh_path_expand_tilde (const char *d) ### Parameters * **d** (const char *) - The path to expand. ### Return Value A new string with the tilde expanded, or NULL on error. The caller must free this string. ``` -------------------------------- ### Minimal Custom Callback Implementation for libssh Source: https://api.libssh.org/stable/libssh_tutor_fido2.html A basic example demonstrating the definition and usage of custom callbacks for FIDO2/U2F security keys in libssh. Includes API version, enrollment, and structure definition. ```c #include #include #include /* Your custom API version callback */ static uint32_t my_sk_api_version(void) { /* Match the major version, set your own minor version */ return SSH_SK_VERSION_MAJOR | 0x0001; } /* Your custom enroll callback */ static int my_sk_enroll(uint32_t alg, const uint8_t *challenge, size_t challenge_len, const char *application, uint8_t flags, const char *pin, struct sk_option **options, struct sk_enroll_response **enroll_response) { /* Parse options array to extract custom parameters */ if (options != NULL) { for (size_t i = 0; options[i] != NULL; i++) { if (strcmp(options[i]->name, "my_custom_option") == 0) { /* Use options[i]->value */ } } } /* Implement your enroll logic here */ /* ... */ return SSH_SK_ERR_GENERAL; /* Return appropriate error code */ } /* Implement other required callbacks: sign, load_resident_keys */ /* ... */ /* Define your callback structure */ static struct ssh_sk_callbacks_struct my_sk_callbacks = { .size = sizeof(struct ssh_sk_callbacks_struct), .api_version = my_sk_api_version, .enroll = my_sk_enroll, .sign = my_sk_sign, /* Your implementation */ .load_resident_keys = my_sk_load_resident_keys, /* Your implementation */ }; /* Usage example */ void use_custom_callbacks(void) { ssh_pki_ctx pki_ctx = ssh_pki_ctx_new(); /* Set your custom callbacks */ ssh_pki_ctx_options_set(pki_ctx, SSH_PKI_OPTION_SK_CALLBACKS, &my_sk_callbacks); /* Pass custom options to your callbacks */ ssh_pki_ctx_sk_callbacks_option_set(pki_ctx, "my_custom_option", "my_custom_value", false); /* Use the context for enrollment, signing, etc. */ } ``` -------------------------------- ### ssh_channel_get_exit_status Source: https://api.libssh.org/stable/group__libssh__channel.html Get the exit status of the channel (error code from the executed instruction). ```APIDOC ## ssh_channel_get_exit_status ### Description Get the exit status of the channel (error code from the executed instruction). ### Signature int | ssh_channel_get_exit_status (ssh_channel channel) ``` -------------------------------- ### ssh_get_publickey Source: https://api.libssh.org/stable/libssh_8h_source.html Deprecated function to get the public key from a session. Use ssh_get_server_publickey instead. ```APIDOC ## ssh_get_publickey ### Description Deprecated function to get the public key from a session. ### Signature SSH_DEPRECATED LIBSSH_API int ssh_get_publickey(ssh_session session, ssh_key *key) ``` -------------------------------- ### Keyboard-Interactive Authentication Example Source: https://api.libssh.org/stable/libssh_tutor_authentication.html This C function demonstrates how to perform keyboard-interactive authentication using libssh. It iteratively prompts the user for input based on server-provided questions and echoes the input according to the server's instructions. ```c int authenticate_kbdint(ssh_session session) { int rc; rc = ssh_userauth_kbdint(session, NULL, NULL); while (rc == SSH_AUTH_INFO) { const char *name = NULL, *instruction = NULL; int nprompts, iprompt; name = ssh_userauth_kbdint_getname(session); instruction = ssh_userauth_kbdint_getinstruction(session); nprompts = ssh_userauth_kbdint_getnprompts(session); if (strlen(name) > 0) printf("%s\n", name); if (strlen(instruction) > 0) printf("%s\n", instruction); for (iprompt = 0; iprompt < nprompts; iprompt++) { const char *prompt = NULL; char echo; prompt = ssh_userauth_kbdint_getprompt(session, iprompt, &echo); if (echo) { char buffer[128], *ptr; printf("%s", prompt); if (fgets(buffer, sizeof(buffer), stdin) == NULL) return SSH_AUTH_ERROR; buffer[sizeof(buffer) - 1] = '\0'; if ((ptr = strchr(buffer, '\n')) != NULL) *ptr = '\0'; if (ssh_userauth_kbdint_setanswer(session, iprompt, buffer) < 0) return SSH_AUTH_ERROR; memset(buffer, 0, strlen(buffer)); } else { char *ptr = NULL; ptr = getpass(prompt); if (ssh_userauth_kbdint_setanswer(session, iprompt, ptr) < 0) return SSH_AUTH_ERROR; } } rc = ssh_userauth_kbdint(session, NULL, NULL); } return rc; } ``` -------------------------------- ### ssh_scp_request_get_size64 (Deprecated) Source: https://api.libssh.org/stable/libssh_8h_source.html Gets the size of the file being pushed from the other party using a 64-bit integer. ```APIDOC ## ssh_scp_request_get_size64 (Deprecated) ### Description Gets the size of the file being pushed from the other party. ### Function Signature ```c SSH_DEPRECATED LIBSSH_API uint64_t ssh_scp_request_get_size64(ssh_scp scp) ``` ### Parameters * **scp** (ssh_scp) - The SCP session context. ### Return Value Returns the size of the file in bytes (uint64_t), or 0 on error. ``` -------------------------------- ### Implement a Reverse Web Server with libssh Source: https://api.libssh.org/stable/libssh_tutor_forwarding.html This C code snippet demonstrates how to set up a reverse port forward to listen on a remote server's port and forward incoming connections to a local libssh application. It includes basic HTTP response handling. ```c int web_server(ssh_session session) { int rc; ssh_channel channel = NULL; char buffer[256]; int nbytes, nwritten; int port = 0; char *peer_address = NULL; int peer_port = 0; char *helloworld = "HTTP/1.1 200 OK\n" "Content-Type: text/html\n" "Content-Length: 113\n" "\n" "\n" " \n" " Hello, World!\n" " \n" " \n" "

Hello, World!

\n" " \n" "\n"; rc = ssh_channel_listen_forward(session, NULL, 8080, NULL); if (rc != SSH_OK) { fprintf(stderr, "Error opening remote port: %s\n", ssh_get_error(session)); return rc; } channel = ssh_channel_open_forward_port(session, 60000, &port, &peer_address, &peer_port); if (channel == NULL) { fprintf(stderr, "Error waiting for incoming connection: %s\n", ssh_get_error(session)); return SSH_ERROR; } while (1) { nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0); if (nbytes < 0) { fprintf(stderr, "Error reading incoming data: %s\n", ssh_get_error(session)); ssh_channel_send_eof(channel); ssh_channel_free(channel); ssh_string_free_char(peer_address); return SSH_ERROR; } if (strncmp(buffer, "GET /", 5)) continue; nbytes = strlen(helloworld); nwritten = ssh_channel_write(channel, helloworld, nbytes); if (nwritten != nbytes) { fprintf(stderr, "Error sending answer: %s\n", ssh_get_error(session)); ssh_channel_send_eof(channel); ssh_channel_free(channel); ssh_string_free_char(peer_address); return SSH_ERROR; } printf("Sent answer to %s:%d\n", peer_address, peer_port); } ssh_channel_send_eof(channel); ssh_channel_free(channel); ssh_string_free_char(peer_address); return SSH_OK; } ``` -------------------------------- ### sftp_new Source: https://api.libssh.org/stable/sftp_8h_source.html Creates a new sftp session. ```APIDOC ## sftp_new ### Description Creates a new sftp session. ### Signature `LIBSSH_API sftp_session sftp_new(ssh_session session)` ``` -------------------------------- ### File Descriptor Management Source: https://api.libssh.org/stable/socket_8h_source.html Functions for setting and getting the file descriptor associated with a socket. ```APIDOC ## File Descriptor Management ### Description Allows setting and retrieving the underlying file descriptor associated with a socket object. ### Functions - `ssh_socket_set_fd(ssh_socket s, socket_t fd)`: Sets the file descriptor for the socket. - `ssh_socket_get_fd(ssh_socket s)`: Retrieves the file descriptor associated with the socket. ### Parameters - `ssh_socket_set_fd`: `s` (ssh_socket) - The socket object. `fd` (socket_t) - The file descriptor to set. - `ssh_socket_get_fd`: `s` (ssh_socket) - The socket object. ### Return Value - `ssh_socket_set_fd` returns an integer: 0 on success, a negative value on error. - `ssh_socket_get_fd` returns the `socket_t` file descriptor. ``` -------------------------------- ### ssh_channel_get_exit_state Source: https://api.libssh.org/stable/group__libssh__channel.html Get the exit state of the channel (error code from the executed instruction or signal). ```APIDOC ## ssh_channel_get_exit_state ### Description Get the exit state of the channel (error code from the executed instruction or signal). ### Signature int | ssh_channel_get_exit_state (ssh_channel channel, uint32_t *pexit_code, char **pexit_signal, int *pcore_dumped) ``` -------------------------------- ### chacha_ivsetup Source: https://api.libssh.org/stable/chacha_8h_source.html Sets up the ChaCha context with an initialization vector (IV) and a counter. This function prepares the context for encryption/decryption with a specific nonce and initial counter value. ```APIDOC ## chacha_ivsetup ### Description Sets up the ChaCha context with an initialization vector (IV) and a counter. ### Signature ```c void chacha_ivsetup(struct chacha_ctx *x, const uint8_t *iv, const uint8_t *ctr) ``` ### Parameters - **x** (*struct chacha_ctx &*) - Pointer to the ChaCha context to be set up. - **iv** (*const uint8_t *&*) - Pointer to the initialization vector (nonce). - **ctr** (*const uint8_t *&*) - Pointer to the initial counter value. ### Notes This function uses `__attribute__((__bounded__(__minbytes__, 2, CHACHA_NONCELEN)))` and `__attribute__((__bounded__(__minbytes__, 3, CHACHA_CTRLEN)))` for bounds checking on the IV and counter pointers, respectively. ``` -------------------------------- ### ssh_message_auth_publickey_state Source: https://api.libssh.org/stable/group__libssh__server.html Gets the state of a public key authentication attempt. Note: This function is deprecated. ```APIDOC ## ssh_message_auth_publickey_state ### Description Gets the state of a public key authentication attempt. Note: This function is deprecated. ### Function Signature `SSH_DEPRECATED LIBSSH_API enum ssh_publickey_state_e | ssh_message_auth_publickey_state (ssh_message msg)` ``` -------------------------------- ### listenForward Source: https://api.libssh.org/stable/libsshpp_8hpp_source.html Sets up a listener for incoming forwarded connections on a specified address and port. ```APIDOC ## listenForward ### Description Sets up a listener for incoming forwarded connections. ### Signature void_throwable listenForward(const char *address, int port, int &boundport) ### Parameters - **address** (const char *) - The address on which to listen for forwarded connections. - **port** (int) - The port on which to listen. - **boundport** (int &) - A reference to an integer that will be set to the actual port bound by the listener. ``` -------------------------------- ### ssh_channel_open_forward_port Source: https://api.libssh.org/stable/group__libssh__channel.html Accept an incoming TCP/IP forwarding channel and get information about incoming connection. ```APIDOC ## ssh_channel_open_forward_port ### Description Accept an incoming TCP/IP forwarding channel and get information about incoming connection. ### Signature ssh_channel | ssh_channel_open_forward_port (ssh_session session, int timeout_ms, int *destination_port, char **originator, int *originator_port) ``` -------------------------------- ### ssh_channel_accept_forward Source: https://api.libssh.org/stable/group__libssh__channel.html Accept an incoming TCP/IP forwarding channel and get some information about incoming connection. ```APIDOC ## ssh_channel_accept_forward ### Description Accept an incoming TCP/IP forwarding channel and get some information about incoming connection. ### Signature ssh_channel | ssh_channel_accept_forward (ssh_session session, int timeout_ms, int *destination_port) ``` -------------------------------- ### sftp_aio_begin_write Source: https://api.libssh.org/stable/group__libssh__sftp.html Starts an asynchronous write operation to an SFTP file. This function sends the write request to the server and prepares an aio handle for tracking the operation. It must be paired with sftp_aio_wait_write. ```APIDOC ## sftp_aio_begin_write() ### Description Starts an asynchronous write to a file using an opened SFTP file handle. This function is the first step in a two-step process (the second being `sftp_aio_wait_write()`) to avoid the request/response overhead of synchronous writes. It sends the write request to the SFTP server and allocates memory to store information about the request, returning an `sftp_aio` handle to this memory. ### Parameters - **file** (sftp_file *) - The opened SFTP file handle to write to. - **buf** (const void *) - Pointer to the buffer containing the data to write. - **len** (size_t) - The number of bytes to write. This value may be capped by the server's maximum write length. - **aio** (sftp_aio **) - Pointer to a location where the `sftp_aio` handle for the sent request will be stored. ### Returns On success, returns the number of bytes the server was requested to write (the capped value of `len`). On error, returns `SSH_ERROR` and sets SFTP and SSH errors. ### Warning - The internal file offset is updated by the number of bytes requested to write. - Failure to call `sftp_aio_wait_write()` after `sftp_aio_begin_write()` will result in memory leaks. - The `sftp_file` handle passed to this function must not be closed before `sftp_aio_wait_write()` returns. ``` -------------------------------- ### ssh_pki_ctx_new Source: https://api.libssh.org/stable/group__libssh__pki.html Allocates and initializes a new generic PKI context container. ```APIDOC ## ssh_pki_ctx_new ### Description Allocates and initializes a new generic PKI context container. This context can be used to hold various PKI-related options and states. ### Function Signature `ssh_pki_ctx ssh_pki_ctx_new(void)` ### Returns * `ssh_pki_ctx` - A pointer to the newly created PKI context. Returns NULL on failure. ``` -------------------------------- ### ssh_forward_accept Source: https://api.libssh.org/stable/group__libssh__channel.html Accept an incoming TCP/IP forwarding channel and get some information about incoming connection. ```APIDOC ## ssh_forward_accept ### Description Accept an incoming TCP/IP forwarding channel and get some information about incoming connection. ### Signature ssh_channel | **ssh_forward_accept** (ssh_session session, int timeout_ms) ``` -------------------------------- ### ssh_connect Source: https://api.libssh.org/stable/libssh_8h_source.html Establishes a connection to the SSH server. ```APIDOC ## ssh_connect ### Description Connects to the SSH server using the provided session context. ### Function Signature ```c LIBSSH_API int ssh_connect(ssh_session session) ``` ### Parameters * **session** (ssh_session) - The SSH session context, which should be configured with server details. ### Return Value Returns 0 on success, or a negative value on error. ``` -------------------------------- ### Get SSH Protocol Version Source: https://api.libssh.org/stable/libsshpp_8hpp_source.html Retrieves the SSH protocol version string negotiated with the server. ```cpp int getVersion(){ return ssh_get_version(c_session); } ``` -------------------------------- ### ssh_key_get_signature_algorithm Source: https://api.libssh.org/stable/group__libssh__pki.html Gets the signature algorithm name to be used with a given key type for an SSH session. ```APIDOC ## ssh_key_get_signature_algorithm() ### Description Gets the signature algorithm name to be used with a given key type for an SSH session. ### Parameters #### Path Parameters - **session** (ssh_session) - In - SSH session. - **type** (enum ssh_keytypes_e) - In - The algorithm type to convert. ### Returns A string for the keytype or NULL if unknown. ``` -------------------------------- ### Initialize and Set SSH Bind Callbacks Source: https://api.libssh.org/stable/group__libssh__server.html Demonstrates how to initialize an `ssh_callbacks_struct` and then set these callbacks for an SSH bind. The `userdata` parameter can be used to pass private data to the callback functions. ```c struct ssh_callbacks_struct cb = { .userdata = data, .auth_function = my_auth_function }; ssh_callbacks_init(&cb); ssh_bind_set_callbacks(session, &cb); ``` -------------------------------- ### Get OpenSSH Version Source: https://api.libssh.org/stable/libsshpp_8hpp_source.html Retrieves the OpenSSH protocol version string from the server. This can be useful for compatibility checks. ```cpp int getOpensshVersion(){ return ssh_get_openssh_version(c_session); } ``` -------------------------------- ### Connect to SSH Server Source: https://api.libssh.org/stable/libsshpp_8hpp_source.html Establishes a connection to the SSH server. This function should be called after setting necessary session options. ```cpp void_throwable connect(){ int ret=ssh_connect(c_session); ssh_throw(ret); return_throwable; } ``` -------------------------------- ### Get Disconnect Message Source: https://api.libssh.org/stable/libsshpp_8hpp_source.html Retrieves the disconnect message sent by the server. This is useful for understanding the reason for disconnection. ```cpp const char *getDisconnectMessage(){ const char *msg=ssh_get_disconnect_message(c_session); return msg; } ``` -------------------------------- ### connect Source: https://api.libssh.org/stable/classssh_1_1Session.html Establishes a connection to the remote SSH host. ```APIDOC ## connect() ### Description Establishes a connection to the remote SSH host. ### Method `void_throwable connect()` ### Exceptions - SshException: Thrown on error. ``` -------------------------------- ### Get SSH Message Subtype Source: https://api.libssh.org/stable/group__libssh__messages.html Retrieves the subtype of an SSH message. Returns -1 if an error occurs. ```c int ssh_message_subtype (ssh_message msg) ``` -------------------------------- ### Get SSH Message Type Source: https://api.libssh.org/stable/group__libssh__messages.html Retrieves the type of an SSH message. Returns -1 if an error occurs. ```c int ssh_message_type (ssh_message msg) ``` -------------------------------- ### Get Last Error Message Source: https://api.libssh.org/stable/libsshpp_8hpp_source.html Retrieves the last error message associated with the SSH session. This is helpful for debugging. ```cpp const char *getError(){ return ssh_get_error(c_session); } ``` -------------------------------- ### Write Strings Asynchronously with SFTP AIO Source: https://api.libssh.org/stable/libssh_tutor_sftp_aio.html Demonstrates writing multiple strings to a file asynchronously using sftp_aio_begin_write and sftp_aio_wait_write. It includes error handling and cleanup using sftp_aio_free. ```c void print_sftp_error(sftp_session sftp) { if (sftp == NULL) { return; } fprintf(stderr, "sftp error : %d\n", sftp_get_error(sftp)); fprintf(stderr, "ssh error : %s\n", ssh_get_error(sftp->session)); } // Returns 0 on success, -1 on error int write_strings(sftp_file file) { const char * strings[] = { "This is the first string", "This is the second string", "This is the third string", "This is the fourth string" }; size_t string_count = sizeof(strings) / sizeof(strings[0]); size_t i; sftp_session sftp = NULL; sftp_aio aio = NULL; int rc; if (file == NULL) { return -1; } ... // Code to initialize the queue which will be used to store sftp aio // handles sftp = file->sftp; for (i = 0; i < string_count; ++i) { rc = sftp_aio_begin_write(file, strings[i], strlen(strings[i]), &aio); if (rc == SSH_ERROR) { print_sftp_error(sftp); goto err; } // Pseudo code ENQUEUE aio in the queue of sftp aio handles } for (i = 0; i < string_count; ++i) { // Pseudo code aio = DEQUEUE an sftp aio handle from the queue of sftp aio handles; rc = sftp_aio_wait_write(&aio); if (rc == SSH_ERROR) { print_sftp_error(sftp); goto err; } } ... // Code to destroy the queue in which sftp aio handles were // stored return 0; err: while (queue is not empty) { // Pseudo code aio = DEQUEUE an sftp aio handle from the queue of sftp aio handles; sftp_aio_free(aio); } ... // Code to destroy the queue in which sftp aio handles were // stored. return -1; } ``` -------------------------------- ### Get Current Threading Type Source: https://api.libssh.org/stable/group__libssh__threads.html Returns a string indicating the type of threading implementation currently in use by libssh. ```c const char * ssh_threads_get_type (void) ``` -------------------------------- ### chacha_keysetup Source: https://api.libssh.org/stable/chacha_8h_source.html Sets up the ChaCha context with a given key and key bits. This function is used to initialize the encryption context with the secret key. ```APIDOC ## chacha_keysetup ### Description Sets up the ChaCha context with a given key and key bits. ### Signature ```c void chacha_keysetup(struct chacha_ctx *x, const uint8_t *k, uint32_t kbits) ``` ### Parameters - **x** (*struct chacha_ctx &*) - Pointer to the ChaCha context to be set up. - **k** (*const uint8_t *&*) - Pointer to the secret key. - **kbits** (*uint32_t*) - The number of bits in the key (e.g., 128 or 256). ### Notes This function uses `__attribute__((__bounded__(__minbytes__, 2, CHACHA_MINKEYLEN)))` for bounds checking on the key pointer `k`. ```