code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def getExecuteCmd(self, proto, port): """Get the ExecuteCmd format string specified by the operator. Args: proto: The protocol name port: The port number Returns: The format string if applicable None, otherwise """ listener = self...
Get the ExecuteCmd format string specified by the operator. Args: proto: The protocol name port: The port number Returns: The format string if applicable None, otherwise
getExecuteCmd
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def _isWhiteListMiss(self, thing, whitelist): """Check if thing is NOT in whitelist. Args: thing: thing to check whitelist for whitelist: list of entries Returns: True if thing is in whitelist False otherwise, or if there is no whitelist ...
Check if thing is NOT in whitelist. Args: thing: thing to check whitelist for whitelist: list of entries Returns: True if thing is in whitelist False otherwise, or if there is no whitelist
_isWhiteListMiss
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def _isBlackListHit(self, thing, blacklist): """Check if thing is in blacklist. Args: thing: thing to check blacklist for blacklist: list of entries Returns: True if thing is in blacklist False otherwise, or if there is no blacklist """ ...
Check if thing is in blacklist. Args: thing: thing to check blacklist for blacklist: list of entries Returns: True if thing is in blacklist False otherwise, or if there is no blacklist
_isBlackListHit
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def isProcessWhiteListMiss(self, proto, port, proc): """Check if proc is OUTSIDE the process WHITElist for a port. Args: proto: The protocol name port: The port number proc: The process name Returns: False if no listener on this port ...
Check if proc is OUTSIDE the process WHITElist for a port. Args: proto: The protocol name port: The port number proc: The process name Returns: False if no listener on this port Return value of _isWhiteListMiss otherwise
isProcessWhiteListMiss
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def isProcessBlackListHit(self, proto, port, proc): """Check if proc is IN the process BLACKlist for a port. Args: proto: The protocol name port: The port number proc: The process name Returns: False if no listener on this port Return...
Check if proc is IN the process BLACKlist for a port. Args: proto: The protocol name port: The port number proc: The process name Returns: False if no listener on this port Return value of _isBlackListHit otherwise
isProcessBlackListHit
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def isHostWhiteListMiss(self, proto, port, host): """Check if host is OUTSIDE the process WHITElist for a port. Args: proto: The protocol name port: The port number host: The process name Returns: False if no listener on this port Ret...
Check if host is OUTSIDE the process WHITElist for a port. Args: proto: The protocol name port: The port number host: The process name Returns: False if no listener on this port Return value of _isWhiteListMiss otherwise
isHostWhiteListMiss
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def isHostBlackListHit(self, proto, port, host): """Check if host is IN the process BLACKlist for a port. Args: proto: The protocol name port: The port number host: The process name Returns: False if no listener on this port Return va...
Check if host is IN the process BLACKlist for a port. Args: proto: The protocol name port: The port number host: The process name Returns: False if no listener on this port Return value of _isBlackListHit otherwise
isHostBlackListHit
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def isDistinct(self, prev, bound_ips): """Not quite inequality. Requires list of bound IPs for that IP protocol version and recognizes when a foreign-destined packet was redirected to localhost or to an IP occupied by an adapter local to the system to be able to suppress output ...
Not quite inequality. Requires list of bound IPs for that IP protocol version and recognizes when a foreign-destined packet was redirected to localhost or to an IP occupied by an adapter local to the system to be able to suppress output of these near-duplicates.
isDistinct
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def __init__(self, diverter_config, listeners_config, ip_addrs, logging_level=logging.INFO): """Initialize the DiverterBase. TODO: Replace the sys.exit() calls from this function with exceptions or some other mechanism appropriate for allowing the user of this class to ...
Initialize the DiverterBase. TODO: Replace the sys.exit() calls from this function with exceptions or some other mechanism appropriate for allowing the user of this class to programmatically detect and handle these cases in their own way. This may entail moving configuration parsing to ...
__init__
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def set_debug_level(self, lvl, labels={}): """Enable debug output if necessary, set the debug output level, and maintain a reference to the dictionary of labels to print when a given logging level is encountered. Args: lvl: An int mask of all debug logging levels ...
Enable debug output if necessary, set the debug output level, and maintain a reference to the dictionary of labels to print when a given logging level is encountered. Args: lvl: An int mask of all debug logging levels labels: A dict of int => str assigning names to each ...
set_debug_level
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def pdebug(self, lvl, s): """Log only the debug trace messages that have been enabled via set_debug_level. Args: lvl: An int indicating the debug level of this message s: The mssage Returns: None """ if self.pdebug_level & lvl: ...
Log only the debug trace messages that have been enabled via set_debug_level. Args: lvl: An int indicating the debug level of this message s: The mssage Returns: None
pdebug
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def check_privileged(self): """UNIXy and Windows-oriented check for superuser privileges. Returns: True if superuser, else False """ try: privileged = (os.getuid() == 0) except AttributeError: privileged = (ctypes.windll.shell32.IsUserAnAdmin(...
UNIXy and Windows-oriented check for superuser privileges. Returns: True if superuser, else False
check_privileged
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def parse_listeners_config(self, listeners_config): """Parse listener config sections. TODO: Replace the sys.exit() calls from this function with exceptions or some other mechanism appropriate for allowing the user of this class to programmatically detect and handle these cases in their...
Parse listener config sections. TODO: Replace the sys.exit() calls from this function with exceptions or some other mechanism appropriate for allowing the user of this class to programmatically detect and handle these cases in their own way. This may entail modifying fakenet.py. ...
parse_listeners_config
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def build_cmd(self, pkt, pid, comm): """Retrieve the ExecuteCmd directive if applicable and build the command to execute. Args: pkt: An fnpacket.PacketCtx or derived object pid: Process ID associated with the packet comm: Process name (command) that sent the pac...
Retrieve the ExecuteCmd directive if applicable and build the command to execute. Args: pkt: An fnpacket.PacketCtx or derived object pid: Process ID associated with the packet comm: Process name (command) that sent the packet Returns: A str that is ...
build_cmd
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def _build_cmd(self, tmpl, pid, comm, src_ip, sport, dst_ip, dport): """Build a command based on the template specified in an ExecuteCmd config directive, applying the parameters as needed. Accepts individual arguments instead of an fnpacket.PacketCtx so that the Diverter can test any E...
Build a command based on the template specified in an ExecuteCmd config directive, applying the parameters as needed. Accepts individual arguments instead of an fnpacket.PacketCtx so that the Diverter can test any ExecuteCmd directives at configuration time without having to synthesize ...
_build_cmd
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def execute_detached(self, execute_cmd): """OS-agnostic asynchronous subprocess creation. Executes the process with the appropriate subprocess.Popen parameters for UNIXy or Windows platforms to isolate the process from FakeNet-NG to prevent it from being interrupted by termination of Fa...
OS-agnostic asynchronous subprocess creation. Executes the process with the appropriate subprocess.Popen parameters for UNIXy or Windows platforms to isolate the process from FakeNet-NG to prevent it from being interrupted by termination of FakeNet-NG, Ctrl-C, etc. Args: ...
execute_detached
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def parse_diverter_config(self): """Parse [Diverter] config section. Args: N/A Side-effects: Diverter members (whitelists, pcap, etc.) initialized. Returns: None """ # SingleHost vs MultiHost mode self.network_mode = 'SingleHost' # Defa...
Parse [Diverter] config section. Args: N/A Side-effects: Diverter members (whitelists, pcap, etc.) initialized. Returns: None
parse_diverter_config
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def write_pcap(self, pkt): """Writes a packet to the pcap. Args: pkt: A fnpacket.PacketCtx or derived object Returns: None Side-effects: Calls dpkt.pcap.Writer.writekpt to persist the octets """ if self.pcap and self.pcap_lock: ...
Writes a packet to the pcap. Args: pkt: A fnpacket.PacketCtx or derived object Returns: None Side-effects: Calls dpkt.pcap.Writer.writekpt to persist the octets
write_pcap
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def formatPkt(self, pkt, pid, comm): """Format a packet analysis log line for DGENPKTV. Args: pkt: A fnpacket.PacketCtx or derived object pid: Process ID associated with the packet comm: Process executable name Returns: A str containing the log l...
Format a packet analysis log line for DGENPKTV. Args: pkt: A fnpacket.PacketCtx or derived object pid: Process ID associated with the packet comm: Process executable name Returns: A str containing the log line
formatPkt
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def check_should_ignore(self, pkt, pid, comm): """Indicate whether a packet should be passed without mangling. Checks whether the packet matches black and whitelists, or whether it signifies an FTP Active Mode connection. Args: pkt: A fnpacket.PacketCtx or derived object ...
Indicate whether a packet should be passed without mangling. Checks whether the packet matches black and whitelists, or whether it signifies an FTP Active Mode connection. Args: pkt: A fnpacket.PacketCtx or derived object pid: Process ID associated with the packet ...
check_should_ignore
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def check_log_icmp(self, crit, pkt): """Log an ICMP packet if the header was parsed as ICMP. Args: crit: A DivertParms object pkt: An fnpacket.PacketCtx or derived object Returns: None """ if (pkt.is_icmp and (not self.running_on_windows or ...
Log an ICMP packet if the header was parsed as ICMP. Args: crit: A DivertParms object pkt: An fnpacket.PacketCtx or derived object Returns: None
check_log_icmp
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def getOriginalDestPort(self, orig_src_ip, orig_src_port, proto): """Return original destination port, or None if it was not redirected. The proxy listener uses this method to obtain and provide port information to listeners in the taste() callback as an extra hint as to whether the tra...
Return original destination port, or None if it was not redirected. The proxy listener uses this method to obtain and provide port information to listeners in the taste() callback as an extra hint as to whether the traffic may be appropriate for parsing by that listener. Args: ...
getOriginalDestPort
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def maybe_redir_ip(self, crit, pkt, pid, comm): """Conditionally redirect foreign destination IPs to localhost. On Linux, this is used only under SingleHost mode. Args: crit: DivertParms object pkt: fnpacket.PacketCtx or derived object pid: int process ID as...
Conditionally redirect foreign destination IPs to localhost. On Linux, this is used only under SingleHost mode. Args: crit: DivertParms object pkt: fnpacket.PacketCtx or derived object pid: int process ID associated with the packet comm: Process name (co...
maybe_redir_ip
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def maybe_fixup_srcip(self, crit, pkt, pid, comm): """Conditionally fix up the source IP address if the remote endpoint had their connection IP-forwarded. Check is based on whether the remote endpoint corresponds to a key in the IP forwarding table. Args: crit: Dive...
Conditionally fix up the source IP address if the remote endpoint had their connection IP-forwarded. Check is based on whether the remote endpoint corresponds to a key in the IP forwarding table. Args: crit: DivertParms object pkt: fnpacket.PacketCtx or derived ...
maybe_fixup_srcip
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def maybe_redir_port(self, crit, pkt, pid, comm): """Conditionally send packets to the default listener for this proto. Args: crit: DivertParms object pkt: fnpacket.PacketCtx or derived object pid: int process ID associated with the packet comm: Process n...
Conditionally send packets to the default listener for this proto. Args: crit: DivertParms object pkt: fnpacket.PacketCtx or derived object pid: int process ID associated with the packet comm: Process name (command) that sent the packet Side-effects: ...
maybe_redir_port
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def maybe_fixup_sport(self, crit, pkt, pid, comm): """Conditionally fix up source port if the remote endpoint had their connection port-forwarded to the default listener. Check is based on whether the remote endpoint corresponds to a key in the port forwarding table. Side-effec...
Conditionally fix up source port if the remote endpoint had their connection port-forwarded to the default listener. Check is based on whether the remote endpoint corresponds to a key in the port forwarding table. Side-effects: May mangle the packet by modifying the source ...
maybe_fixup_sport
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def decide_redir_port(self, pkt, bound_ports): """Decide whether to redirect a port. Optimized logic derived by truth table + k-map. See docs/internals.md for details. Args: pkt: fnpacket.PacketCtx or derived object bound_ports: Set of ports that are bound for t...
Decide whether to redirect a port. Optimized logic derived by truth table + k-map. See docs/internals.md for details. Args: pkt: fnpacket.PacketCtx or derived object bound_ports: Set of ports that are bound for this protocol Returns: True if the pac...
decide_redir_port
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def addSession(self, pkt): """Add a connection to the sessions hash table. Args: pkt: fnpacket.PacketCtx or derived object Returns: None """ session = namedtuple('session', ['dst_ip', 'dport', 'pid', 'comm', 'dpor...
Add a connection to the sessions hash table. Args: pkt: fnpacket.PacketCtx or derived object Returns: None
addSession
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def maybeExecuteCmd(self, pkt, pid, comm): """Execute any ExecuteCmd associated with this port/listener. Args: pkt: fnpacket.PacketCtx or derived object pid: int process ID associated with the packet comm: Process name (command) that sent the packet Returns:...
Execute any ExecuteCmd associated with this port/listener. Args: pkt: fnpacket.PacketCtx or derived object pid: int process ID associated with the packet comm: Process name (command) that sent the packet Returns: None
maybeExecuteCmd
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def mapProxySportToOrigSport(self, proto, orig_sport, proxy_sport, is_ssl_encrypted): """Maps Proxy initiated source ports to their original source ports. The Proxy listener uses this method to notify the diverter about the proxy originated source port for the original source port. ...
Maps Proxy initiated source ports to their original source ports. The Proxy listener uses this method to notify the diverter about the proxy originated source port for the original source port. It also notifies if the packet uses SSL encryption. Args: proto: str protocol of...
mapProxySportToOrigSport
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def logNbi(self, sport, nbi, proto, application_layer_proto, is_ssl_encrypted): """Collects the NBIs from all listeners into a dictionary. All listeners use this method to notify the diverter about any NBI captured within their scope. Args: sport: int port bound...
Collects the NBIs from all listeners into a dictionary. All listeners use this method to notify the diverter about any NBI captured within their scope. Args: sport: int port bound by listener nbi: dict NBI captured within the listener proto: str protocol use...
logNbi
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def prettyPrintNbi(self): """Convenience method to print all NBIs in appropriate format upon fakenet session termination. Called by stop() method of diverter. """ banner = r""" ...
Convenience method to print all NBIs in appropriate format upon fakenet session termination. Called by stop() method of diverter.
prettyPrintNbi
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def generate_html_report(self): """Generates an interactive HTML report containing NBI summary saved to the main working directory of flare-fakenet-ng. Called by stop() method of diverter. """ if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'): # Inside a P...
Generates an interactive HTML report containing NBI summary saved to the main working directory of flare-fakenet-ng. Called by stop() method of diverter.
generate_html_report
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def isProcessBlackListed(self, proto, sport=None, process_name=None, dport=None): """Checks if a process is blacklisted. Expected arguments are either: - process_name and dport, or - sport """ pid = None if self.single_host_mode and proto is not None: ...
Checks if a process is blacklisted. Expected arguments are either: - process_name and dport, or - sport
isProcessBlackListed
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def logNbi(self, sport, nbi, proto, application_layer_proto, is_ssl_encrypted): """Delegate the logging of NBIs to the diverter. This method forwards the provided NBI information to the logNbi() method in the underlying diverter object. Called by all listeners to log NBIs. "...
Delegate the logging of NBIs to the diverter. This method forwards the provided NBI information to the logNbi() method in the underlying diverter object. Called by all listeners to log NBIs.
logNbi
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def mapProxySportToOrigSport(self, proto, orig_sport, proxy_sport, is_ssl_encrypted): """Delegate the mapping of proxy sport to original sport to the diverter. This method forwards the provided parameters to the mapProxySportToOrigSport() method in the underlying diverter ob...
Delegate the mapping of proxy sport to original sport to the diverter. This method forwards the provided parameters to the mapProxySportToOrigSport() method in the underlying diverter object. Called by ProxyListener to report the mapping between proxy initiated source port and o...
mapProxySportToOrigSport
python
mandiant/flare-fakenet-ng
fakenet/diverters/diverterbase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/diverterbase.py
Apache-2.0
def configure(self, config_dict, portlists=[], stringlists=[], idlists=[]): """Parse configuration. Does three things: 1.) Turn dictionary keys to lowercase 2.) Turn string lists into arrays for quicker access 3.) Expand port range specifications """ ...
Parse configuration. Does three things: 1.) Turn dictionary keys to lowercase 2.) Turn string lists into arrays for quicker access 3.) Expand port range specifications
configure
python
mandiant/flare-fakenet-ng
fakenet/diverters/fnconfig.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/fnconfig.py
Apache-2.0
def _parseIp(self): """Parse IP src/dst fields and next-layer fields if recognized.""" if self._is_ip: self._src_ip0 = self._src_ip = socket.inet_ntoa(self._hdr.src) self._dst_ip0 = self._dst_ip = socket.inet_ntoa(self._hdr.dst) self.proto = self.handled_protocols.get...
Parse IP src/dst fields and next-layer fields if recognized.
_parseIp
python
mandiant/flare-fakenet-ng
fakenet/diverters/fnpacket.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/fnpacket.py
Apache-2.0
def _calcCsums(self): """The roundabout dance of inducing dpkt to recalculate checksums...""" self._hdr.sum = 0 self._hdr.data.sum = 0 # This has the side-effect of invoking dpkt.in_cksum() et al: str(self._hdr)
The roundabout dance of inducing dpkt to recalculate checksums...
_calcCsums
python
mandiant/flare-fakenet-ng
fakenet/diverters/fnpacket.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/fnpacket.py
Apache-2.0
def _iptables_format(self, chain, iface, argfmt): """Format iptables command line with optional interface restriction. Parameters ---------- chain : string One of 'OUTPUT', 'POSTROUTING', 'INPUT', or 'PREROUTING', used for deciding the correct flag (-i versus -o)...
Format iptables command line with optional interface restriction. Parameters ---------- chain : string One of 'OUTPUT', 'POSTROUTING', 'INPUT', or 'PREROUTING', used for deciding the correct flag (-i versus -o) iface : string or NoneType Name of inter...
_iptables_format
python
mandiant/flare-fakenet-ng
fakenet/diverters/linutil.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/linutil.py
Apache-2.0
def start(self, timeout_sec=0.5): """Binds to the netfilter queue number specified in the ctor, obtains the netlink socket, sets a timeout of <timeout_sec>, and starts the thread procedure which checks _stopflag every time the netlink socket times out. """ # Execute ipta...
Binds to the netfilter queue number specified in the ctor, obtains the netlink socket, sets a timeout of <timeout_sec>, and starts the thread procedure which checks _stopflag every time the netlink socket times out.
start
python
mandiant/flare-fakenet-ng
fakenet/diverters/linutil.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/linutil.py
Apache-2.0
def parse(self, multi=False, max_col=None): """Rip through the file and call cb to extract field(s). Specify multi if you want to collect an aray instead of exiting the first time the callback returns anything. Only specify max_col if you are uncertain that the maximum column n...
Rip through the file and call cb to extract field(s). Specify multi if you want to collect an aray instead of exiting the first time the callback returns anything. Only specify max_col if you are uncertain that the maximum column number you will access may exist. For procfs files, this...
parse
python
mandiant/flare-fakenet-ng
fakenet/diverters/linutil.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/linutil.py
Apache-2.0
def linux_get_current_nfnlq_bindings(self): """Determine what NFQUEUE queue numbers (if any) are already bound by existing libnfqueue client processes. Although iptables rules may exist specifying other queues in addition to these, the netfilter team does not support using libiptc (such...
Determine what NFQUEUE queue numbers (if any) are already bound by existing libnfqueue client processes. Although iptables rules may exist specifying other queues in addition to these, the netfilter team does not support using libiptc (such as via python-iptables) to detect that conditi...
linux_get_current_nfnlq_bindings
python
mandiant/flare-fakenet-ng
fakenet/diverters/linutil.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/linutil.py
Apache-2.0
def linux_iptables_redir_iface(self, iface): """Linux-specific iptables processing for interface-based redirect rules. returns: tuple(bool, list(IptCmdTemplate)) Status of the operation and any successful iptables rules that will need to be undone. ""...
Linux-specific iptables processing for interface-based redirect rules. returns: tuple(bool, list(IptCmdTemplate)) Status of the operation and any successful iptables rules that will need to be undone.
linux_iptables_redir_iface
python
mandiant/flare-fakenet-ng
fakenet/diverters/linutil.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/linutil.py
Apache-2.0
def linux_remove_iptables_rules(self, rules): """Execute the iptables command to remove each rule that was successfully added. """ failed = [] for rule in rules: ret = rule.remove() if ret != 0: failed.append(rule) return failed
Execute the iptables command to remove each rule that was successfully added.
linux_remove_iptables_rules
python
mandiant/flare-fakenet-ng
fakenet/diverters/linutil.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/linutil.py
Apache-2.0
def linux_find_processes(self, names): """But what if a blacklisted process spawns after we call this? We'd have to call this every time we do anything. """ pids = [] proc_pid_dirs = glob.glob('/proc/[0-9]*/') comm_file = '' for proc_pid_dir in proc_pid_dirs: ...
But what if a blacklisted process spawns after we call this? We'd have to call this every time we do anything.
linux_find_processes
python
mandiant/flare-fakenet-ng
fakenet/diverters/linutil.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/linutil.py
Apache-2.0
def _linux_find_sock_by_endpoint_unsafe(self, ipver, proto_name, ip, port, local=True): """Search /proc/net/tcp for a socket whose local (field 1, zero-based) or remote (field 2) address matches ip:port and return the corresponding inode (field 9). ...
Search /proc/net/tcp for a socket whose local (field 1, zero-based) or remote (field 2) address matches ip:port and return the corresponding inode (field 9). Fields referenced above are zero-based. Example contents of /proc/net/tcp (wrapped and double-spaced) sl local_addre...
_linux_find_sock_by_endpoint_unsafe
python
mandiant/flare-fakenet-ng
fakenet/diverters/linutil.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/linutil.py
Apache-2.0
def linux_get_pid_comm_by_endpoint(self, ipver, proto_name, ip, port): """Obtain a pid and executable name associated with an endpoint. NOTE: procfs does not allow us to answer questions like "who just called send()?"; only questions like "who owns a socket associated with this local po...
Obtain a pid and executable name associated with an endpoint. NOTE: procfs does not allow us to answer questions like "who just called send()?"; only questions like "who owns a socket associated with this local port?" Since fork() etc. can result in multiple ownership, the real answer m...
linux_get_pid_comm_by_endpoint
python
mandiant/flare-fakenet-ng
fakenet/diverters/linutil.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/linutil.py
Apache-2.0
def handle_nonlocal(self, nfqpkt): """Handle comms sent to IP addresses that are not bound to any adapter. This allows analysts to observe when malware is communicating with hard-coded IP addresses in MultiHost mode. """ try: pkt = LinuxPacketCtx('handle_nonlocal', n...
Handle comms sent to IP addresses that are not bound to any adapter. This allows analysts to observe when malware is communicating with hard-coded IP addresses in MultiHost mode.
handle_nonlocal
python
mandiant/flare-fakenet-ng
fakenet/diverters/linux.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/linux.py
Apache-2.0
def handle_incoming(self, nfqpkt): """Incoming packet hook. Specific to incoming packets: 5.) If SingleHost mode: a.) Conditionally fix up source IPs to support IP forwarding for otherwise foreign-destined packets 4.) Conditionally mangle destination ports to...
Incoming packet hook. Specific to incoming packets: 5.) If SingleHost mode: a.) Conditionally fix up source IPs to support IP forwarding for otherwise foreign-destined packets 4.) Conditionally mangle destination ports to implement port forwarding for unb...
handle_incoming
python
mandiant/flare-fakenet-ng
fakenet/diverters/linux.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/linux.py
Apache-2.0
def handle_outgoing(self, nfqpkt): """Outgoing packet hook. Specific to outgoing packets: 4.) If SingleHost mode: a.) Conditionally log packets destined for foreign IP addresses (the corresponding check for MultiHost mode is called by handle_nonlocal(...
Outgoing packet hook. Specific to outgoing packets: 4.) If SingleHost mode: a.) Conditionally log packets destined for foreign IP addresses (the corresponding check for MultiHost mode is called by handle_nonlocal()) b.) Conditionally mangle destin...
handle_outgoing
python
mandiant/flare-fakenet-ng
fakenet/diverters/linux.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/linux.py
Apache-2.0
def check_log_nonlocal(self, crit, pkt): """Conditionally log packets having a foreign destination. Each foreign destination will be logged only once if the Linux Diverter's internal log_nonlocal_only_once flag is set. Otherwise, any foreign destination IP address will be logged each ti...
Conditionally log packets having a foreign destination. Each foreign destination will be logged only once if the Linux Diverter's internal log_nonlocal_only_once flag is set. Otherwise, any foreign destination IP address will be logged each time it is observed.
check_log_nonlocal
python
mandiant/flare-fakenet-ng
fakenet/diverters/linux.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/linux.py
Apache-2.0
def redirIcmpIpUnconditionally(self, crit, pkt): """Redirect ICMP to loopback or external IP if necessary. On Windows, we can't conveniently use an iptables REDIRECT rule to get ICMP packets sent back home for free, so here is some code. """ if (pkt.is_icmp and p...
Redirect ICMP to loopback or external IP if necessary. On Windows, we can't conveniently use an iptables REDIRECT rule to get ICMP packets sent back home for free, so here is some code.
redirIcmpIpUnconditionally
python
mandiant/flare-fakenet-ng
fakenet/diverters/windows.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/windows.py
Apache-2.0
def fix_gateway(self): """Check if there is a gateway configured on any of the Ethernet interfaces. If that's not the case, then locate configured IP address and set a gateway automatically. This is necessary for VMWare Host-Only DHCP server which leaves default gateway empty. ""...
Check if there is a gateway configured on any of the Ethernet interfaces. If that's not the case, then locate configured IP address and set a gateway automatically. This is necessary for VMWare Host-Only DHCP server which leaves default gateway empty.
fix_gateway
python
mandiant/flare-fakenet-ng
fakenet/diverters/winutil.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/winutil.py
Apache-2.0
def fix_dns(self): """Check if there is a DNS server on any of the Ethernet interfaces. If that's not the case, then locate configured IP address and set a DNS server automatically. """ fixed = False for adapter in self.get_adapters_info(): if self.check_ipa...
Check if there is a DNS server on any of the Ethernet interfaces. If that's not the case, then locate configured IP address and set a DNS server automatically.
fix_dns
python
mandiant/flare-fakenet-ng
fakenet/diverters/winutil.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/diverters/winutil.py
Apache-2.0
def failEarly(self): """Raise exceptions upon construction rather than later.""" # Test generating banner banner_generated = str(self) # Test generating and getting length of banner banner_generated_len = len(self) return banner_generated, banner_generated_len
Raise exceptions upon construction rather than later.
failEarly
python
mandiant/flare-fakenet-ng
fakenet/listeners/BannerFactory.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/listeners/BannerFactory.py
Apache-2.0
def __len__(self): """Needed for pyftpdlib. If the length changes between the time when the caller obtains the length and the time when the caller obtains the latest generated string, then there is not much that could reasonably be done. It would be possible to cache the...
Needed for pyftpdlib. If the length changes between the time when the caller obtains the length and the time when the caller obtains the latest generated string, then there is not much that could reasonably be done. It would be possible to cache the formatted banner with a short...
__len__
python
mandiant/flare-fakenet-ng
fakenet/listeners/BannerFactory.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/listeners/BannerFactory.py
Apache-2.0
def genBanner(self, config, bannerdict, defaultbannerkey='!generic'): """Select and initialize a banner. Supported banner escapes: !<key> - Use the banner whose key in bannerdict is <key> !random - Use a random banner from bannerdict !generic - Every listener...
Select and initialize a banner. Supported banner escapes: !<key> - Use the banner whose key in bannerdict is <key> !random - Use a random banner from bannerdict !generic - Every listener supporting banners must have a generic Banners can include literal ' ' ...
genBanner
python
mandiant/flare-fakenet-ng
fakenet/listeners/BannerFactory.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/listeners/BannerFactory.py
Apache-2.0
def log_message(self, log_level, is_process_blacklisted, message, *args): """The primary objective of this method is to control the log messages generated for requests from blacklisted processes. In a case where the DNS server is same as the local machine, the DNS requests from a blackl...
The primary objective of this method is to control the log messages generated for requests from blacklisted processes. In a case where the DNS server is same as the local machine, the DNS requests from a blacklisted process will reach the DNS listener (which listens on port 53 locally) ...
log_message
python
mandiant/flare-fakenet-ng
fakenet/listeners/DNSListener.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/listeners/DNSListener.py
Apache-2.0
def main(): """ Run from the flare-fakenet-ng root dir with the following command: python2 -m fakenet.listeners.HTTPListener """ logging.basicConfig(format='%(asctime)s [%(name)15s] %(message)s', datefmt='%m/%d/%y %I:%M:%S %p', level=logging.DEBUG) config = {'port': '8443', 'usessl': 'Yes'...
Run from the flare-fakenet-ng root dir with the following command: python2 -m fakenet.listeners.HTTPListener
main
python
mandiant/flare-fakenet-ng
fakenet/listeners/HTTPListener.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/listeners/HTTPListener.py
Apache-2.0
def safe_join(root, path): """ Joins a path to a root path, even if path starts with '/', using os.sep """ # prepending a '/' ensures '..' does not traverse past the root # of the path if not path.startswith('/'): path = '/' + path normpath = os.path.normpath(path) return roo...
Joins a path to a root path, even if path starts with '/', using os.sep
safe_join
python
mandiant/flare-fakenet-ng
fakenet/listeners/ListenerBase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/listeners/ListenerBase.py
Apache-2.0
def abs_config_path(path): """ Attempts to return the absolute path of a path from a configuration setting. First tries just to just take the abspath() of the parameter to see if it exists relative to the current working directory. If that does not exist, attempts to find it relative to the 'f...
Attempts to return the absolute path of a path from a configuration setting. First tries just to just take the abspath() of the parameter to see if it exists relative to the current working directory. If that does not exist, attempts to find it relative to the 'fakenet' package directory. Ret...
abs_config_path
python
mandiant/flare-fakenet-ng
fakenet/listeners/ListenerBase.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/listeners/ListenerBase.py
Apache-2.0
def main(): """ Run from the flare-fakenet-ng root dir with the following command: python2 -m fakenet.listeners.TFTPListener """ logging.basicConfig(format='%(asctime)s [%(name)15s] %(message)s', datefmt='%m/%d/%y %I:%M:%S %p', level=logging.DEBUG) config = {'port': '69', 'protocol': 'udp'...
Run from the flare-fakenet-ng root dir with the following command: python2 -m fakenet.listeners.TFTPListener
main
python
mandiant/flare-fakenet-ng
fakenet/listeners/TFTPListener.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/listeners/TFTPListener.py
Apache-2.0
def create_cert(self, cn, ca_cert=None, ca_key=None, cert_dir=None): """ Create a cert given the common name, a signing CA, CA private key and the directory output. return: tuple(None, None) on error tuple(cert_file_path, key_file_path) on success """ f_...
Create a cert given the common name, a signing CA, CA private key and the directory output. return: tuple(None, None) on error tuple(cert_file_path, key_file_path) on success
create_cert
python
mandiant/flare-fakenet-ng
fakenet/listeners/ssl_utils/__init__.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/listeners/ssl_utils/__init__.py
Apache-2.0
def abs_config_path(self, path): """ Attempts to return the absolute path of a path from a configuration setting. """ # Try absolute path first abspath = os.path.abspath(path) if os.path.exists(abspath): return abspath if getattr(sys, 'frozen...
Attempts to return the absolute path of a path from a configuration setting.
abs_config_path
python
mandiant/flare-fakenet-ng
fakenet/listeners/ssl_utils/__init__.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/fakenet/listeners/ssl_utils/__init__.py
Apache-2.0
def get_ips(ipvers): """Return IP addresses bound to local interfaces including loopbacks. Parameters ---------- ipvers : list IP versions desired (4, 6, or both); ensures the netifaces semantics (e.g. netiface.AF_INET) are localized to this function. """ specs = [] resu...
Return IP addresses bound to local interfaces including loopbacks. Parameters ---------- ipvers : list IP versions desired (4, 6, or both); ensures the netifaces semantics (e.g. netiface.AF_INET) are localized to this function.
get_ips
python
mandiant/flare-fakenet-ng
test/test.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/test/test.py
Apache-2.0
def _irc_evt_handler(self, srv, evt): """Check for each case and set the corresponding success flag.""" if evt.type == 'join': if evt.target.startswith(self.join_chan): self.join_ok = True elif evt.type == 'welcome': if evt.arguments[0].startswith('Welcome...
Check for each case and set the corresponding success flag.
_irc_evt_handler
python
mandiant/flare-fakenet-ng
test/test.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/test/test.py
Apache-2.0
def _irc_script(self, srv): """Callback manages individual test cases for IRC.""" # Clear success flags self.welcome_ok = False self.join_ok = False self.privmsg_ok = False self.pubmsg_ok = False # This handler should set the success flags in success cases ...
Callback manages individual test cases for IRC.
_irc_script
python
mandiant/flare-fakenet-ng
test/test.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/test/test.py
Apache-2.0
def _run_irc_script(self, nm, callback): """Connect to server and give control to callback.""" r = irc.client.Reactor() srv = r.server() srv.connect(self.hostname, self.port, self.nick) retval = callback(srv) srv.close() return retval
Connect to server and give control to callback.
_run_irc_script
python
mandiant/flare-fakenet-ng
test/test.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/test/test.py
Apache-2.0
def _filterMatchingTests(self, tests, matchspec): """Remove tests that match negative specifications (regexes preceded by a minus sign) or do not match positive specifications (regexes not preceded by a minus sign). Modifies the contents of the tests dictionary. """ nega...
Remove tests that match negative specifications (regexes preceded by a minus sign) or do not match positive specifications (regexes not preceded by a minus sign). Modifies the contents of the tests dictionary.
_filterMatchingTests
python
mandiant/flare-fakenet-ng
test/test.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/test/test.py
Apache-2.0
def _test_ftp(self, hostname, port=0): """Note that the FakeNet-NG Proxy listener won't know what to do with this client if you point it at some random port, because the client listens silently for the server 220 welcome message which doesn't give the Proxy listener anything to work with...
Note that the FakeNet-NG Proxy listener won't know what to do with this client if you point it at some random port, because the client listens silently for the server 220 welcome message which doesn't give the Proxy listener anything to work with to decide where to forward it.
_test_ftp
python
mandiant/flare-fakenet-ng
test/test.py
https://github.com/mandiant/flare-fakenet-ng/blob/master/test/test.py
Apache-2.0
def preprocess_input(audio_path, dim_ordering='default'): '''Reads an audio file and outputs a Mel-spectrogram. ''' if dim_ordering == 'default': dim_ordering = K.image_dim_ordering() assert dim_ordering in {'tf', 'th'} if librosa_exists(): import librosa else: raise Run...
Reads an audio file and outputs a Mel-spectrogram.
preprocess_input
python
fchollet/deep-learning-models
audio_conv_utils.py
https://github.com/fchollet/deep-learning-models/blob/master/audio_conv_utils.py
MIT
def decode_predictions(preds, top_n=5): '''Decode the output of a music tagger model. # Arguments preds: 2-dimensional numpy array top_n: integer in [0, 50], number of items to show ''' assert len(preds.shape) == 2 and preds.shape[1] == 50 results = [] for pred in preds: ...
Decode the output of a music tagger model. # Arguments preds: 2-dimensional numpy array top_n: integer in [0, 50], number of items to show
decode_predictions
python
fchollet/deep-learning-models
audio_conv_utils.py
https://github.com/fchollet/deep-learning-models/blob/master/audio_conv_utils.py
MIT
def preprocess_input(x): """Preprocesses a numpy array encoding a batch of images. This function applies the "Inception" preprocessing which converts the RGB values from [0, 255] to [-1, 1]. Note that this preprocessing function is different from `imagenet_utils.preprocess_input()`. # Arguments ...
Preprocesses a numpy array encoding a batch of images. This function applies the "Inception" preprocessing which converts the RGB values from [0, 255] to [-1, 1]. Note that this preprocessing function is different from `imagenet_utils.preprocess_input()`. # Arguments x: a 4D numpy array consis...
preprocess_input
python
fchollet/deep-learning-models
inception_resnet_v2.py
https://github.com/fchollet/deep-learning-models/blob/master/inception_resnet_v2.py
MIT
def conv2d_bn(x, filters, kernel_size, strides=1, padding='same', activation='relu', use_bias=False, name=None): """Utility function to apply conv + BN. # Arguments x: input tensor. filters: filter...
Utility function to apply conv + BN. # Arguments x: input tensor. filters: filters in `Conv2D`. kernel_size: kernel size as in `Conv2D`. padding: padding mode in `Conv2D`. activation: activation in `Conv2D`. strides: strides in `Conv2D`. name: name of the ops...
conv2d_bn
python
fchollet/deep-learning-models
inception_resnet_v2.py
https://github.com/fchollet/deep-learning-models/blob/master/inception_resnet_v2.py
MIT
def inception_resnet_block(x, scale, block_type, block_idx, activation='relu'): """Adds a Inception-ResNet block. This function builds 3 types of Inception-ResNet blocks mentioned in the paper, controlled by the `block_type` argument (which is the block name used in the official TF-slim implementation)...
Adds a Inception-ResNet block. This function builds 3 types of Inception-ResNet blocks mentioned in the paper, controlled by the `block_type` argument (which is the block name used in the official TF-slim implementation): - Inception-ResNet-A: `block_type='block35'` - Inception-ResNet-B: `b...
inception_resnet_block
python
fchollet/deep-learning-models
inception_resnet_v2.py
https://github.com/fchollet/deep-learning-models/blob/master/inception_resnet_v2.py
MIT
def InceptionResNetV2(include_top=True, weights='imagenet', input_tensor=None, input_shape=None, pooling=None, classes=1000): """Instantiates the Inception-ResNet v2 architecture. Optionally loads weig...
Instantiates the Inception-ResNet v2 architecture. Optionally loads weights pre-trained on ImageNet. Note that when using TensorFlow, for best performance you should set `"image_data_format": "channels_last"` in your Keras config at `~/.keras/keras.json`. The model and the weights are compatible w...
InceptionResNetV2
python
fchollet/deep-learning-models
inception_resnet_v2.py
https://github.com/fchollet/deep-learning-models/blob/master/inception_resnet_v2.py
MIT
def conv2d_bn(x, filters, num_row, num_col, padding='same', strides=(1, 1), name=None): """Utility function to apply conv + BN. Arguments: x: input tensor. filters: filters in `Conv2D`. num_row: height o...
Utility function to apply conv + BN. Arguments: x: input tensor. filters: filters in `Conv2D`. num_row: height of the convolution kernel. num_col: width of the convolution kernel. padding: padding mode in `Conv2D`. strides: strides in `Conv2D`. name: name of ...
conv2d_bn
python
fchollet/deep-learning-models
inception_v3.py
https://github.com/fchollet/deep-learning-models/blob/master/inception_v3.py
MIT
def InceptionV3(include_top=True, weights='imagenet', input_tensor=None, input_shape=None, pooling=None, classes=1000): """Instantiates the Inception v3 architecture. Optionally loads weights pre-trained on ImageNet. Note that ...
Instantiates the Inception v3 architecture. Optionally loads weights pre-trained on ImageNet. Note that when using TensorFlow, for best performance you should set `image_data_format="channels_last"` in your Keras config at ~/.keras/keras.json. The model and the weights are compatible with both ...
InceptionV3
python
fchollet/deep-learning-models
inception_v3.py
https://github.com/fchollet/deep-learning-models/blob/master/inception_v3.py
MIT
def MobileNet(input_shape=None, alpha=1.0, depth_multiplier=1, dropout=1e-3, include_top=True, weights='imagenet', input_tensor=None, pooling=None, classes=1000): """Instantiates the MobileNet architectur...
Instantiates the MobileNet architecture. Note that only TensorFlow is supported for now, therefore it only works with the data format `image_data_format='channels_last'` in your Keras config at `~/.keras/keras.json`. To load a MobileNet model via `load_model`, import the custom objects `relu6`...
MobileNet
python
fchollet/deep-learning-models
mobilenet.py
https://github.com/fchollet/deep-learning-models/blob/master/mobilenet.py
MIT
def _conv_block(inputs, filters, alpha, kernel=(3, 3), strides=(1, 1)): """Adds an initial convolution layer (with batch normalization and relu6). # Arguments inputs: Input tensor of shape `(rows, cols, 3)` (with `channels_last` data format) or (3, rows, cols) (with `channels_fi...
Adds an initial convolution layer (with batch normalization and relu6). # Arguments inputs: Input tensor of shape `(rows, cols, 3)` (with `channels_last` data format) or (3, rows, cols) (with `channels_first` data format). It should have exactly 3 inputs channels, ...
_conv_block
python
fchollet/deep-learning-models
mobilenet.py
https://github.com/fchollet/deep-learning-models/blob/master/mobilenet.py
MIT
def _depthwise_conv_block(inputs, pointwise_conv_filters, alpha, depth_multiplier=1, strides=(1, 1), block_id=1): """Adds a depthwise convolution block. A depthwise convolution block consists of a depthwise conv, batch normalization, relu6, pointwise convolution, batch normali...
Adds a depthwise convolution block. A depthwise convolution block consists of a depthwise conv, batch normalization, relu6, pointwise convolution, batch normalization and relu6 activation. # Arguments inputs: Input tensor of shape `(rows, cols, channels)` (with `channels_last` data...
_depthwise_conv_block
python
fchollet/deep-learning-models
mobilenet.py
https://github.com/fchollet/deep-learning-models/blob/master/mobilenet.py
MIT
def MusicTaggerCRNN(weights='msd', input_tensor=None, include_top=True): '''Instantiate the MusicTaggerCRNN architecture, optionally loading weights pre-trained on Million Song Dataset. Note that when using TensorFlow, for best performance you should set `image_dim_ordering="tf"`...
Instantiate the MusicTaggerCRNN architecture, optionally loading weights pre-trained on Million Song Dataset. Note that when using TensorFlow, for best performance you should set `image_dim_ordering="tf"` in your Keras config at ~/.keras/keras.json. The model and the weights are compatible with...
MusicTaggerCRNN
python
fchollet/deep-learning-models
music_tagger_crnn.py
https://github.com/fchollet/deep-learning-models/blob/master/music_tagger_crnn.py
MIT
def identity_block(input_tensor, kernel_size, filters, stage, block): """The identity block is the block that has no conv layer at shortcut. # Arguments input_tensor: input tensor kernel_size: defualt 3, the kernel size of middle conv layer at main path filters: list of integers, the fi...
The identity block is the block that has no conv layer at shortcut. # Arguments input_tensor: input tensor kernel_size: defualt 3, the kernel size of middle conv layer at main path filters: list of integers, the filterss of 3 conv layer at main path stage: integer, current stage lab...
identity_block
python
fchollet/deep-learning-models
resnet50.py
https://github.com/fchollet/deep-learning-models/blob/master/resnet50.py
MIT
def conv_block(input_tensor, kernel_size, filters, stage, block, strides=(2, 2)): """conv_block is the block that has a conv layer at shortcut # Arguments input_tensor: input tensor kernel_size: defualt 3, the kernel size of middle conv layer at main path filters: list of integers, the ...
conv_block is the block that has a conv layer at shortcut # Arguments input_tensor: input tensor kernel_size: defualt 3, the kernel size of middle conv layer at main path filters: list of integers, the filterss of 3 conv layer at main path stage: integer, current stage label, used f...
conv_block
python
fchollet/deep-learning-models
resnet50.py
https://github.com/fchollet/deep-learning-models/blob/master/resnet50.py
MIT
def ResNet50(include_top=True, weights='imagenet', input_tensor=None, input_shape=None, pooling=None, classes=1000): """Instantiates the ResNet50 architecture. Optionally loads weights pre-trained on ImageNet. Note that when using TensorFlow, for best performance ...
Instantiates the ResNet50 architecture. Optionally loads weights pre-trained on ImageNet. Note that when using TensorFlow, for best performance you should set `image_data_format="channels_last"` in your Keras config at ~/.keras/keras.json. The model and the weights are compatible with both ...
ResNet50
python
fchollet/deep-learning-models
resnet50.py
https://github.com/fchollet/deep-learning-models/blob/master/resnet50.py
MIT
def VGG16(include_top=True, weights='imagenet', input_tensor=None, input_shape=None, pooling=None, classes=1000): """Instantiates the VGG16 architecture. Optionally loads weights pre-trained on ImageNet. Note that when using TensorFlow, for best performance you should set ...
Instantiates the VGG16 architecture. Optionally loads weights pre-trained on ImageNet. Note that when using TensorFlow, for best performance you should set `image_data_format="channels_last"` in your Keras config at ~/.keras/keras.json. The model and the weights are compatible with both Te...
VGG16
python
fchollet/deep-learning-models
vgg16.py
https://github.com/fchollet/deep-learning-models/blob/master/vgg16.py
MIT
def VGG19(include_top=True, weights='imagenet', input_tensor=None, input_shape=None, pooling=None, classes=1000): """Instantiates the VGG19 architecture. Optionally loads weights pre-trained on ImageNet. Note that when using TensorFlow, for best performance you should set ...
Instantiates the VGG19 architecture. Optionally loads weights pre-trained on ImageNet. Note that when using TensorFlow, for best performance you should set `image_data_format="channels_last"` in your Keras config at ~/.keras/keras.json. The model and the weights are compatible with both Te...
VGG19
python
fchollet/deep-learning-models
vgg19.py
https://github.com/fchollet/deep-learning-models/blob/master/vgg19.py
MIT
def Xception(include_top=True, weights='imagenet', input_tensor=None, input_shape=None, pooling=None, classes=1000): """Instantiates the Xception architecture. Optionally loads weights pre-trained on ImageNet. This model is available for TensorFlow only, and can o...
Instantiates the Xception architecture. Optionally loads weights pre-trained on ImageNet. This model is available for TensorFlow only, and can only be used with inputs following the TensorFlow data format `(width, height, channels)`. You should set `image_data_format="channels_last"` in your Keras ...
Xception
python
fchollet/deep-learning-models
xception.py
https://github.com/fchollet/deep-learning-models/blob/master/xception.py
MIT
def beam_search_generator(sess, net, initial_state, initial_sample, early_term_token, beam_width, forward_model_fn, forward_args): '''Run beam search! Yield consensus tokens sequentially, as a generator; return when reaching early_term_token (newline). Args: sess: tensorflow session reference ...
Run beam search! Yield consensus tokens sequentially, as a generator; return when reaching early_term_token (newline). Args: sess: tensorflow session reference net: tensorflow net graph (must be compatible with the forward_net function) initial_state: initial hidden state of the net ...
beam_search_generator
python
pender/chatbot-rnn
chatbot.py
https://github.com/pender/chatbot-rnn/blob/master/chatbot.py
MIT
def __init__(self, cell_fn, partition_size=128, partitions=1, layers=2): """Create a RNN cell composed sequentially of a number of RNNCells. Args: cell_fn: reference to RNNCell function to create each partition in each layer. partition_size: how many horizontal cells to include i...
Create a RNN cell composed sequentially of a number of RNNCells. Args: cell_fn: reference to RNNCell function to create each partition in each layer. partition_size: how many horizontal cells to include in each partition. partitions: how many horizontal partitions to include ...
__init__
python
pender/chatbot-rnn
model.py
https://github.com/pender/chatbot-rnn/blob/master/model.py
MIT
def _rnn_state_placeholders(state): """Convert RNN state tensors to placeholders, reflecting the same nested tuple structure.""" # Adapted from @carlthome's comment: # https://github.com/tensorflow/tensorflow/issues/2838#issuecomment-302019188 if isinstance(state, tf.contrib.rnn.LSTMStateTuple): ...
Convert RNN state tensors to placeholders, reflecting the same nested tuple structure.
_rnn_state_placeholders
python
pender/chatbot-rnn
model.py
https://github.com/pender/chatbot-rnn/blob/master/model.py
MIT
def forward_model(self, sess, state, input_sample): '''Run a forward pass. Return the updated hidden state and the output probabilities.''' shaped_input = np.array([[input_sample]], np.float32) inputs = {self.input_data: shaped_input} self.add_state_to_feed_dict(inputs, state) [p...
Run a forward pass. Return the updated hidden state and the output probabilities.
forward_model
python
pender/chatbot-rnn
model.py
https://github.com/pender/chatbot-rnn/blob/master/model.py
MIT
def check_container_exec_instances(context, num): """Modern docker versions remove ExecIDs after they finished, but older docker versions leave ExecIDs behind. This test is for asserting that the ExecIDs are cleaned up one way or another""" container_info = context.docker_client.inspect_container( ...
Modern docker versions remove ExecIDs after they finished, but older docker versions leave ExecIDs behind. This test is for asserting that the ExecIDs are cleaned up one way or another
check_container_exec_instances
python
Yelp/paasta
general_itests/steps/paasta_execute_docker_command.py
https://github.com/Yelp/paasta/blob/master/general_itests/steps/paasta_execute_docker_command.py
Apache-2.0
def tail_paasta_logs_let_threads_be_threads(context): """This test lets tail_paasta_logs() fire off processes to do work. We verify that the work was done, basically irrespective of how it was done. """ service = "fake_service" context.levels = ["fake_level1", "fake_level2"] context.components =...
This test lets tail_paasta_logs() fire off processes to do work. We verify that the work was done, basically irrespective of how it was done.
tail_paasta_logs_let_threads_be_threads
python
Yelp/paasta
general_itests/steps/tail_paasta_logs.py
https://github.com/Yelp/paasta/blob/master/general_itests/steps/tail_paasta_logs.py
Apache-2.0
def register_bounce_method(name: str) -> Callable[[BounceMethod], BounceMethod]: """Returns a decorator that registers that bounce function at a given name so get_bounce_method_func can find it.""" def outer(bounce_func: BounceMethod): _bounce_method_funcs[name] = bounce_func return bounce_...
Returns a decorator that registers that bounce function at a given name so get_bounce_method_func can find it.
register_bounce_method
python
Yelp/paasta
paasta_tools/bounce_lib.py
https://github.com/Yelp/paasta/blob/master/paasta_tools/bounce_lib.py
Apache-2.0
def brutal_bounce( new_config: BounceMethodConfigDict, new_app_running: bool, happy_new_tasks: Collection, old_non_draining_tasks: Sequence, margin_factor=1.0, ) -> BounceMethodResult: """Pays no regard to safety. Starts the new app if necessary, and kills any old ones. Mostly meant as an ex...
Pays no regard to safety. Starts the new app if necessary, and kills any old ones. Mostly meant as an example of the simplest working bounce method, but might be tolerable for some services. :param new_config: The configuration dictionary representing the desired new app. :param new_app_running: Whethe...
brutal_bounce
python
Yelp/paasta
paasta_tools/bounce_lib.py
https://github.com/Yelp/paasta/blob/master/paasta_tools/bounce_lib.py
Apache-2.0
def upthendown_bounce( new_config: BounceMethodConfigDict, new_app_running: bool, happy_new_tasks: Collection, old_non_draining_tasks: Sequence, margin_factor=1.0, ) -> BounceMethodResult: """Starts a new app if necessary; only kills old apps once all the requested tasks for the new version are ...
Starts a new app if necessary; only kills old apps once all the requested tasks for the new version are running. See the docstring for brutal_bounce() for parameters and return value.
upthendown_bounce
python
Yelp/paasta
paasta_tools/bounce_lib.py
https://github.com/Yelp/paasta/blob/master/paasta_tools/bounce_lib.py
Apache-2.0
def crossover_bounce( new_config: BounceMethodConfigDict, new_app_running: bool, happy_new_tasks: Collection, old_non_draining_tasks: Sequence, margin_factor=1.0, ) -> BounceMethodResult: """Starts a new app if necessary; slowly kills old apps as instances of the new app become happy. See t...
Starts a new app if necessary; slowly kills old apps as instances of the new app become happy. See the docstring for brutal_bounce() for parameters and return value.
crossover_bounce
python
Yelp/paasta
paasta_tools/bounce_lib.py
https://github.com/Yelp/paasta/blob/master/paasta_tools/bounce_lib.py
Apache-2.0
def downthenup_bounce( new_config: BounceMethodConfigDict, new_app_running: bool, happy_new_tasks: Collection, old_non_draining_tasks: Sequence, margin_factor=1.0, ) -> BounceMethodResult: """Stops any old apps and waits for them to die before starting a new one. See the docstring for bruta...
Stops any old apps and waits for them to die before starting a new one. See the docstring for brutal_bounce() for parameters and return value.
downthenup_bounce
python
Yelp/paasta
paasta_tools/bounce_lib.py
https://github.com/Yelp/paasta/blob/master/paasta_tools/bounce_lib.py
Apache-2.0