/// <summary> /// Retrieves identity and role information from the currently /// logged in Windows user. /// </summary> protected void PopulateWindowsIdentity() { string DomainDelimiter = "\\"; System.Security.Principal.IdentityReferenceCollection groups = System.Security.Principal.WindowsIdentity.GetCurrent().Groups; MobileList <string> roles = new MobileList <string>(); foreach (System.Security.Principal.IdentityReference item in groups) { System.Security.Principal.NTAccount account = (System.Security.Principal.NTAccount)item.Translate(typeof(System.Security.Principal.NTAccount)); if (account.Value.Contains(DomainDelimiter)) { roles.Add(account.Value.Substring(account.Value.LastIndexOf(DomainDelimiter) + 1)); } else { roles.Add(account.Value); } } string identityName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; if (identityName.Contains(DomainDelimiter)) { identityName = identityName.Substring(identityName.LastIndexOf(DomainDelimiter) + 1); } this.LoadProperty(RolesProperty, roles); this.LoadProperty(IsAuthenticatedProperty, true); this.LoadProperty(NameProperty, identityName); }
public void TestGetAccessControlSections() { var filename = Util.CreateNewFile(longPathDirectory); try { var fi = new FileInfo(filename); FileSecurity security = fi.GetAccessControl(AccessControlSections.Access); Assert.IsNotNull(security); Assert.AreEqual(typeof(FileSystemRights), security.AccessRightType); Assert.AreEqual(typeof(FileSystemAccessRule), security.AccessRuleType); Assert.AreEqual(typeof(FileSystemAuditRule), security.AuditRuleType); Assert.IsTrue(security.AreAccessRulesCanonical); Assert.IsTrue(security.AreAuditRulesCanonical); Assert.IsFalse(security.AreAccessRulesProtected); Assert.IsFalse(security.AreAuditRulesProtected); var securityGetAccessRules = security.GetAuditRules(true, true, typeof(System.Security.Principal.NTAccount)).Cast <FileSystemAccessRule>(); Assert.AreEqual(0, securityGetAccessRules.Count()); AuthorizationRuleCollection perm = security.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)); var ntAccount = new System.Security.Principal.NTAccount(System.Security.Principal.WindowsIdentity.GetCurrent().Name); FileSystemAccessRule rule = perm.Cast <FileSystemAccessRule>().SingleOrDefault(e => ntAccount == e.IdentityReference); Assert.IsNotNull(rule); Assert.IsTrue((rule.FileSystemRights & FileSystemRights.FullControl) != 0); } finally { File.Delete(filename); } }
public void TestGetAccessControl() { var tempLongPathFilename = Path.Combine(uncDirectory, Path.GetRandomFileName()); Directory.CreateDirectory(tempLongPathFilename); try { var security = Directory.GetAccessControl(tempLongPathFilename); Assert.IsNotNull(security); Assert.AreEqual(typeof(FileSystemRights), security.AccessRightType); Assert.AreEqual(typeof(FileSystemAccessRule), security.AccessRuleType); Assert.AreEqual(typeof(FileSystemAuditRule), security.AuditRuleType); Assert.IsTrue(security.AreAccessRulesCanonical); Assert.IsTrue(security.AreAuditRulesCanonical); Assert.IsFalse(security.AreAccessRulesProtected); Assert.IsFalse(security.AreAuditRulesProtected); AuthorizationRuleCollection perm = security.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)); var ntAccount = new System.Security.Principal.NTAccount(System.Security.Principal.WindowsIdentity.GetCurrent().Name); FileSystemAccessRule rule = perm.Cast <FileSystemAccessRule>().SingleOrDefault(e => ntAccount == e.IdentityReference); Assert.IsNotNull(rule); Assert.IsTrue((rule.FileSystemRights & FileSystemRights.FullControl) != 0); } finally { Directory.Delete(tempLongPathFilename); } }
public static void Test() { System.Security.Principal.NTAccount ntuser = new System.Security.Principal.NTAccount(@"cor\stefan.steiger"); System.Security.Principal.SecurityIdentifier sID = (System.Security.Principal.SecurityIdentifier)ntuser.Translate(typeof(System.Security.Principal.SecurityIdentifier)); string strSID = sID.Value; // Mozilla/4.0 (compatible; MSIE 8.0; Win32) // https://stackoverflow.com/questions/9978193/how-to-edit-the-registry-keys-of-a-specific-user-programatically/9986068 // HKCU is just a symbolic link for one of the keys under HKEY_USERS. // If you know the SID of that user, then you can find it in there. You can get the SID as so: // The better option is to impersonate. The second option might work better when you don't know that user's credentials. // The disadvantage is you will need administrative rights to write in someone else's account. // Microsoft.Win32.Registry.Users.SetValue(strSID + @"\Software\Microsoft\Windows\CurrentVersion\Internet Settings\User Agent", "Test", Microsoft.Win32.RegistryValueKind.String); //using (var impersonation = new Impersonate(username, password)) //{ // ChangeRegistry(keys, values); //} // https://stackoverflow.com/questions/125341/how-do-you-do-impersonation-in-net // https://github.com/mj1856/SimpleImpersonation // https://stackoverflow.com/questions/6564153/edit-registry-key-of-other-user System.IntPtr handle; LogonUser("stefan.steiger", "cor", "Inspiron1370", 2, 0, out handle); Microsoft.Win32.SafeHandles.SafeAccessTokenHandle safeHandle = new Microsoft.Win32.SafeHandles.SafeAccessTokenHandle(handle); System.Security.Principal.WindowsIdentity.RunImpersonated(safeHandle, delegate() { System.Console.WriteLine(System.Environment.UserName); }); }
public void AclUser() { var account = new System.Security.Principal.NTAccount(Environment.UserName); Assert.That(account.ToString().Contains(Environment.UserName)); Assert.That(account.IsValidTargetType(typeof(System.Security.Principal.SecurityIdentifier))); var securityAccount = account.Translate(typeof(System.Security.Principal.SecurityIdentifier)) as System.Security.Principal.SecurityIdentifier; Assert.That(securityAccount.IsAccountSid(), Is.True); }
protected override void ProcessRecord() { //OU can be passed as name or as dn List <ObjectInfo> OUs = DirectoryUtils.GetOU(Identity); if (OUs.Count > 1) { foreach (ObjectInfo ou in OUs) { WriteObject(ou); } throw new Exception("More than one object found, search using distinguishedName instead"); } if (OUs.Count == 0) { throw new Exception("Object not found"); } ActiveDirectorySecurity sec = DirectoryUtils.GetObjectSecurity(conn, OUs[0].DistinguishedName, System.DirectoryServices.Protocols.SecurityMasks.Dacl); //apply permissions only to computer objects Guid inheritedObjectGuid = DirectoryUtils.GetSchemaGuid(conn, forestRootDomain.schemaNamingContext, "computer", SchemaObjectType.Class); Guid timestampGuid = DirectoryUtils.GetSchemaGuid(conn, forestRootDomain.schemaNamingContext, Constants.TimestampAttributeName, SchemaObjectType.Attribute); //System.DirectoryServices.PropertyAccessRule rule; System.DirectoryServices.ActiveDirectoryAccessRule rule; foreach (string principalName in AllowedPrincipals) { System.Security.Principal.NTAccount principal = new System.Security.Principal.NTAccount(principalName); // read ms-Mcs-AdmPwdExpirationTime on computer objects rule = new System.DirectoryServices.PropertyAccessRule(principal, System.Security.AccessControl.AccessControlType.Allow, PropertyAccess.Read, timestampGuid, ActiveDirectorySecurityInheritance.Descendents, inheritedObjectGuid ); sec.AddAccessRule(rule); // write ms-Mcs-AdmPwdExpirationTime on computer objects rule = new System.DirectoryServices.PropertyAccessRule(principal, System.Security.AccessControl.AccessControlType.Allow, PropertyAccess.Write, timestampGuid, ActiveDirectorySecurityInheritance.Descendents, inheritedObjectGuid ); sec.AddAccessRule(rule); } DirectoryUtils.SetObjectSecurity(conn, OUs[0].DistinguishedName, sec, System.DirectoryServices.Protocols.SecurityMasks.Dacl); OUs[0].Status = PermissionDelegationState.Delegated; WriteObject(OUs[0]); }
/// <summary> /// For IIS to use a certificate its process user must be able to encrypt outgoing traffic, /// so it needs the private key for our certificate. If a system user creates the certificate /// the default permission may not allow access to the private key. /// </summary> /// <param name="cert"> cert including private key </param> /// <param name="accountName"> user to grant read access for </param> public static void GrantUserAccessToCertificatePrivateKey(X509Certificate2 cert, string accountName) { if (cert.PrivateKey is RSACryptoServiceProvider rsa) { var privateKeyPath = GetMachineKeyLocation(rsa.CspKeyContainerInfo.UniqueKeyContainerName); var file = new FileInfo(privateKeyPath + "\\" + rsa.CspKeyContainerInfo.UniqueKeyContainerName); var fs = file.GetAccessControl(); var account = new System.Security.Principal.NTAccount(accountName); fs.AddAccessRule(new FileSystemAccessRule(account, FileSystemRights.Read, AccessControlType.Allow)); file.SetAccessControl(fs); } }
protected override void ProcessRecord() { //OU can be passed as name or as dn List <ObjectInfo> OUs = DirectoryUtils.GetOU(Identity); if (OUs.Count > 1) { foreach (ObjectInfo ou in OUs) { WriteObject(ou); } throw new Exception("More than one object found, search using distinguishedName instead"); } if (OUs.Count == 0) { throw new Exception("Object not found"); } ActiveDirectorySecurity sec = DirectoryUtils.GetObjectSecurity(conn, OUs[0].DistinguishedName, System.DirectoryServices.Protocols.SecurityMasks.Sacl); //apply permissions only to computer objects Guid inheritedObjectGuid = DirectoryUtils.GetSchemaGuid(conn, forestRootDomain.schemaNamingContext, "computer", SchemaObjectType.Class); Guid pwdGuid = DirectoryUtils.GetSchemaGuid(conn, forestRootDomain.schemaNamingContext, Constants.PasswordAttributeName, SchemaObjectType.Attribute); System.DirectoryServices.ActiveDirectoryAuditRule auditRule; foreach (string principalName in AuditedPrincipals) { System.Security.Principal.NTAccount principal = new System.Security.Principal.NTAccount(principalName); auditRule = new ActiveDirectoryAuditRule( principal, ActiveDirectoryRights.ExtendedRight, AuditType, pwdGuid, ActiveDirectorySecurityInheritance.Descendents, inheritedObjectGuid ); sec.AddAuditRule(auditRule); } DirectoryUtils.SetObjectSecurity(conn, OUs[0].DistinguishedName, sec, System.DirectoryServices.Protocols.SecurityMasks.Sacl); OUs[0].Status = PermissionDelegationState.Delegated; WriteObject(OUs[0]); }
private static void Main(string[] args) { var user = new System.Security.Principal.NTAccount(@"IIS APPPOOL\10e6c294-9836-44a9-af54-207385846ebf"); var sid = user.Translate(typeof(System.Security.Principal.SecurityIdentifier)); var ctx = new PrincipalContext(ContextType.Machine); // This is weird - the user SID resolves to a group prinicpal, but it works that way. var appPoolIdentityGroupPrincipal = GroupPrincipal.FindByIdentity(ctx, IdentityType.Sid, sid.Value); Console.WriteLine(appPoolIdentityGroupPrincipal.Name); Console.WriteLine(appPoolIdentityGroupPrincipal.DisplayName); GroupPrincipal targetGroupPrincipal = GroupPrincipal.FindByIdentity(ctx, "Performance Monitor Users"); // Making appPoolIdentity "group" a member of the "Performance Monitor Users Group" targetGroupPrincipal.Members.Add(appPoolIdentityGroupPrincipal); targetGroupPrincipal.Save(); Console.WriteLine("DONE!"); Console.ReadKey(); }
/// <summary> /// Create ssas base cube by calling SSAS API /// </summary> /// <param name="cubeServer">Cube server</param> /// <param name="cubeDBName">Cube data base name</param> /// <param name="cubeXmla">Base cube xmla</param> public void CREATE_SSAS_BASE_CUBE( DB_SQLHELPER_BASE sqlHelper, Server cubeServer, String cubeDBName, String cubeName, String dwConnectionString ) { String SSASConfigurationPath = CONFIGURATION_HELPER.BASIC_CONFIGURATION_FOLDER + @"\SSASConfiguration\BaseCubeXMLA.xml"; String SSASConfiguration = ""; System.Security.Principal.NTAccount _Everyone_Account = new System.Security.Principal.NTAccount("Everyone"); System.Security.Principal.SecurityIdentifier _SecurityIdentifier = (System.Security.Principal.SecurityIdentifier)_Everyone_Account.Translate(typeof(System.Security.Principal.SecurityIdentifier)); String sidString = _SecurityIdentifier.ToString(); SSASConfiguration = System.IO.File.ReadAllText(SSASConfigurationPath); SSASConfiguration = SSASConfiguration .Replace("$(dwConnectionString)", dwConnectionString) .Replace("$(cubeDBName)", cubeDBName) .Replace("$(cubeName)", cubeName) .Replace("$(DBTableSchemaName)", CONFIGURATION_HELPER.GET_METADATA_PROPERTY("db_table_schema_name")) .Replace("$(sid)", sidString); sqlHelper.ADD_MESSAGE_LOG(String.Format("[Create base cube] Starting create cube database {0}", cubeDBName), MESSAGE_TYPE.CREATE_CUBE, MESSAGE_RESULT_TYPE.Normal); XmlaResultCollection resultCol = cubeServer.Execute(SSASConfiguration); foreach (XmlaResult result in resultCol) { foreach (XmlaMessage message in result.Messages) { if (message.ToString().Contains("error") || message.ToString().Contains("failed")) { sqlHelper.ADD_MESSAGE_LOG("[Create base cube]" + message.ToString(), MESSAGE_TYPE.CREATE_CUBE, MESSAGE_RESULT_TYPE.Error); return; } else { sqlHelper.ADD_MESSAGE_LOG("[Create base cube]" + message.ToString(), MESSAGE_TYPE.CREATE_CUBE, MESSAGE_RESULT_TYPE.Succeed); } } } sqlHelper.ADD_MESSAGE_LOG("[Create base cube]" + String.Format("Succeed to create cube database {0}", cubeDBName), MESSAGE_TYPE.CREATE_CUBE, MESSAGE_RESULT_TYPE.Succeed); }
private int CreaCartella(string path) { try { DirectoryInfo dir = Directory.CreateDirectory(path); var nn = new FileSystemAccessRule(@"tsf\TFSSetup", FileSystemRights.FullControl, AccessControlType.Allow); var u = new System.Security.Principal.NTAccount("tsf", "tfssetup"); var dirSec = new DirectorySecurity(); dirSec.AddAccessRule(nn); Directory.SetAccessControl(path, dirSec); var user = System.IO.Directory.GetAccessControl(path).GetOwner(typeof(System.Security.Principal.NTAccount)); return 0; } catch(Exception ex) { throw ex; } }
static void Main(string[] args) { DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\"); Debug.WriteLine("Directories in C drive:"); foreach (DirectoryInfo di in directoryInfo.GetDirectories()) { Debug.WriteLine(di.Name); } //Criar diretorios var directory = Directory.CreateDirectory(@"C:\Temp2\Directory"); var directoryCreate = new DirectoryInfo(@"C:\Temp2\DirectoryInfo"); directoryCreate.Create(); //Deletar /*if (Directory.Exists(@"C:\Temp2\Directory")) * { * Console.WriteLine("Deletando pasta 'C:\\Temp2\\Directory'"); * Directory.Delete(@"C:\Temp2\Directory"); * } * * if (directoryCreate.Exists) * { * directoryCreate.Delete(); * }*/ System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null); System.Security.Principal.NTAccount acct = sid.Translate(typeof(System.Security.Principal.NTAccount)) as System.Security.Principal.NTAccount; string strEveryoneAccount = acct.ToString(); //Controle de acesso as pastas //No caso abaixo não permitir a deleção de uma determinada pasta por um determinado usuario DirectorySecurity directorySecurity = directoryInfo.GetAccessControl(); directorySecurity.AddAccessRule(new FileSystemAccessRule(@"DESKTOP\FulanoX", FileSystemRights.Delete, AccessControlType.Deny)); directoryCreate.SetAccessControl(directorySecurity); Console.ReadLine(); }
public static List <AccessRuleObject> GetAccessRules(DirectoryEntry de) { if (de == null) { throw new AdException($"DirectoryEntry Can Not Be NULL", AdStatusType.MissingInput); } List <AccessRuleObject> accessRules = new List <AccessRuleObject>(); AuthorizationRuleCollection rules = de?.ObjectSecurity?.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier)); if (rules != null) { foreach (AuthorizationRule rule in rules) { ActiveDirectoryAccessRule accessRule = (ActiveDirectoryAccessRule)rule; AccessRuleObject aro = new AccessRuleObject() { ControlType = accessRule.AccessControlType, Rights = accessRule.ActiveDirectoryRights, IdentityReference = accessRule.IdentityReference.Value, InheritanceFlags = accessRule.InheritanceFlags, IsInherited = accessRule.IsInherited, }; String identity = aro.IdentityReference; if (DirectoryServices.IsSid(aro.IdentityReference)) { // Get User-Readable Principal Name from Sid System.Security.Principal.SecurityIdentifier sid = (System.Security.Principal.SecurityIdentifier)rule.IdentityReference; System.Security.Principal.NTAccount acct = (System.Security.Principal.NTAccount)sid.Translate(typeof(System.Security.Principal.NTAccount)); identity = acct.Value; } aro.IdentityName = identity; accessRules.Add(aro); } } return(accessRules); }
private static void registerChannel(string name, string port) { System.Runtime.Remoting.Channels.BinaryServerFormatterSinkProvider serverProv = new System.Runtime.Remoting.Channels.BinaryServerFormatterSinkProvider(); serverProv.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full; System.Runtime.Remoting.Channels.BinaryClientFormatterSinkProvider clientProv = new System.Runtime.Remoting.Channels.BinaryClientFormatterSinkProvider(); System.Collections.IDictionary properties = new System.Collections.Hashtable(); properties["name"] = name; properties["priority"] = "20"; properties["portName"] = port; properties["secure"] = true; properties["tokenImpersonationLevel"] = System.Security.Principal.TokenImpersonationLevel.Impersonation; properties["includeVersions"] = false; properties["strictBinding"] = false; System.Security.Principal.SecurityIdentifier sidAdmin = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.InteractiveSid, null); System.Security.Principal.NTAccount nt = (System.Security.Principal.NTAccount)sidAdmin.Translate(typeof(System.Security.Principal.NTAccount)); progress("registerChannel: " + port + " with authorized group " + nt); properties["authorizedGroup"] = nt.Value; System.Runtime.Remoting.Channels.Ipc.IpcChannel ipcCh = new System.Runtime.Remoting.Channels.Ipc.IpcChannel(properties, clientProv, serverProv); System.Runtime.Remoting.Channels.ChannelServices.RegisterChannel(ipcCh, true); }
public static bool CheckPermission(string path, System.Security.AccessControl.FileSystemRights filePerm) { bool canPerform = false; System.Security.AccessControl.FileSecurity acl = File.GetAccessControl(path); string user = Environment.UserName; System.Security.Principal.NTAccount uid = new System.Security.Principal.NTAccount(user); foreach (System.Security.AccessControl.FileSystemAccessRule rule in acl.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount))) { if (rule.IdentityReference == uid) { if ((rule.FileSystemRights & filePerm) != 0) { canPerform = true; } } } return(canPerform); }
public FileSystemFile(FileSystemDirectory directory, System.IO.FileInfo file) { this.Directory = directory; // alle filenames in lowercase! this.Name = file.Name.ToLower(); this.Extension = file.Extension.ToLower(); this.Size = file.Length; this.DateCreate = file.CreationTime; this.DateWrite = file.LastWriteTime; this.DateAccess = file.LastAccessTime; System.Security.Principal.SecurityIdentifier sid = null; try { System.Security.AccessControl.FileSecurity fileSecurity = file.GetAccessControl(); sid = fileSecurity.GetOwner(typeof(System.Security.Principal.SecurityIdentifier)) as System.Security.Principal.SecurityIdentifier; System.Security.Principal.NTAccount ntAccount = sid.Translate(typeof(System.Security.Principal.NTAccount)) as System.Security.Principal.NTAccount; this.Owner = ntAccount.Value; } catch (System.Security.Principal.IdentityNotMappedException ex) { if (sid != null) { this.Owner = sid.ToString(); } else { this.Owner = "unknown"; } } catch (Exception ex) { this.Owner = "error:" + ex.ToString(); } }
/// <summary> /// 移除 指定目录 指定用户的 权限 /// </summary> /// <param name="DirectoryName"></param> /// <param name="Account"></param> public static void RemoveDirectoryAccountSecurity(string DirectoryName, string Account) { DirectoryInfo dInfo = new DirectoryInfo(DirectoryName); if (dInfo.Exists) { System.Security.Principal.NTAccount myAccount = new System.Security.Principal.NTAccount(System.Environment.MachineName, Account); DirectorySecurity dSecurity = dInfo.GetAccessControl(); FileSystemAccessRule AccessRule = new FileSystemAccessRule(Account, FileSystemRights.FullControl, AccessControlType.Allow); FileSystemAccessRule AccessRule2 = new FileSystemAccessRule(Account, FileSystemRights.FullControl, AccessControlType.Deny); InheritanceFlags iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit; PropagationFlags pFlags = PropagationFlags.InheritOnly | PropagationFlags.NoPropagateInherit; dSecurity.AccessRuleFactory(myAccount, 983551, false, iFlags, pFlags, AccessControlType.Allow); dSecurity.RemoveAccessRuleAll(AccessRule); dSecurity.RemoveAccessRuleAll(AccessRule2); dInfo.SetAccessControl(dSecurity); } }
[TestMethod, Ignore] //("does not work on some server/domain systems.") public void TestGetAccessControl() { var tempLongPathFilename = Path.Combine(longPathDirectory, Path.GetRandomFileName()); Directory.CreateDirectory(tempLongPathFilename); try { var di = new DirectoryInfo(tempLongPathFilename); var security = di.GetAccessControl(); Assert.IsNotNull(security); Assert.AreEqual(typeof(FileSystemRights), security.AccessRightType); Assert.AreEqual(typeof(FileSystemAccessRule), security.AccessRuleType); Assert.AreEqual(typeof(FileSystemAuditRule), security.AuditRuleType); Assert.IsTrue(security.AreAccessRulesCanonical); Assert.IsTrue(security.AreAuditRulesCanonical); Assert.IsFalse(security.AreAccessRulesProtected); Assert.IsFalse(security.AreAuditRulesProtected); AuthorizationRuleCollection perm = security.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)); var ntAccount = new System.Security.Principal.NTAccount(System.Security.Principal.WindowsIdentity.GetCurrent().Name); FileSystemAccessRule rule = perm.Cast<FileSystemAccessRule>().SingleOrDefault(e => ntAccount == e.IdentityReference); Assert.IsNotNull(rule); Assert.IsTrue((rule.FileSystemRights & FileSystemRights.FullControl) != 0); } finally { Directory.Delete(tempLongPathFilename); } }
protected override void ProcessRecord() { //OU can be passed as name or as dn var OUs = DirectoryUtils.GetOU(Identity); if (OUs.Count > 1) { foreach (ObjectInfo ou in OUs) { WriteObject(ou); } throw new AmbiguousResultException("More than one object found, search using distinguishedName instead"); } if (OUs.Count == 0) { throw new NotFoundException($"Object not found: {Identity}"); } ActiveDirectorySecurity sec = DirectoryUtils.GetObjectSecurity(conn, OUs[0].DistinguishedName, System.DirectoryServices.Protocols.SecurityMasks.Dacl); //apply permissions only to computer objects Guid inheritedObjectGuid = DirectoryUtils.GetSchemaGuid(conn, forestRootDomain.SchemaNamingContext, "computer", SchemaObjectType.Class); Guid timestampGuid; Guid pwdGuid; try { timestampGuid = DirectoryUtils.GetSchemaGuid(conn, forestRootDomain.SchemaNamingContext, Constants.TimestampAttributeName, SchemaObjectType.Attribute); } catch (Exception) { throw new NotFoundException($"Object not found: {Constants.TimestampAttributeName}"); } try { pwdGuid = DirectoryUtils.GetSchemaGuid(conn, forestRootDomain.SchemaNamingContext, Constants.PasswordAttributeName, SchemaObjectType.Attribute); } catch (Exception) { throw new NotFoundException($"Object not found: {Constants.PasswordAttributeName}"); } System.DirectoryServices.ActiveDirectoryAccessRule rule; foreach (string principalName in AllowedPrincipals) { System.Security.Principal.NTAccount principal = new System.Security.Principal.NTAccount(principalName); // read ms-Mcs-AdmPwdExpirationTime on computer objects rule = new System.DirectoryServices.PropertyAccessRule(principal, System.Security.AccessControl.AccessControlType.Allow, PropertyAccess.Read, timestampGuid, ActiveDirectorySecurityInheritance.Descendents, inheritedObjectGuid ); sec.AddAccessRule(rule); // read ms-Mcs-AdmPwd on computer objects rule = new System.DirectoryServices.PropertyAccessRule(principal, System.Security.AccessControl.AccessControlType.Allow, PropertyAccess.Read, pwdGuid, ActiveDirectorySecurityInheritance.Descendents, inheritedObjectGuid ); sec.AddAccessRule(rule); // control access on ms-Mcs-AdmPwd on computer objects rule = new System.DirectoryServices.ActiveDirectoryAccessRule(principal, ActiveDirectoryRights.ExtendedRight, System.Security.AccessControl.AccessControlType.Allow, pwdGuid, ActiveDirectorySecurityInheritance.Descendents, inheritedObjectGuid ); sec.AddAccessRule(rule); } DirectoryUtils.SetObjectSecurity(conn, OUs[0].DistinguishedName, sec, System.DirectoryServices.Protocols.SecurityMasks.Dacl); WriteObject(OUs[0]); }
private static void Main() { string[] args = Environment.GetCommandLineArgs(); if (args.Length > 1 && args[1] == "-setpermissions") { System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null); System.Security.Principal.NTAccount acct = sid.Translate(typeof(System.Security.Principal.NTAccount)) as System.Security.Principal.NTAccount; string strEveryoneAccount = acct.ToString(); GeneralHelper.AddDirectorySecurity(".\\", strEveryoneAccount, FileSystemRights.FullControl, InheritanceFlags.None, PropagationFlags.NoPropagateInherit, AccessControlType.Allow); GeneralHelper.AddDirectorySecurity(".\\", strEveryoneAccount, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly, AccessControlType.Allow); GeneralHelper.RemoveReadOnlyRecursive(".\\"); return; } string name = Path.GetFileNameWithoutExtension(Application.ExecutablePath); bool moved = false; #if DEBUG bool firstInstance = true; #else bool firstInstance = Process.GetProcessesByName(name).Length < 2; #endif string file = ""; if (args.Length > 1) { for (int i = 1; i < args.Length; i++) { file += args[i] + " "; } file = file.Trim(); moved = true; } if (!firstInstance) { Thread.Sleep(1500); firstInstance = Process.GetProcessesByName(name).Length < 2; if (!firstInstance && !moved) { if (DialogResult.OK == MessageBox.Show("osu! is already running!\nWould you like to force-kill the other copy?", name, MessageBoxButtons.OKCancel, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)) { KillStuckProcesses(name); int count = 0; while (count++ < 20 && !firstInstance) { Thread.Sleep(100); firstInstance = Process.GetProcessesByName(name).Length < 2; } if (!firstInstance) { MessageBox.Show("Killing failed. Please manually kill the process using Task Manager.", name, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); return; } } else { return; } } } if (moved || firstInstance) { if (firstInstance) { try { IPC.AcceptConnections(); } catch (Exception) { } } else { try { TcpClient c = new TcpClient("localhost", 13373); StreamWriter w = new StreamWriter(c.GetStream()); w.WriteLine(file); w.Flush(); c.Close(); } catch (Exception) { } return; } } Environment.CurrentDirectory = Application.StartupPath; using (GameBase game = new GameBase(file)) { if (File.Exists("_osume.exe")) { File.Delete("osume.exe"); File.Move("_osume.exe", "osume.exe"); GeneralHelper.ProcessStart("osume.exe"); } else #if !DEBUG { try { #endif game.Run(); } if (Restart) { GeneralHelper.ProcessStart("osu!.exe"); } #if !DEBUG }
public Boolean Authenticate() { System.Security.Principal.NTAccount userAccount; System.Security.Principal.NTAccount groupAccount; DateTime authenticationStartTime = DateTime.Now; if (((System.Threading.Thread.CurrentPrincipal.Identity.AuthenticationType == "NTLM") || (System.Threading.Thread.CurrentPrincipal.Identity.AuthenticationType == "Kerberos") || (System.Threading.Thread.CurrentPrincipal.Identity.AuthenticationType == "Negotiate")) && (System.Threading.Thread.CurrentPrincipal.Identity.IsAuthenticated) && (!String.IsNullOrEmpty(System.Threading.Thread.CurrentPrincipal.Identity.Name))) { // When using Windows Integrated (Negotiated) Authentication, the calling identity // is in the Thread.CurrentPrinicpal while the ASP.NET host identity is in the System.Security.Principal System.Diagnostics.Trace.WriteLineIf(traceSwitchSecurity.TraceVerbose, "\r\n[Mercury.Server.Security.WindowsIntegrated.Provider] Current Credentials"); System.Diagnostics.Trace.WriteLineIf(traceSwitchSecurity.TraceVerbose, "Server Thread Principal: " + System.Threading.Thread.CurrentPrincipal.Identity.Name); System.Diagnostics.Trace.WriteLineIf(traceSwitchSecurity.TraceVerbose, "Server System Principal: " + System.Security.Principal.WindowsIdentity.GetCurrent().Name); System.Diagnostics.Trace.WriteLineIf(traceSwitchSecurity.TraceVerbose, "Server Thread Authentication Type: " + System.Threading.Thread.CurrentPrincipal.Identity.AuthenticationType); threadIdentity = (System.Security.Principal.WindowsIdentity)System.Threading.Thread.CurrentPrincipal.Identity; userAccount = new System.Security.Principal.NTAccount(threadIdentity.Name); credentials.UserAccountId = threadIdentity.User.Value; if (userAccount.Value.Contains(@"\")) { credentials.UserAccountName = userAccount.Value.Split('\\')[1]; } else { credentials.UserAccountName = userAccount.Value; } credentials.UserDisplayName = GetUserDisplayName(credentials.UserAccountName); if (credentials.UserDisplayName == String.Empty) { credentials.UserDisplayName = credentials.UserAccountName; } System.Diagnostics.Trace.WriteLineIf(traceSwitchSecurity.TraceVerbose, "\r\n[Mercury.Server.Security.WindowsIntegrated.Provider] Thread Group Membership"); foreach (System.Security.Principal.IdentityReference currentGroup in threadIdentity.Groups) { groupAccount = (System.Security.Principal.NTAccount)currentGroup.Translate(typeof(System.Security.Principal.NTAccount)); if (!credentials.Groups.Contains(currentGroup.Value)) { credentials.Groups.Add(currentGroup.Value); } System.Diagnostics.Trace.WriteLineIf(traceSwitchSecurity.TraceVerbose, "[" + currentGroup.ToString() + "] " + groupAccount.Value); } credentials.AuthenticationTime = Convert.ToInt32(DateTime.Now.Subtract(authenticationStartTime).TotalMilliseconds); if (DateTime.Now.Subtract(authenticationStartTime).Seconds > 1) { System.Diagnostics.Trace.WriteLineIf(traceSwitchSecurity.TraceWarning, "Windows Integrated Authentication Time [Warning]: " + credentials.AuthenticationTime.ToString()); } else { System.Diagnostics.Trace.WriteLineIf(traceSwitchSecurity.TraceVerbose, "Windows Integrated Authentication Time: " + credentials.AuthenticationTime.ToString()); } return(true); } else // non-Windows account authentication in Thread.CurrentPrincipal { return(false); } }
static void Main(string[] args) { string root = ""; string newOwner = ""; string currentOwner = ""; for (uint argIndex = 0; argIndex < args.Length; ++argIndex) { string op = args[argIndex]; switch (op) { case "--root": { ++argIndex; if (argIndex < args.Length) { root = args[argIndex]; } else { PrintUsage(); return; } break; } case "--to": { ++argIndex; if (argIndex < args.Length) { newOwner = args[argIndex]; } else { PrintUsage(); return; } break; } case "--from": { ++argIndex; if (argIndex < args.Length) { currentOwner = args[argIndex]; } else { PrintUsage(); return; } break; } case "--dry-run": { sDryRun = true; break; } default: { Console.WriteLine("Unknown option '{0}'", op); PrintUsage(); break; } } } if (root == "" || newOwner == "") { PrintUsage(); return; } // Parse owner strings string SIDPattern = @"^S-\d-\d+-(\d+-){1,14}\d+$"; System.Security.Principal.IdentityReference currentOwnerId = null; if (currentOwner != "") { if (Regex.IsMatch(currentOwner, SIDPattern)) { Console.WriteLine("Current owner '{0}' is a SID", currentOwner); currentOwnerId = new System.Security.Principal.SecurityIdentifier(currentOwner); } else { Console.WriteLine("Current owner '{0}' is an NT Account", currentOwner); currentOwnerId = new System.Security.Principal.NTAccount(currentOwner); } } System.Security.Principal.IdentityReference newOwnerId; if (Regex.IsMatch(newOwner, SIDPattern)) { Console.WriteLine("New owner '{0}' is a SID", newOwner); newOwnerId = new System.Security.Principal.SecurityIdentifier(newOwner); } else { Console.WriteLine("New owner '{0}' is an NT Account", newOwner); newOwnerId = new System.Security.Principal.NTAccount(newOwner); } Console.WriteLine(); Console.WriteLine(); uint numDirsToProcess = 0; uint numDirsProcessed = 0; uint numFilesProcessed = 0; uint numReparsePoints = 0; DirectoryInfo rootDir = null; try { rootDir = new DirectoryInfo(root); } catch (Exception exception) { Console.WriteLine("Error opening directory '{0}': {1}", root, exception.Message); } if (rootDir != null && rootDir.Exists) { Stack <DirectoryInfo> searchStack = new Stack <DirectoryInfo>(); HashSet <string> visitedDirs = new HashSet <string>(); searchStack.Push(rootDir); visitedDirs.Add(rootDir.FullName); ++numDirsToProcess; ChangeOwner(rootDir, currentOwnerId, newOwnerId); while (searchStack.Count != 0) { DirectoryInfo dirInfo = searchStack.Pop(); ++numDirsProcessed; Console.SetCursorPosition(0, Math.Max(0, Console.CursorTop - 2)); try { // Change all files in dir IEnumerable <FileInfo> fileEntries = dirInfo.EnumerateFiles(); foreach (FileInfo fileEntry in fileEntries) { ChangeOwner(fileEntry, currentOwnerId, newOwnerId); ++numFilesProcessed; } // Change and add all subdirs IEnumerable <DirectoryInfo> dirEntries = dirInfo.EnumerateDirectories(); foreach (DirectoryInfo dirEntry in dirEntries) { // Ignore reparse points if ((dirEntry.Attributes & FileAttributes.ReparsePoint) == 0) { ++numDirsToProcess; ChangeOwner(dirEntry, currentOwnerId, newOwnerId); searchStack.Push(dirEntry); visitedDirs.Add(dirEntry.FullName); } else { ++numReparsePoints; } } } catch (Exception exception) { Console.WriteLine("Exception '{0}'", exception.Message); } Console.WriteLine("Processed {0}\\{1} directories", numDirsProcessed, numDirsToProcess); Console.WriteLine("Processed {0} files", numFilesProcessed); } } Console.WriteLine("-------------------------"); Console.WriteLine(" Summary"); Console.WriteLine("-------------------------"); Console.WriteLine("Successfully changed {0} directories and files", sNumChanged); Console.WriteLine("Skipped {0} linked directories", numReparsePoints); Console.WriteLine(); }
static void AddWriteAccess(string keyName) { try { TokenManipulator.AddPrivilege("SeRestorePrivilege"); TokenManipulator.AddPrivilege("SeBackupPrivilege"); TokenManipulator.AddPrivilege("SeTakeOwnershipPrivilege"); //HKEY_CLASSES_ROOT //HKEY_CURRENT_USER //HKEY_LOCAL_MACHINE RegistryKey root = null; string localName = null; if (keyName.StartsWith("HKEY_CLASSES_ROOT")) { root = Registry.ClassesRoot; localName = keyName.Substring(18); } else if (keyName.StartsWith("HKEY_CURRENT_USER")) { root = Registry.CurrentUser; localName = keyName.Substring(18); } else if (keyName.StartsWith("HKEY_LOCAL_MACHINE")) { root = Registry.LocalMachine; localName = keyName.Substring(19); } else { throw new InvalidOperationException("Unsupported registry root"); } using (var thing = root.OpenSubKey(localName, RegistryKeyPermissionCheck.ReadWriteSubTree, System.Security.AccessControl.RegistryRights.TakeOwnership)) { if (thing != null) { //change owner to Administrators and give administrators full rights var acl = thing.GetAccessControl(); var admins = new System.Security.Principal.NTAccount("Administrators"); acl.SetOwner(admins); thing.SetAccessControl(acl); var acl2 = thing.GetAccessControl(); acl2.AddAccessRule(new RegistryAccessRule(admins, RegistryRights.FullControl, AccessControlType.Allow)); thing.SetAccessControl(acl2); Console.WriteLine("Added write permissions for Administrator"); } } using (var thing = root.OpenSubKey(localName, RegistryKeyPermissionCheck.ReadWriteSubTree, System.Security.AccessControl.RegistryRights.TakeOwnership | RegistryRights.FullControl)) { if (thing != null) { //change ownership back to TrustedInstaller var acl = thing.GetAccessControl(); var account = new System.Security.Principal.NTAccount(@"NT SERVICE\TrustedInstaller"); acl.SetOwner(account); thing.SetAccessControl(acl); Console.WriteLine("Restored Ownership to TrustedInstaller"); } } } catch (Exception) { throw; } finally { TokenManipulator.RemovePrivilege("SeRestorePrivilege"); TokenManipulator.RemovePrivilege("SeBackupPrivilege"); TokenManipulator.RemovePrivilege("SeTakeOwnershipPrivilege"); } }
static void _DfsGetPartsNoWildcard(string[] args, int startparts, int lastparts) { if (!dfs.DfsConfigExists(DFSXMLPATH)) { Console.Error.WriteLine("DFS not setup; use: {0} format", appname); SetFailure(); return; } if (args.Length < 2) { Console.Error.WriteLine("dfs get error: {0} dfs get <dfspath> <localpath>", appname); SetFailure(); return; } string dfspath = args[0]; if (dfspath.StartsWith("dfs://", StringComparison.OrdinalIgnoreCase)) { dfspath = dfspath.Substring(6); } if (dfspath.Length == 0) { Console.Error.WriteLine("Invalid dfspath"); SetFailure(); return; } string localpath = args[1]; //System.Threading.Thread.Sleep(8000); string localstartname = localpath; string localendname = ""; { // Remove ext... int ildot = localstartname.LastIndexOf('.'); if (-1 != ildot) { bool anotherdotcheck = (localstartname.Length - ildot <= 4); localstartname = localstartname.Substring(0, ildot); if (anotherdotcheck) { ildot = localstartname.LastIndexOf('.'); if (-1 != ildot) { if (localstartname.Length - ildot <= 4) { localstartname = localstartname.Substring(0, ildot); } } } } } localendname = localpath.Substring(localstartname.Length); // e.g. ".txt.gz" if (!localendname.EndsWith(".gz", StringComparison.OrdinalIgnoreCase)) { localendname += ".gz"; } localstartname += ".part"; { string edir = "."; string efile = localstartname + "*" + localendname; { int ilslash = efile.LastIndexOfAny(new char[] { '/', '\\' }); if (-1 != ilslash) { edir = efile.Substring(0, ilslash); efile = efile.Substring(ilslash + 1); } } string[] existparts = System.IO.Directory.GetFiles(edir, efile); if (existparts.Length != 0) { /* Console.Error.WriteLine("Abort: output files already exist"); SetFailure(); return; * */ if (QuietMode || !InteractiveMode) { Console.Error.WriteLine("The specified file(s) already exists locally: {0}", localstartname + "*" + localendname); SetFailure(); return; } Console.Write("The specified file(s) already exists locally; overwrite? "); ConsoleFlush(); for (; ; ) { string s = Console.ReadLine(); char ch = '\0'; if (0 != s.Length) { ch = char.ToUpper(s[0]); } if ('N' == ch) { Console.WriteLine(" Aborted by user"); return; } else if ('Y' == ch) { break; // ! } else { Console.Write("Overwrite, yes or no? "); ConsoleFlush(); } } // Delete them before writing; new output might have less part count. for (int i = 0; i < existparts.Length; i++) { System.IO.File.Delete(existparts[i]); } } } int ncpus = Surrogate.NumberOfProcessors; dfs dc = LoadDfsConfig(); dfs.DfsFile df = DfsFind(dc, dfspath); if (null == df) { Console.Error.WriteLine("Error: File not found in DFS: {0}", dfspath); SetFailure(); return; } Console.WriteLine("Getting GZip parts of DFS file '{1}'...", df.Nodes.Count, df.Name); List<System.Threading.Thread> threads = new List<System.Threading.Thread>(ncpus); GettingParts gp = new GettingParts(); gp.dc = dc; //gp.parts = df.Nodes; gp.parts = new List<dfs.DfsFile.FileNode>(); bool hitlimit = false; for (int dn = 0; dn < df.Nodes.Count; dn++) { if (dn > lastparts) { hitlimit = true; break; } gp.parts.Add(df.Nodes[dn]); } gp.nextpart = startparts; gp.localendname = localendname; gp.localstartname = localstartname; { System.Security.Principal.NTAccount nt = new System.Security.Principal.NTAccount(userdomain, dousername); System.Security.Principal.SecurityIdentifier secID = (System.Security.Principal.SecurityIdentifier)nt.Translate(typeof(System.Security.Principal.SecurityIdentifier)); System.Security.AccessControl.FileSystemAccessRule rule = new System.Security.AccessControl.FileSystemAccessRule(secID, System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow); gp.rule = rule; } for (int i = 0; i < ncpus; i++) { System.Threading.Thread thd = new System.Threading.Thread(new System.Threading.ThreadStart(gp.threadproc)); thd.Start(); threads.Add(thd); } for (int i = 0; i < threads.Count; i++) { threads[i].Join(); } //if (verbose) { if (hitlimit) { Console.WriteLine("Done with partial get {0}-{1}", startparts, lastparts); } else { Console.WriteLine("Done"); } } Console.WriteLine("Files written to '{0}N{1}'", localstartname, localendname); }
// <dfspath> <localpath> static void _DfsGetNoWildcard(string[] args, int startparts, int lastparts) { //System.Threading.Thread.Sleep(8000); if (!dfs.DfsConfigExists(DFSXMLPATH)) { Console.Error.WriteLine("DFS not setup; use: {0} format", appname); SetFailure(); return; } if (args.Length < 2) { Console.Error.WriteLine("dfs get error: {0} dfs get <dfspath> <localpath>", appname); SetFailure(); return; } { string dfspath = args[0]; if (dfspath.StartsWith("dfs://", StringComparison.OrdinalIgnoreCase)) { dfspath = dfspath.Substring(6); } if (dfspath.Length == 0) { Console.Error.WriteLine("Invalid dfspath"); SetFailure(); return; } string localpath = args[1]; EnsureNetworkPath(localpath); if (localpath.EndsWith(".gz")) { //Console.Error.WriteLine("Error: dfs get not supported for GZip (.gz) files; use dfs getgzip"); //SetFailure(); _DfsGetPartsNoWildcard(args, startparts, lastparts); return; } if (!System.IO.File.Exists(localpath)) { string folderPath = localpath; System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(folderPath); if (di.Exists) localpath += "\\" + args[0]; else if(!di.Parent.Exists) { Console.Error.WriteLine("Specified path does not exist, double check existance of the folders in the path"); return; } } if (System.IO.File.Exists(localpath)) { if (QuietMode || !InteractiveMode) { Console.Error.WriteLine("The specified file already exists locally: {0}", localpath); SetFailure(); return; } Console.Write("The specified file already exists locally; overwrite? "); ConsoleFlush(); for (; ; ) { string s = Console.ReadLine(); char ch = '\0'; if (0 != s.Length) { ch = char.ToUpper(s[0]); } if ('N' == ch) { Console.WriteLine(" Aborted by user"); return; } else if ('Y' == ch) { break; // ! } else { Console.Write("Overwrite, yes or no? "); ConsoleFlush(); } } } const int MAX_SIZE_PER_RECEIVE = 0x400 * 64; byte[] fbuf = new byte[MAX_SIZE_PER_RECEIVE]; dfs dc = LoadDfsConfig(); dfs.DfsFile dfsf = DfsFindAny(dc, dfspath); if (null == dfsf) { Console.Error.WriteLine("Error: The specified file '{0}' does not exist in DFS", dfspath); SetFailure(); return; } if (0 != string.Compare(dfsf.Type, DfsFileTypes.NORMAL, StringComparison.OrdinalIgnoreCase) && 0 != string.Compare(dfsf.Type, DfsFileTypes.BINARY_RECT, StringComparison.OrdinalIgnoreCase)) { Console.Error.WriteLine("DFS file '{0}' is not of expected type", dfsf.Name); SetFailure(); return; } bool warned = false; long curfilepos = 0; using (System.IO.FileStream _fs = new System.IO.FileStream(localpath, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write, System.IO.FileShare.Read, FILE_BUFFER_SIZE)) { System.IO.Stream fs = _fs; /*if (localpath.EndsWith(".gz")) { //if (verbose) { Console.WriteLine("Warning: GZip (.gz) does not suport files over 4 GB in size; use 'dfs getgzip' if large file support is ever needed"); } fs = new System.IO.Compression.GZipStream(_fs, System.IO.Compression.CompressionMode.Compress); }*/ bool hitlimit = false; for (int dn = startparts; dn < dfsf.Nodes.Count; dn++) { if (dn > lastparts) { //if (verbose) { Console.WriteLine(" Done with partial get {0}-{1}", startparts, lastparts); } hitlimit = true; break; } dfs.DfsFile.FileNode node = dfsf.Nodes[dn]; if (curfilepos != node.Position) { if (-1 != node.Position) { if (!warned) { warned = true; if (startparts != 0) { LogOutput("1 or more parts of the file are not received. Index of parts for this file starts from 0 to " + (dfsf.Nodes.Count - 1).ToString()); } else { LogOutput("Warning: file positions do not line up; " + dfs.DFSXMLNAME + " or data-node chunks may be corrupted"); } //return; } } } using (System.IO.Stream _fc = new DfsFileNodeStream(node, true, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read, FILE_BUFFER_SIZE)) { System.IO.Stream fc = _fc; if (1 == dc.slave.CompressDfsChunks) { fc = new System.IO.Compression.GZipStream(_fc, System.IO.Compression.CompressionMode.Decompress); } { int xread = StreamReadLoop(fc, fbuf, 4); if (4 == xread) { int hlen = MySpace.DataMining.DistributedObjects.Entry.BytesToInt(fbuf); StreamReadExact(fc, fbuf, hlen - 4); } } for (; ; ) { int xread = fc.Read(fbuf, 0, MAX_SIZE_PER_RECEIVE); if (xread <= 0) { break; } fs.Write(fbuf, 0, xread); curfilepos += xread; } fc.Close(); } } if (!hitlimit) { if (curfilepos != dfsf.Size) { if (-1 != dfsf.Size) { if (!warned) { warned = true; if (startparts != 0) { LogOutput("1 or more parts of the file are not received. Index of parts for this file starts from 0 to " + (dfsf.Nodes.Count - 1).ToString()); } else { LogOutput("Warning: file data received is not correct resulting size; " + dfs.DFSXMLNAME + " or data-node chunks may be corrupted"); } //return; } } } } fs.Close(); try { System.Security.Principal.NTAccount nt = new System.Security.Principal.NTAccount(userdomain, dousername); System.Security.Principal.SecurityIdentifier secID = (System.Security.Principal.SecurityIdentifier)nt.Translate(typeof(System.Security.Principal.SecurityIdentifier)); System.Security.AccessControl.FileSystemAccessRule rule = new System.Security.AccessControl.FileSystemAccessRule(secID, System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow); System.Security.AccessControl.FileSecurity fsec = new System.Security.AccessControl.FileSecurity(); fsec.AddAccessRule(rule); System.IO.File.SetAccessControl(localpath, fsec); } catch(Exception e) { Console.Error.WriteLine("Error while assigning file permission to: {0}\\{1}", userdomain, dousername); Console.Error.WriteLine(e.ToString()); } } Console.WriteLine("Received {0} bytes to file {1}", curfilepos, localpath); } }
/// <summary> /// 记录日志 /// </summary> /// <param name="logFilePath"></param> /// <param name="msg"></param> public void WriteLog(string logFilePath, string msg) { string filePostfix = logFilePath.Substring(logFilePath.LastIndexOf('.') + 1); try { System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(this.LogFileFolderPath); if (!dir.Exists) { System.Security.AccessControl.DirectorySecurity ds = new System.Security.AccessControl.DirectorySecurity(); //Everyone账户 System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null); System.Security.Principal.NTAccount acct = sid.Translate(typeof(System.Security.Principal.NTAccount)) as System.Security.Principal.NTAccount; ds.AddAccessRule( new System.Security.AccessControl.FileSystemAccessRule( acct , System.Security.AccessControl.FileSystemRights.FullControl , System.Security.AccessControl.AccessControlType.Allow) ); dir.Create(ds); } else { System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(() => { DeleteOldFiles(); })); t.Start(); t.Join(); } if (!string.Equals("txt", filePostfix, StringComparison.OrdinalIgnoreCase)) { throw new Exception("仅支持txt文件"); } bool bAppend = true; System.IO.FileInfo f = new System.IO.FileInfo(logFilePath); if (!f.Exists || f.Length > this.MaxFileSize)//文件太大,清空旧内容 { bAppend = false; } lock (objlck) { using (System.IO.StreamWriter sw = new System.IO.StreamWriter(logFilePath, bAppend)) { string logContent = string.Format("\r\n=======================" + "\r\n{0}" + "\r\n{1}" + "\r\n=======================\r\n", DateTime.Now.ToString("[yyyy-MM-dd HH:mm:ss] "), msg); sw.Write(logContent); sw.Flush(); sw.Close(); } } } catch (Exception ex) { throw ex; } }
static int _DfsGetBinaryNoWildCard(string dfspath, string targetFolder) { if (!targetFolder.EndsWith(@"\")) { targetFolder += @"\"; } if (!dfs.DfsConfigExists(DFSXMLPATH)) { Console.Error.WriteLine("DFS not setup; use: {0} format", appname); SetFailure(); return 0; } if (dfspath.StartsWith("dfs://", StringComparison.OrdinalIgnoreCase)) { dfspath = dfspath.Substring(6); } if (dfspath.Length == 0) { Console.Error.WriteLine("Invalid dfspath"); SetFailure(); return 0; } EnsureNetworkPath(targetFolder); if (!System.IO.Directory.Exists(targetFolder)) { Console.Error.WriteLine("Target folder is not found: {0}", targetFolder); return 0; } dfs dc = LoadDfsConfig(); dfs.DfsFile dfsf = DfsFind(dc, dfspath); if (null == dfsf) { Console.Error.WriteLine("Error: The specified file '{0}' does not exist in DFS", dfspath); SetFailure(); return 0; } int blobPadSize = MySpace.DataMining.DistributedObjects.Blob.padSize; const int MAX_SIZE_PER_RECEIVE = 0x400 * 16 * 4; int filesCount = 0; byte[] fbuf = new byte[MAX_SIZE_PER_RECEIVE]; System.Security.Principal.NTAccount nt = new System.Security.Principal.NTAccount(userdomain, dousername); System.Security.Principal.SecurityIdentifier secID = (System.Security.Principal.SecurityIdentifier)nt.Translate(typeof(System.Security.Principal.SecurityIdentifier)); System.Security.AccessControl.FileSystemAccessRule rule = new System.Security.AccessControl.FileSystemAccessRule(secID, System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow); List<string> perrors = new List<string>(); foreach (dfs.DfsFile.FileNode node in dfsf.Nodes) { bool eof = false; bool newline = false; System.IO.Stream fs = null; System.IO.FileStream ft = null; try { fs = new DfsFileNodeStream(node, true, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read, FILE_BUFFER_SIZE); { int xhead = StreamReadLoop(fs, fbuf, 4); if (4 == xhead) { int hlen = MySpace.DataMining.DistributedObjects.Entry.BytesToInt(fbuf); StreamReadExact(fs, fbuf, hlen - 4); } } while (!eof) { if (newline) { if (ft != null) { ft.Close(); ft = null; } } int xread = 0; while (xread < MAX_SIZE_PER_RECEIVE) { newline = false; int ib = fs.ReadByte(); if (ib == -1) { eof = true; break; } if ('\n' == ib) { newline = true; break; } if (ib != '\r') { fbuf[xread++] = (byte)ib; } } string s = System.Text.Encoding.UTF8.GetString(fbuf, 0, xread); if (s.Length > 0) { if (ft == null) { string targetPath = targetFolder + s.Substring(0, blobPadSize).Trim(); s = s.Substring(260); if (System.IO.File.Exists(targetPath)) { Console.Error.WriteLine("Warning: Local file overwritten: {0}", targetPath); } ft = new System.IO.FileStream(targetPath, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.Read, FILE_BUFFER_SIZE); filesCount++; try { System.Security.AccessControl.FileSecurity fsec = new System.Security.AccessControl.FileSecurity(); fsec.AddAccessRule(rule); System.IO.File.SetAccessControl(targetPath, fsec); } catch (Exception e) { perrors.Add(e.ToString()); } } byte[] data = Convert.FromBase64String(s); ft.Write(data, 0, data.Length); } } } catch (Exception e) { Console.Error.WriteLine("Error: {0}", e.Message); } finally { if (ft != null) { ft.Close(); ft = null; } if (fs != null) { fs.Close(); fs = null; } } } if (perrors.Count > 0) { Console.Error.WriteLine("Error while assigning file permission to: {0}\\{1}", userdomain, dousername); foreach (string perr in perrors) { Console.Error.WriteLine(perr); } } return filesCount; }
public void TestGetAccessControlSections() { var filename = Util.CreateNewFile(longPathDirectory); try { var security = File.GetAccessControl(filename, AccessControlSections.Access); Assert.IsNotNull(security); Assert.AreEqual(typeof(FileSystemRights), security.AccessRightType); Assert.AreEqual(typeof(FileSystemAccessRule), security.AccessRuleType); Assert.AreEqual(typeof(FileSystemAuditRule), security.AuditRuleType); Assert.IsTrue(security.AreAccessRulesCanonical); Assert.IsTrue(security.AreAuditRulesCanonical); Assert.IsFalse(security.AreAccessRulesProtected); Assert.IsFalse(security.AreAuditRulesProtected); var securityGetAccessRules = security.GetAuditRules(true, true, typeof(System.Security.Principal.NTAccount)).Cast<FileSystemAccessRule>(); Assert.AreEqual(0, securityGetAccessRules.Count()); AuthorizationRuleCollection perm = security.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)); var ntAccount = new System.Security.Principal.NTAccount(System.Security.Principal.WindowsIdentity.GetCurrent().Name); FileSystemAccessRule rule = perm.Cast<FileSystemAccessRule>().SingleOrDefault(e => ntAccount == e.IdentityReference); Assert.IsNotNull(rule); Assert.IsTrue((rule.FileSystemRights & FileSystemRights.FullControl) != 0); } finally { File.Delete(filename); } }
public static IEnumerable <string> ConvertTo_SID(Args_ConvertTo_SID args = null) { if (args == null) { args = new Args_ConvertTo_SID(); } var DomainSearcherArguments = new Args_Get_DomainObject { Domain = args.Domain, Server = args.Server, Credential = args.Credential }; var SIDs = new List <string>(); foreach (var item in args.ObjectName) { var name = item.Replace(@"/", @"\"); if (args.Credential != null) { var DN = ConvertADName.Convert_ADName(new Args_Convert_ADName { Identity = new[] { name }, OutputType = ADSNameType.DN, Domain = DomainSearcherArguments.Domain, Server = DomainSearcherArguments.Server, Credential = DomainSearcherArguments.Credential }); if (DN != null) { var UserDomain = DN.First().Substring(DN.First().IndexOf(@"DC=")).Replace(@"DC=", @"").Replace(@",", @"."); var UserName = DN.First().Split(',')[0].Split('=')[1]; DomainSearcherArguments.Identity = new[] { UserName }; DomainSearcherArguments.Domain = UserDomain; DomainSearcherArguments.Properties = new[] { @"objectsid" }; var obj = GetDomainObject.Get_DomainObject(DomainSearcherArguments); foreach (LDAPProperty ldapProperty in obj) { SIDs.AddRange(ldapProperty.objectsid); } } } else { try { if (name.Contains(@"\")) { args.Domain = name.Split('\\')[0]; name = name.Split('\\')[1]; } else if (args.Domain.IsNullOrEmpty()) { args.Domain = GetDomain.Get_Domain().Name; } var obj = new System.Security.Principal.NTAccount(args.Domain, name); SIDs.Add(obj.Translate(typeof(System.Security.Principal.SecurityIdentifier)).Value); } catch (Exception e) { Logger.Write_Verbose($@"[ConvertTo-SID] Error converting {args.Domain}\{name} : {e}"); } } } return(SIDs); }