1212
1313from __future__ import annotations
1414
15- from collections import defaultdict
16- from datetime import datetime , timedelta
17- from typing import Dict , Any , List , Tuple , Optional
1815import json
1916import os
17+ from collections import defaultdict
18+ from datetime import datetime , timedelta , timezone
19+ from typing import Any , Dict , List , Optional , Tuple
2020
2121
2222class SignatureIDS :
@@ -28,7 +28,9 @@ class SignatureIDS:
2828
2929 def __init__ (self ) -> None :
3030 # (src, dst) -> list[(ts, dport)]
31- self .port_scan_map : Dict [Tuple [str , str ], List [Tuple [datetime , int ]]] = defaultdict (list )
31+ self .port_scan_map : Dict [Tuple [str , str ], List [Tuple [datetime , int ]]] = (
32+ defaultdict (list )
33+ )
3234 # (src, dst) -> list[ts]
3335 self .syn_counter : Dict [Tuple [str , str ], List [datetime ]] = defaultdict (list )
3436 # src -> list[ts]
@@ -47,7 +49,9 @@ def __init__(self) -> None:
4749 # Custom rules for Rule Editor
4850 self .custom_rules : List [Dict [str , Any ]] = []
4951 # (rule_idx, src, dport) -> list[datetime]
50- self .custom_state : Dict [Tuple [int , str , int ], List [datetime ]] = defaultdict (list )
52+ self .custom_state : Dict [Tuple [int , str , int ], List [datetime ]] = defaultdict (
53+ list
54+ )
5155
5256 base_dir = os .path .abspath (os .path .dirname (__file__ ))
5357 self .rules_path : str = os .path .join (base_dir , "rules.json" )
@@ -149,15 +153,17 @@ def analyze_packet(self, meta: Dict[str, Any]) -> Optional[Dict[str, Any]]:
149153 Returns:
150154 alert dict or None
151155 """
152- now = datetime .utcnow ( )
156+ now = datetime .now ( timezone . utc )
153157 self ._cleanup (now )
154158
155159 src = meta .get ("src" )
156160 dst = meta .get ("dst" )
157161 proto = meta .get ("proto" )
158162 dport = meta .get ("dport" )
159- flags = (meta .get ("flags" ) or "" )
160- length = int (meta .get ("length" ) or 0 ) # فعلاً استفاده نمیکنیم ولی برای آینده خوبه
163+ flags = meta .get ("flags" ) or ""
164+ length = int (
165+ meta .get ("length" ) or 0
166+ ) # فعلاً استفاده نمیکنیم ولی برای آینده خوبه
161167
162168 alert : Optional [Dict [str , Any ]] = None
163169
@@ -176,7 +182,13 @@ def analyze_packet(self, meta: Dict[str, Any]) -> Optional[Dict[str, Any]]:
176182 }
177183
178184 # ---------------- Port Scan detection ----------------
179- if alert is None and src and dst and dport is not None and proto in ("TCP" , "UDP" ):
185+ if (
186+ alert is None
187+ and src
188+ and dst
189+ and dport is not None
190+ and proto in ("TCP" , "UDP" )
191+ ):
180192 key = (src , dst )
181193 arr2 = self .port_scan_map [key ]
182194 arr2 .append ((now , int (dport )))
0 commit comments