Exemplo n.º 1
0
        public Func <int> startHTTPThread(out ThreadTask <OneTimeHTTPRequest.HTTPTaskResult> httpTask,
                                          string TokenData, int acceptTimeoutSec, string contentType = "text/plain")
        {
            OneTimeHTTPRequest server = new OneTimeHTTPRequest()
            {
                findInRequest   = Properties.Settings.Default.RequestMustContainArray.Split(';'),
                AcceptTimeout   = TimeSpan.FromSeconds(acceptTimeoutSec),
                DataToServe     = Encoding.ASCII.GetBytes(TokenData),
                DataContentType = contentType
            };

            httpTask = new ThreadTask <OneTimeHTTPRequest.HTTPTaskResult>(
                () => { return(server.StartListener(IPAddress.Loopback, 0, () => Flags.USER_CANCEL)); }
                );
            httpTask.Start();
            return(() => server.Port);
        }
Exemplo n.º 2
0
        public void joinHTTPThread(ThreadTask <OneTimeHTTPRequest.HTTPTaskResult> httpTask, bool killOnTokenError)
        {
            if (httpTask.Join())
            {
                OneTimeHTTPRequest.HTTPTaskResult httpTaskResult = httpTask.Result();
                switch (httpTaskResult.StatusCode)
                {
                case OneTimeHTTPRequest.HTTPResultEnum.SUCCESS:
                    checkItem("STEP_TOKEN");
                    log("Token sucess!!");
                    break;

                case OneTimeHTTPRequest.HTTPResultEnum.NOTOKEN_ERROR:
                    log("Error serving token\n" + httpTaskResult.description);
                    checkItem("STEP_ERROR");
                    break;

                case OneTimeHTTPRequest.HTTPResultEnum.TOKEN_AUTH_ERROR:
                    checkItem("STEP_TOKEN_ERROR");
                    log("Error that might risk the token, error: " +
                        httpTaskResult.description);
                    if (killOnTokenError)
                    {
                        log("closing all processes in user because token error");
                        new ProcessWatcher(LimitedChromeManager.Properties.Settings.Default.AllowedClientUsernames)
                        .KillAllUserProcesses(() => false);
                    }
                    else
                    {
                        log("Skipping closing apps due to config");
                    }
                    break;
                }
            }
            else
            {
                log("Error serving token\n" + httpTask.GetError());
                checkItem("STEP_ERROR");
            }
        }
Exemplo n.º 3
0
 public static void fastThread(
     threadAction mainAction, Action <T> onSucess,
     Action <Exception> onThreadError,
     Action <Exception> onError)
 {
     try
     {
         ThreadTask <T> tt = new ThreadTask <T>(mainAction);
         tt.Start();
         if (tt.Join())
         {
             onSucess(tt.Result());
         }
         else
         {
             onThreadError(tt.GetError());
         }
     }
     catch (Exception ex)
     {
         onError(ex);
     }
 }
Exemplo n.º 4
0
        private void bwProcess_DoWork(object sender, DoWorkEventArgs e)
        {
            /* Example for running multiple tasks:
             * ============================================
             * Thread wait5 = new Thread(wait5SecondThread_example);
             * Thread waitCancel = new Thread(waitForCancel_example);
             * wait5.Start();
             * waitCancel.Start();
             * waitCancel.Join();
             * wait5.Join();
             */

            // Steps:
            // =====================================
            int step = 100 / 7;

            log("Getting all EP from proxy");
            string[] req_proxy = Properties.Settings.Default.DebugProxyString.Split(':');
            WebProxy myProxy   = null; // For development porpuses

            if (req_proxy.Length == 2 && int.TryParse(req_proxy[1], out _))
            {
                myProxy = new WebProxy(req_proxy[0], int.Parse(req_proxy[1]));
            }
            JsonElement endpoints = JsonSerializer.Deserialize <JsonElement>(
                RequestSync("http://" + proxy_host + "/", accept: "application/json", proxy: myProxy)
                );

            // 0. Token Challenge
            TokenResult token = TokenChallenge(endpoints, myProxy);

            if (string.IsNullOrEmpty(token.token))
            {
                log("Got empty token!");
                checkItem("STEP_TOKEN_ERROR");
            }
            else
            {
                checkItem("STEP_TOKEN_CHALL");
                setProgress(step * 1);


                // 1. Close all apps in LimitedChrome
                if (Properties.Settings.Default.ShouldKillProcessAtStart)
                {
                    ProcessWatcher pw =
                        new ProcessWatcher(Properties.Settings.Default.AllowedClientUsernames);
                    checkItem("STEP_CLEAN");
                    log("Closing apps in limited user...");
                    int closedProcesses = pw.KillAllUserProcesses(() => Flags.USER_CANCEL);
                    log("Closed " + closedProcesses + " apps in limited user");
                }
                else
                {
                    log("Skipping closing apps due to config");
                }
                setProgress(step * 2);

                // 3. Start HTTP Token server (Has accept timout)
                log("Starting HTTP Token server...");
                checkItem("STEP_HTTP");
                string token_stringify = JsonSerializer.Serialize(token);

                ThreadTask <OneTimeHTTPRequest.HTTPTaskResult> httpTask = null;
                Func <int> start_port = startHTTPThread(out httpTask, token_stringify,
                                                        Properties.Settings.Default.RequestTimeoutSec, contentType: "application/json");

                // Let port populate by unjoind thread
                int get_port_retries = 10;
                int actual_port      = start_port();
                while (actual_port < 0 && get_port_retries > 0)
                {
                    Thread.Sleep((int)TimeSpan.FromSeconds(1).TotalMilliseconds);

                    get_port_retries--;
                    actual_port = start_port();
                }
                if (actual_port < 0)
                {
                    throw new Exception("Can't get server port");
                }

                log("Server started in address http://localhost:" + actual_port + "/");
                setProgress(step * 3);

                log("Sending temp token to proxy...");
                SendTempPort(endpoints, myProxy, actual_port);
                checkItem("STEP_TEMP_PORT");
                setProgress(step * 4);

                // 4. Run chrome limited
                Process p = Process.Start(
                    Properties.Settings.Default.ProcessToRun,
                    Properties.Settings.Default.ProcessToRunArgs
                    );
                log("Open process with Id: " + p.Id + ", Exited? " + p.HasExited);
                checkItem("STEP_CHROME");
                setProgress(step * 5);

                // 5. Wait for HTTP thread to join
                setProgress(-1);
                joinHTTPThread(httpTask, killOnTokenError: Properties.Settings.Default.ShouldKillProcessAtStart);
                setProgress(step * 6);

                log("All Done threads!");
                setProgress(100);
            }
        }