Click here to Skip to main content
15,884,298 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I had popup a UI using win32 api creaprocessasuser. It works as I use admin user login. but it give two exception
1. unhandled exception (in event handler)as a normal user try to launch pop UI.

Description: The process was terminated due to an unhandled exception.
Exception Info: System.ObjectDisposedException
at System.Windows.Forms.Control.CreateHandle()
at System.Windows.Forms.Form.CreateHandle()
at System.Windows.Forms.Control.get_Handle()
at System.Windows.Forms.ContainerControl.FocusActiveControlInternal()
at System.Windows.Forms.Form.SetVisibleCore(Boolean)
at System.Windows.Forms.Control.set_Visible(Boolean)
at System.Windows.Forms.Application+ThreadContext.RunMessageLoopInner(Int32, System.Windows.Forms.ApplicationContext)
at System.Windows.Forms.Application+ThreadContext.RunMessageLoop(Int32, System.Windows.Forms.ApplicationContext)
at System.Windows.Forms.Application.Run(System.Windows.Forms.Form)
at WinFormPrintDriverApp.Program.Main(System.String[])


Faulting application name: myapplication.exe, version: 1.0.0.0, time stamp: 0xab4b49da
Faulting module name: KERNELBASE.dll, version: 6.3.9600.19671, time stamp: 0x5e67335c
Exception code: 0xe0434352
Fault offset: 0x00013d28
Faulting process id: 0x1d84
Faulting application start time: 0x01d77a36c724e6f6
Faulting application path: c:\testpath\myapplication.exe
Faulting module path: C:\Windows\SYSTEM32\KERNELBASE.dll
Report Id: 0ae714c2-e62a-11eb-8106-0050568ffd89
Faulting package full name:
Faulting package-relative application ID:


what might be issue? Any help appreciated to resolve this issue.

What I have tried:

my code:
C#
  1  public static bool StartProcessAsCurrentUser(string appPath, string cmdLine, string currentUserName, string workDir = null, bool visible = true)
  2  {
  3      var hUserToken = IntPtr.Zero;
  4      var startInfo = new STARTUPINFO();
  5      var procInfo = new PROCESS_INFORMATION();
  6      var pEnv = IntPtr.Zero;
  7      int iResultOfCreateProcessAsUser;
  8  
  9      startInfo.cb = Marshal.SizeOf(typeof(STARTUPINFO));
 10        
 11      try
 12      {
 13          if (!GetSessionUserToken(ref hUserToken, currentUserName))
 14          {
 15              throw new Exception("StartProcessAsCurrentUser: GetSessionUserToken failed.");
 16          }
 17          uint dwCreationFlags = CREATE_UNICODE_ENVIRONMENT | (uint)(visible ? CREATE_NEW_CONSOLE : CREATE_NO_WINDOW);
 18          startInfo.wShowWindow = (short)(visible ? SW.SW_SHOW : SW.SW_HIDE);
 19          startInfo.lpDesktop = "winsta0\\default";
 20              
 21          if (!CreateEnvironmentBlock(ref pEnv, hUserToken, false))
 22          {
 23              throw new Exception("StartProcessAsCurrentUser: CreateEnvironmentBlock failed.");
 24          }
 25              
 26          if (!CreateProcessAsUser(hUserToken,
 27               appPath, // Application Name
 28               cmdLine, // Command Line
 29               IntPtr.Zero,
 30               IntPtr.Zero,
 31               false,
 32               dwCreationFlags,
 33               pEnv,
 34               workDir, // Working directory
 35               ref startInfo,
 36               out procInfo))
 37          {
 38              iResultOfCreateProcessAsUser = Marshal.GetLastWin32Error();
 39              throw new Exception("StartProcessAsCurrentUser: CreateProcessAsUser failed.  Error Code -" + iResultOfCreateProcessAsUser);
 40          }
 41          iResultOfCreateProcessAsUser = Marshal.GetLastWin32Error();
 42      }
 43      catch(Exception ex)
 44      { 
 45          log.Info("StartProcessAsCurrentUser exeption msg:"+ex.Message +" stacktrace:"+ex.StackTrace); 
 46      }
 47      finally
 48      {
 49          CloseHandle(hUserToken);
 50          if (pEnv != IntPtr.Zero)
 51          {
 52              DestroyEnvironmentBlock(pEnv);
 53          }
 54          CloseHandle(procInfo.hThread);
 55          CloseHandle(procInfo.hProcess);
 56      }
 57      return true;
 58  }
 59  }
 60  
 61  private static bool GetSessionUserToken(ref IntPtr phUserToken, string currentUserName)
 62  {
 63      var bResult = false;
 64      var hImpersonationToken = IntPtr.Zero;
 65      var activeSessionId = INVALID_SESSION_ID;
 66      try
 67      {
 68          ITerminalServicesManager manager = new TerminalServicesManager();
 69          using (ITerminalServer server = manager.GetLocalServer())
 70          {
 71              server.Open();
 72              foreach (ITerminalServicesSession session in server.GetSessions())
 73              {
 74                  if (session.UserName.ToUpper() == currentUserName.ToUpper())
 75                  {
 76                      activeSessionId = (uint)session.SessionId;
 77                      break;
 78                  }
 79              }
 80          }
 81  
 82          // If enumerating did not work, fall back to the old method
 83          if (activeSessionId == INVALID_SESSION_ID)
 84          {
 85              activeSessionId = WTSGetActiveConsoleSessionId();
 86          }
 87          log.Info("Method GetSessionUserToken:  activeSessionId:" + activeSessionId);
 88          if (WTSQueryUserToken(activeSessionId, ref hImpersonationToken) != 0)
 89          {
 90              // Convert the impersonation token to a primary token
 91              bResult = DuplicateTokenEx(hImpersonationToken, 0, IntPtr.Zero,
 92                  (int)SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, (int)TOKEN_TYPE.TokenPrimary, ref phUserToken);
 93              CloseHandle(hImpersonationToken);
 94          }
 95          log.Info("GetSessionUserToken ends.");
 96      }
 97      catch(Exception ex)
 98      {
 99          log.Info("GetSessionUserToken exception:." + ex.Message);
100      }
101      
102      return bResult;
103  }
Posted
Updated 29-Jul-21 4:50am
v2
Comments
Dave Kreskowiak 29-Jul-21 15:48pm    
Your question isn't really clear. Is the code you posted running under an admin account? Is the code running elevated?
Member 14770565 30-Jul-21 1:14am    
service is running under local system account. Service code is run under admin account. After deployment if standard user try to launch pop up(UI) then exception occurred
Dave Kreskowiak 30-Jul-21 9:46am    
service is running under local system account.
Service code is run under admin account.
These are contradictory things. You cannot have the same code running under multiple accounts at the same time.

The problem seems to be you're trying to launch a process from the service, running as LocalSystem, as the logged in user on their Desktop.

Correct?
Member 14770565 30-Jul-21 10:41am    
Yes. This is right scenario. Why it give exception while standard user run application but it run successfully as admin user run the application.
Dave Kreskowiak 30-Jul-21 11:39am    
I found where you lifted the code from. You might want to ask the person who wrote it.

Keep in mind that what you're attempting to do is a large security risk. MS can patch this out at any time and your code no longer works.

A better method would be instead of having the service create the process, the service can send commands to a process running started at user login, already running as the user. This app and the service can communicate through a named pipe. The service can send commands to the user process through the pipe and tell the user process to launch an application, which it can easily do without having to jump through the flaming hoops of manually managing security tokens.

1 solution

We can't tell - it needs you app running in your system with your data, and we don't have access to any of those.

So, it's going to be up to you.
Fortunately, you have a tool available to you which will help you find out what is going on: the debugger. If you don't know how to use it then a quick Google for "Visual Studio debugger" should give you the info you need.

Put a breakpoint on the first line in the function, and run your code through the debugger. Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why.

Sorry, but we can't do that for you - time for you to learn a new (and very, very useful) skill: debugging!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900