Exemplo n.º 1
0
Arquivo: Shell.cs Projeto: wangzq/bips
 public Shell(IConsole consoleWindow, ShellConfiguration shellConfiguration)
 {
     _threadStopEvent    = new ManualResetEvent(false);
     _writePromptEvent   = new ManualResetEvent(false);
     _consoleWindow      = consoleWindow;
     _shellConfiguration = shellConfiguration;
 }
Exemplo n.º 2
0
        public async Task <ShellSettings> LoadSettingsAsync(string tenant)
        {
            await _semaphore.WaitAsync();

            try
            {
                await EnsureConfigurationAsync();

                var tenantsSettings = (await new ConfigurationBuilder()
                                       .AddSourcesAsync(_settingsSources))
                                      .Build();

                var tenantSettings = new ConfigurationBuilder()
                                     .AddConfiguration(_configuration)
                                     .AddConfiguration(_configuration.GetSection(tenant))
                                     .AddConfiguration(tenantsSettings.GetSection(tenant))
                                     .Build();

                var settings      = new ShellConfiguration(tenantSettings);
                var configuration = new ShellConfiguration(tenant, _tenantConfigBuilderFactory);

                return(new ShellSettings(settings, configuration)
                {
                    Name = tenant,
                });
            }
            finally
            {
                _semaphore.Release();
            }
        }
Exemplo n.º 3
0
        public ShellPool(ShellConfiguration shellConfiguration)
        {
            Task.Run(() =>
            {
                while (true)
                {
                    // Do check per 2 minutes
                    Thread.Sleep(120 * 1000);

                    foreach (var shell in ShellPoolDictionary.ToArray())
                    {
                        // Haven't access more than Max Idle Minutes or Connected Is False
                        var expiredShells = shell.Value.Sessions.Where(u => u.Value.LastAccessSessionDate < DateTime.Now.AddMinutes(-shellConfiguration.MaxIdleMinutes) || !u.Value.Client.IsConnected).ToArray();

                        foreach (var expiredShell in expiredShells)
                        {
                            shell.Value.RemoveActiveSession(expiredShell.Key);
                        }

                        if (shell.Value.Sessions.Count == 0)
                        {
                            // All sessions are expired, Remove session key
                            ShellPoolDictionary.TryRemove(shell.Key, out _);
                        }
                    }
                }
            });

            ShellConfiguration = shellConfiguration;
        }
Exemplo n.º 4
0
        public IEnumerable <ShellSettings> LoadSettings()
        {
            var tenantsSettings = new ConfigurationBuilder()
                                  .AddSources(_settingsSources)
                                  .Build();

            var tenants = tenantsSettings.GetChildren().Select(section => section.Key);

            var allTenants = _configuredTenants.Concat(tenants).Distinct().ToArray();

            var allSettings = new List <ShellSettings>();

            foreach (var tenant in allTenants)
            {
                var tenantSettings = new ConfigurationBuilder()
                                     .AddConfiguration(_configuration)
                                     .AddConfiguration(_configuration.GetSection(tenant))
                                     .AddConfiguration(tenantsSettings.GetSection(tenant))
                                     .Build();

                var settings      = new ShellConfiguration(tenantSettings);
                var configuration = new ShellConfiguration(tenant, _configBuilderFactory);

                var shellSettings = new ShellSettings(settings, configuration)
                {
                    Name = tenant,
                };

                allSettings.Add(shellSettings);
            }
            ;

            return(allSettings);
        }
Exemplo n.º 5
0
        public ShellSettings(ShellSettings settings)
        {
            _settings      = new ShellConfiguration(settings._settings);
            _configuration = new ShellConfiguration(settings.Name, settings._configuration);

            Name = settings.Name;
        }
Exemplo n.º 6
0
 private string GetWorkingDirectory(ShellConfiguration configuration)
 {
     if (string.IsNullOrWhiteSpace(configuration.WorkingDirectory) || !Directory.Exists(configuration.WorkingDirectory))
     {
         return(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile));
     }
     return(configuration.WorkingDirectory);
 }
Exemplo n.º 7
0
        public ShellPageViewModel(ISettingsService settingsService, IDialogService dialogService, IDefaultValueProvider defaultValueProvider)
        {
            _settingsService      = settingsService;
            _dialogService        = dialogService;
            _defaultValueProvider = defaultValueProvider;

            RestoreDefaultsCommand           = new RelayCommand(async() => await RestoreDefaults().ConfigureAwait(false));
            BrowseForCustomShellCommand      = new RelayCommand(async() => await BrowseForCustomShell().ConfigureAwait(false));
            BrowseForWorkingDirectoryCommand = new RelayCommand(async() => await BrowseForWorkingDirectory().ConfigureAwait(false));

            _shellConfiguration = _settingsService.GetShellConfiguration();
        }
Exemplo n.º 8
0
        private string GetShellLocation(ShellConfiguration configuration)
        {
            switch (configuration.Shell)
            {
            case ShellType.CMD:
                return(@"C:\Windows\System32\cmd.exe");

            case ShellType.PowerShell:
                return(@"C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe");

            case ShellType.Custom:
                return(configuration.CustomShellLocation);

            default:
                return(null);
            }
        }
        public async Task <CreateTerminalResponse> CreateTerminal(TerminalSize size, ShellConfiguration shellConfiguration)
        {
            var request = new CreateTerminalRequest
            {
                Size          = size,
                Configuration = shellConfiguration
            };

            var message = new ValueSet
            {
                { MessageKeys.Type, MessageTypes.CreateTerminalRequest },
                { MessageKeys.Content, JsonConvert.SerializeObject(request) }
            };

            var responseMessage = await _appServiceConnection.SendMessageAsync(message);

            return(JsonConvert.DeserializeObject <CreateTerminalResponse>((string)responseMessage.Message[MessageKeys.Content]));
        }
        public IEnumerable <ShellSettings> LoadSettings()
        {
            var tenantsSettings = new ConfigurationBuilder()
                                  .AddSources(_settingsSources)
                                  .Build();

            var tenants = tenantsSettings.GetChildren().Select(section => section.Key);

            // TODO: Can be removed when going to RC.
            if (!tenants.Any() && File.Exists(Path.Combine(_tenantsContainerPath,
                                                           ShellHelper.DefaultShellName, "Settings.txt")))
            {
                // If no tenants and an old 'Settings.txt', try to update from Beta2.
                UpgradeFromBeta2();
                tenantsSettings.Reload();
                tenants = tenantsSettings.GetChildren().Select(section => section.Key);
            }

            var allTenants = _configuredTenants.Concat(tenants).Distinct().ToArray();

            var allSettings = new List <ShellSettings>();

            foreach (var tenant in allTenants)
            {
                var tenantSettings = new ConfigurationBuilder()
                                     .AddConfiguration(_configuration)
                                     .AddConfiguration(_configuration.GetSection(tenant))
                                     .AddConfiguration(tenantsSettings.GetSection(tenant))
                                     .Build();

                var settings      = new ShellConfiguration(tenantSettings);
                var configuration = new ShellConfiguration(tenant, _configBuilderFactory);

                var shellSettings = new ShellSettings(settings, configuration)
                {
                    Name = tenant,
                };

                allSettings.Add(shellSettings);
            }
            ;

            return(allSettings);
        }
Exemplo n.º 11
0
        public async Task <IEnumerable <ShellSettings> > LoadSettingsAsync()
        {
            await _semaphore.WaitAsync();

            try
            {
                await EnsureConfigurationAsync();

                var tenantsSettings = (await new ConfigurationBuilder()
                                       .AddSourcesAsync(_settingsSources))
                                      .Build();

                var tenants    = tenantsSettings.GetChildren().Select(section => section.Key);
                var allTenants = _configuredTenants.Concat(tenants).Distinct().ToArray();

                var allSettings = new List <ShellSettings>();

                foreach (var tenant in allTenants)
                {
                    var tenantSettings = new ConfigurationBuilder()
                                         .AddConfiguration(_configuration)
                                         .AddConfiguration(_configuration.GetSection(tenant))
                                         .AddConfiguration(tenantsSettings.GetSection(tenant))
                                         .Build();

                    var settings      = new ShellConfiguration(tenantSettings);
                    var configuration = new ShellConfiguration(tenant, _tenantConfigBuilderFactory);

                    var shellSettings = new ShellSettings(settings, configuration)
                    {
                        Name = tenant,
                    };

                    allSettings.Add(shellSettings);
                }
                ;

                return(allSettings);
            }
            finally
            {
                _semaphore.Release();
            }
        }
Exemplo n.º 12
0
        public async Task <ClientLoginModel> Login(ClientLoginModel loginModel, [FromServices] ShellConfiguration shellConfiguration)
        {
            if (shellConfiguration.NeedAuthorization && (string.IsNullOrWhiteSpace(loginModel.Captcha) || HttpContext.Session.GetString(nameof(ClientLoginModel.Captcha)) != loginModel.Captcha.ToLowerInvariant()))
            {
                loginModel.Status  = LoginStatus.Failed;
                loginModel.Message = "Wrong captcha";
            }
            else
            {
                var user = ShellConfiguration.Users.FirstOrDefault(u => !shellConfiguration.NeedAuthorization || u.UserName == loginModel.UserName && u.Password == loginModel.Password);

                if (user == null)
                {
                    loginModel.Status  = LoginStatus.Failed;
                    loginModel.Message = "Wrong username or password";
                }
                else
                {
                    loginModel.Status = LoginStatus.Succesful;

                    var claims = new[]
                    {
                        new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                        new Claim(ClaimTypes.Name, user.UserName)
                    };

                    var identity   = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                    var principal  = new ClaimsPrincipal(identity);
                    var properties = new AuthenticationProperties();

                    if (loginModel.Persist)
                    {
                        properties.IsPersistent = true;
                        properties.ExpiresUtc   = DateTime.UtcNow.AddMonths(12);
                    }

                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, properties);
                }
            }

            HttpContext.Session.Remove(nameof(ClientLoginModel.Captcha));
            return(loginModel);
        }
Exemplo n.º 13
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDistributedMemoryCache();

            services.AddSession(options =>
            {
                options.IdleTimeout        = TimeSpan.FromMinutes(60);
                options.Cookie.HttpOnly    = true;
                options.Cookie.IsEssential = true;
            });

            services.AddControllersWithViews();
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
            {
                options.Events = new CookieAuthenticationEvents
                {
                    OnRedirectToLogin = ctx =>
                    {
                        if (ctx.Request.Path.StartsWithSegments("/api"))
                        {
                            ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                        }
                        else
                        {
                            ctx.Response.Redirect(ctx.RedirectUri);
                        }

                        return(Task.FromResult(0));
                    }
                };
            });

            services.AddRazorPages();

            var config = new ShellConfiguration();

            Configuration.Bind("ShellConfiguration", config);
            services.AddSingleton(config);
            services.AddSingleton(new ShellPool(config));
        }
Exemplo n.º 14
0
        public ServerActiveSessionModel Connected(ActiveSessionModel activeSessionModel, ShellConfiguration shellConfiguration)
        {
            SshClient   sshClient   = null;
            ShellStream shellStream = null;

            try
            {
                var timeOutMinutes           = shellConfiguration.MaxIdleMinutes < 1 ? 1 : shellConfiguration.MaxIdleMinutes > 20 ? 20 : shellConfiguration.MaxIdleMinutes;
                var clientStoredSessionModel = activeSessionModel.StoredSessionModel;
                sshClient = new SshClient(clientStoredSessionModel.Host, clientStoredSessionModel.Port, clientStoredSessionModel.UserName, clientStoredSessionModel.PasswordDecryped);
                sshClient.ConnectionInfo.Timeout = TimeSpan.FromMinutes(timeOutMinutes);
                sshClient.Connect();
                shellStream = sshClient.CreateShellStream("Terminal", 80, 30, 800, 400, 1000);
                var outputQueue = new ConcurrentQueue <string>();

                var sessionModel = new ServerActiveSessionModel
                {
                    Status                = "Connected",
                    UniqueKey             = activeSessionModel.UniqueKey,
                    ShellStream           = shellStream,
                    Client                = sshClient,
                    StartSessionDate      = DateTime.Now,
                    LastAccessSessionDate = DateTime.Now,
                    StoredSessionModel    = clientStoredSessionModel,
                    OutputQueue           = outputQueue
                };

                string result = null;
                while ((result = sessionModel.ShellStream.ReadLine(TimeSpan.FromSeconds(0.3))) != null)
                {
                    outputQueue.Enqueue(result + Constants.NewLineForShell);
                }

                outputQueue.Enqueue(sessionModel.ShellStream.Read());

                shellStream.DataReceived += (obj, e) =>
                {
                    try
                    {
                        outputQueue.Enqueue(Encoding.UTF8.GetString(e.Data));

                        if (outputQueue.Count > Constants.MaxinumQueueCount)
                        {
                            outputQueue.TryDequeue(out _);
                        }
                    }
                    catch (Exception ex)
                    {
                        outputQueue.Enqueue(ex.Message);
                    }
                };

                AddActiveSession(sessionModel);

                sshClient.ErrorOccurred += SshClient_ErrorOccurred;

                return(sessionModel);
            }
            catch
            {
                shellStream?.Dispose();
                sshClient?.Dispose();

                throw;
            }
        }
Exemplo n.º 15
0
 public LoginController(ShellConfiguration shellConfiguration)
 {
     ShellConfiguration = shellConfiguration;
 }
Exemplo n.º 16
0
 public ShellSettings()
 {
     _settings      = new ShellConfiguration();
     _configuration = new ShellConfiguration();
 }
Exemplo n.º 17
0
 public ShellSettings(ShellConfiguration settings, ShellConfiguration configuration)
 {
     _settings      = settings;
     _configuration = configuration;
 }
Exemplo n.º 18
0
 public void SaveShellConfiguration(ShellConfiguration shellConfiguration)
 {
     _localSettings.WriteValueAsJson(nameof(ShellConfiguration), shellConfiguration);
 }