Пример #1
0
def blacklistLoop():
    sha1input = ""
    md5input = ""
    sha256input = ""
    for root, dirs, files in os.walk(dir_to_whitelist):
        for file in files:
            # print(os.path.join(root, file))
            if file.endswith(".exe") | file.endswith(".dll") | file.endswith(".EXE") | file.endswith(".DLL"):
                filename = os.path.join(root, file)
                # filename = root + "\\" + file
                try:
                    sha1input = hashlib.sha1(open(filename, 'rb').read()).hexdigest()
                    md5input = hashlib.md5(open(filename, 'rb').read()).hexdigest()
                    sha256input = hashlib.sha256(open(filename, 'rb').read()).hexdigest()
                except IOError:
                    print("Unable to open file for hashing")
                    sys.exc_clear()

                sha1base64 = base64.b64encode(sha1input.decode('hex'))
                md5base64 = base64.b64encode(md5input.decode('hex'))
                sha256base64 = base64.b64encode(sha256input.decode('hex'))

                mc = mcafee.client(ePOIP, '8443', ePOUser, ePOUserPwd, 'https', 'json')
                PresentTimeDate = time.strftime("%c")
                PresentHost = socket.gethostname()
                filePath = os.path.normpath(filename)
                repString = '[{"sha256":"' + sha256base64 + '","sha1":"' + sha1base64 + '","md5":"' + md5base64 + '","reputation":"' + reputationBlack + '","name":"' + str(file) + '","comment":"' + PresentTimeDate + " " + "Blacklisted by Script" + " on Host: " + PresentHost + "," + " " + "Located at path: " + str(json.dumps(filePath).replace('\"', '')) + '"}]'
                print('Adding Blacklisted Files to TIE Server: ' + repString)
                mc.tie.setReputations(repString)
Пример #2
0
def main():
    global epo
    epo = mcafee.client(SERVER, '8443', USERNAME, PASSWORD)
    systems = (line.rstrip('\n') for line in open(input_filename))
    for host in systems:
        if not epo.system.find(host):
            print(host + " doesn't exist in ePo")
            file = open(
                output_filename,
                "a")  # open file and append logs. write will clear the file
            file.write(host + "\n")
        else:
            print(host + " is in ePo")
Пример #3
0
def main(argv):
    global epo, verbose
    epo = mcafee.client(SERVER, '8443', USERNAME, PASSWORD)
    filename = ""
    remove_tag = False
    verbose = False
    wake_up_agent = False

    #step 1. Read cli arguments
    try:
        opts, args = getopt.getopt(argv, "hi:rwv", ["filename="])
    except getopt.GetoptError:
        print("mcafee_apply_tag.py -i <input file> [-r, remove tag]")
        sys.exit(2)

    for opt, arg in opts:
        if opt == "-h":
            print("mcafee_apply_tag.py -i <input file>")
            print("This script allows to assign/remove tags")
            print("-i <file>    import file with hostnames")
            print("-r   remove tag instead")
            print("-v   verbose output")
            sys.exit()
        elif opt in ("-i", "--ifile"):
            filename = arg
        elif opt in ("-r", "--remove"):
            remove_tag = True
        elif opt == "-v":
            verbose = True
        elif opt == "-w":
            wake_up_agent = True

    cis = (line.rstrip('\n') for line in open(filename))

    if remove_tag:
        for ci in cis:
            epo.system.clearTag(ci, TAG_NAME)
            print("Tag /" + TAG_NAME + "/ removed from " + ci)
    else:
        for ci in cis:
            epo.system.applyTag(ci, TAG_NAME)
            print("Tag /" + TAG_NAME + "/ assigned to " + ci)

    # wake up agents
    if wake_up_agent:
        for ci in cis:
            epo.system.wakeupAgent(ci, '', '', '', 'True')
        print("Wake-up call sent")
Пример #4
0
def main(epo_host, epo_port, epo_un, epo_pw, set_tag, system_file, verbose):
    try:
        # Create an ePO client object
        mc = mcafee.client(epo_host, epo_port, epo_un, epo_pw)
    except e:
        print(
            "Failed to authenticate to ePO. Please ensure the username and password are correct, and that the "
            "account is a superuser.")
        exit()

    try:
        # Get file for reading operations
        this_file = open(system_file, 'r')
    except e:
        print(
            "Failed to read system file. Perhaps the location or file name is incorrect?"
        )
        exit()

    # Apply the tag for each system in file
    systems_updated = 0
    system_count = 0
    for this_system in this_file:
        epo_system = this_system.rstrip('\n')
        if verbose:
            print("Applying tag: {} to system: {}".format(set_tag, epo_system))

        change_result = mc.system.applyTag(epo_system, set_tag)

        if change_result == 1:
            if verbose:
                print("Applying tag: {} to system: {}".format(
                    set_tag, epo_system))
            systems_updated += 1
        else:
            print("Failed to apply tag: {} to system: {}".format(
                set_tag, epo_system))
            print(
                "Perhaps the system already has the tag or the system was not found in ePO"
            )

        system_count += 1

    print("Successfully added tag: {} to {}/{} systems".format(
        set_tag, systems_updated, system_count))
Пример #5
0
def main():
    total_hosts = 0

    # Step 0. Open Epo connection and grab query
    epo = mcafee.client(SERVER, '8443', USERNAME, PASSWORD)
    query = epo.core.executeQuery(
        '439'
    )  # get query  "DAT file distribution". epo.core.listQueries will show all

    # Step 1. Get query and output to CSV
    csvfile = open(CSVFILENAME, "w")
    for q in query:
        #   print(q[u'EPOProdPropsView_VIRUSCAN.datver'], q[u'count'])
        csvfile.write(
            json.dumps(q[u'EPOProdPropsView_VIRUSCAN.datver']) + ";" +
            json.dumps(q[u'count']) + "\n")
    csvfile.close()

    # Step 2. Process logs. Build final report
    for q in query:
        total_hosts += int(json.dumps(q[u'count']))

    last_6_days_DAT_hosts = int(json.dumps(query[0][u'count']))+int(json.dumps(query[1][u'count']))+ \
                                                    int(json.dumps(query[2][u'count']))+int(json.dumps(query[3][u'count']))+ \
                                                    int(json.dumps(query[4][u'count']))+int(json.dumps(query[5][u'count']))

    current_compliance_level = (last_6_days_DAT_hosts * 100 / total_hosts
                                )  #int is always bigger then 1
    DAT_0_share = int(json.dumps(query[0][u'count'])) * 100 / total_hosts
    DAT_1_share = int(json.dumps(query[1][u'count'])) * 100 / total_hosts
    DAT_2_share = int(json.dumps(query[2][u'count'])) * 100 / total_hosts
    DAT_3_share = int(json.dumps(query[3][u'count'])) * 100 / total_hosts
    DAT_4_share = int(json.dumps(query[4][u'count'])) * 100 / total_hosts
    DAT_5_share = int(json.dumps(query[5][u'count'])) * 100 / total_hosts
    old_DAT_share = 100 - current_compliance_level

    reportfile = open(REPORTFILENAME, "a")
    reportfile.write(datetime.datetime.now().strftime("%Y-%m-%d") + ";" + str(current_compliance_level) + ";" + \
                     str(total_hosts) + ";" + str(last_6_days_DAT_hosts) + ";" + str(DAT_0_share) + ";" + \
                     str(DAT_1_share) + ";" + str(DAT_2_share) + ";" + str(DAT_3_share) + ";" + str(DAT_4_share) + ";" + \
                     str(DAT_5_share) + ";" + str(old_DAT_share) + "\n" )
    reportfile.close()
Пример #6
0
def main(argv):
    global epo, verbose
    epo = mcafee.client(SERVER, '8443', USERNAME, PASSWORD)

    try:
        opts, args = getopt.getopt(argv, "hi:", ["filename="])
    except getopt.GetoptError:
        print("delstock.py -i <input file>")
        sys.exit(2)

    for opt, arg in opts:
        if opt == "-h":
            print("delstock.py -i <input file>")
            print("This script will remove unneeded machines from ePo")
            print("-i <file>    import file with hostnames")
            sys.exit()
        elif opt in ("-i", "--ifile"):
            filename = arg
    stock = (line.rstrip('\n') for line in open(filename))
    for host in stock:
        if epo.system.find(host):
            epo.system.delete(host)
            print(host + ' is deleted')
Пример #7
0
def main():
    # Main Function
    args = request_args()
    if args.epo_password is None:
        args.epo_password = get_ePO_password(args.epo_user)

    # Connect to ePO
    mc = mcafee.client(args.epo, args.epo_port, args.epo_user,
                       args.epo_password)

    # Grab ePO managed Instance Ids and System Names
    endpoint_instances = epoInstances(mc)

    # Create list of only the AWS Instance Ids for Systems in ePO Database
    endpoint_instanceids = epoInstanceIds(mc, endpoint_instances)

    # Create a list of all instance ids in all  AWS regions
    aws_instances = awsInstanceIds(args.access_key, args.secret_key)

    # Create a list of AWS Instance Ids that remain in the ePO Database but no longer exist in AWS
    uniques = ePOnotinAWS(endpoint_instanceids, aws_instances)

    # Delete all systems that remain in ePO Database but no longer exist in AWS
    deleteEPOUniqueInstances(mc, endpoint_instances, uniques)
# This script executes a custom query against ePO to return a list of systems with Custom Prop 1 equal to 'CN=*', and no desired tag
# It then tags the system, and issues an agent wakeup call.

import mcafee

# ePO IP
ePOIP = ''
# Login username
ePOUser = ''
# Login user's password
ePOUserPwd = ''
# Tag Name
ePOTag = 'Server'

mc = mcafee.client(ePOIP, '8443', ePOUser, ePOUserPwd, 'https', 'json')
ePOTagSet = mc.system.findTag(ePOTag)
if ePOTagSet:
    for ePOTagInfo in ePOTagSet:
        systems = mc.core.executeQuery(
            target='EPOLeafNode',
            select=
            '(select EPOComputerProperties.ComputerName EPOComputerProperties.ParentID EPOComputerProperties.UserProperty1)',
            where=
            '(and(startsWith EPOComputerProperties.UserProperty1 "CN=") (doesNotHaveTag EPOLeafNode.AppliedTags '
            + str(ePOTagInfo['tagId']) + '))')
        if systems:
            for system in systems:
                mc.eeadmin.assignUser(
                    systemNode='True',
                    nodeId=str(system['EPOComputerProperties.ParentID']),
                    dn=system['EPOComputerProperties.UserProperty1'])
from dxlclient.client import DxlClient
from dxlmarclient import MarClient

# Import common logging and configuration
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/..")
from common import *

# Configure local logger
logging.getLogger().setLevel(logging.ERROR)
logger = logging.getLogger(__name__)

# Create DXL configuration from file
config = DxlClientConfig.create_dxl_config_from_file(CONFIG_FILE)

# Connect to ePO with WebAPI
mc = mcafee.client('{epoip}','8443','{account}','{pwd}','https','json')
#ePOTag = 'Suspect'

class MyFirstInstanceCallback(FirstInstanceCallback):
    """
    My first instance callback
    """
    def on_first_instance(self, first_instance_dict, original_event):
        # Display the DXL topic that the event was received on
        print "First instance on topic: " + original_event.destination_topic

        # Dump the dictionary
        print json.dumps(first_instance_dict,
                         sort_keys=True, indent=4, separators=(',', ': '))
        agentGuid = json.dumps(first_instance_dict['agentGuid'])[1:-1]
        fileName = json.dumps(first_instance_dict['name'])[1:-1]
Пример #10
0
def main():
    '''
    The main functiona allows different operations:
        1.- Manually import of hash
        2.- Import a list of hashes via csv file
        3.- Automatic calculation of the hash of a file and further submission
        4.- Automatic calculation of the hashed of a folder and further submission
    '''
    option = parseargs()
    ipaddress = option.ipaddress
    port = option.port
    username = option.username
    password = option.password

    path_to_file = option.import_file
    path_to_object = option.object_path

    mc = mcafee.client(ipaddress, port, username, password, 'https','json')

    if path_to_file:
        try:
            with open(path_to_file, 'rb') as csvfile:
                lines = csv.reader(csvfile)
                for line in lines:
                    try:
                        sha1 = line[0]
                        md5 = line[1]
                        reputation = line[2]
                        file_comment = line[3]
                        file_name = line[4]

                    except Exception as er:
                        print "Error - Format file error"
                        break

                    send_reputation(mc, sha1, md5, reputation, file_comment, file_name)

        except Exception as er:
            print 'Error opening file: %s' % er

    elif path_to_object:
        if isfile(path_to_object):
            sha1, md5 = get_hash(path_to_object)
            file_name = path_to_object.split(os.sep)[-1]
            file_comment = option.file_comment
            reputation = option.value

            send_reputation(mc, sha1, md5, reputation, file_comment, file_name)

        else:
            list_of_files = get_files(path_to_object)

            for unique_file in list_of_files:
                sha1, md5 = get_hash(unique_file)
                file_name = unique_file.split(os.sep)[-1]
                file_comment = option.file_comment
                reputation = option.value

                send_reputation(mc, sha1, md5, reputation, file_comment, file_name)

    else:
        sha1 = option.sha1_string
        md5 = option.md5_string
        reputation = option.value
        file_name = option.file_name
        file_comment = option.file_comment

        send_reputation(mc, sha1, md5, reputation, file_comment, file_name)
a browser, encode the URL.
Parameters:
 fileReps (param 1) - JSON string of file reputations. At least one hash need to
be present. Optional parameters: "name" and "comment". Ex: 

[{"sha1":"frATnSF1c5s8yw0REAZ4IL5qvSk=","md5":"8se7isyX+S6Yei1Ah9AhsQ==","sha256":"39Gv4ExOzWr5SMNMrObQJ3A3SSSzEoz2MFi4X8YNAVQ=","reputation":"99"},{"sha1":"d3HtjhR0Eb3qN6c+vVxeqVVe0t4=","md5":"V+0uApv5yjk4PSpnHvT7UA==","reputation":"85"}]
 certReps (param 2) - JSON string of certificate reputations. Both sha1 and
publicKeySha1 are required. Optional parameter: "comment". Ex: 

[{"sha1":"frATnSF1c5s8yw0REAZ4IL5qvSk=","publicKeySha1":"frATnSF1c5s8yw0REAZ4IL5qvSk=","reputation":"99"}]
'''

import base64
import csv
import json
import mcafee

mc = mcafee.client('your IP here', '8443', 'your ePO username', 'your ePO user passwd')

# Read the file and set the reputations
with open('reputations.csv') as f:
    fileReputations = csv.reader(f)
    for rowofdata in fileReputations:
        name = rowofdata[0].lower()
        hashType = rowofdata[1].lower()
        fileHash = rowofdata[2].upper()
        reputation = rowofdata[3]
        comment = rowofdata[4]
        Info = json.dumps([{hashType:base64.b64encode(fileHash.decode("hex")),'reputation':reputation,'name':name,'comment':comment}])
        print mc.tie.setReputations(Info)
    ePOIP = raw_input('Please enter IP of McAfee ePO Server: ')

# Prompt for ePO username
ePOUser = ''
while ePOUser == '':
    ePOUser = raw_input('Username: '******'s password
ePOUserPwd = ''
while ePOUserPwd == '':
    ePOUserPwd = getpass.getpass('Password: '******'config.yaml') as f:
    data = yaml.load(f, Loader=yaml.FullLoader)

mc = mcafee.client(ePOIP, '8443', ePOUser, ePOUserPwd)
currentPath = os.getcwd()

# Create extensions, policies, and tasks by Group and Order, and Check-in any Packages
extensions = []
packages = []
policies = []
tasks = []
for key, value in data.items():
    for key2, value2 in value.items():
        for item in value2:
            if item['Type'] == 'Extension':
                extensions.append(item)
            elif item['Type'] == 'Package':
                packages.append(item)
            elif item['Type'] == 'Policy':