o
    j>                  
   @   s  d dl mZ d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dl	m
Z
 d dlmZ d dl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mZ d dlmZ G dd dZG dd dZ e!dkrKej"j#du re$dej"e_"e%ej& ej'dddZ(e(j)dddd e(j)dddd e(j)dddd e(j*dd d!Z+e+j,d"d#d$Z-e-j)d%ddd&d' e-j)d(dd)d*d+d, e-j)d-dd*d*d.d/ e-j)d0dd*d1d2 e+j,d3d4d$Z,e,j)d%ddd&d' e,j)d(dd)d*d5d, e,j)d6dd7d*d8d9d: e,j)d;d<d=d*d>g d: e,j)d?dd*d@d' e+j,dAdBd$Z.e.j)d%ddd&d' e.j)d(dd)d*dCd, e.j)dDdd*dEd' e.j)d-dd*dFd' e+j,dGdHd$Z/e/j)d%ddd&d' e/j)dIdJddKddLdM e+j,dNdOd$Z0e0j)dIdJddKddLdM e(1dPZ2e2j)dQddRdSdT e2j)dUddVd e2j)dWddXd e2j)dYddZd[dT e(1d\Z2e2j)d]dd^d_dT e2j)d`dd^dadT e2j)dbdcddgdedddfdgdh e3ej4dikre(5  e6di e(7 Z8e9e8j:e8j; ee8j<\Z=Z>Z?Z@e8jAdu re@e8_Ae=du rdjZ=e8jBdurde8_Ce?djkre>djkre8jDdu re8jEd*u re8jBdu rd dklFmFZF eFdlZ?e e>e?e=e8ZGz
eGHe@e8jA W dS  eIyJ ZJ zeKeLeJ W Y dZJ[JdS dZJ[Jww dS )m    )division)print_functionN)unpack)version)	transportrrpscmrrpcrt)logger)parse_target)ERROR_NO_MORE_ITEMS)hexdump)SMBConnectionSessionError)READ_CONTROLc                   @   sN   e Zd ZdddZdd Zdd Zdd	 Zd
d Zdd Zdd Z	dd Z
dS )RemoteOperationsNc                 C   sX   || _ | j d d| _d| _d | _d | _|| _|| _d| _d| _	d| _
d| _d | _d S )Ni,  RemoteRegistryzncacn_np:445[\pipe\winreg]Fzncacn_np:445[\pipe\svcctl]) _RemoteOperations__smbConnection
setTimeout_RemoteOperations__serviceName&_RemoteOperations__stringBindingWinReg_RemoteOperations__rrp_RemoteOperations__regHandle_RemoteOperations__doKerberos_RemoteOperations__kdcHost_RemoteOperations__disabled_RemoteOperations__shouldStop_RemoteOperations__started&_RemoteOperations__stringBindingSvcCtl_RemoteOperations__scmr)selfsmbConnection
doKerberoskdcHost r$   /root/aizidognhua/tmp/workspace/projects/ec89d86c-575f-41c9-af57-ac45cbdbf775/venv/lib/python3.10/site-packages/../../../bin/reg.py__init__4   s   
zRemoteOperations.__init__c                 C   s   | j S N)r   r    r$   r$   r%   getRRPF   s   zRemoteOperations.getRRPc                 C   >   t | j}|| j | | _| j  | jt	j
 d S r'   )r   DCERPCTransportFactoryr   set_smb_connectionr   get_dce_rpcr   connectbindr   MSRPC_UUID_SCMRr    rpcr$   r$   r%   __connectSvcCtlI   
   

z RemoteOperations.__connectSvcCtlc                 C   r*   r'   )r   r+   r   r,   r   r-   r   r.   r/   r   MSRPC_UUID_RRPr1   r$   r$   r%   connectWinRegP   r4   zRemoteOperations.connectWinRegc                 C   s:  t | j}|d | _t | j| j| j}|d | _t | j| j}|d d t jkr:t	
d| j  d| _d| _n |d d t jkrRt	d| j  d| _d| _ntd	|d
  | jdu rt | j| j}|d d dkrt	
d| j  d| _t j| j| jdd t	
d| j  t | j| j td d S d S )N
lpScHandlelpServiceHandlelpServiceStatusdwCurrentStatezService %s is in stopped stateTFzService %s is already runningz%Unknown service state 0x%x - AbortingCurrentStatelpServiceConfigdwStartType   z#Service %s is disabled, enabling it   r=   zStarting service %s   )r   hROpenSCManagerWr   "_RemoteOperations__scManagerHandlehROpenServiceWr    _RemoteOperations__serviceHandlehRQueryServiceStatusSERVICE_STOPPEDlogginginfor   r   SERVICE_RUNNINGdebug	ExceptionhRQueryServiceConfigWr   hRChangeServiceConfigWhRStartServiceWtimesleep)r    ansr$   r$   r%   __checkServiceStatusW   s0   


z%RemoteOperations.__checkServiceStatusc                 C   s   |    |   |   d S r'   ) _RemoteOperations__connectSvcCtl%_RemoteOperations__checkServiceStatusr6   r(   r$   r$   r%   enableRegistryv   s   zRemoteOperations.enableRegistryc                 C   sd   | j du rtd| j  t| j| jtj | j	du r0td| j  tj
| j| jdd d S d S )NTzStopping service %sz+Restoring the disabled state for service %sr>   r@   )r   rH   rI   r   r   hRControlServicer   rE   SERVICE_CONTROL_STOPr   rN   r(   r$   r$   r%   	__restore{   s   

zRemoteOperations.__restorec                 C   s8   |    | jd ur| j  | jd ur| j  d S d S r'   )_RemoteOperations__restorer   
disconnectr   r(   r$   r$   r%   finish   s   


zRemoteOperations.finishr'   )__name__
__module____qualname__r&   r)   rT   r6   rU   rV   rZ   r\   r$   r$   r$   r%   r   3   s    
	r   c                   @   sp   e Zd Zdd Zdd Zdd Zdd Zd	d
 Zdd Zdd Z	dd Z
dd Zdd Zdd Zedd ZdS )
RegHandlerc              
   C   s   || _ || _|| _|| _|j | _d| _d| _|j	| _
|j| _|j| _d | _d | _dddddddd	d
d	| _|jd urH|jd\| _| _d S d S )N REG_NONEREG_SZREG_EXPAND_SZ
REG_BINARY	REG_DWORDREG_DWORD_BIG_ENDIANREG_LINKREG_MULTI_SZ	REG_QWORD)	r   rA      r?   r>               :)_RegHandler__username_RegHandler__password_RegHandler__domain_RegHandler__optionsactionupper_RegHandler__action_RegHandler__lmhash_RegHandler__nthashaesKey_RegHandler__aesKeyk_RegHandler__doKerberosdc_ip_RegHandler__kdcHost_RegHandler__smbConnection_RegHandler__remoteOps_RegHandler__regValueshashessplit)r    usernamepassworddomainoptionsr$   r$   r%   r&      s$   

zRegHandler.__init__c              	   C   sj   t ||t| jjd| _| jr$| j| j| j| j	| j
| j| j| j d S | j| j| j| j	| j
| j d S )N)	sess_port)r   intrt   portr   r}   kerberosLoginrq   rr   rs   rx   ry   r{   r   login)r    
remoteName
remoteHostr$   r$   r%   r.      s   "zRegHandler.connectc              
   C   s  |  || t| j| j| j| _z| j  W n' ty> } zt	t
| td |   | j  W Y d }~nd }~ww zz[| j }| jdkrT| || jj nF| jdkre| || jj| jj n5| jdkrs| || jj n'| jdkr| || jj n| jdkrdD ]}| || qntd| j  W n ttfy } ztt
| W Y d }~nd }~ww W | jr| j  d S d S | jr| j  w w )	NzICannot check RemoteRegistry status. Triggering start trough named pipe...QUERYADDDELETESAVEBACKUP)zHKLM\SAMzHKLM\SYSTEMzHKLM\SECURITYzMethod %s not implemented yet!)r.   r   r   r}   r   r   rV   rL   rH   rK   strwarningtriggerWinRegr6   r)   rw   queryrt   keyNameadd
persistentdeletesaveerrorKeyboardInterruptcriticalr\   )r    r   r   edcehiver$   r$   r%   run   sJ   







zRegHandler.runc                 C   sH   | j d}z| j j|ddddd W n	 ty   Y nw td d S )NzIPC$z\winregi @      )creationOptionfileAttributesrA   )r   connectTreeopenFiler   rP   rQ   )r    tidr$   r$   r%   r      s   zRegHandler.triggerWinRegc              
   C   s   |  ||\}}d| jj|f }td|  z$tj|||tjtjB tj	d}t
||d | td||f  W d S  tyW } ztd||f  W Y d }~d S d }~ww )Nz
%s\%s.savezMDumping %s, be patient it can take a while for large hives (e.g. HKLM\SYSTEM)	dwOptions
samDesired	phkResultzSaved %s to %szCouldn't save %s: %s)_RegHandler__strip_root_keyrt   
outputPathrH   rK   r   hBaseRegOpenKeyREG_OPTION_BACKUP_RESTOREREG_OPTION_OPEN_LINKKEY_READhBaseRegSaveKeyrI   rL   r   )r    r   r   hRootKeysubKeyoutputFileNameans2r   r$   r$   r%   r      s    zRegHandler.savec           	      C   sp  |  ||\}}tj|||tjtjB tjB d}| jjrGt| t	||d | jj}td| jj d | j
|d d d t|d  d S | jjrnt| t	||d d}td| j
|d d d t|d  d S | jjr| ||d	 |d d d S t| | ||d  d}	 zt||d |}t|d	 |d d d   |d7 }W n
 ty   Y d S w q)Nr   r   	r   KEY_NOT_FOUNDrA   ra   z	(Default)	\T	lpNameOut)r   r   r   MAXIMUM_ALLOWEDKEY_ENUMERATE_SUB_KEYSKEY_QUERY_VALUErt   vprinthBaseRegQueryValuer   getr   ves*_RegHandler__print_all_subkeys_and_entries_RegHandler__print_key_valueshBaseRegEnumKeyrL   )	r    r   r   r   r   r   valueikeyr$   r$   r%   r      s4   
8,zRegHandler.queryc                 C   s8  |  ||\}}| jjd u rb|}d|dd d }tj|||ttjB tj	B d}d}|du r4d}nt
d tj||||ttjB tj	B d}	|	d	 dkrVt
d
|  d S t
d|	d	 |f  d S tj|||ttjB tj	B d}tt| jjd }
|
d u s| jjdstd| jj |
tjkrd| jj}|d }|dd}nBt| jjdkr| jjd nd}|
tjtjtjtjtjfv rt|}n|
tjkrt|}||d@ 7 }t||d}n|d }|}t||d | jj|
|}	|	d	 dkr	t
d|| jj| jj|f  d S t
d|	d	 || jj| jj|f  d S )Nr   r   r   rA   Tr   zD[!] The created key is volatile and will not remain after a reboot. r   	ErrorCodezSuccessfully set subkey %sz%Error 0x%08x while creating subkey %sREG_zError parsing value type %s z  z
		ra   0r   z.Successfully set
	key	%s\%s
	type	%s
	value	%sz8Error 0x%08x while setting
	key	%s\%s
	type	%s
	value	%s)r   rt   r   joinr   r   r   r   KEY_SET_VALUEKEY_CREATE_SUB_KEYr   hBaseRegCreateKeygetattrvt
startswithrL   ri   vdreplacelenrf   rg   REG_DWORD_LITTLE_ENDIANrj   REG_QWORD_LITTLE_ENDIANr   re   binasciia2b_hexljusthBaseRegSetValue)r    r   r   r   r   r   subKeyCreater   dwOptionans3dwTyper   	valueDatavalueDataToPrintbin_value_lenr$   r$   r%   r     sl   



 

zRegHandler.addc                 C   sx  |  ||\}}| jjd u r| jjs| jjs|}d|dd d }tj|||t	tj
B tjB d}z	t|||}W n7 tjy\ } z|jdkrWtd|  W Y d }~d S  d }~w tys } ztd W Y d }~d S d }~ww |d dkrtd	|  d S td
|d |f  d S | jjrtj|||t	tj
B tjB d}t||d | jj}|d dkrtd|| jjf  d S td|d || jjf  d S | jjr	tj|||t	tj
B tjB d}t||d d}|d dkrtd|df  d S td|d || jjf  d S | jjrtj|||tjtjB d}d}	g }
	 zt||d |	}|d d d }|
| |	d7 }	W n! tjy] } z| tkrSW Y d }~nW Y d }~nd }~ww q tj|||tjtjB d}|
D ]J}z't||d |}|d dkrtd||f  ntd|d ||f  W qo ty } ztdt|||f  W Y d }~qod }~ww d S d S )Nr   r   r   rl   zMCannot delete key %s. Possibly it contains subkeys or insufficient privilegesz+Unhandled exception while hBaseRegDeleteKeyr   r   zSuccessfully deleted subkey %sz%Error 0x%08x while deleting subkey %sr   zSuccessfully deleted key %s\%sz%Error 0x%08x while deleting key %s\%sra   z Successfully deleted value %s\%sDefaultz'Error 0x%08x while deleting value %s\%sTlpValueNameOutrA   z'Error 0x%08x in deletion of value %s\%sz-Unhandled error %s in deletion of value %s\%s)r   rt   r   var   r   r   r   r   r   r   r   hBaseRegDeleteKeyr	   DCERPCException
error_coder   rL   rH   r   hBaseRegDeleteValuer   r   hBaseRegEnumValueappendDCERPCSessionErrorget_error_coder   r   )r    r   r   r   r   subKeyDeleter   r   r   r   
allSubKeyslp_value_nameans4ans5r$   r$   r%   r   R  s   


















zRegHandler.deletec                 C   s   z| dd }d| ddd  }W n ty"   td| w | dkr/t|}n*| dkr;t|}n| dkrGt|}n| dkrSt|}ntd	| |d
 }||fS )Nr   r   rA   zError parsing keyName %sHKLMHKCUHKUHKCRzInvalid root key %s phKey)	r   r   rL   rv   r   hOpenLocalMachinehOpenCurrentUser
hOpenUsershOpenClassesRoot)r    r   r   rootKeyr   rR   r   r$   r$   r%   __strip_root_key  s"   zRegHandler.__strip_root_keyc           	   
   C   s   d}	 zAt |||}|d d d }t|dkrd}|d }d|d }td	| d	 | j|d
 d	 dd | || |d7 }W n  t jyd } z|	 t
krZW Y d }~d S W Y d }~nd }~ww q)Nr   Tr   r   z	(Default)lpType    lpDatar   r    )endrA   )r   r   r   r   r   r   r   _RegHandler__parse_lp_datar   r   r   )	r    r2   
keyHandlerr   r   r   lp_typelp_datar   r$   r$   r%   __print_key_values  s&   &zRegHandler.__print_key_valuesc           	   
   C   sR  d}	 z>t |||}|d7 }t j|||d t jt jB d}||d d d  d }t| | ||d  | |||d d W nf t jya } z|	 t
krWW Y d }~d S W Y d }~nKd }~w tjy } z:t|d	dkrtd
|d d d   W Y d }~qt|ddkrtd|d d d   W Y d }~d S  d }~ww q)Nr   TrA   r   r   r   r   r   access_deniedz%Cannot access subkey %s, bypassing itrpc_x_bad_stub_dataz6Fault call, cannot retrieve value for %s, bypassing it)r   r   r   r   r   r   r   r   r   r   r   r	   r   r   findrH   r   )	r    r2   r   r  indexsubkeyrR   
newKeyNamer   r$   r$   r%   __print_all_subkeys_and_entries  s8   
z*RegHandler.__print_all_subkeys_and_entriesc              
   C   s  z| t jks| t jkr(t|tu rtd W d S td|dd d   W d S | t jkr9td t|d W d S | t j	krLtdt
d|d	   W d S | t jkr_tdt
d
|d	   W d S | t jkrzt|dkrutd t|d ntd W W d S W W d S    td Y W d S | t jkrtd|dd d   W d S td|   t| W d S  ty } ztdt|  td W Y d }~d S d }~ww )NNULLz%szutf-16ler   ra   r   z0x%xz<Lr   z<QrA   z NULLzUnknown Type 0x%x!z+Exception thrown when printing reg value %szInvalid data)r   rc   rd   typer   r   decodere   r   rf   r   rj   rb   r   ri   rL   rH   rK   r   )	valueTyper   r   r$   r$   r%   __parse_lp_data  s>    




 zRegHandler.__parse_lp_dataN)r]   r^   r_   r&   r.   r   r   r   r   r   r   r   r   r   staticmethodr  r$   r$   r$   r%   r`      s    	$Oir`   __main__utf8Tz%Windows Register manipulation script.)add_helpdescriptiontargetstorez6[[domain/]username[:password]@]<targetName or address>)ru   helpz-debug
store_truezTurn DEBUG output ONz-tsz&Adds timestamp to every logging outputactionsru   )r$  destr   zqReturns a list of the next tier of subkeys and entries that are located under a specified subkey in the registry.)r$  z-keyNamezSpecifies the full path of the subkey. The keyName must include a valid root key. Valid root keys for the local computer are: HKLM, HKU, HKCU, HKCR.)ru   requiredr$  z-v	VALUENAMEFzoSpecifies the registry value name that is to be queried. If omitted, all value names for keyName are returned. )ru   metavarr(  r$  z-vez1Queries for the default value or empty value name)ru   defaultr(  r$  z-sz;Specifies to query all subkeys and value names recursively.)ru   r+  r$  r   z*Adds a new subkey or entry to the registryz[Specifies the registry value name that is to be set. Set to "" to write the (Default) valuez-vt	VALUETYPEzSpecifies the registry type name that is to be set. Default is REG_SZ. Valid types are: REG_NONE, REG_SZ, REG_EXPAND_SZ, REG_BINARY, REG_DWORD, REG_DWORD_BIG_ENDIAN, REG_LINK, REG_MULTI_SZ, REG_QWORDrc   )ru   r*  r(  r$  r+  z-vdr   	VALUEDATAzSpecifies the registry value data that is to be set. In case of adding a REG_MULTI_SZ value, set this option once for each line you want to add.z--persistentzjSpecify that the created key is intended to be persistent through reboot. Default is volatile key creationr   z-Deletes a subkey or entries from the registryz8Specifies the registry value name that is to be deleted.z-vaz!Delete all values under this key.z/Delete the value of empty value name (Default).r   z[Saves a copy of specified subkeys, entries, and values of the registry in a specified file.z-or   z\\192.168.0.2\sharezCOutput UNC path the target system must export the registry saves to)r'  ru   r*  r(  r$  backupzW(special command) Backs up HKLM\SAM, HKLM\SYSTEM and HKLM\SECURITY to a specified file.authenticationz-hasheszLMHASH:NTHASHz$NTLM hashes, format is LMHASH:NTHASH)ru   r*  r$  z-no-passz&don't ask for password (useful for -k)z-kzUse Kerberos authentication. Grabs credentials from ccache file (KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use the ones specified in the command linez-aesKeyzhex keyz<AES key to use for Kerberos Authentication (128 or 256 bits)
connectionz-dc-ipz
ip addressztIP Address of the domain controller. If omitted it will use the domain part (FQDN) specified in the target parameterz
-target-ipzIP Address of the target machine. If omitted it will use whatever was specified as target. This is useful when target is the NetBIOS name and you cannot resolve itz-port139445?zdestination portz)Destination port to connect to SMB Server)choicesnargsr+  r*  r$  rA   ra   )getpassz	Password:)M
__future__r   r   argparsecodecsrH   sysrP   r   structr   impacketr   impacket.dcerpc.v5r   r   r   r	   impacket.examplesr
   impacket.examples.utilsr   impacket.system_errorsr   impacket.structurer   impacket.smbconnectionr   r   impacket.dcerpc.v5.dtypesr   r   r`   r]   stdoutencoding	getwriterr   BANNERArgumentParserparseradd_argumentadd_subparsers
subparsers
add_parserquery_parserdelete_parsersave_parserbackup_parseradd_argument_groupgroupr   argv
print_helpexit
parse_argsr   inittsrK   r"  r   r   r   r   	target_iprz   r|   r   no_passr6  
regHandlerr   rL   r   r   r   r$   r$   r$   r%   <module>   s   Y   












8 