I'm building a custom authentication subpackage for MSV1_0 for Windows 7. I've used the msvsubauth sample in from the Windows SDK and I have 2 questions regarding some problems I'm facing with that:
When I'm trying just to make sure that the routine get's invoked and set the Auth0 property in the registry to my package and add a simple code at the end of the Msv1_0SubAuthenticationRoutine that creates a file:
//
// Cleanup up before returning.
//
Cleanup:
hTestFile = CreateFile(
TEXT("C:\\lsa\\lsa.txt"),
GENERIC_READ|GENERIC_WRITE, 0,
NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL);
if(hTestFile != INVALID_HANDLE_VALUE) {
CloseHandle(hTestFile);
}
return Status;
} // Msv1_0SubAuthenticationRoutine
Apparently the package gets invoked because when I enter my password I get an error message from windows "the parameter is incorrect" which is a good sign. But why I'm getting that error? when the exactly same code is executed from a separate .exe file it runs perfectly and creates the test text file. I've checked the permissions and set "full control" for "everyone". Any ideas? the SDK doesn't exactly mention what kind of isolation LSA is creating for code within auth packages.
The second problem is testing the AP. Currently with every change I rebuild the library, copy it to a test VM and then to the System32 folder and reboot it. Is there an easier way to do that?
Thank in advance!
Debugging in Winlogon and LSASS makes for the most time consuming debugging.
To ease your debugging, you could write a proxy AP that exports the same functions. When loaded, you proxy_ap would
Copy the real AP from a known location to a temp locationand.
LoadLibrary that DLL, GetProcAddress of everything, and forward any calls it receives to that newly loaded DLL.
Watch for changes in the directory where the original AP was copied from
When a change occurs (and if your AP changed) FreeLibrary and goto step 2
But you need to keep a tight grip on what happens on your development target, because handling the dll switch while dealing with requests comming from many threads can become a worse nightmare that what you are trying to solve.
LogonUI.exe starts a new instance every time, but LSASS.exe is long lived.
+Have a look at CVSNT source code (http://cvsnt.sourcearchive.com/). They have a pretty nice AP that implements su. Run the sample in the local system account with psexec -s (from Microsoft/SysInternals pstools suite)
Perhaps your problem is Everyone only includes Authenticated users? This is just a guess.
I suggest you use Process Monitor to monitor for Access Denied messages or for your path. It is fantastic for debugging permission/path problems of all kinds.
http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx
If you experience the issue at the "Unlock Workstation" or "change Password" screens, and it doesn't prevent you logging in, this should be easy to do - set it running, reproduce the problem, log back in and hey presto.
Otherwise you might have to resort to tricks like executing that code path only for certain user accounts, on the Nth try, etc.
Related
Short disclaimer: As this question includes topics regarding hacking/pentesting, I'd like to state that this question is only asked for educational purposes as part of a school project. To prevent possible abuse, I will only post code that is necessary for understanding the problem.
To demonstrate dangers and vulnerabilities of Windows 10, I'm currently writing a small C++/WinAPI application that utilizes two common techniques:
A UAC bypass using the "fodhelper technique" (this works by simply setting a specific registry value to the path of the executable which is supposed to be elevated and then launching an automatically elevated Windows executable called "fodhelper.exe", which will then read the registry value and execute it as command/launch the specified application).
Performing PE injection, i.e. running a PE file from the address space of the current process (based on this example from github). The PE that gets injected in my program is a simple C++ Console Application (x86) that prints a message box. The shellcode is hardcoded in the injector binary (x86).
I managed to perform both of these techniques successfully in independent files. However, once I combine these two methods (i.e. first elevating, then injecting), a weird error appears.
Description of the problem
When the injector gets started manually (by double clicking), everything works fine, but when the injector is launched by System32\fodhelper.exe (x64) as a result of the UAC bypass, the following happens: After the injection has finished, the console window of the injected application appears, but instead of continuing the execution, I receive a bunch of error messages stating "The code execution cannot proceed because [garbage characters].dll was not found". This indicates that something went wrong with the offsets, and the Windows loader is trying to read the imports at a wrong position.
To summarize: The code injection works fine, unless the injector was started by fodhelper.exe. In this case the injected PE file is unable to run.
Things I have tried so far to find the origin of the issue
Debugging the injection using GetLastError and printing the various memory addresses used during the injection. There is no difference if the file is manually started (and the injection is successful) or if it gets started by fodhelper.exe (and the injection fails).
Replace the WriteProcessMemory calls with WriteFile to compare the output file when the injector gets manually launched or by fodhelper.exe. Both output files are exactly the same and runnable. This indicates that the injection itself is not the problem, but the Windows loader seems to act differently.
Manually elevating the injector using UAC or by using an elevated command prompt. In both cases, the injection is successful.
Copying fodhelper.exe to another location (for example to the desktop) and launching this copy. In this case, the injection is successful. The injection only fails if the injector gets started by the original fodhelper.exe in the System32 folder.
It seems that the injection behaves completely identical, but the indicators show that due to some unknown impact of fodhelper.exe that gets passed down to the injector, the Windows loader seems to behave differently.
I appreciate any explanation or assumption! Feel free to ask if you require more information.
Minimal reproducible example
(with limited debug info and comments):
https://0bin.net/paste/UPRIg12n#6nJvBok72UcDvIa56c-XEss7AibIh1Zrs+c3sUzvQMj
Note: See how the injection works if you exclude the elevateProcess function or manually elevate the exe with UAC, and how it fails when including said function.
Edit
According to the answer by user RbMm, this error is a result of a specific exploit protection attribute (PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY with the EnableModuleTamperingProtection value) that gets automatically applied onto fodhelper.exe and seemingly gets inherited by all child processes. According to this, removing/resetting this attribute when launching the target process should fix the error. So far I've tried the following, but couldn't achieve any change in the outcome:
DWORD resetPolicy = 0;
STARTUPINFOEXA siEx = { 0 };
SIZE_T AttributeListSize = 0;
siEx.StartupInfo.cb = sizeof(siEx);
InitializeProcThreadAttributeList(NULL, 1, 0, &AttributeListSize);
siEx.lpAttributeList = (LPPROC_THREAD_ATTRIBUTE_LIST)HeapAlloc(GetProcessHeap(), 0, AttributeListSize);
InitializeProcThreadAttributeList(siEx.lpAttributeList, 1, 0, &AttributeListSize);
UpdateProcThreadAttribute(siEx.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY, &resetPolicy, sizeof(resetPolicy), NULL, NULL);
...
CreateProcessA(CurrentFilePath, NULL, NULL, NULL, FALSE, EXTENDED_STARTUPINFO_PRESENT | CREATE_SUSPENDED, NULL, NULL, (LPSTARTUPINFOA)&siEx, &PI);
when process created via RunAs with elevation - the appinfo.dll call RAiLaunchAdminProcess function (this is in some svchost.exe) and this function, pass STARTUPINFOEX (and EXTENDED_STARTUPINFO_PRESENT flag) to CreateProcessAsUser. and here - lpAttributeList, in particular PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY attribute key is used for set several exploit mitigation policy for the child process (fodhelper.exe in your case). and here EnableModuleTamperingProtection is set for child process tree. effect of this - when system resolve import descriptor, it check (inside LdrpGetImportDescriptorForSnap) for this mitigation flag, and if it enabled - call LdrpCheckPagesForTampering api, it return true, if SharedOriginal is 0, this means this is a copy-on-write private copy of the EXE/IAT -- hence 'tampered' with.
after this LdrpMapCleanModuleView is called. at this point your try begin breaking
possible first public info about this, from Alex Ionescu -
LdrpCheckPagesForTampering/LdrpMapCleanModuleView (RS3) are pretty
cool antihollowing mitigations
(EPROCESS.EnableModuleTamperingProtection)
if you by self launch new process, you of course not call UpdateProcThreadAttribute for set PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY and in this case, your code sometime work. really only random and sometime - here exist many other errors and bad codding
I am having a problem with calling the function MsiOpenDatabase (https://msdn.microsoft.com/en-us/library/aa370338(v=vs.85).aspx) from inside a program when I choose to "run as administrator". When I run it under an admin account but without explicitly starting the executable as elevated it all works just fine. This indicates that the path to MSI file etc should be correct.
So, when running elevated the MsiOpenDatabase() I get an error code of 110 (0x6e).
I have tried to call MsiGetLastErrorRecord as explained here (https://msdn.microsoft.com/en-us/library/aa370124(v=vs.85).aspx) but nothing happens when I try to print the code in a message box. It simply doesn't get there.
I do not have Visual studio for debuggning on the target machine, so debugging is a bit of a pain.
Target machine is Windows 7 x64. Application is 32-bit.
But just the pure fact that it works un-elevated but fails when run as an administrator...it feels like there should be some kind of answer to this which can be derived from this fact perhaps?
Thankful for any help!
EDIT:
I finally solved it!
Apparently I had to go to the network share where the MSI file is located (which I am trying to call MsiOpenDatabase on) and right cklick on a file there and choose "run as administrator" because then and only then did I get a UAC dialog box asking for credentials (I mean I was able to open Windows Explorer as admin and navigate to the network share without problem so I never thought that it would be what would give me these peoblems). After haing done that I was able to run my application and it did no longer fail on any MsiOpenDatabase call.
But, why must I do this procedure to get access to run file on a network share since I already had access (execute rights) with the same user but when not elevated? How come Windows needs to ask the same user for credentials if it is already running elevated on the very same account that already has access to the network share? Seems strange to me, but I suppose I am missing some crucial part?
SAMPLE CODE
LPCTSTR szPersist = MSIDBOPEN_READONLY;
MSIHANDLE handleDB;
UINT result = MsiOpenDatabase(strPath, szPersist, &handleDB); // strPath is something like _T("\\server\MSI\Setup.msi");
result variable has value 110 when this error occurrs as explained above and keep the part in the update section in mind. I find it strange, but perhaps someone knows UAC better than me and why I have to provide credentials again by going to a file on the netowrk share and choose to run as admin to get it working (since I have already provided credentials as non-admin with the same account earlier at that very same network share location)?
This is standard UAC behavior since Windows Vista and is not related to MSI at all. Do a google search for "uac network drives".
You should be closing your MSI handles though as I commented above. Use PMSIHANDLE instead of MSIHANDLE.
This touches on some already-answered questions, so feel free to duplicate away, but chances are I've already read them and am not satisfied.
There are 2 drivers on my system (located in C:\Windows\System32\drivers) called pefndis.sys and wfpcapture.sys. I am 100% sure pefndis.sys is a kernel driver and 99.9% sure wfpcature.sys is as well. These are 3rd party drivers installed by Mircosoft's Message Analyzer. I have discovered pefndis.sys is used to capture data on the wire and wfpcapture.sys is used to capture data above the network layer (ie, this will capture loopback traffic). I have no documentation, header files, etc, for these drivers as there was no intention of Microsoft for these drivers to be used for custom solutions as I would like to do. It just so happens I've identified wfpcapture.sys as performing the exact tasks I want, and I'd love to tap into what it can do; this seems so much more reasonable than spending the time and pain of implementing my own driver. However, my efforts have failed.
This is what I've done: I have some simple c++ code here:
void Provider::InitDriver()
{
HANDLE wfpHandle = NULL;
DWORD lastError = 0;
LPCTSTR wfpName = L"\\\\.\\wfpcapture";
LPCTSTR pefName = L"\\\\.\\pefndis";
wfpHandle = CreateFile(
wfpName,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
lastError = GetLastError();
CloseHandle(wfpHandle);
}
When I run CreateFile with wfpName, I get an invalid handle and lastError==2 meaning the file cannot be found. When I run CreateFile with pefName, I get a valid handle and lastError==0. Upon further investigation, most of my randomly-picked .sys files from the drivers folder produce invalid handles with error codes of 2. Occasionally I'd get an error code of 5 (Access Denied, which also seems odd since I'm running everything as administrator). Does anyone have an explanation why I cannot get a handle to wfpcapture.sys? I brought up the pefndis.sys driver because it was installed by the same program as wfpcapture.sys, and I can clearly get a handle to that, so all my strings are formatted correctly, and both files are in the same directory. I came across this post yesterday which told me IoCreateSymbolicLink can be used in the driver code to give the driver another alias. If I'm using the wrong alias, does that explain why so many .sys files return FILE_NOT_FOUND errors when I try to get handles to them?
I've tried to do some more research on the file using IL DASM (no luck, this is native code), DUMPBIN, WinObj, and DependencyWalker.
DUMPBIN /EXPORTS [...]wfpcapture.sys returns no exports. I find this extremely odd. These answers suggest .DLLs without exports are simply resources or the code is obfuscated. I am almost certain wfpcapture.sys does not just contain resources. Is obfuscation the most reasonable explanation.. any other ideas why it doesn't have any exports?
I could not find wfpcapture in WinObj anywhere. I located pefndis in Device\. Where is wfpcapture? It doesn't actually talk to a device, so that makes sense, but it is still a driver, correct? Do drivers need to register with Windows in some way before CreateFile can find them?
DependencyWalker verified what DUMPBIN told me, I think .. no exports. I have no idea how Message Analyzer (or anything else down its dependency stack) is actually talking to it.
Just a bit more background for a complete picture... wfpcapture.sys is an ETW Provider that taps into Microsoft's WFP architecture (used for firewall and IDS applications) to sniff packets above the network layer. I want code that "activates" wfpcapture.sys and then sits back and collects the events (packet captures) that wfpcapture publishes. It's this activation part that I can't figure out. If I setup Message Analyzer to start capturing localhost traffic, then turn on the part of my code that captures the events (using StartTrace(...) and EnableTraceEx2(...)), that works just fine. I am just dying to know how Message Analyzer is talking to wfpcapture.sys and what it's saying in order to get it to cooperate and start publishing events. Another fun fact: When I start a trace in Message Analyzer and do sc query wfpcapture, it tells me the service (here it is identified as a kernel driver) is running. When I stop the trace, the query tells me the service is stopped. If I manually sc start wfpcapture and verify the service is running,, and then run my event capturing code, I get nothing. This tells me Message Analyzer must be sending something to wfpcapture.sys to get it activated and publishing. My plan that spawned this whole thing was to get a handle to driver and start sending it control codes via DeviceIoControl to glean some knowledge on how it worked. I have also seen some very strong evidence that Message Analyzer is passing filter masks to the driver.
Am I completely wasting my time here? That driver is not meant for my consumption, and poking and prodding it to learn about it may be a long shot, but I'm certain it does exactly what I need and I've never written a driver in my life; trying to do that seems foolish when this is sitting right here. Message Analyzer is free, I'm not trying to steal software. Could there possibly be some DRM associated with the driver that's boxing me out? I'd love to hear the thoughts of anyone out there who has Windows driver experience.
Ok, lot of questions there, hope this doesn't get flagged as too broad.
I have been dabbling with working nicely with UAC for a while and I found about a few things:
With UAC enabled, a program in the Startup folder, that requires to be run as admin (say by an embedded manifest), cannot be run according to this Stack Overflow thread.
Another method of running a program at startup is by creating a key containing the path to that application in: HKLM or HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run or HKLM or HKCU\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Run in 64 bit machines.
Yet another method is using the task scheduler setting the Run with highest privileges option. This is the only method that bypasses the problem stated in point 1.
Coming from a Linux background, I had no clue about all these admin rights related problems. If someone can list out scenarios which absolutely need administrator privileges, it would be of great help!
I'm asking this because when I'm developing some application, I keep encountering several problems during implementation mostly because my application required admin rights when it shouldn't.
If I know, at design time, all possible scenarios that require admin rights, I could possibly design a common service for all my applications that takes care of all the administrator tasks (I think services are the Windows way of doing things like this).
There really isn't a list of scenarios or API function calls that require elevation. Your best option will probably be to focus on what API calls require elevation. The reason for this is that it may be required only if certain values are passed to the function. For instance CreateFile can create a file in your home directory without elevation but requires it for creating a file in C:\Windows. If the directory is provided through user input the only way you can know if elevation is required is to check the error code when the call fails. If elevation is required the function will set the error status to ERROR_ACCESS_DENIED and return a value indicating failure.
I have created a windows service that checks installed printers and updates a file currently located at "C:\App\Data\info" (no file extension) Very simple, all it does is call EnumPrinters with the correct flags and dumps PRINTER_INFO_2 to a file.
Everything works exactly as expected in Visual Studio 2010, in the "testing" project leading me to believe the issue is not in my service. As soon as I install this as a windows service it stops looping. It will run through the loop once and never again.
Code Reference:
I am using the template from here: http://www.kencotutorials.com/WindowsService.aspx
and have only changed the service class file.
Initial thoughts are either security permissions or the wait function not returning.
Edit: I have already checked the whole file system to see if its being written elsewhere and confirmed that it is not.
This is the service loop function that is called by the template.
void CMyService::MyServiceLoop(void)
{
CheckPrinters(); // updates a PRINTER_INFO_2 struct with all installed printers
WritePrinterFile(); // writes the file (i know there's no issue with the actual writing)
Sleep(10000);
OutputDebugString("Done sleeping");
Return;
}
I have added OutputDebugString("Shell loop entered") at the start of the shell app loop.
I have also added OutputDebugString("Waiting for object") in front of the call to WaitForSingleObject()
The loop seems to hang on the WaitForSingleObject. Last message in DbgView is "Waiting for object".
Could be a lot of reasons. I'd recommend you add some OutputDebugString() calls (Win32 API function) and get DbgView.exe from Microsoft to see what is going on. Also, doesn't sound like you are doing this, but make sure you aren't writing to a mapped drive or network location, since your service most likely doesn't have access to those.
When you set up your Windows Service, did you specify an account on the Log On tab?
http://www.coretechnologies.com/WindowsServices/FAQ.html#AppNotWorkingFromService
The default Local System account almost surely doesn't have the rights to use the printers so be sure to set an account that can access the printers normally.