The SFTPServer class is used to create a SFTP Server.
ipworkssftp_sftpserver_open(); ipworkssftp_sftpserver_close($res); ipworkssftp_sftpserver_register_callback($res, $id, $function); ipworkssftp_sftpserver_get_last_error($res); ipworkssftp_sftpserver_get_last_error_code($res); ipworkssftp_sftpserver_set($res, $id, $index, $value); ipworkssftp_sftpserver_get($res, $id, $index); ipworkssftp_sftpserver_do_config($res, $configurationstring); ipworkssftp_sftpserver_do_disconnect($res, $connectionid); ipworkssftp_sftpserver_do_doevents($res); ipworkssftp_sftpserver_do_exchangekeys($res, $connectionid); ipworkssftp_sftpserver_do_reset($res); ipworkssftp_sftpserver_do_setfilelist($res, $connectionid, $list); ipworkssftp_sftpserver_do_shutdown($res);
The SFTPServer class provides a simple way to create a SFTP server. Any SFTP client will be able to connect and transfer files to and from the server.
To begin, first provide a valid certificate with private key in the SSHCert property.
Set the RootDirectory property to a valid local path. When clients connect they will see this as their initial directory.
To start the server set Listening to true.
Client authentication is handled through the SSHUserAuthRequest event. Inside this event, the Accept parameter determines whether authentication is accepted; this parameter should be set to True if a successful authentication is detected and False otherwise.
When a client connects, the AuthMethod parameter indicates the method of authentication the client wishes to use. Connecting clients will initially attempt authentication with an AuthMethod of "none". This is done with the expectation that the request will fail and the server will provide a list of support authentication methods. The client then selects an available method and re-authenticates. If AuthMethod is "none", Accept should be set to False.
For password authentication, the User parameter will hold the client's username and the AuthParam parameter will hold the password provided by the client. An external list of known usernames and passwords should be maintained to check these values against.
For publickey authentication, the User parameter will hold the client's username and the AuthParam parameter will hold the key provided by the client. This key should be compared to and external list of known keys and usernames.
For keyboard-interactive authentication, the SSHUserAuthRequest event will fire multiple times; once for each prompt and response sent by the client. The index of the response is specified as a suffix in the AuthMethod parameter (e.g. keyboard-interactive-1, keyboard-interactive-2, etc), and AuthParam will contain the client's response to the prompt. Finally, SSHUserAuthRequest will fire one last time with AuthMethod set to "keyboard-interactive" and AuthParam set to an empty string. The Accept parameter must be set to True each time the event fires in order for the authentication process to succeed.
When a client requests a directory listing, the DirList event fires with the Path parameter set to the directory to enumerate. If the directory listing is allowed, the appropriate set of files should be passed to the SetFileList method. The StatusCode parameter should be set according to the status of the operation, and the valid status codes can be found in the documentation for the DirList event.
Event handlers are the primary method of customizing the class's functionality. When a client attempts to connect, open a file, authenticate to the server, etc, the corresponding SFTPServer event will fire to allow for custom handling of the client's request.
The following events are fired both before and after the requested operation is executed:
Each of these events has a BeforeExec event parameter that is True when the event is fired before execution of the operation, and False after execution of the operation. Handling the event before execution provides an opportunity to use custom logic to determine whether the operation should be denied, diverted, or otherwise modified. Handling the event after execution provides an opportunity to report success or any errors related to the operation to the client.
The following events are fired only after the requested operation is executed:
Any logic to deny opening a file for read or write should be done in the FileOpen event handler.
Note: Server components are designed to process events as they occur. To ensure events are processed in a timely manner DoEvents should be called in a loop after the server is started.
The following is the full list of the properties of the class with short descriptions. Click on the links for further details.
|ConnectionBacklog||The maximum number of pending connections maintained by the TCP/IP subsystem.|
|SFTPConnectionCount||The number of records in the SFTPConnection arrays.|
|SFTPConnectionConnected||Used to disconnect individual connections and/or show their status.|
|SFTPConnectionErrorMessage||ErrorMessage is used together with status codes returned from events to send informative errors back to the SFTP client through the SSH_FXP_STATUS message.|
|SFTPConnectionFileData||The FileData should be set or read when processing read/write file events.|
|SFTPConnectionLocalAddress||This property shows the IP address of the interface through which the connection is passing.|
|SFTPConnectionProtocolVersion||The ProtocolVersion shows the SFTP protocol version negotiated with the client when the SFTP connection was established.|
|SFTPConnectionRemoteHost||The RemoteHost shows the IP address of the remote host through which the connection is coming.|
|SFTPConnectionRemotePort||The RemotePort shows the TCP port on the remote host through which the connection is coming.|
|SFTPConnectionTimeout||A timeout for the class.|
|DefaultAuthMethods||Specifies the supported authentication methods.|
|DefaultTimeout||An initial timeout value to be used by incoming connections.|
|KeyboardInteractiveMessage||The instructions to send to the client during keyboard-interactive authentication.|
|KeyboardInteractivePromptCount||The number of records in the KeyboardInteractivePrompt arrays.|
|KeyboardInteractivePromptEcho||Specifies if the client should echo the value entered by the user or not.|
|KeyboardInteractivePromptPrompt||The prompt label/text the client should present to the user.|
|Listening||If True, the class accepts incoming connections on LocalPort.|
|LocalHost||The name of the local host or user-assigned IP interface through which connections are initiated or accepted.|
|LocalPort||The TCP port in the local host where the class listens.|
|RootDirectory||The root directory for the entire SFTP server.|
|SSHCertEncoded||The certificate (PEM/base64 encoded).|
|SSHCertStore||The name of the certificate store for the client certificate.|
|SSHCertStorePassword||If the certificate store is of a type that requires a password, this property is used to specify that password in order to open the certificate store.|
|SSHCertStoreType||The type of certificate store for this certificate.|
|SSHCertSubject||The subject of the certificate used for client authentication.|
|SSHCompressionAlgorithms||A comma-separated list containing all allowable compression algorithms.|
|SSHEncryptionAlgorithms||A comma-separated list containing all allowable encryption algorithms.|
The following is the full list of the methods of the class with short descriptions. Click on the links for further details.
|Config||Sets or retrieves a configuration setting.|
|Disconnect||Disconnect the specified client.|
|DoEvents||Processes events from the internal message queue.|
|ExchangeKeys||Causes the class to exchange a new set of session keys on the specified connection.|
|Reset||Reset the class.|
|SetFileList||Sets the file list for a connection during a directory listing request.|
|Shutdown||Shuts down the server.|
The following is the full list of the events fired by the class with short descriptions. Click on the links for further details.
|Connected||Fired immediately after a connection completes (or fails).|
|ConnectionRequest||Fired when a request for connection comes from a remote host.|
|DirCreate||Fires when a client wants to create a new directory.|
|DirList||Fires when a client attempts to open a directory for listing.|
|DirRemove||Fires when a client wants to delete a directory.|
|Disconnected||Fired when a connection is closed.|
|Error||Information about errors during data delivery.|
|FileClose||Fires when a client attempts to close an open file or directory handle.|
|FileOpen||Fires when a client wants to open or create a file.|
|FileRead||Fires when a client wants to read from an open file.|
|FileRemove||Fires when a client wants to delete a file.|
|FileRename||Fires when a client wants to rename a file.|
|FileWrite||Fires when a client wants to write to an open file.|
|GetAttributes||Fires when a client needs to get file information.|
|Log||Fires once for each log message.|
|ResolvePath||Fires when a client attempts to canonicalize a path.|
|SetAttributes||Fires when a client attempts to set file or directory attributes.|
|SSHStatus||Shows the progress of the secure connection.|
|SSHUserAuthRequest||Fires when a client attempts to authenticate a connection.|
The following is a list of configuration settings for the class with short descriptions. Click on the links for further details.
|DirListBufferSize[ConnectionId]||The number of entries to be returned in one response to a request for a directory listing.|
|MaskSensitive||Masks passwords in logs.|
|ProtocolVersion||The highest allowable SFTP version to use.|
|RestrictUserToHomeDir[ConnectionId]||Whether to restrict the user to their home directory.|
|ServerEOL||Specifies the line endings used in files on the server.|
|SFTPErrorMessage[ConnectionId]||Specifies the error message to be returned to the client.|
|UserRootDirectory[ConnectionId]||The path of the server root directory for a particular user.|
|KeyboardInteractivePrompts[ConnectionId]||Specifies custom keyboard-interactive prompts for particular connections.|
|KeyRenegotiationThreshold||Sets the threshold for the SSH Key Renegotiation.|
|LogLevel||Specifies the level of detail that is logged.|
|MaxAuthAttempts||The maximum authentication attempts allowed before forcing a disconnect.|
|ServerSSHVersionString||The SSH version string sent to connecting clients.|
|SSHKeepAliveCountMax||The maximum number of keep alive packets to send without a response.|
|SSHKeepAliveInterval||The interval between keep alive packets.|
|SSHKeyExchangeAlgorithms||Specifies the supported key exchange algorithms.|
|SSHMacAlgorithms||Specifies the supported Mac algorithms.|
|SSHPublicKeyAlgorithms||Specifies the supported public key algorithms.|
|SSHVersionPattern||The pattern used to match the remote host's version string.|
|UserAuthBanner[ConnectionId]||A custom user authentication banner.|
|AllowedClients||A comma-separated list of host names or IP addresses that can access the class.|
|BindExclusively||Whether or not the class considers a local port reserved for exclusive use.|
|ConnectionUID||The unique connectionId for a connection.|
|DefaultConnectionTimeout||The inactivity timeout applied to the SSL handshake.|
|InBufferSize||The size in bytes of the incoming queue of the socket.|
|KeepAliveInterval||The retry interval, in milliseconds, to be used when a TCP keep-alive packet is sent and no response is received.|
|KeepAliveRetryCount||The number of keep-alive packets to be sent before the remotehost is considered disconnected.|
|KeepAliveTime||The inactivity time in milliseconds before a TCP keep-alive packet is sent.|
|MaxConnections||The maximum number of connections available.|
|OutBufferSize||The size in bytes of the outgoing queue of the socket.|
|TcpNoDelay||Whether or not to delay when sending packets.|
|UseIOCP||Whether to use the completion port I/O model.|
|UseIPv6||Whether to use IPv6.|
|UseWindowsMessages||Whether to use the WSAAsyncSelect I/O model.|
|BuildInfo||Information about the product's build.|
|CodePage||The system code page used for Unicode to Multibyte translations.|
|LicenseInfo||Information about the current license.|
|ProcessIdleEvents||Whether the class uses its internal event loop to process events when the main thread is idle.|
|SelectWaitMillis||The length of time in milliseconds the class will wait when DoEvents is called if there are no events to process.|
|UseInternalSecurityAPI||Tells the class whether or not to use the system security libraries or an internal implementation.|