Пример #1
0
        private void Form1_Load(object sender, EventArgs e)
        {
            loadMap();
            mapCacher = new ArrayMapCacher(map.GetLength(0), map.GetLength(1), map);
            camera    = new Camera(map, entities, this, mapCacher);

            WindowState    = FormWindowState.Maximized;
            DoubleBuffered = true;

            Bitmap playerSprite;

            //playerSprite = new Bitmap(Bitmap.FromFile(@""));
            playerSprite = createBox(100, 100, Color.Black);
            player       = new Player(playerSprite, 60, 200);
            entities.Add(player);

            keyManager = new KeysManager(player);

            gameLoop          = new Timer();
            gameLoop.Interval = 10;
            gameLoop.Tick    += GameLoop_Tick;
            gameLoop.Start();



            keyManager.registerKeybind(Keys.F, new SaveKeybind(mapLoader));
            keyManager.registerKeybind(Keys.R, new NewMapKeybind(mapLoader, this));
        }
Пример #2
0
        private void createServer()
        {
            AES.getInstance();
            RSA rsa = new RSA("Server");

            KeysManager.generateAESKey();
            KeysManager.generateRSAPublicKey(rsa.rsaSP);
            KeysManager.generateRSAPrivateKey(rsa.rsaSP);

            server = new ServerObject(IP, HOST);

            server.logger = Log;
            server.intiServer();

            server.startServer();
            Log("Server Generated AES Public Key", Convert.ToBase64String(KeysManager.AESkey));
            Log("Server Generated RSA Public Key", KeysManager.RSAPublicKey);
            Log();


            server.respose = (s) => {
                string requstType = s.ReadString();
                ResposesManager.ProcessRequst(requstType, s, this);
            };
        }
Пример #3
0
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            Window.AllowUserResizing = true;
            IsMouseVisible           = true;

            // TODO: Add your initialization logic here
            base.Initialize();

            int genEnd = map.GetLength(0);

            loadMap();
            DiamondSquareTerrainGenerator terrainGenerator = new DiamondSquareTerrainGenerator(10, new Random());

            terrainGenerator.generate(map, 0, genEnd);

            GrassTerrainGenerator grassTerrainGenerator = new GrassTerrainGenerator();

            grassTerrainGenerator.generate(map, 0, genEnd);

            //mapCacher = new ArrayMapCacher(map.GetLength(0), map.GetLength(1), map);
            player = new Player(playerSprite, new Vector2(60, 200));
            entities.Add(player);

            keyManager = new KeysManager(player);


            keyManager.registerKeybind(Keys.F, new SaveKeybind(mapLoader));
            keyManager.registerKeybind(Keys.R, new NewMapKeybind(mapLoader, this));

            //spawnSnake();

            camera = new Camera(map, entities, this, new ArrayMapCacher(), GraphicsDevice, spriteBatch, player, graphics, tileTextureMap, frameCounter, spriteFont);
        }
 /// <summary>
 /// CheckPin method inplementation
 /// </summary>
 private bool CheckPin(AuthenticationContext usercontext, int pin)
 {
     foreach (HashMode algo in Enum.GetValues(typeof(HashMode)))
     {
         if (algo <= Algorithm)
         {
             if (TOTPShadows <= 0)
             {
                 if (!KeysManager.ValidateKey(usercontext.UPN))
                 {
                     throw new CryptographicException(string.Format("SECURTY ERROR : Invalid Key for User {0}", usercontext.UPN));
                 }
                 byte[]   encodedkey = KeysManager.ProbeKey(usercontext.UPN);
                 DateTime call       = DateTime.UtcNow;
                 TOTP     gen        = new TOTP(encodedkey, usercontext.UPN, call, algo, this.Duration, this.Digits); // eg : TOTP code
                 gen.Compute(call);
                 return(pin == gen.OTP);
             }
             else
             {   // Current TOTP
                 if (!KeysManager.ValidateKey(usercontext.UPN))
                 {
                     throw new CryptographicException(string.Format("SECURTY ERROR : Invalid Key for User {0}", usercontext.UPN));
                 }
                 byte[]   encodedkey = KeysManager.ProbeKey(usercontext.UPN);
                 DateTime tcall      = DateTime.UtcNow;
                 TOTP     gen        = new TOTP(encodedkey, usercontext.UPN, tcall, algo, this.Duration, this.Digits); // eg : TOTP code
                 gen.Compute(tcall);
                 if (pin == gen.OTP)
                 {
                     return(true);
                 }
                 // TOTP with Shadow (current - x latest)
                 for (int i = 1; i <= TOTPShadows; i++)
                 {
                     DateTime call = tcall.AddSeconds(-(i * this.Duration));
                     TOTP     gen2 = new TOTP(encodedkey, usercontext.UPN, call, algo, this.Duration, this.Digits); // eg : TOTP code
                     gen2.Compute(call);
                     if (pin == gen2.OTP)
                     {
                         return(true);
                     }
                 }
                 // TOTP with Shadow (current + x latest) - not possible. but can be usefull if time sync is not adequate
                 for (int i = 1; i <= TOTPShadows; i++)
                 {
                     DateTime call = tcall.AddSeconds(i * this.Duration);
                     TOTP     gen3 = new TOTP(encodedkey, usercontext.UPN, call, algo, this.Duration, this.Digits); // eg : TOTP code
                     gen3.Compute(call);
                     if (pin == gen3.OTP)
                     {
                         return(true);
                     }
                 }
             }
         }
     }
     return(false);
 }
Пример #5
0
        public FlatFileKeyRepository(IOptions <Config> config, ILogger <FlatFileKeyRepository> logger)
        {
            _config = config;
            _logger = logger;
            var seed = _config.Value.GetSeed().GetAwaiter().GetResult();

            _keysManager = new KeysManager(seed, DateTime.UtcNow);
            _logger.LogInformation($"Our nodeid is {GetNodeSecret().PubKey.ToHex()}");
        }
Пример #6
0
        private void SetUserSettings()
        {
            //MAIN AES
            if (!string.IsNullOrEmpty(MAesTextBox.Text))
            {
                if (MAesTextBox.Text.StartsWith("0x"))
                {
                    FProp.Default.FPak_MainAES = Regex.Replace(MAesTextBox.Text.Substring(2).ToUpper(), @"\s+", string.Empty);
                }
                else
                {
                    FProp.Default.FPak_MainAES = Regex.Replace(MAesTextBox.Text.ToUpper(), @"\s+", string.Empty);
                }
            }
            else
            {
                FProp.Default.FPak_MainAES = string.Empty;
            }
            DebugHelper.WriteLine($"AESManager SET: Main PAKs with key: {MAesTextBox.Text}");

            //DYNAMIC AESs
            AESEntries.AESEntriesList = new List <AESInfosEntry>();
            if (PAKEntries.PAKEntriesList != null && PAKEntries.PAKEntriesList.Any())
            {
                foreach (PAKInfosEntry Pak in PAKEntries.PAKEntriesList.Where(x => x.bTheDynamicPAK))
                {
                    TextBox PakTextBox = UIHelper.FindChild <TextBox>(this, $"TxtBox_{Regex.Match(Path.GetFileNameWithoutExtension(Pak.ThePAKPath), @"\d+").Value}");
                    if (!string.IsNullOrEmpty(PakTextBox.Text))
                    {
                        if (PakTextBox.Text.StartsWith("0x"))
                        {
                            KeysManager.Serialize(Path.GetFileNameWithoutExtension(Pak.ThePAKPath), Regex.Replace(PakTextBox.Text.Substring(2).ToUpper(), @"\s+", string.Empty));
                        }
                        else
                        {
                            KeysManager.Serialize(Path.GetFileNameWithoutExtension(Pak.ThePAKPath), Regex.Replace(PakTextBox.Text.ToUpper(), @"\s+", string.Empty));
                        }
                    }
                    else
                    {
                        KeysManager.Serialize(Path.GetFileNameWithoutExtension(Pak.ThePAKPath), string.Empty);
                    }
                    DebugHelper.WriteLine($"AESManager SET: {Pak.ThePAKPath} with key: {PakTextBox.Text}");
                }

                Directory.CreateDirectory(Path.GetDirectoryName(AESManager_PATH));
                using (var fileStream = new FileStream(AESManager_PATH, FileMode.Create))
                {
                    KeysManager.serializer.Serialize(fileStream, AESEntries.AESEntriesList);
                }
            }

            //SAVE
            FProp.Default.Save();
            DebugHelper.WriteLine($"AESManager: Saved");
        }
 /// <summary>
 /// newkeyBtn_Click event
 /// </summary>
 private void newkeyBtn_Click(object sender, EventArgs e)
 {
     KeysManager.NewKey(_upn);
     _secretkey              = KeysManager.EncodedKey(_upn);
     this.DisplayKey.Text    = _secretkey;
     this.qrCodeGraphic.Text = ManagementAdminService.GetQRCodeValue(_upn, this.DisplayKey.Text);
     if (!SyncDisabled)
     {
         userPropertyPage.SyncSharedUserData(this, true);
     }
 }
Пример #8
0
 public static void setKey(string key, string newValue)
 {
     try
     {
         KeysManager.setKey(key, newValue);
     }
     catch (System.Exception ex)
     {
         NttDataWA.UIManager.AdministrationManager.DiagnosticError(ex);
     }
 }
Пример #9
0
 public override void Handle()
 {
     while (Main.IsAlive)
     {
         GameFiber.Yield();
         if (KeysManager.IsKeyDownComputerCheck(Configuration.Instance.ReadKey(K_OPEN_MENU, "F5")) && !UICustomMenuManager.MenuPool.IsAnyMenuOpen() && this.CanCreateTicket())
         {
             Menu.Visible = !Menu.Visible;
         }
         UICustomMenuManager.MenuPool.ProcessMenus();
     }
 }
Пример #10
0
 public static string getKey(string key, string defaultValue)
 {
     try
     {
         return(KeysManager.getKey(key, defaultValue));
     }
     catch (System.Exception ex)
     {
         NttDataWA.UIManager.AdministrationManager.DiagnosticError(ex);
         return(null);
     }
 }
        /// <summary>
        /// BTNReinit_Click event
        /// </summary>
        private void BTNReinit_Click(object sender, EventArgs e)
        {
            MMCRegistrationList lst = userPropertyPage.GetSharedUserData();

            foreach (MMCRegistration reg in lst)
            {
                KeysManager.NewKey(reg.UPN);
            }
            if (!SyncDisabled)
            {
                userPropertyPage.SyncSharedUserData(this, true);
            }
        }
Пример #12
0
        private ChannelManager GetTestChannelManager()
        {
            var logger              = new TestLogger();
            var broadcaster         = new TestBroadcaster();
            var feeEstiamtor        = new TestFeeEstimator();
            var n                   = NBitcoin.Network.TestNet;
            var chainWatchInterface = new ChainWatchInterfaceUtil(n);
            var keySeed             = new byte[] { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 };
            var keysInterface       = new KeysManager(keySeed, DateTime.UnixEpoch);
            var channelManager      = ChannelManager.Create(n, in TestUserConfig.Default, chainWatchInterface, keysInterface, logger, broadcaster, feeEstiamtor, 400000);

            return(channelManager);
        }
        public TestPeerManagerProvider(IBroadcaster broadcaster, IFeeEstimator feeEstimator, IChainWatchInterface chainWatchInterface, IOptions <Config> config, ILoggerFactory loggerFactory, IKeysRepository keysRepository)
        {
            _broadcaster         = broadcaster;
            _feeEstimator        = feeEstimator;
            _chainWatchInterface = chainWatchInterface;
            var seed          = new byte[32];
            var n             = NBitcoin.Network.RegTest;
            var conf          = config.Value.RustLightningConfig;
            var logger        = new NativeLogger(loggerFactory.CreateLogger <NativeLogger>());
            var keysInterface = new KeysManager(seed, DateTime.UnixEpoch);

            _peerManager =
                PeerManager.Create(seed.AsSpan(), n, conf, chainWatchInterface, keysInterface, broadcaster, logger, feeEstimator, 100);
        }
Пример #14
0
 private void OnTriggerEnter(Collider other)
 {
     if (KeysManager.CheckKeys())
     {
         SoundManager.PlaySound("UseEndGameChest", 1f);
         SceneManager.LoadScene(6);
         Debug.Log("The player has all the keys, the game ends");
         //End game
     }
     else
     {
         Debug.Log("Some keys are missing, cannot end the game");
     }
 }
 public override void Handle()
 {
     while (Main.IsAlive)
     {
         GameFiber.Yield();
         if (KeysManager.IsKeyCombinationDownComputerCheck(
                 Configuration.Instance.ReadKey(K_CUSTOM_LOC, "W"), // CTRL + W by default
                 Configuration.Instance.ReadKey(K_CUSTOM_LOC_MOD, "LControlKey")
                 ) &&
             false == IsAlreadyFollowing)
         {
             this.OnSetCustomLocation();
         }
     }
 }
Пример #16
0
        private void AddLblTxtForDynamicPAKs()
        {
            if (PAKEntries.PAKEntriesList != null && PAKEntries.PAKEntriesList.Any())
            {
                if (AESEntries.AESEntriesList == null)
                {
                    KeysManager.Deserialize();
                }
                int yPos = 4;

                foreach (PAKInfosEntry Pak in PAKEntries.PAKEntriesList.Where(x => x.bTheDynamicPAK))
                {
                    Label PakLabel = new Label
                    {
                        Content             = Path.GetFileNameWithoutExtension(Pak.ThePAKPath),
                        HorizontalAlignment = HorizontalAlignment.Left,
                        Margin            = new Thickness(2, yPos - 2, 0, 0),
                        VerticalAlignment = VerticalAlignment.Top,
                        Foreground        = new SolidColorBrush(Color.FromRgb(239, 239, 239))
                    };

                    TextBox PakTextBox = new TextBox
                    {
                        Height            = 19,
                        TextWrapping      = TextWrapping.NoWrap,
                        AcceptsReturn     = false,
                        Margin            = new Thickness(160, yPos, 5, 0),
                        VerticalAlignment = VerticalAlignment.Top,
                        Foreground        = new SolidColorBrush(Color.FromRgb(239, 239, 239)),
                        Name = $"TxtBox_{Regex.Match(Path.GetFileNameWithoutExtension(Pak.ThePAKPath), @"\d+").Value}"
                    };

                    string PAKKeyFromXML = string.Empty;
                    if (AESEntries.AESEntriesList != null && AESEntries.AESEntriesList.Any())
                    {
                        PAKKeyFromXML   = AESEntries.AESEntriesList.Where(x => string.Equals(x.ThePAKName, Path.GetFileNameWithoutExtension(Pak.ThePAKPath))).Select(x => x.ThePAKKey).FirstOrDefault();
                        PakTextBox.Text = $"0x{PAKKeyFromXML}";
                    }

                    yPos += 28;
                    Grid_DynamicKeys.Children.Add(PakLabel);
                    Grid_DynamicKeys.Children.Add(PakTextBox);

                    DebugHelper.WriteLine($"AESManager GET: {Pak.ThePAKPath} with key: {PAKKeyFromXML}");
                }
            }
        }
Пример #17
0
        /// <summary>
        /// KeyDataEvent method implementation
        /// </summary>
        internal void KeyDataEvent(string user, KeysDataManagerEventKind kind)
        {
            switch (kind)
            {
            case KeysDataManagerEventKind.add:
                KeysManager.NewKey(user);
                break;

            case KeysDataManagerEventKind.Get:
                KeysManager.ReadKey(user);
                break;

            case KeysDataManagerEventKind.Remove:
                KeysManager.RemoveKey(user);
                break;
            }
        }
Пример #18
0
        private (ChannelManager, ChannelManagerReadArgs, ManyChannelMonitor, ManyChannelMonitorReadArgs) GetTestChannelManager()
        {
            var logger              = new TestLogger();
            var broadcaster         = new TestBroadcaster();
            var feeEstiamtor        = new TestFeeEstimator();
            var n                   = Network.TestNet;
            var chainWatchInterface = new ChainWatchInterfaceUtil(n);
            var keySeed             = new byte[] { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 };
            var keysInterface       = new KeysManager(keySeed, DateTime.UnixEpoch);
            var manyChannelMonitor  = ManyChannelMonitor.Create(n, chainWatchInterface, broadcaster, logger, feeEstiamtor);
            var userConfig          = new UserConfigObject();
            var channelManager      = ChannelManager.Create(n, userConfig, chainWatchInterface, keysInterface, logger, broadcaster, feeEstiamtor, 400000, manyChannelMonitor);
            var readArgs            = new ChannelManagerReadArgs(keysInterface, broadcaster, feeEstiamtor, logger, chainWatchInterface, n, manyChannelMonitor);
            var monitorReadArgs     = new ManyChannelMonitorReadArgs(chainWatchInterface, broadcaster, logger, feeEstiamtor, n);

            return(channelManager, readArgs, manyChannelMonitor, monitorReadArgs);
        }
Пример #19
0
        public static PeerManager getTestPeerManager()
        {
            var logger       = new TestLogger();
            var broadcaster  = new TestBroadcaster();
            var feeEstiamtor = new TestFeeEstimator();
            var n            = NBitcoin.Network.TestNet;

            var chainWatchInterface = new ChainWatchInterfaceUtil(n);
            var seed          = new byte[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
            var keysInterface = new KeysManager(seed, DateTime.UnixEpoch);
            var peerManager   =
                PeerManager.Create(
                    seed, n, in TestUserConfig.Default, chainWatchInterface, keysInterface, broadcaster, logger, feeEstiamtor, 400000
                    );

            return(peerManager);
        }
        /// <summary>
        /// AddUser method implmentation
        /// </summary>
        public static MMCRegistrationList AddUser(MMCRegistrationList registrations)
        {
            EnsureService();
            IAdministrationService svc = null;
            if (!Config.UseActiveDirectory)
                svc = new SQLAdminService(Config);
            else
                svc = new ADDSAdminService(Config);

            MMCRegistrationList lst = new MMCRegistrationList();
            foreach(MMCRegistration reg in registrations)
            {
                KeysManager.NewKey(reg.UPN);
                MMCRegistration ret = svc.AddUserRegistration(reg);
                lst.Add(ret);
            }
            return lst;
        }
        /// <summary>
        /// DeleteUser method implmentation
        /// </summary>
        public static bool DeleteUser(MMCRegistrationList registrations)
        {
            EnsureService();
            bool _ret = true;
            IAdministrationService svc = null;
            if (!Config.UseActiveDirectory)
                svc = new SQLAdminService(Config);
            else
                svc = new ADDSAdminService(Config);

            foreach(MMCRegistration reg in registrations)
            {
                bool ret = svc.DeleteUserRegistration(reg);
                if (!ret)
                    _ret = false;
                KeysManager.RemoveKey(reg.UPN);
            }
            return _ret;
        }
        /// <summary>
        /// SetUserControlData method implmentation
        /// </summary>
        public void SetUserControlData(MMCRegistrationList lst, bool disablesync)
        {
            SyncDisabled = disablesync;
            try
            {
                MMCRegistration obj = ((MMCRegistrationList)lst)[0];
                _secretkey = KeysManager.EncodedKey(((MMCRegistration)obj).UPN);
                _upn       = ((MMCRegistration)obj).UPN;
                _email     = ((MMCRegistration)obj).MailAddress;

                if (string.IsNullOrEmpty(_email))
                {
                    this.EmailPrompt.Text = "Adresse email : ";
                    _emailnotset          = true;
                }
                else
                {
                    this.EmailPrompt.Text = string.Format("Adresse email : {0}", _email);
                    _emailnotset          = false;
                }
                if (!string.IsNullOrEmpty(_secretkey))
                {
                    this.DisplayKey.Text = _secretkey;
                    if (!string.IsNullOrEmpty(_upn))
                    {
                        this.qrCodeGraphic.Text = ManagementAdminService.GetQRCodeValue(_upn, this.DisplayKey.Text);
                    }
                    else
                    {
                        this.qrCodeGraphic.Text = string.Empty;
                    }
                }
                else
                {
                    userPropertyPage.Dirty = true;
                }
                UpdateControlsEnabled();
            }
            finally
            {
                SyncDisabled = false;
            }
        }
        /// <summary>
        /// BTNSendByMail_Click event
        /// </summary>
        private void BTNSendByMail_Click(object sender, EventArgs e)
        {
            Cursor crs = this.Cursor;

            try
            {
                this.Cursor = Cursors.WaitCursor;
                MMCRegistrationList lst = userPropertyPage.GetSharedUserData();
                foreach (MMCRegistration reg in lst)
                {
                    string secret = KeysManager.EncodedKey(reg.UPN);
                    ManagementAdminService.SendKeyByEmail(reg.MailAddress, reg.UPN, secret);
                }
            }
            finally
            {
                this.Cursor = crs;
            }
        }
Пример #24
0
        public void ChannelManagerSerializationTests()
        {
            using var channelManager = GetTestChannelManager();
            var b = channelManager.Serialize(_pool);

            var keySeed             = new byte[] { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 };
            var keysInterface       = new KeysManager(keySeed, DateTime.UnixEpoch);
            var logger              = new TestLogger();
            var broadcaster         = new TestBroadcaster();
            var feeEstiamtor        = new TestFeeEstimator();
            var n                   = NBitcoin.Network.TestNet;
            var chainWatchInterface = new ChainWatchInterfaceUtil(n);
            var manyChannelMonitor  =
                ManyChannelMonitor.Create(n, chainWatchInterface, broadcaster, logger, feeEstiamtor);
            var args  = new ChannelManagerReadArgs(keysInterface, broadcaster, feeEstiamtor, logger, chainWatchInterface, n, manyChannelMonitor);
            var items = ChannelManager.Deserialize(b, args, new TestUserConfigProvider(), _pool);

            var(_, channelManager2) = items;

            Assert.True(channelManager2.Serialize(_pool).SequenceEqual(b));
        }
Пример #25
0
        private void AddLblTxtForDynamicPAKs()
        {
            if (PAKEntries.PAKEntriesList != null && PAKEntries.PAKEntriesList.Any())
            {
                if (AESEntries.AESEntriesList == null)
                {
                    KeysManager.Deserialize();
                }
                int yPos = 4;

                foreach (PAKInfosEntry Pak in PAKEntries.PAKEntriesList.Where(x => x.bTheDynamicPAK == true))
                {
                    Label PakLabel = new Label();
                    PakLabel.Content             = Path.GetFileNameWithoutExtension(Pak.ThePAKPath);
                    PakLabel.HorizontalAlignment = HorizontalAlignment.Left;
                    PakLabel.Margin            = new Thickness(2, yPos - 2, 0, 0);
                    PakLabel.VerticalAlignment = VerticalAlignment.Top;
                    PakLabel.Foreground        = new SolidColorBrush(Color.FromRgb(239, 239, 239));

                    TextBox PakTextBox = new TextBox();
                    PakTextBox.Height            = 19;
                    PakTextBox.TextWrapping      = TextWrapping.NoWrap;
                    PakTextBox.AcceptsReturn     = false;
                    PakTextBox.Margin            = new Thickness(160, yPos, 5, 0);
                    PakTextBox.VerticalAlignment = VerticalAlignment.Top;
                    PakTextBox.Foreground        = new SolidColorBrush(Color.FromRgb(239, 239, 239));
                    PakTextBox.Name = $"TxtBox_{Regex.Match(Path.GetFileNameWithoutExtension(Pak.ThePAKPath), @"\d+").Value}";

                    if (AESEntries.AESEntriesList != null && AESEntries.AESEntriesList.Any())
                    {
                        string PAKKeyFromXML = AESEntries.AESEntriesList.Where(x => string.Equals(x.ThePAKName, Path.GetFileNameWithoutExtension(Pak.ThePAKPath))).Select(x => x.ThePAKKey).FirstOrDefault();
                        PakTextBox.Text = $"0x{PAKKeyFromXML}";
                    }

                    yPos += 28;
                    Grid_DynamicKeys.Children.Add(PakLabel);
                    Grid_DynamicKeys.Children.Add(PakTextBox);
                }
            }
        }
Пример #26
0
        public static PeerManager getTestPeerManager()
        {
            var logger       = new TestLogger();
            var broadcaster  = new TestBroadcaster();
            var feeEstiamtor = new TestFeeEstimator();
            var n            = NBitcoin.Network.TestNet;

            var chainWatchInterface = new ChainWatchInterfaceUtil(n);
            var seed               = new byte[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
            var keysInterface      = new KeysManager(seed, DateTime.UnixEpoch);
            var blockNotifier      = BlockNotifier.Create(chainWatchInterface);
            var manyChannelMonitor = ManyChannelMonitor.Create(n, chainWatchInterface, broadcaster, logger, feeEstiamtor);
            var channelManager     = ChannelManager.Create(n, TestUserConfig.Default, chainWatchInterface, keysInterface, logger, broadcaster, feeEstiamtor, 400000, manyChannelMonitor);

            blockNotifier.RegisterChannelManager(channelManager);
            blockNotifier.RegisterManyChannelMonitor(manyChannelMonitor);
            var peerManager =
                PeerManager.Create(
                    seed, in TestUserConfig.Default, chainWatchInterface, logger, keysInterface.GetNodeSecret().ToBytes(), channelManager, blockNotifier, 10000
                    );

            return(peerManager);
        }
        public void RegistrationTests()
        {
            var keySeed             = new byte[] { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 };
            var keysInterface       = new KeysManager(keySeed, DateTime.UnixEpoch);
            var logger              = new TestLogger();
            var broadcaster         = new TestBroadcaster();
            var feeEstiamtor        = new TestFeeEstimator();
            var n                   = NBitcoin.Network.TestNet;
            var chainWatchInterface = new ChainWatchInterfaceUtil(n);

            using var blockNotifier      = BlockNotifier.Create(chainWatchInterface);
            using var manyChannelMonitor =
                      ManyChannelMonitor.Create(n, chainWatchInterface, broadcaster, logger, feeEstiamtor);

            blockNotifier.RegisterManyChannelMonitor(manyChannelMonitor);

            using var channelManager = ChannelManager.Create(n, UserConfig.GetDefault(), chainWatchInterface, keysInterface, logger, broadcaster, feeEstiamtor, 0, manyChannelMonitor);
            blockNotifier.RegisterChannelManager(channelManager);

            // second block in testnet3
            var block = (Block.Parse("0100000006128e87be8b1b4dea47a7247d5528d2702c96826c7a648497e773b800000000e241352e3bec0a95a6217e10c3abb54adfa05abb12c126695595580fb92e222032e7494dffff001d00d235340101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0e0432e7494d010e062f503253482fffffffff0100f2052a010000002321038a7f6ef1c8ca0c588aa53fa860128077c9e6c11e6830f4d7ee4e763a56b7718fac00000000", n));

            blockNotifier.BlockConnected(block, 1);

            var b = manyChannelMonitor.Serialize(_pool);

            var(manyChannelMonitor2, keyToHeaderHash) = ManyChannelMonitor.Deserialize(new ManyChannelMonitorReadArgs(chainWatchInterface, broadcaster, logger, feeEstiamtor, n), b.AsMemory(), _pool);
            using (manyChannelMonitor2)
            {
                Assert.True(NBitcoin.Utils.ArrayEqual(b, manyChannelMonitor2.Serialize(_pool)));
                // without creating any channel, it will result to empty.
                Assert.Empty(keyToHeaderHash);
            }

            blockNotifier.UnregisterManyChannelMonitor(manyChannelMonitor);
            blockNotifier.UnregisterChannelManager(channelManager);
        }
Пример #28
0
 /// <summary>
 /// CheckPin method inplementation
 /// </summary>
 private bool CheckPin(AuthenticationContext usercontext, int pin)
 {
     if (usercontext.SelectedMethod == AuthenticationResponseKind.PhoneAppOTP)  // Using a TOTP Application (Microsoft Authnetication, Google Authentication, etc...)
     {
         foreach (HashMode algo in Enum.GetValues(typeof(HashMode)))
         {
             if (algo <= Algorithm)
             {
                 if (TOTPShadows <= 0)
                 {
                     if (!KeysManager.ValidateKey(usercontext.UPN))
                     {
                         throw new CryptographicException(string.Format("SECURTY ERROR : Invalid Key for User {0}", usercontext.UPN));
                     }
                     byte[]       encodedkey = KeysManager.ProbeKey(usercontext.UPN);
                     DateTime     call       = DateTime.UtcNow;
                     OTPGenerator gen        = new OTPGenerator(encodedkey, usercontext.UPN, call, algo, this.Duration, this.Digits); // eg : TOTP code
                     gen.ComputeOTP(call);
                     return(Convert.ToInt32(pin) == Convert.ToInt32(gen.Digits));
                 }
                 else
                 {   // Current TOTP
                     if (!KeysManager.ValidateKey(usercontext.UPN))
                     {
                         throw new CryptographicException(string.Format("SECURTY ERROR : Invalid Key for User {0}", usercontext.UPN));
                     }
                     byte[]       encodedkey = KeysManager.ProbeKey(usercontext.UPN);
                     DateTime     tcall      = DateTime.UtcNow;
                     OTPGenerator gen        = new OTPGenerator(encodedkey, usercontext.UPN, tcall, algo, this.Duration, this.Digits); // eg : TOTP code
                     gen.ComputeOTP(tcall);
                     if (pin == Convert.ToInt32(gen.Digits))
                     {
                         return(true);
                     }
                     // TOTP with Shadow (current - x latest)
                     for (int i = 1; i <= TOTPShadows; i++)
                     {
                         DateTime     call = tcall.AddSeconds(-(i * this.Duration));
                         OTPGenerator gen2 = new OTPGenerator(encodedkey, usercontext.UPN, call, algo, this.Duration, this.Digits);  // eg : TOTP code
                         gen2.ComputeOTP(call);
                         if (pin == Convert.ToInt32(gen2.Digits))
                         {
                             return(true);
                         }
                     }
                     // TOTP with Shadow (current + x latest) - not possible. but can be usefull if time sync is not adequate
                     for (int i = 1; i <= TOTPShadows; i++)
                     {
                         DateTime     call = tcall.AddSeconds(i * this.Duration);
                         OTPGenerator gen3 = new OTPGenerator(encodedkey, usercontext.UPN, call, algo, this.Duration, this.Digits);  // eg : TOTP code
                         gen3.ComputeOTP(call);
                         if (pin == Convert.ToInt32(gen3.Digits))
                         {
                             return(true);
                         }
                     }
                 }
             }
         }
         return(false);
     }
     else
     {
         return(false);
     }
 }
 /// <summary>
 /// GetNewUserKey method implementation
 /// </summary>
 public static string GetNewUserKey(string upn)
 {
     KeysManager.NewKey(upn);
     return(KeysManager.EncodedKey(upn));
 }
Пример #30
0
        /// <summary>
        /// DoImport() method implmentation
        /// </summary>
        public override bool DoImport()
        {
            char          sep      = Path.DirectorySeparatorChar;
            string        filename = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + sep + "MFA" + sep + "adimport-" + DateTime.Now.ToFileTime().ToString() + ".log";
            TraceListener listen   = InitializeTrace(filename);

            try
            {
                ADDSHost adht = Config.Hosts.ActiveDirectoryHost;
                if (string.IsNullOrEmpty(DomainName))
                {
                    DomainName = adht.DomainName;
                }
                if (string.IsNullOrEmpty(UserName))
                {
                    UserName = adht.Account;
                }
                if (string.IsNullOrEmpty(Password))
                {
                    Password = adht.Password;
                }

                DataRepositoryService client = null;
                switch (Config.StoreMode)
                {
                case DataRepositoryKind.ADDS:
                    client = new ADDSDataRepositoryService(Config.Hosts.ActiveDirectoryHost, Config.DeliveryWindow);
                    break;

                case DataRepositoryKind.SQL:
                    client = new SQLDataRepositoryService(Config.Hosts.SQLServerHost, Config.DeliveryWindow);
                    break;

                case DataRepositoryKind.Custom:
                    client = CustomDataRepositoryActivator.CreateInstance(Config.Hosts.CustomStoreHost, Config.DeliveryWindow);
                    break;
                }

                Trace.WriteLine("");
                Trace.WriteLine(string.Format("Importing for AD : {0}", LDAPPath));
                Trace.Indent();
                Trace.WriteLine("Querying users from AD");
                MFAUserList lst = client.ImportMFAUsers(DomainName, UserName, Password, LDAPPath, CreatedSince, ModifiedSince, MailAttribute, PhoneAttribute, Method, Config.Hosts.ActiveDirectoryHost.UseSSL, DisableAll);
                Trace.WriteLine(string.Format("Querying return {0} users from AD", lst.Count.ToString()));

                DataRepositoryService client2 = null;
                switch (Config.StoreMode)
                {
                case DataRepositoryKind.ADDS:
                    Trace.WriteLine("");
                    Trace.WriteLine("Importing ADDS Mode");
                    Trace.Indent();
                    client2 = new ADDSDataRepositoryService(Config.Hosts.ActiveDirectoryHost, Config.DeliveryWindow);
                    break;

                case DataRepositoryKind.SQL:
                    Trace.WriteLine("");
                    Trace.WriteLine("Importing SQL Mode");
                    Trace.Indent();
                    client2 = new SQLDataRepositoryService(Config.Hosts.SQLServerHost, Config.DeliveryWindow);
                    break;

                case DataRepositoryKind.Custom:

                    Trace.WriteLine("");
                    Trace.WriteLine("Importing Custom Store Mode");
                    Trace.Indent();
                    client2 = CustomDataRepositoryActivator.CreateInstance(Config.Hosts.CustomStoreHost, Config.DeliveryWindow);
                    break;
                }
                client2.OnKeyDataEvent += KeyDataEvent;
                foreach (MFAUser reg in lst)
                {
                    Trace.TraceInformation(string.Format("Importing user {0} from AD", reg.UPN));
                    try
                    {
                        MFAUser ext = client2.GetMFAUser(reg.UPN);
                        if (ext == null)
                        {
                            reg.PIN = Config.DefaultPin;
                            client2.AddMFAUser(reg, ForceNewKey, false);
                            Trace.TraceInformation(string.Format("User {0} Imported in MFA", reg.UPN));
                            if (!string.IsNullOrEmpty(reg.MailAddress))
                            {
                                if (SendEmail)
                                {
                                    string      qrcode = KeysManager.EncodedKey(reg.UPN);
                                    CultureInfo info   = null;
                                    try
                                    {
                                        info = CultureInfo.CurrentUICulture;
                                    }
                                    catch
                                    {
                                        info = new CultureInfo(Config.DefaultCountryCode);
                                    }
                                    MailUtilities.SendKeyByEmail(reg.MailAddress, reg.UPN, qrcode, Config.MailProvider, Config, info);
                                    Trace.TraceInformation(string.Format("Sending Sensitive mail for User {0} Imported in MFA", reg.UPN));
                                }
                            }
                            RecordsCount++;
                        }
                    }
                    catch (Exception ex)
                    {
                        ErrorsCount++;
                        Trace.TraceError("Error importing Record N° {0} \r\r {1}", (RecordsCount + 1).ToString(), ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError(string.Format("Error importing from AD \r\r {0}", ex.Message));
                return(false);
            }
            finally
            {
                Trace.Unindent();
                FinalizeTrace(listen);
            }
            return(true);
        }