-
Notifications
You must be signed in to change notification settings - Fork 46
/
GraphService.cs
388 lines (337 loc) · 15.5 KB
/
GraphService.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
/*
* Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license.
* See LICENSE in the source repository root for complete license information.
*/
using Microsoft.Graph;
using MicrosoftGraph_Security_API_Sample.Helpers;
using Resources;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
namespace MicrosoftGraph_Security_API_Sample.Models
{
public class GraphService
{
public readonly string GraphBetaBaseUrl = "https://graph.microsoft.com/beta";
public GraphServiceClient graphClient = null;
/// <summary>
/// Initialize the graphClient
/// </summary>
public GraphService()
{
graphClient = SDKHelper.GetAuthenticatedClient();
if (graphClient != null)
{
graphClient.BaseUrl = GraphBetaBaseUrl;
}
}
/// <summary>
/// Get the current user's email address from their profile.
/// </summary>
/// <returns>Email address of the signed in user</returns>
public async Task<string> GetMyEmailAddress()
{
var targetBaseUrl = graphClient.BaseUrl;
graphClient.BaseUrl = this.GraphBetaBaseUrl;
User me = await graphClient.Me.Request().Select("mail,userPrincipalName").GetAsync();
graphClient.BaseUrl = targetBaseUrl;
return me.Mail ?? me.UserPrincipalName;
}
/// <summary>
/// Get additional details about the user to help in investigating the alert
/// </summary>
/// <param name="principalName">User principal name</param>
/// <param name="populatePicture"></param>
/// <param name="populateManager"></param>
/// <param name="populateDevices"></param>
/// <returns>GraphUserModel</returns>
public async Task<GraphUserModel> GetUserDetails(string principalName, bool populatePicture = false, bool populateManager = false, bool populateDevices = false)
{
var graphUrl = graphClient.BaseUrl;
graphClient.BaseUrl = this.GraphBetaBaseUrl;
GraphUserModel userModel = null;
try
{
//var user = await graphClient.Users[principalName].Request().GetAsync();
var user = await graphClient.Users.Request().Filter($"UserPrincipalName eq '{principalName}'").GetAsync();
if (user.Count > 0)
{
userModel = BuildGraphUserModel(user.CurrentPage[0]);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
if (userModel == null)
{
return null;
}
try
{
if (populatePicture)
{
var picture = await graphClient.Users[principalName].Photo.Content.Request().GetAsync();
if (picture != null)
{
MemoryStream picture1 = (MemoryStream)picture;
string pic = "data:image/png;base64," + Convert.ToBase64String(picture1.ToArray(), 0, picture1.ToArray().Length);
userModel.Picture = pic;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
try
{
if (populateManager)
{
var manager = await graphClient.Users[principalName].Manager.Request().GetAsync();
if (!string.IsNullOrEmpty(manager?.Id))
{
userModel.Manager = BuildGraphUserModel(await graphClient.Users[manager.Id].Request().GetAsync());
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
try
{
if (populateDevices)
{
var devices = await graphClient.Users[principalName].RegisteredDevices.Request().GetAsync();
if (devices != null)
{
userModel.RegisteredDevices = await Task.WhenAll(devices.Select(d => GetDeviceById(d.Id)));
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
try
{
if (populateDevices)
{
var devices = await graphClient.Users[principalName].OwnedDevices.Request().GetAsync();
if (devices != null)
{
userModel.OwnedDevices = await Task.WhenAll(devices.Select(d => GetDeviceById(d.Id)));
}
}
}
catch { }
graphClient.BaseUrl = graphUrl;
return userModel;
}
/// <summary>
/// Get additional details about the affected device
/// </summary>
/// <param name="id"></param>
/// <returns>GraphDeviceModel</returns>
public async Task<GraphDeviceModel> GetDeviceById(string id)
{
return BuildRegisteredOwnedeviceModel(await graphClient.Devices[id].Request().GetAsync());
}
/// <summary>
/// Build Registered Owned Device Model
/// </summary>
/// <param name="device"></param>
/// <returns>GraphDeviceModel</returns>
private static GraphDeviceModel BuildRegisteredOwnedeviceModel(Device device)
{
if (device == null)
{
return null;
}
return new GraphDeviceModel
{
Id = device.Id,
DisplayName = device.DisplayName,
IsCompliant = device.IsCompliant,
Os = device.OperatingSystem,
OsVersion = device.OperatingSystemVersion,
IsIntuneManaged = device.IsManaged,
ApproximateLastSignIn = device.ApproximateLastSignInDateTime
};
}
/// <summary>
/// Build Graph User Model
/// </summary>
/// <param name="device"></param>
/// <returns>GraphUserModel</returns>
private static GraphUserModel BuildGraphUserModel(User user)
{
if (user == null)
{
return null;
}
return new GraphUserModel
{
JobTitle = user.JobTitle,
OfficeLocation = user.OfficeLocation,
Email = user.UserPrincipalName,
ContactVia = user.MobilePhone,
DisplayName = user.DisplayName
};
}
/// <summary>
/// Update specific fields of alert
/// </summary>
/// <param name="alert"></param>
/// <param name="updateAlertModel"></param>
/// <returns>the updated alert</returns>
public async Task<Alert> UpdateAlert(Alert alert, UpdateAlertModel updateAlertModel)
{
if (alert == null)
{
throw new ArgumentNullException(nameof(alert));
}
if (!Enum.TryParse<AlertStatus>(updateAlertModel.UpdateStatus, true, out var status))
{
throw new ArgumentOutOfRangeException(nameof(alert.Status));
}
alert.Status = status;
if (!Enum.TryParse<AlertFeedback>(updateAlertModel.Feedback, true, out var feedback))
{
throw new ArgumentOutOfRangeException(nameof(alert.Feedback));
}
alert.Feedback = feedback;
if (!string.IsNullOrEmpty(updateAlertModel.Comments))
{
alert.Comments = updateAlertModel.Comments;
}
alert.AssignedTo = await GetMyEmailAddress();
return await graphClient.Security.Alerts[alert.Id].Request().UpdateAsync(alert);
}
/// <summary>
/// Get alert by Id
/// </summary>
/// <param name="alertId"></param>
/// <returns>Alert</returns>
public async Task<Alert> GetAlertById(string alertId)
{
if (string.IsNullOrEmpty(alertId))
{
return null;
}
return await graphClient.Security.Alerts[alertId].Request().GetAsync();
}
/// <summary>
/// Get alerts based on the alert filters
/// </summary>
/// <param name="filters"></param>
/// <returns>alerts matching the filtering criteria</returns>
public async Task<ISecurityAlertsCollectionPage> GetAlerts(AlertFilter filters)
{
var filteredQuery = string.Empty;
if (!string.IsNullOrEmpty(filters.AssignedToMe) && filters.AssignedToMe.Equals("AssignedToMe", StringComparison.InvariantCultureIgnoreCase))
{
filteredQuery += $"AssignedTo eq '{filters.Email}'";
}
if (filters.Category == null && filters.Provider == null && filters.Status == null && filters.Severity == null)
{
if(filters.Top != null)
{
return await graphClient.Security.Alerts.Request().Top(filters.Top.Value).GetAsync();
}
else
{
return await graphClient.Security.Alerts.Request().Top(1).GetAsync();
}
}
else
{
if (!string.IsNullOrEmpty(filters.Category) && !filters.Category.Equals("All", StringComparison.InvariantCultureIgnoreCase))
{
filteredQuery += (filteredQuery.Length == 0 ? $"Category eq '{filters.Category}'" : $" and Category eq '{filters.Category}'");
}
if (!string.IsNullOrEmpty(filters.Provider) && !filters.Provider.Equals("All", StringComparison.InvariantCultureIgnoreCase))
{
filteredQuery += (filteredQuery.Length == 0 ? $"vendorInformation/provider eq '{filters.Provider}'" : $" and vendorInformation/provider eq '{filters.Provider}'");
}
if (!string.IsNullOrEmpty(filters.Status) && !filters.Status.Equals("All", StringComparison.InvariantCultureIgnoreCase))
{
filteredQuery += (filteredQuery.Length == 0 ? $"Status eq '{filters.Status}'" : $" and Status eq '{filters.Status}'");
}
if (!string.IsNullOrEmpty(filters.Severity) && !filters.Severity.Equals("All", StringComparison.InvariantCultureIgnoreCase))
{
filteredQuery += (filteredQuery.Length == 0 ? $"Severity eq '{filters.Severity}'" : $" and Severity eq '{filters.Severity}'");
}
if (!string.IsNullOrEmpty(filters.HostFqdn))
{
filters.HostFqdn = filters.HostFqdn.ToLower();
filteredQuery += (filteredQuery.Length == 0 ? $"hostStates/any(a:a/fqdn eq '{filters.HostFqdn}')" : $" and hostStates/any(a:a/fqdn eq '{filters.HostFqdn}')");
}
if (!string.IsNullOrEmpty(filters.Upn))
{
filters.Upn = filters.Upn.ToLower();
filteredQuery += (filteredQuery.Length == 0 ? $"userStates/any(a:a/userPrincipalName eq '{filters.Upn}')" : $" and userStates/any(a:a/userPrincipalName eq '{filters.Upn}')");
}
filters.FilteredQuery = filteredQuery;
return await graphClient.Security.Alerts.Request().Filter(filteredQuery).Top(filters.Top.Value).GetAsync();
}
}
/// <summary>
/// Create webhook subscriptions in order to recieve the notifications
/// </summary>
/// <param name="filters"></param>
/// <returns>The subscription object</returns>
public async Task<Subscription> Subscribe(SubscriptionFilters filters)
{
var filteredQuery = string.Empty;
var changeType = "updated";
var resource = "/security/alerts";
var expirationDate = DateTime.UtcNow.AddHours(1);
Random Rand = new Random();
var randno = Rand.Next(1, 100).ToString();
var clientState = "IsgSdkSubscription" + randno;
if (filters.SubscriptionCategory == null && filters.SubscriptionProvider == null && filters.SubscriptionSeverity == null && !string.IsNullOrEmpty(filters.SubscriptionHostFqdn) && !string.IsNullOrEmpty(filters.SubscriptionUpn))
{
return null;
}
else
{
if (!string.IsNullOrEmpty(filters.SubscriptionCategory) && !filters.SubscriptionCategory.Equals("All", StringComparison.InvariantCultureIgnoreCase))
{
filteredQuery += (filteredQuery.Length == 0 ? $"Category eq '{filters.SubscriptionCategory}'" : $" and Category eq '{filters.SubscriptionCategory}'");
}
if (!string.IsNullOrEmpty(filters.SubscriptionProvider) && !filters.SubscriptionProvider.Equals("All", StringComparison.InvariantCultureIgnoreCase))
{
filteredQuery += (filteredQuery.Length == 0 ? $"vendorInformation/provider eq '{filters.SubscriptionProvider}'" : $" and vendorInformation/provider eq '{filters.SubscriptionProvider}'");
}
if (!string.IsNullOrEmpty(filters.SubscriptionSeverity) && !filters.SubscriptionSeverity.Equals("All", StringComparison.InvariantCultureIgnoreCase))
{
filteredQuery += (filteredQuery.Length == 0 ? $"Severity eq '{filters.SubscriptionSeverity}'" : $" and Severity eq '{filters.SubscriptionSeverity}'");
}
if (!string.IsNullOrEmpty(filters.SubscriptionHostFqdn))
{
filteredQuery += (filteredQuery.Length == 0 ? $"hostStates/any(a:a/fqdn eq '{filters.SubscriptionHostFqdn}')" : $" and hostStates/any(a:a/fqdn eq '{filters.SubscriptionHostFqdn}')");
}
if (!string.IsNullOrEmpty(filters.SubscriptionUpn))
{
filteredQuery += (filteredQuery.Length == 0 ? $"userStates/any(a:a/userPrincipalName eq '{filters.SubscriptionUpn}')" : $" and userStates/any(a:a/userPrincipalName eq '{filters.SubscriptionUpn}')");
}
resource += $"?$filter={filteredQuery}";
Subscription subscription = new Subscription()
{
ChangeType = changeType,
NotificationUrl = ConfigurationManager.AppSettings["ida:NotificationUrl"],
Resource = resource,
ExpirationDateTime = expirationDate,
ClientState = clientState
};
return await graphClient.Subscriptions.Request().AddAsync(subscription);
}
}
}
}