o
    jT                     @   s   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
mZmZmZ d dlZdZdZd	Zd
ZdZd	ZdZdZdZdZdZdZddddddZG dd deZG dd deZG dd deZG dd dZG dd dZ dS )    )	Structure)lsadlsat)SMBTransport)SMBConnection)FileSecInformationFILE_OPEN_REPARSE_POINTGENERIC_ALLREAD_CONTROLN               i      i  i  i i   i )RWDXFc                   @   s   e Zd ZdZdS )
FileNTUser))Revision<H=1)Sizer   )NumACEsz<I=1)Buffer:N)__name__
__module____qualname__	structure r!   r!   /root/aizidognhua/tmp/workspace/projects/ec89d86c-575f-41c9-af57-ac45cbdbf775/venv/lib/python3.10/site-packages/impacket/acl.pyr   9   s    r   c                   @   sD   e Zd ZdZdd Zedd Zdd Zdd	 Zd
d Z	dd Z
dS )ACL_SID))r   <B)NumAuthr$   )	Authority6s)Subauthoritiesr   c                 C   sh   t | d d }td| d dd d }dttdt| d	 |gttd
t|| d  S )Nr(   r   z>Hr&      r   -Sr   <{}I)	lenstructunpackjoinmapstrintlistformat)selfn	authorityr!   r!   r"   __repr__K   s   zACL_SID.__repr__c                 C   s   |  ddd  }t|d }t|d }t|d }tjd|gttt|dd  R  }td||d td| | }t|S )	Nr*   r   r   r   r,   z<2Bs        r$   )	splitr3   r-   r.   packr5   tupler1   r#   )dataitemsrevisionnumAuth
sub_lengthsubauthoritiesraw_sidr!   r!   r"   build_from_stringW   s   *
zACL_SID.build_from_stringc                 C      |   S Nr9   r6   r!   r!   r"   __str__f      zACL_SID.__str__c                 C      |   |  kS rF   rG   r6   otherr!   r!   r"   __eq__i      zACL_SID.__eq__c                 C   s   |    S rF   )r9   __hash__rH   r!   r!   r"   rP   l   s   zACL_SID.__hash__c                 O   s   |   j|i |S rF   )rI   r:   )r6   argskwargsr!   r!   r"   r:   o   s   zACL_SID.splitN)r   r   r   r    r9   staticmethodrD   rI   rN   rP   r:   r!   r!   r!   r"   r#   C   s    
r#   c                
   @   sF   e Zd Zddddddddd	effZd
d Zdd Zdd Zdd ZdS )	FileNTACE)Typer$   )NTACE_Flagsr$   )r   <H)SpecificRightsrW   )StandardRightsr$   )GenericRightsr$   )_SIDz_-SIDz(self["Size"] - 8)SIDz:=""c                 C   s4   |   }|  }|dkr|| S |  }|| | S )N(F))get_readable_ntace_flagsget_readable_specific_rightsget_readable_standard_rights)r6   flagsspecificstandardr!   r!   r"   rI      s   zFileNTACE.__str__c                 C   sx   d}| d t @ r|d7 }| d t@ r|d7 }| d t@ r |d7 }| d t@ r*|d7 }| d t@ r4|d7 }|dkr:dS |S )z
        Return the NTACE flags in readable format
        (OI) - object inherit
        (CI) - container inherit
        (IO) - inherit only
        (NP) - don't propagate inherit
        (I) - permission inherited from parent container
         rV   z(OI)z(CI)z(IO)z(NP)z(I))SMB_ACE_FLAG_OISMB_ACE_FLAG_CISMB_ACE_FLAG_IOSMB_ACE_FLAG_NPSMB_ACE_FLAG_Ir6   ra   r!   r!   r"   r^      s   	z"FileNTACE.get_readable_ntace_flagsc                 C   sD   d}| d t @ r|d7 }| d t@ r|d7 }| d t@ r |d7 }|S )z
        Return the standard rights in readable format
        NOTE: does not cover all standard rights (WRITE_DAC and SYNC)
        R - read-only access
        W - write-only access
        D - delete access
        rd   rY   z(R)z(w)z(D))SEC_INFO_STANDARD_READSEC_INFO_STANDARD_WRITESEC_INFO_STANDARD_DELETErj   r!   r!   r"   r`      s   z&FileNTACE.get_readable_standard_rightsc                 C   sL   | d t @ t kr
dS d}| d t@ tkr|d7 }| d t@ tkr$|d7 }|S )z
        Return the specific rights in readable format
        NOTE: does not cover all specific rights (only write, execute, full control)
        W - write access
        X - execute access
        F - full control
        rX   r]   rd   z(W)z(X))SEC_INFO_SPECIFIC_FULLSEC_INFO_SPECIFIC_WRITESEC_INFO_SPECIFIC_EXECUTErj   r!   r!   r"   r_      s   
z&FileNTACE.get_readable_specific_rightsN)	r   r   r   r#   r    rI   r^   r`   r_   r!   r!   r!   r"   rT   t   s    rT   c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )SecurityAttributeszA
    This class represents the security attributes of a file
    c                 C   s   || _ || _i | _i | _d S rF   )ownergroupdaclsreadable_dacls)r6   rr   rs   r!   r!   r"   __init__   s   
zSecurityAttributes.__init__c              	      s(   d  j jd fdd jD S )NzOwner:	{}
Group:	{}
ACLs:
	{}z
	c                    s   g | ]	}t  j| qS r!   )r2   ru   ).0sidrH   r!   r"   
<listcomp>   s    z/SecurityAttributes.__repr__.<locals>.<listcomp>)r5   rr   rs   r0   ru   rH   r!   rH   r"   r9      s
   
zSecurityAttributes.__repr__c                 C   rE   rF   rG   rH   r!   r!   r"   rI      rJ   zSecurityAttributes.__str__c                 C   rK   rF   rG   rL   r!   r!   r"   rN      rO   zSecurityAttributes.__eq__N)r   r   r   __doc__rv   r9   rI   rN   r!   r!   r!   r"   rq      s    rq   c                   @   s   e Zd ZdZd"ddZdd Zd	d
 ZefddZdd Z	dd Z
dd Zdd Zdd Zd#ddZdd Zdd Zedd Zd#d d!ZdS )$
SMBFileACLz
    Manage Windows file ACLs over SMB. You can view, set, or remove ACLs.
    You must have the appropriate permissions to do so.
    Nrd   Fc              	   C   s   t ddi| _ddd| _|du | _|dur|| _nt||| _|	r0| j|||||||
 n
| j||||| | 	 | _
|  | _d| _d| _d| _dS )a  
        @param ip: target server's remote address (IPv4, IPv6) or FQDN
        @param remote_name: Remote NetBIOS name
        @param username: username
        @param password: password
        @param domain: domain where the account is valid for
        @param lmhash: LM hash for NTLM authentication
        @param nthash: NT hash for NTLM authentication
        @param aesKey: AES key for Kerberos authentication
        @param doKerberos: Use Kerberos authentication
        @param kdcHost: KDC hostname or IP address
        @param smb_connection: existing SMBConnection to reuse (if provided, other auth params are ignored)
        zS-1-5-18zNT AUTHORITY\SYSTEMzBUILTIN\AdministratorszDomain Users)544513N)r#   rD   sid_to_namerid_to_name_owns_connection
connectionr   kerberosLoginloginstart_dce_rpcdce_rpcopen_policy_handlepolicy_handle	transporttidfid)r6   ipremote_nameusernamepassworddomainlmhashnthashaesKey
doKerberoskdcHostsmb_connectionr!   r!   r"   rv      s"   




zSMBFileACL.__init__c                 C   s>   | j rt| j| j  | jr| j  | jr| j  dS dS )zh
        Disconnect from the tree id, close the file
        and disconnect from the smb server
        N)	r   r   
hLsarCloser   r   
disconnectr   r   closerH   r!   r!   r"   close_connection  s   
zSMBFileACL.close_connectionc                 C   s4   | j r| j| j| j  | jr| j| j dS dS )z7
        Close the tree ID and file ID handles
        N)r   r   	closeFiler   disconnectTreerH   r!   r!   r"   
close_file'  s
   zSMBFileACL.close_filec                 C   s2   | j || _| j j| j||td| _| j| jfS )z
        Open the given file in the specified share
        @param share_name: share to connect to
        @param file_name: file to open
        @return: tuple of (tid, fid)
        )desiredAccesscreationOption)r   connectTreer   openFiler   r   )r6   
share_name	file_namedesired_accessr!   r!   r"   	open_file0  s
   
zSMBFileACL.open_filec                 C   s0   t | j | jdd| _| j  | j }|S )z]
        Start a new DCE/RPC connection over SMB
        @return: DCE/RPC connection
        lsarpc)r   filename)r   r   getRemoteNamer   connectget_dce_rpc)r6   dcer!   r!   r"   r   =  s   

zSMBFileACL.start_dce_rpcc                 C   s&   | j tj t| j tjd }|S )zU
        Open a new handle to MSRPC_UUID_LSAD
        @return: policy handle
        PolicyHandle)r   bindr   MSRPC_UUID_LSADhLsarOpenPolicy2POLICY_LOOKUP_NAMES)r6   r   r!   r!   r"   r   L  s
   zSMBFileACL.open_policy_handlec                 C   s   dd |d d D }t |D ]2\}}|dv r|| }|dd }|| jv r3| j| | jt|< q|| | jvrA|| j|| < qdS )	z
        Set the sid_to_name dictionary according to the given SIDs
        :param sids: SIDs to translate to their names
        :param resp: the response containing the names
        :return: None
        c                 S   s   g | ]}|d  qS )Namer!   )rw   namer!   r!   r"   ry   _  s    z.SMBFileACL.set_sid_to_name.<locals>.<listcomp>TranslatedNamesNames)None    r*   N)	enumerater:   r   r~   r#   rD   )r6   sidsrespnamesir   ridr!   r!   r"   set_sid_to_nameX  s   
zSMBFileACL.set_sid_to_namec              
   C   sT   zt | j| j|}W n t jy! } z	|j}W Y d}~nd}~ww | || dS )z
        Resolve SIDs to names using LSA_LookupSids
        :param sids: list of SIDs
        :return: list of usernames
        N)r   hLsarLookupSids2r   r   DCERPCSessionErrorpacketr   )r6   r   r   session_errorr!   r!   r"   sids_to_namesj  s   zSMBFileACL.sids_to_namesc              
   C   sh   zt | j| j|g}|d d d d  dd W S  ty3 } ztd| dt| d}~ww )	z=
        Translate name to SID using LSA_LookupNames
        TranslatedSidsSidsr   Sidr   NzFailed to resolve name 'z
' to SID: )r   hLsarLookupNames3r   r   getData	Exceptionr2   )r6   r   r   er!   r!   r"   name_to_sidw  s   "zSMBFileACL.name_to_sidgrantc              	   C   s   d}g }|r=| dD ]}z
|t|  O }W q ty%   || Y qw |r7ddl}|dd|  |s=td| 	|}dt
| }	tddd|	|| }
t|
}||_|S )	z
        Convert given permissions and user to binary format
        @param username: username to add/remove permissions
        @param permissions: permissions in the icacls format
        @param action: 'grant', 'revoke', or 'delete'
        r   ,Nz"Ignoring unsupported permissions: z, zNo valid permissions specifiedr   z<BBHI)r:   SUPPORTED_PERMISSIONSupperKeyErrorappendloggingwarningr0   r   r   r-   r.   r;   rT   action)r6   r   permissionsr   access_requiredinvalid_perms
permissionr   	sid_bytes
total_sizepermissions_as_bytesacer!   r!   r"   permissions_to_ace  s*   
zSMBFileACL.permissions_to_acec              	   C   sj  t |j|d |d  }t |j|d |d  }| ||g z| j| }W n ty3   |}Y nw z| j| }W n tyF   |}Y nw t||}|j|d d }t|}|d }	t|	rt|	}
|	|
d d }	|
d dkrtq]t |
d }|
|j	|< t|	sa| t
|j	  |j	 D ] \}}z| j| }W n ty   |}Y nw d	|||j|< q|S )
z
        Gets the security information of the given FileSecInformation object
        :param sec: FileSecInformation instance
        :return: SecurityAttributes
        OffsetToOwnerOffsetToGroupOffsetToDACLNr   r   r\   r   z{}:{})r#   rawDatar   r~   r   rq   r   r-   rT   rt   r4   keysr>   r5   ru   )r6   secrr   rs   
owner_name
group_namesecurity_attributesntntuserntacefacerx   r   r   r!   r!   r"   get_security_attributes  sB   

z"SMBFileACL.get_security_attributesc                 C   sV   | j ||d z| jjj| j| jdddd}t|}| |}|W |   S |   w )z
        Connect to the given share and get the file permissions
        @param share_name: the share name where the file is to be opened
        @param file_name: file to get permissions from
        @return: SecurityAttributes
        )r   r   r         fileInfoClassinfoTypeadditionalInformation)	r   r   _SMBConnection	queryInfor   r   r   r   r   )r6   r   r   resultr   r   r!   r!   r"   get_permissions  s   
zSMBFileACL.get_permissionsc                 C   s  t | j| d d }|d }d}d}d}|j}t|rd}t|}	t|	d }
|
j|d krd}|dkrT|	d	  |d	 O  < |	d
  |d
 O  < |	d  |d O  < nD|dkr|	d	  |d	  M  < |	d
  |d
  M  < |	d  |d  M  < |	d	 dkr|	d
 dkr|	d dkrd}d}n|dkrd}d}|s||	 7 }||	d d }t|s|r||d< t|d |d< |r|d  d8  < n&|dkr|dkr|d  t| 7  < |d  d7  < | |d  |d< | j| d | d  }| j| d | d  }|  | | |  }|S )a  
        This function will get the current security descriptor, and then
        insert the given permission to it. Supports different actions:
        - grant: Add permissions to existing ACE (OR operation)
        - revoke: Remove specific permissions from existing ACE (AND NOT operation)
        - delete: Remove the entire ACE
        @param sec: current security descriptor
        @param permission: new permission ACE with action attribute
        r   Nr   r   Fr\   Tr   rX   rY   rZ   revoker   deleter   r   r   r   r   r   )r   r   r   r-   rT   r#   r   )r   r   r   r   
new_buffer	sid_foundace_deletedr   
delete_acer   rx   rr   rs   sec_info_blobr!   r!   r"   insert_permission  sb   #
zSMBFileACL.insert_permissionc           
      C   s   |  ||t\| _| _z6| |||}| jjj| j| jdddd}t|}| j	||d}	| jjj
| j| jddd|	d}|W |   S |   w )a  
        Add, remove, or modify permissions for a given user to the given file
        @param share_name: the share name where the file is to be opened
        @param file_name: file to set permissions to
        @param user: user to edit permissions for; can be a SID as well
        @param permissions: permissions in the icacls format (example: R,W,X,D).
        NOTE: not all permission types are supported; currently supporting:
        R - read-only access
        W - write-only access
        D - delete access
        X - execute access
        F - full control
        @param action: action to perform - 'grant' (add), 'revoke' (remove), 'delete' (remove ACE)
        @return: bool. whether the operation succeeded or not
        r   r   r   r   )r   r   r   )r   r   r   	inputBlob)r   r	   r   r   r   r   r   r   r   r   setInfor   )
r6   r   r   userr   r   r   r   r   security_descriptorr!   r!   r"   set_permissions?  s,   	zSMBFileACL.set_permissions)NNrd   rd   rd   rd   rd   NFNN)r   )r   r   r   rz   rv   r   r   r
   r   r   r   r   r   r   r   r   r   rS   r   r  r!   r!   r!   r"   r{      s"    
(	

%0
Lr{   )!impacket.structurer   impacket.dcerpc.v5r   r   impacket.dcerpc.v5.transportr   impacket.smbconnectionr   impacket.smb3structsr   r   r	   r
   r.   re   rf   rg   rh   ri   rl   rk   rm   ro   rp   rn   SEC_READ_RIGHTr   r   r#   rT   rq   r{   r!   r!   r!   r"   <module>   s:   

1[