-
Notifications
You must be signed in to change notification settings - Fork 0
/
arffWriter.py
executable file
·551 lines (441 loc) · 22.4 KB
/
arffWriter.py
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
# This is a Python framework to compliment "Peek-a-Boo, I Still See You: Why Efficient Traffic Analysis Countermeasures Fail".
# Copyright (C) 2012 Kevin P. Dyer (kpdyer.com)
# See LICENSE for more details.
import config
import os
import itertools
from Utils import Utils
import shutil # to remove folders
def writeArffFiles( runID, trainingSet, testingSet ):
# For Open World
outputFilenameArray = [
'k' + str(config.BUCKET_SIZE),
'c' + str(config.COUNTERMEASURE),
'd' + str(config.DATA_SOURCE),
'C' + str(config.CLASSIFIER),
'N' + str(config.TOP_N),
't' + str(config.NUM_TRAINING_TRACES),
'T' + str(config.NUM_TESTING_TRACES),
'D' + str(config.GLOVE_OPTIONS['packetSize']),
'E' + str(config.GLOVE_OPTIONS['burstSize']),
'F' + str(config.GLOVE_OPTIONS['burstTime']),
'G' + str(config.GLOVE_OPTIONS['burstNumber']),
'H' + str(config.GLOVE_OPTIONS['biBurstSize']),
'I' + str(config.GLOVE_OPTIONS['biBurstTime']),
'B' + str(config.GLOVE_OPTIONS['ModelTraceNum']),
'J' + str(config.GLOVE_PARAMETERS['window']),
'K' + str(config.GLOVE_PARAMETERS['no_components']),
'L' + str(config.GLOVE_PARAMETERS['learning_rate']),
'M' + str(config.GLOVE_PARAMETERS['epochs']),
'A' + str(int(config.IGNORE_ACK)),
'V' + str(int(config.FIVE_NUM_SUM)),
'P' + str(int(config.n_components_PCA)),
'G' + str(int(config.n_components_LDA)),
'l' + str(float(config.lasso)),
'b' + str(int(config.bucket_Size))
]
if config.COVARIATE_SHIFT != 0:
outputFilenameArray.append('s' + str(int(config.COVARIATE_SHIFT)))
# For Wang Tor dataset (config.DATA_SOURCE = 5) and others
if config.NUM_NON_MONITORED_SITES != -1 and (config.DATA_SOURCE == 5 or config.DATA_SOURCE == 41 or config.DATA_SOURCE == 42 or config.DATA_SOURCE == 6 \
or config.DATA_SOURCE == 61 or config.DATA_SOURCE == 62 or config.DATA_SOURCE == 63 or config.DATA_SOURCE == 64 or config.DATA_SOURCE == 9):
outputFilenameArray.append('u'+str(config.NUM_NON_MONITORED_SITES))
# HP datasets
if config.NUM_TRACE_PACKETS != -1: # num of packets to be used
outputFilenameArray.append('p'+str(config.NUM_TRACE_PACKETS))
# HP datasets
if config.NUM_HP_DCOY_ATTACKS_TRAIN != -1 or config.NUM_HP_DCOY_ATTACKS_TEST != -1:
outputFilenameArray.append('Q'+str(config.NUM_HP_DCOY_ATTACKS_TOTAL))
outputFilenameArray.append('w'+str(config.NUM_HP_DCOY_ATTACKS_TRAIN))
outputFilenameArray.append('W'+str(config.NUM_HP_DCOY_ATTACKS_TEST))
outputFilename = os.path.join('.'.join(outputFilenameArray))
runID = runID + outputFilename
trainingFilename = 'datafile-'+runID+'-train'
testingFilename = 'datafile-'+runID+'-test'
# Change the name for open world
''' commented out on Aug 19, 2017
if (config.NUM_MONITORED_SITES != -1):
trainingFilename = "datafile-"+ "openworld" + str(config.NUM_MONITORED_SITES) +"." +runID+"-train-orig"
testingFilename = "datafile-"+ "openworld" + str(config.NUM_MONITORED_SITES) +"." +runID+"-test"
'''
# config.NUM_NON_MONITORED_SITES is used for Wang Tor dataset only
# need to maintain this naming convention as other scripts (like owToWangFiles.py depends on this.
# config.DATA_SOURCE == 5 - Wang Tor dataset
#if (config.NUM_NON_MONITORED_SITES != -1 and config.DATA_SOURCE == 5):
# trainingFilename = "datafile-"+ "openworld" + str(config.NUM_MONITORED_SITES) +"." +runID+"-train"
# testingFilename = "datafile-"+ "openworld" + str(config.NUM_MONITORED_SITES) +"." +runID+"-test"
#print "in arff"
classes = []
for instance in trainingSet:
if instance['class'] not in classes:
classes.append(instance['class'])
for instance in testingSet:
if instance['class'] not in classes:
classes.append(instance['class'])
attributes = []
for instance in trainingSet:
for key in instance:
if key not in attributes:
attributes.append( key )
for instance in testingSet:
for key in instance:
if key not in attributes:
attributes.append( key )
if (config.CLASSIFIER == config.KDD_CLASSIFIER):
trainingFile = __writeArffFileKDD( trainingSet, trainingFilename, classes )
testingFile = __writeArffFileKDD( testingSet, testingFilename, classes )
elif (config.NUM_MONITORED_SITES != -1):
trainingFile = __writeArffFileBinary( trainingSet, trainingFilename, classes, attributes )
testingFile = __writeArffFileBinary( testingSet, testingFilename, classes, attributes )
else:
trainingFile = __writeArffFile( trainingSet, trainingFilename, classes, attributes )
testingFile = __writeArffFile( testingSet, testingFilename, classes, attributes )
# For open world only; to produce the open world training arff file
''' commented out on Aug 19, 2017
if (config.NUM_MONITORED_SITES != -1): # and config.DATA_SOURCE != 5):
__writeOpenWorldArffTrainingFile(trainingFilename, config.NUM_MONITORED_SITES )
'''
# Prepare Wang datasets
# Commented on Dec 16, 2015. Uncomment if needed.
#__writeWang(trainingFilename, testingFilename, outputFilename)
return [trainingFile, testingFile]
def __writeArffFile( inputArray, outputFile, classes, attributes ):
arffFile = []
if (config.CLASSIFIER == 16 or config.CLASSIFIER == 116 or config.CLASSIFIER == 1000):
# for Glove to mainain word order
# may apply to other classifiers as well like -C 1000
attributesTemp = list(attributes) # to make the list local so remove won't remove 'class' from the original list
attributesTemp.remove('class') # attributes = ['2', '1', '11', ..., 'class', '0', '23', ...]
attributesTemp = map(int, attributesTemp)
attributesTemp = sorted(attributesTemp)
attributesTemp = map(str, attributesTemp)
attributesTemp.append('class')
attributes = attributesTemp # attributes is local to this func from this point down
else:
attributes = sorted(attributes) # Khaled 10/04/2015
arffFile.append('@RELATION sites')
for attribute in attributes:
if attribute!='class':
arffFile.append('@ATTRIBUTE '+str(attribute)+' real')
arffFile.append('@ATTRIBUTE class {'+','.join(classes)+'}')
arffFile.append('@DATA')
for instance in inputArray:
tmpBuf = []
for attribute in attributes:
if attribute!='class':
val = '0'
if instance.get(attribute) not in [None,0]:
val = str(instance[attribute])
tmpBuf.append(val)
tmpBuf.append(instance['class'])
arffFile.append( ','.join(itertools.imap(str, tmpBuf)) )
outputFile = os.path.join(config.CACHE_DIR, outputFile+'.arff')
f = open( outputFile, 'w' )
f.write( "\n".join( arffFile ) )
f.close()
return outputFile
def __writeOpenWorldArffTrainingFile(trainingFilename, numMonitoredWebsites):
originalTrainingFile = config.CACHE_DIR + "/" + trainingFilename + ".arff"
fileList = Utils.readFile(originalTrainingFile)
newList = []
monitoredClasses = []
for line in fileList:
if line[0] == '@':
if not line.startswith("@ATTRIBUTE class"):
newList.append(line)
else:
monitoredClasses = getMonitoredClasses(line, numMonitoredWebsites)
newList.append("@ATTRIBUTE class {" + ','.join(monitoredClasses) + "}")
else:
instanceSplit = line.split(",")
if monitoredClasses.__contains__(instanceSplit[len(instanceSplit) - 1]):
newList.append(line)
#openWorldArffFile = config.CACHE_DIR + "/" + trainingFilename.substring(0, len(trainingFilename)-5) + ".arff"
openWorldArffFile = config.CACHE_DIR + "/" + trainingFilename[:-5] + ".arff"
f = open( openWorldArffFile, 'w' )
#for line in newList:
# f.write(line)
f.write( "\n".join( newList ) )
f.close()
def __writeWang(trainingFilename, testingFilename, outputFilename):
openWorldTrainingArffFile = os.path.join(config.CACHE_DIR, trainingFilename[:-5] + '.arff')
openWorldTestingArffFile = os.path.join(config.CACHE_DIR, testingFilename + '.arff')
folderName = os.path.join(config.WANG, outputFilename)
if not os.path.exists(folderName):
os.mkdir(folderName)
else:
shutil.rmtree(folderName) # delete and remake folder
os.mkdir(folderName)
trainList = Utils.readFile(openWorldTrainingArffFile)
testList = Utils.readFile(openWorldTestingArffFile)
currentWebsite = ""
fileCtr = 0
for line in trainList:
if line[0] == '@':
if line.startswith("@ATTRIBUTE class"):
monitoredClasses = getMonitoredClasses(line, config.NUM_MONITORED_SITES)
currentWebsite = monitoredClasses[0]
else:
lineArray = line.split(",")
website = lineArray[-1]
if website == currentWebsite:
filename = str(monitoredClasses.index(website)) + "-" + str(fileCtr) + "f"
f = open(os.path.join(folderName, filename), 'w')
f.write(" ".join(lineArray[:-1] ))
f.close()
fileCtr = fileCtr + 1
else:
currentWebsite = website
fileCtr = 0
filename = str(monitoredClasses.index(website)) + "-" + str(fileCtr) + "f"
f = open(os.path.join(folderName, filename), 'w')
f.write(" ".join(lineArray[:-1] ))
f.close()
fileCtr = fileCtr + 1
for line in testList:
if line[0] == '@':
if line.startswith("@ATTRIBUTE class"):
unMonitoredClasses = getUnMonitoredClasses(line, monitoredClasses)
currentWebsite == unMonitoredClasses[0]
else:
lineArray = line.split(",")
website = lineArray[-1]
if unMonitoredClasses.__contains__(website): # last instance of that class will override and we will have one file only
filename = str(unMonitoredClasses.index(website)) + "f"
f = open(os.path.join(folderName, filename), 'w')
f.write(" ".join(lineArray[:-1] ))
f.close()
def getMonitoredClasses( classesLine, numMonitoredWebsites):
#@ATTRIBUTE class {webpage26,webpage36,webpage48..}
classes = classesLine.split(" ")[2]
classes = classes.split("{")[1]
classes = classes.split("}")[0]
classesList = classes.split(",")
monitoredClasses = []
# append the first numMonitoredWebsites from the random list
for i in range(0,numMonitoredWebsites):
monitoredClasses.append(classesList[i])
return monitoredClasses
def getUnMonitoredClasses( classesLine, monitoredClasses):
#@ATTRIBUTE class {webpage26,webpage36,webpage48..}
classes = classesLine.split(" ")[2]
classes = classes.split("{")[1]
classes = classes.split("}")[0]
classesList = classes.split(",")
unMonitoredClasses = set(classesList) - set(monitoredClasses)
return list(unMonitoredClasses)
def writeArffFiles_variable_instances( runID, trainingSet, testingSet ):
# For Open World
outputFilenameArray = [
'k' + str(config.BUCKET_SIZE),
'c' + str(config.COUNTERMEASURE),
'd' + str(config.DATA_SOURCE),
'C' + str(config.CLASSIFIER),
'N' + str(config.TOP_N),
't' + str(config.NUM_TRAINING_TRACES),
'T' + str(config.NUM_TESTING_TRACES),
'D' + str(config.GLOVE_OPTIONS['packetSize']),
'E' + str(config.GLOVE_OPTIONS['burstSize']),
'F' + str(config.GLOVE_OPTIONS['burstTime']),
'G' + str(config.GLOVE_OPTIONS['burstNumber']),
'H' + str(config.GLOVE_OPTIONS['biBurstSize']),
'I' + str(config.GLOVE_OPTIONS['biBurstTime']),
'B' + str(config.GLOVE_OPTIONS['ModelTraceNum']),
'J' + str(config.GLOVE_PARAMETERS['window']),
'K' + str(config.GLOVE_PARAMETERS['no_components']),
'L' + str(config.GLOVE_PARAMETERS['learning_rate']),
'M' + str(config.GLOVE_PARAMETERS['epochs']),
'A' + str(int(config.IGNORE_ACK)),
'V' + str(int(config.FIVE_NUM_SUM)),
'P' + str(int(config.n_components_PCA)),
'G' + str(int(config.n_components_LDA)),
'l' + str(float(config.lasso)),
'b' + str(int(config.bucket_Size))
]
if config.COVARIATE_SHIFT != 0:
outputFilenameArray.append('s' + str(int(config.COVARIATE_SHIFT)))
# For Wang Tor dataset (config.DATA_SOURCE = 5) and others
if config.NUM_NON_MONITORED_SITES != -1 and (config.DATA_SOURCE == 5 or config.DATA_SOURCE == 41 or config.DATA_SOURCE == 42 or config.DATA_SOURCE == 6 \
or config.DATA_SOURCE == 61 or config.DATA_SOURCE == 62 or config.DATA_SOURCE == 63 or config.DATA_SOURCE == 64):
outputFilenameArray.append('u'+str(config.NUM_NON_MONITORED_SITES))
# HP datasets
if config.NUM_TRACE_PACKETS != -1: # num of packets to be used
outputFilenameArray.append('p'+str(config.NUM_TRACE_PACKETS))
# HP datasets
if config.NUM_HP_DCOY_ATTACKS_TRAIN != -1 or config.NUM_HP_DCOY_ATTACKS_TEST != -1:
outputFilenameArray.append('Q'+str(config.NUM_HP_DCOY_ATTACKS_TOTAL))
outputFilenameArray.append('w'+str(config.NUM_HP_DCOY_ATTACKS_TRAIN))
outputFilenameArray.append('W'+str(config.NUM_HP_DCOY_ATTACKS_TEST))
outputFilename = os.path.join('.'.join(outputFilenameArray))
runID = runID + outputFilename
trainingFilename = 'datafile-'+runID+'-train'
testingFilename = 'datafile-'+runID+'-test'
# Change the name for open world
if (config.NUM_MONITORED_SITES != -1):
trainingFilename = "datafile-"+ "openworld" + str(config.NUM_MONITORED_SITES) +"." +runID+"-train-orig"
testingFilename = "datafile-"+ "openworld" + str(config.NUM_MONITORED_SITES) +"." +runID+"-test"
# config.NUM_NON_MONITORED_SITES is used for Wang Tor dataset only
# need to maintain this naming convention as other scripts (like owToWangFiles.py depends on this.
# config.DATA_SOURCE == 5 - Wang Tor dataset
#if (config.NUM_NON_MONITORED_SITES != -1 and config.DATA_SOURCE == 5):
# trainingFilename = "datafile-"+ "openworld" + str(config.NUM_MONITORED_SITES) +"." +runID+"-train"
# testingFilename = "datafile-"+ "openworld" + str(config.NUM_MONITORED_SITES) +"." +runID+"-test"
#print "in arff"
classes = []
for instance in trainingSet:
if instance['class'] not in classes:
classes.append(instance['class'])
for instance in testingSet:
if instance['class'] not in classes:
classes.append(instance['class'])
'''
attributes = []
for instance in trainingSet:
for key in instance:
if key not in attributes:
attributes.append( key )
for instance in testingSet:
for key in instance:
if key not in attributes:
attributes.append( key )
'''
trainingFile = __writeArffFile_variable_instances( trainingSet, trainingFilename, classes )
testingFile = __writeArffFile_variable_instances( testingSet, testingFilename, classes )
# For open world only; to produce the open world training arff file
if (config.NUM_MONITORED_SITES != -1): # and config.DATA_SOURCE != 5):
__writeOpenWorldArffTrainingFile(trainingFilename, config.NUM_MONITORED_SITES )
# Prepare Wang datasets
# Commented on Dec 16, 2015. Uncomment if needed.
#__writeWang(trainingFilename, testingFilename, outputFilename)
return [trainingFile, testingFile]
def __writeArffFile_variable_instances(inputArray, outputFile, classes):
arffFile = []
arffFile.append('@RELATION sites')
arffFile.append('@ATTRIBUTE variable_length real')
arffFile.append('@ATTRIBUTE class {' + ','.join(classes) + '}')
arffFile.append('@DATA')
for instance in inputArray:
attributes = []
for key in instance:
attributes.append( key )
# for Glove to mainain word order
attributesTemp = list(
attributes) # to make the list local so remove won't remove 'class' from the original list
attributesTemp.remove('class') # attributes = ['2', '1', '11', ..., 'class', '0', '23', ...]
attributesTemp = map(int, attributesTemp)
attributesTemp = sorted(attributesTemp)
attributesTemp = map(str, attributesTemp)
attributesTemp.append('class')
attributes = attributesTemp
tmpBuf = []
for attribute in attributes:
if attribute != 'class':
val = '0'
if instance.get(attribute) not in [None, 0]:
val = str(instance[attribute])
tmpBuf.append(val)
tmpBuf.append(instance['class'])
arffFile.append(','.join(itertools.imap(str, tmpBuf)))
'''
if (config.CLASSIFIER == 16 or config.CLASSIFIER == 116):
# for Glove to mainain word order
attributesTemp = list(
attributes) # to make the list local so remove won't remove 'class' from the original list
attributesTemp.remove('class') # attributes = ['2', '1', '11', ..., 'class', '0', '23', ...]
attributesTemp = map(int, attributesTemp)
attributesTemp = sorted(attributesTemp)
attributesTemp = map(str, attributesTemp)
attributesTemp.append('class')
attributes = attributesTemp # attributes is local to this func from this point down
else:
attributes = sorted(attributes) # Khaled 10/04/2015
arffFile.append('@RELATION sites')
for attribute in attributes:
if attribute != 'class':
arffFile.append('@ATTRIBUTE ' + str(attribute) + ' real')
arffFile.append('@ATTRIBUTE class {' + ','.join(classes) + '}')
arffFile.append('@DATA')
for instance in inputArray:
tmpBuf = []
for attribute in attributes:
if attribute != 'class':
val = '0'
if instance.get(attribute) not in [None, 0]:
val = str(instance[attribute])
tmpBuf.append(val)
tmpBuf.append(instance['class'])
arffFile.append(','.join(itertools.imap(str, tmpBuf)))
'''
outputFile = os.path.join(config.CACHE_DIR, outputFile + '.arff')
f = open(outputFile, 'w')
f.write("\n".join(arffFile))
f.close()
return outputFile
def __writeArffFileKDD(inputArray, outputFile, classes):
arffFile = []
#attributes = sorted(attributes) # Khaled 10/04/2015
arffFile.append('@RELATION kdd-features')
for feature in config.KDD_FEATURES:
arffFile.append(feature[1]) # feature = ['duration', '@attribute duration numeric'],
arffFile.append('@ATTRIBUTE class {' + ','.join(classes) + '}')
arffFile.append('@DATA')
for instance in inputArray:
tmpBuf = []
for feature in config.KDD_FEATURES:
attribute = feature[0] # feature = ['duration', '@attribute duration numeric'],
val = '0'
if instance.get(attribute) not in [None, 0]:
val = str(instance[attribute])
tmpBuf.append(val)
tmpBuf.append(instance['class'])
arffFile.append(','.join(itertools.imap(str, tmpBuf)))
outputFile = os.path.join(config.CACHE_DIR, outputFile + '.arff')
f = open(outputFile, 'w')
f.write("\n".join(arffFile))
f.close()
return outputFile
def __writeArffFileBinary(inputArray, outputFile, classes, attributes):
arffFile = []
if (config.CLASSIFIER == 16 or config.CLASSIFIER == 116 or config.CLASSIFIER == 1000):
# for Glove to mainain word order
# may apply to other classifiers as well like -C 1000
attributesTemp = list(
attributes) # to make the list local so remove won't remove 'class' from the original list
attributesTemp.remove('class') # attributes = ['2', '1', '11', ..., 'class', '0', '23', ...]
attributesTemp = map(int, attributesTemp)
attributesTemp = sorted(attributesTemp)
attributesTemp = map(str, attributesTemp)
attributesTemp.append('class')
attributes = attributesTemp # attributes is local to this func from this point down
else:
attributes = sorted(attributes) # Khaled 10/04/2015
arffFile.append('@RELATION sites')
for attribute in attributes:
if attribute != 'class':
arffFile.append('@ATTRIBUTE ' + str(attribute) + ' real')
#arffFile.append('@ATTRIBUTE class {' + ','.join(classes) + '}')
#binaryLabels = ['webpageMon','webpageNonMon']
arffFile.append('@ATTRIBUTE class {' + ','.join(config.binaryLabels) + '}')
arffFile.append('@DATA')
for instance in inputArray:
tmpBuf = []
for attribute in attributes:
if attribute != 'class':
val = '0'
if instance.get(attribute) not in [None, 0]:
val = str(instance[attribute])
tmpBuf.append(val)
classLabel = instance['class']
classID = int(classLabel.split("webpage")[1])
if classID < config.NUM_MONITORED_SITES:
binaryLabel = config.binaryLabels[0]
else:
binaryLabel = config.binaryLabels[1]
#tmpBuf.append(instance['class'])
tmpBuf.append(binaryLabel)
arffFile.append(','.join(itertools.imap(str, tmpBuf)))
outputFile = os.path.join(config.CACHE_DIR, outputFile + '.arff')
f = open(outputFile, 'w')
f.write("\n".join(arffFile))
f.close()
return outputFile