Esempio n. 1
0
 def loadExitNodes(self, dir):
     jsonFiles = glob.glob(str('%s/*.json' % dir))
     with open(jsonFiles[0]) as f:
         jsonObjects = json.load(f)
         Helper.printOnScreenAlways('DNS records have been loaded\n',
                                    MSG_TYPES.YELLOW)
         return jsonObjects
Esempio n. 2
0
def graphTask():
    # make the directories in case they are missing
    makeDirectories()

    DrawGraphsforALL = False
    # Helper.printOnScreenAlways("TEST",MSG_TYPES.RESULT)
    print('Files Directory: %s' % FILE_PATH)
    total, requests, all = getInfoFormTextFiles()
    print('Found %d records: ' % total)

    # TODO: need to be refactored/renamed- be more clear
    writeAllTextFiles(all)
    # write all the Requests into json file
    writeAllRequests(requests)
    getAllDNSIPs(requests)

    # match DNS with its port/ID they used.
    # normalizeDNSRequests(Requests)

    # for getting info for especial ip, port and ID
    # draw graphs for all the DNS records
    if DrawGraphsforALL is True:
        # print('Draw Graphs for each DNS records that has more than %d records...' % MINNUMBER_DrawGraph)
        Helper.printOnScreenAlways(
            'Draw Graphs for each DNS that has more than %d records...' %
            MINNUMBER_DrawGraph, MSG_TYPES.RESULT)
        DrawGraphsForAll(requests)
        Helper.printOnScreenAlways(
            'Done, Graphs are stored in the following directory: Graphs/DNS_Graphs/',
            MSG_TYPES.RESULT)

    drawGraphIDPORTNumber(requests, 1)
Esempio n. 3
0
    def sendRequests(self, runManytimesMode, requestTimes):
        try:

            Helper.printOnScreen(
                (term.format("Requesting our webiste:\n", term.Attr.BOLD)),
                color=MSG_TYPES.RESULT,
                mode=self.mode)
            domain = str(self.exitNodeIp).replace('.',
                                                  '-') + '.' + self.domainUrl
            url = 'http://' + domain
            result = self.query(url)

            #   requesting many times/ testing the same node 100 times./ testing how random is the PORT number and Requset ID
            if runManytimesMode is True:
                self.requestDomain(domain=domain, times=requestTimes)

            self.killConnection()
            if result is True:
                Helper.printOnScreenAlways(
                    ('Successfully connected over TOR: %s' % url),
                    color=MSG_TYPES.RESULT)
                return Result(CONNECTION_STATUS.CONNECTED,
                              DOMAIN_STATUS.ACCESSIBLE)
            else:
                return Result(CONNECTION_STATUS.CONNECTED,
                              DOMAIN_STATUS.NOT_ACCESSIBLE)

        except Exception as ex:
            self.killConnection()
            TORFunctions.loggingError('Connection - sendRequests: %s' %
                                      traceback.format_exc())
            return Result(CONNECTION_STATUS.CONNECTED,
                          DOMAIN_STATUS.STATELESS)  # or something went wrong
Esempio n. 4
0
    def requestDomainViaTor(self):
        Helper.printOnScreenAlways('Requesting %s  via TOR ' % self.DOMAIN_URL)
        start_time = time.time()
        nodesCount = 0
        successfully_Connections = 0
        successfully_Connections_Checking_Failed = 0
        failed_Connections = 0

        json_Objects = self.loadExitNodesFromJSON()
        if stem.util.system.is_windows():
            # Terminate the tor in case if it is still running
            TORFunctions.ProcesskillForWindows('tor.exe')

        for obj in tqdm(json_Objects, ncols=80, desc='Requesting Domain via our DNS'):
            ip = str(obj['ExitNode']['Address'].encode("ascii"), 'utf-8')
            fingerprint = str(obj['ExitNode']['Fingerprint'].encode("ascii"), 'utf-8')
            nickname = str(obj['ExitNode']['Nickname'].encode("ascii"), 'utf-8')
            or_port = str(obj['ExitNode']['Or_port'].encode("ascii"))
            dir_port = str(obj['ExitNode']['Dir_port'].encode("ascii"))
            result = self.connectToTORExitNode(fingerprint, ip, nodesCount + 1, TASK_MODE.REQUEST_DOMAIN)
            exitNode = ExitNode(ipaddress=ip,fingerprint=fingerprint,nickname=nickname,or_port=or_port,dir_port=dir_port,status=result)
            self.ExitNodes_List.append(exitNode)
            self.Result_List.append(result)

        time_taken = time.time() - start_time
        finalResult = Results.FinalResult(self.Result_List, nodesCount, time_taken)

        cur_path = os.path.dirname(__file__)
        os.chdir(cur_path)
        new_path = os.path.relpath(self.PROCESSED_NODES_PATH, cur_path)
        Helper.storeExitNodesJSON(object=self.ExitNodes_List,path=new_path)
Esempio n. 5
0
    def writeCheckedResult(self):
        connectionFailed = 0
        connectionSucceeded = 0
        connectedAndAccessible = 0
        connectedAndReAccessible = 0
        connectedButNotAccessible = 0
        connectedFailed = 0

        print("\n--------------------------")
        Helper.printOnScreenAlways('Finished in  %0.2f seconds' %
                                   (self.timetaken))

        Helper.printOnScreenAlways(
            'Found ' + str(self.nodesCount) + ' Exit nodes', MSG_TYPES.RESULT)
        for result in self.resultList:
            if result.connectionStatus == CONNECTION_STATUS.CONNECTED.value:
                if result.requestingDomainStatus == DOMAIN_STATUS.ACCESSIBLE.value:
                    connectedAndAccessible += 1
                elif result.requestingDomainStatus == DOMAIN_STATUS.RE_ACCESSIBLE.value:
                    connectedAndReAccessible += 1
                elif result.requestingDomainStatus == DOMAIN_STATUS.NOT_ACCESSIBLE.value:
                    connectedButNotAccessible += 1
                connectionSucceeded += 1
            if result.connectionStatus == CONNECTION_STATUS.NOT_CONNECTED.value:
                connectedFailed += 1

        data = ''
        with open(self.OUTPUT_FILE, 'r') as file:
            data = file.read()
        with open(self.OUTPUT_FILE, 'w+') as file:
            file.write(data)
            file.write("\n--------------------------\n")
            file.write("\n--------------------------\n")
            file.write('Finished in  %0.2f seconds\n' % (self.time_taken))
            file.write('Found ' + str(self.nodesCount) + ' Exit nodes:\n')
            file.write('   ' + str(connectionSucceeded) +
                       ': were connected successfully\n')

            file.write('   ' + str(connectionSucceeded) +
                       ': were connected successfully')
            file.write('   ' + str(connectedAndAccessible) +
                       ': were connected and checked successfully.')
            file.write('   ' + str(connectedAndReAccessible) +
                       ': were connected and re-checked successfully.')
            file.write('   ' + str(connectedButNotAccessible) +
                       ': were connected successfully but checked failed.')
            file.write('   ' + str(connectionFailed) + ': failed ')

            file.write('\n--------------------------\n')
            file.write('Checking Success rate:   ' +
                       str(connectionSucceeded / self.nodesCount * 100) + '%')
            file.write('Checking Failed rate:    ' +
                       str(connectedButNotAccessible / self.nodesCount * 100) +
                       '%')
            file.write('Failed Connections rate: ' +
                       str(connectionFailed / self.nodesCount * 100) + '%')
            file.write(
                '\n***********************************================END===============***********************************\n'
            )
Esempio n. 6
0
def writeInfoForSpicalIP(IP,
                         requests,
                         ID=None,
                         PORT=None,
                         DRAW=False,
                         index=0):
    list = []
    temp_Requests = []

    txtFiles = glob.glob(FILE_PATH)
    if ID is not None and PORT is not None:

        filename = ('JSON/ByIP/IP_%s_ID_%s_PORT_%s.json' % (IP, ID, PORT))
        for line in requests:
            if IP in line.srcIP and ID in line.requestId and PORT in line.srcPort:
                list.append(line)

    elif ID is not None:
        filename = ('JSON/ByID/IP_%s_ID_%s.json' % (IP, ID))
        for line in requests:
            if IP in line.srcIP and ID in line.requestId:
                temp_Requests.append(line)
                list.append(line)

    elif PORT is not None:
        filename = ('JSON/ByPort/IP_%s_PORT_%s.json' % (IP, PORT))
        for line in requests:
            if IP in line.srcIP and PORT in line.srcPort:
                temp_Requests.append(line)
                list.append(line)
    else:
        filename = ('JSON/ByIP/IP_%s.json' % IP)
        for line in requests:
            if IP == line.srcIP:
                temp_Requests.append(line)
                list.append(line)

    if list.__len__() > MINNUMBER_DrawGraph:
        print("JSON file are stored %s" % filename)
        with open(filename, 'w') as F:
            # Use the json dumps method to write the ExitNodelist to disk
            F.write(json.dumps(list, default=dumper))
            print('Writing All Requests Info is done :  %s' %
                  str(list.__len__()))

    if DRAW is True:
        # TODO: add enum
        requestCount = temp_Requests.__len__()
        if requestCount > MINNUMBER_DrawGraph:
            drawGraph(temp_Requests, option=1, mode=1)  # Request Ids
            drawGraph(temp_Requests, option=2, mode=1)  # port Number
        else:
            Helper.printOnScreenAlways(
                '%d - Ignored: %s - Requests: %d' %
                (index, temp_Requests[0].srcIP, requestCount),
                MSG_TYPES.YELLOW)
Esempio n. 7
0
    def run(self):
        try:
            if self.opt == '-r':  # check the connections
                self.requestDomainViaTor()
            elif self.opt == '-c':
                self.checkTorConnection(self.REQUIRED_NODES)
            elif self.opt == '-cd':  # check the domain name connection
                self.checkWebsiteConnection(self.REQUIRED_NODES)
            elif self.opt == '-drc':  # check the domain name connection
                self.countDNSRequest()

        except Exception as ex:
            Helper.printOnScreenAlways('TORConnector - run %s'%str(ex),MSG_TYPES.ERROR)
            sys.exit(2)
Esempio n. 8
0
def makeDirectories():
    '''
        Make the directories in case they are missing
    '''

    try:
        # TODO: Directories need more abtracte
        if not os.path.exists('GatheredFiles'):
            os.makedirs('GatheredFiles')
            os.makedirs('GatheredFiles/Logs')
            os.makedirs('GatheredFiles/JSON')
        else:
            if not os.path.exists('GatheredFiles/Logs'):
                os.makedirs('GatheredFiles/Logs')
            if not os.path.exists('GatheredFiles/JSON'):
                os.makedirs('GatheredFiles/JSON')

    except Exception as ex:
        Helper.printOnScreenAlways(ex, term.Color.RED)
Esempio n. 9
0
    def countDNSRequest(self):
        Helper.printOnScreenAlways('Requesting %s  via TOR ' % self.DOMAIN_URL)
        start_time = time.time()
        nodesCount = 0


        json_Objects = self.loadExitNodesFromJSON()
        if stem.util.system.is_windows():
            # Terminate the tor in case if it is still running
            TORFunctions.ProcesskillForWindows('tor.exe')

        for obj in tqdm(json_Objects, ncols=80, desc='Requesting Domain via our DNS'):

            ip = str(obj['ExitNode']['Address'].encode("ascii"), 'utf-8')
            fingerprint = str(obj['ExitNode']['Fingerprint'].encode("ascii"), 'utf-8')
            nickname = str(obj['ExitNode']['Nickname'].encode("ascii"), 'utf-8')
            or_port = str(obj['ExitNode']['Or_port'])
            dir_port = str(obj['ExitNode']['Dir_port'])
            self.connectToTORExitNode(fingerprint, ip, nodesCount + 1, TASK_MODE.DNS_RESOLVER_COUNTER)

        time_taken = time.time() - start_time
Esempio n. 10
0
    def findAllDNSFiles(self, folder: object = 'Logs') -> object:
        RootPath = '\\'.join(
            os.path.dirname(os.path.abspath(__file__)).split('\\')[:-1])
        newDestinationPath = os.path.join(RootPath, self.DESTINATION_PATH)

        # find all the logs folders for DNS
        files = [
            os.path.join(dp, f)
            for dp, dn, fn in os.walk(os.path.expanduser(self.SOURCE_PATH))
            for f in fn
        ]

        if folder == 'Logs':
            newDestinationPath = os.path.join(newDestinationPath, "Logs")
            # find all the logs files for DNS
            filteredLogFiles = [
                filePath for filePath in files if "logs" in filePath.lower()
                and "error" not in filePath.lower() and "DNS" in filePath
            ]
        elif folder == 'JSON':  # TODO: need some more work
            newDestinationPath = os.path.join(newDestinationPath, "JSON")
            # find all the logs files for DNS
            filteredLogFiles = [
                filePath for filePath in files
                if "JSON" in filePath.lower() and "error" not in filePath.
                lower() and "DNS" in filePath and "Checking" in filePath
            ]

        count = 0
        for filePath in filteredLogFiles:
            try:
                shutil.move(filePath, newDestinationPath)
                count += 1
            except shutil.Error as e:
                pass
                # os.rename(filePath, ('v%s _' % index) + filePath)
                # shutil.move(filePath, newDestinationPath)
        Helper.printOnScreenAlways('%d files has been moved.' % count,
                                   MSG_TYPES.RESULT)
Esempio n. 11
0
    def Normalize(self, show='yes'):
        count = 0
        DNSouterList = []
        for obj in self.DNSObj:  # get all the dns ip wittout repetation
            innerList = []

            dnsIP = self.DNSObj[obj]['Request']['SrcIP']
            dnsDomainfull = self.DNSObj[obj]['Request']['Domain']
            dnsDomainfull = [x.strip() for x in dnsDomainfull.split('.')
                             ][0]  # remove the domain: dnstestsuite.space
            temp = ''
            dnsExitnodeIP = [x.strip() for x in dnsDomainfull.split('_')
                             ][-1:][0]  # get the ip of the exitnode
            if (dnsExitnodeIP.__contains__('-')):
                if dnsIP not in DNSouterList:
                    DNSouterList.append(dnsIP)

        DNSouterList = set(DNSouterList)
        DNSList = []
        for obj in DNSouterList:
            node = DNSResolverInfo(obj)
            DNSList.append(node)

        for DnsNodeObj in DNSList:
            tempNodeList = []
            count = 1 + count
            for Dns in self.DNSObj:
                dnsIP = self.DNSObj[Dns]['Request']['SrcIP']
                if dnsIP == DnsNodeObj.DNSIP:
                    nodeDomainfull = self.DNSObj[Dns]['Request']['Domain']
                    nodeModifiedDomainfull = self.DNSObj[Dns]['Request'][
                        'modifiedDomain']
                    nodeDomain = [
                        x.strip() for x in nodeDomainfull.split('.')
                    ][0]  # remove the domain: dnstestsuite.space
                    dnsExitnodeIP = [x.strip() for x in nodeDomain.split('_')
                                     ][-1:][0]  # get the ip of the exitnode
                    if (dnsExitnodeIP.__contains__('-')):
                        dnsExitnodeIP = dnsExitnodeIP.replace("-", ".")

                        if dnsExitnodeIP not in tempNodeList:
                            tempNodeList.append(dnsExitnodeIP)
                            exitnode = DNSExitNode(dnsExitnodeIP, nodeDomain,
                                                   nodeModifiedDomainfull)
                            DnsNodeObj.insertNode(exitnode)
                            DnsNodeObj.nodeCount += 1

        if show == 'yes':
            for DnsNodeObj in DNSList:
                index = 0
                Helper.printOnScreenAlways(
                    'DNS Resolver IP: %s - Exitnode: %d ' %
                    (DnsNodeObj.DNSIP, DnsNodeObj.nodeCount), MSG_TYPES.RESULT)
                for node in DnsNodeObj.ExitNodelist:
                    index += 1
                    Helper.printOnScreenAlways(
                        "      %d - %s " % (index, node.exitNodeIP),
                        MSG_TYPES.YELLOW)
                print()

        Helper.printOnScreenAlways("We found %d DNS Resolvers " % count,
                                   MSG_TYPES.RESULT)

        curpath = os.path.dirname(__file__)
        os.chdir(curpath)
        newJSONPath = os.path.join(curpath, PROCESSED_DNSDATA_PATH)
        Helper.storeDNSResolverData(objects=DNSList, path=newJSONPath)

        return DNSList
Esempio n. 12
0
    def printCheckedResult(self):
        '''
            This function print the result of checking if the DNS support 0x20 bit encoding(Capitalization)
        '''
        connectionFailed = 0
        connectionSucceeded = 0
        connectedAndAccessible = 0
        connectedAndReAccessible = 0
        connectedButNotAccessible = 0
        connectedFailed = 0

        print("\n--------------------------")
        Helper.printOnScreenAlways('Finished in  %0.2f seconds' %
                                   (self.timetaken))

        Helper.printOnScreenAlways(
            'Found ' + str(self.nodesCount) + ' Exit nodes', MSG_TYPES.RESULT)
        for result in self.resultList:
            if result.connectionStatus == CONNECTION_STATUS.CONNECTED.value:
                if result.requestingDomainStatus == DOMAIN_STATUS.ACCESSIBLE.value:
                    connectedAndAccessible += 1
                elif result.requestingDomainStatus == DOMAIN_STATUS.RE_ACCESSIBLE.value:
                    connectedAndReAccessible += 1
                elif result.requestingDomainStatus == DOMAIN_STATUS.NOT_ACCESSIBLE.value:
                    connectedButNotAccessible += 1
                connectionSucceeded += 1
            if result.connectionStatus == CONNECTION_STATUS.NOT_CONNECTED.value:
                connectedFailed += 1

        Helper.printOnScreenAlways(
            str(connectionSucceeded) + ': were connected successfully',
            MSG_TYPES.RESULT)
        Helper.printOnScreenAlways(
            '   ' + str(connectedAndAccessible) +
            ': were connected and checked successfully.', MSG_TYPES.RESULT)
        Helper.printOnScreenAlways(
            '   ' + str(connectedAndReAccessible) +
            ': were connected and re-checked successfully.', MSG_TYPES.RESULT)
        Helper.printOnScreenAlways(
            '   ' + str(connectedButNotAccessible) +
            ': were connected successfully but checked failed.',
            MSG_TYPES.RESULT)
        Helper.printOnScreenAlways(
            str(connectionFailed) + ': failed ', MSG_TYPES.RESULT)
        Helper.printOnScreenAlways("\n--------------------------")

        Helper.printOnScreenAlways(
            'Checking Success rate:   ' +
            str(connectionSucceeded / self.nodesCount * 100) + '%',
            MSG_TYPES.RESULT)
        Helper.printOnScreenAlways(
            'Checking Failed rate:    ' +
            str(connectedButNotAccessible / self.nodesCount * 100) + '%',
            MSG_TYPES.RESULT)
        Helper.printOnScreenAlways(
            'Failed Connections rate: ' +
            str(connectionFailed / self.nodesCount * 100) + '%',
            MSG_TYPES.RESULT)
        Helper.printOnScreenAlways(
            '\n***********************************================END===============***********************************\n',
            MSG_TYPES.RESULT)
Esempio n. 13
0
    def checkDNSFor0x20Encoding(self):
        '''
            Check for 0x20 bit encoding
        '''

        try:
            randNumber = random.randint(1, 10000)  # to avoid cashing
            domain = (str(self.exitNodeIp).replace('.', '-') + '.' +
                      self.domainUrlCheck).strip()
            subDomain = '%d_check_%s' % (
                randNumber, domain
            )  # 768_check_12.23.243.12.dnstestsuite.space/check
            url = 'http://' + subDomain
            message = self.domainCorrectMessageResult
            result_message = 'none'
            try:
                result_message = self.query(url)

            except:
                result_message = 'unreachable'

            if message == result_message:  # matches
                Helper.printOnScreen(
                    ('Connected Successfully to : %s' % subDomain),
                    color=MSG_TYPES.RESULT,
                    mode=self.mode)
                self.wirteIntoFile('Connected Successfully to : %s' %
                                   subDomain)
                result = Result(CONNECTION_STATUS.CONNECTED,
                                DOMAIN_STATUS.ACCESSIBLE)

            else:
                Helper.printOnScreen(('Checking Failed : %s' % subDomain),
                                     color=MSG_TYPES.ERROR,
                                     mode=self.mode)
                self.wirteIntoFile('Checking Failed : %s' % subDomain)
                # re-checking
                Helper.printOnScreenAlways('re-Checking...',
                                           color=MSG_TYPES.ANY)
                subDomain = '%d_re_check_%s' % (
                    randNumber, domain
                )  # 12321_re_check_12.23.243.12.dnstestsuite.space/check
                url = 'http://' + subDomain
                result_message = 'none'

                try:
                    result_message = self.query(url)

                except:
                    result_message = 'unreachable'

                if message == result_message:
                    Helper.printOnScreen(
                        ('re-Checking Successful : %s' % subDomain),
                        color=MSG_TYPES.RESULT,
                        mode=self.mode)
                    self.wirteIntoFile('re-Checking Successful : %s' %
                                       subDomain)
                    result = Result(CONNECTION_STATUS.CONNECTED,
                                    DOMAIN_STATUS.RE_ACCESSIBLE)

                else:
                    Helper.printOnScreen(
                        ('re-Checking Failed : %s' % subDomain),
                        color=MSG_TYPES.ERROR,
                        mode=self.mode)
                    self.wirteIntoFile('re-Checking Failed : %s' % subDomain)
                    result = Result(CONNECTION_STATUS.CONNECTED,
                                    DOMAIN_STATUS.NOT_ACCESSIBLE)

            self.killConnection()

            return result

        except Exception as ex:
            TORFunctions.loggingError(
                'Connection - checkDNSFor0x20Encoding: %s' %
                traceback.format_exc())
            self.killConnection()

            return Result(CONNECTION_STATUS.CONNECTED,
                          DOMAIN_STATUS.NOT_ACCESSIBLE)
Esempio n. 14
0
def main(argv):

    mode = '-none'
    required_Nodes = 0
    printLogo()
    makeDirectories()
    if argv[1:] != []:  # on the server
        try:
            required_Nodes = -1
            opt = argv[1]
            error = False
            if len(argv) == 3:  # mode printing
                if argv[2] == MODE_TYPES.printing.value or argv[
                        2] == MODE_TYPES.none.value:
                    mode = argv[2]

            elif len(argv) == 5:
                if argv[2] == '-n':  # stop after certain nodes number
                    required_Nodes = argv[3]
                else:
                    error = True
                if argv[4] == MODE_TYPES.printing.value or argv[
                        4] == MODE_TYPES.none.value:
                    mode = argv[4]
                else:
                    error = True

                if error is True:
                    Helper.printOnScreen('WRONG ......', color=MSG_TYPES.ERROR)
                    sys.exit(2)
            else:
                Helper.printOnScreen('WRONG Too Many arguments.',
                                     color=MSG_TYPES.ERROR)

            ###---------------------------------------

            try:
                Helper.printOnScreenAlways("Gathering Info ... ",
                                           MSG_TYPES.RESULT)
                nodes = NodesHandler.NodesHandler(mode=mode)
                nodes_Number = nodes.run()
                Helper.printOnScreenAlways(
                    ("DONE, %s nodes have been gathered" % str(nodes_Number)),
                    MSG_TYPES.RESULT)
            except Exception as ex:
                Helper.printOnScreenAlways(
                    ("Exit nodes are not gathered.. :(, ERROR : %s" % str(ex)),
                    MSG_TYPES.ERROR)
                sys.exit()

            if opt == '-r' or opt == '-c' or opt == '-cd' or opt == '-drc':  #   check the connections
                if (int(required_Nodes) > 0):
                    con = TORConnector.TORConnections(opt, mode,
                                                      required_Nodes)
                    con.run()
                else:
                    con = TORConnector.TORConnections(opt, mode)
                    con.run()

        except Exception as ex:
            print(ex)
            sys.exit()
Esempio n. 15
0
def drawGraph(objects, option, mode=0, graphType=GRAPHS.ALL):
    '''
        Plot Request options :Id 1/ Port Nnumber 2 ||| mode: 0:normal / 1: one DNS
    '''

    list = []
    graphName = ''
    graphTitle = ''
    requestCount = objects.__len__()
    storePathHistogram = ''
    storePathScatter = ''
    if requestCount > MINNUMBER_DrawGraph:
        if (option == 1):  # ID graph
            for i in objects:
                list.append(int(i.requestId))
            graphName = 'Request Id'
            graphTitle = 'Request IDs Distribution  -  Requests: ' + str(
                requestCount)

        elif (option == 2):  # Port number graph
            for i in objects:
                list.append(int(i.srcPort))
            graphName = 'Port Numbers'
            graphTitle = 'Port Number Distribution  -  Requests: ' + str(
                requestCount)
        elif (option == 3):
            for i in objects:
                list.append(i.Mix)
            graphName = 'Mix Numbers'
            graphTitle = ' Distribution'
        elif (option == 4):
            for i in objects:
                list.append(i.Min)
                graphName = 'Mix Numbers'
                graphTitle = ' Distribution'
        try:
            srcIP = objects[0].srcIP
            if mode == 1:  # draw grphs for every DNS IP
                graphTitle += '          - IP: ' + srcIP  #+ '  Requests: ' + str(requestCount)
                if (option == 1):
                    storePathHistogram = "Graphs/DNS_Graphs/ByID/H_%s.png" % (
                        graphName + '_' + srcIP)
                    storePathScatter = "Graphs/DNS_Graphs/ByID/S_%s.png" % (
                        graphName + '_' + srcIP)
                elif (option == 2):
                    storePathHistogram = "Graphs/DNS_Graphs/ByPort/H_%s.png" % (
                        graphName + '_' + srcIP)
                    storePathScatter = "Graphs/DNS_Graphs/ByPort/S_%s.png" % (
                        graphName + '_' + srcIP)
            else:
                storePathHistogram = "Graphs/H_%s.png" % (graphName)
                storePathScatter = "Graphs/S_%s.png" % (graphName)

            list.sort()
            if graphType == GRAPHS.ALL:
                plt.hist(list, bins=10, rwidth=0.9)
                plt.xlim([-500, 70000])  # fix the x axis
                plt.xlabel(graphName)
                plt.ylabel("Frequency")
                plt.title(graphTitle)
                if os.path.isfile(storePathHistogram):
                    os.remove(
                        storePathHistogram)  # Opt.: os.system("rm "+strFile)
                plt.savefig(storePathHistogram)
                Helper.printOnScreenAlways(' H_%s Saved' % srcIP,
                                           MSG_TYPES.RESULT)
                plt.clf()

                unique_List = Counter(list)
                set(unique_List)

                x = []
                y = []
                markersize = 1
                if requestCount > 1500:
                    for i in unique_List:
                        newVal = int(i)
                        newValFeq = random.uniform(-0.5, 0.9) + float(
                            unique_List[i]
                        )  # add some noise to help to read the graph
                        x.append(newVal)
                        y.append(newValFeq)
                    plt.plot(x, y, linestyle='', marker='o', markersize=0.7)
                else:
                    for i in unique_List:
                        newVal = int(i)
                        newValFeq = float(
                            unique_List[i]
                        )  # add some noise to help to read the graph
                        x.append(newVal)
                        y.append(newValFeq)
                    plt.plot(x, y, linestyle='', marker='o', markersize=2)

                if os.path.isfile(storePathScatter):
                    os.remove(
                        storePathScatter)  # Opt.: os.system("rm "+strFile)

                plt.xlim([-500, 70000])  # fix the x axis
                plt.xlabel(graphName)
                plt.ylabel("Frequency")
                plt.title(graphTitle)
                plt.savefig(storePathScatter)
                Helper.printOnScreenAlways(' S_%s Saved' % srcIP,
                                           MSG_TYPES.RESULT)
                plt.clf()

            elif graphType == GRAPHS.HISTOGRAM:
                plt.hist(list, bins=10, rwidth=0.9)
                plt.xlim([-500, 70000])  # fix the x axis
                plt.xlabel(graphName)
                plt.ylabel("Frequency")
                if os.path.isfile(storePathHistogram):
                    os.remove(
                        storePathHistogram)  # Opt.: os.system("rm "+strFile)
                plt.savefig(storePathHistogram)
                Helper.printOnScreenAlways(' H_%s Saved' % srcIP,
                                           MSG_TYPES.RESULT)
                plt.clf()

            elif graphType == GRAPHS.SCATTER:
                unique_List = Counter(list)
                set(unique_List)
                x = []
                y = []
                markersize = 1
                if requestCount > 1500:
                    for i in unique_List:
                        newVal = int(i)
                        newValFeq = random.uniform(-0.5, 0.9) + float(
                            unique_List[i]
                        )  # add some noise to help to read the graph
                        x.append(newVal)
                        y.append(newValFeq)
                    plt.plot(x, y, linestyle='', marker='o', markersize=0.7)

                else:
                    for i in unique_List:
                        newVal = int(i)
                        newValFeq = float(
                            unique_List[i]
                        )  # add some noise to help to read the graph
                        x.append(newVal)
                        y.append(newValFeq)

                    plt.plot(x, y, linestyle='', marker='o', markersize=2)

                plt.xlim([-500, 70000])  # fix the x axis
                plt.xlabel(graphName)
                plt.ylabel("Frequency")
                plt.title(graphTitle)
                if os.path.isfile(storePathScatter):
                    print('found %s' % storePathScatter)
                    os.remove(
                        storePathScatter)  # Opt.: os.system("rm "+strFile)
                plt.savefig(storePathScatter)
                Helper.printOnScreenAlways(' H_%s Saved' % srcIP,
                                           MSG_TYPES.RESULT)
                plt.clf()

        except Exception as ex:
            print('In drawGraph' + str(ex))