Alternatives to LogonUser for network impersonation (C++) - c++

Are there any alternatives to LogonUser and for impersonating given account in order to access network resources? I'm looking for the method of impersonation which would let me connect to machine in foreign domains (or, workgroup machines for the same matter).
For initial data I have: machine name, username (or domain\username), cleartext password.
I know there's a way to establish connection using WNetAddConnection to a \\machinename\ipc$, then most network functions will run in a context of that account, however win2008 added another twist and some functions still use the account, that thread is running under.
I'm also aware, that there's some way to get an impersonation token using SSPI. Have anyone experimented with those tokens, are they good for accessing shares, SCM, remote registry and stuff? Is is what WNetAddConnection is using?
EDIT: To clarify, the reason I cannot use LogonUser is because I need to impersonate user in a non-trusted domain or workgroup
EDIT2: Another clarification: the item I'm trying to implement is similar to psexec, e.g.:
program should not modify host or active directory configuration (e.g.: create temporary local users, etc). Moreover assumption cannot be made that it is running on DC or not
there can be no assumptions made about which software is pre-installed on the remote host, only condition given is that windows file sharing is enabled on target
Account/password is known to be working on target, but target machine may be in local domain, foreign domain, not in domain at all.
EDIT3: I would really love to hear more about SSPI InitializeSecurityContext / AcquireCredentialsHandle option. Is there anybody who has been working with this API extensively? Is it possible to use the tokens returned with impersonation, so that a thread can access network shares and copy files, etc? Can someone post a working code snippet?
EDIT4: Thanks to Marsh Ray, problem got resolved. If anyone is looking to see the proof-of-concept code, it is here

If you're wanting to "access network resources" outside of your forest, do that with WNetAddConnection2/3 as you mentioned, or use the standard RPC APIs with RPC_ C__ AUTHN__ GSS__ NEGOTIATE and and explicit credentials structure.
Normally, "impersonation" is something that happens on the server side. The server side will be able to impersonate the connection as the account you're connecting as.
But the key is this: impersonation only makes sense for impersonating an account the server can access in his local SAM/domain/forest directory. If the client and server are in different forests, they clearly can't agree on the SID of an account for an impersonation token (except for the case of well-known SIDs like Administrator which serve mainly to confuse this kind of thing), and that seems necessary to check against DACLs etc.
Perhaps what you want is to call LogonUserEx with the LOGON32__ LOGON__ NEW__ CREDENTIALS flag. This should succeed (even in a different forest - it doesn't actually authenticate the credentials you give it) giving you a token with the username/password you specified. You may have to use DuplicateToken to turn this into an impersonation token. Then you can use SetThreadToken to replace the token on your thread.
IMHO this isn't really "impersonation", you're just using the credentials outright, but it allows you to access network resources transparently as the arbitrary username/password you supply.
Edit: Oh yeah, be aware that there is no protection against man-in-the-middle on this type of connection. The client especially cannot strongly authenticate the server (short of heroics like IPSEC), so in theory you can't trust anything the server tells you.

The theory goes that you pass the credentials as a SEC_WINNT_AUTH_IDENTITY structure to the AcquireCredentialsHandle function that creates the handle used in InitializeSecurityContext. I never tried this on foreign domains though and I don't know if it works.

Doing this directly and reliably via the Windows API seems next to impossible, plus Windows does so much work behind the scenes to make network access "just work". Plus the impersonation side of things only works for the single thread that called the APIs.
But... you can run a whole program under a different user... such as when you run a service.
So you could edit the registry in your main program to run various services under different security tokens and use IPC/Sockets to communicate with those processes from your main application. ie. a whole bunch (or restarting and reconfiguring the same process) of helper processes running under the different user(s) which your main app abuses.
I realize this is a hack but it seems viable ;)

You could open a command line, map the drive using the plaintext username and password. Then disconnect the drive:
net use m: \\machinename\share password /user:username
... do stuff ...
net use m: /delete
http://technet.microsoft.com/en-us/library/cc756153(WS.10).aspx

Related

access mapped network drive through impersonation

Is it impossible to access the mapped network drive( mapped in user session) from service after impersonating the current user by using ImpersonateLoggedOnUser Windows API?
Yes, this is impossible. Drive mappings are only established during an interactive logon. The ImpersonateLoggedOnUser function does not impersonate the user's entire logon session, just their security context. This is only one of the many things that cannot be done using impersonation.
I suppose you might be able to do this by duplicating the user's login token (obtained from one of their interactive processes), and then using that to call the CreateProcessAsUser function. You would then launch a process that would work with the mapped network drive(s). I'm not absolutely certain that this will work, as I've never done it, but it seems theoretically possible.
Of course, it begs the question of why you need to follow such a circuitous route. It would be eminently more sensible to just run your code in the user's interactive process to begin with, as a standard Windows application.
This is not something that a service is designed to do. Services do not support mapped network drives. If you want to access a network resource from within a service, you should just use the UNC path.

Access network share from service with another user [duplicate]

This question already has an answer here:
Access to a protected network share using Win32 C++
(1 answer)
Closed 7 years ago.
I have a service that lives in a quite restricted server system. It must run under a specific user, let's call it user A.
The service must also be able to access a network share which user A does not have access to, but user B has. So the service must access this network share as user B, while running as user A.
The way I would do this if running locally on the computer is to map a network drive under a different user. But services can't access mapped network drives, even if it was mapped under the same user:
Services and Redirected Drives
Does anyone have a suggestion to what I could do? I'm the creator of the service so I can modify it as I please. Is there perhaps some way to let it access the network share as another user via a winapi call (unmanaged C++)?
The article you link to says:
Instead, the service should use client impersonation to impersonate the user.
In this context, that means using LogonUser and ImpersonateLoggedOnUser.
One caveat: that will only work if you are in a domain, i.e., the account that you want to log into the network server with is also valid on the local machine. If not, then you will have to establish a network connection explicitly using WNetAddConnection2 or similar. It is technically true that this risks exposing the connection to other services, but the risk is minimal in most contexts.
I think this SO post might actually be the answer I'm looking for:
Access to a protected network share using Win32 C++
Unless anyone has a better idea or other objections?

Prevent the use of ImpersonateNamedPipeClient()

When a named pipe client connects to a server and writes some data, the server can call ImpersonateNamedPipeClient() to impersonate the client. (The server does need to read the data before calling ImpersonateNamedPipeClient()).
As we can see at this link, this can lead to a privilege escalation security vulnerability.
Is possible to prevent/disable/deny this impersonation, so that a client can connect to the named pipe but not allow the server to impersonate?
Note 1: I know that the client needs to write on the named pipe first. But in some cases, the client will need to write first, so I need to prevent this security flaw.
Note 2: A solution that applies to Windows XP and above is appreciated.
When calling CreateFile() to open the client end of the named pipe, pass SECURITY_IDENTIFICATION in the dwFlagsAndAttributes parameter. This allows the server to identify the user and to determine the client's privileges, but prevents the server from impersonating the client's security context.
You can use SECURITY_ANONYMOUS instead if you also want to prevent the server from identifying the user.
Note that the server can still successfully call ImpersonateNamedPipeClient() but any attempt to make use of the impersonation token will be restricted by the specified impersonation level. For example, if the server attempts to open a file while impersonating the client at identification or anonymous level, the operation will fail.
For more information, see the Impersonation Levels page on MSDN.
It should also be noted that as of Windows XP service pack 2, the server cannot impersonate the client unless it holds the SeImpersonatePrivilege privilege. (See ImpersonateNamedPipeClient on MSDN.) In the default configuration, only system services and administrators have this privilege. This effectively mitigates many (though not all) of the risks described in the article you link to.

Client / Server Cryptography for passwords

I am building a client/server application in C++ and need each client to provide a password. Obviously I want this to be secure during transport so I have been looking into a way of encrypting the password; so that only the server application can decrypt it again.
The problem I am having is not necessarily getting the functions to work, but rather understanding what it is I need to do in order to relate that into code. I am trying to understand and have read MSDN (feels like it) but still I am only learning so really need some clear and accurate guidance on my implementation.
Does this sound right?
I aquire a context to the CSP on both server and client.
I generate a key on the server, or load one (whatever).
and then I
export a public key from the server and send it to the client, the client imports the key and then encrypts the password and returns it so that only the server can decrypt it again.
(Fails when I try).
OR, do I then
export a session key, or an exchange key pair ( single public) which is encrypted with the exchange key pair?
Oh I am so lost, I cannot even explain clearly.
Please help me to understand this...
It really depends on what sort of authentication solution you want to be based one. The options are varied.
You could, for example, rely on the underlying OS authentication. You wouldn't need to manage passwords at all. But this requires a somewhat tighter integration with the domain in which your application is running.
Another option is to use HTTPS and simple authentication. It basically uses SSL to encrypt communication and then sends a username/password pair. Pretty simple, and supported by all web servers. You could probably find C++ code quite easily that takes care of this for you (search StackOverflow for such a question) if you don't want to rely on an existing web server like IIS being installed.
If you do not need the encrypted Communication for other things like data transfer, you can use Challenge-Response for password verification. The Password does not need to be transferred over the network and there is no risk of a replay attack in wich a third party just resends some packets. On the downside, a man in the middle (MITM) attack is possible.
If you need protection from MITM or need an encrypted channel for other communication, you should use TLS with certificates or Public-Key-Encryption with two keypairs.
Do not do anything.
This is very important. Do not implement this yourself.
Repeat do not do anything you will get it wrong.
You should use what is already available. Simply open a connection to an SSL socket and the content of the stream will be automatically encrypted and de-crypted at the other end.
Your application should simply take a username/password tupple and validate if they are correct. Do not attempt to implement the cryptographic part.

Impersonate SYSTEM (or equivalent) from Administrator Account

This question is a follow up and continuation of this question about a Privilege problem I'm dealing with currently.
Problem Summary:
I'm running a program under a Domain Administrator account that does not have Debug programs (SeDebugPrivilege) privilege, but I need it on the local machine.
Klugey Solution:
The program can install itself as a service on the local machine, and start the service. Said service now runs under the SYSTEM account, which enables us to use our SeTCBPrivilege privilege to create a new access token which does have SeDebugPrivilege. We can then use the newly created token to re-launch the initial program with the elevated rights.
I personally do not like this solution. I feel it should be possible to acquire the necessary privileges as an Administrator without having to make system modifications such as installing a service (even if it is only temporary).
I am hoping that there is a solution that minimizes system modifications and can preferably be done on the fly (ie: Not require restarting itself). I have unsuccessfully tried to LogonUser as SYSTEM and tried to OpenProcessToken on a known SYSTEM process (such as csrss.exe) (which fails, because you cannot OpenProcess with PROCESS_QUERY_INFORMATION to get a handle to the process without the privileges I'm trying to acquire).
I'm just at my wit's end trying to come up with an alternative solution to this problem. I was hoping there was an easy way to grab a privileged token on the host machine and impersonate it for this program, but I haven't found a way.
If anyone knows of a way around this, or even has suggestions on things that might work, please let me know. I really appreciate the help, thanks!
By design, no process is allowed to achieve NT AUTHORITY\SYSTEM rights, unless it is started by another process with NT AUTHORITY\SYSTEM rights. The service is a workaround because the Service Control Manager itself is started by the Kernel at system start.
Unfortunately, the operating system is designed to prevent exactly what you're trying to do. If you want to be able to remove your service afterwards, simply grant the user in question SeDebugPrivilege for the local machine and then have the service uninstall itself.
Better yet, have the program whose memory is to be modified change DACLs to allow your administrator access to it's memory without SeDebugPrivilege. Then you don't need to take privilege at all.
EDIT2: And even better yet, just use shared memory in the first place. That's what it's for.