def main():
    # builds the args structure, populating with default server and token and creating many flags
    # we will only use the -p flag here
    args = build_cli_parser()
    if not args.parse_string:
        print "Missing the url containting the Server, Feed ID and Report ID to parse."
        sys.exit(-1)

    su = args.parse_string.strip()
    su_list = su.split('/', )
    if len(su_list) != 6:
        print "Length of list from parsed url is not 6."
        print "Printing parsed url and list and exiting script."
        print args.parse_string
        print su_list
        sys.exit(-1)
    feed_host = su_list[2]
    feed_id = su_list[-2]
    report_id = su_list[-1]

    if not feed_host in cb_servers:
        print "%s not in list of cb_servers.  Exiting" % (feed_host)
        sys.exit(1)
    args.url = 'https://%s' % (feed_host)
    args.token = cb_servers[feed_host]

    cb = cbapi.CbApi(args.url, token=args.token, ssl_verify=args.ssl_verify)

    # retrieve threat report original threat report so we can get the name of the threat feed
    # the threat feed name will be used to locate the threat feed id on the servers
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        report = cb.feed_report_info(feed_id, report_id)

    feed_name = report['feed_name']

    updated_report = {'ids': {}, 'updates': {}}

    if report['is_ignored'] == True:
        updated_report['updates']['is_ignored'] = False
    elif report['is_ignored'] == False:
        updated_report['updates']['is_ignored'] = True

    for server in cb_servers.keys():
        args.url = 'https://%s' % (server)
        args.token = cb_servers[server]
        cb = cbapi.CbApi(args.url,
                         token=args.token,
                         ssl_verify=args.ssl_verify)
        feed_id = cb.feed_get_id_by_name(feed_name)
        updated_report['ids'] = {}
        updated_report['ids'][feed_id] = [report_id]
        url = "%s/api/v1/threat_report" % (args.url)
        r = cb.cbapi_post(url, data=json.dumps(updated_report))
        if r.status_code == 200:
            print "%s (report_id: %s) is_enabled was successfully set to %s on %s" % (
                report['title'], report['id'],
                updated_report['updates']['is_ignored'], server)
        else:
            r.raise_for_status()
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.server_url or not opts.token or not opts.group_id:
        print "Missing required param; run with --help for usage"
        sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.server_url,
                     token=opts.token,
                     ssl_verify=opts.ssl_verify)

    #check if the given group_id truly corresponds to one of the existing sensor groups
    does_exist = False
    for group in cb.group_enum():
        if int(opts.group_id) == int(group['id']):
            does_exist = True

    if does_exist:
        config = cb.group_datasharing_del_all(opts.group_id)

        for key in config.keys():
            print "%-20s : %s" % (key, config[key])
    else:
        sys.exit(-1)
示例#3
0
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.server_url or not opts.token:
        print "Missing required param; run with --help for usage"
        sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.server_url,
                     token=opts.token,
                     ssl_verify=opts.ssl_verify)

    # enumerate configured feeds
    #
    feeds = cb.feed_enum()

    # output a banner
    #
    print "%-3s  %-25s   %-8s   %s" % ("Id", "Name", "Enabled", "Url")
    print "%s+%s+%s+%s" % ("-" * 3, "-" * 27, "-" * 10, "-" * 31)

    # output a row about each feed
    #
    for feed in feeds:
        print "%-3s| %-25s | %-8s | %s" % (feed['id'], feed['name'],
                                           feed['enabled'], feed['feed_url'])
示例#4
0
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.url or not opts.token:
        print "Missing required param; run with --help for usage"
        sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.url, token=opts.token, ssl_verify=opts.ssl_verify)

    # if a period is specified, handle that specially
    #
    if 0 != opts.interval:
        return query_forever(cb, opts.interval, opts.udp)

    # grab the global list of sensors
    # this includes backlog data for each sensor
    #
    sensors = cb.sensors()

    # output
    #
    print "%-30s | %-5s | %-50s | %-10s | %10s" % ("Hostname", "Id", "SID",
                                                   "Events", "Binaries")
    for sensor in sensors:
        print "%-30s | %-5s | %-50s | %-10s | %10s" % (
            sensor['computer_name'], sensor['id'],
            sensor['computer_sid'].strip(), sensor['num_storefiles_bytes'],
            sensor['num_eventlog_bytes'])
示例#5
0
def parent_search(opts, pdoc):

    opts.query = "hostname: %s process_name: %s process_pid: %d" % (
        pdoc['hostname'], pdoc['parent_name'], pdoc['parent_pid'])

    # build a cbapi object
    cb = cbapi.CbApi(opts.url, token=opts.token, ssl_verify=opts.ssl_verify)

    # use the cbapi object to iterate over all matching process documents
    try:
        r = cb.process_search(opts.query)
        identifier = r['results'][0]['id']
        seg_id = r['results'][0]['segment_id']
    except:
        return False

    try:
        events = cb.process_events(identifier, seg_id)
        for cpe in events['process']['childproc_complete']:
            cpe_split = cpe.split('|', )
            if int(cpe_split[4]
                   ) == pdoc['process_pid'] and cpe_split[5] == 'false':
                process_end_time = datetime.datetime.strptime(
                    cpe_split[0], "%Y-%m-%d %H:%M:%S.%f")
                return process_end_time
    except:
        return False
    return False
示例#6
0
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.server_url or not opts.token or (not opts.feedname
                                                 and not opts.feedid):
        print "Missing required param; run with --help for usage"
        print "One of -f or -i must be specified"
        sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.server_url,
                     token=opts.token,
                     ssl_verify=opts.ssl_verify)

    if not opts.feedid:
        id = cb.feed_get_id_by_name(opts.feedname)
        if id is None:
            print "-> No configured feed with name '%s' found!" % (
                opts.feedname)
            return
    else:
        id = opts.feedid

    # delete the feed
    #
    cb.feed_del(id)

    print "-> Feed deleted [id=%s]" % (id, )
示例#7
0
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.url or not opts.token or not opts.name or not opts.type or not opts.query:
        print "Missing required param; run with --help for usage"
        sys.exit(-1)

    # baseline argument validation
    #
    if opts.type != "events" and opts.type != "modules":
        print "Watchlist type must be one of 'events' or 'modules'"
        sys.exit(-1)
    if not opts.query.startswith("q="):
        print "Query must begin with q="
        print opts.query
        sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.url, token=opts.token, ssl_verify=opts.ssl_verify)

    # add a watchlist
    # for the purposes of this test script, hardcode the watchlist type, name, and query string
    #
    print "-> Adding watchlist..."
    watchlist = cb.watchlist_add(opts.type, opts.name, opts.query, id=opts.id, readonly=opts.readonly)
    print "-> Watchlist added [id=%s]" % (watchlist['id'])

    # get record describing this watchlist  
    #
    print "-> Querying for watchlist information..."
    watchlist = cb.watchlist(watchlist['id'])
    print "-> Watchlist queried; details:" 
    watchlist_output(watchlist)
示例#8
0
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.server_url or not opts.token or not opts.query:
        print "Missing required param; run with --help for usage"
        sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.server_url, token=opts.token, ssl_verify=opts.ssl_verify)

    query = "-status:Resolved " + opts.query
    while True:
        results = cb.alert_search(query, rows=100)
        if results['total_results'] == 0: break

        for result in results['results']:
            new = {}
            new['unique_id'] = result['unique_id']
            new['status'] = "resolved"

            response = cb.alert_update(new)
            if not response or response['result'] != 'success':
                raise Exception("error setting status on %s: %s.  Aborting." % (result['unique_id'], repr(response)))
                break
            print "Resolved %s" % (result['unique_id'])
        time.sleep(25)
    print "Complete."
示例#9
0
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.url or not opts.token or not opts.id:
        print "Missing required param; run with --help for usage"
        sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.url, token=opts.token, ssl_verify=opts.ssl_verify)

    watchlists = cb.watchlist()

    watchlist_int_param = int(opts.id)

    # for each result
    for watchlist in watchlists:
        watchlist_int_id = int(watchlist['id'])
        #print "watchlist['id']: %s, opts.id: %s" % (watchlist_int_id,watchlist_int_param,)
        if watchlist_int_id >= watchlist_int_param:
            #print "MATCH: watchlist['id']: %s > opts.id: %s" % (watchlist_int_id,watchlist_int_param,)
            print "-> Deleting watchlist [id=%s]: %s" % (
                watchlist_int_id,
                watchlist['name'],
            )
            watchlist = cb.watchlist_del(watchlist_int_id)
            print "-> Watchlist deleted"
示例#10
0
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)

    if not opts.server_url or not opts.token:
        print "Must specify a CB server and API token with -c and -a"
        sys.exit(-1)

    if not opts.id:
        print "Must specify a feed id"
        sys.exit(-1)

    if not opts.remove and not (opts.certificate and opts.key):
        print "Missing required param; run with --help for usage"
        print "Either -C AND -K must be specified (to add SSL client certificates to a feed) or -r must be specified"
        sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.server_url,
                     token=opts.token,
                     ssl_verify=opts.ssl_verify)

    feed = {"id": opts.id}

    if opts.remove:
        feed["ssl_client_crt"] = ""
        feed["ssl_client_key"] = ""
    else:
        feed["ssl_client_crt"] = open(opts.certificate).read().strip()
        feed["ssl_client_key"] = open(opts.key).read().strip()

    cb.feed_modify(opts.id, feed)

    print "-> Success!"
示例#11
0
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.url or not opts.token or not opts.id or not opts.query:
        print "Missing required param; run with --help for usage"
        sys.exit(-1)

    # ensure the query string is minimally valid
    #
    if not opts.query.startswith("q="):
        print "Query must start with 'q='.  Examples;"
        print "  q=process_name:notepad.exe"
        print "  q=-modload:kernel32.dll"
        sys.exit(0)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.url, token=opts.token, ssl_verify=opts.ssl_verify)

    # edit the search query of the just-added watchlist
    #
    watchlist = {'search_query': opts.query}
    print "-> Modifying the watchlist query..."
    cb.watchlist_modify(opts.id, watchlist)
    print "-> Watchlist modified"

    # get record describing this watchlist
    #
    print "-> Querying for watchlist information..."
    watchlist = cb.watchlist(opts.id)
    print "-> Watchlist queried; details:"
    watchlist_output(watchlist)
示例#12
0
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.url or not opts.token or not opts.id:
        print "Missing required param; run with --help for usage"
        sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.url, token=opts.token, ssl_verify=opts.ssl_verify)

    # get record describing this watchlist
    #
    watchlist = cb.watchlist(opts.id)

    # output the details about the watchlist
    #
    print '%-20s | %s' % ('field', 'value')
    print '%-20s + %s' % ('-' * 20, '-' * 60)
    print '%-20s | %s' % ('id', watchlist['id'])
    print '%-20s | %s' % ('name', watchlist['name'])
    print '%-20s | %s' % ('date_added', watchlist['date_added'])
    print '%-20s | %s' % ('last_hit', watchlist['last_hit'])
    print '%-20s | %s' % ('last_hit_count', watchlist['last_hit_count'])
    print '%-20s | %s' % ('search_query', watchlist['search_query'])
    print '%-20s | %s' % ('readonly', watchlist['readonly'])
示例#13
0
    def load_config_file(self, configile):
        cfile = open(configile, "r").readlines()
        serverurl = str(cfile[0].rstrip())
        apitoken = str(cfile[1].rstrip())

        cb = cbapi.CbApi(serverurl, token=apitoken, ssl_verify=False)

        return cb
示例#14
0
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.url or not opts.token:
        print "Missing required param."
        sys.exit(-1)

    yesterday = datetime.datetime.now() - datetime.timedelta(days=1)
    yesterday = yesterday.strftime('%Y-%m-%d')
    opts.query = 'process_name:powershell.exe and start: %s' % yesterday
    print "Initial Query: %s", opts.query
    # build a cbapi object
    cb = cbapi.CbApi(opts.url, token=opts.token, ssl_verify=opts.ssl_verify)
    source_set = cb.process_search(opts.query)
    if source_set['total_results'] > 500:
        print "Total Results: %d" % source_set['total_results']
        print "More than 500 results to parse, exiting script to spare your CB server."
        sys.exit(0)

    # use the cbapi object to iterate over all matching process documents
    answer = cb.process_search_iter(opts.query)
    count = 0
    lrcount = 0
    # iterate over each process document in the results set
    for pdoc in answer:
        count += 1
        # Query the parent process to see if this child process has ended and assign the end date to process_end_time
        process_end_time = parent_search(opts, pdoc)

        if process_end_time:
            end = process_end_time
        else:
            end = datetime.datetime.strptime(pdoc['last_update'],
                                             "%Y-%m-%dT%H:%M:%S.%fZ")

        # Start time
        start = datetime.datetime.strptime(pdoc['start'],
                                           "%Y-%m-%dT%H:%M:%S.%fZ")

        # Difference betweeen the process end time and process start time
        runtime = int((end - start).seconds)

        # Change the compared value if 60 seconds is not considered a long run of powershell
        if runtime > 60:
            lrcount += 1
            print "#########################"
            print "Proc Doc: %s/#/analyze/%s/%d" % (opts.url, pdoc['id'],
                                                    pdoc['segment_id'])
            print "Hostname: ", pdoc['hostname']
            print "Username: "******"Process Name: ", pdoc['process_name']
            print "Command Line: ", pdoc['cmdline']
            print "Runtime: %d seconds" % runtime
            print "Process start  : %s" % start
            print "Process endtime: %s" % end
            print "$$$$$$$$$$$$$$$$$$$$$$$$$"
    print "Matching Process Count: ", count
    print "Matching Long Running Process Count: ", lrcount
示例#15
0
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.url or not opts.token:
        print "Missing required param; run with --help for usage"
        sys.exit(-1)

    cb = cbapi.CbApi(opts.url, token=opts.token, ssl_verify=opts.ssl_verify)
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        sensors = cb.sensors()

    f = open("isolated_sensors.txt", "w+")
    fis = f.read()
    f.close()

    try:
        former_iso_sensors = json.loads(fis)
    except ValueError:
        former_iso_sensors = collections.defaultdict(dict)

    current_iso_sensors = collections.defaultdict(dict)

    for sensor in sensors:
        if sensor['network_isolation_enabled'] == True:
            #sensor should be isolating, add sensor to list of currently iso enabled sensors
            sid = str(sensor['id'])
            sensor['url'] = opts.url + "/#/host/" + sid
            current_iso_sensors[sid]['network_isolation_enabled'] = sensor[
                'network_isolation_enabled']
            current_iso_sensors[sid]['is_isolating'] = sensor['is_isolating']
            try:
                if not sensor['is_isolating'] == former_iso_sensors[sid][
                        'is_isolating']:
                    #state change, send email
                    send_mail(sensor, opts)
            except KeyError as e:
                #sid is not present in former_iso_sensors, new sensor isolation, send email
                send_mail(sensor, opts)

    f = open("isolated_sensors.txt", "w")
    f.write(json.dumps(current_iso_sensors))
    f.close()

    #remove current isolations from from former isolations leaving the list of sensors removed from
    # isolation since the last running of this script
    iso_removed = [
        item for item in former_iso_sensors if item not in current_iso_sensors
    ]
    for fixed in iso_removed:
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            sensor = cb.sensor(fixed)
        sid = str(sensor['id'])
        sensor['url'] = opts.url + "/#/host/" + sid
        #send notification of isolation removal
        send_mail(sensor, opts)
def isolate_sensor(sensor):
    global cbtoken
    global cbserver

    print "Isolating sensor %s on %s..." % (sensor, cbserver)

    cbURL = "https://" + cbserver
    cb = cbapi.CbApi(cbURL, token=cbtoken, ssl_verify=False)
    status = cb.sensor_toggle_isolation(sensor, True)

    print "status was %s" % status
示例#17
0
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.server_url or not opts.token:
      print "Missing required param; run with --help for usage"
      sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.server_url, token=opts.token, ssl_verify=opts.ssl_verify)

    package = cb.sensor_installer('WindowsMSI', 1)
    print package
示例#18
0
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.url or not opts.token or not opts.sensor:
        print "Missing required param; run with --help for usage"
        sys.exit(-1)
    
    cb = cbapi.CbApi(opts.url, token=opts.token, ssl_verify=opts.ssl_verify, ignore_system_proxy=True)
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        sensor = cb.sensor(opts.sensor)
    
    pprint.pprint(sensor)
示例#19
0
    def validate_config(self):
        if not self.cfg.has_section('bridge'):
            raise ConfigurationError(
                "Configuration file does not have required section 'bridge'")

        self.check_required_options(
            ['carbonblack_server_url', 'carbonblack_server_token'])

        ssl_verify = self.get_config_boolean("carbonblack_server_sslverify",
                                             False)
        server_url = self.cfg.get("bridge", "carbonblack_server_url")
        server_token = self.cfg.get("bridge", "carbonblack_server_token")
        try:
            self.cb = cbapi.CbApi(server_url,
                                  token=server_token,
                                  ssl_verify=ssl_verify)
        except Exception as e:
            raise ConfigurationError(
                "Could not create CbAPI instance to %s: %s" %
                (server_url, e.message))

        if self.get_config_boolean("use_streaming", False):
            self.check_required_options([
                'carbonblack_streaming_host', 'carbonblack_streaming_username',
                'carbonblack_streaming_password'
            ])

            self.streaming_host = self.cfg.get('bridge',
                                               'carbonblack_streaming_host')
            self.streaming_username = self.cfg.get(
                'bridge', 'carbonblack_streaming_username')
            self.streaming_password = self.cfg.get(
                'bridge', 'carbonblack_streaming_password')
            self.use_streaming = True
        else:
            self.use_streaming = False

        self.feed_base_url = "http://%s:%d" % (self.get_config_string(
            'feed_host',
            '127.0.0.1'), self.get_config_integer('listener_port', 8080))
        self.feed_url = "%s%s" % (self.feed_base_url, '/feed.json')

        try:
            cbinfo = self.cb.info()
            self.cb_version = cbinfo['version']
        except Exception as e:
            raise ConfigurationError(
                "Could not connect to Cb server at %s: %s" %
                (server_url, str(e)))

        return True
示例#20
0
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.url or not opts.token:
        print "Missing required param; run with --help for usage"
        sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.url, token=opts.token, ssl_verify=opts.ssl_verify)

    # perform a single process search
    #
    processes = cb.process_search("", rows=0)

    print "%-20s : %s" % ('Total Processes', processes['total_results'])
    print "%-20s : %sms" % ('QTime', int(1000*processes['elapsed']))
    print '\n'


    # top-level statistics - 'noisiest' hostnames, processes, parent 
    #   processes, usernames, and full process paths
    #
    output_mostcommon(processes, 'hostname', 'Hostname')
    output_mostcommon(processes, 'process_name', 'Process Name')
    output_mostcommon(processes, 'parent_name', 'Parent Process Name')
    output_mostcommon(processes, 'username_full', 'Username')
    output_mostcommon(processes, 'path_full', 'Full Process Path')

    # deeper-dive - for the noisiest processes, what are the most common
    #   parent process names?
    #
    print
    print "-" * 80
    print

    i = 0
    for entry in processes['facets']['process_name']:
        processes2 = cb.process_search("process_name:%s" % (entry['name'],), rows=0)
        print
        print "Most common parent processes for %s" % (entry['name'],)
        print "-" * 80 
        for entry2 in processes2['facets']['parent_name']:
            try:
                print "  %-40s | %s" % (entry2['name'], entry2['ratio'])
            except:
                pass
        i = i + 1
        if i > 10:
            break
示例#21
0
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.url or not opts.token:
        print "Missing required param; run with --help for usage"
        sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.url, token=opts.token, ssl_verify=opts.ssl_verify)

    # if none of the four "set" parameters are provided,
    # query for the existing Bit9 Platform Server configuration  
    #
    if None == opts.server_url and\
       None == opts.ssl_cert_verify and\
       None == opts.watchlist_enable and\
       None == opts.auth_token:
        config = cb.get_platform_server_config()
        pprint.pprint(config)
        sys.exit(0)

    # here because one or more of the Bit9 Platform Server configuration options is to be set
    # start with an empty dictionary of parameters
    #
    config = {}

    # apply the server url if so specified
    #
    if opts.server_url is not None:
        config["server_url"] = opts.server_url

    # apply the auth token if so specified
    #
    if opts.auth_token is not None:
        config["auth_token"] = opts.auth_token

    # apply the "watchlist enable" flag if so specified
    #
    if opts.watchlist_enable:
        config["watchlist_export"] = s2b(opts.watchlist_enable)

    # apply the "ssl cert verify" flag if so specified
    #
    if opts.ssl_cert_verify:
       config["ssl_certificate_verify"] = s2b(opts.ssl_cert_verify)

    # apply the configuration
    #
    cb.set_platform_server_config(config)
示例#22
0
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.server_url or not opts.token:
      print "Missing required param; run with --help for usage"
      sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.server_url, token=opts.token, ssl_verify=opts.ssl_verify)

    login = cb.get_login_caps()
    for key in login.keys():
        print "%-20s : %s" % (key, login[key])
示例#23
0
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.server_url or not opts.token:
        print "Missing required param; run with --help for usage"
        sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.server_url,
                     token=opts.token,
                     ssl_verify=opts.ssl_verify)

    output_info(opts.server_url, cb.license_status())
示例#24
0
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.server_url or not opts.token or not opts.id or not opts.action_id:
        print "Missing required param; run with --help for usage"
        sys.exit(-1)

    # build a cbapi object
    #

    cb = cbapi.CbApi(opts.server_url,
                     token=opts.token,
                     ssl_verify=opts.ssl_verify)

    result = cb.feed_action_del(opts.id, opts.action_id)
    print result
示例#25
0
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.server_url or not opts.token or not opts.id:
      print "Missing required param; run with --help for usage"
      sys.exit(-1)

    # build a cbapi object
    #

    cb = cbapi.CbApi(opts.server_url, token=opts.token, ssl_verify=opts.ssl_verify)

    event = cb.event_del(opts.id)
    print ""
    for key in event.keys():
        print "%-20s : %s" % (key, event[key])
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.url or not opts.token:
        print "Missing required param; run with --help for usage"
        sys.exit(-1)

    watchlistIds = []

    global cb
    #
    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.url, token=opts.token, ssl_verify=opts.ssl_verify)

    #
    # enumerate all watchlists
    #
    watchlists = cb.watchlist()

    print "%-4s | %-32s |" % ('id', 'name')
    print "%-4s + %-32s +" % ('-' * 4, '-' * 32)

    #
    # for each result
    #
    for watchlist in watchlists:
        print "%-4s | %-32s |" % (watchlist['id'], watchlist['name'])
        watchlistIds.append(watchlist['id'])
    print "%-4s + %-32s +" % ('-' * 4, '-' * 32)

    if not opts.watchlistid:
        print "Missing watchlist ID parameter; run with --help for usage"
        sys.exit(-1)

    if opts.watchlistid not in watchlistIds:
        print "Error: Watchlist ID not found"
        sys.exit(-1)

    print
    for watchlist in watchlists:
        if opts.watchlistid == watchlist['id']:
            print "Printing %d results for watchlist: %s" % (opts.numrows,
                                                             watchlist['name'])
            printWatchlistHits(cb.server, opts.watchlistid,
                               watchlist['index_type'], opts.numrows)
            break
示例#27
0
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.url or not opts.token:
        print "Missing required param; run with --help for usage"
        sys.exit(-1)

    if not opts.format == 'plain' and not opts.format == 'pipe' and not opts.format == 'csv':
        print "Format must be one of [plain|pipe|csv]"
        sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.url, token=opts.token, ssl_verify=opts.ssl_verify)

    # set up filters
    #
    filters = {}
    if opts.groupid is not None:
        filters['groupid'] = opts.groupid

    # enumerate sensors 
    #
    sensors = cb.sensors(filters)

    # output column headings as appropriate
    #
    if opts.format == 'pipe':
        print "%s|%s|%s|%s|%s" % ("sensor id", "group id", "computer name", "OS", "last checkin time")
    if opts.format == 'csv':
        print "%s,%s,%s,%s,%s" % ("sensor id", "group id", "computer name", "OS", "last checkin time")

    # output each sensor in turn
    #
    for sensor in sensors:
       if opts.format == 'plain': 
           print "%-20s : %s" % ("computer name", sensor['computer_name'])
           print "----------------------------------------------"
           print "%-20s : %s" % ("sensor_group_id", sensor['group_id'])
           print "%-20s : %s" % ("sensor id", sensor['id'])
           print "%-20s : %s" % ("os", sensor['os_environment_display_string'])
           print "%-20s : %s" % ("last checkin time", sensor['last_checkin_time'])
           print
       elif opts.format == 'pipe':
           print "%s|%s|%s|%s|%s" % (sensor['id'], sensor['group_id'], sensor['computer_name'], sensor['os_environment_display_string'], sensor['last_checkin_time'])
       elif opts.format == 'csv':
           print '"%s","%s","%s","%s","%s"' % (sensor['id'], sensor['group_id'], sensor['computer_name'], sensor['os_environment_display_string'], sensor['last_checkin_time'])
示例#28
0
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.url or not opts.token or opts.query is None:
        print "Missing required param; run with --help for usage"
        sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.url, token=opts.token, ssl_verify=opts.ssl_verify)

    # perform a single binary search
    #
    binaries = cb.binary_search(opts.query)

    print "%-20s : %s" % ('Displayed Results', len(binaries['results']))
    print "%-20s : %s" % ('Total Results', binaries['total_results'])
    print "%-20s : %sms" % ('QTime', int(1000 * binaries['elapsed']))
    print '\n'

    # for each result
    for binary in binaries['results']:
        print binary['md5']
        print "-" * 80
        print "%-20s : %s" % ('Size (bytes)',
                              binary.get('orig_mod_len', '<UNKNOWN>'))
        print "%-20s : %s" % ('Signature Status',
                              binary.get('digsig_result', '<UNKNOWN>'))
        print "%-20s : %s" % ('Publisher',
                              binary.get('digsig_publisher', '<UNKNOWN>'))
        print "%-20s : %s" % ('Product Version',
                              binary.get('product_version', '<UNKNOWN>'))
        print "%-20s : %s" % ('File Version',
                              binary.get('file_version', '<UNKNOWN'))
        print "%-20s : %s" % ('64-bit (x64)',
                              binary.get('is_64bit', '<UNKNOWN>'))
        print "%-20s : %s" % ('EXE',
                              binary.get('is_executable_image', '<UNKNOWN>'))

        if len(binary.get('observed_filename', [])) > 0:
            print "%-20s : %s" % (
                'On-Disk Filename(s)',
                binary['observed_filename'][0].split('\\')[-1])
            for observed_filename in binary['observed_filename'][1:]:
                print "%-20s : %s" % ('', observed_filename.split('\\')[-1])

        print '\n'
示例#29
0
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.url or not opts.token or not opts.id:
        print "Missing required param; run with --help for usage"
        sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.url, token=opts.token, ssl_verify=opts.ssl_verify)

    # delete the watchlist
    # for the purposes of this test script, hardcode the watchlist type, name, and query string
    #
    print "-> Deleting watchlist [id=%s]..." % (opts.id,)
    watchlist = cb.watchlist_del(opts.id)
    print "-> Watchlist deleted" 
示例#30
0
def main(argv):
    parser = build_cli_parser()
    opts, args = parser.parse_args(argv)
    if not opts.url or not opts.token:
        print "Missing required param; run with --help for usage"
        sys.exit(-1)

    # build a cbapi object
    #
    cb = cbapi.CbApi(opts.url, token=opts.token, ssl_verify=opts.ssl_verify)

    # add a watchlist
    # for the purposes of this test script, hardcode the watchlist type, name, and query string
    #
    print "-> Adding watchlist..."
    watchlist = cb.watchlist_add('events', 'test watchlist',
                                 'q=process_name:notepad.exe')
    print "-> Watchlist added [id=%s]" % (watchlist['id'])

    # get record describing this watchlist
    #
    print "-> Querying for watchlist information..."
    watchlist = cb.watchlist(watchlist['id'])
    print "-> Watchlist queried; details:"
    watchlist_output(watchlist)

    # edit the search query of the just-added watchlist
    #
    print "-> Modifying the watchlist query..."
    watchlist['search_query'] = 'q=process_name:calc.exe'
    cb.watchlist_modify(watchlist['id'], watchlist)
    print "-> Watchlist modified"

    # get record describing this watchlist
    #
    print "-> Querying for watchlist information..."
    watchlist = cb.watchlist(watchlist['id'])
    print "-> Watchlist queried; details:"
    watchlist_output(watchlist)

    # delete the just-added watchlist
    #
    print "-> Deleting Watchlist..."
    cb.watchlist_del(watchlist['id'])
    print "-> Watchlist deleted"