How to use the cbapi.response.models.Process function in cbapi

To help you get started, we’ve selected a few cbapi examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github carbonblack / cbapi-python / examples / response / enumerate_usb_devices.py View on Github external
def main():
    parser = build_cli_parser("Enumerate USB Devices")
    parser.add_argument("--start", "-s", action="store", default=None, dest="start_time",
                        help="Start time (example: -2h)")

    args = parser.parse_args()
    cb = get_cb_response_object(args)

    query_string = r'regmod:registry\machine\system\currentcontrolset\control\deviceclasses\{53f56307-b6bf-11d0-94f2-00a0c91efb8b}\*'  # noqa: E501
    if args.start_time:
        query_string += ' start:{0:s}'.format(args.start_time)

    for proc in cb.select(Process).where(query_string):
        for rm in proc.regmods:
            if "{53f56307-b6bf-11d0-94f2-00a0c91efb8b}" in rm.path:
                pieces = rm.path.split("usbstor#disk&")
                if len(pieces) < 2:
                    print("WARN:::: {0}".format(str(pieces)))
                else:
                    device_info = pieces[1]  # .split('{53f56307-b6bf-11d0-94f2-00a0c91efb8b}')[0]
                    print(device_info)
github carbonblack / cbapi-python / examples / response / tf.py View on Github external
args = parser.parse_args()
    cb = get_cb_response_object(args)

    if args.procnamefile:
        processes = [s.strip() for s in open(args.procnamefile).readlines()]
    else:
        processes = [s.strip() for s in args.procname.split(",")]

    behavior = count_children
    if args.cmdline:
        behavior = child_cmdlines

    rows = []
    for parent_proc in processes:
        process_facets = cb.select(Process).where("parent_name:{0}".format(parent_proc)).facets("process_name")
        for term in reversed(process_facets["process_name"]):
            termratio = int(float(term['ratio']))
            if int(args.percentless) >= termratio:
                rows.extend(process_hit(cb, parent_proc, term["name"], term["value"], term["ratio"], behavior))

    for row in rows:
        print(",".join([str(x) for x in row]))
github redcanaryco / redcanary-response-utils / timeline.py View on Github external
def process_search(cb_conn, query, query_base=None,
                   filemods=None, netconns=None, 
                   processes=None, regmods=None):

    if query_base != None:
        query += query_base

    log_info("QUERY: {0}".format(query))

    query_result = cb_conn.select(Process).where(query).group_by("id")
    query_result_len = len(query_result)
    log_info('Total results: {0}'.format(query_result_len))

    results = []

    try:
        process_counter = 0
        for proc in query_result:
            process_counter += 1
            if process_counter % 10 == 0:
                log_info('Processing {0} of {1}'.format(process_counter, query_result_len))

            hostname = proc.hostname.lower()
            username = proc.username.lower()
            path = proc.path
            cmdline = proc.cmdline
github carbonblack / cbapi-python / examples / response / new_binaries_with_netconns.py View on Github external
#
        # Update progress bar
        #
        pbar.update(i + 1)

        #
        # Retrieve the binary timestamp
        #
        binary_timestamp = time.asctime(time.gmtime(pefile.PE(data=binary.file.read()).FILE_HEADER.TimeDateStamp))

        #
        # Build a sub query to see if this binary was executed and had netconns
        #
        sub_query = "process_md5:" + binary.md5 + " netconn_count:[1 TO *]"
        process_query = cb.select(Process).where(sub_query)

        #
        # Iterate through results
        #
        for process in process_query:

            #
            # Write out the result
            #
            try:
                csv_writer.writerow((process.path,
                                     process.hostname,
                                     process.username,
                                     process.netconn_count,
                                     process.webui_link,
                                     binary.webui_link,
github redcanaryco / cb-response-surveyor / surveyor.py View on Github external
def process_search(cb_conn, query, query_base=None):
  """Perform a single Cb Response query and return a unique set of
  results.
  """
  results = set()

  query += query_base

  try:
    for proc in cb_conn.select(Process).where(query):
      results.add((proc.hostname.lower(),
            proc.username.lower(), 
            proc.path,
            proc.cmdline))
  except KeyboardInterrupt:
    log("Caught CTRL-C. Returning what we have . . .\n")

  return results
github carbonblack / cbapi-python / examples / response / cmd_exe_filemods.py View on Github external
def main():
    parser = build_cli_parser("Search for cmd.exe writing to exe and dll filepaths")

    args = parser.parse_args()
    cb = get_cb_response_object(args)

    for proc in cb.select(Process).where("process_name:cmd.exe (filemod:*.exe or filemod:*.dll)"):
        for fm in proc.filemods:
            if not fm.path.lower().endswith((".exe", ".dll")):
                continue

            signed = ""
            product_name = ""

            if fm.type == "LastWrote" and fm.md5:
                try:
                    b = cb.select(Binary, fm.md5)
                    signed = b.signed
                    product_name = b.product_name
                except ObjectNotFoundError:
                    pass

            print("%s,%s,%s,%s,%s,%s,%s,%s,%s" % (str(fm.timestamp), proc.hostname, proc.username, proc.path,
github redcanaryco / cb-response-surveyor / surveyor.py View on Github external
def nested_process_search(cb_conn, criteria, query_base=None):
  """Perform Cb Response queries for one or more programs and return a 
  unique set of results per program.
  """
  results = set()

  try:
    for search_field,terms in criteria.items():
      query = '(' + ' OR '.join('%s:%s' % (search_field, term) for term in terms) + ')'
      query += query_base

      for proc in cb_conn.select(Process).where(query):
        results.add((proc.hostname.lower(),
                     proc.username.lower(), 
                     proc.path,
                     proc.cmdline))
  except KeyboardInterrupt:
    log("Caught CTRL-C. Returning what we have . . .")

  return results
github carbonblack / cbapi-python / examples / response / event_export.py View on Github external
group.add_argument("--query", help="query to pull multiple processes")
    args = parser.parse_args()

    cb = get_cb_response_object(args)

    if args.processid:
        if args.processid.startswith("http"):
            # interpret as a URL
            proc = cb.from_ui(args.processid)
        else:
            # interpret as a Process ID
            proc = cb.select(Process, args.processid)

        write_csv(proc, "{0}.csv".format(proc.id))
    else:
        for proc in cb.select(Process).where(args.query).group_by("id"):
            write_csv(proc, "{0}.csv".format(proc.id))
github redcanaryco / redcanary-response-utils / process-util.py View on Github external
def process_search(cb_conn, query, query_base=None, groupby=None):
    if query_base != None:
        query += query_base

    query_result = cb_conn.select(Process).where(query)

    if groupby != None:
        query_result = query_result.group_by(groupby)

    query_result_len = len(query_result)
    log_info('Total results: {0}'.format(query_result_len))

    results = []

    try:
        process_counter = 0
        for process in query_result:
            process_counter += 1
            if process_counter % 100 == 0:
                log_info('Processing {0} of {1}'.format(process_counter, query_result_len))
github redcanaryco / redcanary-response-utils / sensor-util.py View on Github external
counter = 1
    for sensor in sensors:
        if counter % 10 == 0:
            print("{0} of {1}".format(counter, num_sensors))

        if len(sensor.resource_status) > 0:
            commit_charge = "{0:.2f}".format(float(sensor.resource_status[0]['commit_charge'])/1024/1024)
        else:
            commit_charge = ''
        num_eventlog_mb = "{0:.2f}".format(float(sensor.num_eventlog_bytes)/1024/1024)
        num_storefiles_mb = "{0:.2f}".format(float(sensor.num_storefiles_bytes)/1024/1024)
        systemvolume_free_size = "{0:.2f}".format(float(sensor.systemvolume_free_size)/1024/1024)
        systemvolume_total_size = "{0:.2f}".format(float(sensor.systemvolume_total_size)/1024/1024)

        if args.process_count == True:
            process_count = len(cb.select(Process).where('sensor_id:{0}'.format(sensor.id)))
        else:
            process_count = ''

        if args.checkin_ip == True:
            try:
                checkin_ip = cb.select(Process).where('sensor_id:{0}'.format(sensor.id)).first().comms_ip
            except AttributeError:
                checkin_ip = ''
        else:
            checkin_ip = ''

        if args.tamper_count == True:
            tamper_count = len(cb.select(Process).where('tampered:true AND sensor_id:{0}'.format(sensor.id)))
        else:
            tamper_count = ''