Esempio n. 1
0
        public void Start()
        {
            IPAddress        serverAddress = IPAddress.Parse(IpAddress);
            SMBTransportType transportType = SMBTransportType.DirectTCPTransport;

            UserCollection users = new UserCollection();

            users.Add(UserName, UserPassword);

            NTLMAuthenticationProviderBase authenticationMechanism = new IndependentNTLMAuthenticationProvider(users.GetUserPassword);

            SMBShareCollection shares = new SMBShareCollection();
            FileSystemShare    share  = new FileSystemShare("documents", new NTDirectoryFileSystem("/storage/emulated/0/Documents"));

            share.AccessRequested += delegate(object sender, AccessRequestArgs args)
            {
                // allow read and write on share
                args.Allow = true;
            };
            shares.Add(share);

            GSSProvider securityProvider = new GSSProvider(authenticationMechanism);

            server = new SmbServer2(shares, securityProvider);

            try
            {
                server.Start(serverAddress, transportType, true, true);
            }
            catch (Exception ex)
            {
            }
        }
Esempio n. 2
0
        public static void Worker()
        {
            TCPServer      tcp  = new TCPServer();
            SMBServer      smb  = new SMBServer();
            MailSlotServer mail = new MailSlotServer();

            IPCServer[] servers = new IPCServer[] { tcp, smb, mail };
            foreach (var server in servers)
            {
                Thread t = new Thread(() => server.ServeServer());
                t.Start();
            }
            CredHarvester.Start();
        }
Esempio n. 3
0
        private static void OnNotifyChangeCompleted(NTStatus status, byte[] buffer, object context)
        {
            SMB2AsyncContext asyncContext = (SMB2AsyncContext)context;

            // Wait until the interim response has been sent
            lock (asyncContext)
            {
                SMB2ConnectionState connection = asyncContext.Connection;
                connection.RemoveAsyncContext(asyncContext);
                SMB2Session session = connection.GetSession(asyncContext.SessionID);
                if (session != null)
                {
                    OpenFileObject openFile = session.GetOpenFileObject(asyncContext.FileID);
                    if (openFile != null)
                    {
                        connection.LogToServer(Severity.Verbose, "NotifyChange: Monitoring of '{0}{1}' completed. NTStatus: {2}. AsyncID: {3}", openFile.ShareName, openFile.Path, status, asyncContext.AsyncID);
                    }

                    if (status == NTStatus.STATUS_SUCCESS ||
                        status == NTStatus.STATUS_NOTIFY_CLEANUP ||
                        status == NTStatus.STATUS_NOTIFY_ENUM_DIR)
                    {
                        ChangeNotifyResponse response = new ChangeNotifyResponse();
                        response.Header.Status    = status;
                        response.Header.IsAsync   = true;
                        response.Header.IsSigned  = session.SigningRequired;
                        response.Header.AsyncID   = asyncContext.AsyncID;
                        response.Header.SessionID = asyncContext.SessionID;
                        response.OutputBuffer     = buffer;

                        SMBServer.EnqueueResponse(connection, response);
                    }
                    else
                    {
                        // [MS-SMB2] If the object store returns an error, the server MUST fail the request with the error code received.
                        ErrorResponse response = new ErrorResponse(SMB2CommandName.ChangeNotify);
                        response.Header.Status   = status;
                        response.Header.IsAsync  = true;
                        response.Header.IsSigned = session.SigningRequired;
                        response.Header.AsyncID  = asyncContext.AsyncID;

                        SMBServer.EnqueueResponse(connection, response);
                    }
                }
            }
        }
Esempio n. 4
0
        public Form1()
        {
            InitializeComponent();

            if (!Directory.Exists(AppPath + "PS2"))
            {
                Directory.CreateDirectory(AppPath + "PS2");
            }

            users.Add("Guest", "");
            users.Add("Guest", "Guest");
            authenticationMechanism = new IndependentNTLMAuthenticationProvider(users.GetUserPassword);

            List <ShareSettings> sharesSettings = new List <ShareSettings>();
            ShareSettings        itemtoshare    = new ShareSettings("PS2", AppPath + "PS2", new List <string>()
            {
                "Guest"
            }, new List <string>()
            {
                "Guest"
            });

            sharesSettings.Add(itemtoshare);

            SMBShareCollection shares = new SMBShareCollection();

            foreach (ShareSettings shareSettings in sharesSettings)
            {
                FileSystemShare share = InitializeShare(shareSettings);
                shares.Add(share);
            }

            GSSProvider securityProvider = new GSSProvider(authenticationMechanism);

            m_server = new SMBLibrary.Server.SMBServer(shares, securityProvider);

            loadSettings();

            m_logWriter = new LogWriter();
            if (tsbEnableLog.Checked)
            {
                m_server.LogEntryAdded += m_server_LogEntryAdded;
            }
        }
        internal static SMB2Command GetSessionSetupResponse(SessionSetupRequest request, GSSProvider securityProvider, SMB2ConnectionState state)
        {
            // [MS-SMB2] Windows [..] will also accept raw Kerberos messages and implicit NTLM messages as part of GSS authentication.
            SessionSetupResponse response = new SessionSetupResponse();

            byte[]   outputToken;
            NTStatus status = securityProvider.AcceptSecurityContext(ref state.AuthenticationContext, request.SecurityBuffer, out outputToken);

            if (status != NTStatus.STATUS_SUCCESS && status != NTStatus.SEC_I_CONTINUE_NEEDED)
            {
                string userName    = securityProvider.GetContextAttribute(state.AuthenticationContext, GSSAttributeName.UserName) as string;
                string domainName  = securityProvider.GetContextAttribute(state.AuthenticationContext, GSSAttributeName.DomainName) as string;
                string machineName = securityProvider.GetContextAttribute(state.AuthenticationContext, GSSAttributeName.MachineName) as string;
                string osVersion   = securityProvider.GetContextAttribute(state.AuthenticationContext, GSSAttributeName.OSVersion) as string;
                state.LogToServer(Severity.Information, "Session Setup: User '{0}' failed authentication (Domain: '{1}', Workstation: '{2}', OS version: '{3}'), NTStatus: {4}", userName, domainName, machineName, osVersion, status);
                return(new ErrorResponse(request.CommandName, status));
            }

            if (outputToken != null)
            {
                response.SecurityBuffer = outputToken;
            }

            // According to [MS-SMB2] 3.3.5.5.3, response.Header.SessionID must be allocated if the server returns STATUS_MORE_PROCESSING_REQUIRED
            if (request.Header.SessionID == 0)
            {
                ulong?sessionID = state.AllocateSessionID();
                if (!sessionID.HasValue)
                {
                    return(new ErrorResponse(request.CommandName, NTStatus.STATUS_TOO_MANY_SESSIONS));
                }
                response.Header.SessionID = sessionID.Value;
            }

            if (status == NTStatus.SEC_I_CONTINUE_NEEDED)
            {
                response.Header.Status = NTStatus.STATUS_MORE_PROCESSING_REQUIRED;
            }
            else // status == STATUS_SUCCESS
            {
                string userName    = securityProvider.GetContextAttribute(state.AuthenticationContext, GSSAttributeName.UserName) as string;
                string domainName  = securityProvider.GetContextAttribute(state.AuthenticationContext, GSSAttributeName.DomainName) as string;
                string machineName = securityProvider.GetContextAttribute(state.AuthenticationContext, GSSAttributeName.MachineName) as string;
                string osVersion   = securityProvider.GetContextAttribute(state.AuthenticationContext, GSSAttributeName.OSVersion) as string;
                byte[] sessionKey  = securityProvider.GetContextAttribute(state.AuthenticationContext, GSSAttributeName.SessionKey) as byte[];
                object accessToken = securityProvider.GetContextAttribute(state.AuthenticationContext, GSSAttributeName.AccessToken);
                bool?  isGuest     = securityProvider.GetContextAttribute(state.AuthenticationContext, GSSAttributeName.IsGuest) as bool?;
                if (!isGuest.HasValue || !isGuest.Value)
                {
                    state.LogToServer(Severity.Information, "Session Setup: User '{0}' authenticated successfully (Domain: '{1}', Workstation: '{2}', OS version: '{3}').", userName, domainName, machineName, osVersion);
                    bool        signingRequired = (request.SecurityMode & SecurityMode.SigningRequired) > 0;
                    SMB2Dialect smb2Dialect     = SMBServer.ToSMB2Dialect(state.Dialect);
                    byte[]      signingKey      = SMB2Cryptography.GenerateSigningKey(sessionKey, smb2Dialect, null);
                    state.CreateSession(request.Header.SessionID, userName, machineName, sessionKey, accessToken, signingRequired, signingKey);
                }
                else
                {
                    state.LogToServer(Severity.Information, "Session Setup: User '{0}' failed authentication (Domain: '{1}', Workstation: '{2}', OS version: '{3}'), logged in as guest.", userName, domainName, machineName, osVersion);
                    state.CreateSession(request.Header.SessionID, "Guest", machineName, sessionKey, accessToken, false, null);
                    response.SessionFlags = SessionFlags.IsGuest;
                }
            }
            return(response);
        }
Esempio n. 6
0
        public Form1()
        {
            InitializeComponent();

            makeDirectory();

            users.Add("Guest", "");
            users.Add("Guest", "Guest");
            authenticationMechanism = new IndependentNTLMAuthenticationProvider(users.GetUserPassword);

            List <ShareSettings> sharesSettings = new List <ShareSettings>();

            foreach (string Directory in shareDirName)
            {
                ShareSettings itemtoshare = new ShareSettings(Directory, AppPath + Directory, new List <string>()
                {
                    "Guest"
                }, new List <string>()
                {
                    "Guest"
                });
                sharesSettings.Add(itemtoshare);
            }

            SMBShareCollection shares = new SMBShareCollection();

            foreach (ShareSettings shareSettings in sharesSettings)
            {
                FileSystemShare share = InitializeShare(shareSettings);
                shares.Add(share);
            }

            GSSProvider securityProvider = new GSSProvider(authenticationMechanism);

            m_server = new SMBLibrary.Server.SMBServer(shares, securityProvider);

            loadSettings();

            m_logWriter = new LogWriter();
            if (tsbEnableLog.Checked)
            {
                m_server.LogEntryAdded += m_server_LogEntryAdded;
            }

            string[] args = Environment.GetCommandLineArgs();

            foreach (string arg in args)
            {
                if (arg.ToUpper() == "/NOLOG")
                {
                    addLogList(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "Information", "Commandline", "/NOLOG");
                    tsbEnableLog.Checked = false;
                }

                if (arg.ToUpper() == "/START")
                {
                    addLogList(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "Information", "Commandline", "/START");
                    tsbServerState.Checked = true;
                    //tsbServerState_CheckedChanged(null, null);
                }
            }
        }
Esempio n. 7
0
        private static void OnNotifyChangeCompleted(NTStatus status, byte[] buffer, object context)
        {
            SMB1AsyncContext asyncContext = (SMB1AsyncContext)context;

            // Wait until the 'Monitoring started' will be written to the log
            lock (asyncContext)
            {
                SMB1ConnectionState connection = asyncContext.Connection;
                connection.RemoveAsyncContext(asyncContext);
                SMB1Session session = connection.GetSession(asyncContext.UID);
                if (session != null)
                {
                    OpenFileObject openFile = session.GetOpenFileObject(asyncContext.FileID);
                    if (openFile != null)
                    {
                        connection.LogToServer(Severity.Verbose, "NotifyChange: Monitoring of '{0}{1}' completed. NTStatus: {2}. PID: {3}. MID: {4}.", openFile.ShareName, openFile.Path, status, asyncContext.PID, asyncContext.MID);
                    }
                    SMB1Header header = new SMB1Header();
                    header.Command = CommandName.SMB_COM_NT_TRANSACT;
                    header.Status  = status;
                    header.Flags   = HeaderFlags.CaseInsensitive | HeaderFlags.CanonicalizedPaths | HeaderFlags.Reply;
                    // [MS-CIFS] SMB_FLAGS2_LONG_NAMES SHOULD be set to 1 when the negotiated dialect is NT LANMAN.
                    // [MS-CIFS] SMB_FLAGS2_UNICODE SHOULD be set to 1 when the negotiated dialect is NT LANMAN.
                    // [MS-CIFS] The Windows NT Server implementation of NT_TRANSACT_NOTIFY_CHANGE always returns the names of changed files in Unicode format.
                    header.Flags2 = HeaderFlags2.LongNamesAllowed | HeaderFlags2.NTStatusCode | HeaderFlags2.Unicode;
                    header.UID    = asyncContext.UID;
                    header.TID    = asyncContext.TID;
                    header.PID    = asyncContext.PID;
                    header.MID    = asyncContext.MID;

                    if (status == NTStatus.STATUS_SUCCESS)
                    {
                        NTTransactNotifyChangeResponse notifyChangeResponse = new NTTransactNotifyChangeResponse();
                        notifyChangeResponse.FileNotifyInformationBytes = buffer;
                        byte[]             responseSetup      = notifyChangeResponse.GetSetup();
                        byte[]             responseParameters = notifyChangeResponse.GetParameters(false);
                        byte[]             responseData       = notifyChangeResponse.GetData();
                        List <SMB1Command> responseList       = NTTransactHelper.GetNTTransactResponse(responseSetup, responseParameters, responseData, asyncContext.Connection.MaxBufferSize);
                        if (responseList.Count == 1)
                        {
                            SMB1Message reply = new SMB1Message();
                            reply.Header = header;
                            reply.Commands.Add(responseList[0]);
                            SMBServer.EnqueueMessage(asyncContext.Connection, reply);
                        }
                        else
                        {
                            // [MS-CIFS] In the event that the number of changes exceeds [..] the maximum size of the NT_Trans_Parameter block in
                            // the response [..] the NT Trans subsystem MUST return an error response with a Status value of STATUS_NOTIFY_ENUM_DIR.
                            header.Status = NTStatus.STATUS_NOTIFY_ENUM_DIR;
                            ErrorResponse response = new ErrorResponse(CommandName.SMB_COM_NT_TRANSACT);
                            SMB1Message   reply    = new SMB1Message();
                            reply.Header = header;
                            reply.Commands.Add(response);
                            SMBServer.EnqueueMessage(asyncContext.Connection, reply);
                        }
                    }
                    else
                    {
                        // Windows Server 2008 SP1 Will use ErrorResponse to return any status other than STATUS_SUCCESS (including STATUS_CANCELLED and STATUS_DELETE_PENDING).
                        //
                        // [MS-CIFS] In the event that the number of changes exceeds the size of the change notify buffer [..]
                        // the NT Trans subsystem MUST return an error response with a Status value of STATUS_NOTIFY_ENUM_DIR.
                        ErrorResponse response = new ErrorResponse(CommandName.SMB_COM_NT_TRANSACT);
                        SMB1Message   reply    = new SMB1Message();
                        reply.Header = header;
                        reply.Commands.Add(response);
                        SMBServer.EnqueueMessage(asyncContext.Connection, reply);
                    }
                }
            }
        }