
    *1f]                        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
 d dl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  e j        e          Z G d
 dej        j                  Z G d dej                  Z dS )    N)CallableTupleListDict)
interfaces
exceptions	constantsobjects)TreeGridNotAvailableValueformat_hints)requirements)plugins)utility)linux)lsofc            	          e Zd ZdZdZdZd ZdedefdZ	de
j        dee
j        eeeef         ef         fd	Zde
j        d
eddfdZde
j        d
eddfdZde
j        dee
j        eeeef         f         fdZde
j        dee
j        eeeef         f         fdZde
j        dee
j        eeeef         f         fdZde
j        dee
j        eeeef         f         fdZde
j        dee
j        eeeef         f         fdZde
j        dee
j        eeeef         f         fdZde
j        dee
j        eeeef         f         fdZdS )SockHandlerszCHandles several socket families extracting the sockets information.   r   r      r   r   c           	      B   || _         || _        	 |j        j                                        }n# t
          $ r t                      }Y nw xY w|                     |          | _        | j	        | j
        | j
        | j        | j        | j        | j        | j        d| _        d S )N)AF_UNIXAF_INETAF_INET6
AF_NETLINKAF_VSOCK	AF_PACKETAF_XDPAF_BLUETOOTH)_vmlinux_tasknsproxynet_ns	get_inodeAttributeErrorr   _build_network_devices_map_netdevices
_unix_sock
_inet_sock_netlink_sock_vsock_sock_packet_sock	_xdp_sock_bluetooth_sock_sock_family_handlers)selfvmlinuxtasknetns_ids       ^/home/panchajanya/Development/work/volatility3/volatility3/framework/plugins/linux/sockstat.py__init__zSockHandlers.__init__   s    
	+|*4466HH 	+ 	+ 	+(**HHH	+  ::8DD ,(*n 0	&
 	&
"""s   / A
	A
r5   returnc                    i }| j                             d          }| j         j        t          j        z   dz   }|                    |d          D ]}| j         j        t          j        z   dz   }|j                            |d          D ]S}t          |t                    s|	                                |k    r0t          j        |j                  }|||j        <   T|S )aW  Given a namespace ID it returns a dictionary mapping each network
        interface index (ifindex) to its network interface name:

        Args:
            netns_id: The network namespace ID

        Returns:
            netdevices_map: Mapping network interface index (ifindex) to network
                            interface name
        net_namespace_list)symbol_namenetlist
net_devicedev_list)r"   object_from_symbolsymbol_table_namer	   BANGto_listdev_base_head
isinstancer   r&   r   array_to_stringnameifindex)	r2   r5   netdevices_mapnetheadnet_symnamer<   net_device_symnamenet_devdev_names	            r6   r(   z'SockHandlers._build_network_devices_map1   s     -22?S2TTm5	FN??;77 	; 	;C/).@<O  ,445GTT ; ;x):;;}}(22"27<@@2:w//;     sockc                    |                                 }i }| j                            |          }|rm	  ||          \  }}|                     ||           |||fS # t          j        $ r1}t                              t          j	        d||           Y d}~n.d}~ww xY wt                              t          j	        d|           dx}x}	x}
}|
                                }||	|
||f}|||fS )a  Takes a kernel generic `sock` object and processes it with its respective socket family

        Args:
            sock: Kernel generic `sock` object

        Returns a tuple with:
            sock: The respective kernel's \*_sock object for that socket family
            sock_stat: A tuple with the source and destination (address and port) along with its state string
            socket_filter: A dictionary with information about the socket filter
        z'Error processing socket family '%s': %sNzUnsupported family '%s')
get_familyr1   get_update_socket_filters_infor   SymbolErrorvolloglogr	   
LOGLEVEL_V	get_state)r2   rP   familysocket_filtersock_handler	unix_sock	sock_statesrc_addrsrc_portdst_addrdst_portstates                r6   process_sockzSockHandlers.process_sockM   s1    ""155f== 	P'3|D'9'9$	900}EEE )]::)   

(=	        JJy+-FOOO
 598888h  h(EA	Y--s   (A B,'BBr[   Nc                    |                     d          r)|j        r"|j        }d|d<   |                     ||           |                     d          r+|j        r&|j        }d|d<   |                     ||           dS dS dS )zGet information from the socket and reuseport filters

        Args:
            sock: The kernel sock (sk) struct
            socket_filter: A dictionary with information about the socket filter
        	sk_filterr[   filter_typesk_reuseport_cbreuseport_filterN)
has_memberrg   _extract_socket_filter_infori   )r2   rP   r[   sock_filtersock_reuseport_cbs        r6   rT   z(SockHandlers._update_socket_filters_infox   s     ??;'' 	IDN 	I.K+:M-(,,[-HHH??,-- 	O$2F 	O $ 4+=M-(,,->NNNNN	O 	O 	O 	OrO   rm   c                 <   d|d<   |                     d          r|j        sdS |j        }d}	 |                                }||k    rdS n# t          $ r Y dS w xY wd}||k    r)d| d|d<   t                              d	| d
           dS d|d<   |                     d          r|j        sdS |j        }|                     d          rt          |j                  |d<   |                     d          r"t          j
        |j                  }|r	||d<   dS dS dS )zGet specific information for each type of filter

        Args:
            socket_filter: A dictionary with information about the socket filter
        cBPFbpf_filter_typeprogNr   r   zUNK()zUnexpected BPF type z for a socketeBPFauxidbpf_filter_idrG   bpf_filter_name)rk   rr   get_typer'   rV   warningru   strrv   r   rF   rG   )	r2   rm   r[   bpfprogBPF_PROG_TYPE_UNSPECbpfprog_typeBPF_PROG_TYPE_SOCKET_FILTERbpfprog_auxbpfprog_names	            r6   rl   z(SockHandlers._extract_socket_filter_info   s    ,2'(%%f-- 	[5E 	4" 	"++--L333 4 	 	 	44	 '(#666/El/E/E/EM+,NNM,MMMNNN4+1'(!!%(( 	 	Fk!!$'' 	A-0-@-@M/*!!&)) 	@"2;3CDDL @3?/000		@ 	@@ @s   A 
AAc                 z   |                     d          }|                                }|                                }|                                }|j        rU|j                                                             d          }|                                }|                                }ndx}}|||||f}	||	fS )a  Handles the AF_UNIX socket family

        Args:
            sock: Kernel generic `sock` object

        Returns:
            unix_sock: The kernel's `unix_sock` object
            sock_stat: A tuple with the source and destination (address and port) along with its state string
        r]   N)castrY   get_namer&   peerdereference)
r2   rP   r]   rd   r`   ra   r   rb   rc   r^   s
             r6   r*   zSockHandlers._unix_sock   s     IIk**	##%%%%''&&((> 	'>--//44[AAD}}H~~''HH"&&Hxh(EA	)##rO   c                 
   |                     d          }|                                }|                                }|                                }|                                }|                                }|||||f}||fS )a#  Handles the AF_INET/6 socket families

        Args:
            sock: Kernel generic `sock` object

        Returns:
            inet_sock: The kernel's `inet_sock` object
            sock_stat: A tuple with the source and destination (address and port) along with its state string
        	inet_sock)r   get_src_addrget_src_portget_dst_addrget_dst_portrY   )	r2   rP   r   r`   ra   rb   rc   rd   r^   s	            r6   r+   zSockHandlers._inet_sock   s     IIk**	))++))++))++))++##%%h(EA	)##rO   c                     |                     d          }d}|j        r|j                                        }d|d}	 |                                }n# t          $ r t                      }Y nw xY wd|j        d}|j        }|r'|j        r t          j
        |j                  }| d| }	 |                                }	n# t          $ r t                      }	Y nw xY w|                                }
||||	|
f}||fS )a(  Handles the AF_NETLINK socket family

        Args:
            sock: Kernel generic `sock` object

        Returns:
            netlink_sock: The kernel's `netlink_sock` object
            sock_stat: A tuple with the source and destination (address and port) along with its state string
        netlink_sockNz	groups:0x08xzgroup:0xz,lkm:)r   groupsr   
get_portidr'   r   	dst_groupmodulerG   r   rF   get_dst_portidrY   )r2   rP   r   r`   groups_bitmapra   rb   r   module_name_strrc   rd   r^   s               r6   r,   zSockHandlers._netlink_sock   sN    yy00 	7(/;;==M6=666H	+#..00HH 	+ 	+ 	+(**HHH	+ ;l4:::$ 	;fk 	;%5fkBBO"::::H	+#2244HH 	+ 	+ 	+(**HHH	+ &&((h(EA	Y&&s#   A A/.A/.C CCc                     |                     d          }|j        j        }|j        j        }|j        j        }|j        j        }|                                }|||||f}||fS )a   Handles the AF_VSOCK socket family

        Args:
            sock: Kernel generic `sock` object

        Returns:
            vsock_sock: The kernel `vsock_sock` object
            sock_stat: A tuple with the source and destination (address and port) along with its state string
        
vsock_sock)r   
local_addrsvm_cidsvm_portremote_addrrY   )	r2   rP   r   r`   ra   rb   rc   rd   r^   s	            r6   r-   zSockHandlers._vsock_sock  sm     YY|,,
(0(1)1)2$$&&h(EA	9$$rO   c                     |                     d          }|j        }|dk    r| j                            |          nd}|}dx}x}}|                                }	|||||	f}
||
fS )a%  Handles the AF_PACKET socket family

        Args:
            sock: Kernel generic `sock` object

        Returns:
            packet_sock: The kernel's `packet_sock` object
            sock_stat: A tuple with the source and destination (address and port) along with its state string
        packet_sockr   ANYN)r   rH   r)   rS   rY   )r2   rP   r   rH   rN   r`   ra   rb   rc   rd   r^   s              r6   r.   zSockHandlers._packet_sock&  s     ii..%4;aKK4#''000U)---8h%%''h(EA	I%%rO   c                    |                     d          }|j        }|sdS t          j        |j                  }dx}x}}|j        }|sdS |                    d          r|j        sdS |j        }	|	                    d          r|	j        }
d|
 }|	                    d          r t          j        |	j                  }|rd| }|	                                }|
                    dd	          }|||||f}||fS )
a  Handles the AF_XDP socket family

        Args:
            sock: Kernel generic `sock` object

        Returns:
            xdp_sock: The kernel's `xdp_sock` object
            sock_stat: A tuple with the source and destination (address and port) along with its state string
        xdp_sockNru   rv   zebpf_prog_id:rG   zebpf_prog_name:XSK_ )r   devr   rF   rG   xdp_progrk   ru   rv   rY   replace)r2   rP   r   devicer`   ra   rb   rc   r|   r   
bpfprog_idbpf_name	xsk_staterd   r^   s                  r6   r/   zSockHandlers._xdp_sock=  s2    99Z(( 	4*6;77)---8h/ 	4!!%(( 	 	4k!!$'' 	4$J3z33H!!&)) 	8.{/?@@H 87X77&&((	!!&"--h(EA	""rO   c                    |                     d          }d }dx}x}x}}|                                }|dk    r| j                            d          r~|                     d          }	|	                    d          rR| j                            d          r8|	j                            d          rt          j        |	j        j                  }nt          
                    t          j        d	           n|d
k    r| j                            d          rY|                     d          }	 ||	j        j                  } ||	j        j                  }|	j        j        }|	j        j        }nLt          
                    t          j        d           n%|dk    r}| j                            d          r=|                     d          }	 ||	j                  } ||	j                  }|	j        }nt          
                    t          j        d           n|dk    rv| j                            d          r6|                     d          }	 ||	j                  } ||	j                  }nLt          
                    t          j        d           n&t          
                    t          j        d|           |                                }
|||||
f}||fS )a   Handles the AF_BLUETOOTH socket family

        Args:
            sock: Kernel generic `sock` object

        Returns:
            bt_sock: The kernel's `bt_sock` object
            sock_stat: A tuple with the source and destination (address and port) along with its state string
        bt_sockc                 d    d                     t          d | j        D                                 S )N:c                     g | ]}d |z  S )z%02x ).0xs     r6   
<listcomp>zASockHandlers._bluetooth_sock.<locals>.bt_addr.<locals>.<listcomp>x  s    %A%A%AQfqj%A%A%ArO   )joinreversedb)addrs    r6   bt_addrz-SockHandlers._bluetooth_sock.<locals>.bt_addrw  s-    88H%A%A$&%A%A%ABBCCCrO   NHCI	hci_pinfohdevhci_devrN   z?Type definition for 'hci_pinfo' is not available in the symbolsL2CAPl2cap_pinfozAType definition for 'l2cap_pinfo' is not available in the symbolsRFCOMMrfcomm_pinfozBType definition for 'rfcomm_pinfo' is not available in the symbolsSCO	sco_pinfoz?Type definition for 'sco_pinfo' is not available in the symbolsz#Unsupported bluetooth protocol '%s')r   get_protocolr"   has_typerk   r   r   rF   rN   rV   rW   r	   rX   chansrcdstsportpsmchannelrY   )r2   rP   r   r   r`   ra   rb   rc   bt_protocolpinford   r^   s               r6   r0   zSockHandlers._bluetooth_socki  s    ))I&&	D 	D 	D 598888h**,,%}%%k22 [11$$V,,L..y99L 
--j99L
  '6uz7JKKH

(U    G##}%%m44 
]33"75:>22"75:>22 :+ :>

(W    H$$}%%n55 	^44"759--"759-- =

(X    E!!}%%k22 [11"759--"759--

(U   
 JJ$&K[   !!##h(EA		!!rO   )__name__
__module____qualname____doc___required_framework_version_versionr7   intr   r(   r
   
StructTyper   r{   re   PointerdictrT   rl   r*   r+   r,   r-   r.   r/   r0   r   rO   r6   r   r      s       MM"+H
 
 
,3 4    8).&).	w!5c3#7=	>). ). ). ).VOOO48O	O O O O&*@"?*@;?*@	*@ *@ *@ *@X$&$	w!5c3#77	8$ $ $ $6$&$	w!5c3#77	8$ $ $ $,&'&&'	w!5c3#77	8&' &' &' &'P%&%	w!5c3#77	8% % % %,&&&	w!5c3#77	8& & & &.*#&*#	w!5c3#77	8*# *# *# *#XJ"&J"	w!5c3#77	8J" J" J" J" J" J"rO   r   c            
           e Zd ZdZdZdZed             Zed fdej	        j
        dedeegef         fd	            Zd
 Zdee         dedefdZd ZdS )Sockstatz0Lists all network connections for all processes.r   r   c                 ~   t          j        ddg d          t          j        dt          d          t          j        dt
          j        d	
          t          j        dt          j        d          t          j	        dddd          t          j
        ddt          d          t          j        ddd          gS )NkernelzLinux kernel)Intel32Intel64AArch64)rG   descriptionarchitecturesr   r   )rG   	componentversionr   )r   r   r   )rG   pluginr   
linuxutilsr   unixzShow UNIX domain Sockets onlyFT)rG   r   defaultoptionalpidszKFilter results by process IDs. It takes the root PID namespace identifiers.)rG   r   element_typer   netnszFFilter results by network namespace. Otherwise, all of them are shown.)rG   r   r   )r   ModuleRequirementVersionRequirementr   PluginRequirementr   Lsofr   LinuxUtilitiesBooleanRequirementListRequirementr   IntRequirement)clss    r6   get_requirementszSockstat.get_requirements  s     **???  
 +#|Y   *DIy   +!U-A9   +<	   (?    '4	  9"
 "	
rO   c                     dS )NFr   )_s    r6   <lambda>zSockstat.<lambda>  s    u rO   contextsymbol_tablefilter_funcc              #   p  K   |j         |         }|                    d          j        j        }|                    d          j        j        }t          j                            ||j        |          }|D ]>\  }}	}
}|\  }}}|j        ||fvr|	                                }|s1|j
        }|s;t          j                            |dd|          }|j        }|r|j        sn|j                                        }|                                }|                                }t'          ||
          }|                    |          }|s|d         }|                                }|
j        j        }	 |                                }n# t2          $ r t5                      }Y nw xY w|
||||||fV  @dS )a
  Returns every single socket descriptor

        Args:
            context: The context to retrieve required elements (layers, symbol tables) from
            symbol_table: The name of the kernel module on which to operate
            filter_func: A function which takes a task object and returns True if the task should be ignored/filtered

        Yields:
            task: Kernel's task object
            netns_id: Network namespace ID
            fd_num: File descriptor number
            family: Socket family string (AF_UNIX, AF_INET, etc)
            sock_type: Socket type string (STREAM, DGRAM, etc)
            protocol: Protocol string (UDP, TCP, etc)
            sock_fields: A tuple with the \*_sock object, the sock stats and the extended info dictionary
        socket_file_opssockfs_dentry_operationssocket_alloc	vfs_inoder   N)modulesr@   voloffsetr   r   list_fdsrG   f_op
get_dentryd_inoder   r   container_ofsocketskr   ry   rR   r   re   r   r$   r%   r&   r'   r   )r   r   r   r   r3   	sfop_addr	dfop_addrfd_generator_pid
_task_commr4   	fd_fieldsfd_numfilp
_full_pathdentryr  r   r  rP   	sock_typerZ   r\   sock_fields
child_sockprotocolr<   r5   s                               r6   list_socketszSockstat.list_sockets  s     . /,/../@AAEL	../IJJNU	y))'7<MM1= )	S )	S-D*dI'0$FD*yI 666__&&F nG  /<<g L "(F vy 9((**DI__&&F'66L&33D99K $QJ!..00H,%C/==??! / / /,../ &&)X{RRRRRS)	S )	Ss   6FF&%F&c                 \    d |D             }|t                      }t          |          |fS )a(  Prepare the socket fields to be rendered

        Args:
            sock_stat: A tuple with the source and destination (address and port) along with its state string
            protocol: Protocol string (UDP, TCP, etc)

        Returns:
            `sock_stat` and `protocol` formatted.
        c                 L    g | ]!}|t                      nt          |          "S )N)r   r{   )r   fields     r6   r   z+Sockstat._format_fields.<locals>.<listcomp>5  s;     
 
 
EJ5=c%jj
 
 
rO   )r   tuple)r2   r^   r  s      r6   _format_fieldszSockstat._format_fields+  sF    
 
NW
 
 
	 (**HY))rO   r   netns_id_argc              #     K   t           j        j                            |          }|                     | j        ||          }|D ]\  }}}}	}
}}|r||k    r|\  }}}|                     ||          \  }}|r1d                    d |                                D                       nt                      }||j
        |t          j        |j        j                  |	|
|g||R }d|fV  dS )a  Enumerate tasks sockets. Each row represents a kernel socket.

        Args:
            pids: List of PIDs to filter. If a empty list or
            netns_id_arg: If a network namespace ID is set, it will only show this namespace.
            symbol_table: The name of the kernel module on which to operate

        Yields:
            netns_id: Network namespace ID
            family: Socket family string (AF_UNIX, AF_INET, etc)
            sock_type: Socket type string (STREAM, DGRAM, etc)
            protocol: Protocol string (UDP, TCP, etc)
            source addr: Source address string
            source port: Source port string (not all of them are int)
            destination addr: Destination address string
            destination port: Destination port (not all of them are int)
            state: State strings (LISTEN, CONNECTED, etc)
            tasks: String with a list of tasks and FDs using a socket. It can also have
                   extended information such as socket filters, bpf info, etc.
        )r   ,c              3   *   K   | ]\  }}| d | V  dS )=Nr   )r   kvs      r6   	<genexpr>z&Sockstat._generator.<locals>.<genexpr>g  s0      AA1AAAAAAArO   r   N)r   pslistPsListcreate_pid_filterr  r   r  r   itemsr   pidr   Hexr   r  )r2   r   r  r   r   socket_generatorr4   r5   r  rZ   r  r  r  rP   r^   extendedsocket_filter_strfieldss                     r6   
_generatorzSockstat._generator=  sR     * k(::4@@,,L,K - 
 
 !	 !	 
  8 8(3%D)X"&"5"5i"J"JIx )AA0@0@AAAAAA&((   11
 
 "
 
F f+C!	 !	rO   c                    | j                             d          }| j         d         }| j         d         }dt          fdt          fdt          f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
          fg}t          ||                     |||                    S )Nr   r   r   NetNSPidFDzSock OffsetFamilyTypeProtozSource AddrzSource PortzDestination AddrzDestination PortStateFilter)configrS   r   r   r*  r{   r   r/  )r2   r   r5   r   tree_grid_argss        r6   runzSockstat.runz  s    {v&&;w'{8, cNCL3KL,-sOSMcNC C %%cNsO
  h(U(UVVVrO   N)r   r   r   r   r   r   classmethodr   r   r   ContextInterfacer{   r   r   boolr  r  r   r/  r;  r   rO   r6   r   r     s        ::"+H#
 #
 [#
J 
 .=_	ES ES#4ES ES seTk*	ES ES ES [ESN* * *$;tCy ; ;3 ; ; ; ;zW W W W WrO   r   )!loggingtypingr   r   r   r   volatility3.frameworkr   r   r	   r
   volatility3.framework.renderersr   r   r   #volatility3.framework.configurationr    volatility3.framework.interfacesr   volatility3.framework.objectsr   volatility3.framework.symbolsr   volatility3.plugins.linuxr   	getLoggerr   rV   configurationVersionableInterfacer   PluginInterfacer   r   rO   r6   <module>rL     sh  
  . . . . . . . . . . . . L L L L L L L L L L L L U U U U U U U U U U < < < < < < 4 4 4 4 4 4 1 1 1 1 1 1 / / / / / / * * * * * * 
	8	$	$_" _" _" _" _":+@ _" _" _"DYW YW YW YW YWw& YW YW YW YW YWrO   