
    j"?                         d dl Z d dlZd dlmZmZ d dlZd dlmZ d dlm	Z	m
Z
mZ d dlmZmZ d dlmZ  G d d          ZdS )	    N)IteratorUnion)logger)	androconfapkdex)AnalysisStringAnalysis)DecompilerDADc                      e Zd ZdZ	 	 d%dededdfdZd&d	eedf         ddfd
Zd Z	d'dZ
defdZd'dZd Zd Zd	ededeeej        f         fdZ	 	 d(d	ededeedf         dedeeej        ef         f
dZ	 d&d	ededeedf         deeej        ef         fdZ	 	 d)d	edeedf         deedf         deedf         fdZdeeeeeeej                 f                  fdZdej        defdZ dej        dej        fdZ!dej        deedf         fdZ"dej        deedf         fdZ#deeeee$ee%f         f                  fdZ&defd Z'deeeej        f                  fd!Z(	 	 d)d	eedf         d"eedf         deeej        eej                 ef                  fd#Z)deeeej        ef                  fd$Z*dS )*Sessiona  
    A Session is able to store in a database, basic information about APK, DEX or ODEX files.
    Additionally, it offers the possibility to store actions done when using the 'pentest' module.

    NOTE: an attempt to move from pickling to dataset was started here:
    <https://github.com/androguard/androguard/commit/4dd0dc8c4b55605af863925faf16e8eb35f13e45>
    but is NOT finished!

    > Should we go back to pickling or proceed further with the dataset ?
    Fsqlite:///androguard.dbexport_ipythondb_urlreturnNc                 :   |                                   || _        t          j        |          | _        t          j        d                    | j                             | j        d         | _        | j        d         | _	        | j        d         | _
        | j        d         | _        t          | j	                  | _        | j	                            t          | j                             t          j        d                    | j                             dS )	z
        Create a new Session object

        :param export_ipython: set to True in order to create attributes for the
        use in iPython
        zOpening database {}informationsessionpentestsystem)idzCreating new session [{}]N)_setup_objectsr   datasetconnectdbr   infoformattable_informationtable_sessiontable_pentesttable_systemlen
session_idinsertdict)selfr   r   s      Y/home/ubuntu/.hermes/hermes-agent/venv/lib/python3.11/site-packages/androguard/session.py__init__zSession.__init__   s     	,/&)))0099:::!%!7!WY/!WY/ GH-d011!!$$/":":":;;;/66tGGHHHHH    filenamec                 `    t          j        d           | j                                         dS )z*
        Save the current session
        zSaving the databaseN)r   r   r   commit)r&   r*   s     r'   savezSession.save3   s-     	)***r)   c                     t          j        t                    | _        t	                      | _        t	                      | _        g | _        t          j                    | _	        t	                      | _
        d S N)collectionsdefaultdictlistanalyzed_filesr%   analyzed_digestanalyzed_apkadded_filesOrderedDictanalyzed_vmsanalyzed_dexr&   s    r'   r   zSession._setup_objects:   s\    )5d;;#vv FF
 (355
 !FFr)   c                 .    |                                   dS )zD
        Reset the current session, delete all added files.
        N)r   r:   s    r'   resetzSession.resetJ   s     	r)   c                 2    t          | j                  dk    S )z
        Test if any file was analyzed in this session

        :return: `True` if any file was analyzed, `False` otherwise
        r   )r"   r4   r:   s    r'   isOpenzSession.isOpenP   s     4'((1,,r)   c                    t          d                    t          | j                                       | j                                        D ](\  }}t          d                    ||                     )t          d                    t          | j                                       | j                                        D ](\  }}t          d                    ||                     )t          d                    t          | j                                       | j                                        D ](\  }}t          d                    ||                     )dS )z
        Print information to stdout about the current session.
        Gets all APKs, all DEX files and all Analysis objects.
        zAPKs in Session: {}z	{}: {}zDEXs in Session: {}zAnalysis in Session: {}N)printr   r"   r5   itemsr9   r8   )r&   dar   s       r'   showzSession.showX   sO   
 	#**3t/@+A+ABBCCC%++-- 	+ 	+DAq*##Aq))****#**3t/@+A+ABBCCC'--// 	- 	-FAs*##As++,,,,'..s43D/E/EFFGGG%++-- 	+ 	+DAq*##Aq))****	+ 	+r)   c           	          | j                             t          t          | j                  ||||                     d S )N)r#   callcalleeparamsret)r    r$   r%   strr#   )r&   rF   rG   rH   rI   s        r'   insert_eventzSession.insert_eventi   sR    !!t//  	
 	
 	
 	
 	
r)   c           	          | j                             t          t          | j                  ||||                     d S )N)r#   rF   rG   r   rH   )r!   r$   r%   rJ   r#   )r&   rF   rG   r   rH   s        r'   insert_system_eventzSession.insert_system_eventt   sR      t//'  	
 	
 	
 	
 	
r)   datac                    t          j        |                                          }t          j        d                    ||                     | j                            t          t          | j
                  ||d                     t          j        |d          }|g| j        |<   | j        |                             |           || j        |<   | j                            |           t%                      }|| j        |<   |                                D ]}|                     |||d           |                                 t          j        d                    ||                     ||fS )z
        Add an APK file to the Session and run analysis on it.

        :param filename: (file)name of APK file
        :param data: binary data of the APK file
        :return: a tuple of SHA256 Checksum and APK Object
        zadd APK {}:{}APKr#   r*   digesttypeT)postpone_xrefzadded APK {}:{})hashlibsha256	hexdigestr   r   r   r   r$   r%   rJ   r#   r   rP   r5   r3   appendr4   r6   r	   r8   get_all_dexaddDEXcreate_xref)r&   r*   rN   rR   newapkdxr   s          r'   addAPKzSession.addAPK   so    %%//11O**8V<<===%%t//!	  	
 	
 	
 t$$%+H&!H%,,V444'/V$)))ZZ$&&!%%'' 	? 	?CKK#rK>>>> 	%,,Xv>>???v~r)   r]   rT   c                    t          j        |                                          }t          j        d                    |                     | j                            t          t          | j
                  ||d                     t          j        d           t          j        |          }t          j        d                    |                     | j        |                             |           || j        |<   || j        |<   |t%                      }|                    |           |s|                                 t          j        d           |j        D ]:}|                    t/          ||                     |                    |           ;|| j        |<   | j        r(t          j        d           |                                 |||fS )	a  
        Add a DEX file to the Session and run analysis.

        :param filename: the (file)name of the DEX file
        :param data: binary data of the dex file
        :param dx: an existing `Analysis` Object (optional)
        :param postpone_xref: True if no xref shall be created, and will be called manually
        :return: A tuple of SHA256 Hash, DEX Object and `Analysis` object
        z
add DEX:{}DEXrQ   zParsing format ...zadded DEX:{}Nz(Associated decompiler to the DEX objectszExporting in ipython)rU   rV   rW   r   r   r   r   r$   r%   rJ   r#   debugr   r`   r3   rX   r4   r9   r	   addr[   vmsset_decompilerr   set_analysisr8   r   create_python_export)r&   r*   rN   r]   rT   rR   rB   s          r'   rZ   zSession.addDEX   s     %%//11L''//000%%t//!	  	
 	
 	
 	)***GDMMN))&11222H%,,V444'/V$$%&!:B
q			 	NN?@@@ 	 	A]1b11222NN2$&&! 	%L/000""$$$q"}r)   c                    t          j        |                                          }t          j        d|z             | j                            t          t          | j	                  ||d                     t          j        |          }t          j        d|z             | j        |                             |           || j        |<   || j        |<   | j        r|                                 |t'                      }|                    |           |                                 |j        D ]:}|                    t1          ||                     |                    |           ;|| j        |<   |||fS )aP  
        Add an ODEX file to the session and run the analysis

        :param filename: the ODEX filename
        :param data: the ODEX bytes
        :param dx: the `Analysis` object to add the ODEX to
        :returns: a tuple containing the SHA256 digest, the new `dex.ODEX` object, and the `Analysis` it is contained within.
        zadd ODEX:%sODEXrQ   zadded ODEX:%s)rU   rV   rW   r   r   r   r$   r%   rJ   r#   r   rh   ra   r3   rX   r4   r9   r   rf   r	   rb   r[   rc   rd   r   set_vmanalysisr8   )r&   r*   rN   r]   rR   rB   s         r'   addODEXzSession.addODEX   sz    %%//11MF*+++%%t//!	  	
 	
 	
 HTNN_v-...H%,,V444'/V$$%&! 	%""$$$:B
q			
 	! 	!A]1b11222R    $&&!q"}r)   raw_datac                    |sct          j        d                    |                     t          |d          5 }|                                }ddd           n# 1 swxY w Y   t          j        |          }t          j        d                    |                     |sdS |dk    r|                     ||          \  }}nF|dk    r|                     |||          \  }}}n$|dk    r| 	                    |||          \  }}}ndS |S )as  
        Generic method to add a file to the session.

        This is the main method to use when adding files to a Session!

        If an APK file is supplied, all DEX files are analyzed too.
        For DEX and ODEX files, only this file is analyzed (what else should be
        analyzed).

        Returns the SHA256 of the analyzed file.

        :param filename: filename to load
        :param raw_data: bytes of the file, or None to load the file from filename
        :param dx: An already exiting `androguard.core.analysis.analysis.Analysis` object
        :return: the sha256 of the file or None on failure
        zLoading file from '{}'rbNzFound filetype: '{}'rP   r`   DEY)
r   ra   r   openreadr   is_android_rawr^   rZ   rj   )r&   r*   rk   r]   fprI   rR   _s           r'   rb   zSession.add  sP   ,  	%L188BBCCCh%% %7799% % % % % % % % % % % % % % % &x00+22377888 	4%<<Hh77IFAAE\\;;x2>>LFAqqE\\<<(B??LFAqq4s   AA"Ac              #      K   t          | j                  D ]C\  }}| j        |         }|j        D ])}| j        |         }||||                                fV  *DdS )a=  
        Returns all Java Classes from the DEX objects as an array of DEX files.

        :returns: an iterator where each element is a tuple containing the index of the `Analysis` object, the filename containing the class (ODEX, DEX), the SHA256 digest of the `Analysis` object, and a list of `CalssDefItem`
        N)	enumerater8   rc   r4   get_classes)r&   idxrR   r]   vmr*   s         r'   rv   zSession.get_classes;  s       %T%677 	> 	>KC"6*Bf > >/78VR^^-=-======>	> 	>r)   current_classc                     | j         D ]:}| j         |         }|                    |                                          r|c S ;dS )a  
        Returns the [Analysis][androguard.core.analysis.analysis.Analysis] object
        which contains the `current_class`.

        :param current_class: The class to search for
        :returns: the `androguard.core.analysis.analysis.Analysis` object
        N)r8   is_class_presentget_namer&   ry   rR   r]   s       r'   get_analysiszSession.get_analysisI  sX     ' 	 	F"6*B""=#9#9#;#;<< 			tr)   c                     |j         j        S )z
        Returns the [DEX][androguard.core.dex.DEX] of a
        given [ClassDefItem][androguard.core.dex.ClassDefItem].

        :param current_class: A ClassDefItem
        )CMrx   )r&   ry   s     r'   
get_formatzSession.get_formatW  s     ""r)   c                     | j                                         D ];\  }}|                    |                                          r| j        |         c S <dS )ap  
        Returns the filename of the DEX file where the class is in.

        Returns the first filename this class was present.
        For example, if you analyzed an APK, this should return the filename of
        the APK and not of the DEX file.

        :param current_class: `ClassDefItem`
        :returns: `None` if class was not found or the filename
        N)r8   rA   r{   r|   r4   r}   s       r'   get_filename_by_classzSession.get_filename_by_class`  sf     +1133 	4 	4JFB""=#9#9#;#;<< 4+F33334tr)   c                     | j                                         D ]0\  }}|                    |                                          r|c S 1dS )a'  
        Return the SHA256 hash of the object containing the [ClassDefItem][androguard.core.dex.ClassDefItem]

        Returns the first digest this class was present.
        For example, if you analyzed an APK, this should return the digest of
        the APK and not of the DEX file.
        N)r8   rA   r{   r|   r}   s       r'   get_digest_by_classzSession.get_digest_by_classr  s[     +1133 	 	JFB""=#9#9#;#;<< tr)   c              #      K   g }| j                                         D ]C\  }}||v r
|                    |           || j        |         |                                fV  DdS )z
        Yields all [StringAnalysis][androguard.core.analysis.analysis.StringAnalysis] for all unique [Analysis][androguard.core.analysis.analysis.Analysis] objects

        :returns: an iterator of `StringAnalysis` objects
        N)r8   rA   rX   r4   get_strings_analysis)r&   seenrR   r]   s       r'   get_stringszSession.get_strings  s       +1133 	) 	)JFBTzzKKOOO$.&&(() ) ) ) )		) 	)r)   c                     d}g }| j                                         D ]C\  }}||v r
|                    |           |t          |                                          z  }D|S )z
        Return the total number of strings in all [Analysis][androguard.core.analysis.analysis.Analysis] objects

        :returns: the number of strings
        r   )r8   rA   rX   r"   r   )r&   nbr   rR   r]   s        r'   get_nb_stringszSession.get_nb_strings  sp     +1133 	1 	1JFBTzzKKOOO#b--//000BB	r)   c              #   T   K   | j                                         D ]\  }}||fV  dS )a  
        Yields a list of tuples of SHA256 hash of the APK and [APK][androguard.core.apk.APK] objects
        of all analyzed APKs in the Session.

        :returns: an iterator where each element is a tuple of sha256 of the APK, and the `APK` object
        N)r5   rA   )r&   rR   rC   s      r'   get_all_apkszSession.get_all_apks  sC       *0022 	 	IFA!)OOOO	 	r)   rR   c                     |s|st          d          |&| j                            |          }|sdS |d         }| j        |         d         }| j        |         }||j        |fS )a`  
        Returns [APK][androguard.core.apk.APK], list of [DEX][androguard.core.dex.DEX], and [Analysis][androguard.core.analysis.analysis.Analysis] of a specified APK.

        You must specify either `filename` or `digest`.
        It is possible to use both, but in this case only `digest` is used.

        Example:

            >>> s = Session()
            >>> digest = s.add("some.apk")
            >>> a, d, dx = s.get_objects_apk(digest=digest)

        Example:

            >>> s = Session()
            >>> filename = "some.apk"
            >>> digest = s.add(filename)
            >>> a, d, dx = s.get_objects_apk(filename=filename)

        :param filename: the filename of the APK file, only used of digest is `None`
        :param digest: the sha256 hash, as returned by `add` for the APK
        :returns: a tuple of (APK, [DEX], Analysis)
        z&Must give at least filename or digest!N)NNNr   )
ValueErrorr3   getr5   r8   rc   )r&   r*   rR   digestsrC   r]   s         r'   get_objects_apkzSession.get_objects_apk  s    8  	G 	GEFFF>)--h77G (''QZFf%a(v&"&"}r)   c              #   l   K   | j                                         D ]\  }}||| j        |         fV  dS )z
        Yields all [DEX][androguard.core.dex.DEX] objects including their [Analysis][androguard.core.analysis.analysis.Analysis] objects

        :returns: tuple of (sha256, DEX, Analysis)
        N)r9   rA   r8   )r&   rR   rB   s      r'   get_objects_dexzSession.get_objects_dex  sR       *0022 	7 	7IFA!T.v666666	7 	7r)   )Fr   r/   )r   N)NF)NN)+__name__
__module____qualname____doc__boolrJ   r(   r   r-   r   r<   r>   rD   rK   rM   bytestupler   rP   r^   r	   r   r`   rZ   rh   rj   rb   r   intr2   ClassDefItemrv   r~   r   r   r   r%   r
   r   r   r   r   r    r)   r'   r   r      sS       	 	  %/I II I 
	I I I I4 U39-     # # #    - - - - -+ + + +"	
 	
 	
	
 	
 	
%s %% %E#sw,4G % % % %V %)#7 77 7 (D.!	7
 7 
sCGX%	&7 7 7 7t GK/ //#(/.3HdN.C/	sCHh&	'/ / / /h (,$(	) )) t$) (D.!	)
 
sDy	) ) ) )V>	%S#tC,<'==>	?> > > >#*: x    #(8 #SW # # # # -	sDy	   $ -	sDy	   )	%S$sN':";;<	=) ) ) )"    huS#'\':;     &*#'( (T	"( c4i ( 
%cg89	:	( ( ( (T7%SWh0F*G!H 7 7 7 7 7 7r)   r   )r0   rU   typingr   r   r   logurur   androguard.corer   r   r   !androguard.core.analysis.analysisr	   r
    androguard.decompiler.decompilerr   r   r   r)   r'   <module>r      s         " " " " " " " "        / / / / / / / / / / F F F F F F F F : : : : : :P7 P7 P7 P7 P7 P7 P7 P7 P7 P7r)   