├── decepgate-portal ├── config.txt ├── config_pre.txt ├── __init__.py ├── log_collector.py └── decepgate_ui.py ├── service-scripts ├── start_honeyd.sh ├── start-honeyd.timer ├── config_receiver.service ├── start-honeyd.service ├── inotify-decepgate.service └── script.sh ├── images ├── i_arch.png └── o_arch.png ├── src_tools ├── Makefile ├── sender.h └── conf_recv.c ├── yocto-recipe └── honeyd.bb ├── instructions ├── modifications.md └── setup.md ├── README.md └── LICENSE /decepgate-portal/config.txt: -------------------------------------------------------------------------------- 1 | data-log.csv 2 | -------------------------------------------------------------------------------- /decepgate-portal/config_pre.txt: -------------------------------------------------------------------------------- 1 | data-log.csv 2 | -------------------------------------------------------------------------------- /decepgate-portal/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = "1.0.0" 2 | -------------------------------------------------------------------------------- /service-scripts/start_honeyd.sh: -------------------------------------------------------------------------------- 1 | systemctl restart start-honeyd 2 | -------------------------------------------------------------------------------- /images/i_arch.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/comcast/decepgate/main/images/i_arch.png -------------------------------------------------------------------------------- /images/o_arch.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/comcast/decepgate/main/images/o_arch.png -------------------------------------------------------------------------------- /service-scripts/start-honeyd.timer: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Honeyd file swap . 3 | 4 | [Timer] 5 | OnBootSec=9min 6 | Unit=start-honeyd.service 7 | 8 | [Install] 9 | WantedBy=multi-user.target 10 | 11 | -------------------------------------------------------------------------------- /src_tools/Makefile: -------------------------------------------------------------------------------- 1 | HEADERS = sender.h 2 | 3 | default: conf_recv 4 | 5 | conf_recv.o: conf_recv.c $(HEADERS) 6 | gcc -c conf_recv.c -o conf_recv.o 7 | 8 | conf_recv: conf_recv.o 9 | gcc conf_recv.o -o conf_recv 10 | 11 | 12 | clean: 13 | -rm -f conf_recv.o 14 | -rm -f conf_recv 15 | -------------------------------------------------------------------------------- /service-scripts/config_receiver.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Honeyd config receiver service. 3 | #To start any service after starting current service 4 | #After= 5 | 6 | [Service] 7 | Type=simple 8 | RemainAfterExit=yes 9 | ExecStartPre=/bin/mkdir -p /tmp/honeyd_tmp 10 | ExecStart= /usr/bin/conf_recv -p 8083 & 11 | 12 | [Install] 13 | WantedBy=multi-user.target 14 | -------------------------------------------------------------------------------- /service-scripts/start-honeyd.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Honeyd file swap . 3 | #services needs to be started after this service need to add here 4 | #After= 5 | 6 | #Required dependencies 7 | #Requires= 8 | 9 | [Service] 10 | Type=simple 11 | Restart=on-failure 12 | RestartSec=3s 13 | RemainAfterExit=yes 14 | ExecStart= /bin/sh /usr/bin/script.sh & 15 | 16 | 17 | -------------------------------------------------------------------------------- /service-scripts/inotify-decepgate.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Honeyd file notifier service. 3 | #In after can add any service which needs to be started after this service 4 | After=config_receiver.service 5 | 6 | [Service] 7 | Type=simple 8 | RemainAfterExit=yes 9 | ExecStart= /usr/bin/inotify_decepgate /tmp/honeyd_tmp /usr/bin/start_honeyd.sh 1 *.conf & 10 | 11 | [Install] 12 | WantedBy=multi-user.target 13 | 14 | -------------------------------------------------------------------------------- /service-scripts/script.sh: -------------------------------------------------------------------------------- 1 | FILE=/nvram/honeyd_tmp/demo.conf 2 | if [ -f "$FILE" ]; then 3 | echo "$FILE exist" 4 | if pidof "honeyd" > /dev/null; 5 | then 6 | echo "Running" 7 | PID=`pidof honeyd` 8 | kill -9 $PID 9 | sleep 15 10 | if pidof "honeyd" > /dev/null; 11 | then 12 | PID=`pidof honeyd` 13 | echo "Still running" 14 | echo $PID 15 | else 16 | echo "Restart honeyd" 17 | read -r command < /tmp/honeyd_tmp/demo.conf 18 | mkdir -p /nvram/honeyd_conf 19 | cp /tmp/honeyd_tmp/demo.conf /tmp/honeyd_conf 20 | sed -i "1,1 d" /tmp/honeyd_conf/demo.conf 21 | $command & 22 | fi 23 | else 24 | echo "Start services" 25 | read -r command < /tmp/honeyd_tmp/demo.conf 26 | mkdir -p /tmp/honeyd_conf 27 | cp /tmp/honeyd_tmp/demo.conf /tmp/honeyd_conf 28 | sed -i "1,1 d" /tmp/honeyd_conf/demo.conf 29 | sleep 5 30 | $command & 31 | fi 32 | else 33 | echo "$FILE does not exist" 34 | fi 35 | 36 | -------------------------------------------------------------------------------- /yocto-recipe/honeyd.bb: -------------------------------------------------------------------------------- 1 | #Recipe for building application in RDK Platform 2 | DESCRIPTION = "Honeyd application" 3 | LICENSE = "CLOSED" 4 | 5 | #Commit id 6 | SRCREV = "" 7 | #Source file version control url 8 | SRC_URI = "" 9 | S = "${WORKDIR}/git" 10 | 11 | 12 | DEPENDS= "libdnet libevent libpcap libpcre libedit zlib ${@bb.utils.contains('DISTRO_FEATURES', 'cpg-ecfs', 'cpgc', 'cpg-libs', d)}" 13 | inherit autotools pkgconfig systemd 14 | 15 | CFLAGS += "-DPROD_LABELS" 16 | LDFLAGS+= "-L${STAGING_DIR_TARGET}/lib -ldl -L${STAGING_DIR_TARGET}/usr/lib -levent" 17 | EXTRA_OECONF += "--prefix=${STAGING_DIR_TARGET}/usr" 18 | EXTRA_OECONF += "--with-libdnet=${STAGING_DIR_TARGET}/usr" 19 | 20 | do_install_append () { 21 | install -d ${D}${bindir} 22 | install -m 0755 ${S}/service-scripts/script.sh ${D}${bindir} 23 | install -m 0755 ${S}/service-scripts/start_honeyd.sh ${D}${bindir} 24 | install -d ${D}${systemd_unitdir}/system 25 | install -m 0644 ${S}/service-scripts/config_receiver.service ${D}${systemd_unitdir}/system 26 | install -m 0644 ${S}/service-scripts/inotify-decepgate.service ${D}${systemd_unitdir}/system 27 | install -m 0644 ${S}/service-scripts/start-honeyd.service ${D}${systemd_unitdir}/system 28 | install -m 0644 ${S}/service-scripts/start-honeyd.timer ${D}${systemd_unitdir}/system 29 | 30 | } 31 | 32 | FILES_${PN} += "${systemd_unitdir}/system/config_receiver.service ${systemd_unitdir}/system/inotify-decepgate.service ${systemd_unitdir}/system/start-honeyd.service ${systemd_unitdir}/system/start-honeyd.timer" 33 | SYSTEMD_SERVICE_${PN} = "config_receiver.service" 34 | SYSTEMD_SERVICE_${PN} += "inotify-decepgate.service" 35 | SYSTEMD_SERVICE_${PN} += "start-honeyd.service" 36 | SYSTEMD_SERVICE_${PN} += "start-honeyd.timer" 37 | -------------------------------------------------------------------------------- /instructions/modifications.md: -------------------------------------------------------------------------------- 1 | ### Honeyd for embedded devices 2 | 3 | ### Changes Required: 4 | 5 | #### Changes added for cross compilation in toolchain: 6 | > In Honeyd the build tools are supporting native compilation, basically we need to run on respective platforms to build the package, but to cross compile for different platforms currently the toolchain is getting exited due to code snippet execution, which was supposed to be executed only on native platform. 7 | 8 | ##### For supporting cross compilation ,to build for different platforms ,need to do change the toolchain, 9 | Under configure.in ,If the target is for cross compilation then, 10 | - Modify the library and header paths ,by default its picking `/usr/ path` 11 | - Corrected `INC and LIB path`, if withval option included. 12 | - Also should skip the sample code execution of each library in toolchain, so modified those to support while running cross compilation. 13 | `HAVEMETHOD needs to be changed for skipping snippet execution wherever exit has been added.` 14 | 15 | ##### NOTE : 16 | >Earlier it will execute the small program for each library, which is applicable for only native compilation 17 | Also there is redefinition error in particular arm versions due to the structure user which was part of system headers defined in honeyd application ,so renamed the structure. 18 | 19 | #### CHANGES DONE ON SOURCE CODE: 20 | - Replaced new version of fingerprint(removed three finger prints which caused parse issue) 21 | - Replaced the latest fingerprint version from, 22 | `` https://svn.nmap.org/nmap/nmap-os-db 23 | - Most of embedded devices will have only read access for home directory ,so in our source code changed the path referring home to /tmp. 24 | ```EG: 25 | char config_suffix[] = "/.config"; 26 | char config_suffix[] = "/tmp/.config"; 27 | ``` 28 | - Also application is not able to read most of the packets ,due to that huge packet drops happening. Reason is due to pcap version compatibilty in embedded devices. 29 | - To fix this compatibilty issue following changes made, 30 | Changed packet reading polling mechanism from `EV_READ` to `EV_PERSIST ` (polling mechanism in frequent interval) 31 | Reason is our event handler using EV_READ based on packet capture file descriptor, where pcap dispatch used, so in the device the events are not triggering due to packet capture issue in pcap ,so used pcap loop as an alternative to read entire buffer(will do read for entire size),it will behave similar to event persist. 32 | ``` 33 | Old Prototype -> pcap_dispatch(inter->if_pcap, -1, if_recv_cb, (u_char *)inter) 34 | New Prototype-> pcap_loop(inter->if_pcap, -1, if_recv_cb, (u_char *)inter) 35 | ``` 36 | 37 | - Inorder to use new event polling , need to change , 38 | >Removed libevent timer(evtimer_new) and just used,honeyd_delay_callback with timeout by default -> `honeyd_delay_callback(-1, EV_TIMEOUT,delay)` 39 | 40 | - Remove file logging ,as we moved to UDP based remote streaming. 41 | Use macros in sender .h for remote streaming 42 | Macros available are, 43 | H_LOG_ERROR - To log error messages 44 | H_LOG_WARN - To log warning messages 45 | H_LOG_INFO - To log necessary info 46 | 47 | 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /src_tools/sender.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | 12 | 13 | /* 14 | ------------------------------------------------------------ 15 | UDP BASED REMOTE LOG STREAMING MACROS WITH THREE LEVELS 16 | *H_LOG_ERROR - to log error messages 17 | *H_LOG_WARN - to log warning messages 18 | *H_LOG_INFO - to log ncessary info 19 | ----------------------------------------------------------- 20 | 21 | */ 22 | char msg[1024]; 23 | 24 | //H_LOG_ERROR - to log error messages 25 | #define H_LOG_ERROR(format,...) {\ 26 | snprintf(msg,sizeof(msg),"HONEYD [ERROR] " format, ##__VA_ARGS__);\ 27 | struct sockaddr_in clientAddr;\ 28 | int sockfd, clientLen;\ 29 | if((sockfd=socket(AF_INET, SOCK_DGRAM, 0)) == -1)\ 30 | {\ 31 | perror("socket failed:");\ 32 | return;\ 33 | }\ 34 | memset((char *)&clientAddr, 0, sizeof(clientAddr));\ 35 | clientAddr.sin_family = AF_INET;\ 36 | clientAddr.sin_port = htons(DEFAULT_LISTEN_PORT);\ 37 | clientAddr.sin_addr.s_addr = inet_addr(DEFAULT_LISTEN_IP);\ 38 | clientLen = sizeof(clientAddr);\ 39 | if (connect(sockfd, (struct sockaddr *)&clientAddr,clientLen) < 0) \ 40 | { \ 41 | perror("\nConnection Failed \n"); \ 42 | return;\ 43 | } \ 44 | send(sockfd ,msg , strlen(msg) , 0 ); \ 45 | close(sockfd);\ 46 | } 47 | //H_LOG_WARN - to log warning messages 48 | #define H_LOG_WARN(format,...) {\ 49 | sprintf(msg,"HONEYD [WARN] " format, ##__VA_ARGS__);\ 50 | struct sockaddr_in clientAddr;\ 51 | int sockfd, clientLen;\ 52 | if((sockfd=socket(AF_INET, SOCK_DGRAM, 0)) == -1)\ 53 | {\ 54 | perror("socket failed:");\ 55 | return;\ 56 | }\ 57 | memset((char *)&clientAddr, 0, sizeof(clientAddr));\ 58 | clientAddr.sin_family = AF_INET;\ 59 | clientAddr.sin_port = htons(DEFAULT_LISTEN_PORT);\ 60 | clientAddr.sin_addr.s_addr = inet_addr(DEFAULT_LISTEN_IP);\ 61 | clientLen = sizeof(clientAddr);\ 62 | if (connect(sockfd, (struct sockaddr *)&clientAddr,clientLen) < 0) \ 63 | { \ 64 | perror("\nConnection Failed \n"); \ 65 | return;\ 66 | } \ 67 | send(sockfd ,msg , strlen(msg) , 0 ); \ 68 | close(sockfd);\ 69 | } 70 | 71 | //H_LOG_INFO - to log ncessary info 72 | #define H_LOG_INFO(format,...) {\ 73 | sprintf(msg,"HONEYD [INFO] " format, ##__VA_ARGS__);\ 74 | struct sockaddr_in clientAddr;\ 75 | int sockfd, clientLen;\ 76 | if((sockfd=socket(AF_INET, SOCK_DGRAM, 0)) == -1)\ 77 | {\ 78 | perror("socket failed:");\ 79 | return;\ 80 | }\ 81 | memset((char *)&clientAddr, 0, sizeof(clientAddr));\ 82 | clientAddr.sin_family = AF_INET;\ 83 | clientAddr.sin_port = htons(DEFAULT_LISTEN_PORT);\ 84 | clientAddr.sin_addr.s_addr = inet_addr(DEFAULT_LISTEN_IP);\ 85 | clientLen = sizeof(clientAddr);\ 86 | if (connect(sockfd, (struct sockaddr *)&clientAddr,clientLen) < 0) \ 87 | { \ 88 | perror("\nConnection Failed \n"); \ 89 | return;\ 90 | } \ 91 | send(sockfd ,msg , strlen(msg) , 0 ); \ 92 | close(sockfd);\ 93 | } 94 | 95 | -------------------------------------------------------------------------------- /decepgate-portal/log_collector.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018 Comcast Cable Communications Management, LLC 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | '''Log collector for Decepgate''' 17 | import time 18 | from watchdog.observers import Observer 19 | from watchdog.events import FileSystemEventHandler 20 | import sys 21 | import argparse 22 | 23 | file_name=' ' 24 | 25 | class MyHandler(FileSystemEventHandler): 26 | def on_modified(self, event): 27 | ''' WatchDog event Handler for monitoring the logs collected and clean the content for GUI''' 28 | 29 | feed="" 30 | filePath=dir_path+'/'+file_name 31 | 32 | with open(filePath,'r') as f: 33 | lines = f.readlines() 34 | feed=lines[-1].split() 35 | f.close() 36 | 37 | buf = "%s,%s,%s,%s,%s,%s" % (feed[5],feed[6],feed[8],feed[10],feed[9],feed[11]) 38 | 39 | '''Read the file name to write the parsed data ''' 40 | with open("config.txt",'r+') as ft: 41 | ft.seek(0) 42 | i_data=ft.read() 43 | ft.close() 44 | 45 | '''Write the Parsed Data for GUI ''' 46 | with open(i_data,'a+') as fp: 47 | fp.write(buf) 48 | fp.write("\n") 49 | fp.close() 50 | 51 | if __name__ == '__main__': 52 | ''' Map the command line arguments ''' 53 | parser = argparse.ArgumentParser() 54 | parser.add_argument("-f", "--file_name", 55 | nargs='?',help="Specify the name of a log file ") 56 | parser.add_argument("-d", "--dir_path", 57 | nargs='?', 58 | help="Specify the directory to watch") 59 | 60 | args = parser.parse_args() 61 | 62 | if not args.file_name: 63 | printf("Filename missing") 64 | exit() 65 | else: 66 | file_name=args.file_name 67 | if not args.dir_path: 68 | printf("Specify directory path to watch") 69 | exit() 70 | else: 71 | dir_path=args.dir_path 72 | 73 | '''Read the file name to write the header ''' 74 | with open("config.txt",'r+') as ft: 75 | ft.seek(0) 76 | i_data=ft.read().strip() 77 | ft.close() 78 | 79 | ''' Map the header for writing parsed data ''' 80 | fp = open(i_data,"a+") 81 | fp.seek(0) 82 | i_data=fp.read() 83 | if len(i_data) == 0: 84 | fp.write("TimeStamp,Protocol,Src_Ip,Dest_Ip,Src_Port,Dest_Port\n") 85 | fp.close() 86 | 87 | event_handler = MyHandler() 88 | observer = Observer() 89 | ''' Initiate the watchdog handler ''' 90 | observer.schedule(event_handler, path=dir_path, recursive=False) 91 | observer.start() 92 | 93 | try: 94 | while True: 95 | time.sleep(1) 96 | except KeyboardInterrupt: 97 | observer.stop() 98 | observer.join() 99 | -------------------------------------------------------------------------------- /instructions/setup.md: -------------------------------------------------------------------------------- 1 | DECEPGATE SETUP 2 | ============ 3 | 4 | ### Building the honeyd for RDK platform, 5 | - Please refer modifications.md for upgrading honeyd to run on embedded devices 6 | - Using the decepgate.bb yocto recipe , build the image and flash into the RDK devices 7 | - After flashing the image all required services to run honeyd will be ready 8 | 9 | ### prerequisite for dashboard setup 10 | - pip3 install dash (0.37.0) ,dash-core-components (0.43.1), Flask (1.1.2), dash-html-components (0.13.5),plotly (4.3.0),matplotlib (2.1.1),pandas (0.24.2),watchdog (0.9.0) 11 | 12 | ### Remote Server 13 | - Used syslog to collect logs remotely. 14 | - In syslog config enabled udp protocol with port 514 to receive logs across. 15 | `module(load="imudp"),input(type="imudp" port="514")` 16 | - On remote server run `log_collector.py` for listening to logs through syslog and clean it for GUI. 17 | ```python3 log_collector.py --dir_path " directory to watch "--file_name "log_file"``` 18 | 19 | This will prompt you for two inputs: 20 | 1. --dir_path 21 | * Directory path to listen for logs received. 22 | 2. --file-name 23 | * File name of the logs collected. 24 | - For dashboard hosted using flask run decepgate_ui.py 25 | ` python3 decepgate_ui.py --ip host ip"--port "listening port"` 26 | 27 | Two optional inputs, 28 | 1. --ip 29 | * IP where dashboard is hosted. 30 | 2. --port 31 | * Listening port of the dashboard. 32 | - Required files for dashboard is config.txt & config_pre.txt for fault_tolerance. 33 | 34 | These two files usage 35 | 1. config.txt, 36 | - To get file name of the parsed log which is gui input. 37 | 2. config_pre.txt, 38 | - To preserve the file name of parsed log, inorder to maintaina state of each config file. 39 | 40 | 41 | --- 42 | ### Gateway 43 | - To receive file from remote server to gateway, run 44 | ` conf_recv -p 8083 ` 45 | 46 | 47 | * -p is listening port for for file reciver 48 | - Used inotify library and created a package to listen for file received in a directory in gateway and did swapping and starting services with config files. 49 | ```./inotify_decepgate /tmp/honeyd_tmp /tmp/script.sh 1 *.conf``` 50 | 51 | Usage, 52 | 1. ./tmp/honeyd_tmp 53 | - directory where inotify listening 54 | 2. ./tmp/script.sh 55 | - to switch config files when new file received and starting honeyd with new configuration. 56 | 3. .conf 57 | - listen for .conf extension files 58 | 59 | - For streaming logs need to integrate the log macros used in `sender.h` in required places. 60 | 61 | ##### NOTE: 62 | - For injecting honeyd config files to gateway, use dashboard to broadcast. 63 | - We referred inotify sample codes and customized according to our need. So please refer open source inotify packages to use this services 64 | 65 | 66 | ### Files Description 67 | | File Name | Description | 68 | | --- | --- | 69 | | src_tools/conf_recv.c | To receive file from remote server to gateway | 70 | | src_tools/sender.h | For sending logs to remote server | 71 | | src_tools/Makefile | Sample Makefile(For testing compilation locally,but for actual use need to add these modules to honeyd | 72 | | decepgate-portal/log_collector.py | Used for cleaning logs collected in remote server and feed that into GUI | 73 | | decepgate-portal/decepgate_ui.py | Live dashboard for uploading and broadcasting config iles to gateway and also to see the live traffic from gateway | 74 | | decepgate-portal/config.txt | To store the filename of honeyd traffic based on config filename(used for fault tolerence mechanism | 75 | | decepgate-portal/config_pre.txt | Used to switch traffic based on config file name (fault tolenrence mechanism) | 76 | | yocto-recipe/honeyd.bb | Yocto recipe used for building honeyd in RDK platform | 77 | | service-scripts/config_receiver.service | systemd service for file reciever | 78 | | service-scripts/inotify-decepgate.service | systemd service for directory notifier | 79 | | service-scripts/start-honeyd.service | systemd service for honeyd application | 80 | | service-scripts/start-honeyd.timer | Service boot timer | 81 | | service-scripts/script.sh | Script used by inotify to perform actions to swap config files and started honeyd services | 82 | | service-scripts/start_honeyd.sh | small script to start honeyd service | 83 | 84 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DecepGate 2 | DecepGate helps building Honeypots and Honeynets on devices with limited resources such as gateways and embedded devices. DecepGate also gives the ability to manage decoys through a full fledge portal. The portal helps to create profiles, deploy decoys, collect logs and visualize them, and reconfigure the decoys. Below, we provide details on the architecture of the DecepGate and its components. 3 | 4 | # Overall End-to-End Architecture of DecepGate 5 |

6 | 7 |

8 | 9 | The main elements of DecepGate are as follows: 10 | ### User 11 | The user will create config files,design and also do deployments 12 | ### Control Device 13 | The device that the user can access the portal through and manage decoys. 14 | ### Portal 15 | A full fledge portal enabling users to manage decoys and reconfigure them 16 | ### Host Device 17 | The device that is hosting decoys. 18 | 19 | # Internal Architecture of DecepGate 20 |

21 | 22 |

23 | 24 | ### About Honeyd 25 | [Honeyd](http://www.honeyd.org/) is a small daemon that creates virtual hosts on a network and will be running on an Embedded box. The hosts can be configured to run arbitrary services, and their TCP personality can be adapted so that they appear to be running certain 26 | versions of operating systems. Honeyd enables a single host to claim multiple addresses. 27 | 28 | Scanners would be able to interact with the virtual hosts such as pinging the virtual machines, or to traceroute them. 29 | Any type of service on the virtual machine can be simulated according to a simple configuration file. 30 | 31 | ### Portal [/decepgate-portal]: 32 | Using this portal, we are able to upload config files in dashboard and inject them into the embedded devices. Once a config file is uploaded, the portal shows the network topology of our honeynet. Then we can broadcast the file to any device where honeyd running. Also whenever someone hit the virtual networks, will start to display Logs,Graphs,Charts in live dashboard. 33 | We are using syslog to collect logs and watchdogs to parse and feed live data from logs received. 34 | 35 | ### In Device [/service-scripts]: 36 | Whenever config file is injected from the portal remotely, we have config receiver developed running on gateway devices to receive the config file. Once the file received, we use a service named inotify-decepgate developed using intoify watch to listen for a file and start the decepgate using the config file received. Whenever new config file receives, our application will swap the config and start the service with new network topology. 37 | 38 | ### Changes contributed: 39 | #### Honeyd: 40 | Modified Honeyd Toolchain to build images for Embedded devices. By default they are developed to build on native environment. Enhanced the toolchain to support cross compilation. In some of the embedded boxes, the DecepGate application was not able to capture packets due to the compatibility issue. To resolve this issue, we changed the application interface components, with different event triggering option. Also application callbacks changed to timer. 41 | The config access modified. Removed file based logging and replaced with TCP stream. 42 | 43 | #### File Receiver: 44 | TCP-based file receiver developed to receive config file in the box. 45 | 46 | #### Inotify-Decepgate: 47 | To listen for config file in the box, used open-close flag. This was used for notifying file change events happening in a directory, based on which appropriate actions will be taken using the scripts to swap config files and start & stop service-scripts. 48 | 49 | #### Service-scripts: 50 | Created multiple systemd services to start applications and dependencies, swap config file, on boot behavior etc. 51 | 52 | ### Portal hosted remotely: 53 | Here portal developed in Python using Flask and Dash. Using this Portal we can Broadcast a configuration file of DecepGate to the Remote Devices. Used Syslog to receive logs and watchdog package in python to clean the data and send to live dashboard. 54 | 55 | 56 | # Files Description 57 | | File Name | Description | 58 | | --- | --- | 59 | | src_tools/conf_recv.c | To receive file from remote server to gateway | 60 | | src_tools/sender.h | For sending logs to remote server | 61 | | src_tools/Makefile | Sample Makefile(For testing compilation locally,but for actual use need to add these modules to honeyd | 62 | | decepgate-portal/log_collector.py | Used for cleaning logs collected in remote server and feed that into GUI | 63 | | decepgate-portal/decepgate_ui.py | Live dashboard for uploading and broadcasting config iles to gateway and also to see the live traffic from gateway | 64 | | decepgate-portal/config.txt | To store the filename of honeyd traffic based on config filename(used for fault tolerence mechanism | 65 | | decepgate-portal/config_pre.txt | Used to switch traffic based on config file name (fault tolenrence mechanism) | 66 | | yocto-recipe/honeyd.bb | Yocto recipe used for building honeyd in RDK platform | 67 | | service-scripts/config_receiver.service | systemd service for file reciever | 68 | | service-scripts/inotify-decepgate.service | systemd service for directory notifier | 69 | | service-scripts/start-honeyd.service | systemd service for honeyd application | 70 | | service-scripts/start-honeyd.timer | Service boot timer | 71 | | service-scripts/script.sh | Script used by inotify to perform actions to swap config files and started honeyd services | 72 | | service-scripts/start_honeyd.sh | small script to start honeyd service | 73 | -------------------------------------------------------------------------------- /src_tools/conf_recv.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | 19 | #define PORT 8082 20 | #define BACKLOG 5 21 | #define LENGTH 8192 22 | 23 | 24 | /* 25 | --------------------------------------------------------------------- 26 | TCP based file streaming,used to receive files transferred remotely 27 | --------------------------------------------------------------------- 28 | */ 29 | 30 | //File reciever with timeout 31 | int receive_timeout(int s ,FILE *fr, int timeout) 32 | { 33 | int size_recv , total_size= 0; 34 | struct timeval begin , now; 35 | char chunk[LENGTH]; 36 | double timediff; 37 | 38 | //make socket non blocking 39 | fcntl(s, F_SETFL, O_NONBLOCK); 40 | 41 | //beginning time 42 | gettimeofday(&begin , NULL); 43 | 44 | while(1) 45 | { 46 | gettimeofday(&now , NULL); 47 | 48 | //time elapsed in seconds 49 | timediff = (now.tv_sec - begin.tv_sec) + 1e-6 * (now.tv_usec - begin.tv_usec); 50 | 51 | //if you got some data, then break after timeout 52 | if( total_size > 0 && timediff > timeout ) 53 | { 54 | break; 55 | } 56 | 57 | //if you got no data at all, wait a little longer, twice the timeout 58 | else if( timediff > timeout*2) 59 | { 60 | break; 61 | } 62 | 63 | memset(chunk ,0 , LENGTH); //clear the variable 64 | if((size_recv = recv(s , chunk , LENGTH , 0) ) < 0) 65 | { 66 | //if nothing was received then we want to wait a little before trying again, 0.1 seconds 67 | usleep(100000); 68 | 69 | } 70 | else 71 | { 72 | total_size += size_recv; 73 | int write_sz = fwrite(chunk, sizeof(char),size_recv, fr); 74 | if(write_sz < size_recv) 75 | { 76 | perror("File write failed on server.\n"); 77 | } 78 | 79 | //reset beginning time 80 | gettimeofday(&begin , NULL); 81 | } 82 | } 83 | 84 | return total_size; 85 | } 86 | 87 | 88 | void error(const char *msg) 89 | { 90 | perror(msg); 91 | exit(1); 92 | } 93 | 94 | int main (int argc, char **argv) 95 | { 96 | /* Defining Variables */ 97 | int sockfd; 98 | int nsockfd; 99 | int sin_size; 100 | struct sockaddr_in addr_local; /* client addr */ 101 | struct sockaddr_in addr_remote; /* server addr */ 102 | int opt=1; 103 | int port=PORT; 104 | 105 | while ((opt = getopt (argc, argv, "p:")) != -1) 106 | { 107 | switch (opt) 108 | { 109 | case 'p': 110 | printf("port, -p %s:", optarg); 111 | port = atoi(optarg); 112 | break; 113 | default: 114 | printf("Unkown argument:%s", optarg); 115 | } 116 | } 117 | char config_suffix[] = "/tmp/honeyd_tmp"; 118 | char *full_path = malloc(strlen(config_suffix) + 1); 119 | strcpy(full_path, config_suffix); 120 | 121 | if(mkdir(full_path, S_IRWXU|S_IRWXO) != 0) 122 | { 123 | if(errno != EEXIST) 124 | { 125 | perror("Error: Could not create /tmp/honeyd_tmp/"); 126 | } 127 | } 128 | 129 | /* Get the Socket file descriptor */ 130 | if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1 ) 131 | { 132 | fprintf(stderr, "ERROR: Failed to obtain Socket Descriptor. (errno = %d)\n", errno); 133 | exit(1); 134 | } 135 | else 136 | printf("[Server] Obtaining socket descriptor successfully.\n"); 137 | 138 | /* Fill the client socket address struct */ 139 | addr_local.sin_family = AF_INET; // Protocol Family 140 | addr_local.sin_port = htons(port); // Port number 141 | addr_local.sin_addr.s_addr = INADDR_ANY; // AutoFill local address 142 | bzero(&(addr_local.sin_zero), 8); // Flush the rest of struct 143 | 144 | /* Bind a special Port */ 145 | if( bind(sockfd, (struct sockaddr*)&addr_local, sizeof(struct sockaddr)) == -1 ) 146 | { 147 | fprintf(stderr, "ERROR: Failed to bind Port. (errno = %d)\n", errno); 148 | exit(1); 149 | } 150 | else 151 | printf("[Server] Binded tcp port %d in addr 127.0.0.1 sucessfully.\n",port); 152 | 153 | /* Listen remote connect/calling */ 154 | if(listen(sockfd,BACKLOG) == -1) 155 | { 156 | fprintf(stderr, "ERROR: Failed to listen Port. (errno = %d)\n", errno); 157 | exit(1); 158 | } 159 | else 160 | printf ("[Server] Listening the port %d successfully.\n", port); 161 | 162 | int success = 1; 163 | while(success) 164 | { 165 | sin_size = sizeof(struct sockaddr_in); 166 | 167 | /* Wait a connection, and obtain a new socket file despriptor for single connection */ 168 | if ((nsockfd = accept(sockfd, (struct sockaddr *)&addr_remote, (socklen_t *) &sin_size)) == -1) 169 | { 170 | fprintf(stderr, "ERROR: Obtaining new Socket Despcritor. (errno = %d)\n", errno); 171 | exit(1); 172 | } 173 | else 174 | printf("[Server] Server has got connected from %s.\n", inet_ntoa(addr_remote.sin_addr)); 175 | 176 | 177 | /*Receive File from Client */ 178 | char* fr_name = "/tmp/honeyd_tmp/demo.conf"; 179 | FILE *fr = fopen(fr_name, "w"); 180 | if(fr == NULL) 181 | printf("File %s Cannot be opened file on server.\n", fr_name); 182 | else 183 | { 184 | int total_recv = receive_timeout(nsockfd,fr,4); 185 | printf("Total file size %d\n",total_recv); 186 | 187 | if(total_recv < 0) 188 | { 189 | if (errno == EAGAIN) 190 | { 191 | printf("recv() timed out.\n"); 192 | } 193 | else 194 | { 195 | fprintf(stderr, "recv() failed due to errno = %d\n", errno); 196 | exit(1); 197 | } 198 | } 199 | printf("Ok received from client!\n"); 200 | fclose(fr); 201 | } 202 | 203 | 204 | success = 1; 205 | close(nsockfd); //close the socket 206 | printf("[Server] Connection with Client closed. Server will wait now...\n"); 207 | while(waitpid(-1, NULL, WNOHANG) > 0); 208 | } 209 | } 210 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /decepgate-portal/decepgate_ui.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018 Comcast Cable Communications Management, LLC 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | 17 | ''' Dashboard for uploading and broadcasting honeyd config fileas to remote server and 18 | show the live traffic of honeyd detections from the embedded device ''' 19 | 20 | import flask 21 | import os 22 | import dash 23 | from dash.dependencies import Input, Output, State 24 | import dash_core_components as dcc 25 | import dash_html_components as html 26 | import plotly 27 | import plotly.graph_objs as go 28 | import dash_table_experiments as dt 29 | import pandas as pd 30 | from collections import OrderedDict 31 | from datetime import datetime 32 | import time 33 | import base64 34 | import io 35 | import matplotlib.cm as cm 36 | import numpy as np 37 | import dash_cytoscape as cyto 38 | import subprocess 39 | import re 40 | import socket 41 | import fcntl 42 | import struct 43 | import calendar 44 | import sys 45 | import argparse 46 | 47 | ''' Logic for swapping config file and retain logs based on respective config files ''' 48 | conf_file="" 49 | conf_pre_file="" 50 | conf_data="" 51 | csv_file="" 52 | 53 | 54 | 55 | ''' Default dummy config file ''' 56 | fp = open("./data-log.csv","a+") 57 | fp.seek(0) 58 | i_data=fp.read() 59 | if len(i_data) == 0: 60 | fp.write("TimeStamp,Protocol,Src_Ip,Dest_Ip,Src_Port,Dest_Port\n") 61 | fp.close() 62 | 63 | 64 | if len(conf_data) == 0: 65 | data = pd.read_csv( 66 | './data-log.csv' 67 | ) 68 | else: 69 | conf_file=conf_data 70 | csv_file="./"+conf_file 71 | data = pd.read_csv( 72 | csv_file 73 | ) 74 | 75 | ''' Sort Latest data ''' 76 | df = data.sort_values('TimeStamp', ascending=False) 77 | 78 | X = [] 79 | Y = [] 80 | A = [] 81 | B = [] 82 | M = [] 83 | N = [] 84 | L=[] 85 | 86 | 87 | def line_scatter(temp): 88 | '''Line scatter graph calculation for live feed''' 89 | groups = temp.groupby(by=['Dest_Ip','TimeStamp']) 90 | 91 | n=[] 92 | l=[] 93 | m=[] 94 | dt = datetime.now() 95 | 96 | timestamp = time.mktime(dt.timetuple()) + dt.microsecond / 1e6 97 | timestamp_h = timestamp - 60 98 | t_object = datetime.fromtimestamp(timestamp) 99 | t_obj = datetime.fromtimestamp(timestamp_h) 100 | 101 | ''' Grouping data based on time period ''' 102 | for i,k in groups: 103 | time_obj = datetime.strptime(i[1],'%Y-%m-%d-%H:%M:%S.%f') 104 | timestamp_dup = calendar.timegm(time_obj.timetuple())+ time_obj.microsecond / 1e6 105 | if timestamp_dup >= timestamp_h and timestamp_dup <= timestamp: 106 | n.append(i[0]) 107 | l.append(i[1]) 108 | m.append(len(k)) 109 | 110 | data = OrderedDict({'TimeStamp':l,'Dest_Ip':n, 'Count':m}) 111 | 112 | ''' Create DataFrame ''' 113 | dz = pd.DataFrame(data) 114 | 115 | ''' Data Formation for graph ''' 116 | groups = dz.groupby(by=['Dest_Ip']) 117 | y=[] 118 | z=[] 119 | c=[] 120 | for i,k in groups: 121 | e=[] 122 | r=[] 123 | t=0 124 | ''' Picking last one minute live data ''' 125 | for p in range(0,12): 126 | time_t=timestamp-t 127 | t=t+5 128 | timestamp_h = timestamp - t 129 | a=0 130 | for l in k['TimeStamp']: 131 | time_obj = datetime.strptime(l,'%Y-%m-%d-%H:%M:%S.%f') 132 | timestamp_dup = calendar.timegm(time_obj.timetuple())+ time_obj.microsecond / 1e6 133 | if timestamp_dup >= timestamp_h and timestamp_dup <= time_t: 134 | a=a+1 135 | 136 | 137 | e.append(p+1) 138 | r.append(a) 139 | for q in range(0,12): 140 | y.append(i) 141 | z.append(e[q]) 142 | c.append(r[q]) 143 | 144 | return y,z,c 145 | 146 | M,N,L=line_scatter(df) 147 | 148 | dup = pd.DataFrame({'Devices':M , 149 | 'Incomings':L, 150 | 'Time':N}) 151 | 152 | groups = dup.groupby(by='Devices') 153 | 154 | ys=list(set(dup['Devices'])) 155 | 156 | colors = cm.rainbow(np.linspace(0, 1, len(ys))) 157 | 158 | 159 | def bar_stat_ip(temp): 160 | '''Bar stat calculation for live feed''' 161 | n=[] 162 | l=[] 163 | a= list(temp['Dest_Ip']) 164 | d={} 165 | t=0 166 | ''' Data fromation for Bar chart ''' 167 | d={i:a.count(i) for i in a} 168 | for i,k in sorted(d.items(), key=lambda x: x[1],reverse=True): 169 | n.append(i) 170 | l.append(k) 171 | t=t+1 172 | ''' Maximum of 5 devices with highest hit ''' 173 | if t == 5: 174 | break 175 | return n,l 176 | 177 | X,Y=bar_stat_ip(df) 178 | 179 | def get_ip_address(ifname): 180 | '''TO get ip addrees based on interface''' 181 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 182 | return socket.inet_ntoa(fcntl.ioctl( 183 | s.fileno(), 184 | 0x8915, # SIOCGIFADDR 185 | struct.pack('256s',ifname[:15].encode('utf-8')) 186 | )[20:24]) 187 | 188 | base_elements=[] 189 | 190 | 191 | def network_topology(): 192 | '''To create network topology based on config uploaded''' 193 | filePath = './demo.conf' 194 | try: 195 | with open(filePath,'r') as f: 196 | lines = f.readlines() 197 | except IOError as e: 198 | print("Config file yet to be created") 199 | n=[] 200 | return n 201 | tpl=[] 202 | ifc=" " 203 | ''' Chunk the config file for parsing ''' 204 | for i in lines: 205 | if "honeyd" in i : 206 | m=i.split("-i") 207 | v=m[1].split(" ") 208 | ifc=v[1] 209 | continue 210 | tpl.append(i) 211 | 212 | inc=0 213 | tpl_data={} 214 | for i in tpl: 215 | tpl_data[inc]=i.split(" ") 216 | inc=inc+1 217 | 218 | core={} 219 | 220 | h_device=" " 221 | h_conn=[] 222 | h_dev=[] 223 | entry=0 224 | fil_d=[] 225 | 226 | ''' Parsing config file to map topology ''' 227 | for i,k in tpl_data.items(): 228 | if len(k) <= 2: 229 | continue 230 | if k[1] == "entry": 231 | h_device=k[2].rstrip() 232 | entry=1 233 | continue 234 | if k[0] == "bind": 235 | device={} 236 | device['ip']=k[1].rstrip() 237 | device['name']=k[2].rstrip() 238 | h_dev.append(device) 239 | continue 240 | else: 241 | if k[1] == h_device and k[2] == "link": 242 | continue 243 | if k[2] == "add": 244 | if k[5].rstrip() not in fil_d: 245 | route={} 246 | route['s_ip']=k[1].rstrip() 247 | route['d_ip']=k[5].rstrip() 248 | fil_d.append(k[5].rstrip()) 249 | h_conn.append(route) 250 | 251 | fil_d.append(h_device) 252 | node_elements=[] 253 | 254 | ''' Map the parsed data to form topology ''' 255 | if entry == 1: 256 | a={} 257 | buf = "EMBEDDED:HONEYD(%s)" % (h_device) 258 | a['data']={} 259 | a['data']['id']=h_device.rstrip() 260 | a['data']['label']=buf 261 | node_elements.append(a) 262 | else: 263 | dev=ifc 264 | a={} 265 | buf = "EMBEDDED:HONEYD(%s)" % (dev) 266 | a['data']={} 267 | a['data']['id']=dev.rstrip() 268 | a['data']['label']=buf 269 | node_elements.append(a) 270 | 271 | ''' mapping node and edge of the network ''' 272 | edge_elements=[] 273 | basic_elements=[] 274 | for i in h_dev: 275 | a={} 276 | buf = "%s(%s)" % (i['name'].rstrip(),i['ip'].rstrip()) 277 | a['data']={} 278 | a['data']['id']=i['ip'].rstrip() 279 | a['data']['label']=buf 280 | node_elements.append(a) 281 | if entry != 1: 282 | buf="%s-%s" %(i['ip'],dev) 283 | edge={} 284 | edge['data']={} 285 | edge['data']['id']=buf 286 | edge['data']['source']=i['ip'].rstrip() 287 | edge['data']['target']=dev 288 | buf="Edge from %s to %s" %(i['ip'].rstrip(),dev) 289 | edge['data']['label']=buf 290 | edge_elements.append(edge) 291 | continue 292 | if i['ip'] in fil_d: 293 | continue 294 | for j in fil_d: 295 | d_cmp = j.rsplit('.', 1) 296 | if d_cmp[0] in i['ip']: 297 | buf="%s-%s" %(i['ip'].rstrip(),j.rstrip()) 298 | edge={} 299 | edge['data']={} 300 | edge['data']['id']=buf 301 | edge['data']['source']=i['ip'].rstrip() 302 | edge['data']['target']=j.rstrip() 303 | buf="Edge from %s to %s" %(i['ip'].rstrip(),j.rstrip()) 304 | edge['data']['label']=buf 305 | edge_elements.append(edge) 306 | 307 | for i in h_conn: 308 | edge={} 309 | buf = "%s-%s" % (i['d_ip'].rstrip(),i['s_ip'].rstrip()) 310 | edge['data']={} 311 | edge['data']['id']=buf 312 | edge['data']['source']=i['d_ip'].rstrip() 313 | edge['data']['target']=i['s_ip'].rstrip() 314 | buf="Edge from %s to %s" %(i['d_ip'].rstrip(),i['s_ip'].rstrip()) 315 | edge['data']['label']=buf 316 | edge_elements.append(edge) 317 | 318 | basic_elements.extend(node_elements) 319 | basic_elements.extend(edge_elements) 320 | return basic_elements 321 | 322 | base_elements=network_topology() 323 | 324 | 325 | ''' Dashboard style elements ''' 326 | app_colors = { 327 | 'background': '#FFBB0A', 328 | 'text': '#000000', 329 | 'sentiment-plot': '#41EAD4', 330 | 'volume-bar': '#FBFC74', 331 | 'someothercolor': '#FF206E', 332 | } 333 | 334 | app = dash.Dash(__name__) 335 | 336 | app.css.append_css({ 337 | "external_url": "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" 338 | }) 339 | 340 | app.css.append_css({ 341 | "external_url": 'https://codepen.io/chriddyp/pen/bWLwgP.css' 342 | }) 343 | 344 | app.scripts.append_script({ 345 | "external_url": "https://code.jquery.com/jquery-3.2.1.min.js" 346 | }) 347 | 348 | app.scripts.append_script({ 349 | "external_url": "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" 350 | }) 351 | 352 | 353 | styles = { 354 | 'json-output': { 355 | 'overflow-y': 'scroll', 356 | 'height': 'calc(50% - 25px)', 357 | 'border': 'thin lightgrey solid' 358 | }, 359 | 'tab': {'height': 'calc(88vh - 115px)'} 360 | } 361 | 362 | ''' GUI Layout configuration ''' 363 | app.layout = html.Div( 364 | [ 365 | html.Div(children=[ 366 | # Column: Line Chart 367 | html.Div([ 368 | html.H4('Network Topology', style={'color': "#000000", 'width': 'auto','marginLeft': 10}), 369 | cyto.Cytoscape( 370 | id='cytoscape', 371 | elements=base_elements, 372 | layout={ 373 | 'name': 'circle', 374 | }, 375 | style={ 376 | 'height': '60vh', 377 | 'width': '100%' 378 | }, 379 | stylesheet=[ 380 | { 381 | 'selector': 'node', 382 | 'style': { 383 | 'background-color':'#2874A6', 384 | "font-size": "10px", 385 | 'label': 'data(label)' 386 | } 387 | }, 388 | { 389 | 'selector': '[label *= "EMBEDDED"]', 390 | 'style': { 391 | 'background-color': '#F4D03F', 392 | "font-size": "10px", 393 | 'shape': 'rectangle' 394 | } 395 | }, 396 | { 397 | 'selector': '[label *= "HONEYD"]', 398 | 'style': { 399 | 'background-color': '#17202A', 400 | "font-size": "10px", 401 | 'shape': 'triangle' 402 | } 403 | } 404 | 405 | ]) 406 | 407 | ], className="col-md-4",style={'backgroundColor':'#F7FBFE','border': 'thin lightgrey dashed', 'padding': '6px 0px 0px 8px','width':'50%','height': '650'}), 408 | html.Div([ 409 | html.H4('Incoming Traffic', style={'color': "#000000", 'width': 'auto','marginLeft': 35}), 410 | dcc.Graph(id='live-graph', animate=False, style={'width': 'auto'}), 411 | dcc.Graph(id='live-bar', animate=False, style={'width': 'auto'}), 412 | ], className="col-md-4",style={'backgroundColor':'#F7FBFE','border': 'thin lightgrey dashed', 'padding': '6px 0px 0px 8px', 'width':'50%','height': '650'}), 413 | ], className="row"), 414 | 415 | html.Div(className="row", children=[ 416 | html.Div([ 417 | html.H4('Log Stats', style={'color': "#000000", 'width': 'auto','align':'center'}), 418 | dt.DataTable( 419 | rows=df.to_dict('records'), 420 | 421 | #optional - sets the order of columns 422 | columns=df.columns, 423 | max_rows_in_viewport=5, 424 | sortable=True, 425 | selected_row_indices=[], 426 | id='live-table' 427 | ), 428 | ], className="col-md-4", style={'width': '48%', 'display': 'inline-block'}), 429 | html.Div([ 430 | html.H4(' Upload Config and Deploy', style={'color': "#000000", 'width': 'auto','marginLeft': 10}), #file upload tab 431 | dcc.Upload( 432 | id='upload-data', 433 | children=html.Div([ 434 | 'Drag and Drop or ', 435 | html.A('Select Files') 436 | ]), 437 | style={ 438 | 'width': '100%', 439 | 'height': '60px', 440 | 'lineHeight': '60px', 441 | 'borderWidth': '1px', 442 | 'borderStyle': 'dashed', 443 | 'borderRadius': '5px', 444 | 'textAlign': 'center', 445 | 'margin': '10px' 446 | }, 447 | #Allow multiple files to be uploaded 448 | multiple=True 449 | ), 450 | html.Div(id='output-data-upload'), # form design 451 | html.Form([ 452 | dcc.Input(name='name'), 453 | html.Button('Submit', type='submit'), 454 | ], style={'marginLeft': 10, 'marginRight': 10, 'marginTop': 10, 'marginBottom': 10,'width': '30%', 'display': 'inline-block'},action='/post', method='post') 455 | ],className="col-md-4", style={'marginLeft': 20, 'marginRight': 10, 'marginTop': 10, 'marginBottom': 10,'width': '47%', 'display': 'inline-block'})]), 456 | dcc.Interval( 457 | id='graph-update', 458 | interval=5 * 1000 # in millisecond 1*1000= 1 second 459 | ), 460 | ] 461 | 462 | ) 463 | 464 | @app.server.route('/post', methods=['POST']) 465 | def on_post(): 466 | ''' To broadcast uploaded config file ''' 467 | data = flask.request.form 468 | n=data.get("name") 469 | data=n.split(",") 470 | for i in data: 471 | buf = "nc %s 8083 < ./demo.conf" % (i) 472 | print(buf) 473 | t=subprocess.call(buf, shell=True) 474 | if t != 0: 475 | print(t) 476 | return flask.redirect('/') 477 | else: 478 | fp = open("config.txt","w+") #to preserve the data file name 479 | fp.seek(0) 480 | fp.write(conf_file) 481 | fp.close() 482 | return flask.redirect('/') 483 | 484 | 485 | @app.callback(Output('live-table', 'rows'), # selected_row_indices'), 486 | [Input('graph-update', 'n_intervals')]) 487 | def update_table(n_intervals): 488 | ''' Live update of graph ''' 489 | if len(conf_file) == 0: 490 | data = pd.read_csv( 491 | './data-log.csv' 492 | ) 493 | else: 494 | csv_file="./"+conf_file 495 | data = pd.read_csv( 496 | csv_file 497 | ) 498 | 499 | temp_2 = data.sort_values('TimeStamp', ascending=False) 500 | return temp_2.to_dict('records') 501 | 502 | 503 | @app.callback( 504 | Output('live-bar', 'figure'), 505 | [Input('graph-update', 'n_intervals')]) 506 | def update_figure(n_intervals): 507 | ''' live update of bar chart ''' 508 | if len(conf_file) == 0: 509 | data = pd.read_csv( 510 | './data-log.csv' 511 | ) 512 | else: 513 | csv_file="./"+conf_file 514 | data = pd.read_csv( 515 | csv_file 516 | ) 517 | 518 | temp2 = data.sort_values('TimeStamp', ascending=False) 519 | ''' Mark the plot ''' 520 | X, Y = bar_stat_ip(temp2) 521 | trace0 = go.Bar( 522 | x=X, 523 | y=Y, 524 | marker=dict( 525 | color='rgb(158,202,225)', 526 | line=dict( 527 | color='rgb(8,48,107)', 528 | width=1.5, 529 | ) 530 | ), 531 | opacity=0.6 532 | ) 533 | 534 | data = [trace0] 535 | layout = go.Layout( 536 | title='Traffic Stats', 537 | margin={'l': 10, 'b': 40, 't': 40, 'r': 10}, 538 | width=630, 539 | height=270, 540 | xaxis=dict( 541 | title='Devices', 542 | titlefont=dict( 543 | size=16, 544 | color='rgb(107, 107, 107)' 545 | ), 546 | tickfont=dict( 547 | size=14, 548 | color='rgb(107, 107, 107)' 549 | ) 550 | ), 551 | yaxis=dict( 552 | title='Number of Hits', 553 | titlefont=dict( 554 | size=16, 555 | color='rgb(107, 107, 107)' 556 | ), 557 | tickfont=dict( 558 | size=14, 559 | color='rgb(107, 107, 107)' 560 | ) 561 | ), 562 | ) 563 | 564 | fig = go.Figure(data=data, layout=layout) 565 | return fig 566 | 567 | 568 | 569 | def parse_contents_1(contents, filename, date): 570 | ''' Parse the config file contents ''' 571 | content_type, content_string = contents.split(',') 572 | 573 | decoded = base64.b64decode(content_string) 574 | n=decoded.decode('utf-8') 575 | global conf_file 576 | conf_file=filename+".csv" 577 | global csv_file 578 | csv_file="./"+conf_file 579 | fp = open(conf_file,"a+") 580 | fp.seek(0) 581 | i_data=fp.read() 582 | if len(i_data) == 0: 583 | fp.write("TimeStamp,Protocol,Src_Ip,Dest_Ip,Src_Port,Dest_Port\n") 584 | fp.close() 585 | fp = open(conf_pre_file,"w+") 586 | fp.seek(0) 587 | fp.write(conf_file) 588 | fp.close() 589 | with open("demo.conf",'w+') as fp: # demo.conf is the config file uploaded 590 | fp.write(n) 591 | fp.write("\n") 592 | fp.close() 593 | return html.Div([ 594 | 595 | ]) 596 | 597 | 598 | @app.callback(Output('output-data-upload', 'children'), 599 | [Input('upload-data', 'contents')], 600 | [State('upload-data', 'filename'), 601 | State('upload-data', 'last_modified')]) 602 | def update_output(list_of_contents, list_of_names, list_of_dates): 603 | ''' Toplogy update based on config upload ''' 604 | if list_of_contents is not None: 605 | children = [ 606 | parse_contents_1(c, n, d) for c, n, d in 607 | zip(list_of_contents, list_of_names, list_of_dates)] 608 | global base_elements 609 | base_elements=network_topology() 610 | return children 611 | 612 | 613 | @app.callback(Output('cytoscape', 'elements'), 614 | [Input('graph-update', 'n_intervals')]) 615 | def update_nodes(n_intervals): 616 | ''' Live update on topology ''' 617 | return base_elements 618 | 619 | @app.callback(Output('live-graph', 'figure'), 620 | [Input('graph-update', 'n_intervals')]) 621 | def update_graph_scatter(n_intervals): 622 | ''' Live update on graph ''' 623 | if len(conf_file) == 0: 624 | temp_1 = pd.read_csv( 625 | './data-log.csv' 626 | ) 627 | else: 628 | csv_file="./"+conf_file 629 | temp_1= pd.read_csv( 630 | csv_file 631 | ) 632 | 633 | temp = temp_1.sort_values('TimeStamp', ascending=False) 634 | M,N,L=line_scatter(temp) 635 | dup = pd.DataFrame({'Devices':M , 636 | 'Incomings':L, 637 | 'Time':N}) 638 | 639 | groups = dup.groupby(by='Devices') 640 | 641 | ys=list(set(dup['Devices'])) 642 | 643 | colors = cm.rainbow(np.linspace(0, 1, len(ys))) 644 | ''' Mark the topology ''' 645 | data_1 = [] 646 | for group, dataframe in groups: 647 | dataframe = dataframe.sort_values(by=['Time']) 648 | trace = go.Scatter(x=dataframe.Time.tolist(), 649 | y=dataframe.Incomings.tolist(), 650 | marker=dict(color=colors[len(data_1)]), 651 | name=group) 652 | data_1.append(trace) 653 | 654 | layout = go.Layout(xaxis={'title': 'Time'}, 655 | yaxis={'title': 'Traffic'}, 656 | margin={'l': 10, 'b': 40, 't': 40, 'r': 10}, 657 | width=630, 658 | height=280, 659 | hovermode='closest') 660 | 661 | figure = go.Figure(data=data_1, layout=layout) 662 | return figure 663 | 664 | 665 | 666 | 667 | 668 | 669 | if __name__ == '__main__': 670 | 671 | ''' Pasre Command line arguments ''' 672 | parser = argparse.ArgumentParser() 673 | parser.add_argument("-p", "--port", 674 | nargs='?',help="Specify the name of a listening port ") 675 | parser.add_argument("-ip", "--ip", 676 | nargs='?', 677 | help="Specify a ip of the host") 678 | 679 | args = parser.parse_args() 680 | 681 | if not args.port: 682 | port=8050 683 | else: 684 | port=int(args.port) 685 | if not args.ip: 686 | ip='0.0.0.0' 687 | else: 688 | ip=str(args.ip) 689 | 690 | conf_pre_file = "config_pre.txt" 691 | 692 | '''File for preserving file name of data''' 693 | fp = open(conf_pre_file,"a+") 694 | fp.seek(0) 695 | conf_data=fp.read() 696 | fp.close() 697 | 698 | 699 | app.run_server(host=ip, port=port,debug=True) 700 | 701 | --------------------------------------------------------------------------------