Click here to Skip to main content
14,666,876 members
Home » Discussions » .NET (Core and Framework)
   

.NET (Core and Framework)

 
Questionis not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides Pin
indian14329-Aug-17 13:41
Memberindian14329-Aug-17 13:41 
GeneralRe: is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides Pin
PIEBALDconsult29-Aug-17 13:49
professionalPIEBALDconsult29-Aug-17 13:49 
AnswerRe: is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides Pin
Richard MacCutchan29-Aug-17 20:52
mveRichard MacCutchan29-Aug-17 20:52 
Questionpie chart report in vb.net Pin
Member 1338013327-Aug-17 1:21
MemberMember 1338013327-Aug-17 1:21 
AnswerRe: pie chart report in vb.net Pin
debasish mishra23-Jan-18 20:38
professionaldebasish mishra23-Jan-18 20:38 
QuestionGUI from CreateProcessWithTokenW does not show up Pin
gobbo-dd16-Aug-17 7:27
Membergobbo-dd16-Aug-17 7:27 
AnswerRe: GUI from CreateProcessWithTokenW does not show up Pin
Dave Kreskowiak16-Aug-17 12:56
mveDave Kreskowiak16-Aug-17 12:56 
GeneralRe: GUI from CreateProcessWithTokenW does not show up Pin
gobbo-dd16-Aug-17 20:12
Membergobbo-dd16-Aug-17 20:12 
Hi,

mea culpa.
The code is as follows

public class MyRunAs
    {
        [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        internal static extern bool CreateProcessWithTokenW(
            IntPtr dupeTokenHandle,
            LogonFlags dwLogonFlags,  
            string applicationName,
            string commandLine,
            CreationFlags dwCreationFlags, 
            IntPtr environment,
            string currentDirectory,
            ref STARTUPINFO sui,
            out PROCESS_INFORMATION processInfo);

        [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        internal static extern bool DuplicateTokenEx(IntPtr tokenHandle, int
        dwDesiredAccess,
        ref SECURITY_ATTRIBUTES lpTokenAttributes, int
        SECURITY_IMPERSONATION_LEVEL,
        int TOKEN_TYPE, ref IntPtr dupeTokenHandle);

        [DllImport("userenv.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        private static extern bool CreateEnvironmentBlock(
         ref IntPtr lpEnvironment,
         IntPtr hToken,
         bool bInherit);

        [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        static extern bool CreateProcessAsUser(
             IntPtr Token,
             [MarshalAs(UnmanagedType.LPTStr)] string ApplicationName,
             [MarshalAs(UnmanagedType.LPTStr)] string CommandLine,
             ref SECURITY_ATTRIBUTES ProcessAttributes,
             ref SECURITY_ATTRIBUTES ThreadAttributes,
             bool InheritHandles,
             CreationFlags dwCreationFlags,
             IntPtr Environment,
             [MarshalAs(UnmanagedType.LPTStr)] string CurrentDirectory,
             ref STARTUPINFO StartupInfo,
             out PROCESS_INFORMATION ProcessInformation);


        [StructLayout(LayoutKind.Sequential)]
        internal struct SECURITY_ATTRIBUTES
        {
            internal int nLength;
            internal int lpSecurityDescriptor;
            internal bool bInheritHandle;

        }

        public enum CreationFlags
        {
            DefaultErrorMode = 0x04000000,
            NewConsole = 0x00000010,
            NewProcessGroup = 0x00000200,
            SeparateWOWVDM = 0x00000800,
            Suspended = 0x00000004,
            UnicodeEnvironment = 0x00000400,
            ExtendedStartupInfoPresent = 0x00080000
        }

        public enum LogonFlags
        {
            WithProfile = 1,
            NetCredentialsOnly
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct STARTUPINFO
        {
            internal int cb;
            [MarshalAs(UnmanagedType.LPTStr)]
            internal string lpReserved;
            [MarshalAs(UnmanagedType.LPTStr)]
            internal string lpDesktop;
            [MarshalAs(UnmanagedType.LPTStr)]
            internal string lpTitle;
            internal int dwX;
            internal int dwY;
            internal int dwXSize;
            internal int dwYSize;
            internal int dwXCountChars;
            internal int dwYCountChars;
            internal int dwFillAttribute;
            internal int dwFlags;
            internal short wShowWindow;
            internal short cbReserved2;
            internal IntPtr lpReserved2;
            internal IntPtr hStdInput;
            internal IntPtr hStdOutput;
            internal IntPtr hStdError;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct PROCESS_INFORMATION
        {
            internal IntPtr hProcess;
            internal IntPtr hThread;
            internal int dwProcessId;
            internal int dwThreadId;
        }

        // SECURITY_IMPERSONATION_LEVEL
        const int SecurityAnonymous = 0;
        const int SecurityIdentification = 1;
        const int SecurityImpersonation = 2;
        const int SecurityDelegation = 3;

        // TOKEN_TYPE
        const int TokenPrimary = 1;
        const int TokenImpersonation = 2;

        //dwLogonFlags Specifies the logon option
        const int LOGON_WITH_PROFILE = 1;
        const int LOGON_NETCREDENTIALS_ONLY = 2;

        // Access Token constants
        private const int TOKEN_QUERY = 0x0008;
        private const int TOKEN_DUPLICATE = 0x0002;
        private const int TOKEN_ASSIGN_PRIMARY = 0x0001;
        private const int STARTF_USESHOWWINDOW = 0x00000001;
        private const int STARTF_FORCEONFEEDBACK = 0x00000040;
        private const int CREATE_UNICODE_ENVIRONMENT = 0x00000400;
        private const int TOKEN_IMPERSONATE = 0x0004;
        private const int TOKEN_QUERY_SOURCE = 0x0010;
        private const int TOKEN_ADJUST_PRIVILEGES = 0x0020;
        private const int TOKEN_ADJUST_GROUPS = 0x0040;
        private const int TOKEN_ADJUST_DEFAULT = 0x0080;
        private const int TOKEN_ADJUST_SESSIONID = 0x0100;
        private const int STANDARD_RIGHTS_REQUIRED = 0x000F0000;
        private const int TOKEN_ALL_ACCESS =
            STANDARD_RIGHTS_REQUIRED |
            TOKEN_ASSIGN_PRIMARY |
            TOKEN_DUPLICATE |
            TOKEN_IMPERSONATE |
            TOKEN_QUERY |
            TOKEN_QUERY_SOURCE |
            TOKEN_ADJUST_PRIVILEGES |
            TOKEN_ADJUST_GROUPS |
            TOKEN_ADJUST_DEFAULT |
            TOKEN_ADJUST_SESSIONID;

        public static bool CreateTokenChild()
        {
                    
            try {
                
                
                STARTUPINFO startInfo = new STARTUPINFO();
                startInfo.cb = Marshal.SizeOf(startInfo);
                // not needed ?!
                // startInfo.lpDesktop = @"winsta0\default"; 

                // Create Process with token
                IntPtr dupeTokenHandle = IntPtr.Zero;
                // IntPtr tokenHandle = WindowsIdentity.GetCurrent().Token;

                // get impersonation token
                // we can do that since the owner of this thread 
                // has "act as part of operating system" priviledge
                // use UPN of target user
                WindowsIdentity id = new WindowsIdentity("user@domain");
                IntPtr tokenHandle = id.Token;
                
                // Setting security attributes
                SECURITY_ATTRIBUTES lpTokenAttributes = new SECURITY_ATTRIBUTES();
                lpTokenAttributes.nLength = Marshal.SizeOf(lpTokenAttributes);

                // SECURITY_ATTRIBUTES threadAttributes = new SECURITY_ATTRIBUTES();
                // threadAttributes.nLength = Marshal.SizeOf(lpTokenAttributes);

                // get primary token for user to be impersonated to
                bool retVal = DuplicateTokenEx(
                    tokenHandle,
                    TOKEN_ALL_ACCESS, 
                    ref lpTokenAttributes, 
                    SecurityImpersonation, 
                    TokenPrimary, 
                    ref dupeTokenHandle);

                if (!retVal)
                {
                    int winError = Marshal.GetLastWin32Error();
                    File.AppendAllText("C:\\tmp\\out.log", DateTime.Now.ToLongTimeString() + " " + winError + Environment.NewLine);

                    return false;
                }

                // app to be started
                string app = @"c:\Windows\System32\notepad.exe";
                // command line arguments
                string cmd = null;
                // startup path
                string spath = @"C:\";

                // create environment for user to be impersonated to
                IntPtr env = GetEnvironmentBlock(dupeTokenHandle);

                // the process to be created
                PROCESS_INFORMATION processInfo;

                bool ret = CreateProcessWithTokenW(
                    dupeTokenHandle,
                    LogonFlags.WithProfile,
                    app,
                    cmd,
                    CreationFlags.UnicodeEnvironment,
                    env,
                    spath,
                    ref startInfo, 
                    out processInfo);
                
                /*bool ret = CreateProcessAsUser(dupeTokenHandle, spot, cmd, ref lpTokenAttributes, ref threadAttributes, true,
                    CreationFlags.UnicodeEnvironment, env, "C:\\", ref startInfo, out processInfo);
                    */

                if (!ret)
                {
                    int winError = Marshal.GetLastWin32Error();
                    File.AppendAllText("C:\\tmp\\out.log", DateTime.Now.ToLongTimeString() + " error: " + winError + Environment.NewLine);

                    return false;
                }                
                else
                {
                    File.AppendAllText("C:\\tmp\\out.log", DateTime.Now.ToLongTimeString() + " success " + Environment.NewLine);
                }               

            }

            catch (Exception e)
            {
                return false ;
            }
            finally
            {
                // TODO
                // close handles
            }
            return true;
                        
        }

        private static IntPtr GetEnvironmentBlock(IntPtr token)
        {
            var envBlock = IntPtr.Zero;
            if (!CreateEnvironmentBlock(ref envBlock, token, false))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error(), "CreateEnvironmentBlock failed");
            }
            return envBlock;
        }

    }


Sorry for that lack of information. I somehow thought, its not code related but rather some security issue. I compared two processes with process explorer and the only thing that I realized was that "normal" processes have security attribute "NT AUTHORITY\INTERACTIVE" which the process I am starting has not ...

I also tried CreateProcessAsUser and it shows exactly the same behavior ...

Cheers and thanks.
Guido
GeneralRe: GUI from CreateProcessWithTokenW does not show up Pin
Dave Kreskowiak17-Aug-17 4:58
mveDave Kreskowiak17-Aug-17 4:58 
GeneralRe: GUI from CreateProcessWithTokenW does not show up Pin
Eddy Vluggen17-Aug-17 7:46
professionalEddy Vluggen17-Aug-17 7:46 
GeneralRe: GUI from CreateProcessWithTokenW does not show up Pin
gobbo-dd17-Aug-17 9:14
Membergobbo-dd17-Aug-17 9:14 
GeneralRe: GUI from CreateProcessWithTokenW does not show up Pin
Eddy Vluggen17-Aug-17 11:24
professionalEddy Vluggen17-Aug-17 11:24 
GeneralRe: GUI from CreateProcessWithTokenW does not show up Pin
gobbo-dd21-Aug-17 0:07
Membergobbo-dd21-Aug-17 0:07 
GeneralRe: GUI from CreateProcessWithTokenW does not show up Pin
Eddy Vluggen21-Aug-17 5:04
professionalEddy Vluggen21-Aug-17 5:04 
GeneralRe: GUI from CreateProcessWithTokenW does not show up Pin
gobbo-dd21-Aug-17 21:56
Membergobbo-dd21-Aug-17 21:56 
GeneralRe: GUI from CreateProcessWithTokenW does not show up Pin
Eddy Vluggen22-Aug-17 3:56
professionalEddy Vluggen22-Aug-17 3:56 
GeneralRe: GUI from CreateProcessWithTokenW does not show up Pin
gobbo-dd22-Aug-17 22:50
Membergobbo-dd22-Aug-17 22:50 
GeneralRe: GUI from CreateProcessWithTokenW does not show up Pin
Eddy Vluggen23-Aug-17 0:00
professionalEddy Vluggen23-Aug-17 0:00 
GeneralRe: GUI from CreateProcessWithTokenW does not show up Pin
Dave Kreskowiak24-Aug-17 4:21
mveDave Kreskowiak24-Aug-17 4:21 
QuestionError in Panel AutoScroll after rotating a Picturebox within that Panel in VB.Net Pin
Member 90509857-Aug-17 11:59
MemberMember 90509857-Aug-17 11:59 
AnswerRe: Error in Panel AutoScroll after rotating a Picturebox within that Panel in VB.Net Pin
Alan N7-Aug-17 12:47
MemberAlan N7-Aug-17 12:47 
QuestionBest practice connecting to database Pin
A_Griffin5-Aug-17 23:58
MemberA_Griffin5-Aug-17 23:58 
AnswerRe: Best practice connecting to database Pin
Eddy Vluggen6-Aug-17 0:44
professionalEddy Vluggen6-Aug-17 0:44 
GeneralRe: Best practice connecting to database Pin
A_Griffin6-Aug-17 0:55
MemberA_Griffin6-Aug-17 0:55 
GeneralRe: Best practice connecting to database Pin
Eddy Vluggen6-Aug-17 1:06
professionalEddy Vluggen6-Aug-17 1:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.