| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405 |
- using System;
- using System.Collections.Generic;
- using System.Net;
- using System.Net.Sockets;
- using System.Security.Cryptography;
- using System.Text;
- using System.Text.RegularExpressions;
- using System.Threading;
- using Renci.SshNet.Channels;
- using Renci.SshNet.Common;
- using Renci.SshNet.Compression;
- using Renci.SshNet.Messages;
- using Renci.SshNet.Messages.Authentication;
- using Renci.SshNet.Messages.Connection;
- using Renci.SshNet.Messages.Transport;
- using Renci.SshNet.Security;
- using System.Globalization;
- using System.Linq;
- using Renci.SshNet.Abstractions;
- using Renci.SshNet.Security.Cryptography;
- namespace Renci.SshNet
- {
- /// <summary>
- /// Provides functionality to connect and interact with SSH server.
- /// </summary>
- public partial class Session : ISession
- {
- private const byte Null = 0x00;
- private const byte CarriageReturn = 0x0d;
- private const byte LineFeed = 0x0a;
- /// <summary>
- /// Specifies an infinite waiting period.
- /// </summary>
- /// <remarks>
- /// The value of this field is <c>-1</c> millisecond.
- /// </remarks>
- internal static readonly TimeSpan InfiniteTimeSpan = new TimeSpan(0, 0, 0, 0, -1);
- /// <summary>
- /// Specifies an infinite waiting period.
- /// </summary>
- /// <remarks>
- /// The value of this field is <c>-1</c>.
- /// </remarks>
- internal static readonly int Infinite = -1;
- /// <summary>
- /// Specifies maximum packet size defined by the protocol.
- /// </summary>
- private const int MaximumSshPacketSize = LocalChannelDataPacketSize + 3000;
- /// <summary>
- /// Holds the initial local window size for the channels.
- /// </summary>
- /// <value>
- /// 2 MB.
- /// </value>
- private const int InitialLocalWindowSize = LocalChannelDataPacketSize * 32;
- /// <summary>
- /// Holds the maximum size of channel data packets that we receive.
- /// </summary>
- /// <value>
- /// 64 KB.
- /// </value>
- private const int LocalChannelDataPacketSize = 1024*64;
- #if FEATURE_REGEX_COMPILE
- private static readonly Regex ServerVersionRe = new Regex("^SSH-(?<protoversion>[^-]+)-(?<softwareversion>.+)( SP.+)?$", RegexOptions.Compiled);
- #else
- private static readonly Regex ServerVersionRe = new Regex("^SSH-(?<protoversion>[^-]+)-(?<softwareversion>.+)( SP.+)?$");
- #endif
- /// <summary>
- /// Controls how many authentication attempts can take place at the same time.
- /// </summary>
- /// <remarks>
- /// Some server may restrict number to prevent authentication attacks
- /// </remarks>
- private static readonly SemaphoreLight AuthenticationConnection = new SemaphoreLight(3);
- /// <summary>
- /// Holds metada about session messages
- /// </summary>
- private SshMessageFactory _sshMessageFactory;
- /// <summary>
- /// Holds connection socket.
- /// </summary>
- private Socket _socket;
- /// <summary>
- /// Holds locker object for the socket
- /// </summary>
- private readonly object _socketLock = new object();
- /// <summary>
- /// Holds a <see cref="WaitHandle"/> that is signaled when the message listener loop has completed.
- /// </summary>
- private EventWaitHandle _messageListenerCompleted;
- /// <summary>
- /// Specifies outbound packet number
- /// </summary>
- private volatile uint _outboundPacketSequence;
- /// <summary>
- /// Specifies incoming packet number
- /// </summary>
- private uint _inboundPacketSequence;
- /// <summary>
- /// WaitHandle to signal that last service request was accepted
- /// </summary>
- private EventWaitHandle _serviceAccepted = new AutoResetEvent(false);
- /// <summary>
- /// WaitHandle to signal that exception was thrown by another thread.
- /// </summary>
- private EventWaitHandle _exceptionWaitHandle = new ManualResetEvent(false);
- /// <summary>
- /// WaitHandle to signal that key exchange was completed.
- /// </summary>
- private EventWaitHandle _keyExchangeCompletedWaitHandle = new ManualResetEvent(false);
- /// <summary>
- /// WaitHandle to signal that bytes have been read from the socket.
- /// </summary>
- private EventWaitHandle _bytesReadFromSocket = new ManualResetEvent(false);
- /// <summary>
- /// WaitHandle to signal that key exchange is in progress.
- /// </summary>
- private bool _keyExchangeInProgress;
- /// <summary>
- /// Exception that need to be thrown by waiting thread
- /// </summary>
- private Exception _exception;
- /// <summary>
- /// Specifies whether connection is authenticated
- /// </summary>
- private bool _isAuthenticated;
- /// <summary>
- /// Specifies whether user issued Disconnect command or not
- /// </summary>
- private bool _isDisconnecting;
- private IKeyExchange _keyExchange;
- private HashAlgorithm _serverMac;
- private HashAlgorithm _clientMac;
- private Cipher _clientCipher;
- private Cipher _serverCipher;
- private Compressor _serverDecompression;
- private Compressor _clientCompression;
- private SemaphoreLight _sessionSemaphore;
- /// <summary>
- /// Holds the factory to use for creating new services.
- /// </summary>
- private readonly IServiceFactory _serviceFactory;
- /// <summary>
- /// Gets the session semaphore that controls session channels.
- /// </summary>
- /// <value>
- /// The session semaphore.
- /// </value>
- public SemaphoreLight SessionSemaphore
- {
- get
- {
- if (_sessionSemaphore == null)
- {
- lock (this)
- {
- if (_sessionSemaphore == null)
- {
- _sessionSemaphore = new SemaphoreLight(ConnectionInfo.MaxSessions);
- }
- }
- }
- return _sessionSemaphore;
- }
- }
- private bool _isDisconnectMessageSent;
- private uint _nextChannelNumber;
- /// <summary>
- /// Gets the next channel number.
- /// </summary>
- /// <value>
- /// The next channel number.
- /// </value>
- private uint NextChannelNumber
- {
- get
- {
- uint result;
- lock (this)
- {
- result = _nextChannelNumber++;
- }
- return result;
- }
- }
- /// <summary>
- /// Gets a value indicating whether the session is connected.
- /// </summary>
- /// <value>
- /// <c>true</c> if the session is connected; otherwise, <c>false</c>.
- /// </value>
- /// <remarks>
- /// This methods returns true in all but the following cases:
- /// <list type="bullet">
- /// <item>
- /// <description>The <see cref="Session"/> is disposed.</description>
- /// </item>
- /// <item>
- /// <description>The SSH_MSG_DISCONNECT message - which is used to disconnect from the server - has been sent.</description>
- /// </item>
- /// <item>
- /// <description>The client has not been authenticated successfully.</description>
- /// </item>
- /// <item>
- /// <description>The listener thread - which is used to receive messages from the server - has stopped.</description>
- /// </item>
- /// <item>
- /// <description>The socket used to communicate with the server is no longer connected.</description>
- /// </item>
- /// </list>
- /// </remarks>
- public bool IsConnected
- {
- get
- {
- if (_disposed || _isDisconnectMessageSent || !_isAuthenticated)
- return false;
- if (_messageListenerCompleted == null || _messageListenerCompleted.WaitOne(0))
- return false;
- var isSocketConnected = false;
- IsSocketConnected(ref isSocketConnected);
- return isSocketConnected;
- }
- }
- /// <summary>
- /// Gets the session id.
- /// </summary>
- /// <value>
- /// The session id, or <c>null</c> if the client has not been authenticated.
- /// </value>
- public byte[] SessionId { get; private set; }
- private Message _clientInitMessage;
- /// <summary>
- /// Gets the client init message.
- /// </summary>
- /// <value>The client init message.</value>
- public Message ClientInitMessage
- {
- get
- {
- if (_clientInitMessage == null)
- {
- _clientInitMessage = new KeyExchangeInitMessage
- {
- KeyExchangeAlgorithms = ConnectionInfo.KeyExchangeAlgorithms.Keys.ToArray(),
- ServerHostKeyAlgorithms = ConnectionInfo.HostKeyAlgorithms.Keys.ToArray(),
- EncryptionAlgorithmsClientToServer = ConnectionInfo.Encryptions.Keys.ToArray(),
- EncryptionAlgorithmsServerToClient = ConnectionInfo.Encryptions.Keys.ToArray(),
- MacAlgorithmsClientToServer = ConnectionInfo.HmacAlgorithms.Keys.ToArray(),
- MacAlgorithmsServerToClient = ConnectionInfo.HmacAlgorithms.Keys.ToArray(),
- CompressionAlgorithmsClientToServer = ConnectionInfo.CompressionAlgorithms.Keys.ToArray(),
- CompressionAlgorithmsServerToClient = ConnectionInfo.CompressionAlgorithms.Keys.ToArray(),
- LanguagesClientToServer = new[] {string.Empty},
- LanguagesServerToClient = new[] {string.Empty},
- FirstKexPacketFollows = false,
- Reserved = 0
- };
- }
- return _clientInitMessage;
- }
- }
- /// <summary>
- /// Gets or sets the server version string.
- /// </summary>
- /// <value>The server version.</value>
- public string ServerVersion { get; private set; }
- /// <summary>
- /// Gets or sets the client version string.
- /// </summary>
- /// <value>The client version.</value>
- public string ClientVersion { get; private set; }
- /// <summary>
- /// Gets or sets the connection info.
- /// </summary>
- /// <value>The connection info.</value>
- public ConnectionInfo ConnectionInfo { get; private set; }
- /// <summary>
- /// Occurs when an error occurred.
- /// </summary>
- public event EventHandler<ExceptionEventArgs> ErrorOccured;
- /// <summary>
- /// Occurs when session has been disconnected from the server.
- /// </summary>
- public event EventHandler<EventArgs> Disconnected;
- /// <summary>
- /// Occurs when host key received.
- /// </summary>
- public event EventHandler<HostKeyEventArgs> HostKeyReceived;
- /// <summary>
- /// Occurs when <see cref="BannerMessage"/> message is received from the server.
- /// </summary>
- public event EventHandler<MessageEventArgs<BannerMessage>> UserAuthenticationBannerReceived;
- #region Message events
- /// <summary>
- /// Occurs when <see cref="DisconnectMessage"/> message received
- /// </summary>
- internal event EventHandler<MessageEventArgs<DisconnectMessage>> DisconnectReceived;
- /// <summary>
- /// Occurs when <see cref="IgnoreMessage"/> message received
- /// </summary>
- internal event EventHandler<MessageEventArgs<IgnoreMessage>> IgnoreReceived;
- /// <summary>
- /// Occurs when <see cref="UnimplementedMessage"/> message received
- /// </summary>
- internal event EventHandler<MessageEventArgs<UnimplementedMessage>> UnimplementedReceived;
- /// <summary>
- /// Occurs when <see cref="DebugMessage"/> message received
- /// </summary>
- internal event EventHandler<MessageEventArgs<DebugMessage>> DebugReceived;
- /// <summary>
- /// Occurs when <see cref="ServiceRequestMessage"/> message received
- /// </summary>
- internal event EventHandler<MessageEventArgs<ServiceRequestMessage>> ServiceRequestReceived;
- /// <summary>
- /// Occurs when <see cref="ServiceAcceptMessage"/> message received
- /// </summary>
- internal event EventHandler<MessageEventArgs<ServiceAcceptMessage>> ServiceAcceptReceived;
- /// <summary>
- /// Occurs when <see cref="KeyExchangeInitMessage"/> message received
- /// </summary>
- internal event EventHandler<MessageEventArgs<KeyExchangeInitMessage>> KeyExchangeInitReceived;
- /// <summary>
- /// Occurs when <see cref="NewKeysMessage"/> message received
- /// </summary>
- internal event EventHandler<MessageEventArgs<NewKeysMessage>> NewKeysReceived;
- /// <summary>
- /// Occurs when <see cref="RequestMessage"/> message received
- /// </summary>
- internal event EventHandler<MessageEventArgs<RequestMessage>> UserAuthenticationRequestReceived;
- /// <summary>
- /// Occurs when <see cref="FailureMessage"/> message received
- /// </summary>
- internal event EventHandler<MessageEventArgs<FailureMessage>> UserAuthenticationFailureReceived;
- /// <summary>
- /// Occurs when <see cref="SuccessMessage"/> message received
- /// </summary>
- internal event EventHandler<MessageEventArgs<SuccessMessage>> UserAuthenticationSuccessReceived;
- /// <summary>
- /// Occurs when <see cref="GlobalRequestMessage"/> message received
- /// </summary>
- internal event EventHandler<MessageEventArgs<GlobalRequestMessage>> GlobalRequestReceived;
- /// <summary>
- /// Occurs when <see cref="RequestSuccessMessage"/> message received
- /// </summary>
- public event EventHandler<MessageEventArgs<RequestSuccessMessage>> RequestSuccessReceived;
- /// <summary>
- /// Occurs when <see cref="RequestFailureMessage"/> message received
- /// </summary>
- public event EventHandler<MessageEventArgs<RequestFailureMessage>> RequestFailureReceived;
- /// <summary>
- /// Occurs when <see cref="ChannelOpenMessage"/> message received
- /// </summary>
- public event EventHandler<MessageEventArgs<ChannelOpenMessage>> ChannelOpenReceived;
- /// <summary>
- /// Occurs when <see cref="ChannelOpenConfirmationMessage"/> message received
- /// </summary>
- public event EventHandler<MessageEventArgs<ChannelOpenConfirmationMessage>> ChannelOpenConfirmationReceived;
- /// <summary>
- /// Occurs when <see cref="ChannelOpenFailureMessage"/> message received
- /// </summary>
- public event EventHandler<MessageEventArgs<ChannelOpenFailureMessage>> ChannelOpenFailureReceived;
- /// <summary>
- /// Occurs when <see cref="ChannelWindowAdjustMessage"/> message received
- /// </summary>
- public event EventHandler<MessageEventArgs<ChannelWindowAdjustMessage>> ChannelWindowAdjustReceived;
- /// <summary>
- /// Occurs when <see cref="ChannelDataMessage"/> message received
- /// </summary>
- public event EventHandler<MessageEventArgs<ChannelDataMessage>> ChannelDataReceived;
- /// <summary>
- /// Occurs when <see cref="ChannelExtendedDataMessage"/> message received
- /// </summary>
- public event EventHandler<MessageEventArgs<ChannelExtendedDataMessage>> ChannelExtendedDataReceived;
- /// <summary>
- /// Occurs when <see cref="ChannelEofMessage"/> message received
- /// </summary>
- public event EventHandler<MessageEventArgs<ChannelEofMessage>> ChannelEofReceived;
- /// <summary>
- /// Occurs when <see cref="ChannelCloseMessage"/> message received
- /// </summary>
- public event EventHandler<MessageEventArgs<ChannelCloseMessage>> ChannelCloseReceived;
- /// <summary>
- /// Occurs when <see cref="ChannelRequestMessage"/> message received
- /// </summary>
- public event EventHandler<MessageEventArgs<ChannelRequestMessage>> ChannelRequestReceived;
- /// <summary>
- /// Occurs when <see cref="ChannelSuccessMessage"/> message received
- /// </summary>
- public event EventHandler<MessageEventArgs<ChannelSuccessMessage>> ChannelSuccessReceived;
- /// <summary>
- /// Occurs when <see cref="ChannelFailureMessage"/> message received
- /// </summary>
- public event EventHandler<MessageEventArgs<ChannelFailureMessage>> ChannelFailureReceived;
- /// <summary>
- /// Occurs when message received and is not handled by any of the event handlers
- /// </summary>
- internal event EventHandler<MessageEventArgs<Message>> MessageReceived;
- #endregion
- /// <summary>
- /// Initializes a new instance of the <see cref="Session"/> class.
- /// </summary>
- /// <param name="connectionInfo">The connection info.</param>
- /// <param name="serviceFactory">The factory to use for creating new services.</param>
- /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is <c>null</c>.</exception>
- /// <exception cref="ArgumentNullException"><paramref name="serviceFactory"/> is <c>null</c>.</exception>
- internal Session(ConnectionInfo connectionInfo, IServiceFactory serviceFactory)
- {
- if (connectionInfo == null)
- throw new ArgumentNullException("connectionInfo");
- if (serviceFactory == null)
- throw new ArgumentNullException("serviceFactory");
- ClientVersion = "SSH-2.0-Renci.SshNet.SshClient.0.0.1";
- ConnectionInfo = connectionInfo;
- _serviceFactory = serviceFactory;
- _messageListenerCompleted = new ManualResetEvent(true);
- }
- /// <summary>
- /// Connects to the server.
- /// </summary>
- /// <exception cref="SocketException">Socket connection to the SSH server or proxy server could not be established, or an error occurred while resolving the hostname.</exception>
- /// <exception cref="SshConnectionException">SSH session could not be established.</exception>
- /// <exception cref="SshAuthenticationException">Authentication of SSH session failed.</exception>
- /// <exception cref="ProxyException">Failed to establish proxy connection.</exception>
- public void Connect()
- {
- if (IsConnected)
- return;
- try
- {
- AuthenticationConnection.Wait();
- if (IsConnected)
- return;
- lock (this)
- {
- // If connected don't connect again
- if (IsConnected)
- return;
- // reset connection specific information
- Reset();
- // Build list of available messages while connecting
- _sshMessageFactory = new SshMessageFactory();
- switch (ConnectionInfo.ProxyType)
- {
- case ProxyTypes.None:
- SocketConnect(ConnectionInfo.Host, ConnectionInfo.Port);
- break;
- case ProxyTypes.Socks4:
- SocketConnect(ConnectionInfo.ProxyHost, ConnectionInfo.ProxyPort);
- ConnectSocks4();
- break;
- case ProxyTypes.Socks5:
- SocketConnect(ConnectionInfo.ProxyHost, ConnectionInfo.ProxyPort);
- ConnectSocks5();
- break;
- case ProxyTypes.Http:
- SocketConnect(ConnectionInfo.ProxyHost, ConnectionInfo.ProxyPort);
- ConnectHttp();
- break;
- }
- Match versionMatch;
- // Get server version from the server,
- // ignore text lines which are sent before if any
- while (true)
- {
- var serverVersion = SocketReadLine(ConnectionInfo.Timeout);
- if (serverVersion == null)
- throw new SshConnectionException("Server response does not contain SSH protocol identification.", DisconnectReason.ProtocolError);
- versionMatch = ServerVersionRe.Match(serverVersion);
- if (versionMatch.Success)
- {
- ServerVersion = serverVersion;
- break;
- }
- }
- // Set connection versions
- ConnectionInfo.ServerVersion = ServerVersion;
- ConnectionInfo.ClientVersion = ClientVersion;
- // Get server SSH version
- var version = versionMatch.Result("${protoversion}");
- var softwareName = versionMatch.Result("${softwareversion}");
- DiagnosticAbstraction.Log(string.Format("Server version '{0}' on '{1}'.", version, softwareName));
- if (!(version.Equals("2.0") || version.Equals("1.99")))
- {
- throw new SshConnectionException(string.Format(CultureInfo.CurrentCulture, "Server version '{0}' is not supported.", version), DisconnectReason.ProtocolVersionNotSupported);
- }
- SocketAbstraction.Send(_socket, Encoding.UTF8.GetBytes(string.Format(CultureInfo.InvariantCulture, "{0}\x0D\x0A", ClientVersion)));
- // Register Transport response messages
- RegisterMessage("SSH_MSG_DISCONNECT");
- RegisterMessage("SSH_MSG_IGNORE");
- RegisterMessage("SSH_MSG_UNIMPLEMENTED");
- RegisterMessage("SSH_MSG_DEBUG");
- RegisterMessage("SSH_MSG_SERVICE_ACCEPT");
- RegisterMessage("SSH_MSG_KEXINIT");
- RegisterMessage("SSH_MSG_NEWKEYS");
- // Some server implementations might sent this message first, prior establishing encryption algorithm
- RegisterMessage("SSH_MSG_USERAUTH_BANNER");
- // mark the message listener threads as started
- _messageListenerCompleted.Reset();
- // Start incoming request listener
- ThreadAbstraction.ExecuteThread(MessageListener);
- // Wait for key exchange to be completed
- WaitOnHandle(_keyExchangeCompletedWaitHandle);
- // If sessionId is not set then its not connected
- if (SessionId == null)
- {
- Disconnect();
- return;
- }
- // Request user authorization service
- SendMessage(new ServiceRequestMessage(ServiceName.UserAuthentication));
- // Wait for service to be accepted
- WaitOnHandle(_serviceAccepted);
- if (string.IsNullOrEmpty(ConnectionInfo.Username))
- {
- throw new SshException("Username is not specified.");
- }
- // Some servers send a global request immediately after successful authentication
- // Avoid race condition by already enabling SSH_MSG_GLOBAL_REQUEST before authentication
- RegisterMessage("SSH_MSG_GLOBAL_REQUEST");
- ConnectionInfo.Authenticate(this, _serviceFactory);
- _isAuthenticated = true;
- // Register Connection messages
- RegisterMessage("SSH_MSG_REQUEST_SUCCESS");
- RegisterMessage("SSH_MSG_REQUEST_FAILURE");
- RegisterMessage("SSH_MSG_CHANNEL_OPEN_CONFIRMATION");
- RegisterMessage("SSH_MSG_CHANNEL_OPEN_FAILURE");
- RegisterMessage("SSH_MSG_CHANNEL_WINDOW_ADJUST");
- RegisterMessage("SSH_MSG_CHANNEL_EXTENDED_DATA");
- RegisterMessage("SSH_MSG_CHANNEL_REQUEST");
- RegisterMessage("SSH_MSG_CHANNEL_SUCCESS");
- RegisterMessage("SSH_MSG_CHANNEL_FAILURE");
- RegisterMessage("SSH_MSG_CHANNEL_DATA");
- RegisterMessage("SSH_MSG_CHANNEL_EOF");
- RegisterMessage("SSH_MSG_CHANNEL_CLOSE");
- Monitor.Pulse(this);
- }
- }
- finally
- {
- AuthenticationConnection.Release();
- }
- }
- /// <summary>
- /// Disconnects from the server.
- /// </summary>
- /// <remarks>
- /// This sends a <b>SSH_MSG_DISCONNECT</b> message to the server, waits for the
- /// server to close the socket on its end and subsequently closes the client socket.
- /// </remarks>
- public void Disconnect()
- {
- DiagnosticAbstraction.Log(string.Format("[{0}] Disconnecting session", ToHex(SessionId)));
- Disconnect(DisconnectReason.ByApplication, "Connection terminated by the client.");
- // at this point, we are sure that the listener thread will stop as we've
- // disconnected the socket, so lets wait until the message listener thread
- // has completed
- if (_messageListenerCompleted != null)
- {
- _messageListenerCompleted.WaitOne();
- }
- }
- private void Disconnect(DisconnectReason reason, string message)
- {
- _isDisconnecting = true;
- // send disconnect message to the server if the connection is still open
- // and the disconnect message has not yet been sent
- //
- // note that this should also cause the listener thread to be stopped as
- // the server should respond by closing the socket
- if (reason == DisconnectReason.ByApplication)
- {
- SendDisconnect(reason, message);
- }
- // disconnect socket, and dispose it
- SocketDisconnectAndDispose();
- }
- /// <summary>
- /// Waits for the specified handle or the exception handle for the receive thread
- /// to signal within the connection timeout.
- /// </summary>
- /// <param name="waitHandle">The wait handle.</param>
- /// <exception cref="SshConnectionException">A received package was invalid or failed the message integrity check.</exception>
- /// <exception cref="SshOperationTimeoutException">None of the handles are signaled in time and the session is not disconnecting.</exception>
- /// <exception cref="SocketException">A socket error was signaled while receiving messages from the server.</exception>
- /// <remarks>
- /// When neither handles are signaled in time and the session is not closing, then the
- /// session is disconnected.
- /// </remarks>
- void ISession.WaitOnHandle(WaitHandle waitHandle)
- {
- WaitOnHandle(waitHandle, ConnectionInfo.Timeout);
- }
- /// <summary>
- /// Waits for the specified handle or the exception handle for the receive thread
- /// to signal within the connection timeout.
- /// </summary>
- /// <param name="waitHandle">The wait handle.</param>
- /// <exception cref="SshConnectionException">A received package was invalid or failed the message integrity check.</exception>
- /// <exception cref="SshOperationTimeoutException">None of the handles are signaled in time and the session is not disconnecting.</exception>
- /// <exception cref="SocketException">A socket error was signaled while receiving messages from the server.</exception>
- /// <remarks>
- /// When neither handles are signaled in time and the session is not closing, then the
- /// session is disconnected.
- /// </remarks>
- internal void WaitOnHandle(WaitHandle waitHandle)
- {
- WaitOnHandle(waitHandle, ConnectionInfo.Timeout);
- }
- /// <summary>
- /// Waits for the specified handle or the exception handle for the receive thread
- /// to signal within the specified timeout.
- /// </summary>
- /// <param name="waitHandle">The wait handle.</param>
- /// <param name="timeout">The time to wait for any of the handles to become signaled.</param>
- /// <exception cref="SshConnectionException">A received package was invalid or failed the message integrity check.</exception>
- /// <exception cref="SshOperationTimeoutException">None of the handles are signaled in time and the session is not disconnecting.</exception>
- /// <exception cref="SocketException">A socket error was signaled while receiving messages from the server.</exception>
- internal void WaitOnHandle(WaitHandle waitHandle, TimeSpan timeout)
- {
- if (waitHandle == null)
- throw new ArgumentNullException("waitHandle");
- var waitHandles = new[]
- {
- _exceptionWaitHandle,
- _messageListenerCompleted,
- waitHandle
- };
- switch (WaitHandle.WaitAny(waitHandles, timeout))
- {
- case 0:
- throw _exception;
- case 1:
- throw new SshConnectionException("Client not connected.");
- case WaitHandle.WaitTimeout:
- // when the session is disconnecting, a timeout is likely when no
- // network connectivity is available; depending on the configured
- // timeout either the WaitAny times out first or a SocketException
- // detailing a timeout thrown hereby completing the listener thread
- // (which makes us end up in case 1). Either way, we do not want to
- // report an exception to the client when we're disconnecting anyway
- if (!_isDisconnecting)
- {
- throw new SshOperationTimeoutException("Session operation has timed out");
- }
- break;
- }
- }
- /// <summary>
- /// Sends a message to the server.
- /// </summary>
- /// <param name="message">The message to send.</param>
- /// <exception cref="SshConnectionException">The client is not connected.</exception>
- /// <exception cref="SshOperationTimeoutException">The operation timed out.</exception>
- /// <exception cref="InvalidOperationException">The size of the packet exceeds the maximum size defined by the protocol.</exception>
- internal void SendMessage(Message message)
- {
- if (_socket == null || !_socket.CanWrite())
- throw new SshConnectionException("Client not connected.");
- if (_keyExchangeInProgress && !(message is IKeyExchangedAllowed))
- {
- // Wait for key exchange to be completed
- WaitOnHandle(_keyExchangeCompletedWaitHandle);
- }
- DiagnosticAbstraction.Log(string.Format("[{0}] SendMessage to server '{1}': '{2}'.", ToHex(SessionId), message.GetType().Name, message));
- // Messages can be sent by different thread so we need to synchronize it
- var paddingMultiplier = _clientCipher == null ? (byte)8 : Math.Max((byte)8, _serverCipher.MinimumSize); // Should be recalculate base on cipher min length if cipher specified
- var packetData = message.GetPacket(paddingMultiplier, _clientCompression);
- // Lock handling of _outboundPacketSequence since it must be sent sequently to server
- lock (_socketLock)
- {
- if (_socket == null || !_socket.Connected)
- throw new SshConnectionException("Client not connected.");
- byte[] hash = null;
- var packetDataOffset = 4; // first four bytes are reserved for outbound packet sequence
- if (_clientMac != null)
- {
- // write outbound packet sequence to start of packet data
- _outboundPacketSequence.Write(packetData, 0);
- // calculate packet hash
- hash = _clientMac.ComputeHash(packetData);
- }
- // Encrypt packet data
- if (_clientCipher != null)
- {
- packetData = _clientCipher.Encrypt(packetData, packetDataOffset, (packetData.Length - packetDataOffset));
- packetDataOffset = 0;
- }
- if (packetData.Length > MaximumSshPacketSize)
- {
- throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Packet is too big. Maximum packet size is {0} bytes.", MaximumSshPacketSize));
- }
- var packetLength = packetData.Length - packetDataOffset;
- if (hash == null)
- {
- SocketAbstraction.Send(_socket, packetData, packetDataOffset, packetLength);
- }
- else
- {
- var data = new byte[packetLength + (_clientMac.HashSize / 8)];
- Buffer.BlockCopy(packetData, packetDataOffset, data, 0, packetLength);
- Buffer.BlockCopy(hash, 0, data, packetLength, hash.Length);
- SocketAbstraction.Send(_socket, data, 0, data.Length);
- }
- _outboundPacketSequence++;
- Monitor.Pulse(_socketLock);
- }
- }
- /// <summary>
- /// Sends a message to the server.
- /// </summary>
- /// <param name="message">The message to send.</param>
- /// <returns>
- /// <c>true</c> if the message was sent to the server; otherwise, <c>false</c>.
- /// </returns>
- /// <exception cref="InvalidOperationException">The size of the packet exceeds the maximum size defined by the protocol.</exception>
- /// <remarks>
- /// This methods returns <c>false</c> when the attempt to send the message results in a
- /// <see cref="SocketException"/> or a <see cref="SshException"/>.
- /// </remarks>
- private bool TrySendMessage(Message message)
- {
- try
- {
- SendMessage(message);
- return true;
- }
- catch (SshException ex)
- {
- DiagnosticAbstraction.Log(string.Format("Failure sending message server '{0}': '{1}' => {2}", message.GetType().Name, message, ex));
- return false;
- }
- catch (SocketException ex)
- {
- DiagnosticAbstraction.Log(string.Format("Failure sending message server '{0}': '{1}' => {2}", message.GetType().Name, message, ex));
- return false;
- }
- }
- /// <summary>
- /// Receives the message from the server.
- /// </summary>
- /// <returns>Incoming SSH message.</returns>
- /// <exception cref="SshConnectionException"></exception>
- /// <remarks>
- /// We need no locking here since all messages are read by a single thread.
- /// </remarks>
- private Message ReceiveMessage()
- {
- // the length of the packet sequence field in bytes
- const int inboundPacketSequenceLength = 4;
- // The length of the "packet length" field in bytes
- const int packetLengthFieldLength = 4;
- // The length of the "padding length" field in bytes
- const int paddingLengthFieldLength = 1;
- // Determine the size of the first block, which is 8 or cipher block size (whichever is larger) bytes
- var blockSize = _serverCipher == null ? (byte)8 : Math.Max((byte)8, _serverCipher.MinimumSize);
- // Read first block - which starts with the packet length
- var firstBlock = Read(blockSize);
- DiagnosticAbstraction.Log(string.Format("[{0}] FirstBlock [{1}]: {2}", ToHex(SessionId), blockSize, ToHex(firstBlock)));
- if (_serverCipher != null)
- {
- firstBlock = _serverCipher.Decrypt(firstBlock);
- DiagnosticAbstraction.Log(string.Format("[{0}] FirstBlock decrypted [{1}]: {2}", ToHex(SessionId), firstBlock.Length, ToHex(firstBlock)));
- }
- var packetLength = (uint)(firstBlock[0] << 24 | firstBlock[1] << 16 | firstBlock[2] << 8 | firstBlock[3]);
- // Test packet minimum and maximum boundaries
- if (packetLength < Math.Max((byte)16, blockSize) - 4 || packetLength > MaximumSshPacketSize - 4)
- throw new SshConnectionException(string.Format(CultureInfo.CurrentCulture, "Bad packet length: {0}.", packetLength), DisconnectReason.ProtocolError);
- // Determine the number of bytes left to read; We've already read "blockSize" bytes, but the
- // "packet length" field itself - which is 4 bytes - is not included in the length of the packet
- var bytesToRead = (int) (packetLength - (blockSize - packetLengthFieldLength));
- // Construct buffer for holding the payload and the inbound packet sequence as we need both in order
- // to generate the hash
- var data = new byte[bytesToRead + blockSize + inboundPacketSequenceLength];
- _inboundPacketSequence.Write(data, 0);
- Buffer.BlockCopy(firstBlock, 0, data, inboundPacketSequenceLength, firstBlock.Length);
- byte[] serverHash = null;
- if (_serverMac != null)
- {
- serverHash = new byte[_serverMac.HashSize / 8];
- bytesToRead += serverHash.Length;
- }
- if (bytesToRead > 0)
- {
- var nextBlocks = Read(bytesToRead);
- DiagnosticAbstraction.Log(string.Format("[{0}] NextBlocks [{1}]: {2}", ToHex(SessionId), bytesToRead, ToHex(nextBlocks)));
- if (serverHash != null)
- {
- Buffer.BlockCopy(nextBlocks, nextBlocks.Length - serverHash.Length, serverHash, 0, serverHash.Length);
- nextBlocks = nextBlocks.Take(nextBlocks.Length - serverHash.Length);
- DiagnosticAbstraction.Log(string.Format("[{0}] ServerHash [{1}]: {2}", ToHex(SessionId), serverHash.Length, ToHex(serverHash)));
- }
- if (nextBlocks.Length > 0)
- {
- if (_serverCipher != null)
- {
- nextBlocks = _serverCipher.Decrypt(nextBlocks);
- DiagnosticAbstraction.Log(string.Format("[{0}] NextBlocks decrypted [{1}]: {2}", ToHex(SessionId), nextBlocks.Length, ToHex(nextBlocks)));
- }
- nextBlocks.CopyTo(data, blockSize + inboundPacketSequenceLength);
- }
- }
- var paddingLength = data[inboundPacketSequenceLength + packetLengthFieldLength];
- var messagePayloadLength = (int) (packetLength - paddingLength - paddingLengthFieldLength);
- var messagePayloadOffset = inboundPacketSequenceLength + packetLengthFieldLength + paddingLengthFieldLength;
- // Validate message against MAC
- if (_serverMac != null)
- {
- var clientHash = _serverMac.ComputeHash(data);
- if (!serverHash.IsEqualTo(clientHash))
- {
- throw new SshConnectionException("MAC error", DisconnectReason.MacError);
- }
- }
- if (_serverDecompression != null)
- {
- data = _serverDecompression.Decompress(data, messagePayloadOffset, messagePayloadLength);
- // data now only contains the decompressed payload, and as such the offset is reset to zero
- messagePayloadOffset = 0;
- }
- DiagnosticAbstraction.Log(string.Format("[{0}] Message info (Sequence:{1},MessagePayloadLength:{2})", ToHex(SessionId), _inboundPacketSequence, messagePayloadLength));
- _inboundPacketSequence++;
- return LoadMessage(data, messagePayloadOffset);
- }
- private void SendDisconnect(DisconnectReason reasonCode, string message)
- {
- // only send a disconnect message if it wasn't already sent, and we're
- // still connected
- if (_isDisconnectMessageSent || !IsConnected)
- return;
- var disconnectMessage = new DisconnectMessage(reasonCode, message);
- // send the disconnect message, but ignore the outcome
- TrySendMessage(disconnectMessage);
- _isDisconnectMessageSent = true;
- }
- partial void HandleMessageCore(Message message);
- /// <summary>
- /// Handles the message.
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="message">The message.</param>
- private void HandleMessage<T>(T message) where T : Message
- {
- OnMessageReceived(message);
- }
- #region Handle transport messages
- /// <summary>
- /// Invoked via reflection.
- /// </summary>
- private void HandleMessage(DisconnectMessage message)
- {
- OnDisconnectReceived(message);
- Disconnect(message.ReasonCode, message.Description);
- }
- /// <summary>
- /// Invoked via reflection.
- /// </summary>
- private void HandleMessage(IgnoreMessage message)
- {
- OnIgnoreReceived(message);
- }
- /// <summary>
- /// Invoked via reflection.
- /// </summary>
- private void HandleMessage(UnimplementedMessage message)
- {
- OnUnimplementedReceived(message);
- }
- /// <summary>
- /// Invoked via reflection.
- /// </summary>
- private void HandleMessage(DebugMessage message)
- {
- OnDebugReceived(message);
- }
- /// <summary>
- /// Invoked via reflection.
- /// </summary>
- private void HandleMessage(ServiceRequestMessage message)
- {
- OnServiceRequestReceived(message);
- }
- /// <summary>
- /// Invoked via reflection.
- /// </summary>
- private void HandleMessage(ServiceAcceptMessage message)
- {
- // TODO: Refactor to avoid this method here
- OnServiceAcceptReceived(message);
- _serviceAccepted.Set();
- }
- /// <summary>
- /// Invoked via reflection.
- /// </summary>
- private void HandleMessage(KeyExchangeInitMessage message)
- {
- OnKeyExchangeInitReceived(message);
- }
- /// <summary>
- /// Invoked via reflection.
- /// </summary>
- private void HandleMessage(NewKeysMessage message)
- {
- OnNewKeysReceived(message);
- }
- #endregion
- #region Handle User Authentication messages
- /// <summary>
- /// Invoked via reflection.
- /// </summary>
- private void HandleMessage(RequestMessage message)
- {
- OnUserAuthenticationRequestReceived(message);
- }
- /// <summary>
- /// Invoked via reflection.
- /// </summary>
- private void HandleMessage(FailureMessage message)
- {
- OnUserAuthenticationFailureReceived(message);
- }
- /// <summary>
- /// Invoked via reflection.
- /// </summary>
- private void HandleMessage(SuccessMessage message)
- {
- OnUserAuthenticationSuccessReceived(message);
- }
- /// <summary>
- /// Invoked via reflection.
- /// </summary>
- private void HandleMessage(BannerMessage message)
- {
- OnUserAuthenticationBannerReceived(message);
- }
- #endregion
- #region Handle connection messages
- /// <summary>
- /// Invoked via reflection.
- /// </summary>
- private void HandleMessage(GlobalRequestMessage message)
- {
- OnGlobalRequestReceived(message);
- }
- /// <summary>
- /// Invoked via reflection.
- /// </summary>
- private void HandleMessage(RequestSuccessMessage message)
- {
- OnRequestSuccessReceived(message);
- }
- /// <summary>
- /// Invoked via reflection.
- /// </summary>
- private void HandleMessage(RequestFailureMessage message)
- {
- OnRequestFailureReceived(message);
- }
- /// <summary>
- /// Invoked via reflection.
- /// </summary>
- private void HandleMessage(ChannelOpenMessage message)
- {
- OnChannelOpenReceived(message);
- }
- /// <summary>
- /// Invoked via reflection.
- /// </summary>
- private void HandleMessage(ChannelOpenConfirmationMessage message)
- {
- OnChannelOpenConfirmationReceived(message);
- }
- /// <summary>
- /// Invoked via reflection.
- /// </summary>
- private void HandleMessage(ChannelOpenFailureMessage message)
- {
- OnChannelOpenFailureReceived(message);
- }
- /// <summary>
- /// Invoked via reflection.
- /// </summary>
- private void HandleMessage(ChannelWindowAdjustMessage message)
- {
- OnChannelWindowAdjustReceived(message);
- }
- /// <summary>
- /// Invoked via reflection.
- /// </summary>
- private void HandleMessage(ChannelDataMessage message)
- {
- OnChannelDataReceived(message);
- }
- /// <summary>
- /// Invoked via reflection.
- /// </summary>
- private void HandleMessage(ChannelExtendedDataMessage message)
- {
- OnChannelExtendedDataReceived(message);
- }
- /// <summary>
- /// Invoked via reflection.
- /// </summary>
- private void HandleMessage(ChannelEofMessage message)
- {
- OnChannelEofReceived(message);
- }
- /// <summary>
- /// Invoked via reflection.
- /// </summary>
- private void HandleMessage(ChannelCloseMessage message)
- {
- OnChannelCloseReceived(message);
- }
- /// <summary>
- /// Invoked via reflection.
- /// </summary>
- private void HandleMessage(ChannelRequestMessage message)
- {
- OnChannelRequestReceived(message);
- }
- /// <summary>
- /// Invoked via reflection.
- /// </summary>
- private void HandleMessage(ChannelSuccessMessage message)
- {
- OnChannelSuccessReceived(message);
- }
- /// <summary>
- /// Invoked via reflection.
- /// </summary>
- private void HandleMessage(ChannelFailureMessage message)
- {
- OnChannelFailureReceived(message);
- }
- #endregion
- #region Handle received message events
- /// <summary>
- /// Called when <see cref="DisconnectMessage"/> received.
- /// </summary>
- /// <param name="message"><see cref="DisconnectMessage"/> message.</param>
- protected virtual void OnDisconnectReceived(DisconnectMessage message)
- {
- DiagnosticAbstraction.Log(string.Format("[{0}] Disconnect received: {1} {2}", ToHex(SessionId), message.ReasonCode, message.Description));
- _exception = new SshConnectionException(string.Format(CultureInfo.InvariantCulture, "The connection was closed by the server: {0} ({1}).", message.Description, message.ReasonCode), message.ReasonCode);
- _exceptionWaitHandle.Set();
- var disconnectReceived = DisconnectReceived;
- if (disconnectReceived != null)
- disconnectReceived(this, new MessageEventArgs<DisconnectMessage>(message));
- var disconnected = Disconnected;
- if (disconnected != null)
- disconnected(this, new EventArgs());
- }
- /// <summary>
- /// Called when <see cref="IgnoreMessage"/> received.
- /// </summary>
- /// <param name="message"><see cref="IgnoreMessage"/> message.</param>
- protected virtual void OnIgnoreReceived(IgnoreMessage message)
- {
- var handlers = IgnoreReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs<IgnoreMessage>(message));
- }
- /// <summary>
- /// Called when <see cref="UnimplementedMessage"/> message received.
- /// </summary>
- /// <param name="message"><see cref="UnimplementedMessage"/> message.</param>
- protected virtual void OnUnimplementedReceived(UnimplementedMessage message)
- {
- var handlers = UnimplementedReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs<UnimplementedMessage>(message));
- }
- /// <summary>
- /// Called when <see cref="DebugMessage"/> message received.
- /// </summary>
- /// <param name="message"><see cref="DebugMessage"/> message.</param>
- protected virtual void OnDebugReceived(DebugMessage message)
- {
- var handlers = DebugReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs<DebugMessage>(message));
- }
- /// <summary>
- /// Called when <see cref="ServiceRequestMessage"/> message received.
- /// </summary>
- /// <param name="message"><see cref="ServiceRequestMessage"/> message.</param>
- protected virtual void OnServiceRequestReceived(ServiceRequestMessage message)
- {
- var handlers = ServiceRequestReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs<ServiceRequestMessage>(message));
- }
- /// <summary>
- /// Called when <see cref="ServiceAcceptMessage"/> message received.
- /// </summary>
- /// <param name="message"><see cref="ServiceAcceptMessage"/> message.</param>
- protected virtual void OnServiceAcceptReceived(ServiceAcceptMessage message)
- {
- var handlers = ServiceAcceptReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs<ServiceAcceptMessage>(message));
- }
- /// <summary>
- /// Called when <see cref="KeyExchangeInitMessage"/> message received.
- /// </summary>
- /// <param name="message"><see cref="KeyExchangeInitMessage"/> message.</param>
- protected virtual void OnKeyExchangeInitReceived(KeyExchangeInitMessage message)
- {
- _keyExchangeInProgress = true;
- _keyExchangeCompletedWaitHandle.Reset();
- // Disable messages that are not key exchange related
- _sshMessageFactory.DisableNonKeyExchangeMessages();
- _keyExchange = _serviceFactory.CreateKeyExchange(ConnectionInfo.KeyExchangeAlgorithms,
- message.KeyExchangeAlgorithms);
- ConnectionInfo.CurrentKeyExchangeAlgorithm = _keyExchange.Name;
- _keyExchange.HostKeyReceived += KeyExchange_HostKeyReceived;
- // Start the algorithm implementation
- _keyExchange.Start(this, message);
- var keyExchangeInitReceived = KeyExchangeInitReceived;
- if (keyExchangeInitReceived != null)
- keyExchangeInitReceived(this, new MessageEventArgs<KeyExchangeInitMessage>(message));
- }
- /// <summary>
- /// Called when <see cref="NewKeysMessage"/> message received.
- /// </summary>
- /// <param name="message"><see cref="NewKeysMessage"/> message.</param>
- protected virtual void OnNewKeysReceived(NewKeysMessage message)
- {
- // Update sessionId
- if (SessionId == null)
- {
- SessionId = _keyExchange.ExchangeHash;
- }
- // Dispose of old ciphers and hash algorithms
- if (_serverMac != null)
- {
- _serverMac.Dispose();
- _serverMac = null;
- }
- if (_clientMac != null)
- {
- _clientMac.Dispose();
- _clientMac = null;
- }
- // Update negotiated algorithms
- _serverCipher = _keyExchange.CreateServerCipher();
- _clientCipher = _keyExchange.CreateClientCipher();
- _serverMac = _keyExchange.CreateServerHash();
- _clientMac = _keyExchange.CreateClientHash();
- _clientCompression = _keyExchange.CreateCompressor();
- _serverDecompression = _keyExchange.CreateDecompressor();
- // Dispose of old KeyExchange object as it is no longer needed.
- if (_keyExchange != null)
- {
- _keyExchange.HostKeyReceived -= KeyExchange_HostKeyReceived;
- _keyExchange.Dispose();
- _keyExchange = null;
- }
- // Enable activated messages that are not key exchange related
- _sshMessageFactory.EnableActivatedMessages();
- var newKeysReceived = NewKeysReceived;
- if (newKeysReceived != null)
- newKeysReceived(this, new MessageEventArgs<NewKeysMessage>(message));
- // Signal that key exchange completed
- _keyExchangeCompletedWaitHandle.Set();
- _keyExchangeInProgress = false;
- }
- /// <summary>
- /// Called when client is disconnecting from the server.
- /// </summary>
- void ISession.OnDisconnecting()
- {
- _isDisconnecting = true;
- }
- /// <summary>
- /// Called when <see cref="RequestMessage"/> message received.
- /// </summary>
- /// <param name="message"><see cref="RequestMessage"/> message.</param>
- protected virtual void OnUserAuthenticationRequestReceived(RequestMessage message)
- {
- var handlers = UserAuthenticationRequestReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs<RequestMessage>(message));
- }
- /// <summary>
- /// Called when <see cref="FailureMessage"/> message received.
- /// </summary>
- /// <param name="message"><see cref="FailureMessage"/> message.</param>
- protected virtual void OnUserAuthenticationFailureReceived(FailureMessage message)
- {
- var handlers = UserAuthenticationFailureReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs<FailureMessage>(message));
- }
- /// <summary>
- /// Called when <see cref="SuccessMessage"/> message received.
- /// </summary>
- /// <param name="message"><see cref="SuccessMessage"/> message.</param>
- protected virtual void OnUserAuthenticationSuccessReceived(SuccessMessage message)
- {
- var handlers = UserAuthenticationSuccessReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs<SuccessMessage>(message));
- }
- /// <summary>
- /// Called when <see cref="BannerMessage"/> message received.
- /// </summary>
- /// <param name="message"><see cref="BannerMessage"/> message.</param>
- protected virtual void OnUserAuthenticationBannerReceived(BannerMessage message)
- {
- var handlers = UserAuthenticationBannerReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs<BannerMessage>(message));
- }
- /// <summary>
- /// Called when <see cref="GlobalRequestMessage"/> message received.
- /// </summary>
- /// <param name="message"><see cref="GlobalRequestMessage"/> message.</param>
- protected virtual void OnGlobalRequestReceived(GlobalRequestMessage message)
- {
- var handlers = GlobalRequestReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs<GlobalRequestMessage>(message));
- }
- /// <summary>
- /// Called when <see cref="RequestSuccessMessage"/> message received.
- /// </summary>
- /// <param name="message"><see cref="RequestSuccessMessage"/> message.</param>
- protected virtual void OnRequestSuccessReceived(RequestSuccessMessage message)
- {
- var handlers = RequestSuccessReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs<RequestSuccessMessage>(message));
- }
- /// <summary>
- /// Called when <see cref="RequestFailureMessage"/> message received.
- /// </summary>
- /// <param name="message"><see cref="RequestFailureMessage"/> message.</param>
- protected virtual void OnRequestFailureReceived(RequestFailureMessage message)
- {
- var handlers = RequestFailureReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs<RequestFailureMessage>(message));
- }
- /// <summary>
- /// Called when <see cref="ChannelOpenMessage"/> message received.
- /// </summary>
- /// <param name="message"><see cref="ChannelOpenMessage"/> message.</param>
- protected virtual void OnChannelOpenReceived(ChannelOpenMessage message)
- {
- var handlers = ChannelOpenReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs<ChannelOpenMessage>(message));
- }
- /// <summary>
- /// Called when <see cref="ChannelOpenConfirmationMessage"/> message received.
- /// </summary>
- /// <param name="message"><see cref="ChannelOpenConfirmationMessage"/> message.</param>
- protected virtual void OnChannelOpenConfirmationReceived(ChannelOpenConfirmationMessage message)
- {
- var handlers = ChannelOpenConfirmationReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs<ChannelOpenConfirmationMessage>(message));
- }
- /// <summary>
- /// Called when <see cref="ChannelOpenFailureMessage"/> message received.
- /// </summary>
- /// <param name="message"><see cref="ChannelOpenFailureMessage"/> message.</param>
- protected virtual void OnChannelOpenFailureReceived(ChannelOpenFailureMessage message)
- {
- var handlers = ChannelOpenFailureReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs<ChannelOpenFailureMessage>(message));
- }
- /// <summary>
- /// Called when <see cref="ChannelWindowAdjustMessage"/> message received.
- /// </summary>
- /// <param name="message"><see cref="ChannelWindowAdjustMessage"/> message.</param>
- protected virtual void OnChannelWindowAdjustReceived(ChannelWindowAdjustMessage message)
- {
- var handlers = ChannelWindowAdjustReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs<ChannelWindowAdjustMessage>(message));
- }
- /// <summary>
- /// Called when <see cref="ChannelDataMessage"/> message received.
- /// </summary>
- /// <param name="message"><see cref="ChannelDataMessage"/> message.</param>
- protected virtual void OnChannelDataReceived(ChannelDataMessage message)
- {
- var handlers = ChannelDataReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs<ChannelDataMessage>(message));
- }
- /// <summary>
- /// Called when <see cref="ChannelExtendedDataMessage"/> message received.
- /// </summary>
- /// <param name="message"><see cref="ChannelExtendedDataMessage"/> message.</param>
- protected virtual void OnChannelExtendedDataReceived(ChannelExtendedDataMessage message)
- {
- var handlers = ChannelExtendedDataReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs<ChannelExtendedDataMessage>(message));
- }
- /// <summary>
- /// Called when <see cref="ChannelCloseMessage"/> message received.
- /// </summary>
- /// <param name="message"><see cref="ChannelCloseMessage"/> message.</param>
- protected virtual void OnChannelEofReceived(ChannelEofMessage message)
- {
- var handlers = ChannelEofReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs<ChannelEofMessage>(message));
- }
- /// <summary>
- /// Called when <see cref="ChannelCloseMessage"/> message received.
- /// </summary>
- /// <param name="message"><see cref="ChannelCloseMessage"/> message.</param>
- protected virtual void OnChannelCloseReceived(ChannelCloseMessage message)
- {
- var handlers = ChannelCloseReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs<ChannelCloseMessage>(message));
- }
- /// <summary>
- /// Called when <see cref="ChannelRequestMessage"/> message received.
- /// </summary>
- /// <param name="message"><see cref="ChannelRequestMessage"/> message.</param>
- protected virtual void OnChannelRequestReceived(ChannelRequestMessage message)
- {
- var handlers = ChannelRequestReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs<ChannelRequestMessage>(message));
- }
- /// <summary>
- /// Called when <see cref="ChannelSuccessMessage"/> message received.
- /// </summary>
- /// <param name="message"><see cref="ChannelSuccessMessage"/> message.</param>
- protected virtual void OnChannelSuccessReceived(ChannelSuccessMessage message)
- {
- var handlers = ChannelSuccessReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs<ChannelSuccessMessage>(message));
- }
- /// <summary>
- /// Called when <see cref="ChannelFailureMessage"/> message received.
- /// </summary>
- /// <param name="message"><see cref="ChannelFailureMessage"/> message.</param>
- protected virtual void OnChannelFailureReceived(ChannelFailureMessage message)
- {
- var handlers = ChannelFailureReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs<ChannelFailureMessage>(message));
- }
- /// <summary>
- /// Called when <see cref="Message"/> message received.
- /// </summary>
- /// <param name="message"><see cref="Message"/> message.</param>
- protected virtual void OnMessageReceived(Message message)
- {
- var handlers = MessageReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs<Message>(message));
- }
- #endregion
- private void KeyExchange_HostKeyReceived(object sender, HostKeyEventArgs e)
- {
- var handlers = HostKeyReceived;
- if (handlers != null)
- handlers(this, e);
- }
- /// <summary>
- /// Reads the specified length of bytes from the server.
- /// </summary>
- /// <param name="length">The length.</param>
- /// <returns>
- /// The bytes read from the server.
- /// </returns>
- private byte[] Read(int length)
- {
- var buffer = new byte[length];
- SocketRead(length, buffer);
- return buffer;
- }
- #region Message loading functions
- /// <summary>
- /// Registers SSH message with the session.
- /// </summary>
- /// <param name="messageName">The name of the message to register with the session.</param>
- public void RegisterMessage(string messageName)
- {
- _sshMessageFactory.EnableAndActivateMessage(messageName);
- }
- /// <summary>
- /// Unregister SSH message from the session.
- /// </summary>
- /// <param name="messageName">The name of the message to unregister with the session.</param>
- public void UnRegisterMessage(string messageName)
- {
- _sshMessageFactory.DisableAndDeactivateMessage(messageName);
- }
- /// <summary>
- /// Loads a message from a given buffer.
- /// </summary>
- /// <param name="data">An array of bytes from which to construct the message.</param>
- /// <param name="offset">The zero-based byte offset in <paramref name="data"/> at which to begin reading.</param>
- /// <returns>
- /// A message constructed from <paramref name="data"/>.
- /// </returns>
- /// <exception cref="SshException">The type of the message is not supported.</exception>
- private Message LoadMessage(byte[] data, int offset)
- {
- var messageType = data[offset];
- var message = _sshMessageFactory.Create(messageType);
- DiagnosticAbstraction.Log(string.Format("[{0}] Loading message with offset '{1}': {2}", ToHex(SessionId), offset, ToHex(data, 0)));
- message.Load(data, offset);
- DiagnosticAbstraction.Log(string.Format("[{0}] ReceiveMessage from server: '{1}': '{2}'.", ToHex(SessionId), message.GetType().Name, message));
- return message;
- }
- private static string ToHex(byte[] bytes, int offset)
- {
- var byteCount = bytes.Length - offset;
- var builder = new StringBuilder(bytes.Length * 2);
- for (var i = offset; i < byteCount; i++)
- {
- var b = bytes[i];
- builder.Append(b.ToString("X2"));
- }
- return builder.ToString();
- }
- internal static string ToHex(byte[] bytes)
- {
- if (bytes == null)
- return null;
- return ToHex(bytes, 0);
- }
- #endregion
- /// <summary>
- /// Gets a value indicating whether the socket is connected.
- /// </summary>
- /// <value>
- /// <c>true</c> if the socket is connected; otherwise, <c>false</c>.
- /// </value>
- partial void IsSocketConnected(ref bool isConnected);
- /// <summary>
- /// Establishes a socket connection to the specified host and port.
- /// </summary>
- /// <param name="host">The host name of the server to connect to.</param>
- /// <param name="port">The port to connect to.</param>
- /// <exception cref="SshOperationTimeoutException">The connection failed to establish within the configured <see cref="Renci.SshNet.ConnectionInfo.Timeout"/>.</exception>
- /// <exception cref="SocketException">An error occurred trying to establish the connection.</exception>
- private void SocketConnect(string host, int port)
- {
- var ipAddress = DnsAbstraction.GetHostAddresses(host)[0];
- var ep = new IPEndPoint(ipAddress, port);
- DiagnosticAbstraction.Log(string.Format("Initiating connect to '{0}:{1}'.", host, port));
- _socket = SocketAbstraction.Connect(ep, ConnectionInfo.Timeout);
- const int socketBufferSize = 2 * MaximumSshPacketSize;
- _socket.SendBufferSize = socketBufferSize;
- _socket.ReceiveBufferSize = socketBufferSize;
- }
- /// <summary>
- /// Performs a blocking read on the socket until <paramref name="length"/> bytes are received.
- /// </summary>
- /// <param name="length">The number of bytes to read.</param>
- /// <param name="buffer">The buffer to read to.</param>
- /// <exception cref="SshConnectionException">The socket is closed.</exception>
- /// <exception cref="SshOperationTimeoutException">The read has timed-out.</exception>
- /// <exception cref="SocketException">The read failed.</exception>
- private void SocketRead(int length, byte[] buffer)
- {
- if (SocketAbstraction.Read(_socket, buffer, 0, length, InfiniteTimeSpan) > 0)
- {
- // signal that bytes have been read from the socket
- // this is used to improve accuracy of Session.IsSocketConnected
- _bytesReadFromSocket.Set();
- return;
- }
- // 2012-09-11: Kenneth_aa
- // When Disconnect or Dispose is called, this throws SshConnectionException(), which...
- // 1 - goes up to ReceiveMessage()
- // 2 - up again to MessageListener()
- // which is where there is a catch-all exception block so it can notify event listeners.
- // 3 - MessageListener then again calls RaiseError().
- // There the exception is checked for the exception thrown here (ConnectionLost), and if it matches it will not call Session.SendDisconnect().
- //
- // Adding a check for _isDisconnecting causes ReceiveMessage() to throw SshConnectionException: "Bad packet length {0}".
- //
- if (_isDisconnecting)
- throw new SshConnectionException(
- "An established connection was aborted by the software in your host machine.",
- DisconnectReason.ConnectionLost);
- throw new SshConnectionException("An established connection was aborted by the server.",
- DisconnectReason.ConnectionLost);
- }
- /// <summary>
- /// Performs a blocking read on the socket until a line is read.
- /// </summary>
- /// <param name="timeout">A <see cref="TimeSpan"/> that represents the time to wait until a line is read.</param>
- /// <exception cref="SshOperationTimeoutException">The read has timed-out.</exception>
- /// <exception cref="SocketException">An error occurred when trying to access the socket.</exception>
- /// <returns>
- /// The line read from the socket, or <c>null</c> when the remote server has shutdown and all data has been received.
- /// </returns>
- private string SocketReadLine(TimeSpan timeout)
- {
- var encoding = SshData.Ascii;
- var buffer = new List<byte>();
- var data = new byte[1];
- // read data one byte at a time to find end of line and leave any unhandled information in the buffer
- // to be processed by subsequent invocations
- do
- {
- var bytesRead = SocketAbstraction.Read(_socket, data, 0, data.Length, timeout);
- if (bytesRead == 0)
- // the remote server shut down the socket
- break;
- buffer.Add(data[0]);
- }
- while (!(buffer.Count > 0 && (buffer[buffer.Count - 1] == LineFeed || buffer[buffer.Count - 1] == Null)));
- if (buffer.Count == 0)
- return null;
- if (buffer.Count == 1 && buffer[buffer.Count - 1] == 0x00)
- // return an empty version string if the buffer consists of only a 0x00 character
- return string.Empty;
- if (buffer.Count > 1 && buffer[buffer.Count - 2] == CarriageReturn)
- // strip trailing CRLF
- return encoding.GetString(buffer.ToArray(), 0, buffer.Count - 2);
- if (buffer.Count > 1 && buffer[buffer.Count - 1] == LineFeed)
- // strip trailing LF
- return encoding.GetString(buffer.ToArray(), 0, buffer.Count - 1);
- return encoding.GetString(buffer.ToArray(), 0, buffer.Count);
- }
- /// <summary>
- /// Disconnects and disposes the socket.
- /// </summary>
- private void SocketDisconnectAndDispose()
- {
- if (_socket != null)
- {
- lock (_socketLock)
- {
- if (_socket != null)
- {
- if (_socket.Connected)
- {
- _socket.Shutdown(SocketShutdown.Send);
- SocketAbstraction.ClearReadBuffer(_socket);
- }
- _socket.Dispose();
- _socket = null;
- }
- }
- }
- }
- /// <summary>
- /// Listens for incoming message from the server and handles them. This method run as a task on separate thread.
- /// </summary>
- private void MessageListener()
- {
- try
- {
- while (_socket != null && _socket.Connected)
- {
- var message = ReceiveMessage();
- HandleMessageCore(message);
- }
- }
- catch (SocketException ex)
- {
- RaiseError(new SshConnectionException(ex.Message, DisconnectReason.ConnectionLost, ex));
- }
- catch (Exception exp)
- {
- RaiseError(exp);
- }
- finally
- {
- // signal that the message listener thread has stopped
- _messageListenerCompleted.Set();
- }
- }
- private byte SocketReadByte()
- {
- var buffer = new byte[1];
- SocketRead(1, buffer);
- return buffer[0];
- }
- private void SocketWriteByte(byte data)
- {
- SocketAbstraction.Send(_socket, new[] {data});
- }
- private void ConnectSocks4()
- {
- // Send socks version number
- SocketWriteByte(0x04);
- // Send command code
- SocketWriteByte(0x01);
- // Send port
- SocketWriteByte((byte)(ConnectionInfo.Port / 0xFF));
- SocketWriteByte((byte)(ConnectionInfo.Port % 0xFF));
- // Send IP
- var ipAddress = DnsAbstraction.GetHostAddresses(ConnectionInfo.Host)[0];
- SocketAbstraction.Send(_socket, ipAddress.GetAddressBytes());
- // Send username
- var username = SshData.Ascii.GetBytes(ConnectionInfo.ProxyUsername);
- SocketAbstraction.Send(_socket, username);
- SocketWriteByte(0x00);
- // Read 0
- if (SocketReadByte() != 0)
- {
- throw new ProxyException("SOCKS4: Null is expected.");
- }
- // Read response code
- var code = SocketReadByte();
- switch (code)
- {
- case 0x5a:
- break;
- case 0x5b:
- throw new ProxyException("SOCKS4: Connection rejected.");
- case 0x5c:
- throw new ProxyException("SOCKS4: Client is not running identd or not reachable from the server.");
- case 0x5d:
- throw new ProxyException("SOCKS4: Client's identd could not confirm the user ID string in the request.");
- default:
- throw new ProxyException("SOCKS4: Not valid response.");
- }
- var dummyBuffer = new byte[4];
- // Read 2 bytes to be ignored
- SocketRead(2, dummyBuffer);
- // Read 4 bytes to be ignored
- SocketRead(4, dummyBuffer);
- }
- private void ConnectSocks5()
- {
- // Send socks version number
- SocketWriteByte(0x05);
- // Send number of supported authentication methods
- SocketWriteByte(0x02);
- // Send supported authentication methods
- SocketWriteByte(0x00); // No authentication
- SocketWriteByte(0x02); // Username/Password
- var socksVersion = SocketReadByte();
- if (socksVersion != 0x05)
- throw new ProxyException(string.Format("SOCKS Version '{0}' is not supported.", socksVersion));
- var authenticationMethod = SocketReadByte();
- switch (authenticationMethod)
- {
- case 0x00:
- break;
- case 0x02:
- // Send version
- SocketWriteByte(0x01);
- var username = SshData.Ascii.GetBytes(ConnectionInfo.ProxyUsername);
- if (username.Length > byte.MaxValue)
- throw new ProxyException("Proxy username is too long.");
- // Send username length
- SocketWriteByte((byte)username.Length);
- // Send username
- SocketAbstraction.Send(_socket, username);
- var password = SshData.Ascii.GetBytes(ConnectionInfo.ProxyPassword);
- if (password.Length > byte.MaxValue)
- throw new ProxyException("Proxy password is too long.");
- // Send username length
- SocketWriteByte((byte)password.Length);
- // Send username
- SocketAbstraction.Send(_socket, password);
- var serverVersion = SocketReadByte();
- if (serverVersion != 1)
- throw new ProxyException("SOCKS5: Server authentication version is not valid.");
- var statusCode = SocketReadByte();
- if (statusCode != 0)
- throw new ProxyException("SOCKS5: Username/Password authentication failed.");
- break;
- case 0xFF:
- throw new ProxyException("SOCKS5: No acceptable authentication methods were offered.");
- }
- // Send socks version number
- SocketWriteByte(0x05);
- // Send command code
- SocketWriteByte(0x01); // establish a TCP/IP stream connection
- // Send reserved, must be 0x00
- SocketWriteByte(0x00);
- var ip = DnsAbstraction.GetHostAddresses(ConnectionInfo.Host)[0];
- // Send address type and address
- if (ip.AddressFamily == AddressFamily.InterNetwork)
- {
- SocketWriteByte(0x01);
- var address = ip.GetAddressBytes();
- SocketAbstraction.Send(_socket, address);
- }
- else if (ip.AddressFamily == AddressFamily.InterNetworkV6)
- {
- SocketWriteByte(0x04);
- var address = ip.GetAddressBytes();
- SocketAbstraction.Send(_socket, address);
- }
- else
- {
- throw new ProxyException(string.Format("SOCKS5: IP address '{0}' is not supported.", ip));
- }
- // Send port
- SocketWriteByte((byte)(ConnectionInfo.Port / 0xFF));
- SocketWriteByte((byte)(ConnectionInfo.Port % 0xFF));
- // Read Server SOCKS5 version
- if (SocketReadByte() != 5)
- {
- throw new ProxyException("SOCKS5: Version 5 is expected.");
- }
- // Read response code
- var status = SocketReadByte();
- switch (status)
- {
- case 0x00:
- break;
- case 0x01:
- throw new ProxyException("SOCKS5: General failure.");
- case 0x02:
- throw new ProxyException("SOCKS5: Connection not allowed by ruleset.");
- case 0x03:
- throw new ProxyException("SOCKS5: Network unreachable.");
- case 0x04:
- throw new ProxyException("SOCKS5: Host unreachable.");
- case 0x05:
- throw new ProxyException("SOCKS5: Connection refused by destination host.");
- case 0x06:
- throw new ProxyException("SOCKS5: TTL expired.");
- case 0x07:
- throw new ProxyException("SOCKS5: Command not supported or protocol error.");
- case 0x08:
- throw new ProxyException("SOCKS5: Address type not supported.");
- default:
- throw new ProxyException("SOCKS4: Not valid response.");
- }
- // Read 0
- if (SocketReadByte() != 0)
- {
- throw new ProxyException("SOCKS5: 0 byte is expected.");
- }
- var addressType = SocketReadByte();
- var responseIp = new byte[16];
- switch (addressType)
- {
- case 0x01:
- SocketRead(4, responseIp);
- break;
- case 0x04:
- SocketRead(16, responseIp);
- break;
- default:
- throw new ProxyException(string.Format("Address type '{0}' is not supported.", addressType));
- }
- var port = new byte[2];
- // Read 2 bytes to be ignored
- SocketRead(2, port);
- }
- private void ConnectHttp()
- {
- var httpResponseRe = new Regex(@"HTTP/(?<version>\d[.]\d) (?<statusCode>\d{3}) (?<reasonPhrase>.+)$");
- var httpHeaderRe = new Regex(@"(?<fieldName>[^\[\]()<>@,;:\""/?={} \t]+):(?<fieldValue>.+)?");
- SocketAbstraction.Send(_socket, SshData.Ascii.GetBytes(string.Format("CONNECT {0}:{1} HTTP/1.0\r\n", ConnectionInfo.Host, ConnectionInfo.Port)));
- // Sent proxy authorization is specified
- if (!string.IsNullOrEmpty(ConnectionInfo.ProxyUsername))
- {
- var authorization = string.Format("Proxy-Authorization: Basic {0}\r\n",
- Convert.ToBase64String(SshData.Ascii.GetBytes(string.Format("{0}:{1}", ConnectionInfo.ProxyUsername, ConnectionInfo.ProxyPassword)))
- );
- SocketAbstraction.Send(_socket, SshData.Ascii.GetBytes(authorization));
- }
- SocketAbstraction.Send(_socket, SshData.Ascii.GetBytes("\r\n"));
- HttpStatusCode? statusCode = null;
- var contentLength = 0;
- while (true)
- {
- var response = SocketReadLine(ConnectionInfo.Timeout);
- if (response == null)
- // server shut down socket
- break;
- if (statusCode == null)
- {
- var statusMatch = httpResponseRe.Match(response);
- if (statusMatch.Success)
- {
- var httpStatusCode = statusMatch.Result("${statusCode}");
- statusCode = (HttpStatusCode) int.Parse(httpStatusCode);
- if (statusCode != HttpStatusCode.OK)
- {
- var reasonPhrase = statusMatch.Result("${reasonPhrase}");
- throw new ProxyException(string.Format("HTTP: Status code {0}, \"{1}\"", httpStatusCode,
- reasonPhrase));
- }
- }
- continue;
- }
- // continue on parsing message headers coming from the server
- var headerMatch = httpHeaderRe.Match(response);
- if (headerMatch.Success)
- {
- var fieldName = headerMatch.Result("${fieldName}");
- if (fieldName.Equals("Content-Length", StringComparison.OrdinalIgnoreCase))
- {
- contentLength = int.Parse(headerMatch.Result("${fieldValue}"));
- }
- continue;
- }
- // check if we've reached the CRLF which separates request line and headers from the message body
- if (response.Length == 0)
- {
- // read response body if specified
- if (contentLength > 0)
- {
- var contentBody = new byte[contentLength];
- SocketRead(contentLength, contentBody);
- }
- break;
- }
- }
- if (statusCode == null)
- throw new ProxyException("HTTP response does not contain status line.");
- }
- /// <summary>
- /// Raises the <see cref="ErrorOccured"/> event.
- /// </summary>
- /// <param name="exp">The exp.</param>
- private void RaiseError(Exception exp)
- {
- var connectionException = exp as SshConnectionException;
- if (_isDisconnecting)
- {
- // a connection exception which is raised while isDisconnecting is normal and
- // should be ignored
- if (connectionException != null)
- return;
- // any timeout while disconnecting can be caused by loss of connectivity
- // altogether and should be ignored
- var socketException = exp as SocketException;
- if (socketException != null && socketException.SocketErrorCode == SocketError.TimedOut)
- return;
- }
- DiagnosticAbstraction.Log(string.Format("[{0}] Raised exception: {1}", ToHex(SessionId), exp));
- _exception = exp;
- _exceptionWaitHandle.Set();
- var errorOccured = ErrorOccured;
- if (errorOccured != null)
- errorOccured(this, new ExceptionEventArgs(exp));
- if (connectionException != null)
- {
- Disconnect(connectionException.DisconnectReason, exp.ToString());
- }
- }
- /// <summary>
- /// Resets connection-specific information to ensure state of a previous connection
- /// does not affect new connections.
- /// </summary>
- private void Reset()
- {
- if (_exceptionWaitHandle != null)
- _exceptionWaitHandle.Reset();
- if (_keyExchangeCompletedWaitHandle != null)
- _keyExchangeCompletedWaitHandle.Reset();
- if (_messageListenerCompleted != null)
- _messageListenerCompleted.Set();
- SessionId = null;
- _isDisconnectMessageSent = false;
- _isDisconnecting = false;
- _isAuthenticated = false;
- _exception = null;
- _keyExchangeInProgress = false;
- }
- #region IDisposable implementation
- private bool _disposed;
- /// <summary>
- /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
- /// </summary>
- public void Dispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
- /// <summary>
- /// Releases unmanaged and - optionally - managed resources
- /// </summary>
- /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
- protected virtual void Dispose(bool disposing)
- {
- if (_disposed)
- return;
- if (disposing)
- {
- DiagnosticAbstraction.Log(string.Format("[{0}] Disposing session", ToHex(SessionId)));
- Disconnect();
- var serviceAccepted = _serviceAccepted;
- if (serviceAccepted != null)
- {
- serviceAccepted.Dispose();
- _serviceAccepted = null;
- }
- var exceptionWaitHandle = _exceptionWaitHandle;
- if (exceptionWaitHandle != null)
- {
- exceptionWaitHandle.Dispose();
- _exceptionWaitHandle = null;
- }
- var keyExchangeCompletedWaitHandle = _keyExchangeCompletedWaitHandle;
- if (keyExchangeCompletedWaitHandle != null)
- {
- keyExchangeCompletedWaitHandle.Dispose();
- _keyExchangeCompletedWaitHandle = null;
- }
- var serverMac = _serverMac;
- if (serverMac != null)
- {
- serverMac.Dispose();
- _serverMac = null;
- }
- var clientMac = _clientMac;
- if (clientMac != null)
- {
- clientMac.Dispose();
- _clientMac = null;
- }
- var keyExchange = _keyExchange;
- if (keyExchange != null)
- {
- keyExchange.HostKeyReceived -= KeyExchange_HostKeyReceived;
- keyExchange.Dispose();
- _keyExchange = null;
- }
- var bytesReadFromSocket = _bytesReadFromSocket;
- if (bytesReadFromSocket != null)
- {
- bytesReadFromSocket.Dispose();
- _bytesReadFromSocket = null;
- }
- var messageListenerCompleted = _messageListenerCompleted;
- if (messageListenerCompleted != null)
- {
- messageListenerCompleted.Dispose();
- _messageListenerCompleted = null;
- }
- _disposed = true;
- }
- }
- /// <summary>
- /// Releases unmanaged resources and performs other cleanup operations before the
- /// <see cref="Session"/> is reclaimed by garbage collection.
- /// </summary>
- ~Session()
- {
- Dispose(false);
- }
- #endregion IDisposable implementation
- #region ISession implementation
- /// <summary>
- /// Gets or sets the connection info.
- /// </summary>
- /// <value>The connection info.</value>
- IConnectionInfo ISession.ConnectionInfo
- {
- get { return ConnectionInfo; }
- }
- WaitHandle ISession.MessageListenerCompleted
- {
- get { return _messageListenerCompleted; }
- }
- /// <summary>
- /// Create a new SSH session channel.
- /// </summary>
- /// <returns>
- /// A new SSH session channel.
- /// </returns>
- IChannelSession ISession.CreateChannelSession()
- {
- return new ChannelSession(this, NextChannelNumber, InitialLocalWindowSize, LocalChannelDataPacketSize);
- }
- /// <summary>
- /// Create a new channel for a locally forwarded TCP/IP port.
- /// </summary>
- /// <returns>
- /// A new channel for a locally forwarded TCP/IP port.
- /// </returns>
- IChannelDirectTcpip ISession.CreateChannelDirectTcpip()
- {
- return new ChannelDirectTcpip(this, NextChannelNumber, InitialLocalWindowSize, LocalChannelDataPacketSize);
- }
- /// <summary>
- /// Creates a "forwarded-tcpip" SSH channel.
- /// </summary>
- /// <returns>
- /// A new "forwarded-tcpip" SSH channel.
- /// </returns>
- IChannelForwardedTcpip ISession.CreateChannelForwardedTcpip(uint remoteChannelNumber, uint remoteWindowSize,
- uint remoteChannelDataPacketSize)
- {
- return new ChannelForwardedTcpip(this,
- NextChannelNumber,
- InitialLocalWindowSize,
- LocalChannelDataPacketSize,
- remoteChannelNumber,
- remoteWindowSize,
- remoteChannelDataPacketSize);
- }
- /// <summary>
- /// Sends a message to the server.
- /// </summary>
- /// <param name="message">The message to send.</param>
- /// <exception cref="SshConnectionException">The client is not connected.</exception>
- /// <exception cref="SshOperationTimeoutException">The operation timed out.</exception>
- /// <exception cref="InvalidOperationException">The size of the packet exceeds the maximum size defined by the protocol.</exception>
- void ISession.SendMessage(Message message)
- {
- SendMessage(message);
- }
- /// <summary>
- /// Sends a message to the server.
- /// </summary>
- /// <param name="message">The message to send.</param>
- /// <returns>
- /// <c>true</c> if the message was sent to the server; otherwise, <c>false</c>.
- /// </returns>
- /// <exception cref="InvalidOperationException">The size of the packet exceeds the maximum size defined by the protocol.</exception>
- /// <remarks>
- /// This methods returns <c>false</c> when the attempt to send the message results in a
- /// <see cref="SocketException"/> or a <see cref="SshException"/>.
- /// </remarks>
- bool ISession.TrySendMessage(Message message)
- {
- return TrySendMessage(message);
- }
- #endregion ISession implementation
- }
- }
|