?
Solved

Identify the windows console type : Normal user or runas window

Posted on 2009-04-30
13
Medium Priority
?
233 Views
Last Modified: 2012-05-06
Hi,

Could anyone please tell me if there is a way to find out the type of console window from where user is running the application. Basically, I want to differentiate between normal console window (cmd.exe) and runas console window (runas /usr:username cmd.exe).

Is there any environment, registry or anything that indicate the current console window is runas console?

I am not sure what are the zones this question eligible for.

Thanks.
0
Comment
Question by:deshaw
  • 8
  • 5
13 Comments
 
LVL 5

Accepted Solution

by:
drilus earned 2000 total points
ID: 24272080
You can do this by finding the token for the current running process. I haven't attempted this in C# but I have done it in Delphi.

Here is a link I found where someone else was having this same problem. Hope it helps.

http://www.sellsbrothers.com/askthewonk/Secure/HowcanIgetthesecurityprin.htm
0
 
LVL 1

Author Comment

by:deshaw
ID: 24276924
I know using token but there are so many problems with that approach. The token can be generated only in System account but my actuall application is running as normal user. I can also make the token generated process in System using psexe.exe and createprocess but those changes required Admin privileges. So definately generating token is not going to work/not efficient solution for me.
Please let me know if there is any other example you have such as getting parent process(because normal window will have cmd parent and runas window will have runas process parent). I think it also possible with WMI using but I dont know how to do that. If you have any example then it would be great.
Thanks.
0
 
LVL 1

Author Comment

by:deshaw
ID: 24277203
I found the way to do this but it is not strong way. I could see for the parent windows title and look for the "running as" string. If Parent windows Title contain "running as" then that window is runas console else not. Could any one suggest strong solution on this.
Thanks.

[DllImport("KERNEL32.dll")]
  public static extern int CreateToolhelp32Snapshot(uint flags, uint processid);
 
  [DllImport("KERNEL32.DLL")]
  public static extern int CloseHandle(int handle);
 
  [DllImport("KERNEL32.DLL")]
  public static extern int Process32Next(int handle, ref ProcessEntry32 pe);
 
  [StructLayout(LayoutKind.Sequential)]
  public struct ProcessEntry32
  {
      public uint dwSize;
      public uint cntUsage;
      public uint th32ProcessID;
      public IntPtr th32DefaultHeapID;
      public uint th32ModuleID;
      public uint cntThreads;
      public uint th32ParentProcessID;
      public int pcPriClassBase;
      public uint dwFlags;
      [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
      public string szExeFile;
  };
 
    public static void FindParentProcess()
    {
        int SnapShot = CreateToolhelp32Snapshot(0x00000002, 0); //2 = SNAPSHOT of all procs 
        try
        {
            ProcessEntry32 pe32 = new ProcessEntry32();
            pe32.dwSize = 296;
            int procid = System.Diagnostics.Process.GetCurrentProcess().Id;
            Console.WriteLine("Current Process: " + System.Diagnostics.Process.GetCurrentProcess().ProcessName.ToString());
            while (Process32Next(SnapShot, ref pe32) != 0)
            {
                string xname = pe32.szExeFile.ToString();
                if (procid == pe32.th32ProcessID)
                {
                    Process pProcess = System.Diagnostics.Process.GetProcessById(Convert.ToInt32(pe32.th32ParentProcessID));
                    Console.WriteLine("Parent Process: " + pProcess.ProcessName.ToString());
                    if (pProcess.MainWindowTitle.ToString().ToLower().IndexOf("running as") > -1)
                    {
                        Console.WriteLine("The parent window is runas console");
                    }
                    else
                    {
                        Console.WriteLine("The parent window isn't runas console");
                    }
                }
            }
 
        }
        catch (Exception ex)
        {
           Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod() + " failed! [Type:" + ex.GetType().ToString() + ", Msg:" + ex.Message + "]");
        }
        finally
        {
            CloseHandle(SnapShot);
        }        
    }

Open in new window

0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 5

Expert Comment

by:drilus
ID: 24278761
I have done this through WMI only in Delphi. My code is not ported as I'm new to C#.

I used Win32_Process and called GetOwner.

I have found another article on WMI and GetOwner in C#. Hope it works for you.

http://objectmix.com/csharp/349324-c-win32_process-getowner-remote-machine.html
0
 
LVL 5

Expert Comment

by:drilus
ID: 24278793
It looks like you can also you the "LookupAccountSid" API which might be easier than using WMI.
0
 
LVL 1

Author Comment

by:deshaw
ID: 24279011
"GetOwner" method will not work because  if user do run as himself then owner of proces will be that user only. In this case we cannot detect whether the window from he is executing process is normal command winow or runas window. See below I did runas my self in two windows but all SIDs and Owner are same so no one solution would work.
 I got this program from http://www.sellsbrothers.com/askthewonk/Secure/HowcanIgetthesecurityprin.htm. I am printing SIDs as well.

C:\>EnumProcessIdentities.exe
cmd running under XXX : S-1-5-21-40860068-2010480466-677931608-49469
cmd running under XXX : S-1-5-21-40860068-2010480466-677931608-49469
cmd running under XXX : S-1-5-21-40860068-2010480466-677931608-49469


0
 
LVL 1

Author Comment

by:deshaw
ID: 24279189
One thing we can do here is ignore the case where same user will do runas as him self then we can identify by comparing logged on user and runas user. If they are not same that means it is a runas window console. Is there any simple method to get logged on user? The runas user we can get using Environment.Username.
Thanks.
0
 
LVL 1

Author Comment

by:deshaw
ID: 24279485
Thanks for being there.
I found the solution. Putting for someone else as a reference.

RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon");
string loginUser = registryKey.GetValue("DefaultUserName").ToString().ToLower();
if (!loginUser.Equals(Environment.UserName.ToLower()))
{
Console.WriteLine("This is run as window");
return;
}
0
 
LVL 1

Author Closing Comment

by:deshaw
ID: 31576437
Your solution was correct and hence accepting. Thanks.
0
 
LVL 5

Expert Comment

by:drilus
ID: 24279556

using System.Security.Principal;
 
 
string a;
a = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
 
MessageBox.Show(a.ToString());

Open in new window

0
 
LVL 1

Author Comment

by:deshaw
ID: 24279626
FYI, System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString() wil return the current environment user and it will be same as "Environment.UserDomainName + "\\" + Environment.Username" but logged on user will be different.
0
 
LVL 5

Expert Comment

by:drilus
ID: 24280180
When I run the code as a different user using RunAs it reports the user account running the program. Not the system account.
0
 
LVL 1

Author Comment

by:deshaw
ID: 24280219
correct that what I am telling.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Integration Management Part 2
Loops Section Overview
Suggested Courses

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question