private static void ExportAlias() { string aliasName = string.Empty; string outfile = string.Empty; try { aliasName = SelectedMode.GetString(Parameter.AliasToExport.ID); outfile = SelectedMode.GetString(Parameter.OutExportAlias.ID); bool overwriteExisting = SelectedMode.GetBool(Parameter.OverWriteExistingFile.ID); X509Context Context = SelectedMode.GetContext(Parameter.Context.ID); X509Alias Alias = new X509Alias(aliasName, Context); Alias.Export(ref outfile, includeCert: true, overwriteExisting); ConsoleMessage($"{nameof(X509Alias)} aliasName was successfully exported to file {outfile.InQuotes()}"); } catch (FileNotFoundException) { throw; } catch (X509CryptoException) { throw; } catch (Exception ex) { throw new X509CryptoException($"An exception occurred when attempting to export the {nameof(X509Alias)}", ex); } }
private static void InstallCert() { string infile = string.Empty; string thumbprint = string.Empty; string aliasName = string.Empty; X509Context Context = null; try { infile = SelectedMode.GetString(Parameter.InInstallCert.ID); Context = SelectedMode.GetContext(Parameter.InstallCertContext.ID); SecureString PfxPassword = Util.GetPassword($"Enter the password to unlock {Path.GetFileName(infile).InQuotes()}", 0); thumbprint = X509Utils.InstallCert(infile, PfxPassword, Context); StringBuilder Expression = new StringBuilder($"Added encryption certificate to the {Context.Name} {nameof(X509Context)}. \r\nCertificate Thumbprint: {thumbprint}"); if (SelectedMode.IsParameterDefined(Parameter.AliasToInstall.ID)) { aliasName = SelectedMode.GetString(Parameter.AliasToInstall.ID); if (CreateAlias(aliasName, thumbprint, Context)) { Expression.Append($"\r\n {nameof(X509Alias)}: {aliasName}"); } } ConsoleMessage(Expression.ToString()); } catch (Exception ex) { throw new X509CryptoException(@"Unable to install the specified certificate", ex); } }
static void EncryptText() { bool secretAdded = false; string ciphertext = string.Empty; string outfile = string.Empty; string aliasName = string.Empty; string secretName = string.Empty; string plaintext = string.Empty; X509Context Context = null; try { aliasName = SelectedMode.GetString(Parameter.AliasEnc.ID); Context = SelectedMode.GetContext(Parameter.Context.ID); plaintext = SelectedMode.GetString(Parameter.InEncText.ID); using (X509Alias Alias = new X509Alias(aliasName, Context)) { if (Parameter.SecretEnc.IsDefined) { secretName = SelectedMode.GetString(Parameter.SecretEnc.ID); ciphertext = Alias.EncryptText(plaintext); secretAdded = Util.AddSecret(secretName, ciphertext, Alias); } } if (!secretAdded) { WriteOutput(ciphertext, Parameter.OutEncText.ID, Samples.Ciphertext); } } catch (Exception ex) { throw new X509CryptoException($"An exception occurred when attempting to export the {nameof(X509Alias)}", ex); } }
private static void UpdateAlias() { try { string aliasName = SelectedMode.GetString(Parameter.AliasToUpdate.ID); string newThumbprint = SelectedMode.GetString(Parameter.Thumbprint.ID); X509Context OldContext = SelectedMode.GetContext(Parameter.OldContext.ID); X509Context NewContext = SelectedMode.GetContext(Parameter.NewContext.ID, OldContext); if (!X509CryptoAgent.CertificateExists(newThumbprint, NewContext)) { throw new X509CryptoCertificateNotFoundException(newThumbprint, NewContext); } X509Alias Alias = new X509Alias(aliasName, OldContext); Alias.ReEncrypt(newThumbprint, NewContext); Alias.Commit(); ConsoleMessage($"{nameof(X509Alias)} {aliasName} successfully updated. Now using encryption certificate with thumbprint {newThumbprint} from the {NewContext.Name} {nameof(X509Context)}"); } catch (Exception ex) { if (ex is X509CryptoCertificateNotFoundException) { throw; } else { throw new X509CryptoException(@"Unable to update the specified alias", ex); } } }
private static void ImportAlias() { try { string aliasName = Parameter.AliasToImport.IsDefined ? SelectedMode.GetString(Parameter.AliasToImport.ID) : string.Empty; string inFile = SelectedMode.GetString(Parameter.InImportAlias.ID); bool overwriteExisting = SelectedMode.GetBool(Parameter.OverWriteExistingAlias.ID); X509Context Context = SelectedMode.GetContext(Parameter.Context.ID); X509Alias AliasToImport = X509Alias.Import(inFile, Context, aliasName); if (!overwriteExisting && X509Alias.AliasExists(AliasToImport)) { throw new X509AliasAlreadyExistsException(AliasToImport); } AliasToImport.Commit(); ConsoleMessage($"{nameof(X509Alias)} {AliasToImport.Name.InQuotes()} has been successfully imported into the {Context.Name} {nameof(X509Context)} from the file {inFile.InQuotes()}"); if (!X509CryptoAgent.CertificateExists(AliasToImport)) { ConsoleWarning($"An encryption certificate with thumbprint {AliasToImport.Thumbprint.InQuotes()} could not be found in the {Context.Name} {nameof(X509Context)}. Ensure this certificate is installed on the system before using this alias."); } } catch (Exception ex) { if (ex is X509AliasAlreadyExistsException) { throw; } else { throw new X509CryptoException(@"Unable to import the specified alias", ex); } } }
private void DoWork() { Context = X509Context.Select(Location, false); var Aliases = Context.GetAliases(Constants.DoNotIncludeIfCertNotFound); Aliases.ForEach(p => Result.Add(new X509AliasDescription(p))); var AssignedThumbprints = Aliases.Select(p => p.Certificate.Thumbprint.ToUpper()).ToList(); if (All) { using (var Store = new X509Store(Context.Location)) { Store.Open(OpenFlags.ReadOnly); foreach (X509Certificate2 Cert in Store.Certificates) { if (!AssignedThumbprints.Contains(Cert.Thumbprint.ToUpper())) { Result.Add(new X509AliasDescription(Cert)); } } } } }
private void DoWork() { Console.WriteLine($"Path: {Path}"); var Context = X509Context.Select(Location, true); var Alias = Context.GetAliases(true).FirstOrDefault(p => p.Name.Matches(Name)); if (null != Alias) { if (!Overwrite || !Util.WarnConfirm($"An existing {nameof(X509Alias)} with the name {Name.InQuotes()} exists in the {Context.Name} {nameof(X509Context)}. OK to overwrite?", Constants.Affirm)) { throw new X509CryptoException($"Could not import the certificate. An {nameof(X509Alias)} with the name {Name.InQuotes()} exists in the {Context.Name} {nameof(X509Context)}"); } } var PfxPassword = Util.GetPassword($"Enter the password to unlock {System.IO.Path.GetFileName(Path).InQuotes()}", 0); var thumbprint = X509Utils.InstallCert(Path, PfxPassword, Context); StringBuilder Expression = new StringBuilder($"Added encryption certificate to the {Context.Name} {nameof(X509Context)}. \r\nCertificate Thumbprint: {thumbprint}"); if (null != Alias && Alias.HasCert(Context)) { Alias.ReEncrypt(thumbprint, Context); Expression.AppendLine($"\r\nAll secrets contained in the existing {nameof(X509Alias)} {Alias.Name.InQuotes()} have been re-encrypted using the new certificate."); } else { Alias = new X509Alias(Name, thumbprint, Context, false); Alias.Commit(); Expression.Append($"\r\n {nameof(X509Alias)}: {Name}"); } Util.ConsoleMessage(Expression.ToString()); Result = Alias; }
internal static X509Context GetContext(this Mode mode, Parameter param, X509Context DefaultContext = null) { Parameter Result = mode.GetParameter(param); if (Result.IsContext) { if (param.IsDefined) { return(Result.SelectedContext); } else { if (DefaultContext != null) { return(DefaultContext); } else { throw new Exception($"{param.Name} could not be defined"); } } } else { throw new InvalidX509ContextNameException(param.Name); } }
private static void ReEncryptFile() { string oldAliasName = string.Empty; string newAliasName = string.Empty; string infile = string.Empty; X509Alias OldAlias = null; X509Alias NewAlias = null; X509Context OldContext = null; X509Context NewContext = null; try { oldAliasName = SelectedMode.GetString(Parameter.OldAlias.ID); newAliasName = SelectedMode.GetString(Parameter.NewAliasReEnc.ID); OldContext = SelectedMode.GetContext(Parameter.OldContext.ID); NewContext = SelectedMode.GetContext(Parameter.NewContext.ID); infile = SelectedMode.GetString(Parameter.InReEncFile.ID); OldAlias = new X509Alias(oldAliasName, OldContext); NewAlias = new X509Alias(newAliasName, NewContext); X509Utils.ReEncryptFile(OldAlias, NewAlias, infile); ConsoleMessage($"The file {infile.InQuotes()} was successfully re-encrypted using the X509Crypto alias {newAliasName.InQuotes()} located in the {NewContext.Name.InQuotes()} {nameof(X509Context)}"); } catch (Exception ex) { throw new X509CryptoException(@"Unable to re-encrypt the specified file", ex); } }
private void DoWork() { context = X509Context.Select(Location, true); X509Alias Alias = new X509Alias(Name, context); Result = Alias; Console.WriteLine($"Alias {Name.InQuotes()} has been loaded from the {context.Name.InQuotes()} {nameof(X509Context)}"); }
private static void EncryptFile() { int wipeTimesToWrite = 0; string inFile = string.Empty; string outfile = string.Empty; string aliasName = string.Empty; bool overwriteExisting = false; X509Context Context = null; try { inFile = SelectedMode.GetString(Parameter.InEncFile.ID); if (Parameter.OutEncFile.IsDefined) { outfile = SelectedMode.GetString(Parameter.OutEncFile.ID); } else { outfile = $"{inFile}{FileExtensions.Ciphertext}"; } overwriteExisting = SelectedMode.GetBool(Parameter.OverWriteExistingFile.ID); Util.CheckForExistingFile(outfile, overwriteExisting, Parameter.OverWriteExistingFile.Name, Constants.Affirm); if (Parameter.Wipe.IsDefined) { if (!Util.WarnConfirm($"You have included the {Parameter.Wipe.Name.InQuotes()} argument. This will permanently delete the file {inFile.InQuotes()} from disk.", Constants.Affirm)) { return; } else { wipeTimesToWrite = SelectedMode.GetInt(Parameter.Wipe.ID); } } aliasName = SelectedMode.GetString(Parameter.AliasEnc.ID); Context = SelectedMode.GetContext(Parameter.Context.ID); using (X509Alias Alias = new X509Alias(aliasName, Context)) { Alias.EncryptFile(inFile, outfile, wipeTimesToWrite); } StringBuilder Expression = new StringBuilder($"The file {inFile.InQuotes()} was successfully encrypted. The ciphertext file name is {outfile.InQuotes()}"); if (Parameter.Wipe.IsDefined) { Expression.Append($"\r\nThe plaintext file has also been erased from disk"); } ConsoleMessage(Expression.ToString()); } catch (Exception ex) { throw new X509CryptoException(@"Unable to encrypt the specified file", ex); } }
private static void EnterModeImpersonated() { bool loadSuccess; int errCode; try { X509Context.CreateImpersonatedUserAppDirectory(ImpUser); #region Load User Profile //Get a token for the impersonated user LogonUser(ImpUser, ImpDomain, ImpSecret.Plaintext(), LoginType.LOGON32_LOGON_BATCH, Constants.LOGON32_PROVIDER_DEFAULT, ref Token); //Load the impersonated user profile ProfileInfo profileInfo = new ProfileInfo(); profileInfo.dwSize = Marshal.SizeOf(profileInfo); profileInfo.lpUserName = ImpUser; profileInfo.dwFlags = 1; loadSuccess = LoadUserProfile(Token, ref profileInfo); if (!loadSuccess) { errCode = Marshal.GetLastWin32Error(); Win32Exception wex = new Win32Exception(errCode); throw new LoadUserProfileFailedException(FullyQualifiedImpUser, errCode, wex); } if (profileInfo.hProfile == IntPtr.Zero) { errCode = Marshal.GetLastWin32Error(); Win32Exception wex = new Win32Exception(errCode); throw new LoadUserProfileFailedException(FullyQualifiedImpUser, errCode, wex); } #endregion Impersonation.RunAsUser(Credentials, LogonType.Batch, () => { EnterMode(); }); } catch (Win32Exception wex) { throw new LoadUserProfileFailedException(FullyQualifiedImpUser, wex); } catch (Exception ex) { throw new LoadUserProfileFailedException(FullyQualifiedImpUser, ex); } }
private void DoWork() { context = X509Context.Select(Location, true); if (string.IsNullOrEmpty(Thumbprint)) { Thumbprint = MakeCert(); } X509Alias Alias = new X509Alias(Name, Thumbprint, context, true); Alias.Commit(); Result = Alias; Console.WriteLine($"New alias {Name.InQuotes()} committed to {context.Name.InQuotes()} {nameof(X509Context)}\r\nThumbprint: {Alias.Thumbprint}"); }
private static void AddAlias() { try { string thumbprint = SelectedMode.GetString(Parameter.Thumbprint.ID); string aliasName = SelectedMode.GetString(Parameter.AliasToAdd.ID); X509Context Context = SelectedMode.GetContext(Parameter.Context.ID); X509Alias NewAlias = new X509Alias(aliasName, thumbprint, Context, AllowExistingAlias.No); NewAlias.Commit(); ConsoleMessage($"New {nameof(X509Alias)} {aliasName.InQuotes()} was created in the {Context.Name} {nameof(X509Context)} using certificate with thumbprint {thumbprint.InQuotes()}"); } catch (Exception ex) { throw new X509CryptoException(@"An exception occurred. The new alias could not be created.", ex); } }
internal X509Context GetContext(int id, X509Context DefaultContext = null) { try { return(Parameters.Where(p => p.IsDefined && p.IsContext) .First(p => p.ID == id).SelectedContext); } catch (Exception) { if (DefaultContext != null) { return(DefaultContext); } else { throw new InvalidX509ContextNameException(); } } }
private static void RemoveAlias() { try { string aliasName = SelectedMode.GetString(Parameter.AliasToRemove.ID); X509Context Context = SelectedMode.GetContext(Parameter.Context.ID); if (Util.WarnConfirm($"This will ERASE the {nameof(X509Alias)} {aliasName.InQuotes()} from the {Context.Name} {nameof(X509Context)} on this computer.", Constants.Affirm)) { X509Alias AliasToRemove = new X509Alias(aliasName, Context); AliasToRemove.Remove(); ConsoleMessage($"{nameof(X509Alias)} {aliasName.InQuotes()} was removed from the {Context.Name} {nameof(X509Context)}."); } } catch (Exception ex) { throw new X509CryptoException(@"Unable to remove the specified alias", ex); } }
private void DoWork() { var Context = X509Context.Select(Location, true); var AliasToImport = X509Alias.Import(Path, Context, Name); if (!Overwrite && X509Alias.AliasExists(AliasToImport)) { throw new X509AliasAlreadyExistsException(AliasToImport); } AliasToImport.Commit(); Util.ConsoleMessage($"{nameof(X509Alias)} {AliasToImport.Name.InQuotes()} has been successfully imported into the {Context.Name} {nameof(X509Context)} from the file {Path.InQuotes()}"); if (!X509CryptoAgent.CertificateExists(AliasToImport)) { Util.ConsoleWarning($"An encryption certificate with thumbprint {AliasToImport.Thumbprint.InQuotes()} could not be found in the {Context.Name} {nameof(X509Context)}. Ensure this certificate is installed on the system before using this alias."); } Result = AliasToImport; }
private static void ReEncryptText() { bool secretAdded = false; string oldCiphertext = string.Empty; string newCiphertext = string.Empty; string oldAliasName = string.Empty; string targetAliasName = string.Empty; string secretName = string.Empty; string outfile = string.Empty; X509Context OldContext = null; X509Context TargetContext = null; X509Alias OldAlias = null; X509Alias TargetAlias = null; try { oldAliasName = SelectedMode.GetString(Parameter.OldAlias.ID); targetAliasName = SelectedMode.GetString(Parameter.NewAlias.ID); OldContext = SelectedMode.GetContext(Parameter.OldContext.ID); TargetContext = SelectedMode.GetContext(Parameter.TargetContext.ID); OldAlias = new X509Alias(oldAliasName, OldContext); TargetAlias = new X509Alias(targetAliasName, TargetContext); newCiphertext = TargetAlias.ReEncryptSecret(secretName, OldAlias); if (Parameter.SecretReEnc.IsDefined) { secretName = SelectedMode.GetString(Parameter.SecretReEnc.ID); secretAdded = Util.AddSecret(secretName, newCiphertext, TargetAlias); } if (!secretAdded) { WriteOutput(newCiphertext, Parameter.OutEncText.ID, Samples.Ciphertext); } } catch (Exception ex) { ConsoleError(new X509CryptoException(@"Unable to re-encrypt the specified expression", ex), SelectedMode.Usage(SelectedCommand.Name, InCli)); } }
static void DecryptText() { string plaintext = string.Empty; string ciphertext = string.Empty; string outfile = string.Empty; string aliasName = string.Empty; string secretName = string.Empty; X509Context Context = null; try { if (!(Parameter.SecretDec.IsDefined ^ Parameter.InDecText.IsDefined)) { throw new X509CryptoException($"Either {Parameter.SecretDec.Name.InQuotes()} or {Parameter.InDecText.Name.InQuotes()} must be defined, but not both."); } aliasName = SelectedMode.GetString(Parameter.AliasDec.ID); Context = SelectedMode.GetContext(Parameter.Context.ID); using (X509Alias Alias = new X509Alias(aliasName, Context)) { if (Parameter.SecretDec.IsDefined) { secretName = SelectedMode.GetString(Parameter.SecretDec.ID); plaintext = Alias.RecoverSecret(secretName); } else { ciphertext = SelectedMode.GetString(Parameter.InDecText.ID); plaintext = Alias.DecryptText(ciphertext); } } WriteOutput(plaintext, Parameter.OutDecText.ID, Samples.Plaintext); } catch (Exception ex) { throw new X509CryptoException(@"Unable to decrypt the specified expression or secret", ex); } }
private void DoWork() { X509Context OldContext, NewContext; OldContext = Alias.Context; if (contextSet) { NewContext = X509Context.Select(Location, false); } else { NewContext = Alias.Context; } if (!X509CryptoAgent.CertificateExists(Thumbprint, NewContext)) { throw new X509CryptoCertificateNotFoundException(Thumbprint, NewContext); } Alias.ReEncrypt(Thumbprint, NewContext); Alias.Commit(); Console.WriteLine($"{nameof(X509Alias)} {Alias.Name} successfully updated. Now using encryption certificate with thumbprint {Thumbprint} from the {NewContext.Name} {nameof(X509Context)}"); }
private static bool CreateAlias(string aliasName, string thumbprint, X509Context Context) { X509Alias Alias = null; try { Alias = new X509Alias(aliasName, thumbprint, Context, true); Alias.Commit(); return(true); } catch (X509AliasAlreadyExistsException) { if (Util.WarnConfirm($"{nameof(X509Alias)} {aliasName.InQuotes()} already exists. Do you wish to overwrite it?", Constants.Affirm)) { Alias = new X509Alias(aliasName, thumbprint, Context, false); Alias.Commit(); return(true); } else { return(false); } } }
private static void DumpAlias() { string output = string.Empty; string aliasName = string.Empty; X509Context Context = null; bool reveal = false; try { aliasName = SelectedMode.GetString(Parameter.AliasToDump.ID); Context = SelectedMode.GetContext(Parameter.Context.ID); reveal = SelectedMode.GetBool(Parameter.Reveal.ID); using (X509Alias Alias = new X509Alias(aliasName, Context)) { output = SelectedMode.OutputType == Output.File ? Alias.DumpSecrets(SecretDumpFormat.CommaSeparated, reveal) : Alias.DumpSecrets(SecretDumpFormat.Text, reveal); } WriteOutput(output, Parameter.OutDumpAlias.ID); } catch (Exception ex) { throw new X509CryptoException($"Unable to dump the specified {nameof(X509Alias)}", ex); } }
private static void List() { string output = string.Empty; string outfile = string.Empty; string listType = string.Empty; X509Context Context = null; try { listType = SelectedMode.GetString(Parameter.ListType.ID); Context = SelectedMode.GetContext(Parameter.Context.ID); switch (listType) { case ListType.Certs: output = X509CryptoAgent.ListCerts(SelectedMode.GetContext(Parameter.Context.ID)); break; case ListType.Aliases: output = X509CryptoAgent.ListAliases(SelectedMode.GetContext(Parameter.Context.ID)); break; default: throw new X509CryptoException($"{listType}: Unsupported list type."); } WriteOutput(output, Parameter.OutList.ID); } catch (X509CryptoException ex) { throw ex; } catch (Exception ex) { throw new X509CryptoException(@"An exception occurred attempting to generate the list", ex); } }
private static void ExportCert() { string outfile = string.Empty; string thumbprint = string.Empty; string aliasName = string.Empty; SecureString Password = null; X509Context Context = null; X509Alias Alias = null; try { if (!(SelectedMode.IsParameterDefined(Parameter.AliasExportCert.ID) ^ SelectedMode.IsParameterDefined(Parameter.ThumbprintToExport.ID))) { throw new ArgumentException($"Either {Parameter.AliasExportCert.Name} or {Parameter.ThumbprintToExport.Name} must be defined, but not both"); } outfile = SelectedMode.GetString(Parameter.OutExportCert.ID); try { Path.GetFullPath(outfile); } catch { throw new IOException($"Not a valid NTFS path: {outfile}"); } if (!Path.GetExtension(outfile).Matches(FileExtensions.Pfx)) { outfile = $"{outfile}{FileExtensions.Pfx}"; } if (File.Exists(outfile)) { if (Util.WarnConfirm($"The specified file {outfile} already exists. Do you wish to overwrite it?", Constants.Affirm)) { X509Utils.DeleteFile(outfile, confirmDelete: true); } else { return; } } Context = SelectedMode.GetContext(Parameter.Context.ID); if (SelectedMode.IsParameterDefined(Parameter.AliasExportCert.ID)) { aliasName = SelectedMode.GetString(Parameter.AliasExportCert.ID); Alias = new X509Alias(aliasName, Context); thumbprint = Alias.Thumbprint; } else { thumbprint = SelectedMode.GetString(Parameter.ThumbprintToExport.ID); } Password = Util.GetPassword(@"Enter a strong password: "******"Encryption certificate with thumbprint {thumbprint} from the {Context.Name} {nameof(X509Context)} has been exported to the file {outfile.InQuotes()}"); } catch (Exception ex) { throw new X509CryptoException(@"Unable to export the specified certificate and key pair", ex); } }
private static void MakeCert() { string subject = string.Empty; string keySize = string.Empty; string thumbprint = string.Empty; string aliasName = string.Empty; int keyLength = Constants.DefaultKeyLength; int yearsValid = Constants.DefaultYearsValid; X509Context Context = null; try { Context = SelectedMode.GetContext(Parameter.Context.ID); if (SelectedMode.IsParameterDefined(Parameter.MakeCertSubject.ID)) { subject = SelectedMode.GetString(Parameter.MakeCertSubject.ID); } else { subject = Context.Name.Matches(X509Context.UserReadOnly.Name) ? Environment.UserName : Environment.MachineName; } if (SelectedMode.IsParameterDefined(Parameter.MakeCertKeySize.ID)) { keySize = SelectedMode.GetString(Parameter.MakeCertKeySize.ID); switch (keySize) { case KeySize.Small: keyLength = KeyLength.Small; break; case KeySize.Medium: keyLength = KeyLength.Medium; break; case KeySize.Large: keyLength = KeyLength.Large; break; default: throw new InvalidArgumentsException(Parameter.MakeCertKeySize.Name, keySize); } } if (SelectedMode.IsParameterDefined(Parameter.MakeCertYearsValid.ID)) { yearsValid = SelectedMode.GetInt(Parameter.MakeCertYearsValid.ID); } Context.MakeCertWorker(subject, keyLength, yearsValid, out thumbprint); StringBuilder Expression = new StringBuilder($"Certificate was created and added to the {Context.Name} {nameof(X509Context)}\r\nCertificate Thumbprint: {thumbprint}"); if (SelectedMode.IsParameterDefined(Parameter.AliasToInstall.ID)) { aliasName = SelectedMode.GetString(Parameter.AliasToInstall.ID); if (CreateAlias(aliasName, thumbprint, Context)) { Expression.Append($"\r\n {nameof(X509Alias)}: {aliasName}"); } } ConsoleMessage(Expression.ToString()); } catch (Exception ex) { ConsoleError(new X509CryptoException(@"An exception occurred attempting to generate a new encryption certificate", ex)); } }