/// <summary> /// 设置Everyone的写入权限 /// </summary> static void SetControls(FileInfo file) { var everyOneIdentity = new NTAccount("Everyone"); var everyoneAce = new FileSystemAccessRule(everyOneIdentity, FileSystemRights.Write, AccessControlType.Allow); var securityDescriptor = new FileSecurity(); securityDescriptor.SetAccessRule(everyoneAce); file.SetAccessControl(securityDescriptor); }
public void setOwner() { IdentityReference owner = new NTAccount(userAccountPath); DirectoryInfo directory = new DirectoryInfo(textPath.Text); DirectorySecurity directorySecurity = directory.GetAccessControl(); directorySecurity.SetOwner(owner); directory.SetAccessControl(directorySecurity); }
protected void btnUndelegate_Click(object sender, EventArgs e) { NTAccount delegatedNTAccount = new NTAccount("ProductManager1"); SecurityIdentifier delegatedSid = (SecurityIdentifier)delegatedNTAccount.Translate(typeof(SecurityIdentifier)); IAzManItem item = this.application["Controllo del Budget"]; item.DeleteDelegateAuthorization(this.identity, new SqlAzManSID(delegatedSid), RestrictedAuthorizationType.Allow); this.btnDelegateForBudgetCheck.Enabled = true; this.btnUndelegate.Enabled = false; }
static CompressedFile() { sidAdminGroup = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null); ntAdminGroup = (NTAccount)sidAdminGroup.Translate(typeof(NTAccount)); sidTrustedInstaller = new SecurityIdentifier(TrustedInstallerAccountSid); ntTrustedInstaller = (NTAccount)sidTrustedInstaller.Translate(typeof(NTAccount)); sidUsersGroup = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null); driversPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "drivers"); }
/// <summary> /// Returns the SID of the currently logged in user that is running the installer, /// which may differ from the current user context because the installer may be /// impersonating an elevated user on behalf of the logged in user. /// </summary> /// <param name="logger"></param> /// <param name="note"></param> /// <returns></returns> public static string GetUserSid(string note) { var domain = Environment.GetEnvironmentVariable("USERDOMAIN"); var username = Environment.GetEnvironmentVariable("USERNAME"); var userdom = domain != null ? $@"{domain.ToUpper()}\{username.ToLower()}" : username.ToLower(); logger?.WriteLine($"translating user {userdom} to SID"); var tries = 0; while (tries <= 2) { try { var account = new NTAccount(userdom); var sid = ((SecurityIdentifier)account.Translate(typeof(SecurityIdentifier))).ToString(); logger?.WriteLine($"{note} for user {userdom} ({sid})"); return(sid); } catch (Exception exc) { tries++; logger?.WriteLine($"error translating, retrying {tries} of 2"); logger?.WriteLine(exc); System.Threading.Thread.Sleep(200 * tries); } } logger?.WriteLine("fallback to search username in HKEY_USERS"); foreach (var sid in Registry.Users.GetSubKeyNames()) { var key = Registry.Users.OpenSubKey($@"{sid}\Volatile Environment"); if (key != null) { var vname = key.GetValue("USERNAME") as string; if (!string.IsNullOrEmpty(vname)) { var vdomain = key.GetValue("USERDOMAIN") as string; var candidate = !string.IsNullOrEmpty(vdomain) ? $@"{vdomain.ToUpper()}\{vname.ToLower()}" : vname.ToLower(); if (candidate == userdom) { return(sid); } } } } return(null); }
/// <summary> /// Adds a reservation to the list of reserved URLs /// </summary> /// <param name="urlPrefix">The prefix of the URL to reserve.</param> /// <param name="user">The user with which to reserve the URL.</param> internal static void AddReservation(string urlPrefix, string user) { NTAccount account = new NTAccount(user); SecurityIdentifier sid = (SecurityIdentifier)account.Translate(typeof(SecurityIdentifier)); string sddl = GenerateSddl(sid); ErrorCode retVal = ErrorCode.Success; // NOERROR = 0 retVal = NativeMethods.HttpInitialize(HttpApiConstants.Version1, HttpApiConstants.InitializeConfig, IntPtr.Zero); if (ErrorCode.Success == retVal) { HttpServiceConfigUrlAclKey keyDesc = new HttpServiceConfigUrlAclKey(urlPrefix); HttpServiceConfigUrlAclParam paramDesc = new HttpServiceConfigUrlAclParam(sddl); HttpServiceConfigUrlAclSet inputConfigInfoSet = new HttpServiceConfigUrlAclSet(); inputConfigInfoSet.KeyDesc = keyDesc; inputConfigInfoSet.ParamDesc = paramDesc; IntPtr inputConfigInfoBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(HttpServiceConfigUrlAclSet))); Marshal.StructureToPtr(inputConfigInfoSet, inputConfigInfoBuffer, false); retVal = NativeMethods.HttpSetServiceConfiguration( IntPtr.Zero, HttpServiceConfigId.HttpServiceConfigUrlAclInfo, inputConfigInfoBuffer, Marshal.SizeOf(inputConfigInfoSet), IntPtr.Zero); if (ErrorCode.AlreadyExists == retVal) { retVal = NativeMethods.HttpDeleteServiceConfiguration( IntPtr.Zero, HttpServiceConfigId.HttpServiceConfigUrlAclInfo, inputConfigInfoBuffer, Marshal.SizeOf(inputConfigInfoSet), IntPtr.Zero); if (ErrorCode.Success == retVal) { retVal = NativeMethods.HttpSetServiceConfiguration( IntPtr.Zero, HttpServiceConfigId.HttpServiceConfigUrlAclInfo, inputConfigInfoBuffer, Marshal.SizeOf(inputConfigInfoSet), IntPtr.Zero); } } Marshal.FreeHGlobal(inputConfigInfoBuffer); NativeMethods.HttpTerminate(HttpApiConstants.InitializeConfig, IntPtr.Zero); } if (ErrorCode.Success != retVal) { throw new Win32Exception(Convert.ToInt32(retVal, CultureInfo.InvariantCulture)); } }
} // StopListening // // end of IChannelReceiver implementation // // Thread for listening void Listen() { InternalRemotingServices.RemotingTrace("Waiting to Accept a Connection on Port: " + _portName); // // Wait for an incoming client connection // IntPtr handle = IntPtr.Zero; bool connected = false; CommonSecurityDescriptor descriptor = _securityDescriptor; // Connect with exlusive flag the first time try{ // If the descriptor is not explicitly set through code use the _authorizedGroup config if (descriptor == null && _authorizedGroup != null) { NTAccount ntAccount = new NTAccount(_authorizedGroup); descriptor = IpcPort.CreateSecurityDescriptor((SecurityIdentifier)ntAccount.Translate(typeof(SecurityIdentifier))); } _port = IpcPort.Create(_portName, descriptor, _bExclusiveAddressUse); } catch (Exception e) { _startListeningException = e; } finally { _bListening = (_startListeningException == null); _waitForStartListening.Set(); // allow main thread to continue now that we have tried to start the socket } if (_port != null) { connected = _port.WaitForConnect(); } while (_bListening) { InternalRemotingServices.RemotingTrace("IpcChannel::Listen"); // For DevDiv#220882, we need to create new IpcPort before handling the current message // to avoid race condition in case the message is handled and finished before // the new IpcPort is created. The client will intermittently fail with Port not found. IpcPort port = IpcPort.Create(_portName, descriptor, false); if (connected) { // Initialize the server handler and perform an async read IpcServerHandler serverHandler = new IpcServerHandler(_port, CoreChannel.RequestQueue, new PipeStream(_port)); serverHandler.DataArrivedCallback = new WaitCallback(_transportSink.ServiceRequest); serverHandler.BeginReadMessage(); } _port = port; connected = _port.WaitForConnect(); } }
public string FindLatipiumDir(string user) { if (IsService) { IntPtr accessToken = AccessToken; try { IntPtr path; uint error = SHGetKnownFolderPath(KNOWNFOLDERID.RoamingAppData, 0, accessToken, out path); switch (error) { case S_OK: try { string dir = Path.Combine(Marshal.PtrToStringAuto(path), "latipium"); Directory.CreateDirectory(dir); string username; string domain; if (GetUser(accessToken, out username, out domain)) { NTAccount account = new NTAccount(domain, username); DirectorySecurity acl = Directory.GetAccessControl(dir); if (!acl.GetAccessRules(true, true, typeof(NTAccount)).OfType <FileSystemAccessRule>() .Any(r => r.IdentityReference == account && r.FileSystemRights == FileSystemRights.FullControl && r.AccessControlType == AccessControlType.Allow)) { acl.AddAccessRule(new FileSystemAccessRule(account, FileSystemRights.FullControl, AccessControlType.Allow)); } Directory.SetAccessControl(dir, acl); } return(dir); } finally { Marshal.FreeCoTaskMem(path); } case E_FAIL: WindowsService.WriteLog("Error in SHGetKnownFolderPath: Unspecified failure (2147500037)"); break; case E_INVALIDARG: WindowsService.WriteLog("Error in SHGetKnownFolderPath: One or more arguments are not valid (2147942487)"); break; default: WindowsService.WriteLog(string.Format("Error in SHGetKnownFolderPath: ({0})", error)); break; } } finally { CloseHandle(accessToken); } return(null); } else { string dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "latipium"); Directory.CreateDirectory(dir); return(dir); } }
public void CreateSharedTestingDirectory() { var testingDirectoryPath = @"C:\Testing"; Directory.CreateDirectory(testingDirectoryPath); var directoryInfo = new DirectoryInfo(testingDirectoryPath); var directorySecurity = directoryInfo.GetAccessControl(); directorySecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow)); directoryInfo.SetAccessControl(directorySecurity); var manager = new ManagementClass("win32_share"); var inParameters = manager.GetMethodParameters("Create"); inParameters["Description"] = "Shared Testing Folder"; inParameters["Name"] = "Testing"; inParameters["Path"] = testingDirectoryPath; inParameters["Type"] = 0x0; inParameters["MaximumAllowed"] = null; inParameters["Password"] = null; inParameters["Access"] = null; var outParameters = manager.InvokeMethod("Create", inParameters, null); var ntAccount = new NTAccount("Everyone"); var userSID = (SecurityIdentifier)ntAccount.Translate(typeof(SecurityIdentifier)); var userSIDArray = new byte[userSID.BinaryLength]; userSID.GetBinaryForm(userSIDArray, 0); ManagementObject userTrustee = new ManagementClass(new ManagementPath("Win32_Trustee"), null); userTrustee["Name"] = "Everyone"; userTrustee["SID"] = userSIDArray; ManagementObject userACE = new ManagementClass(new ManagementPath("Win32_Ace"), null); userACE["AccessMask"] = 2032127; //Full access userACE["AceFlags"] = AceFlags.ObjectInherit | AceFlags.ContainerInherit; userACE["AceType"] = AceType.AccessAllowed; userACE["Trustee"] = userTrustee; ManagementObject userSecurityDescriptor = new ManagementClass(new ManagementPath("Win32_SecurityDescriptor"), null); userSecurityDescriptor["ControlFlags"] = 4; //SE_DACL_PRESENT userSecurityDescriptor["DACL"] = new object[] { userACE }; var share = new ManagementObject(manager.Path + ".Name='" + inParameters["Name"] + "'"); share.InvokeMethod("SetShareInfo", new[] { Int32.MaxValue, inParameters["Description"], userSecurityDescriptor }); }
public static void SetServicePermissions(string service, string username) { System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(service); ServiceControllerStatus status = sc.Status; byte[] psd = new byte[0]; uint bufSizeNeeded; bool ok = ServiceAccountHelper.QueryServiceObjectSecurity(sc.ServiceHandle, SecurityInfos.DiscretionaryAcl, psd, 0, out bufSizeNeeded); if (!ok) { int err = Marshal.GetLastWin32Error(); if (err == 122 || err == 0) { // ERROR_INSUFFICIENT_BUFFER // expected; now we know bufsize psd = new byte[bufSizeNeeded]; ok = ServiceAccountHelper.QueryServiceObjectSecurity(sc.ServiceHandle, SecurityInfos.DiscretionaryAcl, psd, bufSizeNeeded, out bufSizeNeeded); } else { throw new ApplicationException("error calling QueryServiceObjectSecurity() to get DACL for " + username + ": error code=" + err); } } if (!ok) { throw new ApplicationException("error calling QueryServiceObjectSecurity(2) to get DACL for " + username + ": error code=" + Marshal.GetLastWin32Error()); } // get security descriptor via raw into DACL form so ACE // ordering checks are done for us. RawSecurityDescriptor rsd = new RawSecurityDescriptor(psd, 0); RawAcl racl = rsd.DiscretionaryAcl; DiscretionaryAcl dacl = new DiscretionaryAcl(false, false, racl); // Add start/stop/read access NTAccount acct = new NTAccount(username); SecurityIdentifier sid = (SecurityIdentifier)acct.Translate(typeof(SecurityIdentifier)); dacl.AddAccess(AccessControlType.Allow, sid, (int)ServiceAccountHelper.SERVICE_ACCESS.SERVICE_START, InheritanceFlags.None, PropagationFlags.None); dacl.AddAccess(AccessControlType.Allow, sid, (int)ServiceAccountHelper.SERVICE_ACCESS.SERVICE_STOP, InheritanceFlags.None, PropagationFlags.None); // convert discretionary ACL back to raw form; looks like via byte[] is only way byte[] rawdacl = new byte[dacl.BinaryLength]; dacl.GetBinaryForm(rawdacl, 0); rsd.DiscretionaryAcl = new RawAcl(rawdacl, 0); // set raw security descriptor on service again byte[] rawsd = new byte[rsd.BinaryLength]; rsd.GetBinaryForm(rawsd, 0); ok = ServiceAccountHelper.SetServiceObjectSecurity(sc.ServiceHandle, SecurityInfos.DiscretionaryAcl, rawsd); if (!ok) { throw new ApplicationException("error calling SetServiceObjectSecurity(); error code=" + Marshal.GetLastWin32Error()); } }
/// <summary> /// Impersonate the SYSTEM user. Equates to `ImpersonateUser("NT AUTHORITY\SYSTEM")`. (Requires Admin) /// </summary> /// <returns>True if impersonation succeeds, false otherwise.</returns> public bool GetSystem() { Console.WriteLine("Getting system..."); SecurityIdentifier securityIdentifier = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null); NTAccount systemAccount = (NTAccount)securityIdentifier.Translate(typeof(NTAccount)); Console.WriteLine("Impersonate " + systemAccount.ToString() + "..."); return(this.ImpersonateUser(systemAccount.ToString())); }
public string GetOwnerName(string path) { //string user = System.IO.File.GetAccessControl(path).GetOwner(typeof(System.Security.Principal.NTAccount)).ToString(); FileSecurity fileSecurity = File.GetAccessControl(path); IdentityReference identityReference = fileSecurity.GetOwner(typeof(SecurityIdentifier)); NTAccount ntAccount = identityReference.Translate(typeof(NTAccount)) as NTAccount; return(ntAccount.Value); }
/// <summary> /// Sets the owner /// </summary> public void SetOwner(NTAccount newOwner) { Contract.Requires(newOwner != null); if (IsRoot) { throw new NotSupportedException("Root directory does not provide owner access"); } GetFileSystemSecurity().FileSystemSecurityInformation.SetOwner(newOwner.Translate(typeof(SecurityIdentifier))); }
/// <summary> /// Creates a SDDL string representation of the ACL that Allows Generic eXecute for the specified user. /// </summary> /// <param name="account">the name of the account</param> /// <returns>a SDDL string that Allows Generic eXecute for the specified user.</returns> private static string CreateSddl(string account) { string sid = new NTAccount(account).Translate(typeof(SecurityIdentifier)).ToString(); // DACL that Allows Generic eXecute for the user // specified by account // see help for HTTP_SERVICE_CONFIG_URLACL_PARAM // for details on what this means return(string.Format("D:(A;;GX;;;{0})", sid)); }
public override bool Equals(object o) { NTAccount nt = (o as NTAccount); if (nt == null) { return(false); } return(nt.Value == Value); }
/// <summary> /// By defult Environment.SpecialFolder.CommonApplicationData does not have writting permission /// </summary> /// <param name="userIdentityName"></param> public static void AllowReadWriteConfig(string userIdentityName = null) { if (userIdentityName == null) { userIdentityName = UserRoutines.GetCurrentUserName3(); } NTAccount a = new NTAccount(userIdentityName); allowReadWriteConfig((SecurityIdentifier)a.Translate(typeof(SecurityIdentifier))); }
protected void btnCheckAccessTest_Click(object sender, EventArgs e) { try { NTAccount nta = (NTAccount)(this.Request.LogonUserIdentity.User.Translate(typeof(NTAccount))); string currentUpnName = nta.Value; if (currentUpnName.IndexOf('\\') != -1) { currentUpnName = currentUpnName.Substring(currentUpnName.IndexOf('\\') + 1); } if (String.IsNullOrEmpty(this.txtWindowsUser.Text) && this.rbWindowsUser.Checked) { this.txtWindowsUser.Text = currentUpnName; } if (this.rbWindowsUser.Checked) { this.dbuser = null; if (this.txtWindowsUser.Text == currentUpnName) { //Current Windows User this.wid = this.Request.LogonUserIdentity; } else { //Kerberos Protocol Transition this.wid = new WindowsIdentity(this.txtWindowsUser.Text); } } else if (this.rbDBUser.Checked && !String.IsNullOrEmpty(this.txtDBUser.Text)) { this.wid = null; this.dbuser = this.application.GetDBUser(this.txtDBUser.Text); } this.txtDetails.Text = String.Empty; this.WriteLineDetailMessage("Check Access Test started at " + DateTime.Now.ToString()); this.WriteLineDetailMessage(String.Empty); this.WriteIdentityDetails(); this.WriteLineDetailMessage(String.Empty); this.WriteDetailMessage("Building Items Hierarchy ..."); this.RefreshItemsHierarchy(); this.WriteLineDetailMessage("Done."); this.WriteLineDetailMessage(String.Empty); TreeNode applicationTreeNode = this.itemsHierarchyTreeView.Nodes[0].ChildNodes[0].ChildNodes[0]; foreach (TreeNode itemTreeNode in applicationTreeNode.ChildNodes) { this.checkAccessTest(itemTreeNode); } this.WriteLineDetailMessage(String.Empty); this.WriteLineDetailMessage("Check Access Test finished at " + DateTime.Now.ToString()); } catch (Exception ex) { this.ShowError(ex.Message); } }
public static IChannel PublishLocalProxy(ExecutionServiceProxy proxy) { //We want the object to be available for as long as possible so we choose one year LifetimeServices.LeaseTime = TimeSpan.FromDays(365); RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off; BinaryServerFormatterSinkProvider provider = new BinaryServerFormatterSinkProvider(); provider.TypeFilterLevel = TypeFilterLevel.Full; //need full deserialization //create a server channel and make the object available remotely Hashtable channelSettings = new Hashtable(); channelSettings["portName"] = ExecutionService.LocalPortName; //Grant access to everyone (need to get the name from the well known SID to support localized builds) SecurityIdentifier everyoneSid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); NTAccount everyoneAccount = (NTAccount)everyoneSid.Translate(typeof(NTAccount)); channelSettings["authorizedGroup"] = everyoneAccount.Value; //Because use use ExecutionService to update itself we have to disallow exclusive access //to the port, otherwise updating ExecutionService fails. channelSettings["exclusiveAddressUse"] = false; // Workaround for Remoting breaking change. This custom security descriptor is needed // to allow Medium IL processes to use IPC to talk to elevated UAC processes. DiscretionaryAcl dacl = new DiscretionaryAcl(false, false, 1); // This is the well-known sid for network security ID string networkSidSddlForm = @"S-1-5-2"; // This is the well-known sid for all users on this machine string everyoneSidSddlForm = @"S-1-1-0"; // Deny all access to NetworkSid dacl.AddAccess(AccessControlType.Deny, new SecurityIdentifier(networkSidSddlForm), -1, InheritanceFlags.None, PropagationFlags.None); // Add access to the current user creating the pipe dacl.AddAccess(AccessControlType.Allow, WindowsIdentity.GetCurrent().User, -1, InheritanceFlags.None, PropagationFlags.None); // Add access to the all users on the machine dacl.AddAccess(AccessControlType.Allow, new SecurityIdentifier(everyoneSidSddlForm), -1, InheritanceFlags.None, PropagationFlags.None); // Initialize and return the CommonSecurityDescriptor CommonSecurityDescriptor allowMediumILSecurityDescriptor = new CommonSecurityDescriptor(false, false, ControlFlags.OwnerDefaulted | ControlFlags.GroupDefaulted | ControlFlags.DiscretionaryAclPresent | ControlFlags.SystemAclPresent, null, null, null, dacl); IpcServerChannel publishedChannel = new IpcServerChannel(channelSettings, provider, allowMediumILSecurityDescriptor); ChannelServices.RegisterChannel(publishedChannel, false); RemotingServices.Marshal(proxy, ExecutionService.ProxyName, typeof(IExecutionService)); return(publishedChannel); }
private string NtAccount(string userName) { var account = new NTAccount(userName); if (account.IsValidTargetType(typeof(SecurityIdentifier))) { return(account.Translate(typeof(SecurityIdentifier)).Value); } return(null); }
public static string UserNameFromSidString(string sid) { try { SecurityIdentifier si = new SecurityIdentifier(sid); NTAccount acct = (NTAccount)si.Translate(typeof(NTAccount)); return(acct.Value); } catch { } return(null); }
public static SecurityIdentifier GetVMnameSid(string VMName) { ManagementObjectCollection queryCollection; SecurityIdentifier sid = null; try { ManagementScope scope = new ManagementScope(@"\\.\root\virtualization\v2"); scope.Connect(); string querystr = "SELECT * FROM Msvm_ComputerSystem where ElementName=\"" + VMName + "\""; ObjectQuery query = new ObjectQuery(querystr); ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query); queryCollection = searcher.Get(); } catch (Exception e) { Console.WriteLine(e.ToString()); return(null); } //Console.WriteLine("Name,GUID,PID"); try { foreach (ManagementObject vm in queryCollection) { try { // display VM details //Console.WriteLine("{0},{1},{2}", vm["ElementName"].ToString(), // vm["Name"].ToString(), vm["ProcessID"].ToString()); string concat = "NT VIRTUAL MACHINE\\" + vm["Name"].ToString(); NTAccount ntaccount = new NTAccount(concat); sid = (SecurityIdentifier)ntaccount.Translate(typeof(SecurityIdentifier)); Console.WriteLine("{0},{1},{2},{3}", vm["ElementName"].ToString(), vm["Name"].ToString(), vm["ProcessID"].ToString(), sid.ToString()); } catch (Exception /*e*/) { // don't print anything, some entries might miss fields like process id, ignore and move on //Console.WriteLine(e.ToString()); continue; } } } catch (Exception e) { Console.WriteLine(e.ToString()); return(null); } return(sid); }
private ActiveDirectoryUser Convert(DirectoryEntry user, bool includeActiveDirectoryGroups, bool includeDomain) { ActiveDirectoryUser activeDirectoryUser = new ActiveDirectoryUser() { FirstName = GetValue <string>(user, "givenName"), LastName = GetValue <string>(user, "sn"), DisplayName = GetValue <string>(user, "name"), Email = GetValue <string>(user, "mail") }; var userGroups = new HashSet <string>(); if (includeActiveDirectoryGroups) { user.RefreshCache(new string[] { "tokenGroups" }); for (int i = 0; i < user.Properties["tokenGroups"].Count; i++) { try { SecurityIdentifier sidTokenGroup = new SecurityIdentifier((byte[])user.Properties["tokenGroups"][i], 0); NTAccount nt = (NTAccount)sidTokenGroup.Translate(typeof(NTAccount)); string name = nt.Value.Substring(nt.Value.IndexOf('\\') + 1); if (name.Length > 0 && name[0] != '.' && name[0] != '*') { name = "*" + name; } if (includeDomain) { name = nt.Value.Substring(0, nt.Value.IndexOf('\\') + 1) + name; } userGroups.Add(name); } catch (Exception ex) { this.logger.LogError(ex, $"Failed to resolve AD-Group for token (Index: {i})"); } } } activeDirectoryUser.Groups = userGroups; byte[] objectsid = GetValue <byte[]>(user, "objectsid"); SecurityIdentifier sid = new SecurityIdentifier(objectsid, 0); activeDirectoryUser.LoginName = ((NTAccount)sid.Translate(typeof(NTAccount))).ToString(); return(activeDirectoryUser); }
private void Share(string path, string user) { try { if (MessageBox.Show("Naozaj chceš vyzdielať " + path + " ?", "Upozornenie", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No) { return; } string accountToAccess = user; string shareName = Path.GetFileName(path); Globals.SharedFolder = shareName; ManagementClass managementClass = new ManagementClass("Win32_Share"); ManagementBaseObject inParams = managementClass.GetMethodParameters("Create"); ManagementBaseObject outParams; inParams["Description"] = "Konica Minolta Sken"; inParams["Name"] = shareName; inParams["Path"] = path; inParams["Type"] = 0x0; inParams["Password"] = null; NTAccount NTAccount = new NTAccount(accountToAccess); SecurityIdentifier sid = (SecurityIdentifier)NTAccount.Translate(typeof(SecurityIdentifier)); byte[] sidArray = new byte[sid.BinaryLength]; sid.GetBinaryForm(sidArray, 0); ManagementObject trustee = new ManagementClass("Win32_Trustee"); trustee["Domain"] = null; trustee["Name"] = accountToAccess; trustee["SID"] = sidArray; ManagementObject dacl = new ManagementClass("Win32_Ace"); dacl["AccessMask"] = 2032127; dacl["AceFlags"] = 3; dacl["AceType"] = 0; dacl["Trustee"] = trustee; ManagementObject securityDescriptor = new ManagementClass("Win32_SecurityDescriptor"); securityDescriptor["ControlFlags"] = 4; securityDescriptor["DACL"] = new object[] { dacl }; inParams["Access"] = securityDescriptor; outParams = managementClass.InvokeMethod("Create", inParams, null); var result = (uint)(outParams.Properties["ReturnValue"].Value); MessageBox.Show("Priečinok " + path + " bol úspešne vyzdielaný"); } catch (ArgumentNullException) { MessageBox.Show("Najskôr musíš vytvoriť užívateľa", "Chyba!", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (UnauthorizedAccessException) { MessageBox.Show("Musíš spustiť program ako SPRÁVCA", "Chyba", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (Exception ex) { MessageBox.Show(ex.Message.ToString(), "Chyba!", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public static bool IsServiceAccount(this WindowsIdentity id) { try { var acct = new NTAccount(id.Name); var si = (SecurityIdentifier)acct.Translate(typeof(SecurityIdentifier)); return(si.IsWellKnown(WellKnownSidType.LocalSystemSid) || si.IsWellKnown(WellKnownSidType.NetworkServiceSid) || si.IsWellKnown(WellKnownSidType.LocalServiceSid)); } catch { } return(false); }
private string GetUserNameOfFSP(string ForeignSecurityPrincipal) { //Returns with syntax of "DOMAIN\logonname" try { DirectoryEntry user = new DirectoryEntry("LDAP://" + ForeignSecurityPrincipal); SecurityIdentifier sid = new SecurityIdentifier((byte[])user.InvokeGet("objectSid"), 0); NTAccount account = (NTAccount)sid.Translate(typeof(NTAccount)); return(account.ToString()); } catch (DirectoryServicesCOMException e) { Console.Write(e.Message); return("Error"); } }
protected void Page_Load(object sender, EventArgs e) { if (User is WindowsPrincipal) { // First of all, output some user information WindowsPrincipal principal = (WindowsPrincipal)User; lblInfo.Text += "<br><b>Power user? </b>"; lblInfo.Text += principal.IsInRole( WindowsBuiltInRole.PowerUser).ToString(); WindowsIdentity identity = (WindowsIdentity)principal.Identity; lblInfo.Text += "<br><b>Token: </b>"; lblInfo.Text += identity.Token.ToString(); lblInfo.Text += "<br><b>Guest? </b>"; lblInfo.Text += identity.IsGuest.ToString(); lblInfo.Text += "<br><b>System? </b>"; lblInfo.Text += identity.IsSystem.ToString(); // Next get the roles for the user lblInfo.Text += "<hr/>"; lblInfo.Text += "<h2>Roles:</h2>"; foreach (IdentityReference SIDRef in identity.Groups) { lblInfo.Text += "<br/>---"; try { // Get the system-code for the SID SecurityIdentifier sid = (SecurityIdentifier)SIDRef.Translate(typeof(SecurityIdentifier)); lblInfo.Text += "<br><b>SID (code): </b></br>"; lblInfo.Text += sid.Value; } catch (Exception ex) { lblInfo.Text += "Unable to translate reference: " + SIDRef.Value; } try { // Get the human-readable SID NTAccount account = (NTAccount)SIDRef.Translate(typeof(NTAccount)); lblInfo.Text += "<br><b>SID (human-readable): </b></br>"; lblInfo.Text += account.Value; } catch (Exception ex) { lblInfo.Text += "Unable to translate sid: " + ex.Message; } } } }
public NTAccount GetDefaultServiceAccount() { SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, domainSid: null); NTAccount account = sid.Translate(typeof(NTAccount)) as NTAccount; if (account == null) { throw new InvalidOperationException(StringUtil.Loc("NetworkServiceNotFound")); } return(account); }
public static string GetNoneGroupSID() { try { var objUsersGroup = new NTAccount("None"); return(((SecurityIdentifier)objUsersGroup.Translate(typeof(SecurityIdentifier))).Value); } catch { throw new Exception("Could not get SID for the local 'None' group. Aborting."); } }
public static FileStream FullAccessStream(string sFilename, Int32 nBufferSize, FileOptions options) { SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); NTAccount acct = sid.Translate(typeof(NTAccount)) as NTAccount; string sEveryoneAccount = acct.ToString(); FileSecurity fSecurity = new FileSecurity(); fSecurity.AddAccessRule(new FileSystemAccessRule(sEveryoneAccount, FileSystemRights.FullControl, AccessControlType.Allow)); FileStream fs = File.Create(sFilename, nBufferSize, options, fSecurity); return(fs); }
public void ApplyConfigChange() { var accountName = string.Equals(ServiceAccount, "LocalSystem", StringComparison.OrdinalIgnoreCase) ? "System" : ServiceAccount; var oldSettings = InstanceFinder.FindMonitoringInstance(Name); var fileSystemChanged = !string.Equals(oldSettings.LogPath, LogPath, StringComparison.OrdinalIgnoreCase); var queueNamesChanged = !(string.Equals(oldSettings.ErrorQueue, ErrorQueue, StringComparison.OrdinalIgnoreCase)); RecreateUrlAcl(oldSettings); if (fileSystemChanged) { var account = new NTAccount(accountName); var modifyAccessRule = new FileSystemAccessRule(account, FileSystemRights.Modify | FileSystemRights.Traverse | FileSystemRights.ListDirectory, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow); FileUtils.CreateDirectoryAndSetAcl(LogPath, modifyAccessRule); } Service.Description = Description; var configuration = ConfigurationManager.OpenExeConfiguration(Service.ExePath); var settings = configuration.AppSettings.Settings; settings.Set(SettingsList.HostName, HostName); settings.Set(SettingsList.Port, Port.ToString()); settings.Set(SettingsList.LogPath, LogPath); settings.Set(SettingsList.ErrorQueue, ErrorQueue); configuration.ConnectionStrings.ConnectionStrings.Set("NServiceBus/Transport", ConnectionString); configuration.Save(); var passwordSet = !string.IsNullOrWhiteSpace(ServiceAccountPwd); var accountChanged = !string.Equals(oldSettings.ServiceAccount, ServiceAccount, StringComparison.OrdinalIgnoreCase); var connectionStringChanged = !string.Equals(ConnectionString, oldSettings.ConnectionString, StringComparison.Ordinal); //have to save config prior to creating queues (if needed) if (queueNamesChanged || accountChanged || connectionStringChanged) { try { QueueCreation.RunQueueCreation(this); } catch (QueueCreationFailedException ex) { ReportCard.Errors.Add(ex.Message); } catch (QueueCreationTimeoutException ex) { ReportCard.Errors.Add(ex.Message); } } if (passwordSet || accountChanged) { Service.ChangeAccountDetails(accountName, ServiceAccountPwd); } }
public static string SidStringFromUserName(string userName) { var acct = new NTAccount(userName); try { var si = (SecurityIdentifier)acct.Translate(typeof(SecurityIdentifier)); return(si.ToString()); } catch { } return(null); }
protected void btnDelegateForBudgetCheck_Click(object sender, EventArgs e) { NTAccount delegatedNTAccount = new NTAccount("ProductManager1"); SecurityIdentifier delegatedSid = (SecurityIdentifier)delegatedNTAccount.Translate(typeof(SecurityIdentifier)); this.application.Store.Storage.OpenConnection(); this.application.Store.Storage.BeginTransaction(AzManIsolationLevel.ReadUncommitted); IAzManAuthorization delegateAuthorization = this.application["Controllo del Budget"].CreateDelegateAuthorization(this.identity, new SqlAzManSID(delegatedSid), RestrictedAuthorizationType.Allow, null, null); delegateAuthorization.CreateAttribute("SomeBusinessAttribute", "Business profile data"); this.application.Store.Storage.CommitTransaction(); this.application.Store.Storage.CloseConnection(); this.btnDelegateForBudgetCheck.Enabled = false; this.btnUndelegate.Enabled = true; }
protected void Page_Load(object sender, EventArgs e) { IAzManStorage storage = new SqlAzManStorage(ConfigurationManager.ConnectionStrings["NetSqlAzManStorage"].ConnectionString); this.application = storage[ConfigurationManager.AppSettings["StoreName"]][ConfigurationManager.AppSettings["ApplicationName"]]; //Get user Identity this.identity = this.Request.LogonUserIdentity; this.lblIAM.Text = this.identity.Name; //Print DateTime this.lblDateTime.Text = DateTime.Now.ToString(); //Check Access on Items this.application.Store.Storage.OpenConnection(); this.btnBudgetCheck.Enabled = this.checkAccessHelper("Controllo del Budget"); this.btnCustomerRelationshipManagement.Enabled = this.checkAccessHelper("Relazioni con i Clienti"); this.btnConstraintCheck.Enabled = this.checkAccessHelper("Controllo dei Vincoli"); this.btnTimesheetCheck.Enabled = this.checkAccessHelper("Approvazione del TimeSheet"); this.btnTimesheetCompile.Enabled = this.checkAccessHelper("Compilazione del Timesheet"); this.btnDevelopment.Enabled = this.checkAccessHelper("Sviluppo"); //Can delegate ? NTAccount delegatedNTAccount = new NTAccount("ProductManager1"); SecurityIdentifier delegatedSid = (SecurityIdentifier)delegatedNTAccount.Translate(typeof(SecurityIdentifier)); bool canDelegate = this.checkAccessForDelegationHelper("Controllo del Budget"); bool alreadyDelegate = this.application["Controllo del Budget"].GetAuthorizations(new SqlAzManSID(this.identity.User), new SqlAzManSID(delegatedSid)).Length > 0; this.btnDelegateForBudgetCheck.Enabled = canDelegate && !alreadyDelegate; this.btnUndelegate.Enabled = canDelegate && alreadyDelegate; //Attributes IAzManAuthorization[] auths = this.application["Controllo del Budget"].GetAuthorizationsOfMember(new SqlAzManSID(this.identity.User)); string toolTip = String.Empty; foreach (IAzManAuthorization auth in auths) { IAzManAttribute<IAzManAuthorization>[] attribs = auth.GetAttributes(); foreach (IAzManAttribute<IAzManAuthorization> attrib in attribs) { toolTip += String.Format("{0} - {1}\r\n", attrib.Key, attrib.Value); } } this.btnBudgetCheck.ToolTip = toolTip; this.application.Store.Storage.CloseConnection(); }
public static bool op_Inequality(NTAccount left, NTAccount right) {}