/// <summary> /// Checks to see if Registry access is available to the caller /// /// </summary> /// /// <returns/> public bool GetIsRegistryAvailable() { PermissionSet permissionSet = new PermissionSet(PermissionState.None); RegistryPermission registryPermission = new RegistryPermission(PermissionState.Unrestricted); permissionSet.AddPermission((IPermission) registryPermission); return permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet); }
//Read Registry public string RegistryReadr(string subKey,string keyName) { try { RegistryPermission regeditPermission = new RegistryPermission(RegistryPermissionAccess.Read, System.IO.Path.Combine(Registry.CurrentUser.ToString(), System.IO.Path.Combine(ProcestaVariables.Variables.REGISTRY_PATH, subKey))); regeditPermission.Demand(); RegistryKey regeditRead = Registry.CurrentUser; regeditRead = regeditRead.OpenSubKey(System.IO.Path.Combine(ProcestaVariables.Variables.REGISTRY_PATH, subKey)); if (regeditRead != null) { if ((regeditRead.GetValue(keyName)).GetType().Equals(typeof(Int32))) { return regeditRead.GetValue(keyName).ToString(); } else { return (string)regeditRead.GetValue(keyName); } } else { RegistryWriter(subKey,keyName,string.Empty,RegistryValueKind.String); RegistryReadr(subKey, keyName); return null; } } catch (Exception) { MessageBox.Show(ProcestaVariables.Variables.ERROR_MESSAGES[0,4], ProcestaVariables.Variables.ERROR_MESSAGES[0,0], MessageBoxButtons.OK, MessageBoxIcon.Error); return null; } }
/// <summary> /// Call this function before creating the RegistryUtils class in order to make sure that /// you (the caller) will have permissions to access the class. /// </summary> /// <param name="subKey"> /// The sub key to demand permissions for. /// </param> public static void DemandLocalMachineAccess(string subKey) { // Create permission objects for the registry keys we're about to use. RegistryPermission readPermissions = new RegistryPermission(RegistryPermissionAccess.Read, @"HKEY_LOCAL_MACHINE\" + subKey); // Now force this function to throw a SecurityException if we don't already have these permissions. readPermissions.Demand(); }
private void CheckSecurity() { //check registry permissions RegistryPermission regPerm; regPerm = new RegistryPermission(RegistryPermissionAccess.Write, "HKEY_CLASSES_ROOT\\" + MenuName); regPerm.AddPathList(RegistryPermissionAccess.Write, "HKEY_CLASSES_ROOT\\" + Command); regPerm.Demand(); }
public static RegistryKey OpenOrCreateCompanyKey(this RegistryKey source) { RegistryPermission f = new RegistryPermission(RegistryPermissionAccess.AllAccess, "HKEY_LOCAL_MACHINE\\SOFTWARE"); RegistryKey keySoftware = source.OpenOrCreateKey("SOFTWARE"); AssemblyCompanyAttribute companyAttribute = System.Reflection.Assembly.GetEntryAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute)).FirstOrDefault() as AssemblyCompanyAttribute; RegistryKey keyCompany = keySoftware.OpenOrCreateKey(companyAttribute.Company); return keyCompany; }
/// <summary> /// Call this function before creating the RegistryUtils class in order to make sure that /// you (the caller) will have permissions to access the class. /// </summary> /// <param name="subKey"> /// The sub key to demand permissions for. /// </param> public static void DemandCurrentUserAccess(string subKey) { // Create permission objects for the registry keys we're about to use. RegistryPermission fullPermissions = new RegistryPermission(RegistryPermissionAccess.AllAccess, @"HKEY_CURRENT_USER\" + subKey); // Now force this function to throw a SecurityException if we don't already have these permissions. fullPermissions.Demand(); }
/// <summary> /// Creates a new WebTransform. /// </summary> public WebTransform() { //[IsolatedStorageFilePermissionAttribute(SecurityAction.Demand, Unrestricted=true)] FileIOPermission filePerm = new FileIOPermission(PermissionState.None); RegistryPermission regPerm = new RegistryPermission(PermissionState.None); filePerm.Demand(); regPerm.Demand(); }
public void PermissionStateUnrestricted () { RegistryPermission ep = new RegistryPermission (PermissionState.Unrestricted); AssertNotNull ("RegistryPermission(PermissionState.Unrestricted)", ep); Assert ("IsUnrestricted", ep.IsUnrestricted ()); RegistryPermission copy = (RegistryPermission)ep.Copy (); AssertEquals ("Copy.IsUnrestricted", ep.IsUnrestricted (), copy.IsUnrestricted ()); SecurityElement se = ep.ToXml (); AssertEquals ("ToXml-Unrestricted", "true", se.Attribute ("Unrestricted")); }
/// <summary> /// Call this function before creating the RegistryUtils class in order to make sure that /// you (the caller) will have permissions to access the class. /// </summary> public static void Demand() { // Create permission objects for the registry keys we're about to use. string fullRegistryPath = @"HKEY_CURRENT_USER\Software\Microsoft\" + ApplicationAcronym; RegistryPermission fullPermissions = new RegistryPermission(RegistryPermissionAccess.AllAccess, fullRegistryPath); // Now force this function to throw a SecurityException if we don't already have these permissions. fullPermissions.Demand(); }
/// <summary> /// Grava um par chave valor no registro do windows /// </summary> /// <param name="chave">chave usada para identificar o objeto</param> /// <param name="valor">valor a ser guardado</param> public static void GravaValor(string chave, string valor) { var perm1 = new RegistryPermission(RegistryPermissionAccess.Write, Key); if (perm1.CanWriteKey(Key)) { GravaValor(Key, chave, valor); } }
public void PermissionStateUnrestricted () { RegistryPermission ep = new RegistryPermission (PermissionState.Unrestricted); Assert.IsNotNull (ep, "RegistryPermission(PermissionState.Unrestricted)"); Assert.IsTrue (ep.IsUnrestricted (), "IsUnrestricted"); RegistryPermission copy = (RegistryPermission)ep.Copy (); Assert.AreEqual (ep.IsUnrestricted (), copy.IsUnrestricted (), "Copy.IsUnrestricted"); SecurityElement se = ep.ToXml (); Assert.AreEqual ("true", se.Attribute ("Unrestricted"), "ToXml-Unrestricted"); }
public void PermissionStateNone () { RegistryPermission ep = new RegistryPermission (PermissionState.None); Assert.IsNotNull (ep, "RegistryPermission(PermissionState.None)"); Assert.IsTrue (!ep.IsUnrestricted (), "IsUnrestricted"); RegistryPermission copy = (RegistryPermission)ep.Copy (); Assert.AreEqual (ep.IsUnrestricted (), copy.IsUnrestricted (), "Copy.IsUnrestricted"); SecurityElement se = ep.ToXml (); Assert.IsTrue (se.Attribute ("class").StartsWith (className), "ToXml-class"); Assert.AreEqual ("1", se.Attribute ("version"), "ToXml-version"); }
public void PermissionStateNone () { RegistryPermission ep = new RegistryPermission (PermissionState.None); AssertNotNull ("RegistryPermission(PermissionState.None)", ep); Assert ("IsUnrestricted", !ep.IsUnrestricted ()); RegistryPermission copy = (RegistryPermission)ep.Copy (); AssertEquals ("Copy.IsUnrestricted", ep.IsUnrestricted (), copy.IsUnrestricted ()); SecurityElement se = ep.ToXml (); Assert ("ToXml-class", se.Attribute ("class").StartsWith (className)); AssertEquals ("ToXml-version", "1", se.Attribute ("version")); }
internal static PermissionSet _UnsafeGetAssertPermSet() { PermissionSet set = new PermissionSet(PermissionState.None); RegistryPermission perm = new RegistryPermission(PermissionState.Unrestricted); set.AddPermission(perm); EnvironmentPermission permission2 = new EnvironmentPermission(PermissionState.Unrestricted); set.AddPermission(permission2); SecurityPermission permission3 = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode); set.AddPermission(permission3); return set; }
protected bool HavePermissionsOnKey(RegistryPermissionAccess accessLevel, string key) { try { RegistryPermission r = new RegistryPermission(accessLevel, key); r.Demand(); return true; } catch (SecurityException) { return false; } }
public static bool CanReadKey(this RegistryPermission reg, string key) { try { RegistryPermission r = new RegistryPermission(RegistryPermissionAccess.Read, key); r.Demand(); return true; } catch (SecurityException) { return false; } }
public static bool HavePermissionsOnKey(this RegistryPermission reg, RegistryPermissionAccess accessLevel, string key) { try { RegistryPermission r = new RegistryPermission(accessLevel, key); r.Demand(); return true; } catch (SecurityException) { return false; } }
protected void Page_Load(object sender, EventArgs e) { //FileManager1.Directory = null; FileManager1.Culture = CultureInfo.CurrentCulture; //FileManager1.DownloadOnDoubleClick = true; //FileManager1.RootDirectories[0].ShowRootIndex = false; string regPath = @"Software\FileManager\"; System.Security.Permissions.RegistryPermission permissions = new System.Security.Permissions.RegistryPermission(System.Security.Permissions.RegistryPermissionAccess.AllAccess, @"HKEY_LOCAL_MACHINE\" + regPath); bool regPermissions = System.Security.SecurityManager.IsGranted(permissions); AppDomain.CurrentDomain.PermissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.AllFlags)); }
/// <summary> /// Content Type /// </summary> /// <param name="filepath">File Path</param> /// <returns>Content Type</returns> public static string ContentType(string filepath) { if (string.IsNullOrWhiteSpace(filepath)) { throw new ArgumentException("filepath"); } else { var fi = new FileInfo(filepath); var dotExt = fi.Extension.ToUpperInvariant(); if (string.IsNullOrWhiteSpace(dotExt)) { throw new InvalidOperationException(string.Format("Unknown extension: {0}", dotExt)); } else if (types.ContainsKey(dotExt)) { return types[dotExt]; } else { var regPerm = new RegistryPermission(RegistryPermissionAccess.Read, "\\\\HKEY_CLASSES_ROOT"); using (var classesRoot = Registry.ClassesRoot) { using (var typeKey = classesRoot.OpenSubKey("MIME\\Database\\Content Type")) { foreach (var keyname in typeKey.GetSubKeyNames()) { using (var curKey = classesRoot.OpenSubKey("MIME\\Database\\Content Type\\" + keyname)) { var extension = curKey.GetValue("Extension"); if (null != extension && extension.ToString().ToUpperInvariant() == dotExt) { return keyname; } } } } } return null; } } }
internal static PermissionSet _UnsafeGetAssertPermSet() { // SEC_NOTE: All callers should already be guarded by EventLogPermission demand. PermissionSet permissionSet = new PermissionSet(PermissionState.None); // We need RegistryPermission RegistryPermission registryPermission = new RegistryPermission(PermissionState.Unrestricted); permissionSet.AddPermission(registryPermission); // It is not enough to just assert RegistryPermission, for some regkeys // we need to assert EnvironmentPermission too EnvironmentPermission environmentPermission = new EnvironmentPermission(PermissionState.Unrestricted); permissionSet.AddPermission(environmentPermission); // For remote machine registry access UnmanagdCodePermission is required. SecurityPermission securityPermission = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode); permissionSet.AddPermission(securityPermission); return permissionSet; }
public static bool RunSecurityDemands() { FileIOPermission fPer = new FileIOPermission(PermissionState.None); fPer.AllLocalFiles = FileIOPermissionAccess.AllAccess; fPer.AllFiles = FileIOPermissionAccess.AllAccess; try { fPer.Demand(); } catch (SecurityException s) { Common.DebugHelper.WriteLine("File IO Permission Error: {0}", s.Message); return false; } System.Security.Permissions.FileDialogPermission fdPer = new FileDialogPermission(FileDialogPermissionAccess.None); fdPer.Access = FileDialogPermissionAccess.OpenSave; try { fdPer.Demand(); } catch (System.Security.SecurityException s) { Common.DebugHelper.WriteLine("File Dialog Persmission Error: {0}", s.Message); return false; } System.Security.Permissions.RegistryPermission rPer = new RegistryPermission(PermissionState.None); rPer.SetPathList(RegistryPermissionAccess.AllAccess, "HKEY_LOCAL_MACHINE"); try { fPer.Demand(); } catch (System.Security.SecurityException s) { Common.DebugHelper.WriteLine("Registry Access Permission Error: {0}", s.Message); return false; } return true; }
public override IPermission Union(IPermission other) { if (other == null) { return(this.Copy()); } if (!base.VerifyType(other)) { throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", new object[] { base.GetType().FullName })); } RegistryPermission registryPermission = (RegistryPermission)other; if (this.IsUnrestricted() || registryPermission.IsUnrestricted()) { return(new RegistryPermission(PermissionState.Unrestricted)); } StringExpressionSet stringExpressionSet = (this.m_read == null) ? registryPermission.m_read : this.m_read.Union(registryPermission.m_read); StringExpressionSet stringExpressionSet2 = (this.m_write == null) ? registryPermission.m_write : this.m_write.Union(registryPermission.m_write); StringExpressionSet stringExpressionSet3 = (this.m_create == null) ? registryPermission.m_create : this.m_create.Union(registryPermission.m_create); StringExpressionSet stringExpressionSet4 = (this.m_viewAcl == null) ? registryPermission.m_viewAcl : this.m_viewAcl.Union(registryPermission.m_viewAcl); StringExpressionSet stringExpressionSet5 = (this.m_changeAcl == null) ? registryPermission.m_changeAcl : this.m_changeAcl.Union(registryPermission.m_changeAcl); if ((stringExpressionSet == null || stringExpressionSet.IsEmpty()) && (stringExpressionSet2 == null || stringExpressionSet2.IsEmpty()) && (stringExpressionSet3 == null || stringExpressionSet3.IsEmpty()) && (stringExpressionSet4 == null || stringExpressionSet4.IsEmpty()) && (stringExpressionSet5 == null || stringExpressionSet5.IsEmpty())) { return(null); } return(new RegistryPermission(PermissionState.None) { m_unrestricted = false, m_read = stringExpressionSet, m_write = stringExpressionSet2, m_create = stringExpressionSet3, m_viewAcl = stringExpressionSet4, m_changeAcl = stringExpressionSet5 }); }
public override IPermission Union(IPermission other) { RegistryPermission rp = Cast(other); if (rp == null) { return(Copy()); } if (IsUnrestricted() || rp.IsUnrestricted()) { return(new RegistryPermission(PermissionState.Unrestricted)); } if (IsEmpty() && rp.IsEmpty()) { return(null); } RegistryPermission result = (RegistryPermission)Copy(); string path = rp.GetPathList(RegistryPermissionAccess.Create); if (path != null) { result.AddPathList(RegistryPermissionAccess.Create, path); } path = rp.GetPathList(RegistryPermissionAccess.Read); if (path != null) { result.AddPathList(RegistryPermissionAccess.Read, path); } path = rp.GetPathList(RegistryPermissionAccess.Write); if (path != null) { result.AddPathList(RegistryPermissionAccess.Write, path); } return(result); }
/// <summary>Creates and returns a permission that is the intersection of the current permission and the specified permission.</summary> /// <returns>A new permission that represents the intersection of the current permission and the specified permission. This new permission is null if the intersection is empty.</returns> /// <param name="target">A permission to intersect with the current permission. It must be of the same type as the current permission. </param> /// <exception cref="T:System.ArgumentException">The <paramref name="target" /> parameter is not null and is not of the same type as the current permission. </exception> public override IPermission Intersect(IPermission target) { RegistryPermission registryPermission = this.Cast(target); if (registryPermission == null) { return(null); } if (this.IsUnrestricted()) { return(registryPermission.Copy()); } if (registryPermission.IsUnrestricted()) { return(this.Copy()); } RegistryPermission registryPermission2 = new RegistryPermission(PermissionState.None); this.IntersectKeys(this.createList, registryPermission.createList, registryPermission2.createList); this.IntersectKeys(this.readList, registryPermission.readList, registryPermission2.readList); this.IntersectKeys(this.writeList, registryPermission.writeList, registryPermission2.writeList); return((!registryPermission2.IsEmpty()) ? registryPermission2 : null); }
/// <summary> Gets a list of all available serial port names this controller provides. </summary> /// <returns> list of all available serial port names this controller provides. </returns> public List<string> GetPortNames() { RegistryKey baseKey = null; RegistryKey serialKey = null; var portNames = new List<string>(); var regperm = new RegistryPermission( RegistryPermissionAccess.Read, @"HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM"); regperm.Assert(); try { baseKey = Registry.LocalMachine; serialKey = baseKey.OpenSubKey(@"HARDWARE\DEVICEMAP\SERIALCOMM", false); if (serialKey != null) { var deviceNames = serialKey.GetValueNames(); portNames.AddRange(deviceNames.Select(devname => (string) serialKey.GetValue(devname))); } } finally { baseKey?.Dispose(); serialKey?.Dispose(); CodeAccessPermission.RevertAssert(); } return portNames; }
public override bool IsSubsetOf(IPermission target) { RegistryPermission rp = Cast(target); if (rp == null) { return(false); } if (rp.IsEmpty()) { return(IsEmpty()); } if (IsUnrestricted()) { return(rp.IsUnrestricted()); } else if (rp.IsUnrestricted()) { return(true); } if (!KeyIsSubsetOf(createList, rp.createList)) { return(false); } if (!KeyIsSubsetOf(readList, rp.readList)) { return(false); } if (!KeyIsSubsetOf(writeList, rp.writeList)) { return(false); } return(true); }
public override IPermission Copy() { RegistryPermission rp = new RegistryPermission(_state); string path = GetPathList(RegistryPermissionAccess.Create); if (path != null) { rp.SetPathList(RegistryPermissionAccess.Create, path); } path = GetPathList(RegistryPermissionAccess.Read); if (path != null) { rp.SetPathList(RegistryPermissionAccess.Read, path); } path = GetPathList(RegistryPermissionAccess.Write); if (path != null) { rp.SetPathList(RegistryPermissionAccess.Write, path); } return(rp); }
public override IPermission CreatePermission() { if (m_unrestricted) { return(new RegistryPermission(PermissionState.Unrestricted)); } else { RegistryPermission perm = new RegistryPermission(PermissionState.None); if (m_read != null) { perm.SetPathList(RegistryPermissionAccess.Read, m_read); } if (m_write != null) { perm.SetPathList(RegistryPermissionAccess.Write, m_write); } if (m_create != null) { perm.SetPathList(RegistryPermissionAccess.Create, m_create); } return(perm); } }
/// <summary> /// Recupera um valor do registro baseado na chave /// </summary> /// <param name="keyPath">Caminho base</param> /// <param name="chave">chave usada para localizar o valor</param> /// <param name="valorPadrao">Valor que deve ser usado caso não obtenha resultado, caso nulo retorna Exception</param> /// <returns>Retorna o objeto referente a chave, caso não encontre volta uma string vazia</returns> public static string RecuperaValor(string keyPath, string chave, string valorPadrao) { try { if (string.IsNullOrEmpty(keyPath)) { throw new ArgumentNullException("keyPath", "O parâmetro chave não pode ser nulo"); } if (string.IsNullOrEmpty(chave)) { throw new ArgumentNullException("chave", "O parâmetro chave não pode ser nulo"); } var perm1 = new RegistryPermission(RegistryPermissionAccess.Read, Key); return perm1.CanReadKey(Key) ? Microsoft.Win32.Registry.GetValue(keyPath, chave, "").ToString() : valorPadrao; } catch (Exception) { if (valorPadrao == null) { throw; } return valorPadrao; } }
public override IPermission CreatePermission() { if (m_unrestricted) { return new RegistryPermission( PermissionState.Unrestricted ); } else { RegistryPermission perm = new RegistryPermission(PermissionState.None); if (m_read != null) perm.SetPathList( RegistryPermissionAccess.Read, m_read ); if (m_write != null) perm.SetPathList( RegistryPermissionAccess.Write, m_write ); if (m_create != null) perm.SetPathList( RegistryPermissionAccess.Create, m_create ); #if FEATURE_MACL if (m_viewAcl != null) perm.SetPathList( AccessControlActions.View, m_viewAcl ); if (m_changeAcl != null) perm.SetPathList( AccessControlActions.Change, m_changeAcl ); #endif return perm; } }
/// <internalonly/> int IBuiltInPermission.GetTokenIndex() { return(RegistryPermission.GetTokenIndex()); }
private void Load( RegistryKey root ) { { string pathList = root.ToString(); var permission = new RegistryPermission( RegistryPermissionAccess.Read, AccessControlActions.View, pathList ); permission.Demand(); } IEnumerable<IConfigurationSection> sections = GetSections( root ); sections.ToList().ForEach( Add ); }
private static Uri GetRegistryPassportCertificationUrl() { // This Function Will return null, if the registry entry is missing // Acquire permissions to read the one key we care about from the registry RegistryPermission permission = new RegistryPermission( RegistryPermissionAccess.Read, System.Security.AccessControl.AccessControlActions.View, _passportActivationRegistryFullKeyName); permission.Assert(); try { RegistryKey key = Registry.LocalMachine.OpenSubKey(_passportActivationRegistryKeyName); if (key == null) { return null; } else { object keyValue = key.GetValue(null); // this should get the default value string stringValue = keyValue as string; if (stringValue != null) { return new Uri(stringValue); } else { return null; } } } finally { RegistryPermission.RevertAssert(); } }
private static void DeleteRegistryEntry(string categoryName) { RegistryKey serviceKey = null; //SECREVIEW: Whoever is able to call this function, must already // have demmanded PerformanceCounterPermission // we can therefore assert the RegistryPermission. RegistryPermission registryPermission = new RegistryPermission(PermissionState.Unrestricted); registryPermission.Assert(); try { serviceKey = Registry.LocalMachine.OpenSubKey(ServicePath, true); bool deleteCategoryKey = false; using (RegistryKey categoryKey = serviceKey.OpenSubKey(categoryName, true)) { if (categoryKey != null) { if (categoryKey.GetValueNames().Length == 0) { deleteCategoryKey = true; } else { categoryKey.DeleteSubKeyTree("Linkage"); categoryKey.DeleteSubKeyTree("Performance"); } } } if (deleteCategoryKey) serviceKey.DeleteSubKeyTree(categoryName); } finally { if (serviceKey != null) serviceKey.Close(); RegistryPermission.RevertAssert(); } }
private static void CreateRegistryEntry(string categoryName, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection creationData, ref bool iniRegistered) { RegistryKey serviceParentKey = null; RegistryKey serviceKey = null; RegistryKey linkageKey = null; //SECREVIEW: Whoever is able to call this function, must already // have demmanded PerformanceCounterPermission // we can therefore assert the RegistryPermission. RegistryPermission registryPermission = new RegistryPermission(PermissionState.Unrestricted); registryPermission.Assert(); try { serviceParentKey = Registry.LocalMachine.OpenSubKey(ServicePath, true); serviceKey = serviceParentKey.OpenSubKey(categoryName + "\\Performance", true); if (serviceKey == null) serviceKey = serviceParentKey.CreateSubKey(categoryName + "\\Performance"); serviceKey.SetValue("Open","OpenPerformanceData"); serviceKey.SetValue("Collect", "CollectPerformanceData"); serviceKey.SetValue("Close","ClosePerformanceData"); serviceKey.SetValue("Library", DllName); serviceKey.SetValue("IsMultiInstance", (int) categoryType, RegistryValueKind.DWord); serviceKey.SetValue("CategoryOptions", 0x3, RegistryValueKind.DWord); string [] counters = new string[creationData.Count]; string [] counterTypes = new string[creationData.Count]; for (int i = 0; i < creationData.Count; i++) { counters[i] = creationData[i].CounterName; counterTypes[i] = ((int) creationData[i].CounterType).ToString(CultureInfo.InvariantCulture); } linkageKey = serviceParentKey.OpenSubKey(categoryName + "\\Linkage" , true); if (linkageKey == null) linkageKey = serviceParentKey.CreateSubKey(categoryName + "\\Linkage" ); linkageKey.SetValue("Export", new string[]{categoryName}); serviceKey.SetValue("Counter Types", (object) counterTypes); serviceKey.SetValue("Counter Names", (object) counters); object firstID = serviceKey.GetValue("First Counter"); if (firstID != null) iniRegistered = true; else iniRegistered = false; } finally { if (serviceKey != null) serviceKey.Close(); if (linkageKey != null) linkageKey.Close(); if (serviceParentKey != null) serviceParentKey.Close(); RegistryPermission.RevertAssert(); } }
// What if an app is locked back? Why would we use this? internal static string GetLatestBuildDllDirectory(string machineName) { string dllDir = ""; RegistryKey baseKey = null; RegistryKey complusReg = null; //This property is retrieved only when creationg a new category, // the calling code already demanded PerformanceCounterPermission. // Therefore the assert below is safe. //This property is retrieved only when creationg a new log, // the calling code already demanded EventLogPermission. // Therefore the assert below is safe. RegistryPermission registryPermission = new RegistryPermission(PermissionState.Unrestricted); registryPermission.Assert(); try { if (machineName.Equals(".")) { return GetLocalBuildDirectory(); } else { baseKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machineName); } if (baseKey == null) throw new InvalidOperationException(SR.GetString(SR.RegKeyMissingShort, "HKEY_LOCAL_MACHINE", machineName)); complusReg = baseKey.OpenSubKey("SOFTWARE\\Microsoft\\.NETFramework"); if (complusReg != null) { string installRoot = (string)complusReg.GetValue("InstallRoot"); if (installRoot != null && installRoot != String.Empty) { // the "policy" subkey contains a v{major}.{minor} subkey for each version installed. There are also // some extra subkeys like "standards" and "upgrades" we want to ignore. // first we figure out what version we are... string versionPrefix = "v" + Environment.Version.Major + "." + Environment.Version.Minor; RegistryKey policyKey = complusReg.OpenSubKey("policy"); // This is the full version string of the install on the remote machine we want to use (for example "v2.0.50727") string version = null; if (policyKey != null) { try { // First check to see if there is a version of the runtime with the same minor and major number: RegistryKey bestKey = policyKey.OpenSubKey(versionPrefix); if (bestKey != null) { try { version = versionPrefix + "." + GetLargestBuildNumberFromKey(bestKey); } finally { bestKey.Close(); } } else { // There isn't an exact match for our version, so we will look for the largest version // installed. string[] majorVersions = policyKey.GetSubKeyNames(); int[] largestVersion = new int[] { -1, -1, -1 }; for (int i = 0; i < majorVersions.Length; i++) { string majorVersion = majorVersions[i]; // If this looks like a key of the form v{something}.{something}, we should see if it's a usable build. if (majorVersion.Length > 1 && majorVersion[0] == 'v' && majorVersion.Contains(".")) { int[] currentVersion = new int[] { -1, -1, -1 }; string[] splitVersion = majorVersion.Substring(1).Split('.'); if(splitVersion.Length != 2) { continue; } if (!Int32.TryParse(splitVersion[0], out currentVersion[0]) || !Int32.TryParse(splitVersion[1], out currentVersion[1])) { continue; } RegistryKey k = policyKey.OpenSubKey(majorVersion); if (k == null) { // We may be able to use another subkey continue; } try { currentVersion[2] = GetLargestBuildNumberFromKey(k); if (currentVersion[0] > largestVersion[0] || ((currentVersion[0] == largestVersion[0]) && (currentVersion[1] > largestVersion[1]))) { largestVersion = currentVersion; } } finally { k.Close(); } } } version = "v" + largestVersion[0] + "." + largestVersion[1] + "." + largestVersion[2]; } } finally { policyKey.Close(); } if (version != null && version != String.Empty) { StringBuilder installBuilder = new StringBuilder(); installBuilder.Append(installRoot); if (!installRoot.EndsWith("\\", StringComparison.Ordinal)) installBuilder.Append("\\"); installBuilder.Append(version); dllDir = installBuilder.ToString(); } } } } } catch { // ignore } finally { if (complusReg != null) complusReg.Close(); if (baseKey != null) baseKey.Close(); RegistryPermission.RevertAssert(); } return dllDir; }
public override IPermission Intersect (IPermission target) { RegistryPermission rp = Cast (target); if (rp == null) return null; if (IsUnrestricted ()) return rp.Copy (); if (rp.IsUnrestricted ()) return Copy (); RegistryPermission result = new RegistryPermission (PermissionState.None); IntersectKeys (createList, rp.createList, result.createList); IntersectKeys (readList, rp.readList, result.readList); IntersectKeys (writeList, rp.writeList, result.writeList); return (result.IsEmpty () ? null : result); }
public override IPermission Copy () { RegistryPermission rp = new RegistryPermission (_state); string path = GetPathList (RegistryPermissionAccess.Create); if (path != null) rp.SetPathList (RegistryPermissionAccess.Create, path); path = GetPathList (RegistryPermissionAccess.Read); if (path != null) rp.SetPathList (RegistryPermissionAccess.Read, path); path = GetPathList (RegistryPermissionAccess.Write); if (path != null) rp.SetPathList (RegistryPermissionAccess.Write, path); return rp; }