private static string GetAuthenticatedUsersAccount() { var sid = new System.Security.Principal.SecurityIdentifier("S-1-5-11"); //Authenticated Users var account = sid.Translate(typeof(System.Security.Principal.NTAccount)); return(account.Value); }
private static string GetUsersGroupName() { const string builtInUsersGroup = "S-1-5-32-545"; var sid = new System.Security.Principal.SecurityIdentifier(builtInUsersGroup); var ntAccount = (System.Security.Principal.NTAccount)sid.Translate(typeof(System.Security.Principal.NTAccount)); return(ntAccount.Value); }
private static System.IO.Pipes.NamedPipeServerStream GetPipeServer(string aPipeName, System.IO.Pipes.PipeDirection aDir) { //Get "Everyone" for localized OS: http://social.msdn.microsoft.com/forums/en-US/netfxbcl/thread/0737f978-a998-453d-9a6a-c348285d7ea3/ 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; System.IO.Pipes.PipeSecurity ps = new System.IO.Pipes.PipeSecurity(); System.IO.Pipes.PipeAccessRule par = new System.IO.Pipes.PipeAccessRule(acct, System.IO.Pipes.PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow); ps.AddAccessRule(par); return new System.IO.Pipes.NamedPipeServerStream(aPipeName, aDir, 1, System.IO.Pipes.PipeTransmissionMode.Message, System.IO.Pipes.PipeOptions.None, 4096, 4096, ps); }
public IActionResult Index() { ClaimsPrincipal claimsPrincipal = ClaimsPrincipal.Current; List <string> groupIds = User.Identities.First().Claims.Where(c => c.Type == "groups").Select(c => c.Value).ToList(); List <string> roles = ((ClaimsIdentity)User.Identity).Claims.Where(q => q.Type == ClaimTypes.GroupSid).Select(q => q.Value).ToList(); foreach (string role in roles) { var name = new System.Security.Principal.SecurityIdentifier(role).Translate(typeof(System.Security.Principal.NTAccount)).ToString(); } bool hasClaim = ((ClaimsIdentity)User.Identity).HasClaim("groups", "AdminPortalAccess"); hasClaim = ((ClaimsIdentity)User.Identity).HasClaim("role", "AdminPortalAccess"); //hasClaim = ((ClaimsIdentity)User.Identity).IsInRole("AdminPortalAccess"); foreach (string groupId in groupIds) { hasClaim = ((ClaimsIdentity)User.Identity).HasClaim("groups", groupId); System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(groupId); string test = sid.Translate(typeof(System.Security.Principal.NTAccount)).ToString(); } // ClaimsIdentity userClaimsId = claimsPrincipal.Identity as ClaimsIdentity; //UserGroupsAndDirectoryRoles userGroupsAndDirectoryRoles = TokenHelper.GetUsersGroupsAsync(ClaimsPrincipal.Current).Result; //List<string> userGroupsAndId = userGroupsAndDirectoryRoles.GroupIds; //string userObjectId = Util.GetSignedInUsersObjectIdFromClaims(); //userGroupsAndId.Add(userObjectId); // Microsoft.Azure.ActiveDirectory.GraphClient.Group graphClient = new Microsoft.Azure.ActiveDirectory.GraphClient.Group() //MSGraphClient msGraphClient = new MSGraphClient(ConfigHelper.Authority, new ADALTokenCache(Util.GetSignedInUsersObjectIdFromClaims())); //User user = await msGraphClient.GetMeAsync(); //UserGroupsAndDirectoryRoles userGroupsAndDirectoryRoles = await msGraphClient.GetCurrentUserGroupsAndRolesAsync(); //IList<Group> groups = await msGraphClient.GetCurrentUserGroupsAsync(); //IList<DirectoryRole> directoryRoles = await msGraphClient.GetCurrentUserDirectoryRolesAsync(); //List<System.Security.Claims.Claim> claims = HttpContext.User.Claims.ToList(); return(View()); }
private static string friendlyTrusteeName(string trustee) { if (Trustee.Keys.Contains(trustee)) { return(Trustee[trustee]); } else { try { System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(trustee); return(sid.Translate(typeof(System.Security.Principal.NTAccount)).ToString()); } catch (Exception) { return(trustee); } } }
/// <summary> /// Sets permissions on a file directory /// </summary> /// <param name="directoryObject">Directory to set permissions for</param> /// <param name="fileRights">Type of directory file rights to set</param> /// <param name="accessControlType">Type of access control to set</param> /// <param name="strSpecificUserName">Optional: Specific username to set permissions for</param> /// <param name="boolAllowEveryOne">Optional: Flag to determine whether or not to set permissions for all users</param> /// <returns></returns> internal static Globals.ResultType SetPermissions(this DirectoryObject directoryObject, FileSystemRights fileRights, AccessControlType accessControlType, string strSpecificUserName = "", bool boolAllowEveryOne = false) { try { // Get User Name string strFQUserName = (strSpecificUserName == "") ? Environment.UserDomainName + "\\" + Environment.UserName : strSpecificUserName; // Check Optional Bool AllowEveryone if (boolAllowEveryOne == true) { // Create New Security Identifier var sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.BuiltinUsersSid, null); // Get Fully Qualified UserName strFQUserName = ((System.Security.Principal.NTAccount)sid.Translate(typeof(System.Security.Principal.NTAccount))).ToString(); } // Create DirectoryInfo DirectoryInfo directoryInfo = new DirectoryInfo(directoryObject.FilePath); // Get Directory Security Settings DirectorySecurity directorySecurity = directoryInfo.GetAccessControl(); // Create Access Rule FileSystemAccessRule directoryAccessRule = new FileSystemAccessRule(strFQUserName, fileRights, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, accessControlType); // Add the FileSystemAccessRule to the Security Settings. directorySecurity.AddAccessRule(directoryAccessRule); // Set Access Control directoryInfo.SetAccessControl(directorySecurity); return(Globals.ResultType.Success); } catch (Exception ex) { // To Be Implemented: Throw Custom Exception... Console.WriteLine(ex.ToString()); return(Globals.ResultType.Failure); } }
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 string GetProcessUserName(System.Diagnostics.Process process = null) { if (process == null) { process = System.Diagnostics.Process.GetCurrentProcess(); } if (process.HasExited) { return(""); } SafeTokenHandle hToken = null; try { if (!NativeMethods.OpenProcessToken(process.Handle, NativeMethods.TOKEN_QUERY, out hToken)) { return(""); } } catch (Exception) { return(""); } uint TokenInfLength = 0; bool Result; // first call gets lenght of TokenInformation Result = GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenUser, IntPtr.Zero, TokenInfLength, out TokenInfLength); IntPtr TokenInformation = Marshal.AllocHGlobal(int.Parse(TokenInfLength.ToString())); Result = GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenUser, TokenInformation, TokenInfLength, out TokenInfLength); if (Result) { TOKEN_USER TokenUser = (TOKEN_USER)Marshal.PtrToStructure(TokenInformation, typeof(TOKEN_USER)); var a = new System.Security.Principal.SecurityIdentifier(TokenUser.User.Sid); return(a.Translate(typeof(System.Security.Principal.NTAccount)).ToString()); } return(""); }
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> /// Updates the UI with details from the job /// </summary> /// <param name="job">The job must always be non-null</param> public void SetJob(BITS.IBackgroundCopyJob job) { Job = job ?? throw new ArgumentNullException("job"); // Update the details BITS.BG_JOB_STATE currState; Job.GetState(out currState); // time details (Create/Modified/Completed) // The DateTime.ToString("F") makes a date + time string in the user's locale. BITS._BG_JOB_TIMES times; Job.GetTimes(out times); var time = MakeDateTime(times.CreationTime); _uiJobCreationTime.Text = time > DateTime.MinValue ? time.ToString("F") : Properties.Resources.JobTimeNotSet; time = MakeDateTime(times.ModificationTime); _uiJobModificationTime.Text = time > DateTime.MinValue ? time.ToString("F") : Properties.Resources.JobTimeNotSet; time = MakeDateTime(times.TransferCompletionTime); _uiJobTransferCompletionTime.Text = time > DateTime.MinValue ? time.ToString("F") : Properties.Resources.JobTimeNotSet; // Progress details (Bytes/Files) BITS._BG_JOB_PROGRESS progress; Job.GetProgress(out progress); var files = String.Format( Properties.Resources.JobProgressFileCount, progress.FilesTransferred, progress.FilesTotal); var bytes = progress.BytesTotal == ulong.MaxValue ? String.Format( Properties.Resources.JobProgressByteCountUnknown, progress.BytesTransferred) : String.Format( Properties.Resources.JobProgressByteCount, progress.BytesTransferred, progress.BytesTotal); _uiJobProgressFiles.Text = files; _uiJobProgressBytes.Text = bytes; // Error details (HRESULT, Context, Description) uint NError = 0; BITS.IBackgroundCopyError Error; BITS.BG_ERROR_CONTEXT ErrorContext; int ErrorHRESULT; string ErrorContextDescription; string ErrorDescription; int langid = System.Globalization.CultureInfo.CurrentUICulture.LCID; langid = (langid & 0xFFFF); // Equivilent of LANGIDFROMLCID(GetThreadLocale()). BITS takes in the LANGID Job.GetErrorCount(out NError); if (NError == 0) { _uiJobErrorCount.Text = Properties.Resources.JobErrorNoErrors; _uiJobError.Text = ""; } else // (NError > 0) { _uiJobErrorCount.Text = NError.ToString("N0"); // Locale-specific numeric with no decimal places if (currState != BITS.BG_JOB_STATE.BG_JOB_STATE_ERROR && currState != BITS.BG_JOB_STATE.BG_JOB_STATE_TRANSIENT_ERROR) { _uiJobError.Text = Properties.Resources.JobErrorWhenError; } else { try { Job.GetError(out Error); Error.GetError(out ErrorContext, out ErrorHRESULT); Error.GetErrorDescription((uint)langid, out ErrorDescription); Error.GetErrorContextDescription((uint)langid, out ErrorContextDescription); var errorText = String.Format("\t{0} \t0x{1:X08}\n\t{2} \t{3}{4}\t{5} \t{6}", Properties.Resources.JobErrorHRESULT, ErrorHRESULT, Properties.Resources.JobErrorDescription, ErrorDescription, ErrorDescription.EndsWith("\n") ? "" : "\n", Properties.Resources.JobErrorContext, ErrorContextDescription ); _uiJobError.Text = errorText; } catch (System.Runtime.InteropServices.COMException) { _uiJobError.Text = Properties.Resources.JobErrorException; } } } string jobOwner; Job.GetOwner(out jobOwner); // convert the user sid to a domain\name var identifier = new System.Security.Principal.SecurityIdentifier(jobOwner); if (identifier.IsValidTargetType(typeof(System.Security.Principal.NTAccount))) { string account = identifier.Translate(typeof(System.Security.Principal.NTAccount)).ToString(); _uiJobOwner.Text = account; } else { _uiJobOwner.Text = jobOwner; } // Job priority details BITS.BG_JOB_PRIORITY jobPriority; Job.GetPriority(out jobPriority); _uiJobPriority.Text = BitsConversions.ConvertJobPriorityToString(jobPriority); // Job Type details BITS.BG_JOB_TYPE jobType; Job.GetType(out jobType); _uiJobType.Text = BitsConversions.ConvertJobTypeToString(jobType); // Job State details BITS.BG_JOB_STATE jobState; Job.GetState(out jobState); _uiJobState.Text = BitsConversions.ConvertJobStateToString(jobState); // Values from IBackgroundCopyJob5 Property interface // COST_FLAGS, DYNAMIC_CONTENT, HIGH_PERFORMANCE, ON_DEMAND_MODE BITS5.IBackgroundCopyJob5 job5 = job as BITS5.IBackgroundCopyJob5; if (job5 == null) { _uiJobCost.Text = Properties.Resources.JobCostNotAvailable; _uiJobFlags.Text = Properties.Resources.JobFlagsNotAvailable; } else { BITS5.BITS_JOB_PROPERTY_VALUE cost; job5.GetProperty(BITS5.BITS_JOB_PROPERTY_ID.BITS_JOB_PROPERTY_ID_COST_FLAGS, out cost); var costString = BitsConversions.ConvertCostToString((BitsCosts)cost.Dword); _uiJobCost.Text = costString; var flagBuilder = new StringBuilder(); BITS5.BITS_JOB_PROPERTY_VALUE flagValue; job5.GetProperty(BITS5.BITS_JOB_PROPERTY_ID.BITS_JOB_PROPERTY_DYNAMIC_CONTENT, out flagValue); if (flagValue.Enable != 0) { if (flagBuilder.Length > 0) { flagBuilder.Append(", "); } flagBuilder.Append(Properties.Resources.JobFlagsDynamic); } job5.GetProperty(BITS5.BITS_JOB_PROPERTY_ID.BITS_JOB_PROPERTY_HIGH_PERFORMANCE, out flagValue); if (flagValue.Enable != 0) { if (flagBuilder.Length > 0) { flagBuilder.Append(", "); } flagBuilder.Append(Properties.Resources.JobFlagsHighPerformance); } job5.GetProperty(BITS5.BITS_JOB_PROPERTY_ID.BITS_JOB_PROPERTY_ON_DEMAND_MODE, out flagValue); if (flagValue.Enable != 0) { if (flagBuilder.Length > 0) { flagBuilder.Append(", "); } flagBuilder.Append(Properties.Resources.JobFlagsOnDemandMode); } if (flagBuilder.Length == 0) { flagBuilder.Append(Properties.Resources.JobFlagsNoneSet); } _uiJobFlags.Text = flagBuilder.ToString(); } // Get the JobHttpOptions custom method var httpOptions2 = Job as BITS10_2.IBackgroundCopyJobHttpOptions2; if (httpOptions2 == null) { _uiJobHttpMethod.Text = Properties.Resources.JobHttpMethodNotAvailable; } else { string httpMethod; try { httpOptions2.GetHttpMethod(out httpMethod); _uiJobHttpMethod.Text = httpMethod ?? Properties.Resources.JobHttpMethodNotSet; } catch (System.Runtime.InteropServices.COMException ex) { _uiJobHttpMethod.Text = String.Format(Properties.Resources.JobHttpMethodException, ex.Message); } } // Get the HttpJobOptions var httpOptions = Job as BITS4.IBackgroundCopyJobHttpOptions; if (httpOptions == null) { _uiJobCustomHeaders.Text = Properties.Resources.JobCustomHeadersNotAvailable; } else { string customHeaders; try { httpOptions.GetCustomHeaders(out customHeaders); var headers = customHeaders == null ? Properties.Resources.JobCustomHeadersNotSet : TabifyHttpHeaders.AddTabs(TabifyHttpHeaders.PrependCRLF(customHeaders)) ; _uiJobCustomHeaders.Text = headers; } catch (System.Runtime.InteropServices.COMException ex) { _uiJobCustomHeaders.Text = String.Format( Properties.Resources.JobCustomHeadersException, ex.Message); } catch (System.UnauthorizedAccessException ex) { _uiJobCustomHeaders.Text = String.Format( Properties.Resources.JobCustomHeadersException, ex.Message); } } // Update the list of files associated with the job. ListBITSJobFiles(Job); }
private static string doParse(string subSDDL, string Seperator, string Seperator2) { string retval = ""; char type = subSDDL.ToCharArray()[0]; if (type == 'O') { string owner = subSDDL.Substring(2); if (Trustee.Keys.Contains(owner)) { return("Owner: " + Trustee[owner] + Seperator); } } else if (type == 'G') { string group = subSDDL.Substring(2); if (Trustee.Keys.Contains(group)) { return("Group: " + Trustee[group] + Seperator); } } else if ((type == 'D') || (type == 'S')) { if (type == 'D') { retval += "DACL" + Seperator; } else { retval += "SACL" + Seperator; } string[] sections = subSDDL.Split('('); for (int count = 1; count < sections.Length; count++) { retval += "# " + count.ToString() + " of " + (sections.Length - 1).ToString() + Seperator; string[] parts = sections[count].TrimEnd(')').Split(';'); retval += ""; if (ACE_Types.Keys.Contains(parts[0])) { retval += Seperator2 + "Type: " + ACE_Types[parts[0]] + Seperator; } if (ACE_Flags.Keys.Contains(parts[1])) { retval += Seperator2 + "Inheritance: " + ACE_Flags[parts[1]] + Seperator; } for (int count2 = 0; count2 < parts[2].Length; count2 += 2) { string perm = parts[2].Substring(count2, 2); if (Permissions.Keys.Contains(perm)) { if (count2 == 0) { retval += Seperator2 + "Permissions: " + Permissions[perm]; } else { retval += "|" + Permissions[perm]; } } } retval += Seperator; if (Trustee.Keys.Contains(parts[5])) { retval += Seperator2 + "Trustee: " + Trustee[parts[5]] + Seperator; } else { try { System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(parts[5]); retval += Seperator2 + "Trustee: " + sid.Translate(typeof(System.Security.Principal.NTAccount)).ToString() + Seperator; } catch (Exception) { retval += Seperator2 + "Trustee: " + parts[5] + Seperator; } } } } return(retval); }
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); }
private DirectoryEntry GetDirectoryEntryFromSID(DirectoryEntry directoryEntry) { try { System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier((byte[])directoryEntry.Properties["objectSid"].Value, 0); System.Security.Principal.NTAccount acct = (System.Security.Principal.NTAccount)sid.Translate(typeof(System.Security.Principal.NTAccount)); DirectoryEntry directoryEntryLDAP = GetDirectoryEntry(acct.Value); if (directoryEntryLDAP.Name != null) return directoryEntryLDAP; } catch { } return null; }
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); }
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 }
/// <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; } }
private string GetDomainAndUserForDirectoryEntry(DirectoryEntry directoryEntry) { try { System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier((byte[])directoryEntry.Properties["objectSid"].Value, 0); System.Security.Principal.NTAccount account = (System.Security.Principal.NTAccount)sid.Translate(typeof(System.Security.Principal.NTAccount)); return account.ToString(); // This give the DOMAIN\User format for the account } catch { string sName = ""; try { sName = Convert.ToString(directoryEntry.Properties["displayName"].Value); if (string.IsNullOrEmpty(sName)) throw new Exception(); return sName; } catch { try { sName = Convert.ToString(directoryEntry.Properties["fullName"].Value); if (string.IsNullOrEmpty(sName)) throw new Exception(); return sName; } catch { try { return directoryEntry.Name; } catch { try { System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier((byte[])directoryEntry.Properties["objectSid"].Value, 0); return sid.Value; } catch { return null; } } } } } }