WMI query to Read 'Microsoft-Windows-AppLocker/EXE and DLL' C# - c#

I have created an agent to read windows event using WMI. I ma using the agent from last 3 years to collect events. It is used in a SEIM product. The query looks like
SELECT * FROM Win32_NTLogEvent where LogFile = 'System' or logFile='Active Directory Web Services'
I am able to get the events properly. But Now I want to read apploacker events 'Microsoft-Windows-AppLocker/EXE and DLL' (Application and Security Logs -> Microsoft -> Windows -> AppLocker -> Exe And DLL).
I tried the below query but it returns zero record though I have 40+ records in it. I can see the record in event viewer.
SELECT * FROM Win32_NTLogEvent where LogFile = 'Microsoft-Windows-AppLocker/EXE and DLL'
I have tried with "wbemtest" but no record with no error.
I am not sure if this can be achieved by any other way using WMI. I know Powershell has a cmdlet and through which I am able to read 'Microsoft-Windows-AppLocker/EXE and DLL' events. But I want to read it using WMI.
Any pointers will be highly appreciated.
Thanks in advance to all viewers.

It seems that the WMI Query parses the registry location HKLM\SYSTEM\CurrentControlSet\Services\EventLog for available event logs (see MSDN Forum post).
Check the list you find there with the result of the query Select * FROM Win32_NTEventLogFile.
To add a logfile for WMI operations, add a new key under the above registry location with the name of the log ('Microsoft-Windows-AppLocker/EXE and DLL' in your case). Now it should return that log with your WMI query.

Depending on the PowerShell version, you could use the "Get-WinEvent" command to simplify what you're doing.
https://msdn.microsoft.com/en-us/powershell/reference/5.0/microsoft.powershell.diagnostics/get-winevent
Get-WinEvent -LogName "Microsoft-Windows-AppLocker/EXE and DLL"

Related

Way to copy parts of windowsEventLog to a defined location? (sec,app, sys)

I need to create three seperate evtx files containing all events from the last X days found in each eventLog (security, application, system) and save those files in a defined location.
I am using c# to implement the functionality. It is also possible to execute a powershell script / bat file. If administration rights are a problem is it possible to do this for application and system only?
From my understanding:
It is not possible to create eventLogs in custom locations without changing the registry.
It is not possible to create eventLogs in the default location without Administration Rights since for creating a new eventlog file it needs to make sure that the eventlog is not already existing and it is not possible to access the security eventLog to check.
Exception message:
"The source was not found, but some or all event logs could not be searched. To create the source, you need permission to read all event logs to make sure that the new source name is unique. Inaccessible logs: Security."
Creating a evtx file with File.Create Method (String) and writing to it with File.WriteAllText Method (String, String) is also not possible
I also tried doing all of this with a powershell script but I pretty much ran into the same problems. $foo = Get-EventLog System -after (Get-Date).addays(-3) -asbaseobject
Check out this VERY useful cmdlet--which I think should have natively shipped with Windows-- Export-EventLog by Jeffrey Patton on TechNet.
It gives you a new function you can run called Export-EventLog, which even allows you to specify a custom location! It even runs on remote computers!
Export-EventLogs -ComputerName $computerName -Credential (Get-Credential) -LogName Application -Destination 'C:\LogFiles1\Application.evtx'

Windows-7:Disable internet connection sharing on network adapter when it's in hidden state?

I'm trying to share internet over a network adapter on windows-7 using NetConLib.dll.
In order to do this, internet sharing should be disabled on all other network adapters.
In normal cases. I can iterate all the installed network adapters and disable sharing on them.
However, sometimes when the network device is unplugged, the adapter is hidden in windows.
But it's properties is still present inside windows registry.
I can't even find the adapter in Control Panel.
And off course, can't iterate it using the NetConlib library.
Possible scenarios.
The easiest way, would be using a windows command to disable internet
sharing on all the adapters. Regardless of their visibility.
Is that possible in anyway ?
The second solution is to recover the network adapter from hidden state, so that
NetConlib could iterate through it and disable it.
I tried to find the adapter's properties in windows registry and unhide it, But couldn't find anything.
Any solution?
#erm3nda.
Thank you for the informative answer. Although it didn't fix the problem I'm facing with NetConlib.
SC config correctly shuts down ICS service. But the shared network adapter continues on being flagged as Shared1. So ICS service being turned off doesn't seem to affect the adapters' settings.
Quite interestingly; when you try to share another adapter using windows GUI (Right click on adapter -> Properties -> Share), a message is prompted telling you
"there is another adapter being shared currently, your new adapter
will be shared instead". You click ok and it's done.
I've been digging the entire internet the whole afternoon to see if there are other solutions using CMD commands.
Maybe there could be a away to share an adapter with a command. This way windows would handle disabling other adapters. In a similar way as when the GUI is used.
1: Windows tells you which adapter is currently being shared in Control Panel\Network and Internet\Network Connections).
Possible solution 1: Disable ICS at all.
You can stop ICS service, so none of the connections will be at sharing status and will not conflict with NetConLib.dll. (Not sure about the hidden ones, you must try).
You can manage it from command line using:
net start SharedAccess or net stop SharedAccess
Also, if you need to disable it from reboot to, must disable service using:
sc config SharedAccess start= disabled
Notes and references:
Executing sc config will display "start= OPTIONS" and some other.
The space below = and option is mandatory. You can check result
running services.msc from Run or cmd.
Exec net to display OPTIONS. The name of service is on the
services.msc list under "Name of the service" label from ICS service.
netsh routing is not on Win7 anymore, so you only can
start/stop/enable/disable but not enable for a particular Interface.
You must set by handMouse... This not work under Win7 ICS into XP
system
Sc Config command was from this cool documentation i found
today.
Possible solution 2: Remove ghost interfaces?
I try also around Adapters and interfaces into registry and do not see anything about show/hid/ghost/enabled or similar. I also search here kb 314053 for registry conf.
I can suggeest try Possible solution 1 :) or directly delete hidden/ghost adapters.
You can do it by two ways. Devcon remove option will delete also drivers.
Device manager: Run set devmgr_show_nonpresent_devices=1 and run
devmgmt.msc. You must see over "See" a "Show hidden" option. The
show_nonpresent must reveal also hidden devices, not only inactive.
kb 269155 - You must click over #link named "Let me fix it
myself"
With devcon.exe utility: This is a device manager tool from Windows
with power moves. You will find a very big and helpfull guide
here.
Basic usage for find netcards devcon findall =net, also you can devcon findall =net *ndis* to list all ndis cards.
Basic usage for remove will be devcon remove =net *ndis* to remove all ndis card type.
I try also enable/disable commands but nothing has change into my network interfaces list.
I removed my own wifi card to test it :) Anyway, i didn't notice any option about "Unhide" feature for such devices from conections panel.
NEW EDIT (Too much verbose, right?)
I found a tool called ics-manager from this superuser post. - read answer #3
You can download directly from utapyngo's Git project page.
It's based on .Net Framework 4. Yo must download and run the build.bat to compile both exe's (You got also the C# source). The solution is to get only the compiled IcsManager.exe (command line version) with the only needed library IcsManagerLibrary.dll.
This app is using also NETCONLib.dll, so you can use it, or read the source to see wich is the correct function you need to do it and implement on your development.
If you got problems with the Ip range "192.168.137.1", you can set from Registry permanently, or run netsh interface ipv4 set address name="YOUR-INTERFACE" source=static addr=192.168.2.1 mask=255.255.255.0. You will got ugly errors from launch the netsh interface using tilde or accutes into interfaces name (Spanish default ethernet name is "Conexión de áreal local"... a joke).
Note: You can pack all at once, using first a Bat to call the IcsManager.exe' with the arguments needed, then launch the netsh configure command later from same batch to full configure.
Comment: About the prompt when try to overwrite an shared connection, it's surely because only one could be shared. I also see, they are configured as Public and Home to set the pair, but i can't find where's the registry key...Also make some exports from reg and using Diffs, no lucky. I got stuck at diffs and start to search "ICS C++ and C#" on Google, then found it.
Extra: I got the netsh it into a bat, and it's launched for Windows Task when a Ethernet cable is plugged (Here is the howto) in order to use with Android Reverse Tethering. As you can see, im too interesting into your question because it makes me research better and also learned a lot.
Sorry about my bad English. Im not.
Regards.
I found that by going into Device Manager, you can show the Hidden Devices and try to disable the internet sharing on the adapters.
Hopefully this is near what you are asking. Good luck!
Atm
Source: http://msdn.microsoft.com/en-us/library/windows/hardware/ff553955%28v=vs.85%29.aspx
I'm about 10 years late to the party, but the complete solution to this problem is nowhere else on the internet. In order to disable internet connection sharing for a device that is unplugged or uninstalled you will need to:
Clear the shared access registry
Clear the WMI sharing entry for the device
Disable sharing through the netcon library
Clearing the registry:
You need to set two registry keys to 0xFFFFFFFF:
HKLM:\Software\Microsoft\Windows\CurrentVersion\SharedAccess\PrivateIndex and
HKLM:\Software\Microsoft\Windows\CurrentVersion\SharedAccess\PublicIndex
For example in powershell:
Set-ItemProperty -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\SharedAccess" -Name "PrivateIndex" -Value 0xFFFFFFFF
Set-ItemProperty -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\SharedAccess" -Name "PublicIndex" -Value 0xFFFFFFFF
Clear the WMI sharing entry for the device:
For every HNet_ConnectionProperties you must ensure IsIcsPublic and IsIcsPrivate is set to false. You can view which interface has IsIcsPublic or IsIcsPrivate set in powershell:
Get-CimInstance -ClassName 'HNet_ConnectionProperties' -Namespace 'root\Microsoft\HomeNet' | Format-Table
Unfortunately, the Set-CimInstance cmdlet does not appear to work in this scenario, so we have to choose another language. Fortunately, code to set these values to false can be found online. For example, here is some C# that performs this task (attibuted to utapyngo)
public static void CleanupWMISharingEntries()
{
var scope = new ManagementScope("root\\Microsoft\\HomeNet");
scope.Connect();
var options = new PutOptions();
options.Type = PutType.UpdateOnly;
var query = new ObjectQuery("SELECT * FROM HNet_ConnectionProperties");
var srchr = new ManagementObjectSearcher(scope, query);
foreach (ManagementObject entry in srchr.Get())
{
if ((bool)entry["IsIcsPrivate"])
entry["IsIcsPrivate"] = false;
if ((bool)entry["IsIcsPublic"])
entry["IsIcsPublic"] = false;
entry.Put(options);
}
}
... and some vbscript (attributed to billchaison):
set WMI = GetObject("WinMgmts:\root\Microsoft\HomeNet")
set objs1 = WMI.ExecQuery("SELECT * FROM HNet_ConnectionProperties WHERE IsIcsPrivate = TRUE")
for each obj in objs1
obj.IsIcsPrivate = FALSE
obj.Put_
next
set objs2 = WMI.ExecQuery("SELECT * FROM HNet_ConnectionProperties WHERE IsIcsPublic = TRUE")
for each obj in objs2
obj.IsIcsPublic = FALSE
obj.Put_
next
Disable sharing through the netcon library:
This part you probably already know, but for completeness, here is some powershell that does it:
regsvr32.exe /s hnetcfg.dll
$NetShare = New-Object -ComObject HNetCfg.HNetShare
foreach ($RawConnection in $NetShare.EnumEveryConnection) {
$Sharing = $NetShare.INetSharingConfigurationForINetConnection.Invoke($RawConnection)
$Sharing.DisableSharing()
}
The documentation for the relevant COM APIs for netcon can be found on MSDN

Get all users that have ever logged into a pc with c#

I'm trying to retrieve all the users that have ever logged into a pc and populate them in a combobox, but after searching, I'm not finding any good answers.
I was going to look at the:
DirectoryInfo(Environment.GetEnvironmentVariable("USERPROFILE")).Parent.GetDirectories();
But I feel that is way to unreliable.
Next I was going to look at the registry, but after reading, that list will not update if a user account name has ever been changed. I know there has to be a record of all the user profiles on a machine, because I have used Microsoft systernals tools to manage them. but I just cannot figure out how to do it programatically with c#.
Ok, well, i figured this out, actually with WMI after all, here is my code.
using System.Security.Principal;
using System.Management;
private void GetLocalUserAccounts()
{
SelectQuery query = new SelectQuery("Win32_UserProfile");
ManagementObjectsSearcher searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject sid in searcher.Get())
{
MessageBox.Show(new SecurityIdentifier(sid["SID"].ToString()).Translate(typeof(NTAccount)).ToString());
}
}
This also returns the system accounts IE: NT_Authority NT_System, but those can be filtered easily. Thanks for all the help.
I would suggest to take a look at WMI. It allows you to run sql-like queries on a machine to get loads of system informations.
Some inspiration in VBScript : http://social.technet.microsoft.com/Forums/en-US/ITCG/thread/2b99b836-ed8f-4146-89e4-947b79bf4862/
If the user is created on the local machine, it should have a user folder, as Joshua said.
Also, you could try running CMD's "net user" command and capturing the return value using something like this.
Edit: per the comments below, check this out and see if it helps: https://stackoverflow.com/a/8455654/1046689
You could iterate the %windir%\Users directory ommitting default folder names (public/admin etc) and parse out the usernames from the filenames

How to get a list of Windows sessions?

I am trying to find a way to get a list of Windows sessions? I need the same information as the one displayed in the Task Manager on the User tab. I need to know if the user is active or not and if s/he is logged on in the Remote Desktop session.
Any idea on how to do that with C# / Windows XP Pro?
As a starting point you can get a list of users logged on by running the command
qwinsta
From the command prompt.
This will give output like
C:\WINDOWS\system32>qwinsta
SESSIONNAME USERNAME ID STATE TYPE DEVICE
>console me 0 Active wdcon
rdp-tcp 65536 Listen rdpwd
and will list any remote sessions.
Use LsaEnumerateLogonSessions via P/Invoke. You'll also need LsaFreeReturnBuffer to cleanup after enumerating.
I believe you'll need to use P/Invoke to retrieve this information.
The relevant APIs are documented in this MSDN page.
Another way is to use the Logonsessions utility from Sysinternals:
http://technet.microsoft.com/en-us/sysinternals/bb896769.aspx
You do not need to use Pinvoke. WMI does it, and well: "select Name, SessionId from Win32_Process" in the root\cimv2 namespace. And, it can be called from a remote machine. Simpler. Add in a where clause in the select to fine tune what you get back.

Process.StartTime Access Denied

My code needs to determine how long a particular process has been running. But it continues to fail with an access denied error message on the Process.StartTime request. This is a process running with a User's credentials (ie, not a high-privilege process). There's clearly a security setting or a policy setting, or something that I need to twiddle with to fix this, as I can't believe the StartTime property is in the Framework just so that it can fail 100% of the time.
A Google search indicated that I could resolve this by adding the user whose credentials the querying code is running under to the "Performance Log Users" group. However, no such user group exists on this machine.
I've read something similar to what you said in the past, Lars. Unfortunately, I'm somewhat restricted with what I can do with the machine in question (in other words, I can't go creating user groups willy-nilly: it's a server, not just some random PC).
Thanks for the answers, Will and Lars. Unfortunately, they didn't solve my problem.
Ultimate solution to this is to use WMI:
using System.Management;
String queryString = "select CreationDate from Win32_Process where ProcessId='" + ProcessId + "'";
SelectQuery query = new SelectQuery(queryString);
ManagementScope scope = new System.Management.ManagementScope(#"\\.\root\CIMV2");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection processes = searcher.Get();
//... snip ... logic to figure out which of the processes in the collection is the right one goes here
DateTime startTime = ManagementDateTimeConverter.ToDateTime(processes[0]["CreationDate"].ToString());
TimeSpan uptime = DateTime.Now.Subtract(startTime);
Parts of this were scraped from Code Project:
http://www.codeproject.com/KB/system/win32processusingwmi.aspx
And "Hey, Scripting Guy!":
http://www.microsoft.com/technet/scriptcenter/resources/qanda/jul05/hey0720.mspx
Process of .Net 1.1 uses the Performance Counters to get the information. Either they are disabled or the user does not have administrative rights. Making sure the Performance Counters are enabled and the user is an administrator should make your code work.
Actually the "Performance Counter Users Group" should enough. The group doesn't exist by default. So you should create it yourself.
Process of .Net 2.0 is not depended on the Performance Counters.
See http://weblogs.asp.net/nunitaddin/archive/2004/11/21/267559.aspx
The underlying code needs to be able to call OpenProcess, for which you may require SeDebugPrivilege.
Is the process you're doing the StartTime request on running as a different user to your own process?
OK, sorry that didn't work... I am no expert on ASP.NET impersonation, I tend to use app pools which I don't think you can do on W2K Have you tried writing a tiny little test app which does the same query, and then running that as various users?
I am reluctant to post a chunk of MS framework code here, but you could use either Reflector or this: http://www.codeplex.com/NetMassDownloader to get the source code for the relevant bits of the framework so that you could try implementing various bits to see where it fails.
Can you get any other info about the process without getting Access Denied?
I can enumerate the process (ie, the GetProcessById function works), and we have other code that gets the EXE name and other bits of information.
I will give the test app a try. I'm also going to attempt to use WMI to get this information if I can't get the C# implementation working properly in short order (this is not critical functionality, so I can't spend days on it).

Categories

Resources