Beispiel #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)
            {
            }
        }
Beispiel #2
0
        public static FileSystemShare InitializeShare(ShareSettings shareSettings)
        {
            string          shareName   = shareSettings.ShareName;
            string          sharePath   = shareSettings.SharePath;
            List <string>   readAccess  = shareSettings.ReadAccess;
            List <string>   writeAccess = shareSettings.WriteAccess;
            FileSystemShare share       = new FileSystemShare(shareName, new NTDirectoryFileSystem(sharePath));

            share.AccessRequested += delegate(object sender, AccessRequestArgs args)
            {
                bool hasReadAccess  = Contains(readAccess, "Users") || Contains(readAccess, args.UserName);
                bool hasWriteAccess = Contains(writeAccess, "Users") || Contains(writeAccess, args.UserName);
                if (args.RequestedAccess == FileAccess.Read)
                {
                    args.Allow = hasReadAccess;
                }
                else if (args.RequestedAccess == FileAccess.Write)
                {
                    args.Allow = hasWriteAccess;
                }
                else // FileAccess.ReadWrite
                {
                    args.Allow = hasReadAccess && hasWriteAccess;
                }
            };
            return(share);
        }
Beispiel #3
0
        private void StartService()
        {
            IPAddress        serverAddress = IPAddress.Any;
            SMBTransportType transportType = SMBTransportType.DirectTCPTransport;

            UserCollection       users          = null;
            List <ShareSettings> sharesSettings = null;
            int port = SettingsHelper.DefaultPort;

            try
            {
                users          = SettingsHelper.ReadUserSettings();
                sharesSettings = SettingsHelper.ReadSharesSettings();
                port           = SettingsHelper.ReadServerPort();
            }
            catch
            {
                m_logWriter.WriteLine("Fail to load Settings.xml");
                return;
            }

            NTLMAuthenticationProviderBase authenticationMechanism = new IndependentNTLMAuthenticationProvider(users.GetUserPassword);

            SMBShareCollection shares = new SMBShareCollection();

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

            GSSProvider securityProvider = new GSSProvider(authenticationMechanism);

            m_server = new SMBLibrary.Server.SMBServer(shares, securityProvider);
            // The provided logging mechanism will synchronously write to the disk during server activity.
            // To maximize server performance, you can disable logging by commenting out the following line.
            m_server.LogEntryAdded += new EventHandler <LogEntry>(m_logWriter.OnLogEntryAdded);

            try
            {
                SMBServer.DirectTCPPort = port;
                m_server.Start(serverAddress, transportType);
                if (transportType == SMBTransportType.NetBiosOverTCP)
                {
                    if (serverAddress.AddressFamily == AddressFamily.InterNetwork && !IPAddress.Equals(serverAddress, IPAddress.Any))
                    {
                        IPAddress subnetMask = NetworkInterfaceHelper.GetSubnetMask(serverAddress);
                        m_nameServer = new NameServer(serverAddress, subnetMask);
                        m_nameServer.Start();
                    }
                }
            }
            catch (Exception ex)
            {
                m_logWriter.WriteLine(ex.Message);
            }
        }
Beispiel #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;
            }
        }
Beispiel #5
0
        private SMBShareCollection ReadShareSettings()
        {
            SMBShareCollection shares     = new SMBShareCollection();
            XmlDocument        document   = GetSettingsXML();
            XmlNode            sharesNode = document.SelectSingleNode("Settings/Shares");

            foreach (XmlNode shareNode in sharesNode.ChildNodes)
            {
                string shareName = shareNode.Attributes["Name"].Value;
                string sharePath = shareNode.Attributes["Path"].Value;

                XmlNode         readAccessNode  = shareNode.SelectSingleNode("ReadAccess");
                List <string>   readAccess      = ReadAccessList(readAccessNode);
                XmlNode         writeAccessNode = shareNode.SelectSingleNode("WriteAccess");
                List <string>   writeAccess     = ReadAccessList(writeAccessNode);
                FileSystemShare share           = new FileSystemShare(shareName, new NTDirectoryFileSystem(sharePath));
                share.AccessRequested += delegate(object sender, AccessRequestArgs args)
                {
                    bool hasReadAccess  = Contains(readAccess, "Users") || Contains(readAccess, args.UserName);
                    bool hasWriteAccess = Contains(writeAccess, "Users") || Contains(writeAccess, args.UserName);
                    if (args.RequestedAccess == FileAccess.Read)
                    {
                        args.Allow = hasReadAccess;
                    }
                    else if (args.RequestedAccess == FileAccess.Write)
                    {
                        args.Allow = hasWriteAccess;
                    }
                    else // FileAccess.ReadWrite
                    {
                        args.Allow = hasReadAccess && hasWriteAccess;
                    }
                };
                shares.Add(share);
            }
            return(shares);
        }
Beispiel #6
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            IPAddress        serverAddress = (IPAddress)comboIPAddress.SelectedValue;
            SMBTransportType transportType;

            if (rbtNetBiosOverTCP.Checked)
            {
                transportType = SMBTransportType.NetBiosOverTCP;
            }
            else
            {
                transportType = SMBTransportType.DirectTCPTransport;
            }

            NTLMAuthenticationProviderBase authenticationMechanism;

            if (chkIntegratedWindowsAuthentication.Checked)
            {
                authenticationMechanism = new IntegratedNTLMAuthenticationProvider();
            }
            else
            {
                UserCollection users;
                try
                {
                    users = SettingsHelper.ReadUserSettings();
                }
                catch
                {
                    MessageBox.Show("Cannot read " + SettingsHelper.SettingsFileName, "Error");
                    return;
                }

                authenticationMechanism = new IndependentNTLMAuthenticationProvider(users.GetUserPassword);
            }

            List <ShareSettings> sharesSettings;

            try
            {
                sharesSettings = SettingsHelper.ReadSharesSettings();
            }
            catch (Exception)
            {
                MessageBox.Show("Cannot read " + SettingsHelper.SettingsFileName, "Error");
                return;
            }

            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);
            m_logWriter = new LogWriter();
            // The provided logging mechanism will synchronously write to the disk during server activity.
            // To maximize server performance, you can disable logging by commenting out the following line.
            m_server.LogEntryAdded += new EventHandler <LogEntry>(m_logWriter.OnLogEntryAdded);

            try
            {
                m_server.Start(serverAddress, transportType, chkSMB1.Checked, chkSMB2.Checked);
                if (transportType == SMBTransportType.NetBiosOverTCP)
                {
                    if (serverAddress.AddressFamily == AddressFamily.InterNetwork && !IPAddress.Equals(serverAddress, IPAddress.Any))
                    {
                        IPAddress subnetMask = NetworkInterfaceHelper.GetSubnetMask(serverAddress);
                        m_nameServer = new NameServer(serverAddress, subnetMask);
                        m_nameServer.Start();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
                return;
            }

            btnStart.Enabled              = false;
            btnStop.Enabled               = true;
            comboIPAddress.Enabled        = false;
            rbtDirectTCPTransport.Enabled = false;
            rbtNetBiosOverTCP.Enabled     = false;
            chkSMB1.Enabled               = false;
            chkSMB2.Enabled               = false;
            chkIntegratedWindowsAuthentication.Enabled = false;
        }
Beispiel #7
0
        static void RunOptions(Options opts)
        {
            logger.Info("Options: {0}", opts);
            List <ShareSettings> sharesSettings;

            try {
                sharesSettings = SettingsHelper.ReadSharesSettings();
            }
            catch (Exception) {
                logger.Error("Cannot read " + SettingsHelper.SettingsFileName);
                return;
            }

            List <AggregatedShareSettings> aggregatedSharesSettings;

            try {
                aggregatedSharesSettings = SettingsHelper.ReadAggregatedSharesSettings();
            }
            catch (Exception) {
                logger.Error("Cannot read " + SettingsHelper.SettingsFileName);
                return;
            }

            SMBShareCollection shares = new SMBShareCollection();

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

            NTLMAuthenticationProviderBase authenticationMechanism = new IntegratedNTLMAuthenticationProvider();
            GSSProvider securityProvider = new GSSProvider(authenticationMechanism);

            theServer = new SMBLibrary.Server.SMBServer(shares, securityProvider);
            if (opts.Verbose)
            {
                theServer.LogEntryAdded += TheServer_LogEntryAdded;
            }
            bool enableSMB1 = (opts.SMBProtocol & SMBProtocol.SMB1) == SMBProtocol.SMB1;
            bool enableSMB2 = (opts.SMBProtocol & SMBProtocol.SMB2) == SMBProtocol.SMB2;
            bool enableSMB3 = (opts.SMBProtocol & SMBProtocol.SMB3) == SMBProtocol.SMB3;

            IPAddress listenAddr;

            if (!IPAddress.TryParse(opts.ListenIPAddress, out listenAddr))
            {
                logger.Error(opts.ListenIPAddress + " is not a valid IP Address.");
                Environment.Exit(-1);
                return;
            }

            try {
                theServer.Start(listenAddr, opts.TransportType, enableSMB1, enableSMB2, enableSMB3);
                if (opts.TransportType == SMBTransportType.NetBiosOverTCP)
                {
                    if (listenAddr.AddressFamily == AddressFamily.InterNetwork && !IPAddress.Equals(listenAddr, IPAddress.Any))
                    {
                        IPAddress subnetMask = NetworkInterfaceHelper.GetSubnetMask(listenAddr);
                        theNameServer = new NameServer(listenAddr, subnetMask);
                        theNameServer.Start();
                    }
                }

                Console.Read();
            }
            catch (Exception ex) {
                logger.Error(ex.Message);
                Environment.Exit(-1);
                return;
            }
        }
Beispiel #8
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);
                }
            }
        }
        internal static SMB2Command GetQueryDirectoryResponse(QueryDirectoryRequest request, ISMBShare share, SMB2ConnectionState state)
        {
            SMB2Session    session  = state.GetSession(request.Header.SessionID);
            OpenFileObject openFile = session.GetOpenFileObject(request.FileId);

            if (openFile == null)
            {
                state.LogToServer(Severity.Verbose, "Query Directory failed. Invalid FileId. (SessionID: {0}, TreeID: {1}, FileId: {2})", request.Header.SessionID, request.Header.TreeID, request.FileId.Volatile);
                return(new ErrorResponse(request.CommandName, NTStatus.STATUS_FILE_CLOSED));
            }

            if (!((FileSystemShare)share).HasReadAccess(session.SecurityContext, openFile.Path))
            {
                state.LogToServer(Severity.Verbose, "Query Directory on '{0}{1}' failed. User '{2}' was denied access.", share.Name, openFile.Path, session.UserName);
                return(new ErrorResponse(request.CommandName, NTStatus.STATUS_ACCESS_DENIED));
            }

            FileSystemShare fileSystemShare = (FileSystemShare)share;

            FileID     fileID     = request.FileId;
            OpenSearch openSearch = session.GetOpenSearch(fileID);

            if (openSearch == null || request.Reopen)
            {
                if (request.Reopen)
                {
                    session.RemoveOpenSearch(fileID);
                }
                List <QueryDirectoryFileInformation> entries;
                NTStatus searchStatus = share.FileStore.QueryDirectory(out entries, openFile.Handle, request.FileName, request.FileInformationClass);
                if (searchStatus != NTStatus.STATUS_SUCCESS)
                {
                    state.LogToServer(Severity.Verbose, "Query Directory on '{0}{1}', Searched for '{2}', NTStatus: {3}", share.Name, openFile.Path, request.FileName, searchStatus.ToString());
                    return(new ErrorResponse(request.CommandName, searchStatus));
                }
                state.LogToServer(Severity.Information, "Query Directory on '{0}{1}', Searched for '{2}', found {3} matching entries", share.Name, openFile.Path, request.FileName, entries.Count);
                openSearch = session.AddOpenSearch(fileID, entries, 0);
            }

            if (request.Restart || request.Reopen)
            {
                openSearch.EnumerationLocation = 0;
            }

            if (openSearch.Entries.Count == 0)
            {
                // [MS-SMB2] If there are no entries to return [..] the server MUST fail the request with STATUS_NO_SUCH_FILE.
                session.RemoveOpenSearch(fileID);
                return(new ErrorResponse(request.CommandName, NTStatus.STATUS_NO_SUCH_FILE));
            }

            if (openSearch.EnumerationLocation == openSearch.Entries.Count)
            {
                return(new ErrorResponse(request.CommandName, NTStatus.STATUS_NO_MORE_FILES));
            }

            List <QueryDirectoryFileInformation> page = new List <QueryDirectoryFileInformation>();
            int pageLength = 0;

            for (int index = openSearch.EnumerationLocation; index < openSearch.Entries.Count; index++)
            {
                QueryDirectoryFileInformation fileInformation = openSearch.Entries[index];
                if (fileInformation.FileInformationClass != request.FileInformationClass)
                {
                    // We do not support changing FileInformationClass during a search (unless SMB2_REOPEN is set).
                    return(new ErrorResponse(request.CommandName, NTStatus.STATUS_INVALID_PARAMETER));
                }

                int entryLength = fileInformation.Length;
                if (pageLength + entryLength <= request.OutputBufferLength)
                {
                    page.Add(fileInformation);
                    int paddedLength = (int)Math.Ceiling((double)entryLength / 8) * 8;
                    pageLength += paddedLength;
                    openSearch.EnumerationLocation = index + 1;
                }
                else
                {
                    break;
                }

                if (request.ReturnSingleEntry)
                {
                    break;
                }
            }

            QueryDirectoryResponse response = new QueryDirectoryResponse();

            response.SetFileInformationList(page);
            return(response);
        }
Beispiel #10
0
        private void StartButton_Click(object sender, RoutedEventArgs e)
        {
            string accountName = this.username_textbox.Text;
            string password    = this.password_box.Password;

            if (CommonUtils.IsEmptyString(accountName))
            {
                MessageBox.Show("User Name or Password cannot be empty!", "Error");
                return;
            }

            List <ShareSettings> sharesSettings = this.GetShareSettings();

            if (sharesSettings == null || sharesSettings.Count == 0)
            {
                MessageBox.Show("Please add directories for sharing!", "Error");
                return;
            }

            int port = SettingsHelper.DefaultPort;

            try
            {
                port = int.Parse(this.port_textbox.Text);
                SettingsHelper.WriteServerPort(port);
            }
            catch
            {
                MessageBox.Show("Invalid port number!", "Error");
                return;
            }

            UserCollection users = new UserCollection();

            users.Add(new User(accountName, password));
            // Save account if necessary
            if (this.NeedUpdateUserCollection())
            {
                SettingsHelper.WriteUserSettings(users);
            }

            bool runAsService = this.service_checkbox.IsChecked ?? false;

            if (runAsService)
            {
                if (!this.IsInAdminRole())
                {
                    MessageBox.Show("To start the service, please run application as administrator.", "Info");
                    return;
                }

                try
                {
                    ServiceController serviceController = new ServiceController("RedfishService");
                    serviceController.Start();
                    this.start_button.IsEnabled = false;
                    this.stop_button.IsEnabled  = true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error");
                }
            }
            else
            {
                KeyValuePair <string, IPAddress> selectedValue = (KeyValuePair <string, IPAddress>) this.address_combobox.SelectedValue;
                IPAddress        serverAddress = selectedValue.Value;
                SMBTransportType transportType = SMBTransportType.DirectTCPTransport;

                NTLMAuthenticationProviderBase authenticationMechanism = new IndependentNTLMAuthenticationProvider(users.GetUserPassword);

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

                GSSProvider securityProvider = new GSSProvider(authenticationMechanism);
                m_server    = new SMBLibrary.Server.SMBServer(shares, securityProvider);
                m_logWriter = new LogWriter();
                // The provided logging mechanism will synchronously write to the disk during server activity.
                // To maximize server performance, you can disable logging by commenting out the following line.
                m_server.LogEntryAdded += new EventHandler <LogEntry>(m_logWriter.OnLogEntryAdded);

                try
                {
                    SMBServer.DirectTCPPort = port;
                    m_server.Start(serverAddress, transportType);
                    if (transportType == SMBTransportType.NetBiosOverTCP)
                    {
                        if (serverAddress.AddressFamily == AddressFamily.InterNetwork && !IPAddress.Equals(serverAddress, IPAddress.Any))
                        {
                            IPAddress subnetMask = NetworkInterfaceHelper.GetSubnetMask(serverAddress);
                            m_nameServer = new NameServer(serverAddress, subnetMask);
                            m_nameServer.Start();
                        }
                    }

                    this.start_button.IsEnabled = false;
                    this.stop_button.IsEnabled  = true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error");
                }
            }
        }