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mZ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 ddlmZmZmZmZmZmZmZmZmZmZmZ dd	lmZ dd
l m!Z!m"Z"m#Z#m$Z$ ddl%m&Z&m'Z' ddl(m)Z)m*Z*m+Z+ dZ,dZ-dZ.G dd deZ/dddddddddd	Z0G dd dej1Z2G dd deZ3d d! Z4G d"d# d#e5Z6		$d.d%d&Z7d'd( Z8d)d)d)d)ddde,df	d*d+Z9d)d)d)d)ddde,df	d,d-Z:dS )/    N)	namedtypeuniv)decoderencoder)LOG)Enum   )getKerberosTGTsendReceive)_sequence_component_sequence_optional_componentseq_setRealmPrincipalNameAuthenticatorAS_REPAP_REQAP_REPKRB_PRIVEncKrbPrivPart)CCache)PrincipalNameTypeApplicationTagNumbersAddressTypeencodeFlags)Keyget_random_bytes)	PrincipalKerberosTimeTicketi  i  zkadmin/changepwc                   @   s0   e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
S )KPasswdResultCodesr   r                       N)__name__
__module____qualname__SUCCESS	MALFORMED	HARDERROR	AUTHERROR	SOFTERRORACCESSDENIEDBAD_VERSIONINITIAL_FLAG_NEEDEDUNKNOWN r4   r4   /root/aizidognhua/tmp/workspace/projects/ec89d86c-575f-41c9-af57-ac45cbdbf775/venv/lib/python3.10/site-packages/impacket/krb5/kpasswd.pyr    4   s    r    zpassword changed successfullyz!protocol error: malformed requestz%server error (KRB5_KPASSWD_HARDERROR)zLauthentication failed (may also indicate that the target user was not found)z1password change rejected (KRB5_KPASSWD_SOFTERROR)zaccess deniedzprotocol error: bad versionz#protocol error: initial flag neededzunknown error)	r   r   r!   r"   r#   r$   r%   r&   r'   c                   @   s:   e Zd Zeedde edde	 edde
 ZdS )ChangePasswdData	newpasswdr   targnamer   	targrealmr!   N)r(   r)   r*   r   
NamedTypesr   r   OctetStringr   r   r   componentTyper4   r4   r4   r5   r6   M   s    r6   c                   @   s$   e Zd ZdZdZdZdZdZdZdS )PasswordPolicyFlagsr   r!   r#             N)	r(   r)   r*   ComplexNoAnonChangeNoClearChangeLockoutAdminsStoreCleartextRefusePasswordChanger4   r4   r4   r5   r=   Y   s    r=   c                    st   d}d}t | t|ks| dd dkrtt||   d  d  d |  d |  fd	d
tD d}|S )Nz!HIIIQQl    @T$r   r!   s     r   r#   r$   c                    s    g | ]}|j  d  @ r|jqS )r"   )valuename).0flag
propertiesr4   r5   
<listcomp>o   s     z)_decodePasswordPolicy.<locals>.<listcomp>)	minLengthhistorymaxAgeminAgeflags)lenstructcalcsize
ValueErrorunpackr=   )ppolicyStringppolicyStructticksInADaypasswordPolicyr4   rK   r5   _decodePasswordPolicyb   s   "

r\   c                   @   s   e Zd ZdS )KPasswdErrorN)r(   r)   r*   r4   r4   r4   r5   r]   w   s    r]   	   localhostc                 C   s  |	d u rt tdd}	|
d u rtjtjj}
t|ts"|	d}t
 }d|d< ||d< t|d| j |
j|d< t|
|d	< |	|d
< tj|d< |j|d d< |j|d d< t	|}||d|d }tdt| t }d|d< t tjj|d< tt |d< t|d|j tj|d< |j|d d< ||d d< t	|}t  }||d< |r|r|! |d< tj|d< t"j#j|d d< ||d d d< t	|}tdt| t$ }t	||d< |	|d
< tj|d< t%j&j|d d < ||d d!< t	|}||d"|d }td#t| t' }d|d< t tj'j|d< tj|d$< |j|d$ d< ||d$ d< t	|}t(|}t(|}d%| | }t)*d&|t+|}|| | }|S )'Nr#   bigutf-8r$   zauthenticator-vnocrealmcnamecusecctimez
seq-numbersubkeykeytypekeyvalue   zb64(authenticator): {}pvnozmsg-typez
ap-optionsticketauthenticatoretypecipherr7   r9   r8   z	name-typezname-stringr   zb64(changePasswdData): {}	user-dataz	s-addressz	addr-typeaddress   b64(encKrbPrivPart): {}enc-partr%   !HHH),int
from_bytesr   datetimenowtimezoneutc
isinstancebytesencoder   r   components_to_asn1microsecondr   to_asn1r   noValueenctypecontentsr   encryptr   debugformatbase64	b64encoder   r   rG   r   listr6   upperr   NT_PRINCIPALr   r   IPv4r   rS   rT   packKRB5_KPASSWD_PROTOCOL_VERSION)	principaldomain	newPasswdtgsrm   
sessionKeysubKeytargetPrincipaltargetDomainsequenceNumberrw   hostnamerk   encodedAuthenticatorencryptedEncodedAuthenticatorapReqapReqEncodedchangePasswdDataencodedChangePasswdDataencKrbPrivPartencodedEncKrbPrivPartencryptedEncKrbPrivPartkrbPrivkrbPrivEncodedapReqLen
krbPrivLen
messageLenencodedr4   r4   r5   createKPasswdRequest{   sv   












r   c                 C   s  d}t |}z!| d | }t ||\}}}| |||  }| || d  }	W n   tdztj|t dd }
tj|	t dd }W n   td|d d }z	||d|}W n   td	t	
d
t| z#tj|t dd }|d  }t|d d d|dd  }}W n   tdt	
d|| zt| }W n ty   td }Y nw zt|}djdi |}W n% tt jfy   z|d}W n ty   t|d}Y nw Y nw |tjjk}||||fS )Nrs   z(kpasswd: malformed reply from the serverasn1Specr   zBkpasswd: malformed AP_REP or KRB_PRIV in the reply from the serverrr   rm   rp   z=kpasswd: cannot decrypt KRB_PRIV in the reply from the serverrq   rn   r!   r_   zNkpasswd: malformed EncKrbPrivPart in the KRB_PRIV in the reply from the serverzresultCode: {}, message: {}r'   zPassword policy:
	Minimum length: {minLength}
	Password history: {history}
	Flags: {flags}
	Maximum password age: {maxAge} days
	Minimum password age: {minAge} daysr`   zlatin-1r4   )rT   rU   rW   r]   r   decoder   r   decryptr   r   r   r   r   r   asOctetsrt   ru   RESULT_MESSAGESKeyErrorr\   rV   errorUnicodeDecodeErrorbinasciihexlifyr    r+   rG   )r   rm   r   headerStruct	headerLenheaders_apRepLenapRepEncodedr   apRepr   r   r   r   result
resultCodemessageresultCodeMessageppolicysuccessr4   r4   r5   decodeKPasswdReply   sb   
&
r    c                 C   s&   t | |dd||||||||	|
| dS )ad  
    Change the password of the requesting user with RFC 3244 Kerberos Change-Password protocol.

    At least one of oldPasswd, (oldLmhash, oldNthash) or (TGT, aesKey) should be defined.

    :param string clientName:   username of the account changing their password
    :param string domain:       domain of the account changing their password
    :param string newPasswd:    new password for the account
    :param string oldPasswd:    current password of the account
    :param string oldLmhash:    current LM hash of the account
    :param string oldNthash:    current NT hash of the account
    :param string aesKey:       current AES key of the account
    :param string TGT:          TGT of the account. It must be a TGT with a SPN of kadmin/changepw
    :param string kdcHost:      KDC address/hostname, used for Kerberos authentication
    :param string kpasswdHost:  KDC exposing the kpasswd service (TCP/464, UDP/464),
                                used when sending the password change requests
                                (Default: same as kdcHost)
    :param int kpasswdPort:     TCP port where kpasswd is exposed (Default: 464)
    :param string subKey:       Subkey to use to encrypt the password change request
                                (Default: generate a random one)

    :return void:               Raise an KPasswdError exception on error.
    N)setPassword)
clientNamer   r   	oldPasswd	oldLmhash	oldNthashaesKeyTGTkdcHostkpasswdHostkpasswdPortr   r4   r4   r5   changePassword  s
   

r   c               
   C   s  |du r|
}t | tjjd}|	du rTtdrTtd}zt|}W n   Y n+t	d
| t}||d}|durK| }	td
|| n	td
|| |	du rit|||||||
td\}}}}n|	d	 }|	d
 }|	d }tj|t dd }t }||d  |du rt|j}t|j|}t|||||||||	}t||||}t|||\}}}}|rdS |}|r|d| 7 }t|)a  
    Set the password of a target account with RFC 3244 Kerberos Set-Password protocol.
    Requires "Reset password" permission on the target, for the user.

    At least one of oldPasswd, (oldLmhash, oldNthash) or (TGT, aesKey) should be defined.

    :param string clientName:   username of the account performing the reset
    :param string domain:       domain of the account performing the reset
    :param string targetName:   username of the account whose password will be changed
    :param string targetDomain: domain of the account whose password will be changed
    :param string newPasswd:    new password for the target account
    :param string oldPasswd:    current password of the account performing the reset
    :param string oldLmhash:    current LM hash of the account performing the reset
    :param string oldNthash:    current NT hash of the account performing the reset
    :param string aesKey:       current AES key of the account performing the reset
    :param string TGT:          TGT of the account performing the reset
                                It must be a TGT with a SPN of kadmin/changepw
    :param string kdcHost:      KDC address/hostname, used for Kerberos authentication
    :param string kpasswdHost:  KDC exposing the kpasswd service (TCP/464, UDP/464),
                                used when sending the password change requests
                                (Default: same as kdcHost)
    :param int kpasswdPort:     TCP port where kpasswd is exposed (Default: 464)
    :param string subKey:       Subkey to use to encrypt the password change request
                                (Default: generate a random one)

    :return bool:               True if successful, raise an KPasswdError exception on error.
    N)type
KRB5CCNAMEzUsing Kerberos cache: {}FzUsing TGT for {} from cache {}z%No valid TGT for {} found in cache {})
serverNameKDC_REPrm   r   r   r   rj   z: )r   r   r   rG   osgetenvr   loadFiler   r   r   KRB5_KPASSWD_TGT_SPNgetCredentialtoTGTinfor	   r   r   r   r   	from_asn1r   keysizer   r   r   r
   r   r]   ) r   r   
targetNamer   r   r   r   r   r   r   r   r   r   r   userNamer   ccacher   credstgtrm   oldSessionKeyr   rj   subKeyByteskpasswordReqkpasswordRepr   r   r   r   errorMessager4   r4   r5   r   =  sP   

r   )NNNNr^   );r   r   rv   r   rT   pyasn1.typer   r   pyasn1.codec.derr   r   impacketr   impacket.dcerpc.v5.enumr   
kerberosv5r	   r
   asn1r   r   r   r   r   r   r   r   r   r   r   r   r   	constantsr   r   r   r   cryptor   r   typesr   r   r   KRB5_KPASSWD_PORTr   r   r    r   Sequencer6   r=   r\   	Exceptionr]   r   r   r   r   r4   r4   r4   r5   <module>   sV   4	
\
F

"