Example #1
0
        private void GetIETypedUrls()
        {
            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(ieregexUserMatch);

            foreach (String subkey in Microsoft.Win32.Registry.Users.GetSubKeyNames())
            {
                if (regex.IsMatch(subkey))
                {
                    var user = new System.Security.Principal.SecurityIdentifier(subkey).Translate(typeof(System.Security.Principal.NTAccount));
                    using (var key = Microsoft.Win32.Registry.Users.OpenSubKey(subkey + "\\Software\\Microsoft\\Internet Explorer\\TypedURLs"))
                    {
                        foreach (String valName in key.GetValueNames())
                        {
                            String val = key.GetValue(valName) as String;
                            var    o   = new BrowserHistory()
                            {
                                User    = user.Value,
                                Browser = "IE_Typed",
                                Url     = val
                            };
                            WriteObject(o);
                        }
                    }
                }
            }
        }
Example #2
0
 static int Main(string[] args)
 {
     byte[] sid;
     try
     {
         //sid = StringToByteArray("0x010600000000000550000000E20F4FE7B15874E48E19026478C2DC9AC307B83E");
         sid = StringToByteArray(args[0]);
     }
     catch (Exception ex)
     {
         Console.WriteLine("введённая hex строка не переводится двоичные данные");
         Console.WriteLine(ex.Message);
         return(1);
     }
     try
     {
         var t = new System.Security.Principal.SecurityIdentifier(sid, 0);
         Console.WriteLine(t.Value);
     }
     catch (Exception ex)
     {
         Console.WriteLine("введённая hex строка не переводится двоичные данные");
         Console.WriteLine(ex.Message);
         return(2);
     }
     return(0);
 }
Example #3
0
        /// <summary>
        /// Creates a new task in WTS with information from ScheduledJobDefinition.
        /// </summary>
        /// <param name="definition">ScheduledJobDefinition</param>
        public void CreateTask(
            ScheduledJobDefinition definition)
        {
            if (definition == null)
            {
                throw new PSArgumentNullException("definition");
            }

            // Create task definition
            ITaskDefinition iTaskDefinition = _taskScheduler.NewTask(0);

            // Add task options.
            AddTaskOptions(iTaskDefinition, definition.Options);

            // Add task triggers.
            foreach (ScheduledJobTrigger jobTrigger in definition.JobTriggers)
            {
                AddTaskTrigger(iTaskDefinition, jobTrigger);
            }

            // Add task action.
            AddTaskAction(iTaskDefinition, definition);

            // Create a security descriptor for the current user so that only the user
            // (and Local System account) can see/access the registered task.
            string startSddl = "D:P(A;;GA;;;SY)(A;;GA;;;BA)";   // DACL Allow Generic Access to System and BUILTIN\Administrators.

            System.Security.Principal.SecurityIdentifier userSid =
                System.Security.Principal.WindowsIdentity.GetCurrent().User;
            CommonSecurityDescriptor SDesc = new CommonSecurityDescriptor(false, false, startSddl);

            SDesc.DiscretionaryAcl.AddAccess(AccessControlType.Allow, userSid, 0x10000000, InheritanceFlags.None, PropagationFlags.None);
            string sddl = SDesc.GetSddlForm(AccessControlSections.All);

            // Register this new task with the Task Scheduler.
            if (definition.Credential == null)
            {
                // Register task to run as currently logged on user.
                _iRootFolder.RegisterTaskDefinition(
                    definition.Name,
                    iTaskDefinition,
                    (int)_TASK_CREATION.TASK_CREATE,
                    null,       // User name
                    null,       // Password
                    _TASK_LOGON_TYPE.TASK_LOGON_S4U,
                    sddl);
            }
            else
            {
                // Register task to run under provided user account/credentials.
                _iRootFolder.RegisterTaskDefinition(
                    definition.Name,
                    iTaskDefinition,
                    (int)_TASK_CREATION.TASK_CREATE,
                    definition.Credential.UserName,
                    GetCredentialPassword(definition.Credential),
                    _TASK_LOGON_TYPE.TASK_LOGON_PASSWORD,
                    sddl);
            }
        }
Example #4
0
        public void StartPipeServer()
        {
            try
            {
                Task serverTask = Task.Factory.StartNew(() =>
                {
                    PipeSecurity ps = new PipeSecurity();
                    System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.BuiltinUsersSid, null);
                    PipeAccessRule par = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
                    ps.AddAccessRule(par);
                    var server = new NamedPipeServerStream("ForecourtToPumpSim", PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 1024, 1024, ps);
                    Console.WriteLine("Waiting for client connection...");
                    server.WaitForConnection();


                    StreamReader serverReader = new StreamReader(server);
                    StreamWriter serverWriter = new StreamWriter(server);
                    ConnectedEvent.Set();


                    while (true)
                    {
                        string line     = serverReader.ReadLine();
                        string response = "";
                        HandleForecourtMessages(line, ref response);

                        serverWriter.WriteLine(response);
                        serverWriter.Flush();
                    }
                });
            }
            catch (IOException e)
            {
            }
        }
Example #5
0
        /// <summary>
        /// Add the tag (<identity impersonate="true"/>) in your web.config file.
        /// </summary>
        internal static void SetFullControlForEveryOne(string path)
        {
            try
            {
                System.Security.AccessControl.DirectorySecurity
                    directorySecurity = System.IO.Directory.GetAccessControl(path);

                // Using this instead of the "Everyone"
                // string means we work on non-English systems.
                System.Security.Principal.SecurityIdentifier everyone =
                    new System.Security.Principal.SecurityIdentifier
                        (System.Security.Principal.WellKnownSidType.WorldSid, null);

                System.Security.AccessControl.FileSystemAccessRule fileSystemAccessRule =
                    new System.Security.AccessControl.FileSystemAccessRule
                        (identity: everyone,
                        fileSystemRights: System.Security.AccessControl.FileSystemRights.FullControl |
                        System.Security.AccessControl.FileSystemRights.Synchronize,
                        inheritanceFlags: System.Security.AccessControl.InheritanceFlags.ContainerInherit |
                        System.Security.AccessControl.InheritanceFlags.ObjectInherit,
                        propagationFlags: System.Security.AccessControl.PropagationFlags.None,
                        type: System.Security.AccessControl.AccessControlType.Allow);

                directorySecurity.AddAccessRule(fileSystemAccessRule);

                System.IO.Directory.SetAccessControl
                    (path: path, directorySecurity: directorySecurity);
            }
            catch (System.Exception ex)
            {
                string errorMessage = ex.Message;
            }
        }
Example #6
0
        public SetupStatus Install(IWin32Window owner)
        {
            if (_status == SetupStatus.Installed)
            {
                return(_status);
            }

            try
            {
                // get Everyone token for the current locale
                string everyone = new System.Security.Principal.SecurityIdentifier(
                    "S-1-1-0").Translate(typeof(System.Security.Principal.NTAccount)).ToString();
                string port      = ConfigurationManager.AppSettings["Port"];
                string arguments = string.Format("http add urlacl url=http://+:{0}/ user=\"\\{1}\"", port, everyone);
                Log.Info("Adding ACL rule...");
                ProcessHelper.RunNetShell(arguments, "Failed to add URL ACL");
                _status = SetupStatus.Installed;
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                _status = SetupStatus.Failed;
                Settings.Instance.UrlReservationSetupHadErrors = true;
                Settings.Instance.Save();
                throw;
            }
            return(_status);
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            string receivedText;

            PipeSecurity ps = new PipeSecurity();

            System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
            PipeAccessRule par = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);

            ps.AddAccessRule(par);

            using (var pipeStream = new NamedPipeServerStream(
                       "test",
                       PipeDirection.InOut,
                       1,
                       PipeTransmissionMode.Message,
                       PipeOptions.Asynchronous,
                       4096,
                       4096,
                       ps))
            {
                await pipeStream.WaitForConnectionAsync(stoppingToken);

                using (var streamReader = new StreamReader(pipeStream))
                {
                    receivedText = await streamReader.ReadToEndAsync();
                }
            }
        }
Example #8
0
        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);
            });
        }
        void ServerListen()
        {
            var ps = new PipeSecurity();

            System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.BuiltinUsersSid, null);
            ps.AddAccessRule(new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow));

            while (true)
            {
                NamedPipeServerStream pipe = null;
                try
                {
                    pipe = new NamedPipeServerStream(pipeName,
                                                     PipeDirection.InOut, 1,
                                                     PipeTransmissionMode.Message,
                                                     PipeOptions.Asynchronous,
                                                     1024, 1024, ps);
                    pipe.WaitForConnection();
                    HandleClientConnection(pipe);
                    pipe.Close();
                }
                catch (UnauthorizedAccessException e)
                {
                    // note: should only come here if another pipe with same name is already open (= another instance of d2interface is running)
                    Console.WriteLine("Error: {0}", e.Message);
                    Thread.Sleep(1000); // try again in 1 sec to prevent tool from lagging
                }
                catch (IOException e)
                {
                    Logger.Error("Item Server Failure", e);
                    pipe?.Close();
                }
            }
        }
Example #10
0
 static void Main()
 {
     // Is admin code basically copy+pasted from http://stackoverflow.com/questions/509292/how-can-i-tell-if-my-process-is-running-as-administrator
     // Thanks casperOne!
     var localAdminGroupSid = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
     bool shouldRun = System.Security.Principal.WindowsIdentity.GetCurrent().Groups.
             Select(g => (SecurityIdentifier)g.Translate(typeof(SecurityIdentifier))).
             Any(s => s == localAdminGroupSid);
     if (!shouldRun)
     {
         DialogResult result = MessageBox.Show("You must run this program as an Administrator! This program makes changes to the Windows Registry, "
             + "which requires Administrator access. You may continue, but it probably won't work!", "Windows 10 Privacy Tool",
             MessageBoxButtons.AbortRetryIgnore);
         if (result == DialogResult.Abort)
         {
             // Do nothing, it will exit normally
         } else if (result == DialogResult.Retry)
         {
             Main();
         } else if (result == DialogResult.Ignore)
         {
             shouldRun = true;
         }
     }
     if (shouldRun)
     {
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         Application.Run(new Form1());
     }
 }
Example #11
0
        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);
        }
        public SetupStatus Install(IWin32Window owner)
        {
            if (_status == SetupStatus.Installed)
                return _status;

            try
            {
                // get Everyone token for the current locale
                string everyone = new System.Security.Principal.SecurityIdentifier(
                    "S-1-1-0").Translate(typeof(System.Security.Principal.NTAccount)).ToString();
                string port = ConfigurationManager.AppSettings["Port"];
                string arguments = string.Format("http add urlacl url=http://+:{0}/ user=\"\\{1}\"", port, everyone);
                Log.Info("Adding ACL rule...");
                ProcessHelper.RunNetShell(arguments, "Failed to add URL ACL");
                _status = SetupStatus.Installed;
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                _status = SetupStatus.Failed;
                Settings.Instance.UrlReservationSetupHadErrors = true;
                Settings.Instance.Save();
                throw;
            }
            return _status;
        }
Example #13
0
            private static byte[] GetBytes(System.Security.Principal.SecurityIdentifier si)
            {
                var b = new byte[si.BinaryLength];

                si.GetBinaryForm(b, 0);
                return(b);
            }
Example #14
0
        /// <summary>
        /// Starts a new Pipe server on a new thread
        /// </summary>
        public void StartServer()
        {
            StopServer();
            Thread = new Thread((pipeName) =>
            {
                if (!(pipeName is String pipeNameString))
                {
                    throw new ArgumentNullException(nameof(pipeName));
                }
                _isRunning = true;
                while (true)
                {
                    string text;
                    try
                    {
                        PipeSecurity ps = new PipeSecurity();
                        System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
                        PipeAccessRule par = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
                        //PipeAccessRule psRule = new PipeAccessRule(@"Everyone", PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
                        ps.AddAccessRule(par);
                        using (var server = new NamedPipeServerStream(pipeNameString,
                                                                      PipeDirection.InOut, 1,
                                                                      PipeTransmissionMode.Message, PipeOptions.None,
                                                                      4028, 4028, ps))
                        {
                            server.WaitForConnection();

                            using (StreamReader reader = new StreamReader(server))
                            {
                                text = reader.ReadToEnd();
                            }
                        }

                        if (text == EXIT_STRING)
                        {
                            break;
                        }

                        OnReceiveString(text);
                    }
                    catch (IOException e)
                    {
                        Log.Warn(e);
                        Thread.Sleep(50);
                    }
                    catch (Exception e)
                    {
                        Log.Error(e);
                        Thread.Sleep(50);
                    }


                    if (_isRunning == false)
                    {
                        break;
                    }
                }
            });
            Thread.Start(NamedPipeName);
        }
Example #15
0
        /// <summary>
        /// Create message compatible with MSMQ
        /// </summary>
        /// <param name="queueName"></param>
        /// <returns></returns>
        public virtual IMessageQueue CreateMessageQueue(string queueName, string topicName = null)
        {
            var pathConfig = System.Configuration.ConfigurationManager.ConnectionStrings[queueName];

            if (pathConfig == null)
            {
                throw new ArgumentException(string.Format("queueName {0} does not exists in connectionStrings section configuration", queueName));
            }

            var path = pathConfig.ConnectionString;

            if (!path.StartsWith("formatname:direct") &&
                !System.Messaging.MessageQueue.Exists(path))
            {
                try
                {
                    string everyone = new System.Security.Principal.SecurityIdentifier(
                        "S-1-1-0").Translate(typeof(System.Security.Principal.NTAccount)).ToString();
                    var queue = System.Messaging.MessageQueue.Create(path);
                    queue.SetPermissions(everyone, MessageQueueAccessRights.FullControl);
                }
                catch (Exception ex)
                {
                    ex.Data.Add("queueName", queueName);
                    ex.Data.Add("queuePath", path);
                    throw ex;
                }
            }

            var result = new System.Messaging.MessageQueue(path, System.Messaging.QueueAccessMode.SendAndReceive);

            return(new QueueProviders.MSMQMessageQueue(result, queueName));
        }
Example #16
0
 /// <summary>
 /// Set required permissions to the Phalanger install folder. To enable phalanger ASP.NET app i.e. to generate/modify dynamic wrappers.
 /// </summary>
 /// <param name="folder">Phalanger install folder.</param>
 private static void SetEveryonePermission(string folder)
 {
     var everyonesid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
     FileSystemAccessRule everyOne = new FileSystemAccessRule(everyonesid, FileSystemRights.FullControl | FileSystemRights.Write | FileSystemRights.Read, AccessControlType.Allow);
     DirectorySecurity dirSecurity = new DirectorySecurity(folder, AccessControlSections.Group);
     dirSecurity.AddAccessRule(everyOne);
     Directory.SetAccessControl(folder, dirSecurity);
 }
Example #17
0
        public static string EncodeSidToString(string sid)
        {
            var realsid = new System.Security.Principal.SecurityIdentifier(sid);
            var bytesid = new byte[realsid.BinaryLength];

            realsid.GetBinaryForm(bytesid, 0);
            return("\\" + BitConverter.ToString(bytesid).Replace("-", "\\"));
        }
Example #18
0
        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);
        }
Example #19
0
        /// <summary>
        /// Set required permissions to the Phalanger install folder. To enable phalanger ASP.NET app i.e. to generate/modify dynamic wrappers.
        /// </summary>
        /// <param name="folder">Phalanger install folder.</param>
        private static void SetEveryonePermission(string folder)
        {
            var everyonesid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
            FileSystemAccessRule everyOne    = new FileSystemAccessRule(everyonesid, FileSystemRights.FullControl | FileSystemRights.Write | FileSystemRights.Read, AccessControlType.Allow);
            DirectorySecurity    dirSecurity = new DirectorySecurity(folder, AccessControlSections.Group);

            dirSecurity.AddAccessRule(everyOne);
            Directory.SetAccessControl(folder, dirSecurity);
        }
Example #20
0
        public static int ReservePort(int port)
        {
            string everyone = new System.Security.Principal.SecurityIdentifier(
                "S-1-1-0").Translate(typeof(System.Security.Principal.NTAccount)).ToString();

            string parameter = $"http add urlacl url=http://*:{port}/ user=\\{everyone}";

            return(LaunchNetworkShell(parameter));
        }
Example #21
0
        public static int ReservePort(int port)
        {
#pragma warning disable CA1416 // Validate platform compatibility
            var everyone = new System.Security.Principal.SecurityIdentifier(
                "S-1-1-0").Translate(typeof(System.Security.Principal.NTAccount)).ToString();
#pragma warning restore CA1416 // Validate platform compatibility

            var parameter = $"http add urlacl url=http://*:{port}/ user=\"{everyone}\"";
            return(LaunchNetworkShell(parameter));
        }
        //Perform this task when a SID is selected
        private void registryUsers_SelectedIndexChanged(object sender, EventArgs e)
        {
            officeVersionLabel.Text = getOutlookVersion();

            //Test if file is locked
            if (IsFileLocked(@"C:\Users\" + registryUsers.SelectedItem.ToString() + @"\NTUSER.DAT"))
            {
                MessageBox.Show("This user's NTUSER.DAT file is locked. You may need to reboot as Windows locks this file.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }


            RegistryKey usersRegistry = Registry.Users.OpenSubKey(registryUsers.SelectedItem.ToString() + @"\SOFTWARE\Microsoft\Office\" + getOutlookVersion() + @"\Outlook\Search");

            if (registryUsers.SelectedItem == null)
            {
                return;
            }
            try
            {
                string account = new System.Security.Principal.SecurityIdentifier(registryUsers.SelectedItem.ToString()).Translate(typeof(System.Security.Principal.NTAccount)).ToString();
                usernameLabel.Text = account;
            }
            catch (Exception)
            {
                usernameLabel.Text = "";
            }


            ArrayList outlookFiles = getOutlookFiles();

            if (outlookFiles == null)
            {
                allOutlookFiles.Items.Clear();
                allOutlookFiles.Items.Add("No Files Found");
                return;
            }

            if (outlookFiles != null || outlookFiles.Count != 0)
            {
                allOutlookFiles.Items.Clear();
                foreach (string name in outlookFiles)
                {
                    allOutlookFiles.Items.Add(name);
                }
            }
            else
            {
                allOutlookFiles.Items.Clear();
                allOutlookFiles.Items.Add("NO FILES FOUND!");
            }


            GC.Collect();
        }
        static void Main(string[] args)
        {
            String username = "******";

            List <string> userNestedMembership = new List <string>();

            DirectoryEntry domainConnection = new DirectoryEntry();

            domainConnection.Path = "LDAP://DC=mydomain,DC=local";
            domainConnection.AuthenticationType = AuthenticationTypes.Secure;


            DirectorySearcher samSearcher = new DirectorySearcher();

            samSearcher.SearchRoot = domainConnection;
            samSearcher.Filter     = "(samAccountName=" + username + ")";
            samSearcher.PropertiesToLoad.Add("displayName");

            SearchResult samResult = samSearcher.FindOne();

            if (samResult != null)
            {
                DirectoryEntry theUser = samResult.GetDirectoryEntry();
                theUser.RefreshCache(new string[] { "tokenGroups" });

                foreach (byte[] resultBytes in theUser.Properties["tokenGroups"])
                {
                    System.Security.Principal.SecurityIdentifier mySID = new System.Security.Principal.SecurityIdentifier(resultBytes, 0);

                    DirectorySearcher sidSearcher = new DirectorySearcher();

                    sidSearcher.SearchRoot = domainConnection;
                    sidSearcher.Filter     = "(objectSid=" + mySID.Value + ")";
                    sidSearcher.PropertiesToLoad.Add("distinguishedName");

                    SearchResult sidResult = sidSearcher.FindOne();

                    if (sidResult != null)
                    {
                        userNestedMembership.Add((string)sidResult.Properties["distinguishedName"][0]);
                    }
                }

                foreach (string myEntry in userNestedMembership)
                {
                    Console.WriteLine(myEntry);
                }
            }
            else
            {
                Console.WriteLine("The user doesn't exist");
            }

            Console.ReadKey();
        }
Example #24
0
        protected String ObjectSidToString(Byte [] sidByteArray)
        {
            if (sidByteArray == null)
            {
                return(String.Empty);
            }

            System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(sidByteArray, 0);

            return(sid.ToString());
        }
Example #25
0
 public static void RegisterFirewallAndHttpUser(int jmmport, int jmmfileport)
 {
     string everyone = new System.Security.Principal.SecurityIdentifier("S-1-1-0").Translate(typeof(System.Security.Principal.NTAccount)).ToString();
     
     //RunNetSh(@"http delete urlacl url=http://*:"+jmmfileport+"/ user=\\" + everyone);
     RunNetSh(@"http add urlacl url=http://*:" + jmmfileport + "/ user=\\" + everyone);
     RunNetSh("advfirewall firewall delete rule name=\"JMM Server - Client Port\"");
     RunNetSh("advfirewall firewall delete rule name=\"JMM Server - File Port\"");
     RunNetSh("advfirewall firewall add rule name=\"JMM Server - Client Port\" dir=in action=allow protocol=TCP localport=" + jmmport);
     RunNetSh("advfirewall firewall add rule name=\"JMM Server - File Port\" dir=in action=allow protocol=TCP localport=" + jmmfileport);
 }
Example #26
0
        public static void RegisterFirewallAndHttpUser(int jmmport, int jmmfileport)
        {
            string everyone = new System.Security.Principal.SecurityIdentifier("S-1-1-0").Translate(typeof(System.Security.Principal.NTAccount)).ToString();

            //RunNetSh(@"http delete urlacl url=http://*:"+jmmfileport+"/ user=\\" + everyone);
            RunNetSh(@"http add urlacl url=http://*:" + jmmfileport + "/ user=\\" + everyone);
            RunNetSh("advfirewall firewall delete rule name=\"JMM Server - Client Port\"");
            RunNetSh("advfirewall firewall delete rule name=\"JMM Server - File Port\"");
            RunNetSh("advfirewall firewall add rule name=\"JMM Server - Client Port\" dir=in action=allow protocol=TCP localport=" + jmmport);
            RunNetSh("advfirewall firewall add rule name=\"JMM Server - File Port\" dir=in action=allow protocol=TCP localport=" + jmmfileport);
        }
Example #27
0
 public static void PrintDACL(List <Utils.ACE> DACL)
 {
     foreach (var ace in DACL)
     {
         var sid = new System.Security.Principal.SecurityIdentifier(ace.Trustee);
         Console.WriteLine($"Trustee: {Utils.SidToAccountName(sid)}");
         Console.WriteLine($"Access Right: {ace.AccessType}");
         Console.WriteLine($"Audit Rights: {ace.AuditRights}");
         Console.WriteLine("Permissions: " + String.Join("|", ace.Permissions));
         Console.WriteLine();
     }
 }
        protected override BitStream internalDecode(BitStream data)
        {
            var len    = data.Length;
            var buf    = new BitReader(data).ReadBytes((int)len);
            var sid    = new System.Security.Principal.SecurityIdentifier(buf, 0);
            var ret    = new BitStream();
            var writer = new BitWriter(ret);

            writer.WriteString(sid.ToString());
            ret.Seek(0, System.IO.SeekOrigin.Begin);
            return(ret);
        }
Example #29
0
        void ServerListen()
        {
            var ps = new PipeSecurity();

            System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.BuiltinUsersSid, null);
            ps.AddAccessRule(new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow));

            while (true)
            {
                NamedPipeServerStream pipe = null;
                try
                {
                    pipe = new NamedPipeServerStream(pipeName,
                                                     PipeDirection.InOut, 1,
                                                     PipeTransmissionMode.Message,
                                                     PipeOptions.Asynchronous,
                                                     1024, 1024, ps);
                    pipe.WaitForConnection();
                    Thread clientConnectionHandler = new Thread(new ParameterizedThreadStart(HandleClientConnection))
                    {
                        IsBackground = true
                    };
                    clientConnectionHandler.Start(pipe);
                    if (!clientConnectionHandler.Join(1000))
                    {
                        clientConnectionHandler.Abort();
                        Console.WriteLine("Connection handler timeout reached");
                        Logger.Instance.WriteLine("Client connection handler timed out in item server thread...");
                    }
                    pipe.Close();
                }
                catch (UnauthorizedAccessException e)
                {
                    // note: should only come here if another pipe with same name is already open (= another instance of d2interface is running)
                    Logger.Instance.WriteLine("Error: {0}", e.Message);
                    Thread.Sleep(1000); // try again in 1 sec to prevent tool from lagging
                }
                catch (IOException e)
                {
                    Logger.Instance.WriteLine("ItemServer Error: {0}", e.Message);

                    if (pipe != null)
                    {
                        pipe.Close();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    Logger.Instance.WriteLine("Other exception: {0}", e.Message);
                }
            }
        }
Example #30
0
        public static string Bytes2SID(List <string> sidBytes)
        {
            byte[] bytes = new byte[sidBytes.Count];
            for (int i = 0; i < sidBytes.Count; i++)
            {
                bytes[i] = Byte.Parse(sidBytes[i]);
            }

            var securityIdentifier = new System.Security.Principal.SecurityIdentifier(bytes, 0);

            return(securityIdentifier.ToString());
        }
Example #31
0
        public DiabloInterfaceServer(string pipeName)
        {
            Logger.Info("Initializing pipe server.");

            this.pipeName = pipeName;

            this.cache = new Cache();

            ps = new PipeSecurity();
            System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.BuiltinUsersSid, null);
            ps.AddAccessRule(new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow));
        }
Example #32
0
        public ADCache(string path)
        {
            eventLog = new EventLog("OIMNTFS ADCache");
            eventLog.Buffer("Reading directory information.");
            try
            {
                DateTime start      = DateTime.Now;
                string[] properties = new string[] { "samAccountName", "objectClass", "canonicalName", "objectSID", "distinguishedName" };
                string   filter     = "(|(objectClass=user)(objectClass=group))";

                eventLog.Buffer("Connecting to {0}...", path);
                DirectoryEntry directoryEntry = null;

                try
                {
                    //directoryEntry = new DirectoryEntry(path);
                    directoryEntry = new DirectoryEntry();
                    directoryEntry.RefreshCache(properties);
                }
                catch
                {
                    eventLog.Buffer("Current user context is not allowed to read from AD.");
                }

                Console.WriteLine("Reading all ad user and group objects...");
                DirectorySearcher ds = new System.DirectoryServices.DirectorySearcher(directoryEntry, filter, properties);
                ds.SearchScope   = SearchScope.Subtree;
                ds.CacheResults  = true;
                ds.ClientTimeout = TimeSpan.FromMinutes(120);
                ds.PageSize      = 100;

                SearchResultCollection entries = ds.FindAll();
                foreach (SearchResult entry in entries)
                {
                    System.Security.Principal.SecurityIdentifier binSID = new System.Security.Principal.SecurityIdentifier((byte[])entry.Properties["objectSID"][0], 0);
                    string sid            = binSID.ToString();
                    string samAccountName = entry.Properties["samAccountName"][0].ToString();

                    if (!cache.ContainsKey(sid))
                    {
                        cache.Add(sid, new Properties(sid, entry));
                    }
                }
                eventLog.Buffer("{0} objects found. Loading AD took actually {1}", cache.Count, (DateTime.Now - start).ToString());
            }
            catch (Exception e)
            {
                eventLog.Buffer("Reading AD failed: {0}", e.Message);
                //throw new Exception("Reading AD failed.");
            }
            eventLog.Flush();
        }
Example #33
0
        /// <summary>
        /// This function will perform a recursive search and will add only one occurance of
        /// the group found in the enumeration.
        /// </summary>
        /// <param name="dSearcher">DirectorySearcher object to perform search</param>
        /// <param name="lGroups">List of the Groups from AD</param>
        /// <param name="sGrpName">
        /// Group name which needs to be checked inside the Groups collection
        /// </param>
        /// <param name="SID">objectSID of the object</param>
        /// <remarks></remarks>
        public static void RecursivelyGetGroups(DirectorySearcher dSearcher, List <string> lGroups, string sGrpName, string SID)
        {
            //Check if the group has already not found
            if (!lGroups.Contains(sGrpName))
            {
                lGroups.Add(sGrpName + " : " + SID);

                //Now perform the search based on this group
                dSearcher.Filter = "(&(objectClass=grp)(CN=" + sGrpName + "))".Replace("\\", "\\\\");
                dSearcher.ClientTimeout.Add(new TimeSpan(0, 2, 0));
                dSearcher.ServerTimeLimit.Add(new TimeSpan(0, 2, 0));

                //Search this group
                SearchResult GroupSearchResult = dSearcher.FindOne();
                if ((GroupSearchResult != null))
                {
                    foreach (var grp in GroupSearchResult.Properties["memberOf"])
                    {
                        string ParentGroupName = Convert.ToString(grp).Remove(0, 3);

                        //Bind to this group
                        DirectoryEntry deTempForSID = new DirectoryEntry("LDAP://" + grp.ToString().Replace("/", "\\/"));
                        try
                        {
                            //Get the objectSID which is Byte array
                            byte[] objectSid = (byte[])deTempForSID.Properties["objectSid"].Value;

                            //Pass this Byte array to Security.Principal.SecurityIdentifier to convert this
                            //byte array to SDDL format
                            System.Security.Principal.SecurityIdentifier ParentSID = new System.Security.Principal.SecurityIdentifier(objectSid, 0);

                            if (ParentGroupName.Contains(",CN"))
                            {
                                ParentGroupName = ParentGroupName.Remove(ParentGroupName.IndexOf(",CN"));
                            }
                            else if (ParentGroupName.Contains(",OU"))
                            {
                                ParentGroupName = ParentGroupName.Remove(ParentGroupName.IndexOf(",OU"));
                            }
                            RecursivelyGetGroups(dSearcher, lGroups, ParentGroupName, ParentSID.ToString());
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error while binding to path : " + grp.ToString());
                            Console.WriteLine(ex.Message.ToString());
                        }
                    }
                }
            }
        }
Example #34
0
        private async Task RunChummerFilePipeThread()
        {
            if (!(NamedPipeName is string pipeNameString))
            {
                throw new ArgumentNullException(nameof(NamedPipeName));
            }
            PipeSecurity ps = new PipeSecurity();

            System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
            PipeAccessRule par = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);

            //PipeAccessRule psRule = new PipeAccessRule(@"Everyone", PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
            ps.AddAccessRule(par);
            while (!_objCancellationTokenSource.IsCancellationRequested)
            {
                try
                {
                    string text;
                    using (NamedPipeServerStream server = new NamedPipeServerStream(pipeNameString,
                                                                                    PipeDirection.InOut, 1,
                                                                                    PipeTransmissionMode.Message, PipeOptions.None,
                                                                                    4028, 4028, ps))
                    {
                        await server.WaitForConnectionAsync();

                        using (StreamReader reader = new StreamReader(server))
                        {
                            text = await reader.ReadToEndAsync();
                        }
                    }

                    if (text == EXIT_STRING)
                    {
                        break;
                    }

                    OnReceiveString(text);
                }
                catch (IOException e)
                {
                    Log.Warn(e);
                    await Chummer.Utils.SafeSleepAsync();
                }
                catch (Exception e)
                {
                    Log.Error(e);
                    await Chummer.Utils.SafeSleepAsync();
                }
            }
        }
        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);
        }
Example #36
0
        /*
        *METHOD		    :	QuestionWindow
        *
        *DESCRIPTION	:	Constructor for the QuestionWindow class. takes in users name, the computers name to connect to and name of the pipe to use.
         *                  Opens connestion to the service and starts the first qestion
        *
        *PARAMETERS		:	string userName     The name of the user
         *                  string serverName   The name of the computer running the server
         *                  string pipeName     The name of the por to connect to
        *
        *RETURNS		:
        *
        */
        public QuestionWindow(string userName, string serverName, string pipeName)
        {
            InitializeComponent();
            this.userName = userName;
            this.serverName = serverName;
            this.pipeName = pipeName;

            answers = new string[4];

            PipeSecurity ps = new PipeSecurity();
            System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
            PipeAccessRule par = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
            ps.AddAccessRule(par);

            questionNumber = 1;
            answers[0] = "";
            answers[1] = "";
            answers[2] = "";
            answers[3] = "";

            //start timer for counting down users score (1 per second)
            timer = new System.Timers.Timer();
            timer.Elapsed += on_Timer_Event;
            timer.Interval = 1000;

            //connect to service
            client = new NamedPipeClientStream(serverName, pipeName + "service");//naming convention for pipe is given name(pipeName) and who has the server (service or user)
            client.Connect(30);
            output = new StreamWriter(client);

            //tell service the name of the computer to connect back to
            output.WriteLine(Environment.MachineName);
            output.Flush();

            server = new NamedPipeServerStream(pipeName + "User", PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 5000, 5000, ps);//naming convention for pipe is given name(pipeName) and who has the server (service or user)
            server.WaitForConnection();
            input = new StreamReader(server);

            Thread.Sleep(100);//allow server time complete actions
            //tell service name of new user
            newUser();
            Thread.Sleep(200);//allow server time complete actions
            //get the first question
            getGameQuestion();
            //start score counter
            timer.Start();
        }
Example #37
0
 public void StartServer(SelectCounter selectCountersDelegate, ReceivedValues receivedValuesDelegate)
 {
     selectCounters = selectCountersDelegate;
     receivedValues = receivedValuesDelegate;
     System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
     PipeAccessRule pac = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
     PipeSecurity ps = new PipeSecurity();
     ps.AddAccessRule(pac);
     sid = null;
     pipeServer = new NamedPipeServerStream(serverPipeName,
             PipeDirection.InOut,
             serverInstances,
             PipeTransmissionMode.Message,
             PipeOptions.Asynchronous,
             1024,
             1024,
             ps);
     AsyncCallback myCallback = new AsyncCallback(AsyncPipeCallback);
     pipeServer.BeginWaitForConnection(myCallback, null);
 }
Example #38
0
        public void ReformatLdif(LdifReader r, LdifWriter w, Encoding passwordEncoding, string defaultPwd, List<string> ignoredAttrs,
            bool allowMsExchange, Func<string, bool> ignoreIt)
        {
            if (!allowMsExchange)
            {
                ignoredAttrs.Add("showinaddressbook");
                ignoredAttrs.Add("legacyexchangedn");
                ignoredAttrs.Add("homemta");
                ignoredAttrs.Add("homemdb");
                ignoredAttrs.Add("mailnickname");
                ignoredAttrs.Add("mdbusedefaults");
                ignoredAttrs.Add("publicdelegatesbl");
                ignoredAttrs.Add("protocolsettings");
                ignoredAttrs.Add("publicdelegates");
                ignoredAttrs.Add("deleteditemflags");
                ignoredAttrs.Add("mDBStorageQuota".ToLowerInvariant());
                ignoredAttrs.Add("mDBOverQuotaLimit".ToLowerInvariant());
                ignoredAttrs.Add("garbageCollPeriod".ToLowerInvariant());
                ignoredAttrs.Add("mDBOverHardQuotaLimit".ToLowerInvariant());
                ignoredAttrs.Add("altrecipient");
                ignoredAttrs.Add("deliverandredirect");
                ignoredAttrs.Add("securityprotocol");
                ignoredAttrs.Add("reporttooriginator");
                ignoredAttrs.Add("reporttoowner");
                ignoredAttrs.Add("oOFReplyToOriginator".ToLowerInvariant());
                ignoredAttrs.Add("mapirecipient");
                ignoredAttrs.Add("internetencoding");
                ignoredAttrs.Add("targetaddress");
                ignoredAttrs.Add("altrecipientbl");
                ignoredAttrs.Add("delivcontlength");
                ignoredAttrs.Add("submissioncontlength");
            }

            bool ignored = false, hasPw = false;
            int pwdScore = 0;
            string thisDn = null;

            r.OnBeginEntry += (s, a) =>
            {
                thisDn = a.DistinguishedName;

                hasPw = false;

                if (ignoreIt != null && ignoreIt.Invoke(a.DistinguishedName))
                {
                    ignored = true;
                }
                // Ignore domain trusts / special accounts
                // This part could use some rethinking.
                else if (a.DistinguishedName.Contains("$,CN=Users,") || a.DistinguishedName.Contains("krbtgt") || a.DistinguishedName.Contains("ForeignSecurityP"))
                {
                    ignored = true;
                }
                else if (!allowMsExchange && a.DistinguishedName.Contains("Exchange System"))
                {
                    ignored = true;
                }
                else
                {
                    ignored = false;
                    w.BeginEntry(a.DistinguishedName);
                }
            };

            r.OnEndEntry += (s, a) =>
            {
                if (!ignored)
                {
                    if (pwdScore > 1 && !hasPw)

                        w.WriteAttr("unicodePwd", passwordEncoding.GetBytes(
                            string.Format("\"{0}\"", defaultPwd))
                            );

                    w.EndEntry();
                }
                pwdScore = 0;
            };

            r.OnAttributeValue += (s, a) =>
            {
                if (!ignored)
                {

                    if (a.Name == "unicodePwd")
                        hasPw = true;
                    else if (a.Name == "objectCategory" && ((string)a.Value).StartsWith("CN=Person"))
                        pwdScore++;
                    else if (a.Name == "objectClass" && "user".Equals(a.Value))
                        pwdScore++;

                    if (string.Equals(a.Name, "objectSID", StringComparison.InvariantCultureIgnoreCase))
                    {
                        if (thisDn.IndexOf("ForeignSecurity", StringComparison.InvariantCultureIgnoreCase) > 0)
                        {
                            if (a.Value is byte[])
                            {
                                System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier((byte[])a.Value, 0);

                                w.WriteAttr(a.Name, sid.ToString());
                            }
                            else if (a.Value is string)
                            {
                                w.WriteAttr(a.Name, (string)a.Value);
                            }
                        }
                    }
                    else
                    {
                        if (a.Value != null && !ignoredAttrs.Contains(a.Name.ToLowerInvariant()))
                        {
                            if (allowMsExchange ||
                                (!a.Name.StartsWith("msExch", StringComparison.InvariantCultureIgnoreCase)
                                  && !a.Name.StartsWith("extensionAttribute")))
                            {
                                if (a.Value is string)
                                {
                                    w.WriteAttr(a.Name, (string)a.Value);
                                }
                                else if (a.Value is byte[])
                                {
                                    w.WriteAttr(a.Name, (byte[])a.Value);
                                }
                                else
                                {
                                    Console.Error.WriteLine("Warn: type of {0} is {1}", a.Name, a.Value.GetType());
                                    w.WriteAttr(a.Name, Convert.ToString(a.Value));
                                }
                            }
                        }
                    }
                }
            };

            while (r.Read())
            {
                // Keep reading
            }

            w.Close();
        }
Example #39
0
        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;
                            }
                        }
                    }
                }
            }
        }
        public string ResolveUsernameToLookupValue(string username, string staffInfoLookupKey)
        {
            if (lookupValuesByUsername.ContainsKey(username))
                return lookupValuesByUsername[username];

            DirectorySearcher search = null;
            string ldapLookupValue = null;
            string ldapLookupKey = null;
            try
            {
                ldapLookupKey = GetLdapLookupKey();

                search = new DirectorySearcher(SearcherEntry)
                            {
                                Filter = "(" + LdapUsernameProperty + "=" + username + ")"
                            };
                search.PropertiesToLoad.Add(ldapLookupKey);

                var result = search.FindOne();

                if (result == null)
                    return null;

                if (!result.Properties.Contains(ldapLookupKey))
                    throw new DistrictProtocolAuthenticationException(string.Format(NoLookupValueErrorMessageFormat, string.Format(NoPropertyReturnedFormat, ldapLookupKey, username))) { Name = username };

                if (result.Properties[ldapLookupKey].Count == 0)
                    throw new DistrictProtocolAuthenticationException(string.Format(NoLookupValueErrorMessageFormat, string.Format(EmptyPropertyCollectionFormat, ldapLookupKey, username))) { Name = username };

                var resultValue = result.Properties[ldapLookupKey][0];
                if (resultValue is string)
                {
                    ldapLookupValue = (string)resultValue;
                }
                else if (resultValue is byte[])
                {
                    //LDAP can return a few different types. If it's a byte[], it's probably because ldapLookupKey is objectsid.  Convert the byte[] to a SID.
                    var sid = new System.Security.Principal.SecurityIdentifier((byte[]) (resultValue), 0);
                    ldapLookupValue = sid.ToString();
                }
                else
                {
                    throw new InvalidCastException("The type of the Property is " + resultValue.GetType() + " and it needs to be a string or a SID.");
                }

                ldapLookupValue = ldapLookupValue.ToLower();

                lookupValuesByUsername[username] = ldapLookupValue;
            }
            finally
            {
                if (search != null)
                    search.Dispose();
            }

            if (string.IsNullOrEmpty(ldapLookupValue))
                throw new DistrictProtocolAuthenticationException(string.Format(NoLookupValueErrorMessageFormat, string.Format(BlankValueReturnedFormat, ldapLookupKey, username))) { Name = username };

            return ldapLookupValue;
        }
Example #41
0
 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;
 }
        internal void SetDriveMapsTargetingFilterInternal(string organizationId, ExchangeAccount[] accounts, string locationPath)
        {
            HostedSolutionLog.LogStart("SetDriveMapsTargetingFilterInternal");
            HostedSolutionLog.DebugInfo("organizationId : {0}", organizationId);
            HostedSolutionLog.DebugInfo("folderName : {0}", locationPath);

            if (string.IsNullOrEmpty(organizationId))
                throw new ArgumentNullException("organizationId");

            if (string.IsNullOrEmpty(locationPath))
                throw new ArgumentNullException("folderName");

             try
             {
                 Dictionary<string, ExchangeAccount> sidAccountPairs = new Dictionary<string, ExchangeAccount>();

                 foreach (var account in accounts)
                 {
                     string path = IsGroup(account) ? GetGroupPath(organizationId, account.AccountName) : GetUserPath(organizationId, account.AccountName);

                     DirectoryEntry entry = ActiveDirectoryUtils.GetADObject(path);

                     byte[] sidByteArr = (byte[])ActiveDirectoryUtils.GetADObjectProperty(entry, ADAttributes.SID);

                     string sid = new System.Security.Principal.SecurityIdentifier(sidByteArr, 0).ToString();

                     sidAccountPairs.Add(sid, account);
                 }

                 string gpoId;

                 if (!CheckMappedDriveGpoExists(organizationId, out gpoId))
                 {
                     CreateAndLinkMappedDrivesGPO(organizationId, out gpoId);
                 }

                 if (!string.IsNullOrEmpty(gpoId))
                 {
                     string drivesXmlPath = string.Format("{0}\\{1}",
                                                          string.Format(GROUP_POLICY_MAPPED_DRIVES_FILE_PATH_TEMPLATE, RootDomain, gpoId),
                                                          "Drives.xml");
                     // open xml document
                     var xml = GetOrCreateDrivesFile(gpoId);

                     XmlNodeList drives = xml.SelectNodes(string.Format("./Drives/Drive[contains(Properties/@path,'{0}')]", locationPath));

                     foreach (XmlNode driveNode in drives)
                     {
                         XmlNodeList childNodes = driveNode.ChildNodes;

                         if (childNodes.Count > 1)
                         {
                             //delete existing filters
                             driveNode.LastChild.ParentNode.RemoveChild(driveNode.LastChild);
                         }

                         XmlNode newFiltersNode = CreateFiltersNode(xml, sidAccountPairs);

                         driveNode.AppendChild(newFiltersNode);
                     }

                     xml.Save(drivesXmlPath);

                     IncrementGPOVersion(organizationId, gpoId);
                 }
             }
             catch (Exception)
             {
                 throw;
             }
             finally
             {
                 HostedSolutionLog.LogEnd("SetDriveMapsTargetingFilterInternal");
             }
        }
        /*
        *METHOD		    :	listener
        *
        *DESCRIPTION	:	Thread used to listen to the default named pipe
         *                  when a connection comes it creates a unique port name
         *                  starts a new thread for that connection on the new port
        *
        *PARAMETERS		:	
        *  
        *RETURNS		:	void
        *
        */
        private void listener()
        {

            NamedPipeClientStream client;
            NamedPipeServerStream server;
            StreamReader input;
            StreamWriter output;
            string serverName = "";
            string clientPipeName = "";

            //set up pipe secutity
            Logger.Log("Waiting for connection");
            PipeSecurity ps = new PipeSecurity();
            System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
            PipeAccessRule par = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
            ps.AddAccessRule(par);

            //start server
            server = new NamedPipeServerStream("ServiceOutgoing", PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 5000, 5000, ps);

            while(!Done)
            {
                try
                {
                    //wait for user to connect
                    server.WaitForConnection();
                    input = new StreamReader(server);

                    //get name of computer that connect
                    serverName = input.ReadLine();
                    Logger.Log("User Connected. Computer name: " + serverName);

                    //connect back
                    client = new NamedPipeClientStream(serverName, "UserOutgoing");//add server name
                    client.Connect(30);
                    output = new StreamWriter(client);
                    Logger.Log("Connected back to user " + serverName);
                    
                    //create a unique pipe name for that computer
                    clientPipeName = "Pipe" + userCount.ToString();
                    userCount++;
                    //send the pipe name
                    output.WriteLine(clientPipeName);
                    output.Flush();

                    Logger.Log("Start Clients Thread, pipe name: " + clientPipeName);
                    //start thread to monitor that pipe
                    Thread t2 = new Thread(new ParameterizedThreadStart(clientThread));
                    t2.Start((object)clientPipeName);

                    //and the thread to the repo
                    clients.AddClient(t2, clientPipeName);
                    //disconect from that user to start listning again
                    server.Disconnect();
                }
                catch (IOException)
                {
                    Logger.Log("Connect() failed");
                    Done = true;
                }
                catch (Exception ex)
                {
                    Logger.Log("Unknown Error: " + ex.Message);
                    Done = true;
                }
            }

            Logger.Log("Main loop closed");
        }
        public void ModifyHttpSettings()
        {
            string everyone = new System.Security.Principal.SecurityIdentifier(
                "S-1-1-0").Translate(typeof(System.Security.Principal.NTAccount)).ToString();

            string parameter = $@"http add urlacl url=http://+:{_portNumber}/ user=\everyone";

            ProcessStartInfo psi = new ProcessStartInfo("netsh", parameter);

            psi.Verb = "runas";
            psi.RedirectStandardOutput = false;
            psi.CreateNoWindow = true;
            psi.WindowStyle = ProcessWindowStyle.Hidden;
            psi.UseShellExecute = true;
            Process.Start(psi);
        }
        /*
        *METHOD		    :	clientThread
        *
        *DESCRIPTION	:	Method to listen to a spesific users pipe
         *                  Is creates the connection, listens for a command
         *                  then acts acordingly based on that command
        *
        *PARAMETERS		:	object sender:  Opject relaying information on where the even call came from
        *                   EventArgs e:    Object that contains data about the event
        *  
        *RETURNS		:	void
        *
        */
        private async void clientThread(object clientPipeName)
        {
            string serverName = "";
            string pipeName = (string)clientPipeName;
            
            NamedPipeClientStream client;
            NamedPipeServerStream server;
            StreamReader input;
            StreamWriter output;

            DAL dal = new DAL();
            string userName = "";

            //set up pipe security
            PipeSecurity ps = new PipeSecurity();
            System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
            PipeAccessRule par = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
            ps.AddAccessRule(par);

            Logger.Log("Client thread started");

            //wait for user to connect
            server = new NamedPipeServerStream(clientPipeName + "service", PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 5000, 5000, ps);
            server.WaitForConnection();
            input = new StreamReader(server);

            Logger.Log("Client connected to pipe: " + clientPipeName);

            //get the name of the computer to connect back to
            serverName = input.ReadLine();

            //connect back
            try
            {
                client = new NamedPipeClientStream(serverName, clientPipeName + "User");
                client.Connect(30);
                output = new StreamWriter(client);

                Logger.Log("User thread connected to pipe: " + clientPipeName);

                //start loop to watch the pipe 
                while (!Done)
                {
                    //async read from pipe
                    char[] temp = new char[5000];
                    await input.ReadAsync(temp, 0, 5000);
                    //move data from pipe to a string (padded with somthing, not sure what)
                    string userCommand = new string(temp);
                    //all commands end in a period. if there is no period then the user left
                    if (!userCommand.Contains("."))
                    {
                        Logger.Log("Pipe: " + clientPipeName + "userLeft");
                        //close connection
                        output.Dispose();
                        input.Dispose();
                        //remove from repo
                        clients.DeleteClient((string)clientPipeName);
                        break;
                    }
                    //if the command is valid
                    //remove the period and all padded data
                    userCommand = userCommand.Remove(userCommand.IndexOf('.'));

                    Logger.Log("Pipe: " + clientPipeName + " Got Command: " + userCommand);
                    //select the command entered
                    if (userCommand == "NewUser")
                    {
                        Logger.Log("Pipe: " + clientPipeName + "in newUser command code");
                        //read in user name
                        userName = input.ReadLine();
                        //add to database
                        output.WriteLine("OK");
                        output.Flush();
                        //if user not in database add
                        dal.OpenConnection();
                        bool isUserTaken = dal.IsNameInDatabase(userName);
                        dal.CloseConnection();
                        if (isUserTaken == false)
                        {
                            dal.OpenConnection();
                            dal.StoreUserName(userName);
                            dal.InitializeUserInLeaderboard(userName, 1);
                            dal.CloseConnection();
                        }
                    }
                    else if (userCommand == "GetQuestion")
                    {
                        Logger.Log("Pipe: " + clientPipeName + "in GetQuestion command code.");
                        string[] splitbuffer = new string[5];
                        
                        //read in question number
                        string buffer = input.ReadLine();
                        int questionNumber = Int32.Parse(buffer);
                        Logger.Log("Pipe: " + clientPipeName + "in GetQuestion command code. Getting Question: " + questionNumber);
                        // get question and answers from database
                        dal.OpenConnection();
                        string questionFromDatabase = dal.GetQuestionAndAnswers(questionNumber);
                        dal.CloseConnection();

                        //get question data
                        //put it in questionFromDatabase
                        splitbuffer = questionFromDatabase.Split('|');
                        output.WriteLine(splitbuffer[0]);//question
                        output.Flush();
                        output.WriteLine(splitbuffer[1]);//answer1
                        output.Flush();
                        output.WriteLine(splitbuffer[2]);//answer2
                        output.Flush();
                        output.WriteLine(splitbuffer[3]);//answer3
                        output.Flush();
                        output.WriteLine(splitbuffer[4]);//answer4
                        output.Flush();
                        output.WriteLine(splitbuffer[5]);//correct answer
                        output.Flush();
                    }
                    else if (userCommand == "QuestionAnswered")
                    {
                        Logger.Log("Pipe: " + clientPipeName + "in QuestionAnswered command code");
                        //read in question number
                        string questionNumber = input.ReadLine();
                        int intQuestionNumber = Convert.ToInt32(questionNumber);
                        //read in users answer
                        string answer = input.ReadLine();
                        //read in user score
                        string score = input.ReadLine();
                        int intScore = Convert.ToInt32(score);

                        //send to database
                        dal.OpenConnection();
                        dal.StoreUserAnswer(userName, 1, intQuestionNumber, answer, intScore);
                        dal.CloseConnection();

                        output.WriteLine("OK");
                        output.Flush();
                    }
                    else if (userCommand == "GameDone")
                    {
                        Logger.Log("Pipe: " + clientPipeName + "in GameDone command code");
              
                        //read in users score for the game
                        string gameScore = input.ReadLine();
                        int intGameScore = Convert.ToInt32(gameScore);
                        //save to database
                        dal.OpenConnection();
                        dal.AlterLeaderboard(1, userName, intGameScore);
                        dal.CloseConnection();

                        //get leaderboard from database
                        dal.OpenConnection();
                        string leaderboard = dal.Leaderboard(1); //get leaderboard from database
                        dal.CloseConnection();
                        //send leaderboard to user
                        output.WriteLine(leaderboard);
                        output.Flush();
                    }
                    else if (userCommand == "GetLeaderboard")
                    {
                        Logger.Log("Pipe: " + clientPipeName + "in GetLeaderboard command code");
                        dal.OpenConnection();
                        string leaderboard = dal.Leaderboard(1); //get leaderboard from database
                        dal.CloseConnection();
                        //send leaderboard to user
                        output.WriteLine(leaderboard);
                        output.Flush();
                    }
                    else if (userCommand == "GetCurrentStatus")
                    {
                        Logger.Log("Pipe: " + clientPipeName + "in GetCurrentStatus command code");
                        dal.OpenConnection();
                        string currentStatus = dal.GetCurrentStatus(1); //get currentStatus from database
                        dal.CloseConnection();
                        //send currentStatus to user
                        output.WriteLine(currentStatus);
                        output.Flush();
                    }
                    else if (userCommand == "SaveQuestion")
                    {
                        Logger.Log("Pipe: " + clientPipeName + "in SaveQuestion command code");
                        int questionNumber = Int32.Parse(input.ReadLine());
                        string question = input.ReadLine();
                        string answer1 = input.ReadLine();
                        string answer2 = input.ReadLine();
                        string answer3 = input.ReadLine();
                        string answer4 = input.ReadLine();
                        int correctAnswer = Int32.Parse(input.ReadLine());

                        //send question to database
                        dal.OpenConnection();
                        dal.UpdateQuestionAndAnswer(questionNumber, question, answer1, answer2, answer3, answer4, correctAnswer);
                        dal.CloseConnection();

                        output.WriteLine("ok");
                        output.Flush();
                    }
                    else if (userCommand == "GetExcel")
                    {
                        Logger.Log("Pipe: " + clientPipeName + "in GetExcel command code");

                        //send all of the questions
                        for (int counter = 0; counter < 10; counter++)
                        {
                            dal.OpenConnection();
                            String question = dal.GetQuestion(counter + 1);
                            dal.CloseConnection();
                            output.WriteLine(question);
                            output.Flush();
                        }

                        //send the average time to answer correctly
                        for (int counter = 0; counter < 10; counter++)
                        {
                            dal.OpenConnection();
                            float currentAverageTime = dal.GetAverageTimeToAnswerCorrectly(counter + 1);
                            dal.CloseConnection();
                            output.WriteLine(currentAverageTime);
                            output.Flush();
                        }

                        //send the percent of users who answered correctly
                        for (int counter = 0; counter < 10; counter++)
                        {
                            dal.OpenConnection();
                            float currentQuestionPercent = dal.GetPercentOfUsersWhoAnsweredCorrectly(counter + 1);
                            dal.CloseConnection();
                            output.WriteLine(currentQuestionPercent);
                            output.Flush();
                        }
                    }
                    else if (userCommand == "Quit")
                    {
                        Logger.Log("Pipe: " + clientPipeName + "Closing");
                        //close connection
                        output.Dispose();
                        input.Dispose();
                        //remove from repo
                        clients.DeleteClient((string)clientPipeName);
                        //change user to inactive
                        dal.OpenConnection();
                        dal.SetUserToInactive(userName);
                        dal.CloseConnection();
                        break;
                    }
                    else
                    {
                        Logger.Log("Pipe: " + clientPipeName + "Command not recognized");
                    }
                }
                //when the loop is done then the user is no longer active
                dal.OpenConnection();
                dal.SetUserToInactive(userName);
                dal.CloseConnection();
            }
            catch(Exception ex)
            {
                Logger.Log("Pipe: " + clientPipeName + " unknown error: " + ex.Message);
                clients.DeleteClient((string)clientPipeName);

                dal.OpenConnection();
                dal.SetUserToInactive(userName);
                dal.CloseConnection();
            }
        }
Example #46
0
        public static void CreateDirectoryForEveryone(string logPath)
        {
            DirectorySecurity dirInfoSec = null;
            if (!Directory.Exists(logPath))
            {
                var dirInfo = Directory.CreateDirectory(logPath);
                dirInfoSec = dirInfo.GetAccessControl();
            }

            if(dirInfoSec == null)
            {
                dirInfoSec = Directory.GetAccessControl(logPath);
            }

            {
                var everyone = new System.Security.Principal.SecurityIdentifier("S-1-1-0").Translate(typeof(System.Security.Principal.NTAccount)).ToString();
                dirInfoSec.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
                dirInfoSec.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.ReadAndExecute, AccessControlType.Allow));
                dirInfoSec.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.CreateFiles, AccessControlType.Allow));
                Directory.SetAccessControl(logPath, dirInfoSec);
            }
        }
 private void Item2_Click(object sender, RoutedEventArgs e)
 {
     if ((ListBox)mostRecent as ListBox == gameBoxSource)
     {
         string directory = Path.Combine(selectedSourcePath.Text.ToString(), "steamapps", "common", leftDictionary[dank.ToString()][0]);
         DirectoryInfo dInfo = new DirectoryInfo(directory);
         System.Security.AccessControl.DirectorySecurity dSecurity = dInfo.GetAccessControl();
         var things = dSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
         foreach (System.Security.AccessControl.FileSystemAccessRule fsaRule in things)
         {
             //MessageBox.Show(fsaRule.IdentityReference + " " + fsaRule.AccessControlType + " " + fsaRule.FileSystemRights);
             if (fsaRule.AccessControlType == System.Security.AccessControl.AccessControlType.Deny)
             {
                 dSecurity.RemoveAccessRule(fsaRule);
             }
         }
         var sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
         dSecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule("CREATOR OWNER", System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.InheritanceFlags.ObjectInherit | System.Security.AccessControl.InheritanceFlags.ContainerInherit, System.Security.AccessControl.PropagationFlags.InheritOnly, System.Security.AccessControl.AccessControlType.Allow));
         dSecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(sid, System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.InheritanceFlags.ObjectInherit | System.Security.AccessControl.InheritanceFlags.ContainerInherit, System.Security.AccessControl.PropagationFlags.InheritOnly, System.Security.AccessControl.AccessControlType.Allow));
         dInfo.SetAccessControl(dSecurity);
     }
     else if ((ListBox)mostRecent as ListBox == gameBoxDest)
     {
         string directory = Path.Combine(selectedDestPath.Text.ToString(), "steamapps", "common", rightDictionary[dank.ToString()][0]);
         DirectoryInfo dInfo = new DirectoryInfo(directory);
         System.Security.AccessControl.DirectorySecurity dSecurity = dInfo.GetAccessControl();
         var things = dSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
         foreach (System.Security.AccessControl.FileSystemAccessRule fsaRule in things)
         {
             //MessageBox.Show(fsaRule.IdentityReference + " " + fsaRule.AccessControlType + " " + fsaRule.FileSystemRights);
             if (fsaRule.AccessControlType == System.Security.AccessControl.AccessControlType.Deny)
             {
                 dSecurity.RemoveAccessRule(fsaRule);
             }
         }
         var sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
         dSecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule("CREATOR OWNER", System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.InheritanceFlags.ObjectInherit | System.Security.AccessControl.InheritanceFlags.ContainerInherit, System.Security.AccessControl.PropagationFlags.InheritOnly, System.Security.AccessControl.AccessControlType.Allow));
         dSecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(sid, System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.InheritanceFlags.ObjectInherit | System.Security.AccessControl.InheritanceFlags.ContainerInherit, System.Security.AccessControl.PropagationFlags.InheritOnly, System.Security.AccessControl.AccessControlType.Allow));
         dInfo.SetAccessControl(dSecurity);
     }
 }
        /// <summary>
        /// Listen from service for commands from core or configurator
        /// </summary>
        public static void StartListening()
        {
            if (connected) return; //only one connection...

            Async.Queue("MB Connection", () =>
            {
                System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.BuiltinUsersSid, null);

                PipeSecurity pipeSa = new PipeSecurity();
                pipeSa.SetAccessRule(new PipeAccessRule(sid,
                       PipeAccessRights.ReadWrite, AccessControlType.Allow));

                using (NamedPipeServerStream pipe = new NamedPipeServerStream(MBServiceController.MBSERVICE_IN_PIPE, PipeDirection.In,1,PipeTransmissionMode.Message,PipeOptions.None,1024,1024,pipeSa))
                {
                    connected = true;
                    bool process = true;
                    while (process)
                    {
                        pipe.WaitForConnection(); //wait for the core to tell us something
                        try
                        {
                            // Read the request from the sender.
                            StreamReader sr = new StreamReader(pipe);

                            string command = sr.ReadLine();
                            switch (command.ToLower())
                            {
                                case IPCCommands.ReloadKernel: //don't use this yet - need to figure out how to unload first do a shutdown and restart
                                    //something changed, we need to re-load everything
                                    Logger.ReportInfo("Re-loading kernel due to request from client.");
                                    Kernel.Init(KernelLoadDirective.ShadowPlugins);
                                    break;
                                case IPCCommands.ReloadConfig:
                                    //re-load the main config file
                                    Kernel.Instance.ReLoadConfig();
                                    break;
                                case IPCCommands.Shutdown:
                                    //close Service
                                    Logger.ReportInfo("Shutting down due to request from client.");
                                    MainWindow.Instance.Shutdown();
                                    break;
                                case IPCCommands.Restart:
                                    //restart Service
                                    Logger.ReportInfo("Restarting due to request from client.");
                                    MainWindow.Instance.Restart();
                                    break;
                                case IPCCommands.CancelRefresh:
                                    //cancel any running refresh
                                    MainWindow.Instance.CancelRefresh();
                                    break;
                                case IPCCommands.ForceRebuild:
                                    //force a re-build of the library - used with new version that requires it
                                    Logger.ReportInfo("Forcing re-build of library due to request from client.");
                                    MainWindow.Instance.ForceRebuild();
                                    break;
                                case IPCCommands.Refresh:
                                    Logger.ReportInfo("Refreshing now due to request from client.");
                                    MainWindow.Instance.RefreshNow();
                                    break;
                                case IPCCommands.CloseConnection:
                                    //exit this connection
                                    Logger.ReportInfo("Client requested we stop listening.");
                                    process = false;
                                    break;

                            }
                            pipe.Disconnect();
                        }
                        catch (IOException e)
                        {
                            Logger.ReportException("Error in MB connection", e);
                        }
                    }
                    pipe.Close();
                    connected = false;
                }
            });
        }
Example #49
0
        static void HandleQueueThread(Object stateInfo)
        {
            // the pipe here will be handled synchronously
            NewQueueToken token = (NewQueueToken)stateInfo;
            string pipename = token.queueName;
            System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
            PipeAccessRule pac = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
            PipeSecurity ps = new PipeSecurity();
            ps.AddAccessRule(pac);
            sid = null;

            using (NamedPipeServerStream queuePipe = new NamedPipeServerStream(pipename,
                    PipeDirection.InOut,
                    serverInstances,
                    PipeTransmissionMode.Message,
                    PipeOptions.None,
                    1024,
                    1024,
                    ps))
            {                Console.WriteLine("pipe {0} created, waiting..", token.queueName);
                // inform the main thread that the queue is on
                token.semaphore.Set();
                if (token.abort)
                    return;
                queuePipe.WaitForConnection();
                Console.WriteLine("pipe {0} connected", token.queueName);
                StreamReader reader = new StreamReader(queuePipe);
                StreamWriter writer = new StreamWriter(queuePipe);
                try
                {
                    MonitorMessage messageIn;
                    // step 1: enable counters
                    char[] data = new char[1024];
                    for (int i = 0; i < data.Length; i++)
                        data[i] = (char)0;
                    reader.ReadBlock(data, 0, data.Length);
                    messageIn = MonitorMessage.ParseFromString(new String(data));
                    Console.WriteLine("pipe {0} received {1}", token.queueName, messageIn.ToString());

                    if (messageIn.OpCode != OpCodes.ENABLE_COUNTERS_MESSAGE)
                        throw new InvalidOperationException("I was expeting an Enumerate Counters message and received " + messageIn.OpCode.ToString());
                    // counters
                    List<string> countersList = new List<string>(messageIn.Body);
                    // list of counters to enable
                    // TODO: how to get selectedCounters?
                    if (token.selectCounter != null)
                    {
                        string[] selectedCounters = token.selectCounter(token.DeviceId, countersList.ToArray());
                        writer.Write(new MonitorMessage(OpCodes.OK_MESSAGE, 0, 0, selectedCounters.Select(x => countersList.IndexOf(x)).ToArray()).ToString());
                        writer.Flush();
                    }
                    else
                    {
                        // delegate not set!
                        writer.Write(new MonitorMessage(OpCodes.OK_MESSAGE, 0, 0, new int[] { }).ToString());
                        writer.Flush();
                    }
                    // step 2:perf init
                    for (int i = 0; i < data.Length; i++)
                        data[i] = (char)0;
                    reader.ReadBlock(data, 0, data.Length);
                    messageIn = MonitorMessage.ParseFromString(new String(data));
                    Console.WriteLine("pipe {0} received {1}", token.queueName, messageIn.ToString());
                    if (messageIn.OpCode != OpCodes.GPU_PERF_INIT_MESSAGE)
                        throw new InvalidOperationException("I was expeting an Perf init message and received " + messageIn.OpCode.ToString());
                    writer.Write(new MonitorMessage(OpCodes.OK_MESSAGE, 0, 0).ToString());
                    writer.Flush();

                    // step 3: release
                    for (int i = 0; i < data.Length; i++)
                        data[i] = (char)0;
                    reader.ReadBlock(data, 0, data.Length);
                    messageIn = MonitorMessage.ParseFromString(new String(data));
                    if (messageIn.OpCode != OpCodes.RELEASE_QUEUE_MESSAGE)
                        throw new InvalidOperationException("I was expeting a release message and received " + messageIn.OpCode.ToString());
                    writer.Write(new MonitorMessage(OpCodes.OK_MESSAGE, 0, 0).ToString());
                    writer.Flush();

                    // step 5: end
                    for (int i = 0; i < data.Length; i++)
                        data[i] = (char)0;
                    reader.ReadBlock(data, 0, data.Length);
                    messageIn = MonitorMessage.ParseFromString(new String(data));
                    Console.WriteLine("pipe {0} received {1}", token.queueName, messageIn.ToString());
                    if (messageIn.OpCode != OpCodes.GPU_PERF_RELEASE_MESSAGE)
                        throw new InvalidOperationException("I was expeting an End message and received " + messageIn.OpCode.ToString());
                    writer.Write(new MonitorMessage(OpCodes.OK_MESSAGE, 0, 0).ToString());
                    writer.Flush();

                    // step 4: get counters
                    for (int i = 0; i < data.Length; i++)
                        data[i] = (char)0;
                    reader.ReadBlock(data, 0, data.Length);
                    messageIn = MonitorMessage.ParseFromString(new String(data));
                    Console.WriteLine("pipe {0} received {1}", token.queueName, messageIn.ToString());
                    if (messageIn.OpCode != OpCodes.GET_COUNTERS_MESSAGE)
                        throw new InvalidOperationException("I was expeting a Get Counters message and received " + messageIn.OpCode.ToString());
                    float[] values = messageIn.BodyAsFloatArray;
                    // TODO: send values
                    if (token.receivedValues != null)
                    {
                        token.receivedValues(token.DeviceId, values);
                    }

                    writer.Write(new MonitorMessage(OpCodes.OK_MESSAGE, 0, 0).ToString());
                    writer.Flush();

                }
                // Catch the IOException that is raised if the pipe is broken
                // or disconnected.
                catch (IOException e)
                {
                    Console.WriteLine("ERROR: {0}", e.Message);
                }
                catch (InvalidOperationException e)
                {
                    // TODO: what is the code for invalid operation?
                    writer.Write(new MonitorMessage(OpCodes.OK_MESSAGE, 1, 1).ToString());
                    writer.Flush();
                }
                finally
                {
                    queuePipe.Close();
                }
            }
        }
        static void Main(string[] args)
        {
            if (args.Length == 1 && (args[0] == "-addurl" || args[0] == "-delurl"))
            {
                string opt = args[0].Substring(1);

                string everyone = new System.Security.Principal.SecurityIdentifier(
                            "S-1-1-0").Translate(typeof(System.Security.Principal.NTAccount)).ToString();

                // Нам нужен номер порта для endpoint'а
                string config_path = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;

                Console.WriteLine("\n\n");
                Console.WriteLine("config_path={0}", config_path);

                int ServicePort = -1;
                System.Xml.XmlDocument config = new System.Xml.XmlDocument();
                config.Load(config_path);

                foreach (System.Xml.XmlNode nx in config.DocumentElement.SelectNodes("/configuration/system.serviceModel/services/service/endpoint"))
                {
                    if (nx.Attributes["contract"].Value == "WindowsServiceHost.INormalizePhraseService")
                    {
                        string address = nx.Attributes["address"].Value;
                        System.Uri uri = new Uri(address);
                        ServicePort = uri.Port;
                        break;
                    }
                }

                /*
                                            //System.ServiceModel.Configuration.ClientSection clientSection = (System.ServiceModel.Configuration.ClientSection)System.Configuration.ConfigurationManager.GetSection("system.serviceModel/client");

                                            System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
                                            System.ServiceModel.Configuration.ServiceModelSectionGroup serviceModelSectionGroup = System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup(configuration);
                                            System.ServiceModel.Configuration.ClientSection clientSection = serviceModelSectionGroup.Client;
                                            Console.WriteLine( "clientSection.Endpoints.Count={0}", clientSection.Endpoints.Count );

                                            for (int k = 0; k < clientSection.Endpoints.Count; ++k)
                                            {

                                                if (clientSection.Endpoints[k].Contract == "WindowsServiceHost.IReplicationService2")
                                                {
                                                    ServicePort = clientSection.Endpoints[k].Address.Port;
                                                    break;
                                                }
                                            }
                */

                if (ServicePort == -1)
                {
                    Console.WriteLine("Could not find endpoint addess in {0}", config_path);
                }
                else
                {
                    string parameter = "http ";

                    if (opt == "addurl")
                    {
                        parameter += "add";
                    }
                    else
                    {
                        parameter += "delete";
                    }

                    parameter += " urlacl url=http://+:" + ServicePort.ToString() + "/NormalizationService/ user=\"" + everyone + "\"";

                    //string parameter = "http add urlacl url=http://+:9003/ReplicationService/ user=\"" + System.Security.Principal.WindowsIdentity.GetCurrent().Name + "\"";

                    System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("netsh", parameter);

                    psi.Verb = "runas";
                    psi.RedirectStandardOutput = false;
                    //psi.CreateNoWindow = true;
                    //psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                    psi.UseShellExecute = true;

                    Console.WriteLine("Executing {0} {1}", psi.FileName, psi.Arguments);
                    System.Diagnostics.Process p = System.Diagnostics.Process.Start(psi);
                    p.WaitForExit();
                    Console.WriteLine("Done");
                }

                return;

            }

            ServiceHost host = new ServiceHost(typeof(WindowsServiceHost.NormalizePhraseService));

            /*
                        Uri base_address = host.Description.Endpoints[0].Address.Uri;

                        ServiceMetadataBehavior smb = host.Description.Behaviors.Find<ServiceMetadataBehavior>();

                        if (smb == null)
                            smb = new ServiceMetadataBehavior();
                        smb.HttpGetEnabled = true;
                        smb.HttpGetUrl = base_address;
                        smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
                        host.Description.Behaviors.Add(smb);

                        // Add MEX endpoint
                        host.AddServiceEndpoint(
                          ServiceMetadataBehavior.MexContractName,
                          MetadataExchangeBindings.CreateMexHttpBinding(),
                          base_address.ToString() + "/mex" //"http://127.0.0.1:9003/ReplicationService/mex"
                        );
            */

            #region Net Tcp Binding
            NetTcpBinding binding = new NetTcpBinding();
            binding.TransferMode = TransferMode.Buffered;
            binding.MaxReceivedMessageSize = int.MaxValue;
            binding.CloseTimeout = TimeSpan.MaxValue;
            binding.SendTimeout = TimeSpan.MaxValue;
            host.AddServiceEndpoint(typeof(WindowsServiceHost.INormalizePhraseService), binding, new Uri("net.tcp://localhost:1973/NormalizationService"));
            #endregion

            /*
                     #region Matadata Exchange Binding
                     host.Description.Behaviors.Add(new ServiceMetadataBehavior());
                     Binding mexBinding = MetadataExchangeBindings.CreateMexTcpBinding();
                     host.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, new Uri("net.tcp://localhost:1973/NormalizationService/mex"));
                     #endregion
            */

            host.Open();

            Console.WriteLine("Press a key to stop the service");
            Console.ReadKey();
            return;
        }
Example #51
0
        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);
        }
Example #52
0
        /*
        *METHOD		    :	btn_submit_Click
        *
        *DESCRIPTION	:	used to send the new question to the service when submit clicked
        *
        *PARAMETERS		:	object sender:  Object relaying information on where the event call came from
        *                   EventArgs e:    Object that contains data about the event
        *
        *RETURNS		:	void
        *
        */
        private void btn_submit_Click(object sender, EventArgs e)
        {
            if (txtbx_server.Text.Length > 0 && txtbx_name.Text.Length > 0)
            {
                try
                {
                    userName = txtbx_name.Text;
                    serverName = txtbx_server.Text;
                    //set up the named pipe security
                    PipeSecurity ps = new PipeSecurity();
                    System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
                    PipeAccessRule par = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
                    ps.AddAccessRule(par);

                    //connect to service
                    client = new NamedPipeClientStream(serverName, "ServiceOutgoing");//add server name
                    client.Connect(30);
                    output = new StreamWriter(client);

                    //tell ther service this computers name
                    output.WriteLine(Environment.MachineName);
                    output.Flush();

                    server = new NamedPipeServerStream("UserOutgoing", PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 5000, 5000, ps);
                    server.WaitForConnection();
                    input = new StreamReader(server);

                    //get namedPipe Name
                    pipeName = input.ReadLine();

                    server.Disconnect();
                    server.Dispose();
                    Close();
                }
                catch (Exception)
                {
                    MessageBox.Show("Failed to connect to Server", "Error");
                }
            }
        }