async def from_smbconnection(connection:SMBConnection, auth_level = None, open:bool = True, perform_dummy:bool = False): """ Creates the connection to the service using an established SMBConnection. This connection will use the given SMBConnection as transport layer. """ try: if auth_level is None: #for SMB connection no extra auth needed auth_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY epm = EPM.from_smbconnection(connection) _, err = await epm.connect() if err is not None: raise err constring, err = await epm.map(Even6RPC().service_uuid) if err is not None: raise err target = DCERPCTarget.from_connection_string(constring, smb_connection = connection) dcerpc_auth = DCERPCAuth.from_smb_gssapi(connection.gssapi) rpc_connection = DCERPC5Connection(dcerpc_auth, target) service, err = await Even6RPC.from_rpcconnection(rpc_connection, auth_level=auth_level, open=open, perform_dummy = perform_dummy) if err is not None: raise err return service, None except Exception as e: return None, e finally: if epm is not None: await epm.disconnect()
async def amain(): try: from aiosmb.commons.connection.credential import SMBCredential, SMBAuthProtocol, SMBCredentialsSecretType from aiosmb.commons.connection.authbuilder import AuthenticatorBuilder from aiosmb.dcerpc.v5.common.connection.authentication import DCERPCAuth ip = '10.10.10.2' target, err = await EPM.create_target(ip, TSCHRPC().service_uuid) if err is not None: raise err cred = SMBCredential(username='******', domain='TEST', secret='Passw0rd!1', secret_type=SMBCredentialsSecretType.PASSWORD, authentication_type=SMBAuthProtocol.NTLM, settings=None, target=None) gssapi = AuthenticatorBuilder.to_spnego_cred(cred) auth = DCERPCAuth.from_smb_gssapi(gssapi) connection = DCERPC5Connection(auth, target) service, err = await TSCHRPC.from_rpcconnection(connection, perform_dummy=True) if err is not None: raise err async for task, err in service.list_tasks(): if err is not None: raise err print(task) except Exception as e: traceback.print_exc()
def from_smbconnection(smb_connection, port: int = 135, protocol: str = 'ncacn_ip_tcp', data_representation=None): """ Sets up the EPM connection from an existing SMB connection """ dcerpc_target_str = r'%s:%s[%s]' % ( protocol, smb_connection.target.get_hostname_or_ip(), port) target = DCERPCTarget.from_connection_string( dcerpc_target_str, proxy=smb_connection.target.proxy) auth = DCERPCAuth.from_smb_gssapi(smb_connection.gssapi) connection = DCERPC5Connection(auth, target) connection.set_auth_type(RPC_C_AUTHN_LEVEL_NONE) return EPM(connection, data_representation)
def get_dce_rpc(self): dcerpc_target = DCERPCSMBTarget( None, self.smb_connection.target.get_hostname_or_ip(), pipe=self.filename, smb_connection=self.smb_connection, timeout=self.smb_connection.target.timeout) #print(str(dcerpc_target)) dcerpc_auth = DCERPCAuth.from_smb_gssapi(self.smb_connection.gssapi) #print(str(dcerpc_auth)) conn = DCERPC5Connection(dcerpc_auth, dcerpc_target) if dcerpc_auth.ntlm is not None: conn.set_auth_type(RPC_C_AUTHN_WINNT) if dcerpc_auth.kerberos is not None: conn.set_auth_type(RPC_C_AUTHN_GSS_NEGOTIATE) #auth level must be set elsewhere, this function cannot fuigure out your needs! return conn
def get_connection_from_stringbinding(self, s): target = DCERPCTarget.from_connection_string( s, smb_connection=self.smb_connection) #target.proxy = self.smb_connection.target.proxy auth = DCERPCAuth.from_smb_gssapi(self.smb_connection.gssapi) return DCERPC5Connection(auth, target)
async def amain(url, service, template, altname, onbehalf, cn = None, pfx_file = None, pfx_password = None, enroll_cert = None, enroll_password = None): try: if pfx_file is None: pfx_file = 'cert_%s.pfx' % os.urandom(4).hex() if pfx_password is None: pfx_password = '******' print('[+] Parsing connection parameters...') su = SMBConnectionURL(url) ip = su.get_target().get_hostname_or_ip() if cn is None: cn = '%s@%s' % (su.username, su.domain) print('[*] Using CN: %s' % cn) print('[+] Generating RSA privat key...') key = rsa.generate_private_key(0x10001, 2048) print('[+] Building certificate request...') attributes = { "CertificateTemplate": template, } csr = x509.CertificateSigningRequestBuilder() csr = csr.subject_name( x509.Name( [ x509.NameAttribute(NameOID.COMMON_NAME, cn), ] ) ) if altname: altname = core.UTF8String(altname).dump() csr = csr.add_extension( x509.SubjectAlternativeName( [ x509.OtherName(PRINCIPAL_NAME, altname), ] ), critical=False, ) csr = csr.sign(key, hashes.SHA256()) if onbehalf is not None: agent_key = None agent_cert = None with open(enroll_cert, 'rb') as f: agent_key, agent_cert, _ = pkcs12.load_key_and_certificates(f.read(), enroll_password) pkcs7builder = pkcs7.PKCS7SignatureBuilder().set_data(csr).add_signer(agent_key, agent_cert, hashes.SHA1()) csr = pkcs7builder.sign(Encoding.DER, options=[pkcs7.PKCS7Options.Binary]) else: csr = csr.public_bytes(Encoding.DER) print('[+] Connecting to EPM...') target, err = await EPM.create_target(ip, ICPRRPC().service_uuid, dc_ip = su.get_target().dc_ip, domain = su.get_target().domain) if err is not None: raise err print('[+] Connecting to ICRPR service...') gssapi = AuthenticatorBuilder.to_spnego_cred(su.get_credential(), target) auth = DCERPCAuth.from_smb_gssapi(gssapi) connection = DCERPC5Connection(auth, target) rpc, err = await ICPRRPC.from_rpcconnection(connection, perform_dummy=True) if err is not None: raise err logger.debug('DCE Connected!') print('[+] Requesting certificate from the service...') res, err = await rpc.request_certificate(service, csr, attributes) if err is not None: print('[-] Request failed!') raise err if res['encodedcert'] in [None, b'']: raise Exception('No certificate was returned from server!. Full message: %s' % res) print('[+] Got certificate!') cert = x509.load_der_x509_certificate(res['encodedcert']) print("[*] Cert subject: {}".format(cert.subject.rfc4514_string())) print("[*] Cert issuer: {}".format(cert.issuer.rfc4514_string())) print("[*] Cert Serial: {:X}".format(cert.serial_number)) try: ext = cert.extensions.get_extension_for_oid(ExtensionOID.EXTENDED_KEY_USAGE) for oid in ext.value: print("[*] Cert Extended Key Usage: {}".format(EKUS_NAMES.get(oid.dotted_string, oid.dotted_string))) except: print('[-] Could not verify extended key usage') try: ext = cert.extensions.get_extension_for_oid(ExtensionOID.SUBJECT_ALTERNATIVE_NAME) for name in ext.value.get_values_for_type(x509.OtherName): if name.type_id == x509.ObjectIdentifier("1.3.6.1.4.1.311.20.2.3"): print('[*] Certificate ALT NAME: %s' % core.UTF8String.load(name.value).native) break else: print('[-] Certificate doesnt have ALT NAME') except: print('[-] Certificate doesnt have ALT NAME') print('[+] Writing certificate to disk (file:"%s" pass: "******")...' % (pfx_file, pfx_password)) # Still waiting for the day oscrypto will have a pfx serializer :( # Until that we'd need to use cryptography with open(pfx_file, 'wb') as f: data = pkcs12.serialize_key_and_certificates( name=b"", key=key, cert=cert, cas=None, encryption_algorithm=BestAvailableEncryption(pfx_password.encode()) ) f.write(data) print('[+] Finished!') return True, None except Exception as e: traceback.print_exc() return False, e
async def amain(): try: targets = [] ip = '10.10.10.2' epm = EPM.from_address(ip) _, err = await epm.connect() if err is not None: raise err x, err = await epm.lookup() if err is not None: raise err await epm.disconnect() print(len(x)) #print(x) for entry in x: version = '%s.%s' % (entry['tower']['Floors'][0]['MajorVersion'], entry['tower']['Floors'][0]['MinorVersion']) uuidstr = bin_to_string( entry['tower']['Floors'][0]['InterfaceUUID']) service_uuid = uuidtup_to_bin((uuidstr, version)) #print(entry['tower']['Floors'][0]['InterfaceUUID']) #print(version) #print(service_uuid) target, err = await EPM.create_target(ip, service_uuid) print(err) if err is not None: if str(err).find('ept_s_not_registered') != -1: continue raise err targets.append((uuidstr, service_uuid, target)) for uuidstr, service_uuid, target in targets: #print('UUID: %s' % uuidstr) #print('Target: %s' % target) cred = SMBCredential(username='******', domain='TEST', secret='Passw0rd!1', secret_type=SMBCredentialsSecretType.PASSWORD, authentication_type=SMBAuthProtocol.NTLM, settings=None, target=None) gssapi = AuthenticatorBuilder.to_spnego_cred(cred) auth = DCERPCAuth.from_smb_gssapi(gssapi) connection = DCERPC5Connection(auth, target) connection.set_auth_level(RPC_C_AUTHN_LEVEL_CONNECT) try: _, err = await connection.connect() if err is not None: raise err _, err = await connection.bind(service_uuid) if err is not None: raise err req = DummyOp() _, err = await connection.request(req) if str(err).find('rpc_s_access_denied') == -1: proto = 'UNK' if uuidstr in KNOWN_PROTOCOLS: proto = KNOWN_PROTOCOLS[uuidstr] print('UUID : %s' % uuidstr) print('proto: %s' % proto) print('err : %s' % err) print() except Exception as e: traceback.print_exc() finally: await connection.disconnect() except Exception as e: traceback.print_exc()