-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
1589 lines (1486 loc) · 61.9 KB
/
index.js
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
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/// <reference path="../App.js" />
(function () {
'use strict'
// default confirmation message
var KB4_DEFAULT_CONFIRMATION_MSG = 'Are you sure you want to report this as a phishing email?'
var KB4_REPORT_EMAIL_US = '[email protected]'
var KB4_REPORT_EMAIL_EU = '[email protected]'
var KB4_RESPONSE_CRID_NOT_FOUND = 'CRID NOT GIVEN'
var KB4_TASKPANE_URL_MARKER = 'TASKPANEHOME.HTML'
// The following should have been CONST or LET declarations, but some old IE versions don't allow these keywords.
var EMAIL_CONTENT_TYPE_MARKER = 'CONTENT-TYPE'
var EMAIL_WINMAIL_MARKER = 'WINMAIL.DAT'
var EMAIL_CONTENT_TRANSFER_MARKER = 'CONTENT-TRANSFER-ENCODING'
var EMAIL_BINARY_CONTENT_MARKER = 'BINARY'
var EMAIL_MIME_VERSION_MARKER = 'MIME-VERSION'
var OK_DEFAULT_TEXT = 'Ok'
var PABV1_COMPLETE_NO_HEADERS = 0
var PABV1_COMPLETE_NO_FORWARD_ADDRESS = 1
var PABV1_STATUS_PROCESSING = 0
var EWS_MAX_SIZE_LIMIT_ASSUMED = 750000 // 3/4 of 1M, assumed as thoretical limit of EWS transactions. (1M is assumed at 1,000,000)
var isTotalItemSizeBeyondLimit = false
var KB4_SETTINGS_PULL_INTERVAL_IN_SECONDS = 60 // Will pull settings once every 60 seconds.
var KB4_SETTINGS_DEFAULT_DISPLAY_DURATION = 3000
var forwardingData
var environmentData
var userEmailAddress
var currentMessageSender = ''
var changeKey // retrieved in getItemDataCallback, used for deleting the email
var headerText
var _settings
var show_message_report_pst // bool; show 'congratulations' prompt for submitting
var message_report_pst // congratulations prompt text
var show_message_report_non_pst // bool; show 'congratulations' prompt for submitting simulated phishing atttempt
var message_report_non_pst // congratulations prompt text for simulated phishing atttempt
var report_button_text
var ok_button_text = OK_DEFAULT_TEXT
var report_group_text
var attachmentTooLargePrefix = 'Email Content Too Large To Send'
var simulatedPhishing
var confirmation_message = KB4_DEFAULT_CONFIRMATION_MSG
var pab_localized_terms
var KB4_REPORT_EMAIL_US = '[email protected]'
var KB4_REPORT_EMAIL_EU = '[email protected]'
// The following should have been CONST or LET declarations, but some old IE versions don't allow these keywords.
var EMAIL_CONTENT_TYPE_MARKER = 'CONTENT-TYPE'
var EMAIL_WINMAIL_MARKER = 'WINMAIL.DAT'
var EMAIL_CONTENT_TRANSFER_MARKER = 'CONTENT-TRANSFER-ENCODING'
var EMAIL_BINARY_CONTENT_MARKER = 'BINARY'
var EMAIL_MIME_VERSION_MARKER = 'MIME-VERSION'
// AsyncDialog variables.
var notifDialog
var isToDeleteEmail = false
var isCloseDialog = false
var timeout_report_pst = ''
var displayDurationInMs = KB4_DEFAULT_CONFIRMATION_MSG
var PABV1_KB4_URLMARKER = 'APPREAD/HOME/'
var enable_forwarding = false
function ForwardingData(email, subject) {
this.email = email
this.subject = subject
};
// The Office initialize function must be run each time a new page is loaded
Office.initialize = function (reason) {
var userProfile = Office.context.mailbox.userProfile
var item = Office.cast.item.toItemRead(Office.context.mailbox.item)
// Record email details first
if (item.itemType === Office.MailboxEnums.ItemType.Message) {
currentMessageSender = Office.cast.item.toMessageRead(item).from
} else if (item.itemType === Office.MailboxEnums.ItemType.Appointment) {
currentMessageSender = Office.cast.item.toAppointmentRead(item).organizer
}
userEmailAddress = userProfile.emailAddress
// Initialization of add-in, acquiring KB4-based settings.
app.initialize()
getEnvironmentData()
getAddinSettings()
$(document).ready(function () {
displayItemDetails()
})
}
/**
* Requests configuration data from the KnowBe4 server, and stores it in the Office.roamingsettings facility.
*
* @return {void}
*/
function getAddinSettings() {
var lastSettingsCallDateTime = null
var tmpLocalterms = null
var callWebServer = true
var licensekey = getLicenseKey()
var serverLocation = getServerLocation()
// Initialize instance variables to access API objects.
_settings = Office.context.roamingSettings
// If the time of the last call to the web server to get user settings is older than 60 seconds, '
// do a fresh call to the webserver
lastSettingsCallDateTime = _settings.get('lastSettingsCallDateTime')
// Force a getaddin settings if the localterms is also null.
tmpLocalterms = _settings.get('pab_localized_terms')
if (lastSettingsCallDateTime == null || tmpLocalterms == null) {
callWebServer = true
} else {
// Do date/time comparison
try {
// Set a date and get the milliseconds
var settingsDateTime = new Date(lastSettingsCallDateTime)
var currentDateTime = new Date(Date())
// Get the difference in milliseconds.
var interval = Math.floor((currentDateTime.getTime() - settingsDateTime.getTime()) / 1000)
callWebServer = (interval > KB4_SETTINGS_PULL_INTERVAL_IN_SECONDS)
} catch (e) {
callWebServer = true
}
}
if (callWebServer == true) {
$.ajax({
type: 'POST',
url: serverLocation + '/api/v1/phishalert/addin_initialized',
async: true,
context: this,
headers: { 'Access-Control-Allow-Origin': '*' },
data: {
addin_version: encodeURI(environmentData.addin_version),
auth_token: encodeURI(licensekey),
os_name: encodeURI(environmentData.os_name),
os_version: encodeURI(environmentData.os_version),
os_architecture: encodeURI(environmentData.os_architecture),
os_locale: encodeURI(environmentData.os_locale),
outlook_version: environmentData.outlook_version,
machine_guid: encodeURI(environmentData.machine_guid),
sender_email: encodeURI(userEmailAddress)
},
success: function (data) {
var myData = JSON.parse(data)
show_message_report_pst = myData.data.show_message_report_pst
message_report_pst = myData.data.message_report_pst
show_message_report_non_pst = myData.data.show_message_report_non_pst
message_report_non_pst = myData.data.message_report_non_pst
report_button_text = myData.data.report_button_text
report_group_text = myData.data.report_group_text
confirmation_message = myData.data.confirmation_message || KB4_DEFAULT_CONFIRMATION_MSG
timeout_report_pst = myData.data.timeout_report_pst
enable_forwarding = myData.data.enable_forwarding
pab_localized_terms = myData.data.PABLocalizedTerms
attachmentTooLargePrefix = pab_localized_terms.CommonTerms.TooLargePrefix
ok_button_text = pab_localized_terms.CommonTerms.Ok
// Initialize notification mechanism of PAB-Exchange
app.setupNotificationBlob(pab_localized_terms)
$('th#subjectLabel').text(pab_localized_terms.CommonTerms.Subject + ':')
$('th#fromLabel').text(pab_localized_terms.CommonTerms.From + ':')
$('#buttonReport').prop('value', report_button_text)
$('#apptitle').text(report_group_text)
$('#confirmation-message').text(confirmation_message)
// save settings
_settings.set('lastSettingsCallDateTime', Date())
_settings.set('show_message_report_pst', show_message_report_pst)
_settings.set('message_report_pst', message_report_pst)
_settings.set('show_message_report_non_pst', show_message_report_non_pst)
_settings.set('message_report_non_pst', message_report_non_pst)
_settings.set('report_button_text', report_button_text)
_settings.set('report_group_text', report_group_text)
_settings.set('confirmation_message', confirmation_message)
_settings.set('timeout_report_pst', timeout_report_pst)
_settings.set('pab_localized_terms', JSON.stringify(pab_localized_terms))
_settings.set('enable_forwarding', enable_forwarding ? 'true':'')
// Save roaming settings for the mailbox to the server so that they will be available in the next session.
_settings.saveAsync(saveMyAddInSettingsCallback)
},
error: function (xhr, status, error) {
endLoaderAndShowError('[getAddinSettings] : ' + xhr.responseText)
return
},
complete: function () {
// nothing to do here.
}
})
} else {
show_message_report_pst = _settings.get('show_message_report_pst')
message_report_pst = _settings.get('message_report_pst')
show_message_report_non_pst = _settings.get('show_message_report_non_pst')
message_report_non_pst = _settings.get('message_report_non_pst')
report_button_text = _settings.get('report_button_text')
report_group_text = _settings.get('report_group_text')
confirmation_message = _settings.get('confirmation_message') || KB4_DEFAULT_CONFIRMATION_MSG
timeout_report_pst = _settings.get('timeout_report_pst')
enable_forwarding = _settings.get('enable_forwarding') ? true:false
pab_localized_terms = JSON.parse(_settings.get('pab_localized_terms'))
attachmentTooLargePrefix = pab_localized_terms.CommonTerms.TooLargePrefix
ok_button_text = pab_localized_terms.CommonTerms.Ok
// Initialize notification mechanism of PAB-Exchange
app.setupNotificationBlob(pab_localized_terms)
$('th#subjectLabel').text(pab_localized_terms.CommonTerms.Subject + ':')
$('th#fromLabel').text(pab_localized_terms.CommonTerms.From + ':')
$('#buttonReport').prop('value', report_button_text)
$('#apptitle').text(report_group_text)
$('#confirmation-message').text(confirmation_message)
}
return
}
/**
* Function handler to handle calls to save addin settings into Office-provided roaming settings facility.
*
* @param {object} asyncResult data blob containing the result of the saveSettings() call.
*
* @return {void}
*/
function saveMyAddInSettingsCallback(asyncResult) {
if (asyncResult.status == Office.AsyncResultStatus.Failed) {
// Nothing to do here. Allow the next invoke to request the addin settings.
}
return
}
/**
* Function handler when displayed name in the "From" entry is clicked.
*
* @return {void}
*/
function displayItemDetails() {
// Displays the "Subject" and "From" fields, based on the current mail item
var item = Office.cast.item.toItemRead(Office.context.mailbox.item)
$('#subject').text(item.subject)
if (currentMessageSender) {
$('#from').text(currentMessageSender.displayName)
$('#from').click(function () {
app.showNotification(currentMessageSender.displayName, currentMessageSender.emailAddress)
})
}
$('#buttonReport').click(submitPhishingReport)
return
};
/**
* Hide the loader or spinner image.
*
* @return {void}
*/
function hideLoader() {
if (window.location.href.toUpperCase().indexOf(KB4_TASKPANE_URL_MARKER) > -1) {
$('#pabSpinner').hide();
} else {
$('#pabv1SpinnerImage').hide();
}
return
}
/**
* Show the loader or spinner image.
*
* @return {void}
*/
function showLoader() {
if (window.location.href.toUpperCase().indexOf(KB4_TASKPANE_URL_MARKER) > -1) {
$('#pabSpinner').show();
} else {
$('#pabv1SpinnerImage').show();
}
return
}
/**
* Hide the loader or spinner and then show an error message.
*
* @return {void}
*/
function endLoaderAndShowError(errorMessage) {
hideLoader()
app.showError(errorMessage)
return
}
/**
* Hide the loader or spinner and then show a message saying the process was completed.
*
* @return {void}
*/
function endLoaderAndShowComplete(completionType, completionMessage) {
hideLoader()
app.showComplete(completionType, completionMessage)
return
}
/**
* Hide the loader or spinner and then show the success message.
*
* @return {void}
*/
function endLoaderAndShowSuccess(successMessage) {
hideLoader()
app.showSuccess(successMessage)
return
}
/**
* Function handler when clicking the PAB-report button
*
* @return {void}
*/
function submitPhishingReport() {
app.showStatus(PABV1_STATUS_PROCESSING)
showLoader()
// Disable the controls while sending data
$('#buttonReport').prop('disabled', true)
sendHeadersRequest()
return
};
/**
* Creates the SOAP request envelope, wrapping the raw EWS request.
*
* @param {string} request string representing the raw EWS request.
*
* @return {string} XML/SOAP envelope used for all EWS requests
*/
function getSoapEnvelope(request) {
// Wrap an Exchange Web Services request in a SOAP envelope.
var result =
"<?xml version='1.0' encoding='utf-8'?>" +
"<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'" +
" xmlns:t='http://schemas.microsoft.com/exchange/services/2006/types'>" +
' <soap:Header>' +
" <t:RequestServerVersion Version='Exchange2013'/>" +
' </soap:Header>' +
' <soap:Body>' +
request +
' </soap:Body>' +
'</soap:Envelope>'
return result
};
/**
* Creates the SOAP request to get the headers of an email
*
* @param {string} id email id whose headers will be requested
*
* @return {string} XML/SOAP request for use in asking for the email headers.
*/
function getHeadersRequest(id) {
// Return a GetItem EWS operation request for the headers of the specified item.
var result =
" <GetItem xmlns='http://schemas.microsoft.com/exchange/services/2006/messages'>" +
' <ItemShape>' +
' <t:BaseShape>IdOnly</t:BaseShape>' +
' <t:BodyType>Text</t:BodyType>' +
' <t:AdditionalProperties>' +
' <t:FieldURI FieldURI="item:Size" />' +
// PR_TRANSPORT_MESSAGE_HEADERS
" <t:ExtendedFieldURI PropertyTag='0x007D' PropertyType='String' />" +
' </t:AdditionalProperties>' +
' </ItemShape>' +
" <ItemIds><t:ItemId Id='" + id + "'/></ItemIds>" +
' </GetItem>'
return result
};
/**
* Executes the actual http-request to ask for the headers of the email about to be reported.
*
* @return {void}
*/
function sendHeadersRequest() {
var mailbox = Office.context.mailbox
var request = getHeadersRequest(mailbox.item.itemId)
var envelope = getSoapEnvelope(request)
try {
mailbox.makeEwsRequestAsync(envelope, getHeadersCallback)
} catch (e) {
endLoaderAndShowError('[sendHeadersRequest] : ' + e)
}
return
}
// This function plug in filters nodes for the one that matches the given name.
// This sidesteps the issues in jquery"s selector logic.
(function ($) {
$.fn.filterNode = function (node) {
return this.find('*').filter(function () {
return this.nodeName === node
})
}
})(jQuery)
/**
* Function called when the EWS request to get headers is complete.
*
* @param {object} asyncResult blob of data representing the result of the getHeaders() call.
*
* @return {void}
*/
function getHeadersCallback(asyncResult) {
// Process the returned response here.
if (asyncResult.value) {
var prop = null
var secondProp = null
try {
var response = $.parseXML(asyncResult.value)
var responseDOM = $(response)
if (responseDOM) {
// See http://stackoverflow.com/questions/853740/jquery-xml-parsing-with-namespaces
// See also http://www.steveworkman.com/html5-2/javascript/2011/improving-javascript-xml-node-finding-performance-by-2000
// We can do this because we know there's only the one property.
var itemSize = responseDOM.filterNode('t:Size')[0]
var actualSize = 0
try {
actualSize = parseInt(itemSize.textContent)
if (actualSize > EWS_MAX_SIZE_LIMIT_ASSUMED) {
isTotalItemSizeBeyondLimit = true
}
} catch (errVal) {
// nothing to do here.
}
prop = responseDOM.filterNode('t:ExtendedProperty')[0]
// let us get the changeKey here at this point.
secondProp = responseDOM.filterNode('t:ItemId')[0]
changeKey = secondProp.getAttribute('ChangeKey')
}
} catch (e) {
// Nothing to do here.
}
if (!prop) {
// Unlike the old implementation which showed granular messaging, this time we only show that the email they are forwarding has no headers.
endLoaderAndShowComplete(PABV1_COMPLETE_NO_HEADERS)
setTimeout(function () { deleteEmail(false) }, KB4_SETTINGS_DEFAULT_DISPLAY_DURATION)
return
}
headerText = prop.textContent.toString()
simulatedPhishing = (headerText.toLowerCase().indexOf('x-phish-crid') > -1)
// NOTE Step 2: Send headers or get forwarding address
if (simulatedPhishing) {
// submit simulated phishing report: send crid value to web service
var headerArray
var crid
try {
// BUG This regEx doesn't work in JavaScript
// regEx = '^(?<header_key>[-A-Za-z0-9]+)(?<seperator>:[ \t]*)' + '(?<header_value>([^\r\n]|\r\n[ \t]+)*)(?<terminator>\r\n)';
// headerArray = headerText.match(regEx); //https://msdn.microsoft.com/en-us/library/7df7sf4x(v=vs.94).aspx
// Split headers into array
headerArray = headerText.split('\n') // This is ugly but can get 'er done - some header values may split across array elements, but we just need to look for one header
for (var index = 0; index < headerArray.length; index++) {
if (headerArray[index].toLowerCase().indexOf('x-phish-crid') > -1) {
var headerlinevals = headerArray[index].split(':')
crid = headerlinevals[1]
crid = crid.replace(/\r?\n|\r|\s+/g, '')
}
}
} catch (e) {
endLoaderAndShowError('[getHeadersCallback] : ' + e)
return
}
// NOTE Send header to web service
submitHeader(crid)
} else {
// submit non-simulated phishing report: forward email with original headers
getForwardingEmailAddress(headerText)
}
} else if (asyncResult.error) {
endLoaderAndShowError('[getHeadersCallback] : ' + asyncResult.error.message)
return
}
return
};
/**
* Submit/Report the campaign id to the KMSAT server and display the appropriate success message.
*
* @param {string} crid the campaign id obtained from the email headers.
*
* @return {void}
*/
function submitHeader(crid) {
var licensekey = getLicenseKey()
var serverLocation = getServerLocation()
var errText = ''
try {
$.ajax({
type: 'POST',
url: serverLocation + '/api/v1/phishalert/report',
async: true,
context: this,
headers: { 'Access-Control-Allow-Origin': '*' },
data: { crid: crid, addin_version: encodeURI(environmentData.addin_version), auth_token: encodeURI(licensekey), os_name: encodeURI(environmentData.os_name), os_version: encodeURI(environmentData.os_version), os_architecture: encodeURI(environmentData.os_architecture), os_locale: encodeURI(environmentData.os_locale), outlook_version: environmentData.outlook_version, machine_guid: encodeURI(environmentData.machine_guid), sender_email: encodeURI(userEmailAddress) },
success: function (data) {
// If the success message is to be displayed then we handle it here.
if (show_message_report_pst) {
try {
hideLoader()
try {
displayDurationInMs = parseInt(timeout_report_pst) * 1000
} catch (e) {
displayDurationInMs = KB4_SETTINGS_DEFAULT_DISPLAY_DURATION // Agreed delay whether error or not is 3 seconds.
}
openDialogAsIframe(ok_button_text, message_report_pst, displayDurationInMs)
} catch (e) {
endLoaderAndShowSuccess(message_report_pst);
setDismissal()
}
} else {
// Get A changekey item and delete email.
getChangeKeyAndDeleteEmail(false)
}
},
error: function (xhr, status, error) {
// If the axios client fails (whether status is 400 or not), we forward the email.
getForwardingEmailAddress(headerText)
}
})
} catch (postReportEx) {
// Get A changekey item and delete email.
getChangeKeyAndDeleteEmail(false)
}
}
/**
* Get the user license based on the url
*
* @return {string} the user license.`
*/
function getLicenseKey() {
var result
// Get license key from manifest URL
var res = window.location.href.match(/\/phishalertonline\/(.*?)(\/.*?)/)
if (res == null) { return null }
if (res.length >= 2) {
result = res[1]
}
return result
}
/**
* Get the server location based on the url on the html window.
*
* @return {string} the server url
*/
function getServerLocation() {
var result
var res = window.location.href.match(/(.*?)\/phishalertonline\/(.*?)(\/.*?)/)
if (res == null) { return null }
if (res.length >= 2) {
result = res[1]
}
return result
}
/**
* Environment data initialization.
*
*/
function EnvironmentData(addin_version, os_name, os_version, os_architecture, os_locale, outlook_version, machine_guid) {
this.addin_version = addin_version
this.os_name = os_name
this.os_version = os_version
this.os_architecture = os_architecture
this.os_locale = os_locale
this.outlook_version = outlook_version
this.machine_guid = machine_guid
};
/**
* Sets the environment data like locale, OS, version and others.
*
* @return {void}
*/
function getEnvironmentData() {
var diags = Office.context.mailbox.diagnostics
var contxt = Office.context
var oslocale, outlookversion
try {
// Get environment settings
// useragent = $.HTTP_USER_AGENT; //How is this used?
outlookversion = diags.hostVersion
oslocale = contxt.displayLanguage
// window.location.href = https://localhost:44301/AppRead/Home/Home.html?_host_Info=Outlook|Win32|16.00|en-US
var paramvalues = window.location.search.split('=')
var os_architecture = 'n/a'
if (paramvalues.length > 1) // outlook web sends these params in, it is unreliable though what params are actually sent!
{
// hostInfo = paramvalues[1].split('|');
os_architecture = 'web'// hostInfo[1]
}
environmentData = new EnvironmentData()
environmentData.addin_version = '1.0' // hardcode this for now
environmentData.os_architecture = os_architecture
environmentData.outlook_version = outlookversion
environmentData.os_locale = oslocale
environmentData.os_name = 'unknown'
environmentData.os_version = 'unknown'
environmentData.machine_guid = 'unknown' // E.g: 15096333-e04f-4726-badb-ef151ecd6990
} catch (e) {
// Nothing to do here.
}
return
}
/**
* Request the email addresses to whom the report email will be sent.
*
* @param {string} headerText list of headers in the email to be reported.
*
* @return {void}
*/
function getForwardingEmailAddress(headerText) {
// get forwarding data
var licensekey = getLicenseKey()
var serverLocation = getServerLocation()
$.ajax({
type: 'POST',
url: serverLocation + '/api/v1/phishalert/forward_emails',
async: true,
context: this,
headers: { 'Access-Control-Allow-Origin': '*' },
data: { addin_version: encodeURI(environmentData.addin_version), auth_token: encodeURI(licensekey), os_name: encodeURI(environmentData.os_name), os_version: encodeURI(environmentData.os_version), os_architecture: encodeURI(environmentData.os_architecture), os_locale: encodeURI(environmentData.os_locale), outlook_version: environmentData.outlook_version, machine_guid: encodeURI(environmentData.machine_guid), sender_email: encodeURI(userEmailAddress) },
success: function (data) {
try {
var myData = JSON.parse(data)
var item = Office.cast.item.toItemRead(Office.context.mailbox.item)
forwardingData = new ForwardingData(myData.data.email_forward, myData.data.email_forward_subject)
var mailbox = Office.context.mailbox
mailbox.makeEwsRequestAsync(getItemDataRequest(item.itemId, ['Body', 'Subject', 'MimeContent']), getItemDataCallback, { itemId: item.itemId, headers: headerText })
} catch (e) {
endLoaderAndShowError('[getForwardingEmailAddress] : ' + '(' + status + ')' + e)
}
},
error: function (xhr, status, error) {
endLoaderAndShowError('[getForwardingEmailAddress] : ' + '(' + status + ')' + error)
},
complete: function () { }
})
return
};
/**
* Creates the SOAP request to get several fields of information on the message ID provided
*
* @param {string} item_id id of the message
* @param {string} fields an array of strings representing data we want to gather from the server based on the message-id
*
* @return {string} XML/SOAP request effectively executing a getItem() call on the Exchange Server.
*/
function getItemDataRequest(item_id, fields) {
var allFields = ''
fields.forEach(function (field) {
allFields += ('<t:FieldURI FieldURI="item:' + field + '" />')
})
var request = '<?xml version="1.0" encoding="utf-8"?>' +
'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' +
' xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"' +
' xmlns:xsd="http://www.w3.org/2001/XMLSchema"' +
' xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"' +
' xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">' +
' <soap:Header>' +
' <RequestServerVersion Version="Exchange2013" xmlns="http://schemas.microsoft.com/exchange/services/2006/types" soap:mustUnderstand="0" />' +
' </soap:Header>' +
' <soap:Body>' +
' <GetItem' +
' xmlns="http://schemas.microsoft.com/exchange/services/2006/messages"' +
' xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">' +
' <ItemShape>' +
' <t:BaseShape>IdOnly</t:BaseShape>' +
' <t:AdditionalProperties>' +
allFields +
' </t:AdditionalProperties>' +
' </ItemShape>' +
' <ItemIds>' +
' <t:ItemId Id="' + item_id + '"/>' +
' </ItemIds>' +
' </GetItem>' +
' </soap:Body>' +
'</soap:Envelope>'
return request
}
/**
* Callback function whenever a request to getItem() for deletion is executed..
*
* @param {object} asyncResult blob of data representing the result of the getItem() call.
*
* @return {void}
*/
function getItemToDeleteCallback(asyncResult) {
if (asyncResult == null) {
endLoaderAndShowError("[getItemToDeleteCallback] : asyncResult=''")
return
}
if (asyncResult.error != null) {
endLoaderAndShowError('[getItemToDeleteCallback] : ' + asyncResult.error.message)
return
} else {
var errorMsg
var prop = null
try {
var response = $.parseXML(asyncResult.value)
var responseDOM = $(response)
if (responseDOM) {
prop = responseDOM.filterNode('t:ItemId')[0]
changeKey = prop.getAttribute('ChangeKey')
}
} catch (e) {
errorMsg = e
}
if (!prop) {
if (errorMsg) {
endLoaderAndShowError('[getItemToDeleteCallback] : ' + errorMsg)
} else {
endLoaderAndShowError("[getItemToDeleteCallback] : prop=''")
}
} else {
if (changeKey) {
// NOW delete the email
var mailbox = Office.context.mailbox
var item = Office.cast.item.toItemRead(Office.context.mailbox.item)
mailbox.makeEwsRequestAsync(moveItemRequest(item.itemId, changeKey), moveItemCallback)
} else {
endLoaderAndShowError('[getItemToDeleteCallback] : ' + prop.textContent)
}
}
}
return
}
/**
* Create an XML entry representing the email addresses to whom the emails will be sent.
*
* @param {array} emlAddressArray array of string containing the recipient email addresses.
*
* @return {string} an XML string representing the TO/CC/BCC email addresses, for use in the SOAP
*/
function buildEmailAddressList(emlAddressArray) {
var finalAddressList = ''
for (var i = 0; i < emlAddressArray.length; i++) {
finalAddressList += '<t:Mailbox><t:EmailAddress>' + emlAddressArray[i] + '</t:EmailAddress></t:Mailbox>'
}
return finalAddressList
}
/**
* Creates the list of email addresses to send the report to, based on a blob data coming from KB4Server
*
* @param {string} forwardingData a comma-separated string containing a set of email addresses.
*
* @return {object} blob of data containing email addresses to whom the report will be sent.
*/
function buildForwardingSoapData(forwardingData) {
var addresses = forwardingData.email.split(',')
var addressTo = ''
var addressBcc = ''
var trimmed_address = ''
var addressToRecipientArray = []
var addressBCCRecipientArray = []
for (var i = 0; i < addresses.length; i++) {
if (addresses[i] && addresses[i] != '') {
trimmed_address = addresses[i].trim()
var upperCaseAddress = trimmed_address.toUpperCase()
// There could never be a case where both KB4_REPORT_EMAIL_US and KB4_REPORT_EMAIL_EU are both existing.
// Unless they are manually registered as recipients. However, let us just try adding them both.
if (upperCaseAddress == KB4_REPORT_EMAIL_US || upperCaseAddress == KB4_REPORT_EMAIL_EU) {
addressBCCRecipientArray.push(trimmed_address)
} else {
addressToRecipientArray.push(trimmed_address)
}
}
}
// is there a valid "To" Recipient? if so, process normally.
if (addressToRecipientArray.length > 0) {
addressTo = buildEmailAddressList(addressToRecipientArray)
addressBcc = buildEmailAddressList(addressBCCRecipientArray)
} else {
// now if there is no "To" recipient, push all bcc recipients (1 per region) to the to "to" recipients
addressTo = buildEmailAddressList(addressBCCRecipientArray)
}
if (addressTo != '') {
if (addressBcc != '') {
return {
'ToRecipients': addressTo,
'BccRecipients': addressBcc
};
}
return { 'ToRecipients': addressTo };
}
return null
}
/**
* Callback function executed when a GettItemData() call is finished.
*
* @param {object} asyncResult a structured data containing information on the result of the getItemData asyncrhonous call.
*
* @return {void}
*/
function getItemDataCallback(asyncResult) {
// We first get the Office context data.
var mailbox = Office.context.mailbox
var item = Office.cast.item.toItemRead(Office.context.mailbox.item)
var addressesSoap = buildForwardingSoapData(forwardingData)
var isOver1mb = false
// Something wrong with the email addresses to forward the emails to.
if (addressesSoap == null) {
endLoaderAndShowComplete(PABV1_COMPLETE_NO_FORWARD_ADDRESS)
// Show the "complete" message but display the error for 3 seconds.
setTimeout(function () { deleteEmail(false) }, KB4_SETTINGS_DEFAULT_DISPLAY_DURATION)
return
}
// Let us mark this as a repeat call.
if (asyncResult.asyncContext.hasOwnProperty('isOver1mb')) {
isOver1mb = true
}
// We don't have any data from the query, let us just return with a null result.
if (asyncResult == null) {
endLoaderAndShowError("[getItemDataCallback] : asyncResult=''")
return
}
// Is the result an error? Is it because we have over 1mb of data?
if (asyncResult.error != null) {
// Check to see if request failed because response is too large
var isErrorMessageOver1MB = (asyncResult.error.message.toUpperCase().indexOf('EXCEEDS 1 MB') !== -1)
var isError9020 = (asyncResult.error.code == 9020)
if (!isOver1mb && (isError9020 || isErrorMessageOver1MB)) {
var headers = asyncResult.asyncContext.headers
Office.context.mailbox.makeEwsRequestAsync(getItemDataRequest(asyncResult.asyncContext.itemId, ['Subject']), getItemDataCallback, { headers: headers, isOver1mb: 'true' })
return
} else {
// Display an error and then return.
endLoaderAndShowError('[getItemDataCallback] : ' + asyncResult.error.message)
return
}
}
// PAB-933-It seems that for MAC-Outlook, EWS requests return success even if the response is beyond 1MB.
// This is a workaround, to ensure that PAB-Exchange does not hang or get stuck in a loop when this case happens.
// Until microsoft comes with a fix on their bug.
if (!isOver1mb && asyncResult.value == null && isTotalItemSizeBeyondLimit) {
var headers = asyncResult.asyncContext.headers
Office.context.mailbox.makeEwsRequestAsync(getItemDataRequest(asyncResult.asyncContext.itemId, ['Subject']), getItemDataCallback, { headers: headers, isOver1mb: 'true' })
return
}
// Now let us process the result, at this point this should either be successful or over 1MB
var errorMsg = null
var prop = null
var mimeContent = ''
try {
var response = $.parseXML(asyncResult.value)
var responseDOM = $(response)
if (responseDOM) {
prop = responseDOM.filterNode('t:ItemId')[0]
}
} catch (e) {
// Something wrong with the parsing.
errorMsg = e
}
if (!prop) {
if (errorMsg) {
endLoaderAndShowError('[getItemDataCallback] : ' + errorMsg)
} else {
endLoaderAndShowError("[getItemDataCallback] : (prop='') asyncResult=" + asyncResult.value)
}
return
}
// Update the value of the changekey, if not, use the one in the sendHeadersRequest()
changeKey = prop.getAttribute('ChangeKey') // Used to delete the email after it is forwarded
// Get the MimeContent so we can construct an attachment from the source email and attach it
// to the new email we are sending (no longer forwarding the email - just creating a blank one with some properties)
prop = null
prop = responseDOM.filterNode('t:MimeContent')[0]
// let us get the mimecontent if it is avaiblable.
if (prop != null) {
mimeContent = prop.textContent
}
// NOTE Step 4: Create new email and send with copy of source email as attachment
var bodyContent = ''
var isHTML = false // default is plain text only.
var sourceSubject = !item.subject ? '' : item.subject;
// mimeContent can be empty because if we failed to retrieve it on the first request it is because
// the response was larger than 1MB.
if (isOver1mb) {
// We will only submit the headers.
sourceSubject = '[' + attachmentTooLargePrefix + ']' + sourceSubject
if (isHTML) {
bodyContent = asyncResult.asyncContext.headers.replace(/(?:\r\n|\r|\n)/g, '<br>')
} else {
bodyContent = asyncResult.asyncContext.headers
}
} else {
// Get the body of the email.
var body = responseDOM.filterNode('t:Body')[0]
var bodyType = body.getAttribute('BodyType')
bodyContent = body.textContent
if (bodyType == 'HTML') {
isHTML = true
}
}
var xml = ''
try {
xml = createAndSendItemWithAttachmentsRequest(forwardingData.subject, sourceSubject, addressesSoap, mimeContent, bodyContent, isHTML)
} catch (xmlException) {
endLoaderAndShowError('[getItemDataCallback] : ' + errorMsg)
return
}
try {
mailbox.makeEwsRequestAsync(xml, createAndSendItemWithAttachmentsCallback, { headers: { 'Content-Type': 'text/xml; charset=utf-8' }})
} catch (xmlException) {
// Just before we send out this data, let us check the length of the XML
if (!isOver1mb && xml.length >= 1000000) {
var headers = asyncResult.asyncContext.headers
Office.context.mailbox.makeEwsRequestAsync(getItemDataRequest(asyncResult.asyncContext.itemId, ['Subject']), getItemDataCallback, { headers: headers, isOver1mb: 'true' })
return
} else {
endLoaderAndShowError('[getItemDataCallback] : ' + errorMsg)
return
}
}
return
}
/**
* Move an email into the delteditems folder without having to update the changekey.
*
* @param {boolean} isFromAsyncDialog set to true if the call is from after displaying an asynchronous dialog. False if not.
*
* @return {void}
*/
function deleteEmail(isFromAsyncDialog) {
var mailbox = Office.context.mailbox
var item = Office.cast.item.toItemRead(Office.context.mailbox.item)
mailbox.makeEwsRequestAsync(moveItemRequest(item.itemId, changeKey), moveItemCallback, { isFromAsyncDialog: isFromAsyncDialog })
return
}
/**
* Convenience function to hide notification and delete email after a pre-determined duration.
*
* @return {void}
*/
function setDismissal() {
var dismissed = false
var dismissBtn = "<span class='dismiss-btn'>" + ok_button_text + "</span>"
$('#notification-message-body').append(dismissBtn)
// delete on dismiss click
$('.dismiss-btn').click(function () {
dismissed = true
$('.dismiss-btn').off('click')
$('.dismiss-btn').addClass('btn-disabled')
$('#notification-message').hide()
deleteEmail(false)
})
// otherwise delete after 3 seconds
setTimeout(function () {
if (dismissed !== true) {
$('#notification-message').hide()
deleteEmail(false)
}
}, KB4_SETTINGS_DEFAULT_DISPLAY_DURATION)
return
}