1 # Copyright (C) 2013 Nippon Telegraph and Telephone Corporation.
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
21 from ryu.lib import hub, alert
22 from ryu.base import app_manager
23 from ryu.controller import event
26 BUFSIZE = alert.AlertPkt._ALERTPKT_SIZE
27 SOCKFILE = "/tmp/snort_alert"
30 class EventAlert(event.EventBase):
31 def __init__(self, msg):
32 super(EventAlert, self).__init__()
36 class SnortLib(app_manager.RyuApp):
39 super(SnortLib, self).__init__()
40 self.name = 'snortlib'
41 self.config = {'unixsock': True}
46 def set_config(self, config):
47 assert isinstance(config, dict)
50 def start_socket_server(self):
51 if not self.config.get('unixsock'):
53 if self.config.get('port') is None:
54 self.config['port'] = 51234
56 self._start_recv_nw_sock(self.config.get('port'))
60 self.logger.info(self.config)
63 self.logger.info("Unix socket start listening...")
65 data = self.sock.recv(BUFSIZE)
66 msg = alert.AlertPkt.parser(data)
68 self.send_event_to_observers(EventAlert(msg))
70 def _start_recv(self):
71 if os.path.exists(SOCKFILE):
74 self.sock = hub.socket.socket(hub.socket.AF_UNIX,
75 hub.socket.SOCK_DGRAM)
76 self.sock.bind(SOCKFILE)
77 hub.spawn(self._recv_loop)
79 def _start_recv_nw_sock(self, port):
81 self.nwsock = hub.socket.socket(hub.socket.AF_INET,
82 hub.socket.SOCK_STREAM)
83 self.nwsock.setsockopt(hub.socket.SOL_SOCKET,
84 hub.socket.SO_REUSEADDR, 1)
85 self.nwsock.bind(('0.0.0.0', port))
88 hub.spawn(self._accept_loop_nw_sock)
90 def _accept_loop_nw_sock(self):
91 self.logger.info("Network socket server start listening...")
93 conn, addr = self.nwsock.accept()
94 self.logger.info("Connected with %s", addr[0])
95 hub.spawn(self._recv_loop_nw_sock, conn, addr)
97 def _recv_loop_nw_sock(self, conn, addr):
98 buf = six.binary_type()
100 ret = conn.recv(BUFSIZE)
102 self.logger.info("Disconnected from %s", addr[0])
106 while len(buf) >= BUFSIZE:
107 # self.logger.debug("Received buffer size: %d", len(buf))
109 msg = alert.AlertPkt.parser(data)
111 self.send_event_to_observers(EventAlert(msg))
114 def _set_logger(self):
115 """change log format."""
116 self.logger.propagate = False
117 hdl = logging.StreamHandler()
118 fmt_str = '[snort][%(levelname)s] %(message)s'
119 hdl.setFormatter(logging.Formatter(fmt_str))
120 self.logger.addHandler(hdl)