Match EventLog and SearchResultEntry - c#

I want to get all ad changes, including all attributes, who made the change and on which machine. No api satisfies both conditions, so I use a combination of SearchResultEntry and EventLogRecord.
To get the "who" and "where" I register a EventLogWatcher:
var query = new EventLogQuery("Security", PathType.LogName, "*");
var propertySelector = new EventLogPropertySelector(new[]
{
"Event/EventData/Data[#Name='TargetUserName']",
"Event/EventData/Data[#Name='TargetDomainName']",
"Event/EventData/Data[#Name='TargetSid']",
"Event/EventData/Data[#Name='SubjectUserName']",
"Event/EventData/Data[#Name='SubjectDomainName']",
"Event/EventData/Data[#Name='SubjectUserSid']",
"/Event/EventData/Data[#Name='AttributeLDAPDisplayName']",
"/Event/EventData/Data[#Name='AttributeValue']",
"/Event/EventData/Data[#Name='OperationType']",
"/Event/System/Computer"
});
using (var watcher = new EventLogWatcher(query))
{
watcher.EventRecordWritten +=
(object eventLogWatcher, EventRecordWrittenEventArgs eventArgs) =>
{
var eventLogRecord = eventArgs.EventRecord as EventLogRecord;
var props = eventLogRecord.GetPropertyValues(propertySelector);
// process entry
};
watcher.Enabled = true;
// block the thread like await Task.Delay(-1);
}
But this will not include all changes and keep in mind, that the properties will vary based on the event type. To get a full copy of the new object when a change occurs, you can register a callback with SearchRequest:
SearchRequest request = new SearchRequest(dn,filter,scope,attributes);
request.Controls.Add(new DirectoryNotificationControl());
IAsyncResult result = _connection.BeginSendRequest(
request,
TimeSpan.FromDays(1),
PartialResultProcessing.ReturnPartialResultsAndNotifyCallback,
(res) =>
{
var r = _connection.GetPartialResults(res);
foreach (SearchResultEntry entry in r)
{
// process entry
}
},
request);
But how do I match these two events ? SearchResultEntry contains just a new object with attributes and EventLogRecord many information, but none to match them exactly. It is assumed, that both tools run on the same domain controller. Just time as match property is not sufficient enough.

You can use pull mush method to millions of data.You don't need to get all the events from AD intead 5136 event itself has all the changes in AD.You can get all the information from EventLogRecord API.Below are my codes
public class EventLogMgmt{
public static void Main(string[] args)
{
Stirng logName = "Security";
String queryString = "<QueryList> <Query Id="0" Path="Security"><Select Path="Security">*[System[(EventID = 5136)]]</Select></Query></QueryList>";
EventLogQuery subscriptionQuery = new EventLogQuery(logName, PathType.LogName, queryString);
watcher = new EventLogWatcher(subscriptionQuery, null, true); //EventLog watcher
watcher.EventRecordWritten += new EventHandler<EventRecordWrittenEventArgs>(EventLogEventRead);
watcher.Enabled = true;
}
public void EventLogEventRead(object obj, EventRecordWrittenEventArgs arg)
{
if (arg.EventRecord != null)
{
EventRecord eventInstance = arg.EventRecord;
//String eventMessage = eventInstance.FormatDescription(); // You can get event information from FormatDescription API itself.
//String eventMessageXMLFmt = eventInstance.ToXml(); // Getting event information in xml format
String[] xPathRefs = new String[9];
xPathRefs[0] = "Event/System/TimeCreated/#SystemTime";
xPathRefs[1] = "Event/System/Computer";
xPathRefs[2] = "Event/EventData/Data[#Name=\"TargetUserName\"]";
IEnumerable<String> xPathEnum = xPathRefs;
EventLogPropertySelector logPropertyContext = new EventLogPropertySelector(xPathEnum);
IList<object> logEventProps = ((EventLogRecord)arg.EventRecord).GetPropertyValues(logPropertyContext);
Log("Time: ", logEventProps[0]);
Log("Computer: ", logEventProps[1]);
}
}
}
All the information like target user,caller user name,modified properties,etc available in above API.

Related

Making DialogFlow v2 DetectIntent Calls w/ C# (including input context)

So I finally figured out a way to successfully make detect intent calls and provide an input context. My question is whether or not this is the CORRECT (or best) way to do it:
(And yes, I know you can just call DetectIntent(agent, session, query) but I have to provide a input context(s) depending on the request)
var query = new QueryInput
{
Text = new TextInput
{
Text = model.Content,
LanguageCode = string.IsNullOrEmpty(model.Language) ? "en-us" : model.Language,
}
};
var commonContext = new global::Google.Cloud.Dialogflow.V2.Context
{
ContextName = new ContextName(agent, model.sessionId, "my-input-context-data"),
LifespanCount = 3,
Parameters = new Struct
{
Fields = {
{ "Source", Value.ForString(model.Source) },
{ "UserId" , Value.ForString(model.UserId.ToString())},
{ "Name" , Value.ForString(model.FirstName)}
}
}
};
var request = new DetectIntentRequest
{
SessionAsSessionName = new SessionName(agent, model.sessionId),
QueryParams = new QueryParameters
{
GeoLocation = new LatLng {Latitude = model.Latitude, Longitude = model.Longitude},
TimeZone = model.TimeZone ?? "MST"
},
QueryInput = query
};
request.QueryParams.Contexts.Add(commonContext);
// ------------
var creds = GetGoogleCredentials("myCredentials.json");
var channel = new Grpc.Core.Channel(SessionsClient.DefaultEndpoint.Host, creds.ToChannelCredentials());
var client = SessionsClient.Create(channel);
var response = client.DetectIntent(request);
channel.ShutdownAsync();
return response;
Note: I included the explicit ShutDownAsync (it's not in an async call) because I was getting some file locking issues when attempting to re-deploy the WebAPI project (and only after having executed this code).
Thanks
Chris
Updated 4/25: The most basic way I use this is to integrate the user's name into intent responses:
It can also be read from within the webhook/inline fulfillment index.js:
const name = request.body.queryResult && request.body.queryResult.outputContexts && request.body.queryResult.outputContexts[0].parameters.Name

Get FileName from FileObject or FileKey in event trace ETW file log C#

I've been searching for a solution to get all Read/Write/Open/Close files by a specific process from an event trace (ETW) session (I will process data from a real-time session).
I write this code and get all event in that operation but I can't get FileName or Path in events. there is just FileObject and FileKey,...
this is my code to get events:
var sessionName = "ETWEventSession";
using (var session = new TraceEventSession(sessionName, null))
{
session.StopOnDispose = true;
using (var source = new ETWTraceEventSource(sessionName, TraceEventSourceType.Session))
{
Action<TraceEvent> logAction = delegate(TraceEvent data)
{
Console.WriteLine(log);
};
var registerParser = new RegisteredTraceEventParser(source);
registerParser.All += logAction;
var fileProviderGuid = TraceEventSession.GetProviderByName("Microsoft-Windows-Kernel-File");
session.EnableProvider(fileProviderGuid, TraceEventLevel.Informational, 0x0200);
source.Process();
}
}
I run my agent and get events like this:
<Event MSec="0.0000" PID="11376" PName="" TID="24668"
EventName="Write" ProviderName="Microsoft-Windows-Kernel-File"
ByteOffset="102386" Irp="0xffffe00148e8c478" FileObject="0xffffe00146c43210"
FileKey="0xffffc0019d3f8140" IssuingThreadId="24668"
IOSize="7" IOFlags="0" ExtraFlags="0"/>
How can I get FileName that affected in this event?
What is FileObject or FileKey?
can I get FileName from FileObject or FileKey?
With this code, can get every thing what I want.
var KernelSession = new TraceEventSession(KernelTraceEventParser.KernelSessionName, null);
var KernelSource = new ETWTraceEventSource(KernelTraceEventParser.KernelSessionName, TraceEventSourceType.Session);
var KernelParser = new KernelTraceEventParser(KernelSource);
KernelSession.StopOnDispose = true;
KernelSession.EnableKernelProvider(
KernelTraceEventParser.Keywords.DiskFileIO |
KernelTraceEventParser.Keywords.FileIOInit |
KernelTraceEventParser.Keywords.Thread |
KernelTraceEventParser.Keywords.FileIO
);
KernelParser.All += GetLog;
KernelSource.Process();
}
private static void GetLog(TraceEvent obj)
{
var log = obj.ToString();
if (log.Contains(#"E:\Final\ETW"))//&& !log.Contains("FileIo/Create")
{
Console.WriteLine(log);
}
}
In ShareAccess property of event you can find ReadWrite event . FileName is in each event. also you can restrict your directory for file events and use this instead of FileSystemWatcher :).
There is already an Kernel Parser in the session.Source which you subscribe to:
var kernel = session.Source.Kernel;
kernel.FileIORead += HandleFileIoReadWrite;
kernel.FileIOWrite += HandleFileIoReadWrite;
private void HandleFileIoReadWrite(FileIOReadWriteTraceData data)
{
if (data.ProcessID == pid) // (data.ProcessName.Contains("foo"))
{
Console.WriteLine(data.FileName);
}
}
here filter per pid or Processname and here you can get the filename at data.FileName. Subscribe to any FileIO event you want to handle.

How to batch queue records and execute them in a different thread and wait till it;s over?

I am using push sharp version PushSharp 4.0.4.
I am using it in a windows application.
I have three main methods
1- BroadCastToAll
2- BrodcatsToIOS
3- BrodcatsToAndriod
I have a button calld send. On the click event of the button. I am calling the
BroadCastToAll function.
private void btnSend_Click(object sender, EventArgs e)
{
var url = "www.mohammad-jouhari.com"
var promotion = new Promotion ();
BroadCastToAll(promotion, url);
}
Here is the BrodcastToAll Function
public void BroadCastToAll(Promotion promotion, string url)
{
var deviceCatalogs = GetDeviceCatalog();
BroadCastToIOS(promotion, url, deviceCatalogs.Where(d => d.OS == "IOS").ToList());
BroadCastToAndriod(promotion, url, deviceCatalogs.Where(d => d.OS == "Android").ToList());
}
Here is the BrodcastToIOS Function
public void BroadCastToIOS(Promotion promotion, string url, List<DeviceCatalog> deviceCatalogs)
{
if (deviceCatalogs.Count == 0)
return;
lock (_lock)// Added this lock because there is a potential chance that PushSharp callback execute during registering devices
{
QueueAllAppleDevicesForNotification(promotion, url, deviceCatalogs, logsMessage);
}
}
Here is the BrodcastToAndriod Function
public void BroadCastToAndriod(Promotion promotion, string url, List<DeviceCatalog> deviceCatalogs)
{
if (deviceCatalogs.Count == 0)
return;
lock (_lock)// Added this lock because there is a potential chance that PushSharp callback execute during registering devices
{
QueueAllGcmDevicesForNotification(promotion, url, deviceCatalogs, logsMessage);
}
}
Here is the QueueAllAppleDevicesForNotification function
private void QueueAllAppleDevicesForNotification(Promotion promotion, string url, List<DeviceCatalog> deviceCatalogs)
{
var apnsServerEnviroment = UseProductionCertificate ? ApnsConfiguration.ApnsServerEnvironment.Production : ApnsConfiguration.ApnsServerEnvironment.Sandbox;
var fileService = new FileService();
var filePath = Application.StartupPath+ "/Certifcates/" + (UseProductionCertificate ? "prod.p12" : "dev.p12");
var buffer = fileService.GetFileBytes(filePath);
var config = new ApnsConfiguration(apnsServerEnviroment, buffer, APPLE_CERTIFICATE_PWD);
apnsServiceBroker = new ApnsServiceBroker(config);
apnsServiceBroker.OnNotificationFailed += (notification, aggregateEx) => {
aggregateEx.Handle (ex => {
// Log the Resposne
});
};
apnsServiceBroker.OnNotificationSucceeded += (notification) => {
// Log The Response
};
apnsServiceBroker.Start();
foreach (var deviceToken in deviceCatalogs) {
var title = GetTitle(promotion, deviceToken);
//title += DateTime.UtcNow.TimeOfDay.ToString();
var NotificationPayLoadObject = new NotificationPayLoadObjectApple();
NotificationPayLoadObject.aps.alert = title;
NotificationPayLoadObject.aps.badge = 0;
NotificationPayLoadObject.aps.sound = "default";
NotificationPayLoadObject.url = url;
var payLoad = JObject.Parse(JsonConvert.SerializeObject(NotificationPayLoadObject));
apnsServiceBroker.QueueNotification(new ApnsNotification
{
Tag = this,
DeviceToken = deviceToken.UniqueID,
Payload = payLoad
});
}
var fbs = new FeedbackService(config);
fbs.FeedbackReceived += (string deviceToken, DateTime timestamp) =>
{
// This Token is no longer avaialble in APNS
new DeviceCatalogService().DeleteExpiredIosDevice(deviceToken);
};
fbs.Check();
apnsServiceBroker.Stop();
}
And here is the QueueAllGcmDevicesForNotification
private void QueueAllGcmDevicesForNotification(Promotion promotion, string url, List<DeviceCatalog> deviceCatalogs, )
{
var config = new GcmConfiguration(ANDROID_SENDER_ID, ANDROID_SENDER_AUTH_TOKEN, ANDROID_APPLICATION_ID_PACKAGE_NAME);
gcmServiceBroker = new GcmServiceBroker(config);
gcmServiceBroker.OnNotificationFailed += (notification, aggregateEx) => {
aggregateEx.Handle (ex => {
// Log Response
return true;
});
};
gcmServiceBroker.OnNotificationSucceeded += (notification) => {
// Log Response
};
var title = GetTitle(shopexPromotion);
gcmServiceBroker.Start ();
foreach (var regId in deviceCatalogs) {
var NotificationPayLoadObject = new NotificationPayLoadObjectAndriod(url, title, "7", promotion.ImageUrl);
var payLoad = JObject.Parse(JsonConvert.SerializeObject(NotificationPayLoadObject));
gcmServiceBroker.QueueNotification(new GcmNotification
{
RegistrationIds = new List<string> {
regId.UniqueID
},
Data = payLoad
});
}
gcmServiceBroker.Stop();
}
Now When I click the send button. The event will start executing.
The BrodcastToAll function will be called. I am calling BrodcastToIOS devices first and then BrodcatsToAndriod.
Is there any way in which I can call BrodcastToIOS and wait until all the devices have been Queued and notification has been pushed by the library and the call back events fired fully then start executing the BrodcastToAndriod Fucntion ?
What lines of code I need to add ?
also Is there any way to batch the number of devices to be Queued ?
For example.
Let us say I have 1000 Devices
500 IOS
500 Andriod
Can I queue 100, 100,100,100,100 for IOS and when it's done
I queue 100,100,100,100,100 for Andriod.
Any Help is appreciated.
Thanks.
The call to broker.Stop () by default will block until all the notifications from the queue have been processed.

Xamarin: Using HttpClient POST in combination with a dynamic Class

I have some services that require rather complex objects. Every service uses almost the same base object but it needs to be extended for each service.
A simple example:
The Standard Object would be something like:
ContextObject {
params {
Device {
Name: "MyMobileDevice",
ID: 123455691919238
}
}
}
and for my service I need to add some properties under params,
something like:
ContextObject {
params {
Device {
Name: "MyMobileDevice",
ID: 123455691919238
},
requested_employee_id: 112929
}
}
I tried to get this by using JObject and got it working so far but now I cant find a proper example on how to send this object to my server using HttpClient.
Edit:
Here is my full JObject which all Requests need:
public static JObject DefaultContext (string ServiceMethod) {
var Context = new JObject();
Context["version"] = "1.1";
Context["method"] = ServiceMethod;
Context["params"] = JObject.FromObject( new {
Context = JObject.FromObject( new {
User = App.UserSettings.USERNAME,
Password = App.UserSettings.PASSWORD,
SerialNumber = "1234567890", // TODO: use generated id
Locale = "de-DE",
Timestamp = DateTime.Now.ToString("yyyy-MM-ddTHH\\:mm\\:ss.fffzzz"),
Device = JObject.FromObject( new {
DeviceType = "phone",
ProductType = "D6603", // TODO: Get from Device-Info
screen = JObject.FromObject( new {
Density = "xxhdpi", // TODO: Get from Device-Info
resolution = JObject.FromObject( new {
Height = "1920", // TODO: Get from Device-Info
Width = "1080" // TODO: Get from Device-Info
})
}),
version = JObject.FromObject( new {
AppVersion = "myAppVersion", // TODO: Get App-Information LayoutVersion = "1.0"
} )
})
})
});
return mobileContext;
}
For my Requests I need to add parameters under the "params"-Node. Which works with:
mobileContext["params"]["mynewparameter"] = "FOO";
Now I wanted to send this JObject via System.Net.Http-Client to my server with something like this:
var client = new HttpClient ();
client.BaseAddress = new Uri (App.UserSettings.HOST + ":" + App.UserSettings.PORT + App.UserSettings.TYPE);
client.Timeout = 3000;
var context = MyContext.DefaultContext (ServiceMethods.CUSTOMER_LIST_METHOD);
context ["params"] ["myrequestparam"] = "FOO";
var jsonString = JsonConvert.SerializeObject (context);
var responseData = await client.Get???????
Is my general approach correct? How would you do it? Is there a sample on how to handle such dynamic stuff?
I couldn't find a example on how to use httpclient correctly with the Newtonsoft.JSON-Library how far am I from actually working code?

WebConsumer.ProcessUserAuthorization returns null

I use DotNetOpenAuth.
So.. I am getting looking good response which has state Authenticated.
That is fine.
Now I want to get user profile info but always getting NULL.
Here is the code.
private ServiceProviderDescription GetServiceDescription()
{
string ValidateTokenEndPoint = ConfigurationManager.AppSettings["identityOAuthValidateTokenEndPointUrl"];
string ValidateAuthorizationHeaderEndPoint = ConfigurationManager.AppSettings["identityOAuthValidateAuthorizationHeaderEndPointUrl"];
string AccessTokenEndPoint = ConfigurationManager.AppSettings["identityOAuthAccessTokenURL"];
bool UseVersion10A = Convert.ToBoolean(ConfigurationManager.AppSettings["identityOAuthUseVersion10a"]);
string RequestTokenStr = ConfigurationManager.AppSettings["identityOAuthRequestTokenURL"];
string UserAuthStr = ConfigurationManager.AppSettings["identityOAuthAuthorizeUserURL"];
string AccessTokenStr = ConfigurationManager.AppSettings["identityOAuthAccessTokenURL"];
string InvalidateTokenStr = ConfigurationManager.AppSettings["identityOAuthRequestInvalidateTokenURL"];
return new ServiceProviderDescription
{
AccessTokenEndpoint = new MessageReceivingEndpoint(AccessTokenStr, HttpDeliveryMethods.PostRequest),
RequestTokenEndpoint = new MessageReceivingEndpoint(RequestTokenStr, HttpDeliveryMethods.PostRequest),
UserAuthorizationEndpoint = new MessageReceivingEndpoint(UserAuthStr, HttpDeliveryMethods.PostRequest),
TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() },
ProtocolVersion = DotNetOpenAuth.OAuth.ProtocolVersion.V10a
};
}
void GetUserProfile()
{
var tokenManager = TokenManagerFactory.GetTokenManager(TokenManagerType.InMemoryTokenManager);
tokenManager.ConsumerKey = ConfigurationManager.AppSettings["identityOAuthConsumerKey"];
tokenManager.ConsumerSecret = ConfigurationManager.AppSettings["identityOAuthConsumerSecret"];
var serviceDescription = GetServiceDescription();
var consumer = new WebConsumer(serviceDescription, tokenManager);
var result = consumer.ProcessUserAuthorization(response);
if (result != null) // It is always null
{
}
Well I checked 10 times and I am pretty sure that all URLs to create ServiceProviderDescription are correct.
Any clue?
Well
finally check your web.config app keys
add key="identityOAuthConsumerKey" value="put here correct data!!!"
add key="identityOAuthConsumerSecret" value="put here correct data!!!"
and if you use hosts file you have to put correct sitename as well
127.0.0.1 site1.host1.com

Categories