Пример #1
0
        public override async Task Run()
        {
            VaultPaths paths;

            if (VaultPath == null)
            {
                paths = new VaultPaths(Environment.CurrentDirectory);
            }
            else
            {
                paths = new VaultPaths(VaultPath);
            }

            var key = PasswordPrompt.PromptPasswordAsHash();

            using var vault = Vault.Open(paths, key);

            if (File.Exists(ToAddPath))
            {
                await vault.AddFileAsync(ToAddPath);

                Notifier.Success(string.Format(Strings.AddCommandAsync_Run_Added_file__0__to_vault, ToAddPath));
            }
            else if (Directory.Exists(ToAddPath))
            {
                var progress = new Progress <ProgressReport>();
                progress.ProgressChanged += ProgressBar.PrintProgressBar;

                await AddDirectory(vault, progress);
            }
        }
Пример #2
0
        private void client_CertificateRequired(object sender, ComponentPro.Security.CertificateRequiredEventArgs e)
        {
            string cert = _loginSettings.Get <string>(FtpLoginInfo.Certificate);

            // If the client cert file is specified.
            if (!string.IsNullOrEmpty(cert))
            {
                // Load Certificate.
                PasswordPrompt passdlg = new PasswordPrompt("Please provide password for certificate");
                // Ask for cert's passpharse
                if (passdlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    X509Certificate2 clientCert = new X509Certificate2(cert, passdlg.Password);
                    e.Certificates = new X509Certificate2Collection(clientCert);
                    return;
                }

                // Password has not been provided.
            }
            CertProvider dlg = new CertProvider();

            dlg.ShowDialog();
            // Get the selected certificate.
            e.Certificates = new X509Certificate2Collection(dlg.SelectedCertificate);
        }
Пример #3
0
        public override async Task Run()
        {
            await Task.Run(() =>
            {
                Log.Debug("Running NewProject with " +
                          $"Name = {Name ?? "null"}, Path = {Path ?? "null"}");

                var vaultName  = Name ?? GetCurrentDirectoryName();
                var vaultPath  = GetVaultCtorPath(Path);
                var folderPath = GetFolderPath(vaultName, Path);

                Log.Debug($"vaultPath: {folderPath}");

                if (!NDirectory.IsDirectoryEmpty(folderPath))
                {
                    throw new DirectoryNotEmptyException(Strings.NewCommandAsync_Run_The_directory_vault_is_not_empty);
                }

                var key = PasswordPrompt.PromptPasswordWithConfirmationAsHash();

                using var vault = Vault.Create(vaultName, key, vaultPath);

                Notifier.Success(string.Format(Strings.NewCommandAsync_Run_Created_vault__0__as__1__, vaultName, folderPath));
            });
        }
Пример #4
0
        public static Vault Generate(string?vaultPath)
        {
            var key = PasswordPrompt.PromptPasswordAsHash();

            var paths = new VaultPaths(vaultPath);

            return(Vault.Open(paths, key));
        }
Пример #5
0
        public static void Main(string[] args)
        {
            CommandLineParser cmd = CommandLineParser.Parse(args);

            Log.CreateInstance(true);

            string keyText = null;

            if (cmd["key"] != null)
            {
                keyText = cmd["key"].Value;
            }
            else
            {
                keyText = PasswordPrompt.Get("Please enter the encryption key");
                string keyText2 = PasswordPrompt.Get("Please confirm the encryption key");

                if (keyText != keyText2)
                {
                    Log.Instance.Write(Log_Severity.Fatal, "Keys did not match");
                }
            }

            if (cmd["to"] == null || cmd["from"] == null)
            {
                Log.Instance.Write(Log_Severity.Fatal, "Need arguments 'to' and 'from'");
            }

            ulong sender    = ulong.Parse(cmd["from"].Value);
            ulong recipient = ulong.Parse(cmd["to"].Value);

            var mt  = new MersenneTwister((uint)Guid.NewGuid().GetHashCode());
            var key = Encoding.UTF8.GetBytes(keyText);

            if (sender == 0)
            {
                sender = mt.NextULong();
            }

            if (recipient == 0)
            {
                recipient = mt.NextULong();
            }

            var iv   = mt.NextBytes(BLOCK_SIZE);
            var data = BitShifter.ToByte(sender).Concat(BitShifter.ToByte(recipient)).ToArray();

            BufferedBlockCipher cipher   = new CtsBlockCipher(new CbcBlockCipher(new AesEngine()));
            ICipherParameters   keyParam = new ParametersWithIV(new KeyParameter(key), iv);

            cipher.Init(true, keyParam);
            Log.Instance.Write(iv.Concat(cipher.DoFinal(data, 0, data.Length)).ToArray().ToHex());
        }
Пример #6
0
        public PasswordPrompt PasswordPrompt(MenuDisplayMode displayMode, string id, string name,
                                             Action <string> submitAction, Action <InputPrompt> closeAction, Func <string, string> validator,
                                             string title = null, string defaultValue = null, string description = null)
        {
            var passwordPrompt = new PasswordPrompt(displayMode, id, name)
                                 .WithSubmitAction(submitAction)
                                 .WithCloseAction(closeAction)
                                 .ValidatedBy(validator)
                                 .WithTitle(title)
                                 .WithDefaultValue(defaultValue)
                                 .WithDescription(description);

            Add(passwordPrompt);

            return(passwordPrompt as PasswordPrompt);
        }
Пример #7
0
 /// <summary>
 /// Invokes the PasswordPrompt event.
 /// </summary>
 /// <param name="e">ValidationMessageEventArgs object.</param>
 public virtual void OnPasswordPrompt(PasswordPromptEventArgs e) => PasswordPrompt?.Invoke(this, e);
Пример #8
0
        /*
         * Decrypt the private key and start the app
         */
        public void ResumeApp()
        {
            //attempt to load the keys if not already loaded
            if (!m_ln.Loaded)
            {
                m_ln.LoadKeys();
            }

            //prompt the user to enter a password to decrypt the private key
            PasswordPrompt p = new PasswordPrompt()
            {
                NegativeButtonVisible = false, PositiveButtonText = "Decrypt"
            };

            p.OnPromptSaved += new Prompt.PromptClosedEventListener(() =>
            {
                if (p.Password == null || p.Password.Length == 0)
                {
                    return;
                }

                //attempt to decrypt the public key
                if (!m_ln.DecryptPrivateKey(p.Password))
                { //decryption failed, incorrect password was entered
                    NotificationFactory.ShortAlert("Password is incorrect");
                    p.Show();
                    return;
                }

                //erase the entered password
                Eraser.SecureErase(p.Password);
                p.Password = "";

                //private key decrypted, start the app normally
                StartAppFinal();
            });
            //check if fingerprint auth is enabled
            if (m_config.UseFingerprint && m_config.EncryptedPassword.Length > 1)
            {
                //prompt for fingerprint
                IFingerprint fp = FingerprintFactory.GetInstance();
                fp.InitReader();
                if (fp.IsReady())
                {
                    Application.Current.MainPage = new FingerprintPage(new EventHandler((oo, ee) =>
                    {
                        byte[] data = (byte[])oo; //page returns the decrypted password

                        //go to password entry if skipped
                        if (data == null)
                        {
                            p.Show();
                            return;
                        }

                        //decrypt the password
                        string pass = Encoding.UTF8.GetString(data);

                        //attempt to decrypt the private key
                        if (!m_ln.DecryptPrivateKey(pass))
                        { //decryption failed
                            return;
                        }

                        //erase the decrypted password
                        Eraser.SecureErase(pass);
                        p.Password = "";

                        //private key decrypted, start the app normally
                        StartAppFinal();
                    }), fp, "");
                }
            }
            else
            {
                p.Show();
            }
        }
Пример #9
0
        public SettingsPage()
        {
            InitializeComponent();

            m_config = ConfigFactory.GetInstance();

            //initialize to the current settings
            chk_lock_on_suspend.IsToggled = m_config.LockOnSuspend;
            chk_save_on_suspend.IsToggled = m_config.SaveOnSuspend;
            chk_fingerprint.IsToggled     = m_config.UseFingerprint;

            //we need to handle the fingerprint enable separately
            chk_fingerprint.Toggled += new EventHandler <ToggledEventArgs>((o, e) =>
            {
                if (chk_fingerprint.IsToggled)
                {
                    IFingerprint fp = FingerprintFactory.GetInstance();
                    fp.InitReader();
                    if (fp.IsReady())
                    {
                        PasswordPrompt pmt = new PasswordPrompt()
                        {
                            IsNavPage = true, PromptTitle = "Verify your Password", PositiveButtonText = "Verify", RestorePage = true
                        };
                        pmt.OnPromptSaved += new Prompt.PromptClosedEventListener(() =>
                        {
                            if (pmt.Password == null || pmt.Password.Length == 0)
                            {
                                return;
                            }

                            //attempt to decrypt the private key, just as a verification method
                            if (!LocknoteMgr.GetInstance().DecryptPrivateKey(pmt.Password))
                            { //decryption failed, incorrect password was entered
                                NotificationFactory.ShortAlert("Password is incorrect");
                                pmt.Show(((NavigationPage)((HomeMDP)Application.Current.MainPage).Detail));
                                return;
                            }

                            //we verified the password is correct, now we can prompt the user to scan a fingerprint
                            Page back = Application.Current.MainPage;
                            Application.Current.MainPage = new FingerprintPage(new EventHandler((oo, ee) =>
                            {
                                byte[] data = (byte[])oo; //page returns the encrypted password
                                if (data != null)
                                {                         //only if was not skipped
                                  //encrypt the password and save it
                                    ConfigFactory.GetInstance().EncryptedPassword = data;
                                    ConfigFactory.GetInstance().UseFingerprint    = true;
                                    NotificationFactory.ShortAlert("Fingerprint unlock enabled");
                                }
                                else
                                {
                                    ConfigFactory.GetInstance().EncryptedPassword = new byte[] { 0 };
                                    ConfigFactory.GetInstance().UseFingerprint    = false;
                                    chk_fingerprint.IsToggled = false;
                                }
                                Application.Current.MainPage = back;
                            }), fp, pmt.Password);
                        });
                        pmt.OnPromptDismissed += new Prompt.PromptClosedEventListener(() =>
                        {
                            chk_fingerprint.IsToggled = false;
                        });
                        pmt.Show(((NavigationPage)((HomeMDP)Application.Current.MainPage).Detail));
                    }
                }
                else
                {
                    ConfigFactory.GetInstance().EncryptedPassword = new byte[] { 0 };
                    ConfigFactory.GetInstance().UseFingerprint    = false;
                }
            });

            //set the button handlers
            btn_save.Clicked += new EventHandler((o, e) =>
            {
                m_config.LockOnSuspend = chk_lock_on_suspend.IsToggled;
                m_config.SaveOnSuspend = chk_save_on_suspend.IsToggled;

                NotificationFactory.ShortAlert("Settings Saved!");
            });
            btn_change_password.Clicked += new EventHandler((o, e) =>
            {
                PasswordEntryView pep = new PasswordEntryView();
                pep.OnSave           += new EventHandler((oo, ee) =>
                {
                    LocknoteMgr.GetInstance().ReencryptPrivateKey(pep.Text);
                    ((NavigationPage)((HomeMDP)Application.Current.MainPage).Detail).PopAsync();
                    NotificationFactory.ShortAlert("Password changed");
                });
                Xamarin.Forms.ContentPage pg = new ContentPage();
                pg.Content = pep;
                ((NavigationPage)((HomeMDP)Application.Current.MainPage).Detail).PushAsync(pg);
            });
        }
Пример #10
0
        static void Main()
        {
            string promptedPassword = "";

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            HostSelect     Selector;
            PasswordPrompt Prompter;

            if (!Directory.Exists(APPDIR))
            {
                Directory.CreateDirectory(APPDIR);
                if (Directory.Exists(SYSTEMSDIR_Old))
                {
                    Directory.Move(SYSTEMSDIR_Old, SYSTEMSDIR);
                }

                if (File.Exists(CONFIGDIR_Old))
                {
                    File.Move(CONFIGDIR_Old, CONFIGFILE);
                }

                if (Directory.Exists(SOURCEDIR_Old))
                {
                    Directory.Move(SOURCEDIR_Old, SOURCEDIR);
                }
            }

            Directory.CreateDirectory(SYSTEMSDIR);
            Directory.CreateDirectory(SOURCEDIR);
            Directory.CreateDirectory(PROJDIR);

            Config = new Config(CONFIGFILE);
            Config.DoEditorDefaults();

            bool Connected = false;

            while (Connected == false)
            {
                Selector = new HostSelect();
                Application.Run(Selector);

                if (Selector.SystemSelected)
                {
                    if (IBMi.CurrentSystem.GetValue("password") == "")
                    {
                        Prompter = new PasswordPrompt(IBMi.CurrentSystem.GetValue("alias"), IBMi.CurrentSystem.GetValue("username"));
                        Prompter.ShowDialog();
                        if (Prompter.Success)
                        {
                            promptedPassword = Prompter.GetResult();
                        }
                    }

                    Connected = IBMi.Connect(Selector.OfflineModeSelected(), promptedPassword);

                    if (Connected)
                    {
                        Application.Run(new Editor());
                        IBMi.Disconnect();
                    }
                    else
                    {
                        //Basically, if it failed to connect when they're using FTPES - offer them a FTP connection
                        if (IBMi.CurrentSystem.GetValue("useFTPES") == "true")
                        {
                            DialogResult Result = MessageBox.Show("Would you like to try and connect again using a plain FTP connection? This will change the systems settings.", "Connection", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                            if (Result == DialogResult.Yes)
                            {
                                IBMi.CurrentSystem.SetValue("useFTPES", "false");
                                Connected = IBMi.Connect(false, promptedPassword);
                                if (Connected)
                                {
                                    Application.Run(new Editor());
                                    IBMi.Disconnect();
                                }
                            }
                        }
                    }
                }
                else
                {
                    Connected = true; //End loop and close
                }
            }
        }
Пример #11
0
        public static void Main(string[] args)
        {
            CommandLineParser cmd = CommandLineParser.Parse(args);

            Log.CreateInstance(true);

            if (cmd["random"] != null)
            {
                int count = 0;
                if (!int.TryParse(cmd["random"].Value, out count))
                {
                    count = 10;
                }

                for (int i = 0; i < count; i++)
                {
                    string text   = StringHelper.GenerateRandomString(32);
                    string key    = StringHelper.GenerateRandomString(32);
                    byte[] b64    = Convert.FromBase64String(text.Encrypt(key));
                    byte[] result = Reduce(Reduce(SHA256.Create().ComputeHash(b64)));
                    Log.Instance.Write(Log_Severity.None, $"Random {i}: {result.ToHex()}");
                }

                return;
            }

            string pw = null;

            if (cmd["password"] != null)
            {
                pw = cmd["password"].Value;
            }
            else
            {
                pw = PasswordPrompt.Get();
                string pw2 = PasswordPrompt.Get("Please confirm your password");

                if (pw != pw2)
                {
                    Log.Instance.Write(Log_Severity.Fatal, "Passwords did not match");
                }
            }

            if (cmd["encrypt"] != null)
            {
                string text = cmd["encrypt"].Value;
                if (File.Exists(text))
                {
                    text = File.ReadAllText(text);
                }

                try {
                    Log.Instance.Write(Log_Severity.None, text.Encrypt(pw));
                } catch {
                    Log.Instance.Write(Log_Severity.Fatal, "Encryption failed");
                }
            }

            if (cmd["decrypt"] != null)
            {
                string text = cmd["decrypt"].Value;
                if (File.Exists(text))
                {
                    text = File.ReadAllText(text);
                }

                try {
                    Log.Instance.Write(Log_Severity.None, text.Decrypt(pw));
                } catch {
                    Log.Instance.Write(Log_Severity.Fatal, "Decryption failed");
                }
            }
        }
Пример #12
0
        static void Main()
        {
            string promptedPassword = "";

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            HostSelect     Selector;
            PasswordPrompt Prompter;

            Directory.CreateDirectory(SYSTEMSDIR);
            Directory.CreateDirectory(SOURCEDIR);
            Directory.CreateDirectory(DUMPSDIR);

            Config = new Config(CONFIGFILE);
            Config.DoEditorDefaults();

            bool Connected = false;

            while (Connected == false)
            {
                Selector = new HostSelect();
                Application.Run(Selector);

                if (Selector.SystemSelected)
                {
                    if (IBMi.CurrentSystem.GetValue("password") == "")
                    {
                        Prompter = new PasswordPrompt(IBMi.CurrentSystem.GetValue("alias"), IBMi.CurrentSystem.GetValue("username"));
                        Prompter.ShowDialog();
                        if (Prompter.Success)
                        {
                            promptedPassword = Prompter.GetResult();
                        }
                    }

                    Connected = IBMi.Connect(Selector.OfflineModeSelected(), promptedPassword);

                    if (Connected)
                    {
                        try
                        {
                            Application.Run(new Editor());
                        }
                        catch (Exception e)
                        {
                            File.WriteAllText(Path.Combine(DUMPSDIR, DateTime.Now.ToFileTime() + ".txt"), e.ToString());
                            MessageBox.Show("There was an error. Crash dump created.");
                        }
                        IBMi.Disconnect();
                    }
                    else
                    {
                        //Basically, if it failed to connect when they're using FTPES - offer them a FTP connection
                        if (IBMi.CurrentSystem.GetValue("useFTPES") == "true")
                        {
                            MessageBox.Show("Failed to connect. Perhaps try disabling FTPES and then connecting again.", "Connection", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
                else
                {
                    Connected = true; //End loop and close
                }
            }
        }
Пример #13
0
 public static String GetUserPassPhase()
 {
     return(PasswordPrompt.ShowDialog("Please provide your passphse:", "Passphase Window"));
 }
Пример #14
0
 public static String GetSmartCardPin()
 {
     return(PasswordPrompt.ShowDialog("Please provide your smart card pin", "Smart Card Pin Window"));
 }
        /// <summary>
        /// Peforms the cloud deployment.
        /// </summary>
        /// <returns>
        /// true if successful else false
        /// </returns>
        private bool PerformCloudDeployment()
        {
            bool isSuccessful = true;
            int stepNumber = 20;

            // Get storage primary key in either case
            string storagePrimaryKey = string.Empty;

            try
            {
                using (CloudDeploymentTasks cloudTasks = new CloudDeploymentTasks(this.cloudArgs))
                {
                    // If its upgrade donot create hosted serviceand storage primary keys
                    if (!cloudTasks.IsUpgrade)
                    {
                        if (this.isNewStorage)
                        {
                            this.backgroundWorker.ReportProgress(++stepNumber, "Creating storage account in cloud....");
                            storagePrimaryKey = cloudTasks.InitStorageAccount();
                        }
                        else
                        {
                            this.backgroundWorker.ReportProgress(++stepNumber, "Updating storage account in cloud....");
                            storagePrimaryKey = cloudTasks.GetStoragePrimaryKey();
                        }

                        this.backgroundWorker.ReportProgress(++stepNumber, "Creating hosted service in cloud....");
                        cloudTasks.InitHostedService();
                    }
                    else
                    {
                        this.backgroundWorker.ReportProgress(++stepNumber, "Receiving storage account primary key from cloud....");
                        storagePrimaryKey = cloudTasks.GetStoragePrimaryKey();

                        // If storage primary key is not found implies need to create a storage account
                        if (string.IsNullOrEmpty(storagePrimaryKey))
                        {
                            storagePrimaryKey = cloudTasks.InitStorageAccount();
                        }

                        this.backgroundWorker.ReportProgress(++stepNumber, "Creating hosted service in cloud....");
                    }

                    this.backgroundWorker.ReportProgress(++stepNumber, "Copying package to cloud....");
                    cloudTasks.CopyCspkg(storagePrimaryKey);
                    this.backgroundWorker.ReportProgress(++stepNumber, "Deploying package in cloud....");
                    cloudTasks.DeployPackageInCloud();

                    this.backgroundWorker.ReportProgress(++stepNumber, "Creating service certificates. User action required....");

                    if (cloudTasks.CertificatePaths != null && cloudTasks.CertificatePaths.Any())
                    {
                        foreach (var item in cloudTasks.CertificatePaths)
                        {
                            // doit variable is to bypass STA
                            bool doit = false;
                            string fileName = Path.GetFileName(item);
                            PasswordPrompt prompt = new PasswordPrompt(fileName);
                            this.Invoke((MethodInvoker)delegate
                            {
                                prompt.TopMost = true;
                                prompt.StartPosition = FormStartPosition.CenterParent;
                                if (prompt.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                                {
                                    doit = true;
                                }
                            });

                            if (doit)
                            {
                                cloudTasks.AddCertificateToCloud(item, prompt.GivenPassword);
                            }
                            else
                            {
                                string.Format("Cannot install certificate : {0}. Cancelled by User", fileName).WriteToLog();
                                string.Format("Cannot install certificate : {0}. Cancelled by User", fileName).ShowUIInformation(FormStartPosition.CenterScreen);
                            }
                        }
                    }

                    this.backgroundWorker.ReportProgress(++stepNumber, "Cloud deployment completed successfully....");
                }
            }
            catch (WebException exception)
            {
                isSuccessful = false;
                this.backgroundWorker.ReportProgress(stepNumber, ReportStatus.Fail);
                exception.WriteToLog();
                this.Invoke((MethodInvoker)(() => exception.ShowGenericException("Deployment to Cloud failed.")));
            }
            catch (Exception exception)
            {
                isSuccessful = false;
                this.backgroundWorker.ReportProgress(stepNumber, ReportStatus.Fail);
                exception.WriteToLog();
                this.Invoke((MethodInvoker)(() => exception.ShowGenericException("Deployment to Cloud failed.")));
            }

            return isSuccessful;
        }
Пример #16
0
        static void Main()
        {
            string promptedPassword = "";

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            HostSelect     Selector;
            PasswordPrompt Prompter;

            Directory.CreateDirectory(SYSTEMSDIR);
            Directory.CreateDirectory(SOURCEDIR);
            Directory.CreateDirectory(DUMPSDIR);

            Config = new Config(CONFIGFILE);
            Config.DoEditorDefaults();

            bool Connected = false;

            while (Connected == false)
            {
                Selector = new HostSelect();
                Application.Run(Selector);

                if (Selector.SystemSelected)
                {
                    if (IBMi.CurrentSystem.GetValue("password") == "")
                    {
                        Prompter = new PasswordPrompt(IBMi.CurrentSystem.GetValue("alias"), IBMi.CurrentSystem.GetValue("username"));
                        Prompter.ShowDialog();
                        if (Prompter.Success)
                        {
                            promptedPassword = Prompter.GetResult();
                        }
                    }

                    Connected = IBMi.Connect(Selector.OfflineModeSelected(), promptedPassword);

                    if (Connected)
                    {
                        if (Config.GetValue("srcdat_agreement") == "false")
                        {
                            MessageBox.Show("Thanks for using ILEditor. This is a notice to tell you that when editing source members, the SRCDAT value is not retained. This is due to a restriction in our connection method. By using ILEditor you agree to our LICENCE, found on the ILEditor GitHub repository. Please seek ILEditor GitHub issues for further information.", "ILEditor Notice", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            Config.SetValue("srcdat_agreement", "true");
                            Config.SaveConfig();
                        }

                        try
                        {
                            Application.Run(new Editor());
                        }
                        catch (Exception e)
                        {
                            File.WriteAllText(Path.Combine(DUMPSDIR, DateTime.Now.ToFileTime() + ".txt"), e.ToString());
                            MessageBox.Show("There was an error. Crash dump created: " + DUMPSDIR);
                        }
                        IBMi.Disconnect();
                    }
                    else
                    {
                        //Basically, if it failed to connect when they're using FTPES - offer them a FTP connection
                        if (IBMi.CurrentSystem.GetValue("useFTPES") == "true")
                        {
                            MessageBox.Show("Failed to connect. Perhaps try disabling FTPES and then connecting again.", "Connection", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
                else
                {
                    Connected = true; //End loop and close
                }
            }
        }
Пример #17
0
 private string GetPassword(string messageText, bool isNewPassword = false)
 {
     var dlg = new PasswordPrompt(messageText, isNewPassword);
     dlg.ShowDialog();
     return dlg.Password;
 }
Пример #18
0
 public static string RetrievePassword()
 {
     var prompt = new PasswordPrompt();
     prompt.ShowDialog();
     return prompt.textBox1.Password;
 }
Пример #19
0
        public async Task MainAsync(string[] args)
        {
            CommandLineParser cmd = CommandLineParser.Parse(args);

            AngryWasp.Logger.Log.CreateInstance(true);

            string token       = null;
            string botAssembly = null;

            if (cmd["token"] != null)
            {
                await Log.Write("Token loaded from command line");

                token = cmd["token"].Value;
            }

            if (token == null && cmd["token-file"] != null)
            {
                await Log.Write("Token loaded from file");

                token = File.ReadAllText(cmd["token-file"].Value);
            }

            if (token == null)
            {
                await Log.Write(Log_Severity.Fatal, "Bot token not provided!");

                Environment.Exit(0);
            }
            else
            {
                await Log.Write($"Loaded token {token}");
            }

            string pw             = null;
            string decryptedToken = null;

            if (cmd["password"] != null)
            {
                pw = cmd["password"].Value;
            }
            else
            {
                pw = PasswordPrompt.Get("Please enter your token decryption password");
            }

            try {
                decryptedToken = token.Decrypt(pw);
            } catch {
                await Log.Write(Log_Severity.Fatal, "Incorrect password");

                Environment.Exit(0);
            }

            if (cmd["bot"] == null)
            {
                await Log.Write(Log_Severity.Fatal, "Bot plugin not provided!");

                Environment.Exit(0);
            }
            else
            {
                botAssembly = cmd["bot"].Value;
            }

            if (!File.Exists(botAssembly))
            {
                await Log.Write(Log_Severity.Fatal, "Bot plugin bot found!");

                Environment.Exit(0);
            }

            if (cmd["debug"] != null)
            {
                Globals.RpcLogConfig = Nerva.Rpc.Log.Presets.Normal;
            }

            List <int> errorCodes = new List <int>();

            for (int i = 0; i < cmd.Count; i++)
            {
                if (cmd[i].Flag == "debug-hide")
                {
                    int j = 0;
                    if (int.TryParse(cmd[i].Value, out j))
                    {
                        errorCodes.Add(-j);
                    }
                }
            }

            if (errorCodes.Count > 0)
            {
                Globals.RpcLogConfig.SuppressRpcCodes = errorCodes;
            }

            //load plugin
            Globals.BotAssembly = ReflectionHelper.Instance.LoadAssemblyFile(botAssembly);
            Type botPluginType = ReflectionHelper.Instance.GetTypesInheritingOrImplementing(Globals.BotAssembly, typeof(IBot))[0];

            Globals.Bot = (IBot)Activator.CreateInstance(botPluginType);

            List <Type> botCommands = ReflectionHelper.Instance.GetTypesInheritingOrImplementing(Globals.BotAssembly, typeof(ICommand));

            //common commands for all bots
            botCommands.Add(typeof(Help));
            botCommands.Add(typeof(Ping));

            Globals.Bot.Init(cmd);

            var client = new DiscordSocketClient();

            Globals.Client = client;
            client.Log    += Log.Write;

            await client.LoginAsync(TokenType.Bot, decryptedToken);

            await client.StartAsync();

            foreach (Type t in botCommands)
            {
                CommandAttribute ca = t.GetCustomAttribute(typeof(CommandAttribute)) as CommandAttribute;
                if (ca == null)
                {
                    continue;
                }

                Globals.BotHelp.Add($"{Globals.Bot.Config.CmdPrefix}{ca.Cmd}", ca.Help);
                Globals.Commands.Add($"{Globals.Bot.Config.CmdPrefix}{ca.Cmd}", t);
            }

            client.MessageReceived += MessageReceived;
            client.Ready           += ClientReady;

            await Task.Delay(-1);
        }
Пример #20
0
        public void Init(CommandLineParser cmd)
        {
            AngryWasp.Serializer.Serializer.Initialize();

            if (cmd["donation-wallet-port"] != null)
            {
                cfg.DonationWalletPort = uint.Parse(cmd["donation-wallet-port"].Value);
            }

            if (cmd["user-wallet-port"] != null)
            {
                cfg.UserWalletPort = uint.Parse(cmd["user-wallet-port"].Value);
            }

            string donationWalletFile = string.Empty, donationWalletPassword = string.Empty;
            string userWalletFile = string.Empty, userWalletPassword = string.Empty;

            if (cmd["key-file"] != null)
            {
                string[] keys            = File.ReadAllLines(cmd["key-file"].Value);
                string   keyFilePassword = PasswordPrompt.Get("Please enter the key file decryption password");

                donationWalletPassword   = keys[0].Decrypt(keyFilePassword);
                userWalletPassword       = keys[1].Decrypt(keyFilePassword);
                cfg.DonationPaymentIdKey = keys[2].Decrypt(keyFilePassword);

                keyFilePassword = null;
            }
            else
            {
                donationWalletPassword   = PasswordPrompt.Get("Please enter the donation wallet password");
                userWalletPassword       = PasswordPrompt.Get("Please enter the user wallet password");
                cfg.DonationPaymentIdKey = PasswordPrompt.Get("Please enter the payment id encryption key");
            }

            if (cmd["donation-wallet-file"] != null)
            {
                donationWalletFile = cmd["donation-wallet-file"].Value;
            }

            if (cmd["user-wallet-file"] != null)
            {
                userWalletFile = cmd["user-wallet-file"].Value;
            }

            string jsonFile = Path.Combine(Environment.CurrentDirectory, $"Wallets/{donationWalletFile}.json");

            Log.Write($"Loading Wallet JSON: {jsonFile}");
            cfg.AccountJson = JsonConvert.DeserializeObject <AccountJson>(File.ReadAllText(jsonFile));

            new OpenWallet(new OpenWalletRequestData
            {
                FileName = donationWalletFile,
                Password = donationWalletPassword
            },
                           (string result) =>
            {
                Log.Write("Wallet loaded");
            },
                           (RequestError error) =>
            {
                Log.Write("Failed to load donation wallet");
                Environment.Exit(1);
            },
                           cfg.WalletHost, cfg.DonationWalletPort).Run();

            new OpenWallet(new OpenWalletRequestData {
                FileName = userWalletFile,
                Password = userWalletPassword
            },
                           (string r1) =>
            {
                Log.Write("Wallet loaded");
                new GetAccounts(null, (GetAccountsResponseData r2) =>
                {
                    foreach (var a in r2.Accounts)
                    {
                        ulong uid = 0;

                        if (ulong.TryParse(a.Label, out uid))
                        {
                            if (!cfg.UserWalletCache.ContainsKey(uid))
                            {
                                cfg.UserWalletCache.Add(uid, new Tuple <uint, string>(a.Index, a.BaseAddress));
                                Log.Write($"Loaded wallet for user: {a.Label} - {a.BaseAddress}");
                            }
                            else
                            {
                                Log.Write($"Duplicate wallet detected for user with id: {uid}");
                            }
                        }
                        else
                        {
                            //fusion owns address index 0
                            if (a.Index == 0)
                            {
                                cfg.UserWalletCache.Add(cfg.BotId, new Tuple <uint, string>(a.Index, a.BaseAddress));
                            }
                            else
                            {
                                Log.Write($"Account index {a.Index} is not associated with a user");
                            }
                        }
                    }
                },
                                (RequestError error) =>
                {
                    Log.Write("Failed to load user wallet");
                    Environment.Exit(1);
                },
                                cfg.WalletHost, cfg.UserWalletPort).Run();
            },
                           (RequestError error) =>
            {
                Log.Write("Failed to load user wallet");
                Environment.Exit(1);
            },
                           cfg.WalletHost, cfg.UserWalletPort).Run();

            //todo: Check if an existing game is still running after restart and load that instead

            string fp = Path.Combine(Environment.CurrentDirectory, "lottery.xml");

            if (File.Exists(fp))
            {
                LotteryManager.Load(fp);
            }
            else
            {
                LotteryManager.Start();
            }
        }