示例#1
0
 public ProcessLogic(Simulator.Simulator process)
 {
     this.process       = process;
     this.previousState = new BitArray(new byte[] { process.Get_State(), 0x00 });
     this.threeSecRule  = new Timer(3000)
     {
         AutoReset = false
     };
     this.threeSecRule.Elapsed += ThreeSecRuleCommand;
     this.functioningPumps      = new bool[] { true, true };
 }
示例#2
0
 private static void MainMenu()
 {
     Console.Clear();
     Console.WriteLine("Welcome to simulator for Hamsters");
     Console.Write("Enter how many days the simulator will run: ");
     int.TryParse(Console.ReadLine(), out int days);
     if (days == 0 || days > 11)
     {
         Console.Clear();
         Console.WriteLine("Can't choose zero days. Try again.");
         Console.WriteLine("Press any key.");
         Console.ReadKey();
         MainMenu();
     }
     Console.Clear();
     Console.Write("Enter tick speed (milliseconds): ");
     int.TryParse(Console.ReadLine(), out int tickSpeed);
     if (tickSpeed < 1 || tickSpeed > 2000)
     {
         Console.Clear();
         Console.WriteLine("To slow. Try again.");
         Console.WriteLine("Press any key.");
         Console.ReadKey();
         MainMenu();
     }
     Console.Clear();
     Console.Write("Enter print speed (milliseconds): ");
     int.TryParse(Console.ReadLine(), out int printSpeed);
     _printSpeed = printSpeed;
     if (printSpeed < tickSpeed)
     {
         Console.Clear();
         Console.WriteLine("Print speed can't be lower than tick speed. Try again.");
         Console.WriteLine("Press any key.");
         Console.ReadKey();
         MainMenu();
     }
     else
     {
         Console.Clear();
         var simulator = new Simulator.Simulator(tickSpeed, days);
         simulator.RunSimulator();
         ReadingInput();
         Print();
     }
 }
示例#3
0
文件: Program.cs 项目: martinaPB/PS2
        static void Main(string[] args)
        {
            Console.WriteLine("Press enter to start...");
            Console.ReadLine();

            process = new Simulator.Simulator();


            senderWorker = new BackgroundWorker();
            senderWorker.WorkerReportsProgress = true;
            senderWorker.DoWork          += SenderWorker_DoWork;
            senderWorker.ProgressChanged += SenderWorker_ProgressChanged;
            senderWorker.RunWorkerAsync();

            Thread listenThread = new Thread(Listen);

            listenThread.Start();
        }
示例#4
0
        private void button1_Click(object sender, EventArgs e)
        {
            _serialPort = new SerialPort();
            _serialPort2 = new SerialPort();

            _serialPort.PortName = comboBox1.SelectedItem.ToString();
            _serialPort.BaudRate = Convert.ToInt32(comboBox2.SelectedItem.ToString());
            _serialPort.Parity = (Parity)Enum.Parse(typeof(Parity), comboBox3.SelectedItem.ToString());
            _serialPort.DataBits = int.Parse(comboBox4.SelectedItem.ToString());
            _serialPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBox5.SelectedItem.ToString());
            _serialPort.Handshake = (Handshake)Enum.Parse(typeof(Handshake), comboBox6.SelectedItem.ToString());

            //_serialPort2.PortName = comboBox12.SelectedItem.ToString();
            _serialPort2.BaudRate = Convert.ToInt32(comboBox11.SelectedItem.ToString());
            _serialPort2.Parity = (Parity)Enum.Parse(typeof(Parity), comboBox10.SelectedItem.ToString());
            _serialPort2.DataBits = int.Parse(comboBox9.SelectedItem.ToString());
            _serialPort2.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBox8.SelectedItem.ToString());
            _serialPort2.Handshake = (Handshake)Enum.Parse(typeof(Handshake), comboBox7.SelectedItem.ToString());

            _serialPort.ReadTimeout = 500;
            _serialPort.WriteTimeout = 500;

            _serialPort2.ReadTimeout = 500;
            _serialPort2.WriteTimeout = 500;

            try
            {

                Simulator x = new Simulator(_serialPort, _serialPort2);
                this.Hide();
                x.Show();

            }
            catch(Exception ex)
            {

                MessageBox.Show(ex.ToString());

            }
        }
示例#5
0
        static void Main()
        {
            Console.WriteLine("Press enter to start...");
            Console.ReadLine();

            process = new Simulator.Simulator();
            logic   = new ProcessLogic(process);

            Thread processThread = new Thread(process.Simulate);

            processThread.Start();                  //pornire thread proces

            Thread logicThread = new Thread(logic.Run);

            logicThread.Start();                    //pornire thread logica

            Thread senderThread = new Thread(Send);

            senderThread.Start();                   //pornire thread send

            Thread listenThread = new Thread(Listen);

            listenThread.Start();                   //pornire thread listen
        }
示例#6
0
 static void Run()
 {
     try
     {
         GUI.PrintInfo();
         bool restart = true;
         while (restart)
         {
             Simulator = new Simulator.Simulator(10, 100);
             BackEnd.DaycareContext.SetupDaycareDatabase();
             restart = GUI.BootSetup();
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex);
     }
     finally
     {
         BackEnd.DaycareContext.ResetHamsterValues();
         BackEnd.DaycareContext.ClearLogs();
         Environment.Exit(0);
     }
 }
示例#7
0
        public static void RunExperimentalSweep(ExperimentalConfiguration[] configurations)
        {
            foreach (ExperimentalConfiguration config in configurations)
            {
                DateTime now = DateTime.Now;
                string dirName = config.OutputPath + config.OutputDirectoryName;
                Directory.CreateDirectory(dirName);
                string path = dirName + @"\";

                // Now that all of the parameters of the sweep have been set, run the simulation
                //TextWriter dataWriter = System.IO.TextWriter.Synchronized(new StreamWriter(path + "data.txt"));
                TextWriter errorWriter = //TextWriter.Synchronized
                    (new StreamWriter(new FileStream(path + "error.txt", FileMode.CreateNew, FileAccess.Write)));
                DebugLogger logger = new DebugLogger(errorWriter);
                try
                {
                    SimulatedPasswords simPasswords = new SimulatedPasswords(logger, config);
                    Simulator simulator = new Simulator(logger, path, config, simPasswords);
                    simulator.Run();
                }
                catch (Exception e)
                {
                    lock (errorWriter)
                    {
                        while (e != null)
                        {
                            errorWriter.WriteLine(e.Message);
                            errorWriter.WriteLine(e.StackTrace);
                            errorWriter.WriteLine(e);
                            e = e.InnerException;
                        }
                        errorWriter.Flush();
                    }
                }
            }
        }
示例#8
0
        public static void Main(string[] args)
        {
            if (args.Length < 3)
            {
                Console.WriteLine("ERROR: Please specify a drone IP, command port, state port, desired timeout (ms)," +
                                  " maximum number of retries, and desired missions. If a value is left blank," +
                                  " a reasonable default will be used instead.\n" +
                                  "Examples:\n" +
                                  "./DroneController ip=127.0.0.1 cmdport=8889 stateport=8890 timeout=2000 retries=5 missions=1\n" +
                                  "./DroneController stateport=8890 timeout=2000 retries=5 missions=1,3\n" +
                                  "./DroneController ip=127.0.0.1 cmdport=8889 stateport=8890 missions=1,2,3\n");
                return;
            }

            string     droneIP         = DefaultConstants.LOCALHOST;
            int        cmdport         = DefaultConstants.DEFAULT_COMMAND_PORT;
            int        stateport       = DefaultConstants.DEFAULT_TELLO_STATE_PORT;
            int        timeout         = DefaultConstants.DEFAULT_TIMEOUT;
            uint       retries         = DefaultConstants.DEFAULT_MAX_RETRIES;
            List <int> desiredMissions = new List <int>();

            foreach (string param in args)
            {
                if (param.StartsWith("ip"))
                {
                    droneIP = param.Split('=')[1];
                }
                else if (param.StartsWith("cmdport"))
                {
                    cmdport = int.Parse(param.Split('=')[1]);
                }
                else if (param.StartsWith("stateport"))
                {
                    stateport = int.Parse(param.Split('=')[1]);
                }
                else if (param.StartsWith("timeout"))
                {
                    timeout = int.Parse(param.Split('=')[1]);
                }
                else if (param.StartsWith("retries"))
                {
                    retries = uint.Parse(param.Split('=')[1]);
                }
                else if (param.StartsWith("missions"))
                {
                    string[] missionStrings = param.Split('=')[1].Split(',');
                    foreach (string mission in missionStrings)
                    {
                        desiredMissions.Add(int.Parse(mission));
                    }
                }
                else
                {
                    Console.WriteLine("WARNING: Invalid commandline argument found: " + param);
                }
            }

            Simulator.Simulator simulator = new Simulator.Simulator(
                commandPort: cmdport,
                telloStatePort: stateport,
                timeout: timeout,
                maxRetries: retries
                );
            simulator.start();

            DroneSession droneSession = new DroneSession(
                droneIp: droneIP,
                commandPort: cmdport,
                telloStatePort: stateport,
                timeout: timeout,
                maxRetries: retries
                );

            foreach (int desiredMission in desiredMissions)
            {
                Console.WriteLine("--- Now executing mission " + desiredMission + " ---");
                droneSession.executeMission(desiredMission);
                Console.WriteLine();
            }

            droneSession.getUDPClient().stop();
            simulator.stop();
        }
示例#9
0
        //public DecayingDouble AllFailures(TimeSpan halfLife) => AccountFailures.Add(halfLife, PasswordFailures);

        //public DecayingDouble AccountFailuresSubsetWithInfrequentPassword(TimeSpan halfLife) => AccountFailures.Subtract(halfLife, AccountFailuresSubsetWithFrequentPassword);
        //public DecayingDouble PasswordFailuresSubsetWithInfrequentPassword(TimeSpan halfLife) => PasswordFailures.Subtract(halfLife, PasswordFailuresSubsetWithFrequentPassword);
        //public DecayingDouble PasswordFailuresSubsetWithoutTypo(TimeSpan halfLife) => PasswordFailures.Subtract(halfLife, PasswordFailuresSubsetWithTypo);
        //public DecayingDouble PasswordFailuresSubsetWithoutEitherFrequentPasswordOrTypo(TimeSpan halfLife) => PasswordFailures.Subtract(halfLife, PasswordFailuresSubsetWithTypoAndFrequentPassword);

        /// <summary>
        /// This analysis will examine the client IP's previous failed attempts to login to this account
        /// to determine if any failed attempts were due to typos.  
        /// </summary>
        /// <param name="account">The account that the client is currently trying to login to.</param>
        /// <param name="whenUtc"></param>
        /// <param name="correctPassword">The correct password for this account.  (We can only know it because
        /// the client must have provided the correct one this loginAttempt.)</param>
        /// <returns></returns>
        public void AdjustBlockingScoreForPastTyposTreatedAsFullFailures(
            Simulator simulator,
            SimulatedUserAccount account,
            DateTime whenUtc,
            string correctPassword)
        {
            SimLoginAttemptSummaryForTypoAnalysis[] recentPotentialTypos =
                RecentPotentialTypos.MostRecentFirst.ToArray();
            foreach (SimLoginAttemptSummaryForTypoAnalysis potentialTypo in recentPotentialTypos)
            {
                if (account == null || potentialTypo.UsernameOrAccountId != account.UsernameOrAccountId)
                    continue;

                // Use an edit distance calculation to determine if it was a likely typo
                bool likelyTypo =
                    EditDistance.Calculate(potentialTypo.Password, correctPassword) <=
                    simulator._experimentalConfiguration.BlockingOptions.MaxEditDistanceConsideredATypo;

                TimeSpan halfLife = simulator._experimentalConfiguration.BlockingOptions.BlockScoreHalfLife;
                DecayingDouble value = new DecayingDouble(1d, potentialTypo.WhenUtc);
                // Add this to the list of changed attempts
                if (potentialTypo.WasPasswordFrequent)
                {
                    PasswordFailuresNoTypoFrequentPassword.SubtractInPlace(halfLife, value);
                    PasswordFailuresTypoFrequentPassword.AddInPlace(halfLife, value);
                }
                RecentPotentialTypos.Remove(potentialTypo);
            }
        }
示例#10
0
        private void button3_Click(object sender, EventArgs e)
        {
            _serialPort = new SerialPort();

            _serialPort.PortName = comboBox1.SelectedItem.ToString();
            _serialPort.BaudRate = 9600;
            _serialPort.Parity = Parity.None;
            _serialPort.DataBits = 8;
            _serialPort.StopBits = StopBits.One;
            _serialPort.Handshake = Handshake.None;

            _serialPort.ReadTimeout = 500;
            _serialPort.WriteTimeout = 500;

            _serialPort2 = new SerialPort();

            _serialPort2.PortName = textBox1.Text.ToString();
            _serialPort2.BaudRate = 9600;
            _serialPort2.Parity = Parity.None;
            _serialPort2.DataBits = 8;
            _serialPort2.StopBits = StopBits.One;
            _serialPort2.Handshake = Handshake.None;

            _serialPort2.ReadTimeout = 500;
            _serialPort2.WriteTimeout = 500;

            try
            {

                Simulator x = new Simulator(_serialPort, _serialPort2);
                this.Hide();
                x.Show();

            }
            catch(Exception ex)
            {

                MessageBox.Show(ex.ToString());

            }
        }
示例#11
0
 private void button2_Click(object sender, EventArgs e)
 {
     Simulator x = new Simulator();
     this.Hide();
     x.Show();
 }
示例#12
0
        public async Task Main(string[] args)
        {
            //for (int i = 1; i < 10; i++)
            //{
            //    ExperimentalConfiguration expConfig1 = new ExperimentalConfiguration();
            //    BlockingAlgorithmOptions blockConfig1 = new BlockingAlgorithmOptions();
            //    blockConfig1.FOR_SIMULATION_ONLY_TURN_ON_SSH_STUPID_MODE = true;
            //    //blockConfig1.BlockThresholdUnpopularPassword = 1 * i;
            //    //blockConfig1.BlockThresholdPopularPassword = blockConfig1.BlockThresholdUnpopularPassword;
            //    //
            //    // Industrial-best-practice baseline
            //    //

            //    // Use the same threshold regardless of the popularity of the account password
            //    blockConfig1.BlockThresholdPopularPassword =
            //        blockConfig1.BlockThresholdUnpopularPassword =1*i;
            //    // Make all failures increase the count towards the threshold by one
            //    blockConfig1.PenaltyForInvalidAccount =
            //        blockConfig1.PenaltyMulitiplierForTypo =
            //        blockConfig1.BasePenaltyForInvalidPassword =
            //        1d;
            //    // If the below is empty, the multiplier for any popularity level will be 1.
            //    blockConfig1.PenaltyForReachingEachPopularityThreshold = new List<PenaltyForReachingAPopularityThreshold>();
            //    // Correct passwords shouldn't help
            //    blockConfig1.RewardForCorrectPasswordPerAccount = 0;

            //    //


            //    expConfig1.TotalLoginAttemptsToIssue = 5000;
            //    expConfig1.RecordUnitAttempts = 5000;
            //    //expConfig1.ChanceOfBenignPasswordTypo = 0.2d;
            //    Simulator simulator = new Simulator(expConfig1, blockConfig1);
            //    Console.WriteLine("Unpopularpassword {0}", blockConfig1.BlockThresholdUnpopularPassword);

            //  //  await simulator.Run(blockConfig1);
            //}

            ulong TotalLoginAttemptsToIssue = 200000;
            ulong RecordUnitAttempts = 200000;
            uint MaliciousIP = 2000;
            //1. Vary BlockThresholdUnpopularPassword from 100 to 2100  (in steps of 200)
            for (int i = 0; i < 11; i++)
            {
                ExperimentalConfiguration expConfig1 = new ExperimentalConfiguration();
                BlockingAlgorithmOptions blockConfig1 = new BlockingAlgorithmOptions();
                //blockConfig1.RewardForCorrectPasswordPerAccount = -10 * i - 10;
                //blockConfig1.PenaltyForInvalidAccount = 1 +  (int)(i/3);
                //blockConfig1.BlockThresholdPopularPassword = 20 + 10 * i;
                //blockConfig1.BlockThresholdUnpopularPassword = 4*blockConfig1.BlockThresholdPopularPassword;
                blockConfig1.BlockThresholdUnpopularPassword = 100 + 200 * i;
                expConfig1.TotalLoginAttemptsToIssue = TotalLoginAttemptsToIssue;
                expConfig1.RecordUnitAttempts = RecordUnitAttempts;
                expConfig1.NumberOfIpAddressesControlledByAttacker = MaliciousIP;
                //blockConfig1.BlockThresholdPopularPassword = 60;
                //blockConfig1.BlockThresholdUnpopularPassword = 900;
                //blockConfig1.PenaltyForInvalidAccount = 35;




                //blockConfig1.PenaltyForReachingEachPopularityThreshold = new List<PenaltyForReachingAPopularityThreshold>
                //{
                //    new PenaltyForReachingAPopularityThreshold { PopularityThreshold = 1d/(100*1000d), Penalty = 10*Math.Pow(2,0.3*i)},
                //    new PenaltyForReachingAPopularityThreshold { PopularityThreshold = 1d/(10*1000d), Penalty = 20*Math.Pow(2,0.3*i)},
                //    new PenaltyForReachingAPopularityThreshold { PopularityThreshold = 1d/(1*1000d), Penalty = 25*Math.Pow(2,0.3*i)},
                //    new PenaltyForReachingAPopularityThreshold { PopularityThreshold = 1d/(100d), Penalty = 30*Math.Pow(2,0.3*i)},
                //};
                Simulator simulator = new Simulator(expConfig1, blockConfig1);
                Console.WriteLine("unpopularpassword {0}", blockConfig1.BlockThresholdUnpopularPassword);

                await simulator.Run(blockConfig1, "BlockThresholdUnpopularPassword");
            }

            //2. Vary blockthresholdpopularpassword from 20 - 120 and unpopularpassword is 4 times



            for (int i = 0; i < 10; i++)
            {
                ExperimentalConfiguration expConfig1 = new ExperimentalConfiguration();
                BlockingAlgorithmOptions blockConfig1 = new BlockingAlgorithmOptions();
                //blockConfig1.RewardForCorrectPasswordPerAccount = -10 * i - 10;
                //blockConfig1.PenaltyForInvalidAccount = 1 +  (int)(i/3);
                blockConfig1.BlockThresholdPopularPassword = 20 + 10 * i;
                blockConfig1.BlockThresholdUnpopularPassword = 4 * blockConfig1.BlockThresholdPopularPassword;
                //blockConfig1.BlockThresholdUnpopularPassword = 100 + 200 * i;
                expConfig1.TotalLoginAttemptsToIssue = TotalLoginAttemptsToIssue;
                expConfig1.RecordUnitAttempts = RecordUnitAttempts;
                expConfig1.NumberOfIpAddressesControlledByAttacker = 100;
                //blockConfig1.BlockThresholdPopularPassword = 60;
                //blockConfig1.BlockThresholdUnpopularPassword = 900;
                //blockConfig1.PenaltyForInvalidAccount = 35;




                //blockConfig1.PenaltyForReachingEachPopularityThreshold = new List<PenaltyForReachingAPopularityThreshold>
                //{
                //    new PenaltyForReachingAPopularityThreshold { PopularityThreshold = 1d/(100*1000d), Penalty = 10*Math.Pow(2,0.3*i)},
                //    new PenaltyForReachingAPopularityThreshold { PopularityThreshold = 1d/(10*1000d), Penalty = 20*Math.Pow(2,0.3*i)},
                //    new PenaltyForReachingAPopularityThreshold { PopularityThreshold = 1d/(1*1000d), Penalty = 25*Math.Pow(2,0.3*i)},
                //    new PenaltyForReachingAPopularityThreshold { PopularityThreshold = 1d/(100d), Penalty = 30*Math.Pow(2,0.3*i)},
                //};
                Simulator simulator = new Simulator(expConfig1, blockConfig1);
                Console.WriteLine("Popularpassword {0}", blockConfig1.BlockThresholdPopularPassword);

                await simulator.Run(blockConfig1, "BlockThresholdPopularPassword");
            }

            //3.Vary PenaltyForInvalidAccount from 1 to 10 (in steps of 1)
            for (int i = 0; i < 10; i++)
            {
                ExperimentalConfiguration expConfig1 = new ExperimentalConfiguration();
                BlockingAlgorithmOptions blockConfig1 = new BlockingAlgorithmOptions();
                //blockConfig1.RewardForCorrectPasswordPerAccount = -10 * i - 10;
                blockConfig1.PenaltyForInvalidAccount = 1 + i;
                //blockConfig1.BlockThresholdPopularPassword = 20 + 10 * i;
                //blockConfig1.BlockThresholdUnpopularPassword = 4 * blockConfig1.BlockThresholdPopularPassword;
                //blockConfig1.BlockThresholdUnpopularPassword = 100 + 200 * i;
                expConfig1.TotalLoginAttemptsToIssue = TotalLoginAttemptsToIssue;
                expConfig1.RecordUnitAttempts = RecordUnitAttempts;
                expConfig1.NumberOfIpAddressesControlledByAttacker = MaliciousIP;
                //blockConfig1.BlockThresholdPopularPassword = 60;
                //blockConfig1.BlockThresholdUnpopularPassword = 900;
                //blockConfig1.PenaltyForInvalidAccount = 35;





                //blockConfig1.PenaltyForReachingEachPopularityThreshold = new List<PenaltyForReachingAPopularityThreshold>
                //{
                //    new PenaltyForReachingAPopularityThreshold { PopularityThreshold = 1d/(100*1000d), Penalty = 10*Math.Pow(2,0.3*i)},
                //    new PenaltyForReachingAPopularityThreshold { PopularityThreshold = 1d/(10*1000d), Penalty = 20*Math.Pow(2,0.3*i)},
                //    new PenaltyForReachingAPopularityThreshold { PopularityThreshold = 1d/(1*1000d), Penalty = 25*Math.Pow(2,0.3*i)},
                //    new PenaltyForReachingAPopularityThreshold { PopularityThreshold = 1d/(100d), Penalty = 30*Math.Pow(2,0.3*i)},
                //};
                Simulator simulator = new Simulator(expConfig1, blockConfig1);
                Console.WriteLine("PenaltyForInvalidAccount {0}", blockConfig1.PenaltyForInvalidAccount);

                await simulator.Run(blockConfig1, "PenaltyForInvalidAccount");
            }
            //4.Vary RewardForCorrectPasswordPerAccount from -10 to -100 
            for (int i = 0; i < 10; i++)
            {
                ExperimentalConfiguration expConfig1 = new ExperimentalConfiguration();
                BlockingAlgorithmOptions blockConfig1 = new BlockingAlgorithmOptions();
                blockConfig1.RewardForCorrectPasswordPerAccount = -10 * i - 10;
                //blockConfig1.PenaltyForInvalidAccount = 1 +  (int)(i/3);
                // blockConfig1.BlockThresholdPopularPassword = 20 + 10 * i;
                //blockConfig1.BlockThresholdUnpopularPassword = 4 * blockConfig1.BlockThresholdPopularPassword;
                //blockConfig1.BlockThresholdUnpopularPassword = 100 + 200 * i;
                expConfig1.TotalLoginAttemptsToIssue = TotalLoginAttemptsToIssue;
                expConfig1.RecordUnitAttempts = RecordUnitAttempts;
                expConfig1.NumberOfIpAddressesControlledByAttacker = MaliciousIP;
                //blockConfig1.BlockThresholdPopularPassword = 60;
                //blockConfig1.BlockThresholdUnpopularPassword = 900;
                //blockConfig1.PenaltyForInvalidAccount = 35;




                //blockConfig1.PenaltyForReachingEachPopularityThreshold = new List<PenaltyForReachingAPopularityThreshold>
                //{
                //    new PenaltyForReachingAPopularityThreshold { PopularityThreshold = 1d/(100*1000d), Penalty = 10*Math.Pow(2,0.3*i)},
                //    new PenaltyForReachingAPopularityThreshold { PopularityThreshold = 1d/(10*1000d), Penalty = 20*Math.Pow(2,0.3*i)},
                //    new PenaltyForReachingAPopularityThreshold { PopularityThreshold = 1d/(1*1000d), Penalty = 25*Math.Pow(2,0.3*i)},
                //    new PenaltyForReachingAPopularityThreshold { PopularityThreshold = 1d/(100d), Penalty = 30*Math.Pow(2,0.3*i)},
                //};
                Simulator simulator = new Simulator(expConfig1, blockConfig1);
                Console.WriteLine("RewardForCorrectPasswordPerAccount {0}", blockConfig1.RewardForCorrectPasswordPerAccount);

                await simulator.Run(blockConfig1, "RewardForCorrectPasswordPerAccount");
            }



            //5.PenaltyForReachingEachPopularityThreshold multiply each by 2 ^{ 0.3 * k} k0-10



            for (int i = 0; i < 11; i++)
            {
                ExperimentalConfiguration expConfig1 = new ExperimentalConfiguration();
                BlockingAlgorithmOptions blockConfig1 = new BlockingAlgorithmOptions();
                //blockConfig1.RewardForCorrectPasswordPerAccount = -10 * i - 10;
                //blockConfig1.PenaltyForInvalidAccount = 1 +  (int)(i/3);
                // blockConfig1.BlockThresholdPopularPassword = 20 + 10 * i;
                //blockConfig1.BlockThresholdUnpopularPassword = 4 * blockConfig1.BlockThresholdPopularPassword;
                //blockConfig1.BlockThresholdUnpopularPassword = 100 + 200 * i;
                expConfig1.TotalLoginAttemptsToIssue = TotalLoginAttemptsToIssue;
                expConfig1.RecordUnitAttempts = RecordUnitAttempts;
                expConfig1.NumberOfIpAddressesControlledByAttacker = MaliciousIP;
                //blockConfig1.BlockThresholdPopularPassword = 60;
                //blockConfig1.BlockThresholdUnpopularPassword = 900;
                //blockConfig1.PenaltyForInvalidAccount = 35;




                blockConfig1.PenaltyForReachingEachPopularityThreshold = new List<PenaltyForReachingAPopularityThreshold>
                {
                    new PenaltyForReachingAPopularityThreshold { PopularityThreshold = 1d/(100*1000d), Penalty = 10*Math.Pow(2,0.3*i)},
                    new PenaltyForReachingAPopularityThreshold { PopularityThreshold = 1d/(10*1000d), Penalty = 20*Math.Pow(2,0.3*i)},
                    new PenaltyForReachingAPopularityThreshold { PopularityThreshold = 1d/(1*1000d), Penalty = 25*Math.Pow(2,0.3*i)},
                    new PenaltyForReachingAPopularityThreshold { PopularityThreshold = 1d/(100d), Penalty = 30*Math.Pow(2,0.3*i)},
                };
                Simulator simulator = new Simulator(expConfig1, blockConfig1);
                Console.WriteLine("PenaltyForReachingEachPopularityThreshold{0}", blockConfig1.PenaltyForReachingEachPopularityThreshold);

                await simulator.Run(blockConfig1, "PenaltyForReachingEachPopularityThreshold");
            }










            //ExperimentalConfiguration expConfig = new ExperimentalConfiguration();
            //BlockingAlgorithmOptions blockConfig = new BlockingAlgorithmOptions();
            //Simulator simulator = new Simulator(expConfig, blockConfig);
            //await simulator.Run();
        }
        public void UpdateSimulatorState(Simulator simulator, SimIpHistory ipHistory)
        {
            IsRepeatFailure = !IsPasswordValid && (
                (SimAccount == null)
                    ? simulator._recentIncorrectPasswords.AddMember(UserNameOrAccountId + "\n" + Password)
                    : simulator._userAccountController.AddIncorrectPhaseTwoHash(SimAccount, Password, TimeOfAttemptUtc)
            );

            int passwordsHeightOnBinomialLadder = (IsPasswordValid || IsRepeatFailure)
                ? simulator._binomialLadderFilter.GetHeight(Password)
                : simulator._binomialLadderFilter.Step(Password);

            IsFrequentlyGuessedPassword = passwordsHeightOnBinomialLadder >=
                                          simulator._experimentalConfiguration.BlockingOptions.BinomialLadderFrequencyThreshdold_T;

            DeviceCookieHadPriorSuccessfulLoginForThisAccount = SimAccount != null &&
                simulator._userAccountController.HasClientWithThisHashedCookieSuccessfullyLoggedInBefore(SimAccount, CookieProvidedByBrowser);

            if (SimAccount != null && IsPasswordValid)
            {
                // Determine if any of the outcomes for login attempts from the client IP for this request were the result of typos,
                // as this might impact our decision about whether or not to block this client IP in response to its past behaviors.
                ipHistory.AdjustBlockingScoreForPastTyposTreatedAsFullFailures(simulator, SimAccount, TimeOfAttemptUtc,
                    Password);
                simulator._userAccountController.RecordHashOfDeviceCookieUsedDuringSuccessfulLoginBackground(
                    SimAccount, CookieProvidedByBrowser, TimeOfAttemptUtc);
                // Clear the count of consecutive failures
                SimAccount.ConsecutiveIncorrectAttempts.SetValue(0, this.TimeOfAttemptUtc);
            }
            else if (SimAccount != null && !IsRepeatFailure)
            {
                // Add the the account's consecutive failure count
                SimAccount.ConsecutiveIncorrectAttempts.AddInPlace(
                    simulator._experimentalConfiguration.BlockingOptions.BlockScoreHalfLife, 1d,
                    this.TimeOfAttemptUtc);
                // Increase the max consecutive faiulre count if the current consecutive failure count exceeds it
                if (SimAccount.ConsecutiveIncorrectAttempts.GetValue(
                        simulator._experimentalConfiguration.BlockingOptions.BlockScoreHalfLife)
                    >
                    SimAccount.MaxConsecutiveIncorrectAttempts.GetValue(
                        simulator._experimentalConfiguration.BlockingOptions.BlockScoreHalfLife))
                    SimAccount.MaxConsecutiveIncorrectAttempts.SetValue(SimAccount.ConsecutiveIncorrectAttempts);
            }

            if (!IsPasswordValid && !IsRepeatFailure && SimAccount != null)
            {
                // This attempt is a non-repeat failure and could be a typo.  Store it in the ste of potential typos.
                ipHistory.RecentPotentialTypos.Add(new SimLoginAttemptSummaryForTypoAnalysis()
                {
                    WhenUtc = TimeOfAttemptUtc,
                    Password = Password,
                    UsernameOrAccountId = UserNameOrAccountId,
                    WasPasswordFrequent = IsFrequentlyGuessedPassword
                });
            }


            DecayingDouble decayingOneFromThisInstant = new DecayingDouble(1, TimeOfAttemptUtc);
            TimeSpan halfLife = simulator._experimentalConfiguration.BlockingOptions.BlockScoreHalfLife;
            if (IsPasswordValid)
            {
                ipHistory.SuccessfulLogins.AddInPlace(halfLife, decayingOneFromThisInstant);
            } else if (SimAccount == null)
            {
                if (IsRepeatFailure)
                {
                    if (IsFrequentlyGuessedPassword)
                        ipHistory.RepeatAccountFailuresFrequentPassword.AddInPlace(halfLife, decayingOneFromThisInstant);
                    else
                        ipHistory.RepeatAccountFailuresInfrequentPassword.AddInPlace(halfLife, decayingOneFromThisInstant);
                }
                else
                {
                    if (IsFrequentlyGuessedPassword)
                        ipHistory.AccountFailuresFrequentPassword.AddInPlace(halfLife, decayingOneFromThisInstant);
                    else
                        ipHistory.AccountFailuresInfrequentPassword.AddInPlace(halfLife, decayingOneFromThisInstant);
                }
            }
            else
            {
                if (IsRepeatFailure)
                {
                    if (IsFrequentlyGuessedPassword)
                        ipHistory.RepeatPasswordFailuresNoTypoFrequentPassword.AddInPlace(halfLife, decayingOneFromThisInstant);
                    else
                        ipHistory.RepeatPasswordFailuresNoTypoInfrequentPassword.AddInPlace(halfLife, decayingOneFromThisInstant);
                }
                else
                {
                    if (IsFrequentlyGuessedPassword)
                        ipHistory.PasswordFailuresNoTypoFrequentPassword.AddInPlace(halfLife, decayingOneFromThisInstant);
                    else
                        ipHistory.PasswordFailuresNoTypoInfrequentPassword.AddInPlace(halfLife, decayingOneFromThisInstant);
                }
            }

        }
示例#14
0
        public void UpdateSimulatorState(Simulator simulator, SimIpHistory ipHistory)
        {
            IsRepeatFailure = !IsPasswordValid && (
                (SimAccount == null)
                    ? simulator._recentIncorrectPasswords.AddMember(UserNameOrAccountId + "\n" + Password)
                    : simulator._userAccountController.AddIncorrectPhaseTwoHash(SimAccount, Password, TimeOfAttemptUtc)
                );

            int passwordsHeightOnBinomialLadder = (IsPasswordValid || IsRepeatFailure)
                ? simulator._binomialLadderFilter.GetHeight(Password)
                : simulator._binomialLadderFilter.Step(Password);

            IsFrequentlyGuessedPassword = passwordsHeightOnBinomialLadder >=
                                          simulator._experimentalConfiguration.BlockingOptions.BinomialLadderFrequencyThreshdold_T;

            DeviceCookieHadPriorSuccessfulLoginForThisAccount = SimAccount != null &&
                                                                simulator._userAccountController.HasClientWithThisHashedCookieSuccessfullyLoggedInBefore(SimAccount, CookieProvidedByBrowser);

            if (SimAccount != null && IsPasswordValid)
            {
                // Determine if any of the outcomes for login attempts from the client IP for this request were the result of typos,
                // as this might impact our decision about whether or not to block this client IP in response to its past behaviors.
                ipHistory.AdjustBlockingScoreForPastTyposTreatedAsFullFailures(simulator, SimAccount, TimeOfAttemptUtc,
                                                                               Password);
                simulator._userAccountController.RecordHashOfDeviceCookieUsedDuringSuccessfulLoginBackground(
                    SimAccount, CookieProvidedByBrowser, TimeOfAttemptUtc);
                // Clear the count of consecutive failures
                SimAccount.ConsecutiveIncorrectAttempts.SetValue(0, this.TimeOfAttemptUtc);
            }
            else if (SimAccount != null && !IsRepeatFailure)
            {
                // Add the the account's consecutive failure count
                SimAccount.ConsecutiveIncorrectAttempts.AddInPlace(
                    simulator._experimentalConfiguration.BlockingOptions.BlockScoreHalfLife, 1d,
                    this.TimeOfAttemptUtc);
                // Increase the max consecutive faiulre count if the current consecutive failure count exceeds it
                if (SimAccount.ConsecutiveIncorrectAttempts.GetValue(
                        simulator._experimentalConfiguration.BlockingOptions.BlockScoreHalfLife)
                    >
                    SimAccount.MaxConsecutiveIncorrectAttempts.GetValue(
                        simulator._experimentalConfiguration.BlockingOptions.BlockScoreHalfLife))
                {
                    SimAccount.MaxConsecutiveIncorrectAttempts.SetValue(SimAccount.ConsecutiveIncorrectAttempts);
                }
            }

            if (!IsPasswordValid && !IsRepeatFailure && SimAccount != null)
            {
                // This attempt is a non-repeat failure and could be a typo.  Store it in the ste of potential typos.
                ipHistory.RecentPotentialTypos.Add(new SimLoginAttemptSummaryForTypoAnalysis()
                {
                    WhenUtc             = TimeOfAttemptUtc,
                    Password            = Password,
                    UsernameOrAccountId = UserNameOrAccountId,
                    WasPasswordFrequent = IsFrequentlyGuessedPassword
                });
            }


            DecayingDouble decayingOneFromThisInstant = new DecayingDouble(1, TimeOfAttemptUtc);
            TimeSpan       halfLife = simulator._experimentalConfiguration.BlockingOptions.BlockScoreHalfLife;

            if (IsPasswordValid)
            {
                ipHistory.SuccessfulLogins.AddInPlace(halfLife, decayingOneFromThisInstant);
            }
            else if (SimAccount == null)
            {
                if (IsRepeatFailure)
                {
                    if (IsFrequentlyGuessedPassword)
                    {
                        ipHistory.RepeatAccountFailuresFrequentPassword.AddInPlace(halfLife, decayingOneFromThisInstant);
                    }
                    else
                    {
                        ipHistory.RepeatAccountFailuresInfrequentPassword.AddInPlace(halfLife, decayingOneFromThisInstant);
                    }
                }
                else
                {
                    if (IsFrequentlyGuessedPassword)
                    {
                        ipHistory.AccountFailuresFrequentPassword.AddInPlace(halfLife, decayingOneFromThisInstant);
                    }
                    else
                    {
                        ipHistory.AccountFailuresInfrequentPassword.AddInPlace(halfLife, decayingOneFromThisInstant);
                    }
                }
            }
            else
            {
                if (IsRepeatFailure)
                {
                    if (IsFrequentlyGuessedPassword)
                    {
                        ipHistory.RepeatPasswordFailuresNoTypoFrequentPassword.AddInPlace(halfLife, decayingOneFromThisInstant);
                    }
                    else
                    {
                        ipHistory.RepeatPasswordFailuresNoTypoInfrequentPassword.AddInPlace(halfLife, decayingOneFromThisInstant);
                    }
                }
                else
                {
                    if (IsFrequentlyGuessedPassword)
                    {
                        ipHistory.PasswordFailuresNoTypoFrequentPassword.AddInPlace(halfLife, decayingOneFromThisInstant);
                    }
                    else
                    {
                        ipHistory.PasswordFailuresNoTypoInfrequentPassword.AddInPlace(halfLife, decayingOneFromThisInstant);
                    }
                }
            }
        }