
    [
#g ]                        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 j2                  e      Z G d
 dej8                  j:                        Z G d dej>                        Z y)    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y)SockHandlerszCHandles several socket families extracting the sockets information.   r   r      r   r   c           	         || _         || _        	 |j                  j                  j	                         }| j                  |      | _        | j                  | j                  | j                  | j                  | j                  | j                  | j                  | j                  d| _        y # t
        $ r t               }Y w xY w)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6H  ::8D ,,((**nn 00	&
"  	+(*H	+s   $B+ +C Cr5   returnc                    i }| j                   j                  d      }| j                   j                  t        j                  z   dz   }|j                  |d      D ]  }| j                   j                  t        j                  z   dz   }|j                  j                  |d      D ]T  }t        |t              s|j                         |k7  r't        j                  |j                        }|||j                  <   V  |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mm55	FN??;7C//)..@<O  ,,445GTx):;}}(2"227<<@2:w/ U	 8     sockc                    |j                         }i }| j                  j                  |      }|r#	  ||      \  }}| j                  ||       |||fS t        j                  t        j                  d|       dx}x}	x}
}|j                         }||	|
||f}|||fS # t        j
                  $ r0}t        j                  t        j                  d||       Y d}~bd}~ww xY w)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   s     "1155f='3D'9$	900}E )]:: JJy++-FO
 598888h h(EA	Y--' )) 

((=	 s   !B C/&CCr[   Nc                    |j                  d      r/|j                  r#|j                  }d|d<   | j                  ||       |j                  d      r1|j                  r$|j                  }d|d<   | j                  ||       yyy)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~     ??;'DNN..K+:M-(,,[-H??,-$2F2F $ 4 4+=M-(,,->N 3G-rO   rm   c                    d|d<   |j                  d      r|j                  sy|j                  }|j                         }|sy|dk(  ry|dk7  r#d| d|d<   t        j	                  d	| d
       yd|d<   |j                  d      r|j
                  sy|j
                  }|j                  d      rt        |j                        |d<   |j                  d      r(t        j                  |j                        }|r||d<   yyy)zGet specific information for each type of filter

        Args:
            socket_filter: A dictionary with information about the socket filter
        cBPFbpf_filter_typeprogNBPF_PROG_TYPE_UNSPECBPF_PROG_TYPE_SOCKET_FILTERzUNK()zUnexpected BPF type z for a socketeBPFauxidbpf_filter_idrG   bpf_filter_name)rk   rr   get_typerV   warningrw   strrx   r   rF   rG   )r2   rm   r[   bpfprogbpfprog_typebpfprog_auxbpfprog_names          r6   rl   z(SockHandlers._extract_socket_filter_info   s    ,2'(%%f-[5E5E""'')118815l^1/EM+,NN1,}MN+1'(!!%(kk!!$'-0-@M/*!!&)"22;3C3CDL3?/0  *rO   c                 N   |j                  d      }|j                         }|j                         }|j                         }|j                  rJ|j                  j                         j                  d      }|j                         }|j                         }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[AD}}H~~'H"&&Hxh(EA	)##rO   c                     |j                  d      }|j                         }|j                         }|j                         }|j	                         }|j                         }|||||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   ss     IIk*	))+))+))+))+##%h(EA	)##rO   c                    |j                  d      }d}|j                  r |j                  j                         }d|d}	 |j                         }d|j                  d}|j                  }|r2|j                  r&t        j                  |j                        }| d| }	 |j                         }	|j                         }
||||	|
f}||fS # t        $ r t               }Y w xY w# t        $ r t               }	Y Iw xY w)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   s    yy0(//;;=M"="56H	+#..0H l44S9:$$fkk%55fkkBO"5(9:H	+#224H &&(h(EA	Y&&!  	+(*H	+  	+(*H	+s$   C "C& C#"C#&C<;C<c                 
   |j                  d      }|j                  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  s     YY|,
((00((11))11))22$$&h(EA	9$$rO   c                     |j                  d      }|j                  }|dkD  r| j                  j                  |      nd}|}dx}x}}|j	                         }	|||||	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$  sx     ii.%%4;aK4##''0U)---8h%%'h(EA	I%%rO   c                 
   |j                  d      }|j                  }|syt        j                  |j                        }dx}x}}|j
                  }|sy|j                  d      r|j                  sy|j                  }	|	j                  d      r|	j                  }
d|
 }|	j                  d      r&t        j                  |	j                        }|rd| }|j                         }|j                  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_sockNrw   rx   zebpf_prog_id:rG   zebpf_prog_name:XSK_ )r   devr   rF   rG   xdp_progrk   rw   rx   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;  s    99Z(**6;;7)---8h//!!%(kk!!$'$J&zl3H!!&)..{/?/?@H,XJ7&&(	!!&"-h(EA	""rO   c                    |j                  d      }d }dx}x}x}}|j                         }|dk(  r| j                  j                  d      r|j                  d      }	|	j	                  d      rm| j                  j                  d      rQ|	j
                  j	                  d      r5t        j                  |	j
                  j                        }n
t        j                  t        j                  d	       n|d
k(  r| j                  j                  d      rw|j                  d      }	 ||	j                  j                        } ||	j                  j                        }|	j                  j                   }|	j                  j"                  }nMt        j                  t        j                  d       n'|dk(  r| j                  j                  d      rB|j                  d      }	 ||	j                        } ||	j                        }|	j$                  }nt        j                  t        j                  d       n|dk(  rv| j                  j                  d      r6|j                  d      }	 ||	j                        } ||	j                        }nJt        j                  t        j                  d       n%t        j                  t        j                  d|       |j'                         }
|||||
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           	      v    dj                  t        | j                  D cg c]  }d|z  	 c}            S c c}w )N:z%02x)joinreversedb)addrxs     r6   bt_addrz-SockHandlers._bluetooth_sock.<locals>.bt_addru  s,    88H$&&%AQfqj%ABCC%As   6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_sockg  sV    ))I&	D 598888h**,%}}%%k2[1$$V,..y9

--j9&66uzz7J7JKH

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

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

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

((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    rO   r6   r   r      s+   M"+H
,3 4 8).&&).	w!!5c3#7=	>).VOOOO48O	O&(@"??(@;?(@	(@T$&&$	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"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y)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 **DIIy ++!U-A-A9 ++<	 ((?  ''4	9"
 "	
rO   c                      y)NFr   )_s    r6   <lambda>zSockstat.<lambda>  s    urO   contextsymbol_tablefilter_funcc              #     K   |j                   |   }|j                  d      j                  j                  }|j                  d      j                  j                  }t        j
                  j                  ||j                  |      }|D ]  \  }}	}
}|\  }}}|j                  ||fvr |j                         }|s3|j                  }|sBt        j                  j                  |dd|      }|j                  }|r|j                  s|j                  j!                         }|j#                         }|j%                         }t'        ||
      }|j)                  |      }|s|d   }|j+                         }|
j,                  j.                  }	 |j1                         }|
||||||f " y# t2        $ r t5               }Y $w xY ww)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   r{   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EELL	../IJNNUU	yy))'7<<M1=-D*dI'0$FD*yyI 66__&FnnG //<<gL "((Fvyy99((*DI__&F'6L&33D9K$QJ!..0H,,%%C/==? &&)X{RRS 2>L " /,./s*   FGF-G-G GGGc                     |D cg c]  }|
t               n
t        |       }}|
t               }t        |      |fS c c}w )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.
        )r   r}   tuple)r2   r^   r  fields       r6   _format_fieldszSockstat._format_fields)  sV     OX
EJ5=c%j@
	 
 (*HY))
s   >r   netns_id_argc              #     K   t         j                  j                  j                  |      }| j	                  | j
                  ||      }|D ]  \  }}}}	}
}}|r||k7  r|\  }}}| j                  ||      \  }}|r&dj                  d |j                         D              n	t               }||j                  |t        j                  |j                  j                        |	|
|g||}d|f  yw)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   0   K   | ]  \  }}| d |   yw)=Nr   ).0kvs      r6   	<genexpr>z&Sockstat._generator.<locals>.<genexpr>e  s     A1A3asAs   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;  s    * kk((::4@,,LL,K - 
 
 8(3%D)X"&"5"5i"JIx  A0@AA&(    1
 
 "
F f+3 s   C2C4c                 |   | j                   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        || j                  |||            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.runx  s    {{v&;;w'{{8, cNCL3KL,,-sOSMcNC C %%cNsO
  h(UVVrO   N)r   r   r   r   r   r   classmethodr   r   r   ContextInterfacer}   r   r   boolr  r  r   r,  r8  r   rO   r6   r   r     s    :"+H#
 #
J 
 .=	ES##44ES ES seTk*	ES ESN*$;tCy ; ;3 ;z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>rI     sp   
  . . L L U U < 4 1 / * 
		8	$]":++@@ ]"@YWw&& YWrO   