Table of Contents

Logging and diagnostics

SshSharp reports what it does through the standard .NET channels: ILogger for logs, an ActivitySource for traces and a Meter for metrics, all named SshSharp. None of them ever contain passwords, private keys, command text, user names or host names.

When to use

  • A connection fails and the exception message is not enough: log at Debug.
  • You run SshSharp in a service: export traces and metrics with OpenTelemetry.
  • You need to know what a server negotiated (for an audit, or to find hosts without post-quantum key exchange).

Log

using var loggerFactory = LoggerFactory.Create(builder => builder
    .AddSimpleConsole(o => o.TimestampFormat = "HH:mm:ss ")
    .SetMinimumLevel(LogLevel.Debug));

await using var client = await SshClient.ConnectAsync("example.com", 22, new SshClientOptions
{
    UserName = "deploy",
    Password = Environment.GetEnvironmentVariable("DEPLOY_PASSWORD"),
    HostKeyVerifier = verifier,
    Logger = loggerFactory.CreateLogger("SshSharp"),   // never logs passwords, keys, command text or user names
}, cancellationToken);

At Information: connected (algorithms and host key fingerprint), authenticated (which method), identity files and agent keys that were skipped and why, host keys recorded by UpdateHostKeys, and connections without post-quantum key exchange. At Debug: key exchanges and rekeys, channels and sessions, each authentication attempt.

With dependency injection, clients log through the container's ILoggerFactory automatically, under the category SshSharp.

Inspect a connection

Console.WriteLine($"server:    {client.ServerIdentification}");                      // SSH-2.0-OpenSSH_9.9 ...
Console.WriteLine($"host key:  {client.HostKey.KeyType} {client.HostKey.Fingerprint}");
Console.WriteLine($"kex:       {client.Algorithms.KeyExchange} (post-quantum: {client.Algorithms.IsPostQuantum})");
Console.WriteLine($"cipher:    {client.Algorithms.EncryptionClientToServer}");
Console.WriteLine($"strict kex: {client.Algorithms.StrictKeyExchange}");
Console.WriteLine($"round trip: {(await client.PingAsync(cancellationToken)).TotalMilliseconds:F1} ms");
Console.WriteLine($"client:    {SshSharpInfo.SoftwareVersion}");                       // SshSharp_1.0.0

The client also has the connection's endpoints, when it was made, its session id and how many bytes it has carried:

Console.WriteLine($"server:     {client.ServerIdentification}");         // SSH-2.0-OpenSSH_9.9
Console.WriteLine($"remote:     {client.RemoteEndPoint}");               // 192.0.2.10:22 (null over a stream that is no socket)
Console.WriteLine($"local:      {client.LocalEndPoint}");                // 198.51.100.7:50514
Console.WriteLine($"connected:  {client.ConnectedAt:u} ({DateTimeOffset.UtcNow - client.ConnectedAt:hh\\:mm\\:ss} ago)");
Console.WriteLine($"session id: {Convert.ToHexString(client.SessionId.Span)}");
Console.WriteLine($"traffic:    {client.BytesSent:N0} bytes sent, {client.BytesReceived:N0} received");
Console.WriteLine($"cipher:     {client.Algorithms.EncryptionClientToServer}");
Console.WriteLine($"compressed: {client.Algorithms.CompressionServerToClient}");  // zlib@openssh.com, or none

These are for your own reports: SshSharp never logs or records the endpoints itself. See Tune and inspect a connection.

Trace and measure with OpenTelemetry

builder.Services.AddOpenTelemetry()
    .WithTracing(tracing => tracing.AddSource(SshTelemetry.SourceName))
    .WithMetrics(metrics => metrics.AddMeter(SshTelemetry.SourceName));

The SshSharp.Connect span covers connecting, key exchange and authentication (each ProxyJump hop is a span of its own inside it), with SshSharp.Authenticate inside it for the method that logged in and how many attempts it took. SshSharp.Command covers each RunCommandAsync, and SshSharp.Sftp.Upload, Download, UploadDirectory and DownloadDirectory each SFTP transfer, with the bytes it moved (SshSharp.Scp.* the same for SCP). The metrics count connections, channels, commands, bytes, key exchanges, SFTP and SCP file data and forwarded connections, and time connecting and keep-alive round trips; with dependency injection, the shared connection's reconnections too. Errors and diagnostics lists every tag and instrument.

Listen without OpenTelemetry

The BCL's listeners see the same data, for a quick look in a console tool or a test:

// Without OpenTelemetry: the spans, straight from the ActivitySource. TagObjects, not Tags: Tags leaves out the numbers.
var listener = new ActivityListener
{
    ShouldListenTo = source => source.Name == SshTelemetry.SourceName,
    Sample = (ref ActivityCreationOptions<ActivityContext> _) => ActivitySamplingResult.AllDataAndRecorded,
    ActivityStopped = activity => Console.WriteLine(
        $"{activity.OperationName} {activity.Duration.TotalMilliseconds:F0} ms {activity.Status} " +
        string.Join(' ', activity.TagObjects.Select(t => $"{t.Key}={t.Value}"))),
};
ActivitySource.AddActivityListener(listener);
var listener = new MeterListener
{
    InstrumentPublished = (instrument, l) =>
    {
        if (instrument.Meter.Name == SshTelemetry.SourceName)
        {
            l.EnableMeasurementEvents(instrument);
        }
    },
};
// Most counters are long; sshsharp.key_exchanges and the open-now counts (connections, channels, forwarded connections) are
// int, and durations double.
listener.SetMeasurementEventCallback<long>((instrument, value, tags, _) => Console.WriteLine($"{instrument.Name} {value:+#;-#;0}"));
listener.SetMeasurementEventCallback<int>((instrument, value, tags, _) => Console.WriteLine($"{instrument.Name} {value:+#;-#;0}"));
listener.SetMeasurementEventCallback<double>((instrument, value, tags, _) => Console.WriteLine($"{instrument.Name} {value:F3}"));
listener.Start();

Notes and pitfalls

  • Host names are not recorded, by design (see the threat model): add server.address to a parent span of your own when you want it.
  • Nothing is recorded unless something listens, so the instrumentation costs nothing when unused.
  • Entries the server can repeat are rate-limited. Refused or failed forwarded connections, messages the client does not implement and refused forwarded-agent requests: each connection writes at most 8 a minute at their own level and the rest at Debug, with one summary entry (event id 63). See Logging.
  • Exception messages can contain what the server said (an SFTP error, a refused command). Treat them as server-controlled text before showing them to end users.
  • Comparing with ssh -vvv. The Debug log shows the same stages (key exchange, host key, authentication methods), so it is the place to look when ssh connects and SshSharp does not.

See also