/// <summary> /// Checks whether the user can perform the specified action. /// </summary> /// <param name="userName">The name of the user that is being checked.</param> /// <param name="permission">The permission to check.</param> /// <param name="defaultRight">The default right to use.</param> /// <param name="manager"></param> /// <returns>True if the permission is valid, false otherwise.</returns> public virtual bool CheckPermission(ISecurityManager manager, string userName, SecurityPermission permission, SecurityRight defaultRight) { return true; }
public static void Main() { SecurityPermission perm = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode); // The method itself is attached with the security permission Deny // for unmanaged code, which will override the Assert permission in // this stack frame. However, because you are using // SuppressUnmanagedCodeSecurityAttribute, you can still call the // unmanaged methods successfully. // The code should use other security checks to ensure that you // don't incur a security hole. perm.Assert(); CallUnmanagedCodeWithoutPermission(); // The method itself is attached with the security permission // Assert for unmanaged code, which will override the Deny // permission in this stack frame. Because you are using // SuppressUnmanagedCodeSecurityAttribute, you can call the // unmanaged methods successfully. // The SuppressUnmanagedCodeSecurityAttribute will let you succeed, // even if you don't have a permission. perm.Deny(); CallUnmanagedCodeWithPermission(); }
/// <summary> /// Checks whether the user can perform the specified action. /// </summary> /// <param name="userName">The name of the user that is being checked.</param> /// <param name="permission">The permission to check.</param> /// <param name="defaultRight">The default right to use.</param> /// <param name="manager"></param> /// <returns>True if the permission is valid, false otherwise.</returns> public virtual bool CheckPermission(ISecurityManager manager, string userName, SecurityPermission permission, SecurityRight defaultRight) { return manager.CheckServerPermission(userName, permission); }
private static void CallUnmanagedCodeWithoutPermission() { // Create a security permission object to describe the // UnmanagedCode permission: SecurityPermission perm = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode); // Deny the UnmanagedCode from our current set of permissions. // Any method that is called on this thread until this method // returns will be denied access to unmanaged code. // Even though the CallUnmanagedCodeWithPermission method // is called from a stack frame that already // calls Assert for unmanaged code, you still cannot call native // code. Because you use Deny here, the permission gets // overwritten. perm.Deny(); try { Console.WriteLine("Attempting to call unmanaged code without permission."); NativeMethods.puts("Hello World!"); NativeMethods._flushall(); Console.WriteLine("Called unmanaged code without permission. Whoops!"); } catch (SecurityException) { Console.WriteLine("Caught Security Exception attempting to call unmanaged code."); } }
private static void CallUnmanagedCodeWithPermission() { // Create a security permission object to describe the // UnmanagedCode permission: SecurityPermission perm = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode); // Check that you have permission to access unmanaged code. // If you don't have permission to access unmanaged code, then // this call will throw a SecurityException. // Even though the CallUnmanagedCodeWithPermission method // is called from a stack frame that already // calls Assert for unmanaged code, you still cannot call native // code. Because you use Deny here, the permission gets // overwritten. perm.Assert(); try { Console.WriteLine("Attempting to call unmanaged code with permission."); NativeMethods.puts("Hello World!"); NativeMethods._flushall(); Console.WriteLine("Called unmanaged code with permission."); } catch (SecurityException) { Console.WriteLine("Caught Security Exception attempting to call unmanaged code. Whoops!"); } }
public static void Main() { // The method itself will call the security permission Deny // for unmanaged code, which will override the Assert permission // in this stack frame. SecurityPermission perm = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode); perm.Assert(); CallUnmanagedCodeWithoutPermission(); // The method itself will call the security permission Assert // for unmanaged code, which will override the Deny permission in // this stack frame. perm.Deny(); CallUnmanagedCodeWithPermission(); }
public static void Main() { SecurityPermission perm = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode); // The method itself is attached with the security permission // Deny for unmanaged code, which will override // the Assert permission in this stack frame. perm.Assert(); CallUnmanagedCodeWithoutPermission(); // The method itself is attached with the security permission // Assert for unmanaged code, which will override the Deny // permission in this stack frame. perm.Deny(); CallUnmanagedCodeWithPermission(); }
/// <summary> /// Checks the result of this permission. /// </summary> /// <param name="permission">The permission to check.</param> /// <param name="manager"></param> /// <returns>The security right.</returns> public virtual SecurityRight CheckPermission(ISecurityManager manager, SecurityPermission permission) { if (string.IsNullOrEmpty(refId)) { return CheckPermissionActual(manager, permission); } else { IPermission refPermission = manager.RetrievePermission(refId); if (refPermission == null) { throw new BadReferenceException(refId); } else { return refPermission.CheckPermission(manager, permission); } } }
public override void RemoveEventHandler(object target, Delegate handler) { if (Marshal.IsComObject(target)) { // retrieve sourceIid and dispid Guid sourceIid; int dispid; GetDataForComInvocation(_innerEventInfo, out sourceIid, out dispid); // now validate the caller can call into native and redirect to ComEventHelpers.Combine SecurityPermission perm = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode); perm.Demand(); System.Runtime.InteropServices.ComEventsHelper.Remove(target, sourceIid, dispid, handler); } else { // we are dealing with a managed object - just add the delegate through relection _innerEventInfo.RemoveEventHandler(target, handler); } }
internal void OpenFile(string fileName) { NativeMethods.SECURITY_ATTRIBUTES sa = new NativeMethods.SECURITY_ATTRIBUTES(); try { unsafe { // Disable PREsharp warning about not calling Marshal.GetLastWin32Error, // because we already check the handle for invalid value and // we are not particularly interested in specific Win32 error. #pragma warning disable 6523 long size; using (SafeFileHandle fileHandle = UnsafeNativeMethods.CreateFile( fileName, NativeMethods.GENERIC_READ, NativeMethods.FILE_SHARE_READ, null, NativeMethods.OPEN_EXISTING, 0, IntPtr.Zero )) { if (fileHandle.IsInvalid) { Util.ThrowWin32Exception(Marshal.GetLastWin32Error(), fileName); } UnsafeNativeMethods.LARGE_INTEGER fileSize = new UnsafeNativeMethods.LARGE_INTEGER(); if (!UnsafeNativeMethods.GetFileSizeEx(fileHandle, ref fileSize)) { throw new IOException(SR.Get(SRID.IOExceptionWithFileName, fileName)); } size = (long)fileSize.QuadPart; if (size == 0) { throw new FileFormatException(new Uri(fileName)); } _mappingHandle = UnsafeNativeMethods.CreateFileMapping( fileHandle, sa, UnsafeNativeMethods.PAGE_READONLY, 0, 0, null); } if (_mappingHandle.IsInvalid) { throw new IOException(SR.Get(SRID.IOExceptionWithFileName, fileName)); } _viewHandle = UnsafeNativeMethods.MapViewOfFileEx(_mappingHandle, UnsafeNativeMethods.FILE_MAP_READ, 0, 0, IntPtr.Zero, IntPtr.Zero); if (_viewHandle.IsInvalid) { throw new IOException(SR.Get(SRID.IOExceptionWithFileName, fileName)); } #pragma warning restore 6523 // Initialize() method demands UnmanagedCode permission, and OpenFile() is already marked as critical. new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert(); //Blessed Assert try { Initialize((byte *)_viewHandle.Memory, size, size, FileAccess.Read); } finally { SecurityPermission.RevertAssert(); } } } finally { sa.Release(); sa = null; } }
/// <summary> /// Checks to see if a session has the required right to perform a permission. /// </summary> /// <param name="sessionToken">The session to check.</param> /// <param name="projectName">The project the permission is for.</param> /// <param name="permission">The permission being checked.</param> /// <param name="eventType">The event type for logging.</param> /// <returns>The display name of the user if the permission is allowed.</returns> private string CheckSecurity(string sessionToken, string projectName, SecurityPermission permission, SecurityEvent? eventType) { // Retrieve the project authorisation IProjectAuthorisation authorisation = null; bool requiresSession = securityManager.RequiresSession; string userName = securityManager.GetUserName(sessionToken); string displayName = securityManager.GetDisplayName(sessionToken, null) ?? userName; if (!string.IsNullOrEmpty(projectName)) { IProjectIntegrator projectIntegrator = GetIntegrator(projectName); if ((projectIntegrator != null) && (projectIntegrator.Project != null) && (projectIntegrator.Project.Security != null)) { // The project has been found and it has security authorisation = projectIntegrator.Project.Security; requiresSession = authorisation.RequiresSession(securityManager); } else if ((projectIntegrator != null) && (projectIntegrator.Project != null) && (projectIntegrator.Project.Security == null)) { // The project is found, but security is missing - application error string errorMessage = string.Format("Security not found for project {0}", projectName); Log.Error(errorMessage); if (eventType.HasValue) { securityManager.LogEvent(projectName, userName, eventType.Value, SecurityRight.Deny, errorMessage); } throw new SecurityException(errorMessage); } else { // Couldn't find the requested project string errorMessage = string.Format("project not found {0}", projectName); Log.Error(errorMessage); if (eventType.HasValue) { securityManager.LogEvent(projectName, userName, eventType.Value, SecurityRight.Deny, errorMessage); } throw new NoSuchProjectException(projectName); } } if (!requiresSession || (userName != null)) { if (string.IsNullOrEmpty(projectName)) { // Checking server-level security if (!securityManager.CheckServerPermission(userName, permission)) { string info = string.Format("{2} [{0}] has been denied {1} permission at the server", userName, permission, displayName); Log.Warning(info); if (eventType.HasValue) { securityManager.LogEvent(projectName, userName, eventType.Value, SecurityRight.Deny, info); } throw new PermissionDeniedException(permission.ToString()); } else { string info = string.Format("{2} [{0}] has been granted {1} permission at the server", userName, permission, displayName); Log.Debug(info); if (eventType.HasValue) { securityManager.LogEvent(projectName, userName, eventType.Value, SecurityRight.Allow, info); } return displayName; } } else { // Checking project-level security if (!authorisation.CheckPermission(securityManager, userName, permission, securityManager.GetDefaultRight(permission))) { string info = string.Format("{3} [{0}] has been denied {1} permission on '{2}'", userName, permission, projectName, displayName); Log.Warning(info); if (eventType.HasValue) { securityManager.LogEvent(projectName, userName, eventType.Value, SecurityRight.Deny, info); } throw new PermissionDeniedException(permission.ToString()); } else { Log.Debug(string.Format("{3} [{0}] has been granted {1} permission on '{2}'", userName, permission, projectName, displayName)); if (eventType.HasValue) { securityManager.LogEvent(projectName, userName, eventType.Value, SecurityRight.Allow, null); } return displayName; } } } else { SecurityRight defaultRight = securityManager.GetDefaultRight(permission); switch (defaultRight) { case SecurityRight.Allow: Log.Debug(string.Format("{3} [{0}] has been granted {1} permission on '{2}'", userName, permission, projectName, displayName)); return string.Empty; default: // Tell the user that the session is unknown var info = string.Format("Session with token '{0}' is not valid", sessionToken); Log.Warning(info); if (eventType.HasValue) { securityManager.LogEvent(projectName, null, eventType.Value, SecurityRight.Deny, info); } throw new SessionInvalidException(); } } }
/// <summary> /// Removes user from reference list and frees the 7-zip library if it becomes empty /// </summary> /// <param name="user">Caller of the function</param> /// <param name="format">Archive format</param> public static void FreeLibrary(object user, Enum format) { #if !WINCE && !MONO var sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode); sp.Demand(); #endif lock (_syncRoot) { if (_modulePtr != IntPtr.Zero) { if (format is InArchiveFormat) { if (_inArchives != null && _inArchives.ContainsKey(user) && _inArchives[user].ContainsKey((InArchiveFormat)format) && _inArchives[user][(InArchiveFormat)format] != null) { try { Marshal.ReleaseComObject(_inArchives[user][(InArchiveFormat)format]); } catch (InvalidComObjectException) {} _inArchives[user].Remove((InArchiveFormat)format); _totalUsers--; if (_inArchives[user].Count == 0) { _inArchives.Remove(user); } } } #if COMPRESS if (format is OutArchiveFormat) { if (_outArchives != null && _outArchives.ContainsKey(user) && _outArchives[user].ContainsKey((OutArchiveFormat)format) && _outArchives[user][(OutArchiveFormat)format] != null) { try { Marshal.ReleaseComObject(_outArchives[user][(OutArchiveFormat)format]); } catch (InvalidComObjectException) {} _outArchives[user].Remove((OutArchiveFormat)format); _totalUsers--; if (_outArchives[user].Count == 0) { _outArchives.Remove(user); } } } #endif if ((_inArchives == null || _inArchives.Count == 0) #if COMPRESS && (_outArchives == null || _outArchives.Count == 0) #endif ) { _inArchives = null; #if COMPRESS _outArchives = null; #endif if (_totalUsers == 0) { #if !WINCE && !MONO NativeMethods.FreeLibrary(_modulePtr); #endif _modulePtr = IntPtr.Zero; } } } } }
internal static QuickCacheEntryType GenerateQuickCache(PolicyLevel level) { QuickCacheEntryType[] ExecutionMap = new QuickCacheEntryType[] { QuickCacheEntryType.ExecutionZoneMyComputer, QuickCacheEntryType.ExecutionZoneIntranet, QuickCacheEntryType.ExecutionZoneInternet, QuickCacheEntryType.ExecutionZoneTrusted, QuickCacheEntryType.ExecutionZoneUntrusted }; QuickCacheEntryType[] UnmanagedMap = new QuickCacheEntryType[] { QuickCacheEntryType.UnmanagedZoneMyComputer, QuickCacheEntryType.UnmanagedZoneIntranet, QuickCacheEntryType.UnmanagedZoneInternet, QuickCacheEntryType.UnmanagedZoneTrusted, QuickCacheEntryType.UnmanagedZoneUntrusted }; QuickCacheEntryType[] BindingRedirectMap = new QuickCacheEntryType[] { QuickCacheEntryType.BindingRedirectsZoneMyComputer, QuickCacheEntryType.BindingRedirectsZoneIntranet, QuickCacheEntryType.BindingRedirectsZoneInternet, QuickCacheEntryType.BindingRedirectsZoneTrusted, QuickCacheEntryType.BindingRedirectsZoneUntrusted }; QuickCacheEntryType[] SkipVerificationMap = new QuickCacheEntryType[] { QuickCacheEntryType.SkipVerificationZoneMyComputer, QuickCacheEntryType.SkipVerificationZoneIntranet, QuickCacheEntryType.SkipVerificationZoneInternet, QuickCacheEntryType.SkipVerificationZoneTrusted, QuickCacheEntryType.SkipVerificationZoneUntrusted }; QuickCacheEntryType[] FullTrustMap = new QuickCacheEntryType[] { QuickCacheEntryType.FullTrustZoneMyComputer, QuickCacheEntryType.FullTrustZoneIntranet, QuickCacheEntryType.FullTrustZoneInternet, QuickCacheEntryType.FullTrustZoneTrusted, QuickCacheEntryType.FullTrustZoneUntrusted }; QuickCacheEntryType accumulator = (QuickCacheEntryType)0; SecurityPermission execPerm = new SecurityPermission(SecurityPermissionFlag.Execution); SecurityPermission unmanagedPerm = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode); SecurityPermission skipVerifPerm = new SecurityPermission(SecurityPermissionFlag.SkipVerification); SecurityPermission bindingRedirectPerm = new SecurityPermission(SecurityPermissionFlag.BindingRedirects); Evidence noEvidence = new Evidence(); PermissionSet policy = null; try { policy = level.Resolve(noEvidence).PermissionSet; if (policy.Contains(execPerm)) { accumulator |= QuickCacheEntryType.ExecutionAll; } if (policy.Contains(unmanagedPerm)) { accumulator |= QuickCacheEntryType.UnmanagedAll; } if (policy.Contains(skipVerifPerm)) { accumulator |= QuickCacheEntryType.SkipVerificationAll; } if (policy.Contains(bindingRedirectPerm)) { accumulator |= QuickCacheEntryType.BindingRedirectsAll; } if (policy.IsUnrestricted()) { accumulator |= QuickCacheEntryType.FullTrustAll; } } catch (PolicyException) { } Array zones = Enum.GetValues(typeof(SecurityZone)); for (int i = 0; i < zones.Length; ++i) { if (((SecurityZone)zones.GetValue(i)) == SecurityZone.NoZone) { continue; } Evidence zoneEvidence = new Evidence(); zoneEvidence.AddHost(new Zone((SecurityZone)zones.GetValue(i))); PermissionSet zonePolicy = null; try { zonePolicy = level.Resolve(zoneEvidence).PermissionSet; if (zonePolicy.Contains(execPerm)) { accumulator |= ExecutionMap[i]; } if (zonePolicy.Contains(unmanagedPerm)) { accumulator |= UnmanagedMap[i]; } if (zonePolicy.Contains(skipVerifPerm)) { accumulator |= SkipVerificationMap[i]; } if (zonePolicy.Contains(bindingRedirectPerm)) { accumulator |= BindingRedirectMap[i]; } if (zonePolicy.IsUnrestricted()) { accumulator |= FullTrustMap[i]; } } catch (PolicyException) { } } return(accumulator); }
/// <remarks/> public void GetRightAsync(string strDatabase, string strItem, string strAccount, SecurityPermission rightState, Credentials credentials, object userState) { if ((this.GetRightOperationCompleted == null)) { this.GetRightOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetRightOperationCompleted); } this.InvokeAsync("GetRight", new object[] { strDatabase, strItem, strAccount, rightState, credentials}, this.GetRightOperationCompleted, userState); }
/// <summary> /// Checks whether the user can perform the specified action at the server level. /// </summary> /// <param name="userName">The name of the user that is being checked.</param> /// <param name="permission">The permission to check.</param> /// <returns>True if the permission is valid, false otherwise.</returns> public override bool CheckServerPermission(string userName, SecurityPermission permission) { SecurityRight currentRight = SecurityRight.Inherit; // Iterate through the permissions stopping when we hit the first non-inherited permission foreach (IPermission permissionToCheck in permissions) { if (permissionToCheck.CheckUser(this, userName)) currentRight = permissionToCheck.CheckPermission(this, permission); if (currentRight != SecurityRight.Inherit) break; } // If we don't have a result, then use the default right if (currentRight == SecurityRight.Inherit) currentRight = GetDefaultRight(permission); return (currentRight == SecurityRight.Allow); }
public static void SecurityPermissionCallMethods() { SecurityPermission sp = new SecurityPermission(new Permissions.PermissionState()); SecurityPermission sp2 = new SecurityPermission(new Permissions.SecurityPermissionFlag()); IPermission ip = sp.Copy(); IPermission ip2 = sp.Intersect(ip); bool testbool = sp.IsSubsetOf(ip); testbool = sp.IsUnrestricted(); ip2 = sp.Union(ip); SecurityElement se = new SecurityElement(""); sp.FromXml(se); se = sp.ToXml(); }
/// <include file='doc\SoapServerTlb.uex' path='docs/doc[@for="SoapServerTlb.AddServerTlb"]/*' /> public void AddServerTlb( string progId, string classId, string interfaceId, string srcTlbPath, string rootWebServer, string inBaseUrl, string inVirtualRoot, string clientActivated, string wellKnown, string discoFile, string operation, out string strAssemblyName, out string typeName ) { strAssemblyName = ""; typeName = ""; bool bDelete = false; //these are the defaults for these flags bool bDiscoFile = false; bool bWellKnown = false; bool bClientActivated = true; try { try { SecurityPermission sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode); sp.Demand(); } catch (Exception e) { if (e.GetType() == typeof(System.Security.SecurityException)) { string Error = Resource.FormatString("Soap_SecurityFailure"); ComSoapPublishError.Report(Error); } throw; } Platform.Assert(Platform.Whistler, "SoapServerTlb.AddServerTlb"); if (null != operation && operation.ToLower(CultureInfo.InvariantCulture) == "delete") { bDelete = true; } //if ProgId is an empty string, it means it does not go in the configuration file if (srcTlbPath.Length <= 0) { return; } bDiscoFile = SoapServerInfo.BoolFromString(discoFile, bDiscoFile); bWellKnown = SoapServerInfo.BoolFromString(wellKnown, bWellKnown); bClientActivated = SoapServerInfo.BoolFromString(clientActivated, bClientActivated); string PhysicalPath = SoapServerInfo.ServerPhysicalPath(rootWebServer, inBaseUrl, inVirtualRoot, !bDelete); string srcdll = srcTlbPath.ToLower(CultureInfo.InvariantCulture); if (srcdll.EndsWith("mscoree.dll")) { Type typ = Type.GetTypeFromProgID(progId); typeName = typ.FullName; Assembly assem = typ.Assembly; AssemblyName assemname = assem.GetName(); strAssemblyName = assemname.Name; } else if (srcdll.EndsWith("scrobj.dll")) { if (!bDelete) { throw new ServicedComponentException(Resource.FormatString("ServicedComponentException_WSCNotSupported")); } } else { string Error = ""; GenerateMetadata metaGen = new GenerateMetadata(); if (bDelete) { strAssemblyName = metaGen.GetAssemblyName(srcTlbPath, PhysicalPath + "\\bin\\"); } else { strAssemblyName = metaGen.GenerateSigned(srcTlbPath, PhysicalPath + "\\bin\\", false, out Error); } if (strAssemblyName.Length > 0) { try { //TODO - review GetTypeNameFromProgId to determine if we can use the IID // to simplify the logic typeName = GetTypeName(PhysicalPath + "\\bin\\" + strAssemblyName + ".dll", progId, classId); } catch (Exception e) { if (bDelete && e.GetType() != typeof(System.IO.DirectoryNotFoundException) && e.GetType() != typeof(System.IO.FileNotFoundException)) { throw; } } } } // pull the generated Assembly.Type from the assembly for configuration files if (progId.Length > 0 && strAssemblyName.Length > 0 && typeName.Length > 0) { // write to the server configuration files DiscoFile objDiscoFile = new DiscoFile(); string strFileName = PhysicalPath + "\\bin\\" + strAssemblyName + ".dll"; if (bDelete) { SoapServerConfig.DeleteComponent(PhysicalPath + "\\Web.Config", strAssemblyName, typeName, progId, strFileName); objDiscoFile.DeleteElement(PhysicalPath + "\\Default.disco", progId + ".soap?WSDL"); // we have no way of telling from a single component what other components are in this type library // metadata assembly. If we remove from GAC or delete we kill all the other components simultaneously //GacRemove(strFileName); //File.Delete(strFileName); } else { SoapServerConfig.AddComponent(PhysicalPath + "\\Web.Config", strAssemblyName, typeName, progId, strFileName, "SingleCall", bWellKnown, bClientActivated); if (bDiscoFile) { objDiscoFile.AddElement(PhysicalPath + "\\Default.disco", progId + ".soap?WSDL"); } } } } catch (Exception e) { string Error = Resource.FormatString("Soap_PublishServerTlbFailure"); ComSoapPublishError.Report(Error); if (typeof(ServicedComponentException) == e.GetType() || typeof(RegistrationException) == e.GetType()) { throw; } } }
/// <summary> /// Checks to see if a session has the required right to perform a permission. /// </summary> /// <param name="userName">The user to check.</param> /// <param name="projectName">The project the permission is for.</param> /// <param name="permission">The permission being checked.</param> /// <returns>True if the permission is allowed, false otherwise.</returns> private bool DiagnosePermission(string userName, string projectName, SecurityPermission permission) { bool isAllowed = false; if (userName != null) { if (string.IsNullOrEmpty(projectName)) { isAllowed = securityManager.CheckServerPermission(userName, permission); } else { IProjectIntegrator projectIntegrator = GetIntegrator(projectName); if ((projectIntegrator != null) && (projectIntegrator.Project != null) && (projectIntegrator.Project.Security != null)) { IProjectAuthorisation authorisation = projectIntegrator.Project.Security; isAllowed = authorisation.CheckPermission(securityManager, userName, permission, securityManager.GetDefaultRight(permission)); } } } return isAllowed; }
private static void CreateDepartmentPermission() { IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy(); // Move through the policy levels to the Machine policy level. while(policyEnumerator.MoveNext()) { PolicyLevel currentLevel = (PolicyLevel)policyEnumerator.Current; if(currentLevel.Label == "Machine") { // Enumerate the permission sets in the Machine level. IList namedPermissions = currentLevel.NamedPermissionSets; IEnumerator namedPermission = namedPermissions.GetEnumerator(); // Locate the Everything permission set. while(namedPermission.MoveNext()) { if(((NamedPermissionSet)namedPermission.Current).Name == "Everything") { // The current permission set is a copy of the Everything permission set. // It can be modified to provide the permissions for the new permission set. // Rename the copy to the name chosen for the new permission set. ((NamedPermissionSet)namedPermission.Current).Name = "MyDepartment"; IEnumerator permissions = ((NamedPermissionSet)namedPermission.Current).GetEnumerator(); // Modify security permission by removing and replacing with a new permission. while(permissions.MoveNext()) { if(permissions.Current.GetType().ToString() == "System.Security.Permissions.SecurityPermission") { ((NamedPermissionSet)namedPermission.Current).RemovePermission(permissions.Current.GetType()); // Add a new security permission with limited permissions. SecurityPermission limitedPermission = new SecurityPermission(SecurityPermissionFlag.Execution | SecurityPermissionFlag.RemotingConfiguration | SecurityPermissionFlag.ControlThread); ((NamedPermissionSet)namedPermission.Current).AddPermission(limitedPermission); break; } } try { // If you run this application twice, the following instruction throws // an exception because the named permission set is already present. // You can remove the custom named permission set using Caspole.exe or the // .NET Framework Configuration tool currentLevel.AddNamedPermissionSet(((NamedPermissionSet)namedPermission.Current)); SecurityManager.SavePolicy(); } catch (System.ArgumentException e) { Console.WriteLine(e.Message); } Console.WriteLine(((NamedPermissionSet)namedPermission.Current).ToString()); break; } } } } }
/// <summary> /// Encapsulates the code to process a request. /// </summary> /// <param name="request"></param> /// <param name="permission"></param> /// <param name="eventType"></param> /// <param name="action"></param> /// <returns></returns> private Response RunProjectRequest(ProjectRequest request, SecurityPermission? permission, SecurityEvent? eventType, ProjectRequestAction action) { var response = new Response(request); try { // Validate the request and check the security token ValidateRequest(request); if (permission.HasValue) { CheckSecurity(request.SessionToken, request.ProjectName, permission.Value, eventType); } // Perform the actual action action(request, response); if (response.Result == ResponseResult.Unknown) { response.Result = ResponseResult.Success; } } catch (Exception error) { // Log any errors to help diagnosing issues Log.Warning(error); response.Result = ResponseResult.Failure; response.ErrorMessages.Add( new ErrorMessage( error.Message, error.GetType().Name)); } return response; }
/// <summary> /// Retrieves the actual permission. /// </summary> /// <param name="permission"></param> /// <returns></returns> public SecurityRight GetPermission(SecurityPermission permission) { var right = SecurityRight.Inherit; switch (permission) { case SecurityPermission.ViewProject: right = ViewProjectRight; break; case SecurityPermission.ViewConfiguration: right = ViewConfigurationRight; break; case SecurityPermission.ForceAbortBuild: right = ForceBuildRight; break; case SecurityPermission.SendMessage: right = SendMessageRight; break; case SecurityPermission.StartStopProject: right = StartProjectRight; break; case SecurityPermission.ChangeProjectConfiguration: right = ChangeProjectRight; break; case SecurityPermission.ViewSecurity: right = ViewSecurityRight; break; case SecurityPermission.ModifySecurity: right = ModifySecurityRight; break; } if (right == SecurityRight.Inherit) right = DefaultRight; return right; }
/// <summary> /// /// </summary> /// <param name="systemID"></param> /// <param name="moduleID"></param> /// <param name="employeeID"></param> /// <returns></returns> public SecurityPermissionCollection ModulePermissions(string systemID, string moduleID, string employeeID) { SecurityPermissionCollection collection = new SecurityPermissionCollection(); Poxy.SecurityPermission[] permissions = this.service.ModulePermissions(systemID, moduleID, employeeID); if (permissions != null && permissions.Length > 0) { foreach (Poxy.SecurityPermission sp in permissions) { SecurityPermission securityPermission = new SecurityPermission(); securityPermission.PermissionID = new GUIDEx(sp.PermissionID); securityPermission.PermissionName = sp.PermissionName; collection.Add(securityPermission); } } return collection; }
/// <summary> /// Checks the result of this permission. /// </summary> /// <param name="permission">The permission to check.</param> /// <param name="manager"></param> /// <returns>The security right.</returns> protected virtual SecurityRight CheckPermissionActual(ISecurityManager manager, SecurityPermission permission) { return GetPermission(permission); }
public string GetRight(string strDatabase, string strItem, string strAccount, SecurityPermission rightState, Sitecore.SecurityModel.Credentials credentials) { Error.AssertString(strDatabase, "strDatabase", false); Error.AssertString(strItem, "strItem", false); Login(credentials); Sitecore.Data.Database db = Sitecore.Configuration.Factory.GetDatabase(strDatabase); Sitecore.Data.Items.Item item = db.GetItem(strItem); if (strAccount.IndexOf("sitecore\\") == -1) strAccount = "sitecore\\" + strAccount; Sitecore.Security.Accounts.AccountType accountType = Sitecore.Security.Accounts.AccountType.User; if (Sitecore.Security.SecurityUtility.IsRole(strAccount)) { accountType = Sitecore.Security.Accounts.AccountType.Role; } Sitecore.Security.Accounts.Account account = Sitecore.Security.Accounts.Account.FromName(strAccount, accountType); string sResults = ""; if (rightState == SecurityPermission.AllowAccess) { if (item.Security.CanAdmin(account)) sResults += AccessRight.ItemAdmin + "|"; if (item.Security.CanCreate(account)) sResults += AccessRight.ItemCreate + "|"; if (item.Security.CanDelete(account)) sResults += AccessRight.ItemDelete + "|"; if (item.Security.CanRead(account)) sResults += AccessRight.ItemRead + "|"; if (item.Security.CanRename(account)) sResults += AccessRight.ItemRename + "|"; if (item.Security.CanWrite(account)) sResults += AccessRight.ItemWrite + "|"; } else if (rightState == SecurityPermission.DenyAccess) { if (!item.Security.CanAdmin(account)) sResults += AccessRight.ItemAdmin + "|"; if (!item.Security.CanCreate(account)) sResults += AccessRight.ItemCreate + "|"; if (!item.Security.CanDelete(account)) sResults += AccessRight.ItemDelete + "|"; if (!item.Security.CanRead(account)) sResults += AccessRight.ItemRead + "|"; if (!item.Security.CanRename(account)) sResults += AccessRight.ItemRename + "|"; if (!item.Security.CanWrite(account)) sResults += AccessRight.ItemWrite + "|"; } return sResults; }
/// <summary> /// Checks whether the user can perform the specified action. /// </summary> /// <param name="userName">The name of the user that is being checked.</param> /// <param name="permission">The permission to check.</param> /// <param name="defaultRight">The default right to use.</param> /// <param name="manager"></param> /// <returns>True if the permission is valid, false otherwise.</returns> public virtual bool CheckPermission(ISecurityManager manager, string userName, SecurityPermission permission, SecurityRight defaultRight) { SecurityRight currentRight = SecurityRight.Inherit; // Iterate through the assertions stopping when we hit the first non-inherited permission foreach (IPermission assertion in permissions) { if (assertion.CheckUser(manager, userName)) currentRight = assertion.CheckPermission(manager, permission); if (currentRight != SecurityRight.Inherit) break; } // If we don't have a result, then use the default right if (currentRight == SecurityRight.Inherit) currentRight = this.defaultRight; if (currentRight == SecurityRight.Inherit) currentRight = defaultRight; return (currentRight == SecurityRight.Allow); }
private void Serialize(SoapFormatter formatter, MemoryStream stream, Object value) { SecurityPermission perm = new SecurityPermission(SecurityPermissionFlag.SerializationFormatter); perm.Deny(); formatter.Serialize(stream, value); }
/// <summary> /// Encapsulates the code to process a request. /// </summary> /// <param name="request"></param> /// <param name="permission"></param> /// <param name="eventType"></param> /// <param name="action"></param> /// <returns></returns> private Response RunServerRequest(ServerRequest request, SecurityPermission? permission, SecurityEvent? eventType, Action<ServerRequest> action) { Response response = new Response(request); try { // Validate the request and check the security token ValidateRequest(request); if (permission.HasValue) { CheckSecurity(request.SessionToken, null, permission.Value, eventType); } // Perform the actual action action(request); response.Result = ResponseResult.Success; } catch (Exception error) { // Security exceptions have already been logged, just need to log any other exception if (!(error is SecurityException)) { Log.Warning(error); } // Tell the caller the request failed and include the error message (but not the stack trace!) response.Result = ResponseResult.Failure; response.ErrorMessages.Add( new ErrorMessage( error.Message, error.GetType().Name)); } return response; }
private Object Deserialize(SoapFormatter formatter, MemoryStream stream) { SecurityPermission perm = new SecurityPermission(SecurityPermissionFlag.SerializationFormatter); perm.Deny(); return formatter.Deserialize(stream); }
/// <summary> /// Checks to see if a session has the required right to perform a permission. /// </summary> /// <param name="sessionToken">The session to check.</param> /// <param name="projectName">The project the permission is for.</param> /// <param name="permission">The permission being checked.</param> /// <param name="eventType">The event type for logging.</param> private void CheckSecurity(string sessionToken, string projectName, SecurityPermission permission, SecurityEvent? eventType) { // NASTY HACK: Bypass all security if the session override is being used if (sessionToken == SecurityOverride.SessionIdentifier) { return; } // Retrieve the project authorisation IProjectAuthorisation authorisation = null; bool requiresSession = securityManager.RequiresSession; string userName = securityManager.GetUserName(sessionToken); string displayName = securityManager.GetDisplayName(sessionToken, null) ?? userName; if (!string.IsNullOrEmpty(projectName)) { IProjectIntegrator projectIntegrator = GetIntegrator(projectName); if ((projectIntegrator != null) && (projectIntegrator.Project != null) && (projectIntegrator.Project.Security != null)) { // The project has been found and it has security authorisation = projectIntegrator.Project.Security; requiresSession = authorisation.RequiresSession(securityManager); // if "Guest" have some rights, the service must be able to check the // rights for "Guest", but without userName it wont work. if (string.IsNullOrEmpty(userName)) userName = authorisation.GuestAccountName; } else if ((projectIntegrator != null) && (projectIntegrator.Project != null) && (projectIntegrator.Project.Security == null)) { // The project is found, but security is missing - application error string errorMessage = string.Format(CultureInfo.CurrentCulture, "Security not found for project {0}", projectName); Log.Error(errorMessage); if (eventType.HasValue) { securityManager.LogEvent(projectName, userName, eventType.Value, SecurityRight.Deny, errorMessage); } throw new SecurityException(errorMessage); } else { // Couldn't find the requested project string errorMessage = string.Format(CultureInfo.CurrentCulture, "project not found {0}", projectName); Log.Error(errorMessage); if (eventType.HasValue) { securityManager.LogEvent(projectName, userName, eventType.Value, SecurityRight.Deny, errorMessage); } throw new NoSuchProjectException(projectName); } } if (!requiresSession || (userName != null)) { if (string.IsNullOrEmpty(projectName)) { // Checking server-level security if (!securityManager.CheckServerPermission(userName, permission)) { string info = string.Format(CultureInfo.CurrentCulture, "{2} [{0}] has been denied {1} permission at the server", userName, permission, displayName); Log.Warning(info); if (eventType.HasValue) { securityManager.LogEvent(projectName, userName, eventType.Value, SecurityRight.Deny, info); } throw new PermissionDeniedException(permission.ToString()); } else { string info = string.Format(CultureInfo.CurrentCulture, "{2} [{0}] has been granted {1} permission at the server", userName, permission, displayName); Log.Debug(info); if (eventType.HasValue) { securityManager.LogEvent(projectName, userName, eventType.Value, SecurityRight.Allow, info); } return; } } else { // Checking project-level security if (!authorisation.CheckPermission(securityManager, userName, permission, securityManager.GetDefaultRight(permission))) { string info = string.Format(CultureInfo.CurrentCulture, "{3} [{0}] has been denied {1} permission on '{2}'", userName, permission, projectName, displayName); Log.Warning(info); if (eventType.HasValue) { securityManager.LogEvent(projectName, userName, eventType.Value, SecurityRight.Deny, info); } throw new PermissionDeniedException(permission.ToString()); } else { Log.Debug(string.Format(CultureInfo.CurrentCulture, "{3} [{0}] has been granted {1} permission on '{2}'", userName, permission, projectName, displayName)); if (eventType.HasValue) { securityManager.LogEvent(projectName, userName, eventType.Value, SecurityRight.Allow, null); } return; } } } else { SecurityRight defaultRight = securityManager.GetDefaultRight(permission); switch (defaultRight) { case SecurityRight.Allow: Log.Debug(string.Format(CultureInfo.CurrentCulture, "{3} [{0}] has been granted {1} permission on '{2}'", userName, permission, projectName, displayName)); return; default: // Tell the user that the session is unknown var info = string.Format(CultureInfo.CurrentCulture, "Session with token '{0}' is not valid", sessionToken); Log.Warning(info); if (eventType.HasValue) { securityManager.LogEvent(projectName, null, eventType.Value, SecurityRight.Deny, info); } throw new SessionInvalidException(); } } }
private void ConstructOM() { SecurityPermission perm = new SecurityPermission(SecurityPermissionFlag.SerializationFormatter); perm.Deny(); ObjectManager manager = new ObjectManager(null, new StreamingContext(StreamingContextStates.All)); }
public void ShouldSetItemAccessRules(string propertyName, string accessRight, bool actualPermission, SecurityPermission expectedPermission, string expectedSecurity) { // arrange var user = User.FromName(@"extranet\John", false); using (new UserSwitcher(user)) using (new SecurityDisabler()) using (var db = new Db()) { var dbitem = new DbItem("home"); ReflectionUtil.SetProperty(dbitem.Access, propertyName, actualPermission); // act db.Add(dbitem); var item = db.GetItem("/sitecore/content/home"); // assert item["__Security"].Should().Be(expectedSecurity); } }
public string GetRight(string strDatabase, string strItem, string strAccount, SecurityPermission rightState, Credentials credentials) { object[] results = this.Invoke("GetRight", new object[] { strDatabase, strItem, strAccount, rightState, credentials}); return ((string)(results[0])); }
/// <remarks/> public void GetRightAsync(string strDatabase, string strItem, string strAccount, SecurityPermission rightState, Credentials credentials) { this.GetRightAsync(strDatabase, strItem, strAccount, rightState, credentials, null); }
/// <include file='doc\SoapServerTlb.uex' path='docs/doc[@for="SoapServerTlb.DeleteServerTlb"]/*' /> public void DeleteServerTlb( string progId, string classId, string interfaceId, string srcTlbPath, string rootWebServer, string baseUrl, string virtualRoot, string operation, string assemblyName, string typeName ) { try { SecurityPermission sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode); sp.Demand(); } catch (Exception e) { if (e.GetType() == typeof(System.Security.SecurityException)) { string Error = Resource.FormatString("Soap_SecurityFailure"); ComSoapPublishError.Report(Error); } throw; } Platform.Assert(Platform.Whistler, "SoapServerTlb.DeleteServerTlb"); string strAssemblyName = assemblyName; if (progId.Length <= 0 && classId.Length <= 0 && assemblyName.Length <= 0 && typeName.Length <= 0) { return; } if (baseUrl.Length <= 0 && virtualRoot.Length <= 0) { return; } string PhysicalPath = SoapServerInfo.ServerPhysicalPath(rootWebServer, baseUrl, virtualRoot, false); string srcdll = srcTlbPath.ToLower(CultureInfo.InvariantCulture); if (srcdll.EndsWith("scrobj.dll")) { return; //not supported, nothing to do } if (srcdll.EndsWith("mscoree.dll")) { Type typ = Type.GetTypeFromProgID(progId); typeName = typ.FullName; Assembly assem = typ.Assembly; AssemblyName assemname = assem.GetName(); strAssemblyName = assemname.Name; } else { GenerateMetadata metaGen = new GenerateMetadata(); strAssemblyName = metaGen.GetAssemblyName(srcTlbPath, PhysicalPath + "\\bin\\"); if (strAssemblyName.Length > 0) { try { //TODO - review GetTypeNameFromProgId to determine if we can use the IID // to simplify the logic typeName = GetTypeName(PhysicalPath + "\\bin\\" + strAssemblyName + ".dll", progId, classId); } catch (Exception e) { if (e.GetType() != typeof(System.IO.DirectoryNotFoundException) && e.GetType() != typeof(System.IO.FileNotFoundException)) { throw; } } } } // pull the generated Assembly.Type from the assembly for configuration files if (progId.Length > 0 && strAssemblyName.Length > 0 && typeName.Length > 0) { // write to the server configuration files DiscoFile discoFile = new DiscoFile(); string strFileName = PhysicalPath + "\\bin\\" + strAssemblyName + ".dll"; SoapServerConfig.DeleteComponent(PhysicalPath + "\\Web.Config", strAssemblyName, typeName, progId, strFileName); discoFile.DeleteElement(PhysicalPath + "\\Default.disco", progId + ".soap?WSDL"); // we have no way of telling from a single component what other components are in this type library // metadata assembly. If we remove from GAC or delete we kill all the other components simultaneously //GacRemove(strFileName); //File.Delete(strFileName); } }