123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577 |
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
- using SMBLibrary.NetBios;
- using SMBLibrary.SMB1;
- using SMBLibrary.Services;
- using Utilities;
- namespace SMBLibrary.Server
- {
- public class SMBServer
- {
- public const int NetBiosOverTCPPort = 139;
- public const int DirectTCPPort = 445;
- public const string NTLanManagerDialect = "NT LM 0.12";
- public const bool EnableExtendedSecurity = true;
- private ShareCollection m_shares;
- private INTLMAuthenticationProvider m_users;
- private NamedPipeShare m_services;
- private IPAddress m_serverAddress;
- private SMBTransportType m_transport;
- private Socket m_listenerSocket;
- private bool m_listening;
- private Guid m_serverGuid;
- public SMBServer(ShareCollection shares, INTLMAuthenticationProvider users, IPAddress serverAddress, SMBTransportType transport)
- {
- m_shares = shares;
- m_users = users;
- m_serverAddress = serverAddress;
- m_serverGuid = Guid.NewGuid();
- m_transport = transport;
- m_services = new NamedPipeShare(shares.ListShares());
- }
- public void Start()
- {
- if (!m_listening)
- {
- m_listening = true;
- m_listenerSocket = new Socket(m_serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
- int port = (m_transport == SMBTransportType.DirectTCPTransport ? DirectTCPPort : NetBiosOverTCPPort);
- m_listenerSocket.Bind(new IPEndPoint(m_serverAddress, port));
- m_listenerSocket.Listen((int)SocketOptionName.MaxConnections);
- m_listenerSocket.BeginAccept(ConnectRequestCallback, m_listenerSocket);
- }
- }
- public void Stop()
- {
- m_listening = false;
- SocketUtils.ReleaseSocket(m_listenerSocket);
- }
-
- private void ConnectRequestCallback(IAsyncResult ar)
- {
- System.Diagnostics.Debug.Print("[{0}] New connection request", DateTime.Now.ToString("HH:mm:ss:ffff"));
- Socket listenerSocket = (Socket)ar.AsyncState;
- Socket clientSocket;
- try
- {
- clientSocket = listenerSocket.EndAccept(ar);
- }
- catch (ObjectDisposedException)
- {
- return;
- }
- catch (SocketException ex)
- {
- const int WSAECONNRESET = 10054;
-
-
-
- if (ex.ErrorCode == WSAECONNRESET)
- {
- m_listenerSocket.BeginAccept(ConnectRequestCallback, m_listenerSocket);
- }
- System.Diagnostics.Debug.Print("[{0}] Connection request error {1}", DateTime.Now.ToString("HH:mm:ss:ffff"), ex.ErrorCode);
- return;
- }
- StateObject state = new StateObject();
-
- clientSocket.NoDelay = true;
- state.ClientSocket = clientSocket;
- try
- {
- clientSocket.BeginReceive(state.ReceiveBuffer.Buffer, state.ReceiveBuffer.WriteOffset, state.ReceiveBuffer.AvailableLength, 0, ReceiveCallback, state);
- }
- catch (ObjectDisposedException)
- {
- }
- catch (SocketException)
- {
- }
- m_listenerSocket.BeginAccept(ConnectRequestCallback, m_listenerSocket);
- }
- private void ReceiveCallback(IAsyncResult result)
- {
- StateObject state = (StateObject)result.AsyncState;
- Socket clientSocket = state.ClientSocket;
- if (!m_listening)
- {
- clientSocket.Close();
- return;
- }
- int numberOfBytesReceived;
- try
- {
- numberOfBytesReceived = clientSocket.EndReceive(result);
- }
- catch (ObjectDisposedException)
- {
- return;
- }
- catch (SocketException)
- {
- return;
- }
- if (numberOfBytesReceived == 0)
- {
-
- System.Diagnostics.Debug.Print("[{0}] The other side closed the connection", DateTime.Now.ToString("HH:mm:ss:ffff"));
- clientSocket.Close();
- return;
- }
- SMBConnectionReceiveBuffer receiveBuffer = state.ReceiveBuffer;
- receiveBuffer.SetNumberOfBytesReceived(numberOfBytesReceived);
- ProcessConnectionBuffer(state);
- if (clientSocket.Connected)
- {
- try
- {
- clientSocket.BeginReceive(state.ReceiveBuffer.Buffer, state.ReceiveBuffer.WriteOffset, state.ReceiveBuffer.AvailableLength, 0, ReceiveCallback, state);
- }
- catch (ObjectDisposedException)
- {
- }
- catch (SocketException)
- {
- }
- }
- }
- public void ProcessConnectionBuffer(StateObject state)
- {
- Socket clientSocket = state.ClientSocket;
- SMBConnectionReceiveBuffer receiveBuffer = state.ReceiveBuffer;
- while (receiveBuffer.HasCompletePacket())
- {
- SessionPacket packet = null;
- try
- {
- packet = receiveBuffer.DequeuePacket();
- }
- catch (Exception)
- {
- state.ClientSocket.Close();
- }
- if (packet != null)
- {
- ProcessPacket(packet, state);
- }
- }
- }
- public void ProcessPacket(SessionPacket packet, StateObject state)
- {
- if (packet is SessionRequestPacket && m_transport == SMBTransportType.NetBiosOverTCP)
- {
- PositiveSessionResponsePacket response = new PositiveSessionResponsePacket();
- TrySendPacket(state, response);
- }
- else if (packet is SessionKeepAlivePacket && m_transport == SMBTransportType.NetBiosOverTCP)
- {
-
- }
- else if (packet is SessionMessagePacket)
- {
- SMB1Message message = null;
- #if DEBUG
- message = SMB1Message.GetSMBMessage(packet.Trailer);
- System.Diagnostics.Debug.Print("[{0}] Message Received: {1} Commands, First Command: {2}, Packet length: {3}", DateTime.Now.ToString("HH:mm:ss:ffff"), message.Commands.Count, message.Commands[0].CommandName.ToString(), packet.Length);
- #else
- try
- {
- message = SMB1Message.GetSMBMessage(packet.Trailer);
- }
- catch (Exception)
- {
- state.ClientSocket.Close();
- return;
- }
- #endif
- ProcessMessage(message, state);
- }
- else
- {
- System.Diagnostics.Debug.Print("[{0}] Invalid NetBIOS packet", DateTime.Now.ToString("HH:mm:ss:ffff"));
- state.ClientSocket.Close();
- return;
- }
- }
- public void ProcessMessage(SMB1Message message, StateObject state)
- {
- SMB1Message reply = new SMB1Message();
- PrepareResponseHeader(reply, message);
- List<SMB1Command> sendQueue = new List<SMB1Command>();
- foreach (SMB1Command command in message.Commands)
- {
- SMB1Command response = ProcessCommand(reply.Header, command, state, sendQueue);
- if (response != null)
- {
- reply.Commands.Add(response);
- }
- if (reply.Header.Status != NTStatus.STATUS_SUCCESS)
- {
- break;
- }
- }
- if (reply.Commands.Count > 0)
- {
- TrySendMessage(state, reply);
- foreach (SMB1Command command in sendQueue)
- {
- SMB1Message secondaryReply = new SMB1Message();
- secondaryReply.Header = reply.Header;
- secondaryReply.Commands.Add(command);
- TrySendMessage(state, secondaryReply);
- }
- }
- }
-
-
-
- public SMB1Command ProcessCommand(SMB1Header header, SMB1Command command, StateObject state, List<SMB1Command> sendQueue)
- {
- if (command is NegotiateRequest)
- {
- NegotiateRequest request = (NegotiateRequest)command;
- if (request.Dialects.Contains(SMBServer.NTLanManagerDialect))
- {
- if (EnableExtendedSecurity && header.ExtendedSecurityFlag)
- {
- return NegotiateHelper.GetNegotiateResponseExtended(request, m_serverGuid);
- }
- else
- {
- byte[] serverChallenge = m_users.GenerateServerChallenge();
- return NegotiateHelper.GetNegotiateResponse(header, request, serverChallenge);
- }
- }
- else
- {
- return new NegotiateResponseNotSupported();
- }
- }
- else if (command is SessionSetupAndXRequest)
- {
- SessionSetupAndXRequest request = (SessionSetupAndXRequest)command;
- state.MaxBufferSize = request.MaxBufferSize;
- return NegotiateHelper.GetSessionSetupResponse(header, request, m_users, state);
- }
- else if (command is SessionSetupAndXRequestExtended)
- {
- SessionSetupAndXRequestExtended request = (SessionSetupAndXRequestExtended)command;
- state.MaxBufferSize = request.MaxBufferSize;
- return NegotiateHelper.GetSessionSetupResponseExtended(header, request, m_users, state);
- }
- else if (command is EchoRequest)
- {
- return ServerResponseHelper.GetEchoResponse((EchoRequest)command, sendQueue);
- }
- else if (state.IsAuthenticated(header.UID))
- {
- if (command is TreeConnectAndXRequest)
- {
- TreeConnectAndXRequest request = (TreeConnectAndXRequest)command;
- return TreeConnectHelper.GetTreeConnectResponse(header, request, state, m_shares);
- }
- else if (command is LogoffAndXRequest)
- {
- return new LogoffAndXResponse();
- }
- else if (state.IsTreeConnected(header.TID))
- {
- string rootPath = state.GetConnectedTreePath(header.TID);
- ISMBShare share;
- if (state.IsIPC(header.TID))
- {
- share = m_services;
- }
- else
- {
- share = m_shares.GetShareFromRelativePath(rootPath);
- }
- if (command is CreateDirectoryRequest)
- {
- if (!(share is FileSystemShare))
- {
- header.Status = NTStatus.STATUS_SMB_BAD_COMMAND;
- return new ErrorResponse(command.CommandName);
- }
- CreateDirectoryRequest request = (CreateDirectoryRequest)command;
- return FileSystemResponseHelper.GetCreateDirectoryResponse(header, request, (FileSystemShare)share, state);
- }
- else if (command is DeleteDirectoryRequest)
- {
- if (!(share is FileSystemShare))
- {
- header.Status = NTStatus.STATUS_SMB_BAD_COMMAND;
- return new ErrorResponse(command.CommandName);
- }
- DeleteDirectoryRequest request = (DeleteDirectoryRequest)command;
- return FileSystemResponseHelper.GetDeleteDirectoryResponse(header, request, (FileSystemShare)share, state);
- }
- else if (command is CloseRequest)
- {
- CloseRequest request = (CloseRequest)command;
- return ServerResponseHelper.GetCloseResponse(header, request, share, state);
- }
- else if (command is FlushRequest)
- {
- return new FlushResponse();
- }
- else if (command is DeleteRequest)
- {
- if (!(share is FileSystemShare))
- {
- header.Status = NTStatus.STATUS_SMB_BAD_COMMAND;
- return new ErrorResponse(command.CommandName);
- }
- DeleteRequest request = (DeleteRequest)command;
- return FileSystemResponseHelper.GetDeleteResponse(header, request, (FileSystemShare)share, state);
- }
- else if (command is RenameRequest)
- {
- if (!(share is FileSystemShare))
- {
- header.Status = NTStatus.STATUS_SMB_BAD_COMMAND;
- return new ErrorResponse(command.CommandName);
- }
- RenameRequest request = (RenameRequest)command;
- return FileSystemResponseHelper.GetRenameResponse(header, request, (FileSystemShare)share, state);
- }
- else if (command is QueryInformationRequest)
- {
- if (!(share is FileSystemShare))
- {
- header.Status = NTStatus.STATUS_SMB_BAD_COMMAND;
- return new ErrorResponse(command.CommandName);
- }
- QueryInformationRequest request = (QueryInformationRequest)command;
- return FileSystemResponseHelper.GetQueryInformationResponse(header, request, (FileSystemShare)share);
- }
- else if (command is SetInformationRequest)
- {
- if (!(share is FileSystemShare))
- {
- header.Status = NTStatus.STATUS_SMB_BAD_COMMAND;
- return new ErrorResponse(command.CommandName);
- }
- SetInformationRequest request = (SetInformationRequest)command;
- return FileSystemResponseHelper.GetSetInformationResponse(header, request, (FileSystemShare)share, state);
- }
- else if (command is ReadRequest)
- {
- ReadRequest request = (ReadRequest)command;
- return ReadWriteResponseHelper.GetReadResponse(header, request, share, state);
- }
- else if (command is WriteRequest)
- {
- string userName = state.GetConnectedUserName(header.UID);
- if (share is FileSystemShare && !((FileSystemShare)share).HasWriteAccess(userName))
- {
- header.Status = NTStatus.STATUS_ACCESS_DENIED;
- return new ErrorResponse(command.CommandName);
- }
- WriteRequest request = (WriteRequest)command;
- return ReadWriteResponseHelper.GetWriteResponse(header, request, share, state);
- }
- else if (command is CheckDirectoryRequest)
- {
- if (!(share is FileSystemShare))
- {
- header.Status = NTStatus.STATUS_SMB_BAD_COMMAND;
- return new ErrorResponse(command.CommandName);
- }
- CheckDirectoryRequest request = (CheckDirectoryRequest)command;
- return FileSystemResponseHelper.GetCheckDirectoryResponse(header, request, (FileSystemShare)share);
- }
- else if (command is WriteRawRequest)
- {
-
-
-
-
- return new WriteRawFinalResponse();
- }
- else if (command is SetInformation2Request)
- {
- if (!(share is FileSystemShare))
- {
- header.Status = NTStatus.STATUS_SMB_BAD_COMMAND;
- return new ErrorResponse(command.CommandName);
- }
- SetInformation2Request request = (SetInformation2Request)command;
- return FileSystemResponseHelper.GetSetInformation2Response(header, request, (FileSystemShare)share, state);
- }
- else if (command is LockingAndXRequest)
- {
- header.Status = NTStatus.STATUS_ACCESS_DENIED;
- return new ErrorResponse(CommandName.SMB_COM_LOCKING_ANDX);
- }
- else if (command is OpenAndXRequest)
- {
- OpenAndXRequest request = (OpenAndXRequest)command;
- return OpenAndXHelper.GetOpenAndXResponse(header, request, share, state);
- }
- else if (command is ReadAndXRequest)
- {
- ReadAndXRequest request = (ReadAndXRequest)command;
- return ReadWriteResponseHelper.GetReadResponse(header, request, share, state);
- }
- else if (command is WriteAndXRequest)
- {
- string userName = state.GetConnectedUserName(header.UID);
- if (share is FileSystemShare && !((FileSystemShare)share).HasWriteAccess(userName))
- {
- header.Status = NTStatus.STATUS_ACCESS_DENIED;
- return new ErrorResponse(command.CommandName);
- }
- WriteAndXRequest request = (WriteAndXRequest)command;
- return ReadWriteResponseHelper.GetWriteResponse(header, request, share, state);
- }
- else if (command is FindClose2Request)
- {
- return ServerResponseHelper.GetFindClose2Request(header, (FindClose2Request)command, state);
- }
- else if (command is TreeDisconnectRequest)
- {
- TreeDisconnectRequest request = (TreeDisconnectRequest)command;
- return TreeConnectHelper.GetTreeDisconnectResponse(header, request, state);
- }
- else if (command is TransactionRequest)
- {
- TransactionRequest request = (TransactionRequest)command;
- try
- {
- return TransactionHelper.GetTransactionResponse(header, request, share, state, sendQueue);
- }
- catch (UnsupportedInformationLevelException)
- {
- header.Status = NTStatus.STATUS_INVALID_PARAMETER;
- return new ErrorResponse(command.CommandName);
- }
- }
- else if (command is TransactionSecondaryRequest)
- {
- TransactionSecondaryRequest request = (TransactionSecondaryRequest)command;
- try
- {
- return TransactionHelper.GetTransactionResponse(header, request, share, state, sendQueue);
- }
- catch (UnsupportedInformationLevelException)
- {
- header.Status = NTStatus.STATUS_INVALID_PARAMETER;
- return new ErrorResponse(command.CommandName);
- }
- }
- else if (command is NTTransactRequest)
- {
- NTTransactRequest request = (NTTransactRequest)command;
- return NTTransactHelper.GetNTTransactResponse(header, request, share, state, sendQueue);
- }
- else if (command is NTTransactSecondaryRequest)
- {
- NTTransactSecondaryRequest request = (NTTransactSecondaryRequest)command;
- return NTTransactHelper.GetNTTransactResponse(header, request, share, state, sendQueue);
- }
- else if (command is NTCreateAndXRequest)
- {
- NTCreateAndXRequest request = (NTCreateAndXRequest)command;
- return NTCreateHelper.GetNTCreateResponse(header, request, share, state);
- }
- }
- else
- {
- header.Status = NTStatus.STATUS_SMB_BAD_TID;
- return new ErrorResponse(command.CommandName);
- }
- }
- header.Status = NTStatus.STATUS_SMB_BAD_COMMAND;
- return new ErrorResponse(command.CommandName);
- }
- public static void TrySendMessage(StateObject state, SMB1Message reply)
- {
- SessionMessagePacket packet = new SessionMessagePacket();
- packet.Trailer = reply.GetBytes();
- TrySendPacket(state, packet);
- System.Diagnostics.Debug.Print("[{0}] Reply sent: {1} Commands, First Command: {2}, Packet length: {3}", DateTime.Now.ToString("HH:mm:ss:ffff"), reply.Commands.Count, reply.Commands[0].CommandName.ToString(), packet.Length);
- }
- public static void TrySendPacket(StateObject state, SessionPacket response)
- {
- Socket clientSocket = state.ClientSocket;
- try
- {
- clientSocket.Send(response.GetBytes());
- }
- catch (SocketException)
- {
- }
- catch (ObjectDisposedException)
- {
- }
- }
- private static void PrepareResponseHeader(SMB1Message response, SMB1Message request)
- {
- response.Header.Status = NTStatus.STATUS_SUCCESS;
- response.Header.Flags = HeaderFlags.CaseInsensitive | HeaderFlags.CanonicalizedPaths | HeaderFlags.Reply;
- response.Header.Flags2 = HeaderFlags2.NTStatusCode;
- if ((request.Header.Flags2 & HeaderFlags2.LongNamesAllowed) > 0)
- {
- response.Header.Flags2 |= HeaderFlags2.LongNamesAllowed | HeaderFlags2.LongNameUsed;
- }
- if ((request.Header.Flags2 & HeaderFlags2.ExtendedAttributes) > 0)
- {
- response.Header.Flags2 |= HeaderFlags2.ExtendedAttributes;
- }
- if ((request.Header.Flags2 & HeaderFlags2.ExtendedSecurity) > 0)
- {
- response.Header.Flags2 |= HeaderFlags2.ExtendedSecurity;
- }
- if ((request.Header.Flags2 & HeaderFlags2.Unicode) > 0)
- {
- response.Header.Flags2 |= HeaderFlags2.Unicode;
- }
- response.Header.MID = request.Header.MID;
- response.Header.PID = request.Header.PID;
- response.Header.UID = request.Header.UID;
- response.Header.TID = request.Header.TID;
- }
- }
- }
|