'''
enumLambda - Lambda Function Enumeration Script
(c) Blueinfy solutions pvt. ltd.
This is beta version of the toolkit and it is in the development
phase.
==============================================================
'''

import argparse, json, os
import boto3

parser = argparse.ArgumentParser()


def getFunctions():
	all_functions = raw_functions["Functions"]
	list_of_functions = []
	for i in all_functions:
		list_of_functions.append(i["FunctionName"])
	return list_of_functions

print('\n==============================================================')
print('enumLambda - Lambda Function Enumeration Script (beta)')
print('(c) Blueinfy solutions pvt. ltd.')
print('==============================================================\n')

parser.add_argument('-f', action='store', dest='function_name',
                    help='use function name for enumeration')
parser.add_argument('-e', action='store_true', default=False,
                    dest='enum_all',
                    help='list all functions')
results = parser.parse_args()

if(results.function_name==None and results.enum_all==False):
	print(parser.parse_args(['-h']))

try:
	client = boto3.client('lambda')
	iam = boto3.client('iam')

	raw_functions = client.list_functions()

except Exception as error:
		print('    (-)Error:',error)


if(results.enum_all==True):
	function_names = getFunctions()
	print("(+) Lambda functions ...")
	for j in function_names:
		print("   (-)"+j)
	print("\n")

if(results.function_name!=None):
	
	target_function = results.function_name
	print("(+) Fetching Lambda function "+target_function+"...")
	try:
		myfunc = client.get_function(FunctionName=target_function)

		#print(myfunc)
		temp = myfunc["Configuration"]
		print ("       (+) Platform: "+temp["Runtime"])
		print ("       (+) Permission: "+temp["Role"])

		rolelist = temp["Role"].split('/')
		length = len(rolelist)
		print("       (+) Permission Policy: "+temp["Role"].split('/')[length-1])
		policy = iam.list_attached_role_policies(RoleName=temp["Role"].split('/')[length-1])
		attachedpolicy = policy["AttachedPolicies"]
		for i in attachedpolicy:
			
			rolepolicy = iam.get_policy(PolicyArn=i["PolicyArn"])
			getpolicyversion = iam.get_policy_version(PolicyArn=i["PolicyArn"], VersionId=rolepolicy['Policy']['DefaultVersionId'])
			print("		==> "+json.dumps(getpolicyversion['PolicyVersion']['Document']['Statement']))

		temp_trace = temp["TracingConfig"]
		print ("       (+) xRay-Tracing: "+temp_trace["Mode"])
		temp_code = myfunc["Code"]
		print ("       (+) Code-Location: "+temp_code["Location"]+"\n")
		
		
		print("---Function Mapping---")
		myfunc = client.list_event_source_mappings(FunctionName=target_function)

		temp = myfunc["EventSourceMappings"]
		print(temp)

		print("---Function Policy---")
		myfunc = client.get_policy(FunctionName=target_function)
		#print(myfunc)
		temp = myfunc["Policy"]
		parsed_temp=json.loads(temp)
		list_states = parsed_temp["Statement"]
		for i in list_states:
			print("   (+)Point of Service: "+i["Principal"]["Service"])
			print("        (-)Entry Point: "+i["Condition"]["ArnLike"]["AWS:SourceArn"])

	except Exception as error:
		print('    (-)Error:',error)


		

