public void AclUser()
        {
            var account = new System.Security.Principal.NTAccount(Environment.UserName);

            Assert.That(account.ToString().Contains(Environment.UserName));
            Assert.That(account.IsValidTargetType(typeof(System.Security.Principal.SecurityIdentifier)));
            var securityAccount = account.Translate(typeof(System.Security.Principal.SecurityIdentifier)) as System.Security.Principal.SecurityIdentifier;

            Assert.That(securityAccount.IsAccountSid(), Is.True);
        }
예제 #2
0
        private static void Main(string[] args)
        {
            var user = new System.Security.Principal.NTAccount(@"IIS APPPOOL\10e6c294-9836-44a9-af54-207385846ebf");
            var sid  = user.Translate(typeof(System.Security.Principal.SecurityIdentifier));
            var ctx  = new PrincipalContext(ContextType.Machine);
            // This is weird - the user SID resolves to a group prinicpal, but it works that way.
            var appPoolIdentityGroupPrincipal = GroupPrincipal.FindByIdentity(ctx, IdentityType.Sid, sid.Value);

            Console.WriteLine(appPoolIdentityGroupPrincipal.Name);
            Console.WriteLine(appPoolIdentityGroupPrincipal.DisplayName);
            GroupPrincipal targetGroupPrincipal = GroupPrincipal.FindByIdentity(ctx, "Performance Monitor Users");

            // Making appPoolIdentity "group" a member of the "Performance Monitor Users Group"
            targetGroupPrincipal.Members.Add(appPoolIdentityGroupPrincipal);
            targetGroupPrincipal.Save();
            Console.WriteLine("DONE!");
            Console.ReadKey();
        }
        /// <summary>
        /// Create ssas base cube by calling SSAS API
        /// </summary>
        /// <param name="cubeServer">Cube server</param>
        /// <param name="cubeDBName">Cube data base name</param>
        /// <param name="cubeXmla">Base cube xmla</param>
        public void CREATE_SSAS_BASE_CUBE(
            DB_SQLHELPER_BASE sqlHelper,
            Server cubeServer,
            String cubeDBName,
            String cubeName,
            String dwConnectionString
            )
        {
            String SSASConfigurationPath = CONFIGURATION_HELPER.BASIC_CONFIGURATION_FOLDER + @"\SSASConfiguration\BaseCubeXMLA.xml";
            String SSASConfiguration     = "";

            System.Security.Principal.NTAccount          _Everyone_Account   = new System.Security.Principal.NTAccount("Everyone");
            System.Security.Principal.SecurityIdentifier _SecurityIdentifier = (System.Security.Principal.SecurityIdentifier)_Everyone_Account.Translate(typeof(System.Security.Principal.SecurityIdentifier));
            String sidString = _SecurityIdentifier.ToString();

            SSASConfiguration = System.IO.File.ReadAllText(SSASConfigurationPath);
            SSASConfiguration = SSASConfiguration
                                .Replace("$(dwConnectionString)", dwConnectionString)
                                .Replace("$(cubeDBName)", cubeDBName)
                                .Replace("$(cubeName)", cubeName)
                                .Replace("$(DBTableSchemaName)", CONFIGURATION_HELPER.GET_METADATA_PROPERTY("db_table_schema_name"))
                                .Replace("$(sid)", sidString);

            sqlHelper.ADD_MESSAGE_LOG(String.Format("[Create base cube] Starting create cube database {0}", cubeDBName), MESSAGE_TYPE.CREATE_CUBE, MESSAGE_RESULT_TYPE.Normal);
            XmlaResultCollection resultCol = cubeServer.Execute(SSASConfiguration);

            foreach (XmlaResult result in resultCol)
            {
                foreach (XmlaMessage message in result.Messages)
                {
                    if (message.ToString().Contains("error") || message.ToString().Contains("failed"))
                    {
                        sqlHelper.ADD_MESSAGE_LOG("[Create base cube]" + message.ToString(), MESSAGE_TYPE.CREATE_CUBE, MESSAGE_RESULT_TYPE.Error);
                        return;
                    }
                    else
                    {
                        sqlHelper.ADD_MESSAGE_LOG("[Create base cube]" + message.ToString(), MESSAGE_TYPE.CREATE_CUBE, MESSAGE_RESULT_TYPE.Succeed);
                    }
                }
            }
            sqlHelper.ADD_MESSAGE_LOG("[Create base cube]" + String.Format("Succeed to create cube database {0}", cubeDBName), MESSAGE_TYPE.CREATE_CUBE, MESSAGE_RESULT_TYPE.Succeed);
        }
예제 #4
0
파일: DFS.cs 프로젝트: erisonliang/qizmt
        static int _DfsGetBinaryNoWildCard(string dfspath, string targetFolder)
        {
            if (!targetFolder.EndsWith(@"\"))
            {
                targetFolder += @"\";
            }

            if (!dfs.DfsConfigExists(DFSXMLPATH))
            {
                Console.Error.WriteLine("DFS not setup; use:  {0} format", appname);
                SetFailure();
                return 0;
            }

            if (dfspath.StartsWith("dfs://", StringComparison.OrdinalIgnoreCase))
            {
                dfspath = dfspath.Substring(6);
            }

            if (dfspath.Length == 0)
            {
                Console.Error.WriteLine("Invalid dfspath");
                SetFailure();
                return 0;
            }

            EnsureNetworkPath(targetFolder);
            if (!System.IO.Directory.Exists(targetFolder))
            {
                Console.Error.WriteLine("Target folder is not found: {0}", targetFolder);
                return 0;
            }

            dfs dc = LoadDfsConfig();
            dfs.DfsFile dfsf = DfsFind(dc, dfspath);
            if (null == dfsf)
            {
                Console.Error.WriteLine("Error:  The specified file '{0}' does not exist in DFS", dfspath);
                SetFailure();
                return 0;
            }

            int blobPadSize = MySpace.DataMining.DistributedObjects.Blob.padSize;
            const int MAX_SIZE_PER_RECEIVE = 0x400 * 16 * 4;
            int filesCount = 0;
            byte[] fbuf = new byte[MAX_SIZE_PER_RECEIVE];

            System.Security.Principal.NTAccount nt = new System.Security.Principal.NTAccount(userdomain, dousername);
            System.Security.Principal.SecurityIdentifier secID = (System.Security.Principal.SecurityIdentifier)nt.Translate(typeof(System.Security.Principal.SecurityIdentifier));
            System.Security.AccessControl.FileSystemAccessRule rule = new System.Security.AccessControl.FileSystemAccessRule(secID,
            System.Security.AccessControl.FileSystemRights.FullControl,
            System.Security.AccessControl.AccessControlType.Allow);

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

            foreach (dfs.DfsFile.FileNode node in dfsf.Nodes)
            {
                bool eof = false;
                bool newline = false;
                System.IO.Stream fs = null;
                System.IO.FileStream ft = null;

                try
                {
                    fs = new DfsFileNodeStream(node, true, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read, FILE_BUFFER_SIZE);
                    {
                        int xhead = StreamReadLoop(fs, fbuf, 4);
                        if (4 == xhead)
                        {
                            int hlen = MySpace.DataMining.DistributedObjects.Entry.BytesToInt(fbuf);
                            StreamReadExact(fs, fbuf, hlen - 4);
                        }
                    }

                    while (!eof)
                    {
                        if (newline)
                        {
                            if (ft != null)
                            {
                                ft.Close();
                                ft = null;
                            }
                        }

                        int xread = 0;
                        while (xread < MAX_SIZE_PER_RECEIVE)
                        {
                            newline = false;
                            int ib = fs.ReadByte();
                            if (ib == -1)
                            {
                                eof = true;
                                break;
                            }

                            if ('\n' == ib)
                            {
                                newline = true;
                                break;
                            }

                            if (ib != '\r')
                            {
                                fbuf[xread++] = (byte)ib;
                            }
                        }

                        string s = System.Text.Encoding.UTF8.GetString(fbuf, 0, xread);

                        if (s.Length > 0)
                        {
                            if (ft == null)
                            {
                                string targetPath = targetFolder + s.Substring(0, blobPadSize).Trim();
                                s = s.Substring(260);
                                if (System.IO.File.Exists(targetPath))
                                {
                                    Console.Error.WriteLine("Warning: Local file overwritten: {0}", targetPath);
                                }
                                ft = new System.IO.FileStream(targetPath, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.Read, FILE_BUFFER_SIZE);
                                filesCount++;
                                try
                                {
                                    System.Security.AccessControl.FileSecurity fsec = new System.Security.AccessControl.FileSecurity();
                                    fsec.AddAccessRule(rule);
                                    System.IO.File.SetAccessControl(targetPath, fsec);
                                }
                                catch (Exception e)
                                {
                                    perrors.Add(e.ToString());
                                }
                            }

                            byte[] data = Convert.FromBase64String(s);
                            ft.Write(data, 0, data.Length);
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine("Error: {0}", e.Message);
                }
                finally
                {
                    if (ft != null)
                    {
                        ft.Close();
                        ft = null;
                    }

                    if (fs != null)
                    {
                        fs.Close();
                        fs = null;
                    }
                }
            }

            if (perrors.Count > 0)
            {
                Console.Error.WriteLine("Error while assigning file permission to: {0}\\{1}", userdomain, dousername);
                foreach (string perr in perrors)
                {
                    Console.Error.WriteLine(perr);
                }
            }
            return filesCount;
        }
예제 #5
0
파일: DFS.cs 프로젝트: erisonliang/qizmt
        // <dfspath> <localpath>
        static void _DfsGetNoWildcard(string[] args, int startparts, int lastparts)
        {
            //System.Threading.Thread.Sleep(8000);
            if (!dfs.DfsConfigExists(DFSXMLPATH))
            {
                Console.Error.WriteLine("DFS not setup; use:  {0} format", appname);
                SetFailure();
                return;
            }
            if (args.Length < 2)
            {
                Console.Error.WriteLine("dfs get error:  {0} dfs get <dfspath> <localpath>", appname);
                SetFailure();
                return;
            }
            {
                string dfspath = args[0];
                if (dfspath.StartsWith("dfs://", StringComparison.OrdinalIgnoreCase))
                {
                    dfspath = dfspath.Substring(6);
                }
                if (dfspath.Length == 0)
                {
                    Console.Error.WriteLine("Invalid dfspath");
                    SetFailure();
                    return;
                }
                
               string localpath = args[1];
               

                EnsureNetworkPath(localpath);

                if (localpath.EndsWith(".gz"))
                {
                    //Console.Error.WriteLine("Error: dfs get not supported for GZip (.gz) files; use dfs getgzip");
                    //SetFailure();
                    _DfsGetPartsNoWildcard(args, startparts, lastparts);
                    return;
                }

                if (!System.IO.File.Exists(localpath))
                {
                    
                    string folderPath = localpath;
                    System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(folderPath);
                     

                    if (di.Exists)
                        localpath += "\\" + args[0];
                    else if(!di.Parent.Exists)
                    {
                        Console.Error.WriteLine("Specified path does not exist, double check existance of the folders in the path");
                        return;
                    }

                }                     
                

                if (System.IO.File.Exists(localpath))
                {
                    if (QuietMode || !InteractiveMode)
                    {
                        Console.Error.WriteLine("The specified file already exists locally: {0}", localpath);
                        SetFailure();
                        return;
                    }
                    Console.Write("The specified file already exists locally; overwrite? ");
                    ConsoleFlush();
                    for (; ; )
                    {
                        string s = Console.ReadLine();
                        char ch = '\0';
                        if (0 != s.Length)
                        {
                            ch = char.ToUpper(s[0]);
                        }
                        if ('N' == ch)
                        {
                            Console.WriteLine("    Aborted by user");
                            return;
                        }
                        else if ('Y' == ch)
                        {
                            break; // !
                        }
                        else
                        {
                            Console.Write("Overwrite, yes or no? ");
                            ConsoleFlush();
                        }
                    }
                }

                const int MAX_SIZE_PER_RECEIVE = 0x400 * 64;
                byte[] fbuf = new byte[MAX_SIZE_PER_RECEIVE];

                dfs dc = LoadDfsConfig();

                dfs.DfsFile dfsf = DfsFindAny(dc, dfspath);
                if (null == dfsf)
                {
                    Console.Error.WriteLine("Error:  The specified file '{0}' does not exist in DFS", dfspath);
                    SetFailure();
                    return;
                }
                if (0 != string.Compare(dfsf.Type, DfsFileTypes.NORMAL, StringComparison.OrdinalIgnoreCase)
                    && 0 != string.Compare(dfsf.Type, DfsFileTypes.BINARY_RECT, StringComparison.OrdinalIgnoreCase))
                {
                    Console.Error.WriteLine("DFS file '{0}' is not of expected type", dfsf.Name);
                    SetFailure();
                    return;
                }
                bool warned = false;
                long curfilepos = 0;
               
               
                using (System.IO.FileStream _fs = new System.IO.FileStream(localpath, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write, System.IO.FileShare.Read, FILE_BUFFER_SIZE))
                {
                    System.IO.Stream fs = _fs;
                    /*if (localpath.EndsWith(".gz"))
                    {
                        //if (verbose)
                        {
                            Console.WriteLine("Warning:  GZip (.gz) does not suport files over 4 GB in size; use 'dfs getgzip' if large file support is ever needed");
                        }

                        fs = new System.IO.Compression.GZipStream(_fs, System.IO.Compression.CompressionMode.Compress);
                    }*/

                    bool hitlimit = false;
                    for (int dn = startparts; dn < dfsf.Nodes.Count; dn++)
                    {
                        if (dn > lastparts)
                        {
                            //if (verbose)
                            {
                                Console.WriteLine("    Done with partial get {0}-{1}", startparts, lastparts);
                            }
                            hitlimit = true;
                            break;
                        }
                        dfs.DfsFile.FileNode node = dfsf.Nodes[dn];
                        if (curfilepos != node.Position)
                        {
                            if (-1 != node.Position)
                            {
                                if (!warned)
                                {
                                    warned = true;
                                    if (startparts != 0)
                                    {
                                        LogOutput("1 or more parts of the file are not received.  Index of parts for this file starts from 0 to " + (dfsf.Nodes.Count - 1).ToString());
                                    }
                                    else
                                    {
                                        LogOutput("Warning: file positions do not line up; " + dfs.DFSXMLNAME + " or data-node chunks may be corrupted");
                                    }                                    
                                    //return;
                                }
                            }
                        }
                        using (System.IO.Stream _fc = new DfsFileNodeStream(node, true, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read, FILE_BUFFER_SIZE))
                        {
                            System.IO.Stream fc = _fc;
                            if (1 == dc.slave.CompressDfsChunks)
                            {
                                fc = new System.IO.Compression.GZipStream(_fc, System.IO.Compression.CompressionMode.Decompress);
                            }

                            {
                                int xread = StreamReadLoop(fc, fbuf, 4);
                                if (4 == xread)
                                {
                                    int hlen = MySpace.DataMining.DistributedObjects.Entry.BytesToInt(fbuf);
                                    StreamReadExact(fc, fbuf, hlen - 4);
                                }
                            }

                            for (; ; )
                            {
                                int xread = fc.Read(fbuf, 0, MAX_SIZE_PER_RECEIVE);
                                if (xread <= 0)
                                {
                                    break;
                                }
                                fs.Write(fbuf, 0, xread);
                                curfilepos += xread;
                            }

                            fc.Close();
                        }
                    }
                    if (!hitlimit)
                    {
                        if (curfilepos != dfsf.Size)
                        {
                            if (-1 != dfsf.Size)
                            {
                                if (!warned)
                                {
                                    warned = true;
                                    if (startparts != 0)
                                    {
                                        LogOutput("1 or more parts of the file are not received.  Index of parts for this file starts from 0 to " + (dfsf.Nodes.Count - 1).ToString());
                                    }
                                    else
                                    {
                                        LogOutput("Warning: file data received is not correct resulting size; " + dfs.DFSXMLNAME + " or data-node chunks may be corrupted");
                                    }
                                    //return;
                                }
                            }
                        }
                    }
                    fs.Close();

                    try
                    {
                        System.Security.Principal.NTAccount nt = new System.Security.Principal.NTAccount(userdomain, dousername);
                        System.Security.Principal.SecurityIdentifier secID = (System.Security.Principal.SecurityIdentifier)nt.Translate(typeof(System.Security.Principal.SecurityIdentifier));
                        System.Security.AccessControl.FileSystemAccessRule rule = new System.Security.AccessControl.FileSystemAccessRule(secID,
                            System.Security.AccessControl.FileSystemRights.FullControl,
                            System.Security.AccessControl.AccessControlType.Allow);
                        System.Security.AccessControl.FileSecurity fsec = new System.Security.AccessControl.FileSecurity();
                        fsec.AddAccessRule(rule);
                        System.IO.File.SetAccessControl(localpath, fsec);
                    }
                    catch(Exception e)
                    {
                        Console.Error.WriteLine("Error while assigning file permission to: {0}\\{1}", userdomain, dousername);
                        Console.Error.WriteLine(e.ToString());
                    }                    
                }
                Console.WriteLine("Received {0} bytes to file {1}", curfilepos, localpath);
            }
        }
예제 #6
0
파일: DFS.cs 프로젝트: erisonliang/qizmt
        static void _DfsGetPartsNoWildcard(string[] args, int startparts, int lastparts)
        {
            if (!dfs.DfsConfigExists(DFSXMLPATH))
            {
                Console.Error.WriteLine("DFS not setup; use:  {0} format", appname);
                SetFailure();
                return;
            }
            if (args.Length < 2)
            {
                Console.Error.WriteLine("dfs get error:  {0} dfs get <dfspath> <localpath>", appname);
                SetFailure();
                return;
            }

            string dfspath = args[0];
            if (dfspath.StartsWith("dfs://", StringComparison.OrdinalIgnoreCase))
            {
                dfspath = dfspath.Substring(6);
            }
            if (dfspath.Length == 0)
            {
                Console.Error.WriteLine("Invalid dfspath");
                SetFailure();
                return;
            }

            string localpath = args[1];

            //System.Threading.Thread.Sleep(8000);
            string localstartname = localpath;
            string localendname = "";
            { // Remove ext...
                int ildot = localstartname.LastIndexOf('.');
                if (-1 != ildot)
                {
                    bool anotherdotcheck = (localstartname.Length - ildot <= 4);
                    localstartname = localstartname.Substring(0, ildot);
                    if (anotherdotcheck)
                    {
                        ildot = localstartname.LastIndexOf('.');
                        if (-1 != ildot)
                        {
                            if (localstartname.Length - ildot <= 4)
                            {
                                localstartname = localstartname.Substring(0, ildot);
                            }
                        }
                    }
                }
            }
            localendname = localpath.Substring(localstartname.Length); // e.g. ".txt.gz"
            if (!localendname.EndsWith(".gz", StringComparison.OrdinalIgnoreCase))
            {
                localendname += ".gz";
            }
            localstartname += ".part";

            {
                string edir = ".";
                string efile = localstartname + "*" + localendname;
                {
                    int ilslash = efile.LastIndexOfAny(new char[] { '/', '\\' });
                    if (-1 != ilslash)
                    {
                        edir = efile.Substring(0, ilslash);
                        efile = efile.Substring(ilslash + 1);
                    }
                }
                string[] existparts = System.IO.Directory.GetFiles(edir, efile);
                if (existparts.Length != 0)
                {
                    /*
                    Console.Error.WriteLine("Abort: output files already exist");
                    SetFailure();
                    return;
                     * */
                    if (QuietMode || !InteractiveMode)
                    {
                        Console.Error.WriteLine("The specified file(s) already exists locally: {0}", localstartname + "*" + localendname);
                        SetFailure();
                        return;
                    }
                    Console.Write("The specified file(s) already exists locally; overwrite? ");
                    ConsoleFlush();
                    for (; ; )
                    {
                        string s = Console.ReadLine();
                        char ch = '\0';
                        if (0 != s.Length)
                        {
                            ch = char.ToUpper(s[0]);
                        }
                        if ('N' == ch)
                        {
                            Console.WriteLine("    Aborted by user");
                            return;
                        }
                        else if ('Y' == ch)
                        {
                            break; // !
                        }
                        else
                        {
                            Console.Write("Overwrite, yes or no? ");
                            ConsoleFlush();
                        }
                    }

                    // Delete them before writing; new output might have less part count.
                    for (int i = 0; i < existparts.Length; i++)
                    {
                        System.IO.File.Delete(existparts[i]);
                    }
                }
            }

            int ncpus = Surrogate.NumberOfProcessors;

            dfs dc = LoadDfsConfig();
            dfs.DfsFile df = DfsFind(dc, dfspath);
            if (null == df)
            {
                Console.Error.WriteLine("Error: File not found in DFS: {0}", dfspath);
                SetFailure();
                return;
            }

            Console.WriteLine("Getting GZip parts of DFS file '{1}'...", df.Nodes.Count, df.Name);

            List<System.Threading.Thread> threads = new List<System.Threading.Thread>(ncpus);
            GettingParts gp = new GettingParts();
            gp.dc = dc;
            //gp.parts = df.Nodes;
            gp.parts = new List<dfs.DfsFile.FileNode>();
            bool hitlimit = false;
            for (int dn = 0; dn < df.Nodes.Count; dn++)
            {
                if (dn > lastparts)
                {
                    hitlimit = true;
                    break;
                }
                gp.parts.Add(df.Nodes[dn]);
            }
            gp.nextpart = startparts;
            gp.localendname = localendname;
            gp.localstartname = localstartname;
            {
                System.Security.Principal.NTAccount nt = new System.Security.Principal.NTAccount(userdomain, dousername);
                System.Security.Principal.SecurityIdentifier secID = (System.Security.Principal.SecurityIdentifier)nt.Translate(typeof(System.Security.Principal.SecurityIdentifier));
                System.Security.AccessControl.FileSystemAccessRule rule = new System.Security.AccessControl.FileSystemAccessRule(secID,
                System.Security.AccessControl.FileSystemRights.FullControl,
                System.Security.AccessControl.AccessControlType.Allow);
                gp.rule = rule;
            }

            for (int i = 0; i < ncpus; i++)
            {
                System.Threading.Thread thd = new System.Threading.Thread(new System.Threading.ThreadStart(gp.threadproc));
                thd.Start();
                threads.Add(thd);
            }
            for (int i = 0; i < threads.Count; i++)
            {
                threads[i].Join();
            }
            //if (verbose)
            {
                if (hitlimit)
                {
                    Console.WriteLine("Done with partial get {0}-{1}", startparts, lastparts);
                }
                else
                {
                    Console.WriteLine("Done");
                }
            }
            Console.WriteLine("Files written to '{0}N{1}'", localstartname, localendname);

        }
 public void AclUser() {
     var account = new System.Security.Principal.NTAccount(Environment.UserName);
     Assert.That(account.ToString().Contains(Environment.UserName));
     Assert.That(account.IsValidTargetType(typeof(System.Security.Principal.SecurityIdentifier)));
     var securityAccount = account.Translate(typeof(System.Security.Principal.SecurityIdentifier)) as System.Security.Principal.SecurityIdentifier;
     Assert.That(securityAccount.IsAccountSid(), Is.True);
 }
예제 #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);
            });
        }
예제 #9
0
        public static IEnumerable <string> ConvertTo_SID(Args_ConvertTo_SID args = null)
        {
            if (args == null)
            {
                args = new Args_ConvertTo_SID();
            }

            var DomainSearcherArguments = new Args_Get_DomainObject
            {
                Domain     = args.Domain,
                Server     = args.Server,
                Credential = args.Credential
            };

            var SIDs = new List <string>();

            foreach (var item in args.ObjectName)
            {
                var name = item.Replace(@"/", @"\");

                if (args.Credential != null)
                {
                    var DN = ConvertADName.Convert_ADName(new Args_Convert_ADName
                    {
                        Identity   = new[] { name },
                        OutputType = ADSNameType.DN,
                        Domain     = DomainSearcherArguments.Domain,
                        Server     = DomainSearcherArguments.Server,
                        Credential = DomainSearcherArguments.Credential
                    });


                    if (DN != null)
                    {
                        var UserDomain = DN.First().Substring(DN.First().IndexOf(@"DC=")).Replace(@"DC=", @"").Replace(@",", @".");
                        var UserName   = DN.First().Split(',')[0].Split('=')[1];

                        DomainSearcherArguments.Identity   = new[] { UserName };
                        DomainSearcherArguments.Domain     = UserDomain;
                        DomainSearcherArguments.Properties = new[] { @"objectsid" };
                        var obj = GetDomainObject.Get_DomainObject(DomainSearcherArguments);
                        foreach (LDAPProperty ldapProperty in obj)
                        {
                            SIDs.AddRange(ldapProperty.objectsid);
                        }
                    }
                }
                else
                {
                    try
                    {
                        if (name.Contains(@"\"))
                        {
                            args.Domain = name.Split('\\')[0];
                            name        = name.Split('\\')[1];
                        }
                        else if (args.Domain.IsNullOrEmpty())
                        {
                            args.Domain = GetDomain.Get_Domain().Name;
                        }

                        var obj = new System.Security.Principal.NTAccount(args.Domain, name);
                        SIDs.Add(obj.Translate(typeof(System.Security.Principal.SecurityIdentifier)).Value);
                    }
                    catch (Exception e)
                    {
                        Logger.Write_Verbose($@"[ConvertTo-SID] Error converting {args.Domain}\{name} : {e}");
                    }
                }
            }
            return(SIDs);
        }