
    Xfr                         d dl Z d dlZd dlmZmZmZmZ d dlmZm	Z	m
Z
mZmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d d	lmZmZmZmZ  ej        e          Z G d
 de
j        j         ej!                  Z"dS )    N)IterableOptional	GeneratorTuple)	constants
exceptions
interfaces	rendererssymbols)requirements)format_hints)pdbutil)network)	timeliner)netscanmodulesinfoverinfoc                      e Zd ZdZdZdZed             Zed             Zede	j
        j        deded	ed
ef
d            Zede	j
        j        dededed
ef
d            Ze	 d'de	j
        j        dedededed
ee	j        j                 fd            Zede	j
        j        deded
ee	j        j                 fd            Zede	j
        j        dededededed
ee	j        j        ddf         fd            Zede	j
        j        dedededed
ee	j        j                 fd            Zede	j
        j        dedededed
efd             Zede	j
        j        dedededed
eeef         fd!            Zede	j
        j        dededededed
ee	j        j                 fd"            Zd(d#ee         fd$Zd% Z d& Z!dS ))NetStatzSTraverses network tracking structures present in a particular windows memory image.)   r   r      r   r   c                    t          j        ddddg          t          j        dt          j        d          t          j        d	t
          j        d          t          j        d
t          j        d          t          j        dt          j
        d          t          j        dt          j        d          t          j        dddd          gS )NkernelzWindows kernelIntel32Intel64)namedescriptionarchitecturesr   r   )r   	componentversionr   r   r   r   include-corruptzRadically eases result validation. This will show partially overwritten data. WARNING: the results are likely to include garbage and/or corrupt data. Be cautious!FT)r   r   defaultoptional)r   ModuleRequirementVersionRequirementr   NetScanr   Modulesr   
PDBUtilityr   Infor   VerInfoBooleanRequirement)clss    _/home/panchajanya/Development/work/volatility3/volatility3/framework/plugins/windows/netstat.pyget_requirementszNetStat.get_requirements   s     *,()4  
 +'/9   +'/9   +'*<i   +ty)   +'/9   +& A	  +
 	
    c                     |dz  }|S )zCopied from `windows.handles`.

        Windows encodes pointers to objects and decodes them on the fly
        before using them.

        This function mimics the decoding routine so we can generate the
        proper pointer values as well.
        l     )r.   values     r/   _decode_pointerzNetStat._decode_pointer9   s     **r1   context
layer_nameoffsetlengthreturnc                 v    t                               |j        |                             ||          d          S )a  Reads a pointer at a given offset and returns the address it points to.

        Args:
            context: The context to retrieve required elements (layers, symbol tables) from
            layer_name: The name of the layer on which to operate
            offset: Offset of pointer
            length: Pointer length

        Returns:
            The value the pointer points to.
        little)int
from_byteslayersread)r.   r6   r7   r8   r9   s        r/   read_pointerzNetStat.read_pointerH   s/    ( ~~gnZ8==ffMMxXXXr1   bitmap_offsetbitmap_size_in_bytec                     g }t          |          D ]g}|j        |                             ||z   d          d         }|dz  }t          d          D ]&}	|d|	z  z  dk    r|                    |	|z              'h|S )a  Parses a given bitmap and looks for each occurrence of a 1.

        Args:
            context: The context to retrieve required elements (layers, symbol tables) from
            layer_name: The name of the layer on which to operate
            bitmap_offset: Start address of bitmap
            bitmap_size_in_byte: Bitmap size in Byte, not in bit.

        Returns:
            The list of indices at which a 1 was found.
        r   r      )ranger?   r@   append)
r.   r6   r7   rB   rC   retidxcurrent_bytecurrent_offsbits
             r/   parse_bitmapzNetStat.parse_bitmap^   s    & ,-- 	3 	3C">*5::=3;NPQRRSTUL7LQxx 3 318,11JJs\12223 
r1   tcpnet_symbol_tableportport_pool_addrc              #     K   |dk    r@|t           j        z   dz   }|j                            |                              d          }nH|dk    r@|t           j        z   dz   }|j                            |                              d          }ndS t
                              d|            |dz	  }	|d	z  }
|                    |t           j        z   d
z   ||          }|j        |	         }|j	        j
        |
         }|sdS |                     |j                  }|rf|                    ||||z
            }|V  |j        rB|                    |||                     |j                  |z
            }|V  |j        >dS dS dS )a  Lists all UDP Endpoints and TCP Listeners by parsing UdpPortPool and TcpPortPool.

        Args:
            context: The context to retrieve required elements (layers, symbol tables) from
            layer_name: The name of the layer on which to operate
            net_symbol_table: The name of the table containing the tcpip types
            port: Current port as integer to lookup the associated object.
            port_pool_addr: Address of port pool object
            proto: Either "tcp" or "udp" to decide which types to use.

        Returns:
            The list of network objects from this image's TCP and UDP `PortPools`
        rN   _TCP_LISTENERNextudp_UDP_ENDPOINTNzCurrent Port: rE      _INET_PORT_POOLr7   r8   )r   BANGsymbol_spaceget_typerelative_child_offsetvollogdebugobjectPortAssignmentsInPaBigPoolBaseAssignmentsr5   EntryrT   )r.   r6   r7   rO   rP   rQ   protoobj_name
ptr_offset
list_indextruncated_port	port_poolinpa
assignmentnetw_insidecurr_objs                   r/   enumerate_structures_by_portz$NetStat.enumerate_structures_by_portz   s     . E>>').8?JH -66x@@VV JJ e^^').8?JH -66x@@VV JJ
 4,d,,---QY
 NNy~-0AA!! # 
 
	 (4 )5nE
 	4 ))**:;; 	~~Zj8P &  H NNN - ">>)..x}==
J *  
  -   	 	 r1   
nt_symbolsc                     t           j                            |||          D ]F}|j                                        dk    r't
                              d|j        d           |c S GdS )a|  Uses `windows.modules` to find tcpip.sys in memory.

        Args:
            context: The context to retrieve required elements (layers, symbol tables) from
            layer_name: The name of the layer on which to operate
            nt_symbols: The name of the table containing the kernel symbols

        Returns:
            The constructed tcpip.sys module object.
        z	tcpip.syszFound tcpip.sys image base @ 0xxN)r   r)   list_modulesBaseDllName
get_stringr^   r_   DllBase)r.   r6   r7   rp   mods        r/   get_tcpip_modulezNetStat.get_tcpip_module   su    " ?//ZPP 	 	C))++{::Ns{NNNOOO


 ; tr1   	ht_offset	ht_length	alignmentNc              #      K   t          |          D ]G}|||z  z   }|                    |t          j        z   dz   ||          }	|	j        j        |	k    rC|	V  HdS )a  Parses a hashtable quick and dirty.

        Args:
            context: The context to retrieve required elements (layers, symbol tables) from
            layer_name: The name of the layer on which to operate
            ht_offset: Beginning of the hash table
            ht_length: Length of the hash table

        Returns:
            The hash table entries which are _not_ empty
        pointerrY   N)rF   r`   r   rZ   volr8   )
r.   r6   r7   ry   rz   r{   rO   indexcurrent_addrcurrent_pointers
             r/   parse_hashtablezNetStat.parse_hashtable   s      , 9%% 
	" 
	"E$uy'88L%nn 9>1I=%# -  O ")_<<!!!!!
	" 
	"r1   tcpip_symbol_tabletcpip_module_offsetc           	   #   :  K   t          j        ||          rd}nd}|t          j        z   dz   }|j                            |t          j        z   dz             j        }|j                            |t          j        z   dz             j        }	|                    |t          j        z   dz   |||z             }
|                    |t          j        z   dz   ||
          }t          	                    |j
        |                             ||	z   d	          d
          }||j        _        t                              d                    |
|                     |j                            |                              d          }t'          |j                  D ]\  }}t                              d|            |j        j        dk    rP|                     |||j        j        |j        j        ||          D ]!}|                    ||||z
            }|V  "dS )a  Parses tcpip.sys's PartitionTable containing established TCP connections.
        The amount of Partition depends on the value of the symbol `PartitionCount` and correlates with
        the maximum processor count (refer to Art of Memory Forensics, chapter 11).

        Args:
            context: The context to retrieve required elements (layers, symbol tables) from
            layer_name: The name of the layer on which to operate
            net_symbol_table: The name of the table containing the tcpip types
            tcpip_symbol_table: The name of the table containing the tcpip driver symbols
            tcpip_module_offset: The offset of the tcpip module

        Returns:
            The list of TCP endpoint objects from the `layer_name` layer's `PartitionTable`
           rE   _TCP_ENDPOINTPartitionTablePartitionCountr}   rY   _PARTITION_TABLEr   r<   zBFound TCP connection PartitionTable @ 0x{:x} (partition count: {})	ListEntryzParsing partition r   N)r   symbol_table_is_64bitr   rZ   r[   
get_symboladdressr`   r=   r>   r?   r@   
Partitionscountr^   r_   formatr\   r]   	enumerate	Endpoints
NumEntriesr   	Directory	TableSize)r.   r6   r7   rO   r   r   r{   rf   part_table_symbolpart_count_symbolpart_table_addr
part_table
part_countentry_offsetctr	partitionendpoint_entryendpoints                     r/   parse_partitionszNetStat.parse_partitions  sg     . (2BCC 	III#in4F#0;;/2BB
 

 	 $0;;/2BB
 

 	 "..y~-	9!&):: ) 
 
 ^^y~-0BB!" $ 
 


 ^^N:&++,?BS,SUVWW
 

 '1
#PWW 	
 	
 	

 +44X>>TT
 
 (
(=>> 	# 	#NCLL3c33444"-11&)&9&9'1'1$' ' # #N  '~~ #--<  .    H
 #NNNN!	# 	#r1   config_pathtcpip_module_sizec                     t                               d           t          j                            |t
          j                            |d          |d||          S )a  DEPRECATED: Use PDBUtility.symbol_table_from_pdb instead

        Creates symbol table for the current image's tcpip.sys driver.

        Searches the memory section of the loaded tcpip.sys module for its PDB GUID
        and loads the associated symbol table into the symbol space.

        Args:
            context: The context to retrieve required elements (layers, symbol tables) from
            config_path: The config path where to find symbol files
            layer_name: The name of the layer on which to operate
            tcpip_module_offset: This memory dump's tcpip.sys image offset
            tcpip_module_size: The size of `tcpip.sys` for this dump

        Returns:
            The name of the constructed and loaded symbol table
        zkDeprecation: This plugin uses netstat.create_tcpip_symbol_table instead of PDBUtility.symbol_table_from_pdbtcpip	tcpip.pdb)r^   r_   r   r*   symbol_table_from_pdbr	   configuration	path_join)r.   r6   r   r7   r   r   s         r/   create_tcpip_symbol_tablez!NetStat.create_tcpip_symbol_tableS  s_    4 	y	
 	
 	
 !77$..{GDD
 
 	
r1   c                    d|j         |         j        v r|j                             |t          j        z   dz             j        }|                    |t          j        z   dz   |||z             }|j                             |t          j        z   dz             j        }|                    |t          j        z   dz   |||z             }	nVd|j         |         j        v r'|j                             |t          j        z   dz             j        }
|j                             |t          j        z   dz             j        }|                    |t          j        z   dz   |||
z             }|                    |t          j        z   dz   |||z             }|                    |t          j        z   dz   ||          }|j        j        j	        }|                    |t          j        z   dz   ||          }|j        j        j	        }	nt          j        d|d| d	          t                              d
|dd|	dd           ||	fS )a  Finds the given image's port pools. Older Windows versions (presumably < Win10 build 14251) use driver
        symbols called `UdpPortPool` and `TcpPortPool` which point towards the pools.
        Newer Windows versions use `UdpCompartmentSet` and `TcpCompartmentSet`, which we first have to translate into
        the port pool address. See also: http://redplait.blogspot.com/2016/06/tcpip-port-pools-in-fresh-windows-10.html

        Args:
            context: The context to retrieve required elements (layers, symbol tables) from
            layer_name: The name of the layer on which to operate
            net_symbol_table: The name of the table containing the tcpip types
            tcpip_module_offset: This memory dump's tcpip.sys image offset
            tcpip_symbol_table: The name of the table containing the tcpip driver symbols

        Returns:
            The tuple containing the address of the UDP and TCP port pool respectively.
        UdpPortPoolr}   rY   TcpPortPoolUdpCompartmentSetTcpCompartmentSet_INET_COMPARTMENT_SETz3Neither UdpPortPool nor UdpCompartmentSet found in z tablezFound PortPools @ 0xrr   z (UDP) && 0xz (TCP))r[   r   r   r   rZ   r   r`   InetCompartmentProtocolCompartmentPortPoolr   SymbolErrorr^   r_   )r.   r6   r7   rO   r   r   
upp_symbolupp_addr
tpp_symboltpp_addrucstcs
ucs_offset
tcs_offsetucs_objtcs_objs                   r/   find_port_poolszNetStat.find_port_poolsy  s   2 G01CDLLL -88"Y^3mC   ~~ 9>1I=%*Z7 &  H !-88"Y^3mC   ~~ 9>1I=%*Z7 &  HH !G$89K$L$TTT&11"Y^36II   &11"Y^36II   ! 9>1I=%*S0 (  J
 ! 9>1I=%*S0 (  J nn 9>14KK%! %  G
 .BKHnn 9>14KK%! %  G
 .BKHH ("`FX```   	VHVVVHVVVVWWW!!r1   c           	   #     K   |                      |||||          D ]}|V  |                     |||||          \  }}	|                    |t          j        z   dz   ||          }
|                     |||
j        j        |
j        j        dz            }|                    |t          j        z   dz   ||	          }|                     |||j        j        |j        j        dz            }t          
                    d|            t          
                    d|            |D ]&}|s|                     |||||	d          D ]}|V  '|D ]&}|s|                     |||||d          D ]}|V  'dS )	a&  Lists all UDP Endpoints, TCP Listeners and TCP Endpoints in the primary layer that
        are in tcpip.sys's UdpPortPool, TcpPortPool and TCP Endpoint partition table, respectively.

        Args:
            context: The context to retrieve required elements (layers, symbol tables) from
            layer_name: The name of the layer on which to operate
            nt_symbols: The name of the table containing the kernel symbols
            net_symbol_table: The name of the table containing the tcpip types
            tcpip_module_offset: Offset of `tcpip.sys`'s PE image in memory
            tcpip_symbol_table: The name of the table containing the tcpip driver symbols

        Returns:
            The list of network objects from the `layer_name` layer's `PartitionTable` and `PortPools`
        rX   rY   rE   zFound TCP Ports: zFound UDP Ports: rN   rU   N)r   r   r`   r   rZ   rM   
PortBitMapBufferSizeOfBitMapr^   r_   ro   )r.   r6   r7   rp   rO   r   r   r   r   r   upp_obj
udpa_portstpp_obj
tcpl_portsrP   objs                   r/   list_socketszNetStat.list_sockets  s,     4 ,,
 
 	 	H NNNN !00
 
( ..y~-0AA! ! 
 

 %%%+q0	
 

 ..y~-0AA! ! 
 

 %%%+q0	
 

 	555666555666 	 	D 77%5tXu    				
  	 	D 77%5tXu    						 	r1   show_corrupt_resultsc              #   8  K   | j         j        | j        d                  }t          j                            | j         |j        |j        | j                  }| 	                    | j         |j        |j                  }|st                              d           	 t          j                            | j         t          j                            | j        d          |j        d|j        |j                  }n/# t(          j        $ r t                              d           Y nw xY w|                     | j         |j        |j        ||j        |          D ]F}|s|                                st1          |t2          j                  rt                              d|j        j        d           |                                D ]\  }}}	dt?          j         |j        j                  d|z   ||j!        d	dd
|"                                ptG          j$                    |%                                ptG          j$                    |&                                ptG          j$                    f
fV  t1          |t2          j'                  rt                              d|j        j        d           |(                                t2          j)        k    rd}
nq|(                                t2          j*        k    rd}
nLt                              d+                    |j        j        |(                                                     d}
	 |j,        j-        }n## t\          $ r tG          j$                    }Y nw xY wdt?          j         |j        j                  |
|/                                ptG          j$                    |j0        |1                                ptG          j$                    |j2        ||"                                ptG          j$                    |%                                ptG          j$                    |&                                ptG          j$                    f
fV  t1          |t2          j3                  rt                              d|j        j        d           |                                D ]\  }}}dt?          j         |j        j                  d|z   ||j!        |dd|"                                ptG          j$                    |%                                ptG          j$                    |&                                ptG          j$                    f
fV  t                              d| dti          |                      HdS )z3Generates the network objects for use in rendering.r   z<Unable to locate symbols for the memory image's tcpip moduler   r   zFound UDP_ENDPOINT @ 0x2xr   UDP* zFound _TCP_ENDPOINT @ 0xTCPv4TCPv6z8TCP Endpoint @ 0x{:2x} has unknown address family 0x{:x}zTCPv?zFound _TCP_LISTENER @ 0xTCP	LISTENINGz)Found network object unsure of its type: z	 of type N)5r6   r   configr   r(   create_netscan_symbol_tabler7   symbol_table_namer   rx   r^   errorr   r*   r   r	   r   r   rv   SizeOfImager   VolatilityExceptionr   is_valid
isinstancer   rV   r_   r~   r8   dual_stack_socketsr   HexPortget_owner_pidr
   UnreadableValueget_owner_procnameget_create_timer   get_address_familyAF_INETAF_INET6r   Stater   
ValueErrorget_local_address	LocalPortget_remote_address
RemotePortrS   type)selfr   r   netscan_symbol_tabletcpip_moduler   netw_objverladdr_re   stateraddrs                r/   
_generatorzNetStat._generator.  s      %dk(&;<&JJL&+V-EtGW 
  
 ,,L&+V-E
 
  	YLLWXXX
	Y!(!3!I!I(2243CWMM!$(" " - 	Y 	Y 	YLLWXXXXX	Y ))L$  
 
 _	 _	H ( 0A0A0C0C (G$9:: SOx|7JOOOPPP &.%@%@%B%B  MC(,X\-@AA!CK!$M$2244S	8Q8S8S$7799 ;(8::$4466U):S:U:U    $ Hg&;<< =P8KPPPQQQ..00GOCC#EE0022g6FFF#EELLRYY$L/1L1L1N1N   
 $E8$N6EE! 8 8 8%577EEE8 $()<== 2244S	8Q8S8S * 3355T9R9T9T + ..00OI4M4O4O 3355T9R9T9T 0022Qi6O6Q6Q    " Hg&;<< P8KPPPQQQ *2)D)D)F)F  %C(,X\-@AA!CK!$M!'$2244S	8Q8S8S$7799 ;(8::$4466U):S:U:U    & cccSWX`SaSacc   {_	 _	s%   AC5 5)D! D!MM54M5c              #     K   |                                  D ]}|\  }}i }|\
  |d<   |d<   |d<   |d<   |d<   |d<   |d<   |d<   |d	<   |d
<   t          |d
         t          j                  sUd                    |d         |d	         |d         |d         |d         |d         |d         |d                   }|t          j        j        |d
         fV  d S )NOffsetProto	LocalAddrr   ForeignAddrForeignPortr   PIDOwnerCreatedz`Network connection: Process {} {} Local Address {}:{} Remote Address {}:{} State {} Protocol {} )r   r   datetimer   r   TimeLinerTypeCREATED)r   row_depthrow_datarow_dictr   s         r/   generate_timelinezNetStat.generate_timeline  s0     ??$$ !	V !	VC"FHH "!%%''!!# hy183DEE ==CVUOW%[)[)]+]+W%W%	> 	>  	 7 ?)ATUUUUUC!	V !	Vr1   c                 >   | j                             dd           }t          j        dt          j        fdt          fdt          fdt          fdt          fdt          fdt          fd	t          fd
t          fdt          j        fg
| 	                    |                    S )Nr#   r   r   r   r   r   r   r   r   r   r   )r   )
r   getr
   TreeGridr   r   strr=   r   r   )r   r   s     r/   runzNetStat.run  s    #{/@$GG!<+,#c"c"$$##H-. OO1EOFF
 
 	
r1   )rN   )N)"__name__
__module____qualname____doc___required_framework_version_versionclassmethodr0   r5   r	   r6   ContextInterfacer  r=   rA   listrM   r   objectsObjectInterfacero   r   rx   r   r   r   r   r   r   r   boolr   r  r  r3   r1   r/   r   r      s{       ]]"+H
 
 [
<   [ Y#4Y Y 	Y
 Y 
Y Y Y [Y* #4  	
 ! 
   [6  L L#4L L 	L
 L L 
*$4	5L L L [L\ #4  	
 
*$4	5   [, "#4" " 	"
 " " " 
:%5tTA	B" " " ["B N##4N# N# 	N#
  N# !N# 
*$4	5N# N# N# [N#` #
#4#
 #
 	#

 !#
 #
 
#
 #
 #
 [#
J W"#4W" W" 	W"
  W" !W" 
sCxW" W" W" [W"r X#4X X 	X
 X !X  X 
*$4	5X X X [Xtz zx~ z z z zx"V "V "VH
 
 
 
 
r1   r   )#r   loggingtypingr   r   r   r   volatility3.frameworkr   r   r	   r
   r   #volatility3.framework.configurationr   volatility3.framework.renderersr   %volatility3.framework.symbols.windowsr   0volatility3.framework.symbols.windows.extensionsr   volatility3.pluginsr   volatility3.plugins.windowsr   r   r   r   	getLoggerr  r^   pluginsPluginInterfaceTimeLinerInterfacer   r3   r1   r/   <module>r&     s@  
   7 7 7 7 7 7 7 7 7 7 7 7 W W W W W W W W W W W W W W < < < < < < 8 8 8 8 8 8 9 9 9 9 9 9 D D D D D D ) ) ) ) ) ) G G G G G G G G G G G G		8	$	$K
 K
 K
 K
 K
j 0)2N K
 K
 K
 K
 K
r1   