Esempio n. 1
0
        /// <summary>
        /// Process register payment step
        /// </summary>
        /// <param name="payment"></param>
        /// <param name="orderForm"></param>
        /// <param name="orderGroup"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public override PaymentStepResult Process(IPayment payment, IOrderForm orderForm, IOrderGroup orderGroup)
        {
            var paymentMethodDto = PaymentManager.GetPaymentMethod(payment.PaymentMethodId);

            if (payment.TransactionType == TransactionType.Authorization.ToString() && string.IsNullOrEmpty(payment.ProviderTransactionID))
            {
                var transactionId = "";
                try
                {
                    transactionId = this.Client.Register(CreatePaymentRequest(paymentMethodDto, payment, orderForm, orderGroup));
                }
                catch (Exception ex)
                {
                    Logger.Error(ex.Message);
                    AddNoteAndSaveChanges(orderGroup, "Payment Registered - Error", "Payment Registered - Error: " + ex.Message);
                    return(Fail(ex.Message));
                }

                payment.ProviderTransactionID = transactionId;
                AddNoteAndSaveChanges(orderGroup, "Payment - Registered", $"Payment - Registered with transactionId {transactionId}");

                var isProduction = bool.Parse(paymentMethodDto.GetParameter(NetaxeptConstants.IsProductionField, "false"));
                var merchantId   = paymentMethodDto.GetParameter(NetaxeptConstants.MerchantIdField);
                var redirectUrl  = TerminalHelper.GetRedirectUrl(merchantId, transactionId, isProduction);

                return(Success(redirectUrl));
            }
            else if (Successor != null)
            {
                return(Successor.Process(payment, orderForm, orderGroup));
            }

            return(Fail(null));
        }
Esempio n. 2
0
        public void ParseSettingsTest(string file)
        {
            var terminal = new TerminalPackage(string.Empty, new Version(), string.Empty, string.Empty, string.Empty);

            var settingsPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, file);
            var settings     = File.ReadAllText(settingsPath);
            var profiles     = TerminalHelper.ParseSettings(terminal, settings);

            Assert.AreEqual(profiles.Count, 4);
        }
Esempio n. 3
0
        public AddNewTerminalViewModel()
        {
            name = "";
            connectedBoolList = new List <bool>();
            connectedBoolList.Add(true);
            connectedBoolList.Add(false);
            connectedBoolselected = false;
            terminal = new TerminalHelper();

            AddCommand = new MyICommand <string>(OnAddCommand);
        }
Esempio n. 4
0
        public void ParseProfilesTest(string json, string identifier, string name, bool hidden)
        {
            var profileElement = JsonDocument.Parse(json).RootElement;
            var terminal       = new TerminalPackage(string.Empty, new Version(), string.Empty, string.Empty, string.Empty);
            var profile        = TerminalHelper.ParseProfile(terminal, profileElement);

            var expectedIdentifier = identifier != null ? new Guid(identifier) : null as Guid?;

            Assert.AreEqual(profile.Terminal, terminal);
            Assert.AreEqual(profile.Identifier, expectedIdentifier);
            Assert.AreEqual(profile.Name, name);
            Assert.AreEqual(profile.Hidden, hidden);
        }
Esempio n. 5
0
 private void LaunchElevated(string id, string profile)
 {
     try
     {
         string path = "shell:AppsFolder\\" + id;
         Helper.OpenInShell(path, TerminalHelper.GetArguments(profile, _openNewTab), runAs: Helper.ShellRunAsType.Administrator);
     }
     catch (Exception ex)
     {
         var name    = "Plugin: " + Resources.plugin_name;
         var message = Resources.run_terminal_failed;
         Log.Exception("Failed to open Windows Terminal", ex, GetType());
         _context.API.ShowMsg(name, message, string.Empty);
     }
 }
        public void SynchronizeTerminals()
        {
            var channels = Channels.Keys.ToArray();

            Console.WriteLine("SynchronizeTerminals. Channel Count: {0}", channels.Length);
            try
            {
                foreach (var channel in channels)
                {
                    try
                    {
                        bool result = Channels.TryGetValue(channel, out ChannelInfo info);
                        Console.WriteLine("Channel Key: {0}", info.ChannelKey);
                        if (result)
                        {
                            var kickInterval = DateTimeHelper.CurrentUniversalTime
                                               .AddSeconds(-(ServerChannelConfigurationManager.Instance
                                                             .Configurations.KickIntervalInSeconds));

                            if (kickInterval > info.LastDataReceived && kickInterval > info.ConnectedOn)
                            {
                                RemoveChannel(channel);
                            }
                            else
                            {
                                var pingInterval = DateTimeHelper.CurrentUniversalTime
                                                   .AddSeconds(-(ServerChannelConfigurationManager.Instance
                                                                 .Configurations.PingIntervalInSeconds));
                                if (pingInterval > info.LastSynchronized)
                                {
                                    channel.WriteAndFlushAsync(TerminalHelper.TimeSync());
                                    info.LastSynchronized = DateTimeHelper.CurrentUniversalTime;
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Esempio n. 7
0
        private void LaunchElevated(string id, string profile)
        {
            try
            {
                string path = "shell:AppsFolder\\" + id;
                Helper.OpenInShell(path, TerminalHelper.GetArguments(profile, _openNewTab), runAsAdmin: true);
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
            {
                var name    = "Plugin: " + Resources.plugin_name;
                var message = Resources.run_terminal_failed;
                Log.Exception("Failed to open Windows Terminal", ex, GetType());
                _context.API.ShowMsg(name, message, string.Empty);
            }
        }
Esempio n. 8
0
        private void Launch(string id, string profile)
        {
            var appManager = new ApplicationActivationManager();
            const ActivateOptions noFlags = ActivateOptions.None;
            var queryArguments            = TerminalHelper.GetArguments(profile, _openNewTab);

            try
            {
                appManager.ActivateApplication(id, queryArguments, noFlags, out var unusedPid);
            }
            catch (Exception ex)
            {
                var name    = "Plugin: " + Resources.plugin_name;
                var message = Resources.run_terminal_failed;
                Log.Exception("Failed to open Windows Terminal", ex, GetType());
                _context.API.ShowMsg(name, message, string.Empty);
            }
        }
        public override void ChannelActive(IChannelHandlerContext context)
        {
            string methodName = nameof(ChannelActive);

            try
            {
                base.ChannelActive(context);
                context.WriteAndFlushAsync(TerminalHelper.TimeSync());
                var info = ChannelManager.Instance.AddChannel(context);
                if (info == null)
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                Log?.Error(className, methodName, ex.ToString());
            }
        }
Esempio n. 10
0
        public async void CanProcessAuthorize()
        {
            var appSettings = ConfigurationManager.AppSettings;

            var merchantId   = appSettings["Netaxept:MerchantId"];
            var token        = appSettings["Netaxept:Token"];
            var isProduction = false;

            var client = new NetaxeptServiceClient(new ClientConnection(merchantId, token, isProduction));

            var paymentRequest = CreatePaymentRequest();
            var transactionId  = client.Register(paymentRequest);

            var redirectUrl = TerminalHelper.GetRedirectUrl(merchantId, transactionId, isProduction);

            var browserFetcher = new BrowserFetcher();
            var launchOptions  = new LaunchOptions {
                Headless = true
            };
            await browserFetcher.DownloadAsync();

            using (var browser = await Puppeteer.LaunchAsync(launchOptions))
                using (var page = await browser.NewPageAsync())
                {
                    await page.GoToAsync(redirectUrl);
                    await ExecuteCustomerPaymentAutomation(page, "#Visa", "4925000000000004", DateTime.UtcNow.AddYears(1), "123");

                    // For some reason, page.WaitForNavigationAsync doesn't work
                    // 5 seconds seems enough time for Nets to process
                    await page.WaitForTimeoutAsync(5000);

                    Assert.StartsWith(paymentRequest.SuccessUrl, page.Url);
                }

            var processResult = client.Authorize(transactionId);

            Assert.Equal("OK", processResult.ResponseCode);

            var paymentResult = client.Query(transactionId);

            Assert.True(paymentResult.Authorized);
        }
Esempio n. 11
0
        /// <summary>
        /// Get terminal url for test or production
        /// </summary>
        /// <param name="paymentMethodDto"></param>
        /// <returns></returns>
        private string GetTerminalUrl(PaymentMethodDto paymentMethodDto)
        {
            var isProduction = bool.Parse(paymentMethodDto.GetParameter(NetaxeptConstants.IsProductionField, "false"));

            return(TerminalHelper.GetTerminalUrl(isProduction));
        }
Esempio n. 12
0
        public async Task <int> Execute()
        {
            //Logger.Instance.Log("Params: " + Newtonsoft.Json.JsonConvert.SerializeObject(this), LogLevel.Debug);

            var  currentProcess = System.Diagnostics.Process.GetCurrentProcess();
            bool emptyArgs      = string.IsNullOrEmpty(CommandToRun.FirstOrDefault());

            CommandToRun = ArgumentsHelper.AugmentCommand(CommandToRun.ToArray());
            bool isWindowsApp = ProcessFactory.IsWindowsApp(CommandToRun.FirstOrDefault());
            var  consoleMode  = GetConsoleMode(isWindowsApp);

            if (!RunningAsDesiredUser())
            {
                CommandToRun = AddCopyEnvironment(CommandToRun);
            }
            var exeName = CommandToRun.FirstOrDefault();

            var elevationRequest = new ElevationRequest()
            {
                FileName         = exeName,
                Arguments        = GetArguments(),
                StartFolder      = Environment.CurrentDirectory,
                NewWindow        = GlobalSettings.NewWindow,
                Wait             = (!isWindowsApp && !GlobalSettings.NewWindow) || GlobalSettings.Wait,
                Mode             = consoleMode,
                ConsoleProcessId = currentProcess.Id,
                Prompt           = consoleMode != ElevationRequest.ConsoleMode.Raw || GlobalSettings.NewWindow ? GlobalSettings.Prompt : GlobalSettings.RawPrompt
            };

            Logger.Instance.Log($"Command to run: {elevationRequest.FileName} {elevationRequest.Arguments}", LogLevel.Debug);

            if (elevationRequest.Mode == ElevationRequest.ConsoleMode.VT)
            {
                elevationRequest.ConsoleWidth  = Console.WindowWidth;
                elevationRequest.ConsoleHeight = Console.WindowHeight;

                if (TerminalHelper.IsConEmu())
                {
                    elevationRequest.ConsoleWidth--; // weird ConEmu/Cmder fix
                }
            }

            if (RunningAsDesiredUser()) // already elevated or running as correct user. No service needed.
            {
                if (emptyArgs && !GlobalSettings.NewWindow)
                {
                    Logger.Instance.Log("Already elevated (and no parameters specified). Exiting...", LogLevel.Error);
                    return(Constants.GSUDO_ERROR_EXITCODE);
                }

                Logger.Instance.Log("Already elevated. Running in-process", LogLevel.Debug);

                // No need to escalate. Run in-process

                if (elevationRequest.Mode == ElevationRequest.ConsoleMode.Raw && !elevationRequest.NewWindow)
                {
                    if (!string.IsNullOrEmpty(GlobalSettings.RawPrompt.Value))
                    {
                        Environment.SetEnvironmentVariable("PROMPT", Environment.ExpandEnvironmentVariables(GlobalSettings.RawPrompt.Value));
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(GlobalSettings.Prompt.Value))
                    {
                        Environment.SetEnvironmentVariable("PROMPT", Environment.ExpandEnvironmentVariables(GlobalSettings.Prompt.Value));
                    }
                }

                if (GlobalSettings.NewWindow)
                {
                    using (Process process = ProcessFactory.StartDetached(exeName, GetArguments(), Environment.CurrentDirectory, false))
                    {
                        if (elevationRequest.Wait)
                        {
                            process.WaitForExit();
                            var exitCode = process.ExitCode;
                            Logger.Instance.Log($"Elevated process exited with code {exitCode}", exitCode == 0 ? LogLevel.Debug : LogLevel.Info);
                            return(exitCode);
                        }
                        return(0);
                    }
                }
                else
                {
                    using (Process process = ProcessFactory.StartInProcessAtached(exeName, GetArguments()))
                    {
                        process.WaitForExit();
                        var exitCode = process.ExitCode;
                        Logger.Instance.Log($"Elevated process exited with code {exitCode}", exitCode == 0 ? LogLevel.Debug : LogLevel.Info);
                        return(exitCode);
                    }
                }
            }
            else
            {
                Logger.Instance.Log($"Using Console mode {elevationRequest.Mode}", LogLevel.Debug);
                var callingPid = GetCallingPid(currentProcess);
                var callingSid = WindowsIdentity.GetCurrent().User.Value;
                Logger.Instance.Log($"Caller PID: {callingPid}", LogLevel.Debug);
                Logger.Instance.Log($"Caller SID: {callingSid}", LogLevel.Debug);

                var cmd = CommandToRun.FirstOrDefault();

                var            rpcClient  = GetClient(elevationRequest);
                Rpc.Connection connection = null;

                try
                {
                    try
                    {
                        connection = await rpcClient.Connect(elevationRequest, null, 300).ConfigureAwait(false);
                    }
                    catch (System.IO.IOException) { }
                    catch (TimeoutException) { }
                    catch (Exception ex)
                    {
                        Logger.Instance.Log(ex.ToString(), LogLevel.Warning);
                    }

                    if (connection == null) // service is not running or listening.
                    {
                        // Start elevated service instance
                        if (!StartElevatedService(currentProcess, callingPid, callingSid))
                        {
                            return(Constants.GSUDO_ERROR_EXITCODE);
                        }

                        connection = await rpcClient.Connect(elevationRequest, callingPid, 5000).ConfigureAwait(false);
                    }

                    if (connection == null) // service is not running or listening.
                    {
                        Logger.Instance.Log("Unable to connect to the elevated service.", LogLevel.Error);
                        return(Constants.GSUDO_ERROR_EXITCODE);
                    }

                    await WriteElevationRequest(elevationRequest, connection).ConfigureAwait(false);

                    ConnectionKeepAliveThread.Start(connection);

                    var renderer = GetRenderer(connection, elevationRequest);
                    var exitCode = await renderer.Start().ConfigureAwait(false);

                    if (!(elevationRequest.NewWindow && !elevationRequest.Wait))
                    {
                        Logger.Instance.Log($"Elevated process exited with code {exitCode}", exitCode == 0 ? LogLevel.Debug : LogLevel.Info);
                    }

                    return(exitCode);
                }
                finally
                {
                    connection?.Dispose();
                }
            }
        }
Esempio n. 13
0
        public async Task <int> Execute()
        {
            int? exitCode;
            bool isRunningAsDesiredUser = IsRunningAsDesiredUser();
            bool isElevationRequired    = IsElevationRequired();

            bool isShellElevation = string.IsNullOrEmpty(CommandToRun.FirstOrDefault()); // are we auto elevating the current shell?

            if (isElevationRequired & ProcessHelper.GetCurrentIntegrityLevel() < (int)IntegrityLevel.Medium)
            {
                throw new ApplicationException("Sorry, gsudo doesn't allow to elevate from low integrity level."); // This message is not a security feature, but a nicer error message. It would have failed anyway since the named pipe's ACL restricts it.
            }
            CommandToRun = ArgumentsHelper.AugmentCommand(CommandToRun.ToArray());
            bool isWindowsApp = ProcessFactory.IsWindowsApp(CommandToRun.FirstOrDefault());

            var elevationMode = GetElevationMode(isWindowsApp);

            if (!isRunningAsDesiredUser)
            {
                CommandToRun = AddCopyEnvironment(CommandToRun, elevationMode);
            }

            var exeName = CommandToRun.FirstOrDefault();

            var elevationRequest = new ElevationRequest()
            {
                FileName         = exeName,
                Arguments        = GetArguments(),
                StartFolder      = Environment.CurrentDirectory,
                NewWindow        = InputArguments.NewWindow,
                Wait             = (!isWindowsApp && !InputArguments.NewWindow) || InputArguments.Wait,
                Mode             = elevationMode,
                ConsoleProcessId = Process.GetCurrentProcess().Id,
                IntegrityLevel   = InputArguments.GetIntegrityLevel(),
            };

            if (isElevationRequired && Settings.SecurityEnforceUacIsolation)
            {
                AdjustUacIsolationRequest(elevationRequest, isShellElevation);
            }

            SetRequestPrompt(elevationRequest);

            Logger.Instance.Log($"Command to run: {elevationRequest.FileName} {elevationRequest.Arguments}", LogLevel.Debug);

            if (elevationRequest.Mode == ElevationRequest.ConsoleMode.VT)
            {
                elevationRequest.ConsoleWidth  = Console.WindowWidth;
                elevationRequest.ConsoleHeight = Console.WindowHeight;

                if (TerminalHelper.IsConEmu())
                {
                    elevationRequest.ConsoleWidth--; // weird ConEmu/Cmder fix
                }
            }

            if (isRunningAsDesiredUser && isShellElevation && !InputArguments.NewWindow)
            {
                Logger.Instance.Log("Already running as the specified user/permission-level (and no command specified). Exiting...", LogLevel.Error);
                return(Constants.GSUDO_ERROR_EXITCODE);
            }

            if (isRunningAsDesiredUser || !isElevationRequired) // already elevated or running as correct user. No service needed.
            {
                return(RunWithoutService(exeName, GetArguments(), elevationRequest));
            }

            if (Settings.CacheMode.Value.In(CacheMode.Disabled) ||
                Math.Abs(Settings.CacheDuration.Value.TotalSeconds) < 1 ||
                (InputArguments.KillCache && !IsServiceAvailable()))
            {
                exitCode = await RunUsingSingleUseElevation(elevationRequest).ConfigureAwait(false);
            }
            else if (Settings.CacheMode.Value.In(CacheMode.Auto) ||
                     elevationRequest.Mode != ElevationRequest.ConsoleMode.TokenSwitch)
            {
                exitCode = await RunUsingElevatedService(elevationRequest).ConfigureAwait(false);
            }
            else if (Settings.CacheMode.Value == CacheMode.Explicit && IsServiceAvailable())
            {
                exitCode = await RunUsingElevatedService(elevationRequest).ConfigureAwait(false);
            }
            else
            {
                exitCode = await RunUsingSingleUseElevation(elevationRequest).ConfigureAwait(false);
            }

            if (exitCode.HasValue && exitCode.Value != Constants.GSUDO_ERROR_EXITCODE)
            {
                Logger.Instance.Log($"Process exited with code {exitCode}", exitCode == 0 ? LogLevel.Debug : LogLevel.Info);
            }

            return(exitCode ?? 0);
        }
 protected override void Run()
 {
     TerminalHelper.OpenTerminal(ProjectHelper.GetCurrentPath());
 }
Esempio n. 15
0
        public void ArgumentsTest(string profile, bool openNewTab, string expectedArguments)
        {
            var arguments = TerminalHelper.GetArguments(profile, openNewTab);

            Assert.AreEqual(arguments, expectedArguments);
        }
Esempio n. 16
0
        private static string GetImageBase64()
        {
            TerminalHelper.Execute($"fswebcam --save {ConfigHelper.Get("UsbCamera:ImagePath")} -d {ConfigHelper.Get("UsbCamera:Driver")} -S 1 -r 640x480");

            return(FileHelper.FileToBase64(ConfigHelper.Get("UsbCamera:ImagePath")));
        }
Esempio n. 17
0
        public async Task <int> Start()
        {
            if (Settings.SecurityEnforceUacIsolation)
            {
                throw new NotSupportedException("VT Mode not supported when SecurityEnforceUacIsolation=true");
            }

            Console.OutputEncoding = System.Text.Encoding.UTF8;
            ConsoleHelper.EnableVT();

            try
            {
                Console.CancelKeyPress += CancelKeyPressHandler;

                var t1 = new StreamReader(_connection.DataStream, Settings.Encoding)
                         .ConsumeOutput((s) => WriteToConsole(s));
                var t2 = new StreamReader(_connection.ControlStream, Settings.Encoding)
                         .ConsumeOutput((s) => HandleControlData(s));

                while (_connection.IsAlive)
                {
                    try
                    {
                        while (Console.KeyAvailable)
                        {
                            consecutiveCancelKeys = 0;
                            // send input character-by-character to the pipe
                            var    key      = Console.ReadKey(intercept: true);
                            char[] sequence = TerminalHelper.GetSequenceFromConsoleKey(key, InputArguments.Debug && _elevationRequest.FileName.EndsWith("KeyPressTester.exe", StringComparison.OrdinalIgnoreCase));

                            await _connection.DataStream.WriteAsync(new string(sequence)).ConfigureAwait(false);
                        }
                    }
                    catch (ObjectDisposedException)
                    {
                        break;
                    }
                    catch (IOException)
                    {
                        break;
                    }
                    await Task.Delay(20).ConfigureAwait(false);
                }

                await _connection.FlushAndCloseAll().ConfigureAwait(false);

                if (ExitCode.HasValue && ExitCode.Value == 0 && InputArguments.NewWindow)
                {
                    Logger.Instance.Log($"Process started successfully", LogLevel.Debug);
                    return(0);
                }
                else if (ExitCode.HasValue)
                {
                    return(ExitCode.Value);
                }
                else if (expectedClose)
                {
                    Logger.Instance.Log($"Connection closed by the client.", LogLevel.Debug);
                    return(0);
                }
                else
                {
                    Logger.Instance.Log($"Connection from server lost.", LogLevel.Warning);
                    return(Constants.GSUDO_ERROR_EXITCODE);
                }
            }
            finally
            {
                Console.CancelKeyPress -= CancelKeyPressHandler;
            }
        }