Exemple #1
0
async def filereader_test(connection_string, filename, proxy=None):
    #target = SMBTarget.from_connection_string(connection_string)
    #if proxy is not None:
    #	target.proxy = SMBTargetProxy.from_connection_string(proxy)
    #	print(str(target))
    #
    #credential = SMBCredential.from_connection_string(connection_string)
    cu = SMBConnectionURL(connection_string)
    credential = cu.get_credential()
    target = cu.get_target()

    print(credential)
    print(target)
    input()

    spneg = AuthenticatorBuilder.to_spnego_cred(credential, target)

    async with SMBConnection(spneg, target) as connection:
        await connection.login()

        async with SMBFileReader(connection) as reader:
            await reader.open(filename)
            data = await reader.read()
            print(data)
            """
Exemple #2
0
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()
Exemple #3
0
async def domain_test(connection_string, domain_name, out_file = None, json_out = False):
	target = SMBTarget.from_connection_string(connection_string)
	credential = SMBCredential.from_connection_string(connection_string)
	spneg = AuthenticatorBuilder.to_spnego_cred(credential, target)
	
	async with SMBConnection(spneg, target) as connection: 
		await connection.login()
		
		async with SMBDomain(domain_name, connection=connection) as domain:
			logging.debug('Connecting to SAMR')
			try:
				await domain.open(access_level = samr.DOMAIN_ALL_ACCESS)
			except Exception as e:
				logging.exception('Failed to create domain object')
				
			info = await domain.get_info()
			
			async for user_name, user_sid in domain.list_users():
				print(user_name, user_sid)
				try:
					user_handle = await domain.open_user(user_sid, access_level = samr.USER_ALL_ACCESS)
					#x = await domain.get_security_info(user_handle)
					user_info = await domain.get_user_info(user_handle)
					
					#async for group_sid in domain.get_user_group_memberships(user_handle):
					#	print(group_sid)
				except Exception as e:
					print(e)
					continue
					
			#async for name, sid in domain.list_groups():
			#	print(name, sid)

	print('Done!')
Exemple #4
0
    def get_smb_connection(self, cmd):
        try:
            hostname, ip = self.get_target_address(cmd.target)
            res, domain, username, password = self.get_stored_cred(cmd.creds)
            if res is False:
                raise Exception('Could not find user creds!')

            target = SMBTarget(ip=ip,
                               hostname=hostname,
                               timeout=1,
                               dc_ip=domain,
                               protocol=SMBConnectionProtocol.TCP)
            target.preferred_dialects = SMB2_NEGOTIATE_DIALTECTS_2

            auth_type = SMBAuthProtocol.NTLM
            secret_type = SMBCredentialsSecretType.PASSWORD

            credential = SMBCredential(username=username,
                                       domain=domain,
                                       secret=password,
                                       secret_type=secret_type,
                                       authentication_type=auth_type,
                                       settings=None,
                                       target=target)
            print(target)
            print(credential)

            gssapi = AuthenticatorBuilder.to_spnego_cred(credential, target)
            connection = SMBConnection(gssapi, target)

            return connection, None
        except Exception as e:
            traceback.print_exc()
            return None, e
Exemple #5
0
    def create_connection_newtarget(self, ip):
        credential = self.get_credential()
        credential.target = ip

        target = self.get_target()
        target.ip = ip

        spneg = AuthenticatorBuilder.to_spnego_cred(credential, target)

        return SMBConnection(spneg, target)
Exemple #6
0
    def create_connection_newtarget(self, ip_or_hostname):
        credential = self.get_credential()
        credential.target = ip_or_hostname

        target = self.get_target()
        try:
            ipaddress.ip_address(ip_or_hostname)
            target.ip = ip_or_hostname
            target.hostname = None
        except:
            target.hostname = ip_or_hostname
            target.ip = ip_or_hostname

        spneg = AuthenticatorBuilder.to_spnego_cred(credential, target)

        return SMBConnection(spneg, target)
Exemple #7
0
    def get_connection(self):
        credential = self.get_credential()
        target = self.get_target()
        spneg = AuthenticatorBuilder.to_spnego_cred(credential, target)

        return SMBConnection(spneg, target)
Exemple #8
0
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
Exemple #9
0
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()