how to get under which username a process running - c#

its very irritating, i found a code sample to get username from stackoverflow on how to get under which username a process running and its working fine in console app but not working in windows service. returnVal is 2 and not showing username and domain. Can anyone tell me do i need to change any setting in windows service.

Try running the service under an account that has enough privileges to call GetOwner().

I believe that what you're after is simply:
string user = Environment.UserName;
The service itself is running using some system account but you said you're looking for your own account name, meaning the logged in user account.

Related

Reading Win7 current logged username in web application

I had been stuck with the problem and research for it for few days but to no avail.
I'm working on a c# project and my program will automactically read the username from the user's windows whenever the user try to access the web application through the internet.
I tried with the following commands below and it works when I'm debugging the program/ running from localhost in the server. It managed to grab my username from windows and appear on the application.
(HttpContext.Current.User.Identity.Name);
(System.Environment.UserName);
(WindowsIdentity.GetCurrent().Name);
(Page.User.Identity.Name);
(System.Security.Principal.WindowsIdentity.GetCurrent().Name);
However, they did not work when I publish it and tried to access them from the web.
Instead, it gives me the following ID which I suspect is from the IIS7/ windows server 2008 that I host my site at. Rather than giving me the username from the user's console.
-there is no value-
-it gives me my server name
NTAUTHORITY\NETWORKSERVICE
-there is no value-
NTAUTHORITY\NETWORKSERVICE
May I know what went wrong in this case?
Another thing, through my research, I learnt how to get the username/ userdomain through the cmd.exe with commands below.
echo %username%
set username
wmic useraccount where name=%username% get name
wmic useraccount where name=%username% get sid
whoami
whoami/user
May I know if it's possible to apply these commands in windows visual studio for me to read the username from the user'windows when they access my webpage?
So, I hope I can get some advice from the users from this community. Thank you!
I solved the problem already.
Problem lies in the IIS. I checked against the authentication method and turned off everything except windows. From there, I checked against the web.config and ensure that the is turned to "false".
I also used HttpContext.Current.User.Identity.Name to get the username from the user's console.

Finding users' HOMEPATHs from a service

In the process of writing a service I have
//# Service Account Information
serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
in the installer for it.
I was having problems writing a log to
static string USERS_HOME_DIR = Environment.GetEnvironmentVariable("HOMEDRIVE") + Environment.GetEnvironmentVariable("HOMEPATH");
since when the service was running (installed "as administrator") the event logger was reporting
Service cannot be started. System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Documents\Folder of Interest'
I need the HOMEPATHs of the users of the local_PC, any ideas how to get them?
UPDATE
Actually it would be better to just get the path for the currently logged on user, as their session and the service start. My sevice is not re-entrant but one user is better than none.
If I understand your question correctly what you're looking for are the special folder enumerations.
With something like:
String PersonalFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
If you want to run the service as the localsystem account there's a separate set of standards for storing the data. See this answer on serverfault.

Get current user name when starting with UAC

Our setup has an embedded manifest that triggers the UAC before the application starts. (The applications runs as an admin user). However, if the setup needs to install the .NET Framework, we have to continue the setup after a reboot. For this reason, we have to create a registry key in the current user's RunOnce.
Unfortunatly, HKEY_CURRENT_USER points to the Administrator's registry. We need to find out the user that is currently logged in and started the installation. (Th normal USER clicked the setup.exe, an ADMIN entered his details in the UAC prompt. We need to find out who the USER was)
I've tried all the usual methods (Environment.UserName, WindowsIdentity.GetCurrent())
Thanks!
You can use the LsaEnumerateLogonSessions function to retreive what you need. However, it is a winapi C function call. If you need a managed version of it, I belive you can look at the source code for Cassia, which uses this function in its terminal services API. The call should be the same. You can also look here.
Also you can use the NetWkstaUserEnum WINAPI function. You can find a managed wrapper for it here
With Cassia library this code works fine:
ITerminalServicesManager manager = new TerminalServicesManager();
ITerminalServicesSession session = manager.CurrentSession;
string userInfo = session.DomainName + "\\" + session.UserName;
NTAccount account = session.UserAccount;
Run your initial setup.exe as a small executable that puts up a splash screen while invoking your real setup program as a child process. The small EXE is not run as admin and can pass the logged in user name to the child process. The child process invokes UAC and runs in the admin context but already has the logged in username as a command line parameter.
It is not possible to retrieve the original user if your application is ran as Administrator:
If a user launches Setup by right-clicking its EXE file and selecting
"Run as administrator", then this flag, unfortunately, will have no
effect, because Setup has no opportunity to run any code with the
original user credentials. The same is true if Setup is launched from
an already-elevated process. Note, however, that this is not an Inno
Setup-specific limitation; Windows Installer-based installers cannot
return to the original user credentials either in such cases.
Source : InnoSetup Help
As said by Matthew in comments, you should not run your application as Administrator but only trigger UAC when needed in your code.
This returns the name of the logged in Windows User by stripping out the domain:
using System.Security.Principal; // here is the security namespace you need
...
string userName = WindowsIdentity.GetCurrent().Name.Replace("\\", "|");
string[] split = userName.Split(new Char[] { '|' });
lblDebug.Text = (split.Count() > 1) ? split[1] : userName;

CreateProcessAsUser() not showing CreateWindow of running Process [C#]

My system has 2 accounts (USER and ADMIN) and a service (Service.exe) running under LocalSystem.
The user logs into the USER account, the LocalService can then launch a process (CreateProcessAsUser(...)) as the ADMIN user.
The process the Service runs (Tool.exe) is a legacy C++ application that performs a job and also displays information to the user by using CreateWindow(...), but when launching it by the Service the Window does not show...
When the process is created by the Service I first load the Profile & Environment of the ADMIN user so that the correct context is used ...
(was still hoping the Window would display to USER)
Now, initialy I thought this would cause a problem as ADMIN is running the process so why would the CreateWindow(...) output in the USER desktop, so I tried with a simple command-line test.exe app and when launched as ADMIN the Command Prompt window appeared - so why does that work fine where-as the CreateWindow(...) doesn't display correctly?
Any clues on how I can get the STATUS (using CreateWindow in Tool.exe) running under ADMIN to show in the USER logged-on session?
Can I use the ENVIRONMENT somehow, I tried the following thinking it might work but didn't:
startInfo.lpDesktop = #"WinSta0\Default";
startInfo.dwFlags = STARTF_USESHOWWINDOW;
startInfo.wShowWindow = SW_SHOW;
The Window is created as follows (in Tool.exe):
HWND hwnd = CreateWindow
(
"Tool",
"Tool WINDOW",
WS_POPUP | WS_VISIBLE,
0,0,uWidth,uHeight,
NULL,
NULL,
hInstance,
Text
);
Is the lpDesktop wrong (not exactly sure how this works)?
I know how crazy this sounds - I just would rather not have to launch another ToolDisplay.exe as USER which communicates with Tool.exe as ADMIN as a display when the Tool.exe used to handle everything on its own - so checking to see if there isn't some nice way to handle this...
Any help would be much appreciated...
Thanks,
[Simplified Question:]
My system has 2 accounts (USER and ADMIN), the user is always logged on as USER but at some specific times a process (Tool.exe) is launched under the ADMIN account (by a LocalSystem Service using CreateProcessAsUser(...)), almost everything works fine except for the fact that the process (Tool.exe) is supposed to display status to the user using CreateWindow(...).
When Tool.exe is running (as ADMIN) and the user is logged-on as USER the window is not shown (obviously)...
Is there a way to show the window of Tool.exe running under ADMIN to the user logged-on as USER?
Any help would be much appreciated...
Thanks,
Just in case you want a window / GUI spawned by a service to be visible,
Go to-> run prompt -> services.msc -> go to your service's property, check "Allow service to interact with desktop".
Then restart your service.
Note that in Vista, the prompt will NOT be visible even after above. This is due to sessions issue. However there is a service which helps support prompts from services (I think it is Interactive Services Detection service).

Login with Admin user to some domain and copy files client machines with C#

I have got a project that can copy files to another client's desktops in my domain.There is 300+ client machine.But there is a problem.When i run this project in a non admin user account in my domain.It cant copy files getting error about Access Denied , user restrictions.I wanna do this program like this , in non admin user account when user start to copy files ;
first my program will get admin access by loggin in my admin user accoun to domain than will copy files.Than logout.How can i do this ? I wanna do this with C#.
I had a similar problem: Production needed to run one of my programs that processes files on a location on the network where they don't have any access.
I ended up using Impersonation, which allowed me to run the file processing thread under a set of credentials set at runtime by my program.
In AD I created a special user account with all required permissions for exclusive use by this program.
I know it’s not at all secure, but it works and the odds that it would even occur to someone to hack my program to get these credentials is remote.
Anyway, look into Impersonation I found these resources helpful:
Safely Impersonating Another User
Brian Low's ImpersonationHelper class
-Jay
You can switch privileges when starting the program from itself or from another program. You can do this with two programs, one that runs as the user account and then launches your privileged application. (or launch itself with a different command line to indicate the different run-mode.)
To launch a program in C# as a different user, do this,
// Create a secure version of the password
SecureString pass = new SecureString();
foreach ( char c in _pass.Text )
{
pass.AppendChar( c );
}
Process process = Process.Start( "PrivilegedProgram.exe", _arguments, _user.Text, pass, _domain.Text );
you need to change the thread to the context of an admin user. How you do that in a secure way is the challenge. This sounds like a quick utility program where the security may not be a big deal, however. Just change the admin's password once the utility has been run.

Categories

Resources