internal static void DemandHostStorePermissions(ServiceHost host) { bool validates = ValidatesCertificates(host); bool demand = UsesCertificateServiceCredentials(host); foreach (ServiceEndpoint endpoint in host.Description.Endpoints) { if (UsesCertificateClientCredentials(endpoint) && validates) { demand = true; break; } if (MessageSecurityEnabled(endpoint)) { if (IsAnonymous(endpoint)) { demand = true; break; } else { if (WindowsSecurityEnabled(endpoint) == false) { demand = true; break; } } } } if (demand) { IPermission certPermission = new StorePermission(StorePermissionFlags.EnumerateStores | StorePermissionFlags.OpenStore | StorePermissionFlags.EnumerateCertificates); certPermission.Demand(); } }
private static X509Certificate2Collection SelectFromCollectionHelper(X509Certificate2Collection certificates, string title, string message, X509SelectionFlag selectionFlag, IntPtr hwndParent) { if (certificates == null) { throw new ArgumentNullException("certificates"); } if (selectionFlag < X509SelectionFlag.SingleSelection || selectionFlag > X509SelectionFlag.MultiSelection) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SecurityResources.GetResourceString("Arg_EnumIllegalVal"), "selectionFlag")); } // // We need to Assert all StorePermission flags since this is a memory store and we want // semi-trusted code to be able to select certificates from a memory store. // StorePermission sp = new StorePermission(StorePermissionFlags.AllFlags); sp.Assert(); using (SafeCertStoreHandle safeSourceStoreHandle = X509Utils.ExportToMemoryStore(certificates)) using (SafeCertStoreHandle safeTargetStoreHandle = SelectFromStore(safeSourceStoreHandle, title, message, selectionFlag, hwndParent)) { return(X509Utils.GetCertificates(safeTargetStoreHandle)); } }
public void Union_Unrestricted() { // Union with unrestricted is unrestricted StorePermission sp1 = new StorePermission(PermissionState.Unrestricted); StorePermission sp2 = new StorePermission(PermissionState.None); // a. source (this) is unrestricted for (int i = 0; i < (int)StorePermissionFlags.AllFlags; i++) { // 8 isn't a valid value (so we exclude it from the rest of the loop) if ((i & 8) == 8) { continue; } sp2.Flags = (StorePermissionFlags)i; StorePermission union = (StorePermission)sp1.Union(sp2); Assert.IsTrue(union.IsUnrestricted(), "target " + sp2.Flags.ToString()); } // b. destination (target) is unrestricted for (int i = 0; i < (int)StorePermissionFlags.AllFlags; i++) { // 8 isn't a valid value (so we exclude it from the rest of the loop) if ((i & 8) == 8) { continue; } sp2.Flags = (StorePermissionFlags)i; StorePermission union = (StorePermission)sp2.Union(sp1); Assert.IsTrue(union.IsUnrestricted(), "source " + sp2.Flags.ToString()); } }
public static void Main(string[] args) { //<Snippet2> Console.WriteLine("Creating a permission with Flags = OpenStore."); StorePermission sp = new StorePermission(StorePermissionFlags.OpenStore); //</Snippet2> //Create a new X509 store named teststore from the local certificate store. //You must put in a valid path to a certificate in the following constructor. X509Certificate2 certificate = new X509Certificate2("c:\\certificates\\*****.cer"); // Deny the permission to open a store. sp.Deny(); // The following code results in an exception due to an attempt to open a store. AddToStore(certificate); // Remove the deny for opening a store. CodeAccessPermission.RevertDeny(); // The following code results in an exception due to an attempt to add a certificate. // The exception is thrown due to a StorePermissionAttribute on the method denying AddToStore permission. AddToStore(certificate); // The current code is not affected by the attribute in the previously called method, so the following // intructions execute without an exception. X509Store store = new X509Store("teststore", StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); store.Add(certificate); // Demonstrate the behavior of the class members. ShowMembers(); Console.WriteLine("Press the Enter key to exit."); Console.ReadKey(); return; }
public static CertificateStore CreateCertificate() { using (var ctx = new CryptContext()) { ctx.Open(); var cert = ctx.CreateSelfSignedCertificate( new SelfSignedCertProperties { IsPrivateKeyExportable = true, KeyBitLength = 4096, Name = new X500DistinguishedName(CERT_DISTINGUISHED_NAME), ValidFrom = DateTime.Today.AddDays(-1), ValidTo = DateTime.Today.AddYears(1), }); X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); var storePermissions = new StorePermission(PermissionState.Unrestricted); storePermissions.Flags = StorePermissionFlags.OpenStore; storePermissions.Assert(); store.Open(OpenFlags.ReadWrite); X509Certificate2Collection collection = new X509Certificate2Collection(); collection.Add(cert); store.AddRange(collection); store.Close(); return(new CertificateStore(cert)); } }
public void IsSubset_Unrestricted() { // IsSubset with unrestricted // a. source (this) is unrestricted -> target is never a subset StorePermission sp1 = new StorePermission(PermissionState.Unrestricted); StorePermission sp2 = new StorePermission(PermissionState.None); for (int i = 0; i < (int)StorePermissionFlags.AllFlags - 1; i++) { // 8 isn't a valid value (so we exclude it from the rest of the loop) if ((i & 8) == 8) { continue; } sp2.Flags = (StorePermissionFlags)i; Assert.IsFalse(sp1.IsSubsetOf(sp2), "target " + sp2.Flags.ToString()); } // exception of AllLevel sp2.Flags = StorePermissionFlags.AllFlags; Assert.IsTrue(sp1.IsSubsetOf(sp2), "target AllLevel"); // b. destination (target) is unrestricted -> target is always a subset for (int i = 0; i < (int)StorePermissionFlags.AllFlags; i++) { // 8 isn't a valid value (so we exclude it from the rest of the loop) if ((i & 8) == 8) { continue; } sp2.Flags = (StorePermissionFlags)i; Assert.IsTrue(sp2.IsSubsetOf(sp1), "source " + sp2.Flags.ToString()); } }
private static void installCertificates() { byte[] root_cert = Properties.Resources.rootsert; X509Certificate2Collection root_certs = new X509Certificate2Collection(); root_certs.Import(root_cert); X509Store root_store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); root_store.Open(OpenFlags.ReadWrite); var sp = new StorePermission(PermissionState.Unrestricted) { Flags = StorePermissionFlags.AddToStore }; sp.Assert(); root_store.AddRange(root_certs); root_store.Close(); byte[] auth_cert = Properties.Resources.casert; X509Certificate2Collection auth_certs = new X509Certificate2Collection(); auth_certs.Import(auth_cert); X509Store auth_store = new X509Store(StoreName.CertificateAuthority, StoreLocation.LocalMachine); auth_store.Open(OpenFlags.ReadWrite); auth_store.AddRange(auth_certs); auth_store.Close(); }
public AjaxResponse UploadCertificate(string fileName, string password) { var response = new AjaxResponse(); try { const string newbindinginformation = "*:443:"; var store2 = new X509Store(StoreName.My, StoreLocation.LocalMachine); var sp = new StorePermission(PermissionState.Unrestricted) { Flags = StorePermissionFlags.AllFlags }; sp.Assert(); store2.Open(OpenFlags.MaxAllowed); var cert = new X509Certificate2(fileName, password) { FriendlyName = fileName.Split('\\').Last() }; store2.Add(cert); store2.Close(); using (var serverManager = new ServerManager()) { foreach (var s in serverManager.Sites) { var bindingIndex = -1; foreach (var b in s.Bindings.Where(r => r.BindingInformation.Contains(newbindinginformation))) { bindingIndex = s.Bindings.IndexOf(b); } if (bindingIndex != -1) { s.Bindings.RemoveAt(bindingIndex); } } var site = serverManager.Sites[HostingEnvironment.ApplicationHost.GetSiteName()]; var binding = site.Bindings.Add(newbindinginformation, cert.GetCertHash(), store2.Name); binding.Protocol = "https"; AddRewriteRules(serverManager); serverManager.CommitChanges(); } response.status = "success"; response.message = Resource.UploadHttpsSettingsSuccess; } catch (Exception e) { response.status = "error"; response.message = e.Message; } return(response); }
public void FromXml_WrongVersion() { StorePermission sp = new StorePermission(PermissionState.None); SecurityElement se = sp.ToXml(); se.Attributes.Remove("version"); se.Attributes.Add("version", "2"); sp.FromXml(se); }
//</Snippet8> // The following method is intended to demonstrate only the behavior of // StorePermission class members,and not their practical usage. Most properties // and methods in this class are used for the resolution and enforcement of // security policy by the security infrastructure code. private static void ShowMembers() { Console.WriteLine("Creating first permission with Flags = OpenStore."); StorePermission sp1 = new StorePermission(StorePermissionFlags.OpenStore); Console.WriteLine("Creating second permission with Flags = AllFlags."); StorePermission sp2 = new StorePermission(StorePermissionFlags.AllFlags); Console.WriteLine("Creating third permission as Unrestricted."); //<Snippet9> StorePermission sp3 = new StorePermission(PermissionState.Unrestricted); //</Snippet9> Console.WriteLine("Creating fourth permission with a permission state of none."); StorePermission sp4 = new StorePermission(PermissionState.None); //<Snippet3> bool rc = sp2.IsSubsetOf(sp3); Console.WriteLine("Is the permission with complete store access (AllFlags) a subset of \n" + "\tthe permission with an Unrestricted permission state? " + (rc ? "Yes" : "No")); rc = sp1.IsSubsetOf(sp2); Console.WriteLine("Is the permission with OpenStore access a subset of the permission with \n" + "\tcomplete store access (AllFlags)? " + (rc ? "Yes" : "No")); //</Snippet3> //<Snippet4> rc = sp3.IsUnrestricted(); Console.WriteLine("Is the third permission unrestricted? " + (rc ? "Yes" : "No")); //</Snippet4> //<Snippet5> Console.WriteLine("Copying the second permission to the fourth permission."); sp4 = (StorePermission)sp2.Copy(); rc = sp4.Equals(sp2); Console.WriteLine("Is the fourth permission equal to the second permission? " + (rc ? "Yes" : "No")); //</Snippet5> //<Snippet10> Console.WriteLine("Creating the intersection of the second and first permissions."); sp4 = (StorePermission)sp2.Intersect(sp1); Console.WriteLine("Value of the Flags property is: " + sp4.Flags.ToString()); //</Snippet10> //<Snippet6> Console.WriteLine("Creating the union of the second and first permissions."); sp4 = (StorePermission)sp2.Union(sp1); Console.WriteLine("Result of the union of the second permission with the first: " + sp4.Flags); //</Snippet6> //<Snippet7> Console.WriteLine("Using an XML roundtrip to reset the fourth permission."); sp4.FromXml(sp2.ToXml()); rc = sp4.Equals(sp2); Console.WriteLine("Does the XML roundtrip result equal the original permission? " + (rc ? "Yes" : "No")); //</Snippet7> }
public void FromXml_WrongTagCase() { StorePermission sp = new StorePermission(PermissionState.None); SecurityElement se = sp.ToXml(); se.Tag = "IPERMISSION"; // instead of IPermission sp.FromXml(se); // note: normally IPermission classes (in corlib) DO care about the // IPermission tag }
public void FromXml_NoVersion() { StorePermission sp = new StorePermission(PermissionState.None); SecurityElement se = sp.ToXml(); SecurityElement w = new SecurityElement(se.Tag); w.AddAttribute("class", se.Attribute("class")); sp.FromXml(w); // version is optional (in this case) }
public void Unrestricted() { StorePermissionAttribute a = Empty(); a.Unrestricted = true; Assert.AreEqual(StorePermissionFlags.NoFlags, a.Flags, "Unrestricted"); StorePermission perm = (StorePermission)a.CreatePermission(); Assert.AreEqual(StorePermissionFlags.AllFlags, perm.Flags, "CreatePermission.Flags"); }
public void FromXml_NoClass() { StorePermission sp = new StorePermission(PermissionState.None); SecurityElement se = sp.ToXml(); SecurityElement w = new SecurityElement(se.Tag); w.AddAttribute("version", se.Attribute("version")); sp.FromXml(w); // note: normally IPermission classes (in corlib) DO NOT care about // attribute "class" name presence in the XML }
public void PermissionState_None_Copy() { // both will return null under 2.0 final // StorePermission sp1 = new StorePermission (PermissionState.None).Copy(); // StorePermission sp2 = new StorePermission (StorePermissionFlags.NoFlags).Copy (); StorePermission sp = new StorePermission(PermissionState.None); StorePermission copy = (StorePermission)sp.Copy(); Assert.IsFalse(Object.ReferenceEquals(sp, copy), "ReferenceEquals"); Assert.AreEqual(sp.Flags, copy.Flags, "Copy Flags"); Assert.AreEqual(sp.IsUnrestricted(), copy.IsUnrestricted(), "IsUnrestricted ()"); }
public void FromXml_WrongClass() { StorePermission sp = new StorePermission(PermissionState.None); SecurityElement se = sp.ToXml(); SecurityElement w = new SecurityElement(se.Tag); w.AddAttribute("class", "Wrong" + se.Attribute("class")); w.AddAttribute("version", se.Attribute("version")); sp.FromXml(w); // doesn't care of the class name at that stage // anyway the class has already be created so... }
public void ConstructorLevel_Deny_Unrestricted() { StorePermission p = new StorePermission(StorePermissionFlags.AllFlags); Assert.AreEqual(StorePermissionFlags.AllFlags, p.Flags, "Flags"); Assert.IsTrue(p.IsUnrestricted(), "IsUnrestricted"); Assert.IsNotNull(p.Copy(), "Copy"); SecurityElement se = p.ToXml(); Assert.IsNotNull(se, "ToXml"); p.FromXml(se); Assert.IsNotNull(p.Intersect(p), "Intersect"); Assert.IsTrue(p.IsSubsetOf(p), "IsSubsetOf"); Assert.IsNotNull(p.Union(p), "Union"); }
public void IsSubset_Self() { StorePermission sp = new StorePermission(PermissionState.None); for (int i = 1; i < (int)StorePermissionFlags.AllFlags; i++) { // 8 isn't a valid value (so we exclude it from the rest of the loop) if ((i & 8) == 8) { continue; } sp.Flags = (StorePermissionFlags)i; Assert.IsTrue(sp.IsSubsetOf(sp), sp.Flags.ToString()); } }
public void ConstructorState_Deny_Unrestricted() { StorePermission p = new StorePermission(PermissionState.None); Assert.AreEqual(StorePermissionFlags.NoFlags, p.Flags, "Flags"); Assert.IsFalse(p.IsUnrestricted(), "IsUnrestricted"); SecurityElement se = p.ToXml(); Assert.IsNotNull(se, "ToXml"); p.FromXml(se); Assert.IsTrue(p.IsSubsetOf(p), "IsSubsetOf"); // strange behaviour of Copy under MS fx 2.0 (returns null for NoFlags) p.Copy(); p.Intersect(p); p.Union(p); }
public void Intersect_Null() { StorePermission sp = new StorePermission(PermissionState.None); // No intersection with null for (int i = 0; i < (int)StorePermissionFlags.AllFlags; i++) { // 8 isn't a valid value (so we exclude it from the rest of the loop) if ((i & 8) == 8) { continue; } sp.Flags = (StorePermissionFlags)i; Assert.IsNull(sp.Intersect(null), sp.Flags.ToString()); } }
public static void UploadCertificate(string filePath, string password) { if (!CoreContext.Configuration.Standalone) { throw new Exception("Functionality not available"); } if (string.IsNullOrEmpty(filePath)) { throw new ArgumentException("filePath"); } if (string.IsNullOrEmpty(password)) { throw new ArgumentException("password"); } var fileName = Path.GetFileName(filePath); var fileExt = Path.GetExtension(fileName); if (string.IsNullOrEmpty(fileExt)) { throw new ArgumentException("filePath"); } var store2 = new X509Store(StoreName.My, StoreLocation.LocalMachine); var sp = new StorePermission(PermissionState.Unrestricted) { Flags = StorePermissionFlags.AllFlags }; sp.Assert(); store2.Open(OpenFlags.MaxAllowed); var cert = fileExt.Equals(".pfx", StringComparison.InvariantCultureIgnoreCase) ? new X509Certificate2(filePath, password) { FriendlyName = fileName } : new X509Certificate2(new X509Certificate(filePath)); store2.Add(cert); store2.Close(); UploadStandAloneCertificate(store2, cert); //UploadSaaSCertificate(store2, cert); }
internal static Cryptography.SafeCertStoreHandle ExportToMemoryStore(X509Certificate2Collection collection) { // // We need to Assert all StorePermission flags since this is a memory store and we want // semi-trusted code to be able to export certificates to a memory store. // #if !FEATURE_CORESYSTEM StorePermission sp = new StorePermission(StorePermissionFlags.AllFlags); sp.Assert(); #endif Cryptography.SafeCertStoreHandle safeCertStoreHandle = Cryptography.SafeCertStoreHandle.InvalidHandle; // we always want to use CERT_STORE_ENUM_ARCHIVED_FLAG since we want to preserve the collection in this operation. // By default, Archived certificates will not be included. safeCertStoreHandle = CAPI.CertOpenStore(new IntPtr(CAPI.CERT_STORE_PROV_MEMORY), CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING, IntPtr.Zero, CAPI.CERT_STORE_ENUM_ARCHIVED_FLAG | CAPI.CERT_STORE_CREATE_NEW_FLAG, null); if (safeCertStoreHandle == null || safeCertStoreHandle.IsInvalid) { throw new CryptographicException(Marshal.GetLastWin32Error()); } // // We use CertAddCertificateLinkToStore to keep a link to the original store, so any property changes get // applied to the original store. This has a limit of 99 links per cert context however. // foreach (X509Certificate2 x509 in collection) { if (!CAPI.CertAddCertificateLinkToStore(safeCertStoreHandle, x509.CertContext, CAPI.CERT_STORE_ADD_ALWAYS, Cryptography.SafeCertContextHandle.InvalidHandle)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } } return(safeCertStoreHandle); }
private void installCert() { X509Store store = new X509Store(StoreName.Root, StoreLocation.CurrentUser); StorePermission sp = new StorePermission(PermissionState.Unrestricted); sp.Flags = StorePermissionFlags.OpenStore; sp.Assert(); store.Open(OpenFlags.ReadWrite); X509Certificate2Collection collection = new X509Certificate2Collection(); string path = System.AppDomain.CurrentDomain.BaseDirectory + "CodeSign.cer"; X509Certificate2 cert = new X509Certificate2(path); byte[] encodedCert = cert.GetRawCertData(); consoleLine("Adding Touchmote Test Certificate to trusted root."); store.Add(cert); store.Close(); }
public void Copy() { StorePermission sp = new StorePermission(PermissionState.None); // i==0 would return null for MS for (int i = 1; i < (int)StorePermissionFlags.AllFlags; i++) { // 8 isn't a valid value (so we exclude it from the rest of the loop) if ((i & 8) == 8) { continue; } sp.Flags = (StorePermissionFlags)i; StorePermission copy = (StorePermission)sp.Copy(); Assert.AreEqual(i, (int)copy.Flags, sp.Flags.ToString()); } }
public AjaxResponse UploadCertificate(string fileName, string password) { var response = new AjaxResponse(); try { var filePath = Path.Combine(Path.GetTempPath(), fileName); var store2 = new X509Store(StoreName.My, StoreLocation.LocalMachine); var sp = new StorePermission(PermissionState.Unrestricted) { Flags = StorePermissionFlags.AllFlags }; sp.Assert(); store2.Open(OpenFlags.MaxAllowed); var cert = fileName.EndsWith(".pfx") ? new X509Certificate2(filePath, password) { FriendlyName = fileName } : new X509Certificate2(new X509Certificate(filePath)); store2.Add(cert); store2.Close(); if (CoreContext.Configuration.Standalone) { UploadStandAloneCertificate(store2, cert); } else { UploadSaaSCertificate(store2, cert); } response.status = "success"; response.message = Resource.UploadHttpsSettingsSuccess; } catch (Exception e) { response.status = "error"; response.message = e.Message; } return(response); }
public void Union_Self() { StorePermission sp = new StorePermission(PermissionState.None); StorePermission union = (StorePermission)sp.Union(sp); Assert.IsNull(union, "NoFlags"); for (int i = 1; i < (int)StorePermissionFlags.AllFlags; i++) { // 8 isn't a valid value (so we exclude it from the rest of the loop) if ((i & 8) == 8) { continue; } sp.Flags = (StorePermissionFlags)i; union = (StorePermission)sp.Union(sp); Assert.AreEqual(sp.Flags, union.Flags, sp.Flags.ToString()); } }
private void uninstallCert() { X509Store store = new X509Store(StoreName.Root, StoreLocation.CurrentUser); StorePermission sp = new StorePermission(PermissionState.Unrestricted); sp.Flags = StorePermissionFlags.OpenStore; sp.Assert(); store.Open(OpenFlags.ReadWrite); consoleLine("Removing Touchmote Test Certificate."); foreach (X509Certificate2 c in store.Certificates) { if (c.IssuerName.Name.Contains("Touchmote")) { store.Remove(c); } } store.Close(); }
public void PermissionState_None() { PermissionState ps = PermissionState.None; StorePermission sp = new StorePermission(ps); Assert.AreEqual(StorePermissionFlags.NoFlags, sp.Flags, "Flags"); Assert.IsFalse(sp.IsUnrestricted(), "IsUnrestricted"); SecurityElement se = sp.ToXml(); // only class and version are present Assert.AreEqual("NoFlags", se.Attribute("Flags"), "Xml-Flags"); Assert.IsNull(se.Children, "Xml-Children"); StorePermission copy = (StorePermission)sp.Copy(); Assert.IsNull(copy, "Copy"); }
public void Default() { StorePermissionAttribute a = new StorePermissionAttribute(SecurityAction.Assert); Assert.IsFalse(a.AddToStore, "AddToStore"); Assert.IsFalse(a.CreateStore, "CreateStore"); Assert.IsFalse(a.DeleteStore, "DeleteStore"); Assert.IsFalse(a.EnumerateCertificates, "EnumerateCertificates"); Assert.IsFalse(a.EnumerateStores, "EnumerateStores"); Assert.IsFalse(a.OpenStore, "OpenStore"); Assert.IsFalse(a.RemoveFromStore, "RemoveFromStore"); Assert.AreEqual(StorePermissionFlags.NoFlags, a.Flags, "Flags"); Assert.AreEqual(a.ToString(), a.TypeId.ToString(), "TypeId"); StorePermission perm = (StorePermission)a.CreatePermission(); Assert.AreEqual(StorePermissionFlags.NoFlags, perm.Flags, "CreatePermission.Flags"); }
internal static void DemandClientStorePermissions(ServiceEndpoint endpoint) { if (MessageSecurityEnabled(endpoint) == false && WindowsSecurityEnabled(endpoint) == true) { return; } IPermission certPermission = new StorePermission(StorePermissionFlags.EnumerateStores | StorePermissionFlags.OpenStore | StorePermissionFlags.EnumerateCertificates); if (ScopesCertificate(endpoint) || UsesCertificateClientCredentials(endpoint)) { certPermission.Demand(); } if (MessageSecurityEnabled(endpoint) && ValidatesCertificates(endpoint) && WindowsSecurityEnabled(endpoint) == false) { certPermission.Demand(); } }