/
Engine.cs
938 lines (754 loc) · 45.8 KB
/
Engine.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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.ServiceModel;
using System.Threading;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using XORCISMModel;
using XCommon;
using NCrontab;
namespace XManagerService
{
public class Engine
{
/// <summary>
/// Copyright (C) 2012-2015 Jerome Athias
/// Windows Service managing Agents (bots), Managing Sessions (groups of Jobs) of Plugins (connectors to Tools/Services) interacting with an XORCISM database
/// All trademarks and registered trademarks are the property of their respective owners.
/// This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
///
/// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
///
/// You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
/// </summary>
private Thread m_Thread;
//public Dictionary<int, Thread> ListRunningSessionThread
//{
// get { return m_ListRunningSessionThread; }
// set { m_ListRunningSessionThread = value; }
//}
private class LaunchSessionThreadInfo
{
public int SessionID;
public Thread Thread;
public List<JOB> ListJob;
public LaunchSessionThreadInfo(int sessionID, Thread thread)
{
this.SessionID = sessionID;
this.Thread = thread;
this.ListJob = new List<JOB>();
}
}
private Dictionary<int, LaunchSessionThreadInfo> m_ListRunningSessionThread;
public Engine()
{
}
public void Start()
{
// ==================================================================
// Recovery mode : start again any previously running session threads
// ==================================================================
XORCISMEntities context;
context = new XORCISMEntities();
// Explicitly open the connection.
//context.Connection.Open();
#region RecoveryMode
try
{
string status;
status = XCommon.STATUS.RUNNING.ToString();
//Search in the database the Sessions with a Status of "Running"
var runningSessions = from s in context.SESSION
where s.Status == status
select s;
//If any
if (runningSessions.Count() > 0)
{
//For each of the "Running" Sessions
foreach (SESSION oneSession in runningSessions.ToList())
{
//Depending on the ServiceCategory of the Session
switch (oneSession.ServiceCategoryID)
{
case 8: //HARDCODED
{
//Monitoring
//Dealing with the previous jobs
//Searching the Jobs attached to the current Session
var query = from j in context.JOB
where j.SessionID == oneSession.SessionID
select j;
//Marks all the Session's Jobs as FINISHED
foreach (JOB oneJob in query.ToList())
{
oneJob.Status = XCommon.STATUS.FINISHED.ToString();
context.SaveChanges();
}
Utils.Helper_Trace("MANAGER ENGINE", string.Format("Session {0} will be recovered", oneSession.SessionID));
//Marks the Session's status as IDLE (so it will be (re)started)
oneSession.Status = XCommon.STATUS.IDLE.ToString();
Utils.Helper_Trace("MANAGER ENGINE", "TRACE4");
context.SaveChanges();
break;
}
default:
{
//Canceling the session (changing status)
Utils.Helper_Trace("MANAGER ENGINE", string.Format("Session {0} TOCANCEL", oneSession.SessionID));
oneSession.Status = XCommon.STATUS.TOCANCEL.ToString();
context.SaveChanges();
break;
}
}
}
}
}
catch (ThreadAbortException exThreadAbort)
{
Utils.Helper_Trace("MANAGER ENGINE", string.Format("ThreadError in recovery : Exception = {0}", exThreadAbort.Message));
return;
}
catch (Exception ex)
{
Utils.Helper_Trace("MANAGER ENGINE", string.Format("Error in recovery : Exception = {0} - {1}", ex.Message, ex.InnerException));
// return;
}
#endregion RecoveryMode
// ==============================
// Create the main polling thread
// ==============================
Utils.Helper_Trace("MANAGER ENGINE", "Launching main polling thread");
m_ListRunningSessionThread = new Dictionary<int, LaunchSessionThreadInfo>();
m_Thread = new Thread(new ThreadStart(FuncThread));
m_Thread.Start();
}
private void FuncThread()
{
XORCISMEntities context;
context = new XORCISMEntities();
// Explicitly open the connection.
//context.Connection.Open();
// =================
// Main polling loop
// =================
try
{
while (true) //Infinite loop
{
// =============================================================================
// PHASE 0 : Look in table SESSION and let's see if there is something to cancel
// =============================================================================
#region Phase0
//Utils.Helper_Trace("MANAGER ENGINE", "Looking for new session to cancel (those with status = 'ToCancel')");
string status;
status = XCommon.STATUS.TOCANCEL.ToString();
XORCISMModel.SESSION cancelSession;
cancelSession = context.SESSION.FirstOrDefault(s => s.Status == status);
if (cancelSession != null)
{
// ===============================
// Abort the Launch Session thread
// ===============================
if (m_ListRunningSessionThread.ContainsKey(cancelSession.SessionID) == true)
{
LaunchSessionThreadInfo info;
info = m_ListRunningSessionThread[cancelSession.SessionID];
Thread musCanceledThread;
musCanceledThread = info.Thread;
musCanceledThread.Abort(cancelSession.SessionID.ToString());
// ==============================
// Launch a Cancel Session thread
// ==============================
Utils.Helper_Trace("MANAGER ENGINE", string.Format("Launching cancel session thread (sessionID={0})", cancelSession.SessionID));
cancelSession.Status = XCommon.STATUS.CANCELLING.ToString();
context.SaveChanges();
ParameterizedThreadStart ts;
ts = new ParameterizedThreadStart(FuncThreadCancelSession);
Thread thread;
thread = new Thread(ts);
thread.Start(info);
}
else
{
//Canceling after Manager crash/reboot
//Session is not in m_ListRunningSessionThread
Utils.Helper_Trace("MANAGER ENGINE", string.Format("Session {0} must be canceled", cancelSession.SessionID));
//int accountID;
//accountID = (int)model.USERACCOUNT.FirstOrDefault(o => o.UserID == session.UserID).AccountID;
// =============================
// Cancel the jobs on the agents
// =============================
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : CANCELSESSION : Cancelling jobs on agents", cancelSession.SessionID));
var jobs = from jc in context.JOB
where jc.SessionID == cancelSession.SessionID
select jc;
foreach (JOB J in jobs.ToList())
{
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : CANCELSESSION : Handling job {1}", cancelSession.SessionID, J.JobID));
// ====================================
// Contact the agent and cancel the job
// ====================================
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : CANCELSESSION : Trying to contact the agent", cancelSession.SessionID));
try
{
ServiceReferenceAgent.Service1Client service;
service = new ServiceReferenceAgent.Service1Client();
// TODO :
// service.Endpoint.Address = bestAgent.IPAddress;
service.CancelJob(J.JobID);
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : CANCELSESSION : The agent has been successfully contacted", cancelSession.SessionID));
}
catch (Exception ex)
{
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : CANCELSESSION : Error contacting the agent. Exception = {1} {2}", cancelSession.SessionID, ex.Message, ex.InnerException));
XCommon.Utils.Helper_SendEmail("athiasjerome@gmail.com", "MANAGER ENGINE ERROR", "CANCELSESSION : Error contacting the agent. Exception =" + ex.Message + " " + ex.InnerException);
//return;
}
}
// =============================
// Update table SESSION (Status)
// =============================
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : CANCELSESSION : Updating status in table SESSION to CANCELED", cancelSession.SessionID));
try
{
cancelSession.Status = XCommon.STATUS.CANCELED.ToString();
cancelSession.DateEnd = DateTimeOffset.Now;
context.SaveChanges();
}
catch (Exception ex)
{
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : CANCELSESSION : Error CANCELED. Exception = {1}", cancelSession.SessionID, ex.Message));
//return;
}
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : CANCELSESSION : Finished", cancelSession.SessionID));
}
}
#endregion Phase0
// =============================================================================
// PHASE 1 : Look in table SESSION and let's see if there is something to launch
// =============================================================================
Utils.Helper_Trace("MANAGER ENGINE", "Looking for new session to start (status IDLE)"); //DO NOT COMMENT THIS LINE
string Statut = XCommon.STATUS.IDLE.ToString();
var session = context.SESSION.FirstOrDefault(s => s.Status == Statut);
if (session != null)
{
int sessionID;
sessionID = session.SessionID;
//Check if the Account and User are still valid
USERACCOUNT user = null;
user = context.USERACCOUNT.SingleOrDefault(o => o.UserID == session.UserID);
if (user.ACCOUNT.ValidUntilDate!=null && user.ACCOUNT.ValidUntilDate < DateTimeOffset.Now)
{
Utils.Helper_Trace("MANAGER ENGINE", string.Format("Account not valid for session {0}", sessionID));
Utils.Helper_Trace("MANAGER ENGINE", string.Format("Changing session (sessionID={0}) to CANCELED", sessionID));
session.Status = XCommon.STATUS.CANCELED.ToString();
context.SaveChanges();
}
else
{
if (m_ListRunningSessionThread.ContainsKey(sessionID) == true)
{
Utils.Helper_Trace("MANAGER ENGINE", string.Format("Session {0} is supposed to be launched but a thread is already running for this session !", sessionID));
}
else
{
// =======================
// Launch a session thread
// =======================
Utils.Helper_Trace("MANAGER ENGINE", string.Format("Launching session (sessionID={0})", sessionID));
session.Status = XCommon.STATUS.RUNNING.ToString();
context.SaveChanges();
ParameterizedThreadStart managerThreadStart;
managerThreadStart = new ParameterizedThreadStart(FuncThreadLaunchSession);
Thread thread;
thread = new Thread(managerThreadStart);
LaunchSessionThreadInfo info;
info = new LaunchSessionThreadInfo(sessionID, thread);
thread.Start(info);
// ========================
// Put it in the dictionary
// ========================
m_ListRunningSessionThread.Add(sessionID, info);
}
}
}
// ===================================================================================
// PHASE 2 : Look in table SESSIONCRON and let's see if we have to create new sessions
// ===================================================================================
Statut = XCommon.STATUS.IDLE.ToString();
var q = context.SESSIONCRON.Where(o => o.Status == Statut);
foreach (SESSIONCRON sessionCron in q.ToList())
{
if (sessionCron.DateEnd==null || sessionCron.DateEnd > DateTime.Now)
{
//Check if the Account and User are still valid
USERACCOUNT user = null;
user = context.USERACCOUNT.SingleOrDefault(o => o.UserID == sessionCron.UserID);
if (user.ACCOUNT.ValidUntilDate != null && user.ACCOUNT.ValidUntilDate < DateTimeOffset.Now)
{
//Utils.Helper_Trace("MANAGER ENGINE", string.Format("Account not valid for entry {0} in table SESSIONCRON", sessionCron.SessionCronID));
}
else
{
CrontabSchedule schedule;
schedule = CrontabSchedule.Parse(sessionCron.CronExpression);
DateTimeOffset start = DateTimeOffset.Now;
DateTimeOffset end = start + TimeSpan.FromDays(2 * 360);
var occurrence = schedule.GetNextOccurrences(start, end).GetEnumerator();
occurrence.MoveNext();
// Utils.Helper_Trace("MANAGER ENGINE", "SessionCron "+sessionCron.SessionCronID+" Next occurrence=" + occurrence.Current.DayOfWeek.ToString() + " " + occurrence.Current.Day.ToString() + "/" + occurrence.Current.Month.ToString() + "/" + occurrence.Current.Year.ToString() + " " + occurrence.Current.Hour.ToString() + "H" + occurrence.Current.Minute.ToString() + ":" + occurrence.Current.Second.ToString());
TimeSpan ts;
ts = occurrence.Current - start;
if (ts.TotalSeconds <= 5.0)
{
Utils.Helper_Trace("MANAGER ENGINE", string.Format("Cron expression for entry {0} in table SESSIONCRON has triggered an execution", sessionCron.SessionCronID));
// ================================
// Extract and parse the parameters
// ================================
Dictionary<string, object> dicoParameters;
try
{
MemoryStream ms;
ms = new MemoryStream(sessionCron.Parameters);
BinaryFormatter bf;
bf = new BinaryFormatter();
dicoParameters = (Dictionary<string, object>)bf.Deserialize(ms);
}
catch (Exception e)
{
Utils.Helper_Trace("MANAGER SERVICE", string.Format("Exception while deserializing parameters : {0}", e.Message));
return;
}
int[] tabAssetID = null;
if (dicoParameters["ASSETS"] != null)
tabAssetID = (int[])dicoParameters["ASSETS"];
// ================================
// Add a new entry in table SESSION
// ================================
Utils.Helper_Trace("MANAGER ENGINE", string.Format("Adding an entry in table SESSION"));
SESSION tmpSession = new SESSION();
//xxx
try
{
tmpSession.UserID = sessionCron.UserID;
tmpSession.Status = XCommon.STATUS.IDLE.ToString();
tmpSession.ServiceCategoryID = sessionCron.ServiceCategoryID;
tmpSession.DateStart = DateTimeOffset.Now;
tmpSession.DateEnd = null;
tmpSession.Parameters = sessionCron.Parameters;
tmpSession.SessionCronID = sessionCron.SessionCronID;
context.SESSION.Add(tmpSession);
context.SaveChanges();
//xxx
}
catch (Exception ex)
{
//xxx
Utils.Helper_Trace("MANAGER ENGINE", string.Format("Error adding entry in table SESSION : Exception = {0} - {1}", ex.Message, ex.InnerException.Message));
throw ex;
}
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SessionID = {0}", tmpSession.SessionID));
// ============================================
// Add several entries in table ASSETSESSION
// ============================================
if (tabAssetID != null)
{
Utils.Helper_Trace("MANAGER ENGINE", string.Format("Adding {0} entries in table ASSETSESSION", tabAssetID.Count()));
try
{
foreach (int assetID in tabAssetID)
{
ASSETSESSION tmpAinS = new ASSETSESSION();
tmpAinS.SESSION = tmpSession;
tmpAinS.AssetID = assetID;
context.ASSETSESSION.Add(tmpAinS);
}
context.SaveChanges();
}
catch (Exception ex)
{
Utils.Helper_Trace("MANAGER ENGINE", string.Format("Error adding entries in table ASSETSESSION : Exception = {0}", ex.Message));
throw ex;
}
}
}
}
}
}
// =====
// Sleep
// =====
Thread.Sleep(5000); //Hardcoded
}
}
catch (ThreadAbortException exThreadAbort)
{
//int SessionId;
//SessionId=Convert.ToInt32((string)exThreadAbort.ExceptionState);
//XORCISMModel.SESSION musBeCanceledSession;
//musBeCanceledSession=context.SESSION.SingleOrDefault(s => s.SessionID == SessionId);
//if (musBeCanceledSession != null)
//{
// musBeCanceledSession.Status = XCommon.STATUS.TOCANCEL.ToString();
// context.SaveChanges();
//}
Utils.Helper_Trace("MANAGER ENGINE", string.Format("ThreadError in main polling loop : Exception = {0}", exThreadAbort.Message));
//HARDCODED
XCommon.Utils.Helper_SendEmail("contact@hackenaton.org", "ThreadError in XManager", "MyException = " + exThreadAbort.Message + " " + exThreadAbort.InnerException);
return;
}
catch (Exception ex)
{
Utils.Helper_Trace("MANAGER ENGINE", string.Format("Error in main polling loop : Exception = {0} {1}", ex.Message, ex.InnerException));
//HARDCODED
XCommon.Utils.Helper_SendEmail("contact@hackenaton.org", "Error in XManager", "MyException = " + ex.Message + " " + ex.InnerException);
return;
}
}
private void FuncThreadLaunchSession(object context)
{
LaunchSessionThreadInfo info;
info = (LaunchSessionThreadInfo)context;
int sessionID;
sessionID = info.SessionID;
XORCISMEntities model = new XORCISMEntities();
SESSION session;
session = model.SESSION.SingleOrDefault(o => o.SessionID == sessionID);
int accountID;
accountID = (int)model.USERACCOUNT.FirstOrDefault(o => o.UserID == session.UserID).AccountID;
// ===========================================
// Determine the providers that we have to use
// ===========================================
var category = (from sessions in model.SESSION
where sessions.SessionID == sessionID
select sessions.ServiceCategoryID).First();
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : ServiceCategoryID is {1} AccountID is {2}", sessionID, category.Value, accountID));
var ListProvider = from provider in model.PROVIDER
where provider.ServiceCategoryID == category && provider.PROVIDERSFORACCOUNT.Any(o => o.AccountID == accountID && o.ValidUntil >= DateTimeOffset.Now)
select provider.ProviderID;
List<int> listProviderID;
listProviderID = ListProvider.ToList<int>();
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Session will use {1} providers", sessionID, listProviderID.Count));
int nbjoberror = 0;
if (listProviderID.Count > 0)
{
// ================================
// Add several entries in table JOB
// ================================
var ListAssetInSession = from AinS in model.ASSETSESSION
where AinS.SessionID == sessionID
select AinS.AssetSessionID;
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Session involves {1} assets", sessionID, ListAssetInSession.Count()));
int count;
count = ListAssetInSession.Count() * listProviderID.Count;
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Adding {1} entries in table JOB", sessionID, count));
var param = from o in model.SESSION
where o.SessionID == sessionID
select o.Parameters;
if (ListAssetInSession.Count() != 0)
{
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Case 1", sessionID));
foreach (int AinSID in ListAssetInSession)
{
foreach (int providerID in listProviderID)
{
try
{
JOB job = new JOB();
job.AssetSessionID = AinSID;
job.ProviderID = providerID;
job.DateStart = DateTimeOffset.Now;
job.Status = XCommon.STATUS.IDLE.ToString();
job.Parameters = param.First();
job.SessionID = sessionID;
model.JOB.Add(job);
//model.AddToJOB(job);
//model.SaveChanges();
info.ListJob.Add(job);
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Added Job {1}", sessionID, job.JobID));
}
catch (Exception e1)
{
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Exception AddingJob1 "+e1.Message+" "+e1.InnerException, sessionID));
}
}
}
model.SaveChanges();
}
else
{
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Case 2", sessionID));
switch ((int)category.Value)
{
case 10:
//nmap discovery
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : nmap discovery", sessionID));
break;
case 11:
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : import nessus", sessionID));
break;
case 14:
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : import netsparker", sessionID));
break;
case 15:
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : import acunetix", sessionID));
break;
default:
return;
}
foreach (int providerID in listProviderID)
{
try
{
JOB job = new JOB();
job.AssetSessionID = null;
job.ProviderID = providerID;
job.DateStart = DateTimeOffset.Now;
job.Status = XCommon.STATUS.IDLE.ToString();
job.Parameters = param.First();
job.SessionID = sessionID;
//model.JOB.AddObject(job);
model.JOB.Add(job);
model.SaveChanges();
info.ListJob.Add(job);
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Added Job {1}", sessionID, job.JobID));
}
catch (Exception e1)
{
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Exception AddingJob2 " + e1.Message + " " + e1.InnerException, sessionID));
}
}
}
//model.SaveChanges();
// =========================================
// Dispatch the jobs on the available agents
// =========================================
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Dispatching jobs on agents", sessionID));
foreach (JOB J in info.ListJob)
{
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Handling job {1}", sessionID, J.JobID));
// ======================================================
//TODO Get the agent with the lowest load (loadbalancing)
// ======================================================
//TODO
/*
var agent = from Ag in model.AGENT
where Ag.Status == "ENABLED"
select Ag;
if (agent == null)
{
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : There is no agent with status ENABLED", sessionID));
return;
}
*/
//TODO
/*
var bestAgent = agent.ToList().OrderBy(c => c.Load).First();
bestAgent.Load++;
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : The best agent for this job is at {1} ({2})", sessionID, bestAgent.AgentID, bestAgent.IPAddress));
*/
// ====================================
// Contact the agent and launch the job
// ====================================
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Trying to contact the agent", sessionID));
try
{
ServiceReferenceAgent.Service1Client service;
service = new ServiceReferenceAgent.Service1Client();
// TODO :
// service.Endpoint.Address = bestAgent.IPAddress; // TODO
service.LaunchJob((Guid)session.UserID, J.JobID);
}
catch (Exception ex)
{
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Error contacting the agent. Exception = {1}", sessionID, ex.Message));
//HARDCODED
XCommon.Utils.Helper_SendEmail("athiasjerome@gmail.com", "MANAGER ENGINE ERROR", "THREADLAUNCHSESSION : Error contacting the agent. Exception =" + ex.Message + " " + ex.InnerException);
return;
}
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : The agent has been successfully contacted", sessionID));
// =====================================
//TODO Update table JOB (column AgentID)
// =====================================
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : TODO Updating table JOB (AgentID column)", sessionID));
//TODO
//J.AgentID = bestAgent.AgentID;
//TODO: TryCatch
model.SaveChanges();
}
// =================================
// Wait until all jobs have finished
// =================================
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Waiting until all jobs have finished", sessionID));
try
{
bool bFinished = false;
do
{
Thread.Sleep(10000); //HARDCODED
bFinished = true;
nbjoberror = 0;
// Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : There are {1} jobs in this session", sessionID, info.ListJob.Count.ToString()));
var myCurrentSession = from Sess in model.SESSION
where Sess.SessionID == sessionID
select Sess;
SESSION CurrentSession = myCurrentSession.ToList().First();
foreach (JOB J in info.ListJob)
{
int AllJobs = 0;
// ==========================
// Get the status of this job
// ==========================
var MyJob = from MyJobs in model.JOB
where MyJobs.JobID == J.JobID
select MyJobs.Status;
string jobStatus = (string)MyJob.ToList().First();
if (jobStatus != XCommon.STATUS.FINISHED.ToString() && jobStatus != XCommon.STATUS.ERROR.ToString())
{
bFinished = false;
break;
}
else
{
if (jobStatus == XCommon.STATUS.ERROR.ToString())
{
nbjoberror++;
}
AllJobs++;
}
int pourcent = (100 / (int)MyJob.Count()) * AllJobs;
// CurrentSession.Status = pourcent + "%";
//model.SaveChanges();
}
}
while (bFinished == false);
}
catch (ThreadAbortException ex)
{
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Thread has been aborted", sessionID));
Utils.Helper_Trace("MANAGER ENGINE", string.Format("ThreadAbortException : Exception = {0}", ex.Message));
return;
}
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : All jobs have finished ({1} Errors)", sessionID, nbjoberror));
}
// =============================
// Update table SESSION (Status)
// =============================
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Updating status in table SESSION", sessionID));
var mySession = from Sess in model.SESSION
where Sess.SessionID == sessionID
select Sess;
SESSION MySession = mySession.ToList().First();
string additionalmailMessage = string.Empty;
//Dealing with jobs in error
if (info.ListJob.Count == nbjoberror)
{
//TODO xxx
MySession.Status = XCommon.STATUS.ERROR.ToString();
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : All jobs in error: xxx", sessionID));
//TODO xxx
}
else
{
MySession.Status = XCommon.STATUS.FINISHED.ToString();
}
MySession.DateEnd = DateTimeOffset.Now;
model.SaveChanges();
// ============
// Notification
// ============
//TODO
//XCommon.Utils.Helper_Notify(session.UserID.Value, "TASK_JOB", sessionID.ToString(), XCommon.RIGHT.MODIFY);
//TODO
/*
string mailMessage = "Hello "+ session.aspnet_Membership.USERS.UserName +". Your Hackenaton session " + sessionID + " ("+ MySession.SERVICECATEGORY.ServiceCategoryName +") is completed with the status: "+ MySession.Status+". Assets scanned: "; //HARDCODED
var myAssets = from assets in model.ASSET
join assetinsess in model.ASSETSESSION on assets.AssetID equals assetinsess.AssetID
where assetinsess.SessionID == sessionID
select assets;
foreach (ASSET ass in myAssets)
{
//TODO ipaddressIPv4
mailMessage += ass.ipaddressIPv4 + " ";
}
mailMessage += "Completed in " + string.Format("{0:00}:{1:00}:{2:00}", (MySession.DateEnd.Value - MySession.DateStart.Value).Hours, (MySession.DateEnd.Value - MySession.DateStart.Value).Minutes, (MySession.DateEnd.Value - MySession.DateStart.Value).Seconds);
mailMessage +=". Visit the Hackenaton website to display the Report.";
mailMessage += additionalmailMessage;
XCommon.Utils.Helper_SendEmail(session.aspnet_Membership.Email, "Hackenaton scan finished", mailMessage); //HARDCODED
*/
m_ListRunningSessionThread.Remove(sessionID);
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADLAUNCHSESSION : Finished", sessionID));
}
private void FuncThreadCancelSession(object context)
{
LaunchSessionThreadInfo info;
info = (LaunchSessionThreadInfo)context;
int sessionID;
sessionID = info.SessionID;
XORCISMEntities model = new XORCISMEntities();
SESSION session;
session = model.SESSION.SingleOrDefault(o => o.SessionID == sessionID);
//int accountID;
//accountID = (int)model.USERACCOUNT.FirstOrDefault(o => o.UserID == session.UserID).AccountID;
// =============================
// Cancel the jobs on the agents
// =============================
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADCANCELSESSION : Cancelling jobs on agents", sessionID));
foreach (JOB J in info.ListJob)
{
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADCANCELSESSION : Handling job {1}", sessionID, J.JobID));
// ====================================
// Contact the agent and cancel the job
// ====================================
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADCANCELSESSION : Trying to contact the agent", sessionID));
try
{
ServiceReferenceAgent.Service1Client service;
service = new ServiceReferenceAgent.Service1Client();
// TODO :
// service.Endpoint.Address = bestAgent.IPAddress;
service.CancelJob(J.JobID);
}
catch (Exception ex)
{
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADCANCELSESSION : Error contacting the agent. Exception = {1} {2}", sessionID, ex.Message, ex.InnerException));
//HARDCODED
XCommon.Utils.Helper_SendEmail("athiasjerome@gmail.com", "MANAGER ENGINE ERROR", "THREADCANCELSESSION : Error contacting the agent. Exception ="+ex.Message+" "+ex.InnerException);
return;
}
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADCANCELSESSION : The agent has been successfully contacted", sessionID));
}
// =============================
// Update table SESSION (Status)
// =============================
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADCANCELSESSION : Updating status in table SESSION to CANCELED", sessionID));
var mySession = from Sess in model.SESSION
where Sess.SessionID == sessionID
select Sess;
SESSION MySession = mySession.ToList().First();
MySession.Status = XCommon.STATUS.CANCELED.ToString();
MySession.DateEnd = DateTimeOffset.Now;
model.SaveChanges();
try
{
m_ListRunningSessionThread.Remove(sessionID);
}
catch (Exception ex)
{
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADCANCELSESSION : Error m_ListRunningSessionThread.Remove. Exception = {1}", sessionID, ex.Message));
return;
}
Utils.Helper_Trace("MANAGER ENGINE", string.Format("SESSION {0} : THREADCANCELSESSION : Finished", sessionID));
}
private void service_LaunchJobCompleted(object sender, AsyncCompletedEventArgs e)
{
}
}
}