A local TCP application can reach one service on the SSH server through a forward. For example, an application connects to port 18080 on its own loopback interface. The SSH server opens a connection to port 8080 on its loopback interface. The application exchanges the service's usual TCP bytes.
Assign the server to the SSHServer property of a TstSSHSenderControllerSocket. This component makes the onward TCP connection for a direct-tcpip channel. Assign the server to a TstSSHServerUsers and give the account SenderRights of [lrIPv4, lrLocalhost, lrUnprivilegedPort] for this example.
To limit the account to the intended service, keep a policy object alive while the server is active. Set its ServicePort to 8080 and assign its CheckTarget method to the server's OnAuthDirectTcpIP event. The event receives the result of the account's rights check. Keeping that result in the expression preserves an account-level refusal.
type tForwardServicePolicy = class public ServicePort: Word; procedure CheckTarget(Sender: TObject; const aAddress: string; aPort: UInt32; var aOK: Boolean); end;
procedure tForwardServicePolicy.CheckTarget(Sender: TObject; const aAddress: string; aPort: UInt32; var aOK: Boolean); begin aOK := aOK and (aAddress = '127.0.0.1') and (ServicePort <> 0) and (aPort = ServicePort); end;
uses
System.SysUtils, System.Classes, System.Math, stSocket,
StreamSec.SSH.Transport, StreamSec.SSH.ClientChannel, StreamSec.SSH.SocketClient;
First verify the SSH server's host key and sign in on the SSH client. On the client computer, call ListenForLocalForward(18080). Passing zero lets the operating system choose a port, which you can read from the returned socket's LocalPort.
function ListenForLocalForward(aPort: Word): tAbstractSocket; begin Result := NewSocket; try Result.Listen('127.0.0.1', aPort); except Result.Free; raise; end; end;
On a worker thread, call ForwardOneConnection with the listener, the authenticated SSH client and the service port (8080 here). Now connect the local application to 127.0.0.1:18080. The worker accepts one connection and opens an SSH channel to the configured service. The local application supplies only its bytes. A refused channel raises an exception before forwarding begins.
const
cBufferSize = 16384;
cTimeoutMs = 30000;
procedure ForwardOneConnection(aListener: tAbstractSocket; aSSH: TstSSHSocketClient; aServicePort: Word); var lHandle: TSocketHandle; lLocal: tAbstractSocket; lChannel: iSSHClientChannel; lStart: UInt64; begin if aServicePort = 0 then raise EArgumentException.Create('Supply the service port on the SSH server'); if not aListener.WaitForData(cTimeoutMs) then raise EInOutError.Create('Timed out waiting for a local connection'); lHandle := aListener.AcceptHandle; if lHandle = cInvalidSocket then raise EInOutError.Create('Could not accept the local connection'); lLocal := NewSocket(lHandle); try lChannel := aSSH.CreateChannel('127.0.0.1', aServicePort, lLocal.RemoteAddress, lLocal.RemotePort); try lStart := TThread.GetTickCount64; while lChannel.State = csConnecting do begin if TThread.GetTickCount64 - lStart >= cTimeoutMs then raise EInOutError.Create('Timed out opening the SSH channel'); TThread.Sleep(5); end; if lChannel.State <> csConnected then raise EInOutError.CreateFmt('SSH server refused the channel (%d): %s', [lChannel.ErrorCode, lChannel.ErrorMessage]); Relay(lLocal, lChannel); finally lChannel.Close; end; finally lLocal.Free; end; end;
The sample allows 30 seconds for a local connection, 30 seconds for a channel to open and 30 seconds without data during the transfer. Choose an idle timeout appropriate for the service. After the worker returns, call it again to serve the next connection, or free the listener. Keep the SSH client connected until the worker has finished.
Relay checks both directions on each pass. The SSH channel has one writer, which reads up to the space in the peer's window. The other direction retains any bytes the local socket could take only in part. When the local application finishes sending, the worker sends SSH EOF and continues reading the service's reply. It drains the reply before closing the local socket's sending side.
procedure Relay(aLocal: tAbstractSocket; const aChannel: iSSHClientChannel); var lUp, lDown: TBytes; lCount, lWindow, lSent, lDownOffset, lDownCount: Integer; lLocalEOF, lRemoteEOF, lRemoteDone, lProgress: Boolean; lLastProgress: UInt64; begin SetLength(lUp, cBufferSize); SetLength(lDown, cBufferSize); lLocalEOF := False; lRemoteEOF := False; lDownCount := 0; lDownOffset := 0; lLastProgress := TThread.GetTickCount64; repeat lProgress := False; lRemoteDone := aChannel.PeerEOF or (aChannel.State <> csConnected); if not lRemoteEOF and (lDownCount = 0) then begin if aChannel.RecvLength > 0 then begin lDownCount := aChannel.Recv(lDown, 0, Length(lDown), False); lDownOffset := 0; end else if lRemoteDone then begin aLocal.ShutdownSend; lRemoteEOF := True; end; end; if (lDownCount > 0) and aLocal.WaitForWrite(0) then begin lSent := aLocal.Send(lDown[lDownOffset], lDownCount); if lSent = 0 then raise EInOutError.Create('Local connection closed during write'); if lSent > 0 then begin Inc(lDownOffset, lSent); Dec(lDownCount, lSent); lProgress := True; end; end; if lRemoteEOF and (lLocalEOF or (aChannel.State <> csConnected)) then Exit; // This worker is the channel's only writer. Read what its window accepts. lWindow := aChannel.RemoteWindowSize; if (aChannel.State = csConnected) and not lLocalEOF and (lWindow > 0) and aLocal.WaitForData(0) then begin lCount := aLocal.Receive(lUp[0], Min(lWindow, Length(lUp))); if lCount = 0 then begin aChannel.SendEOF; lLocalEOF := True; lProgress := True; end else if lCount > 0 then begin if aChannel.Send(lUp, 0, lCount) <> Cardinal(lCount) then raise EInOutError.Create('SSH channel closed during write'); lProgress := True; end; end; if lProgress then lLastProgress := TThread.GetTickCount64 else if TThread.GetTickCount64 - lLastProgress >= cTimeoutMs then raise EInOutError.Create('Forwarding idle timeout') else TThread.Sleep(5); until False; end;
The SSH notes describe channel flow control and TCP half-close behavior.
TstSSHSocketClient · TstSSHSocketServer · TstSSHServerUsers · TstSSHSenderControllerSocket · StreamSec.SSH.SocketClient · StreamSec.SSH.ClientChannel · StreamSec.SSH.Transport · StreamSec.SSH.SocketServer · StreamSec.SSH.Server · StreamSec.SSH.DirectSenderSocket · stSocket