Example #1
0
 def test_integration_devices_get_all_date_phy_filter(self):
     here_dir = os.path.dirname(os.path.abspath(__file__))
     test_db = os.path.join(here_dir, "../assets/testdata.kismet_5")
     abstraction = kismetdb.Devices(test_db)
     all_alerts = abstraction.get_all(first_time_gt="2018-01-01",
                                      phyname=["Bluetooth", "IEEE802.11"])
     assert all_alerts
Example #2
0
 def test_integration_devices_yield_meta(self):
     here_dir = os.path.dirname(os.path.abspath(__file__))
     test_db = os.path.join(here_dir, "../assets/testdata.kismet_5")
     abstraction = kismetdb.Devices(test_db)
     for alert in abstraction.yield_meta():
         assert alert
         assert "device" not in alert
Example #3
0
 def test_integration_devices_get_meta(self):
     here_dir = os.path.dirname(os.path.abspath(__file__))
     test_db = os.path.join(here_dir, "../assets/testdata.kismet_5")
     abstraction = kismetdb.Devices(test_db)
     all_alerts = abstraction.get_meta()
     assert all_alerts
     assert "json" not in all_alerts[0]
Example #4
0
 def test_integration_devices_get_all(self):
     here_dir = os.path.dirname(os.path.abspath(__file__))
     test_db = os.path.join(here_dir, "../assets/testdata.kismet_4")
     abstraction = kismetdb.Devices(test_db)
     all_devices = abstraction.get_all()
     assert all_devices
     for device in all_devices:
         assert isinstance(device["min_lat"], float)
         assert isinstance(device["min_lon"], float)
         assert isinstance(device["max_lat"], float)
         assert isinstance(device["max_lon"], float)
         assert isinstance(device["avg_lat"], float)
         assert isinstance(device["avg_lon"], float)
def main():
    parser = argparse.ArgumentParser(description="Kismet devices to json")
    parser.add_argument("--in",
                        action="store",
                        dest="infile",
                        help="Input (.kismet) file")
    parser.add_argument("--out",
                        action="store",
                        dest="outfile",
                        help=("Output filename (optional). If omitted, logs "
                              "multi-line and indented (human-readable) "
                              "to stdout."))
    parser.add_argument("--start-time",
                        action="store",
                        dest="starttime",
                        help="Only list devices seen after given time")
    parser.add_argument("--min-signal",
                        action="store",
                        dest="minsignal",
                        help=("Only list devices with a best signal higher "
                              "than min-signal"))

    results = parser.parse_args()
    query_args = {}

    if results.infile is None:
        print("Expected --in [file]")
        sys.exit(1)

    if not os.path.isfile(results.infile):
        print("Could not find input file \"{}\"".format(results.infile))
        sys.exit(1)

    if results.starttime:
        query_args["first_time_gt"] = results.starttime

    if results.minsignal:
        query_args["strongest_signal_gt"] = results.minsignal
    logf = None

    devices_abstraction = kismetdb.Devices(results.infile)

    devs = [row["device"] for row in devices_abstraction.get_all(**query_args)]

    if results.outfile:
        logf = open(results.outfile, "w")
        logf.write(
            json.dumps(devs, sort_keys=True, indent=4, separators=(",", ": ")))
    else:
        print(
            json.dumps(devs, sort_keys=True, indent=4, separators=(",", ": ")))
def main():
    parser = argparse.ArgumentParser(description="Kismet to Filebeat json")
    parser.add_argument("--in",
                        action="store",
                        dest="infile",
                        required=True,
                        help="Input (.kismet) file")
    parser.add_argument("--out",
                        action="store",
                        dest="outfile",
                        help=("Output filename (optional) for appending. If "
                              "unspecified, each record will be printed to "
                              "stdout, one record per line, ideal for piping "
                              "into filebeat."))
    parser.add_argument("--start-time",
                        action="store",
                        dest="starttime",
                        help="Only list devices seen after given time")
    parser.add_argument("--min-signal",
                        action="store",
                        dest="minsignal",
                        help=("Only list devices with a best signal higher "
                              "than min-signal"))

    results = parser.parse_args()
    query_args = {}

    if not os.path.isfile(results.infile):
        print("Could not find input file \"{}\"".format(results.infile))
        sys.exit(1)

    if results.starttime:
        query_args["first_time_gt"] = results.starttime

    if results.minsignal:
        query_args["strongest_signal_gt"] = results.minsignal
    logf = None

    devices_abstraction = kismetdb.Devices(results.infile)

    for device in [
            json.loads(row["device"])
            for row in devices_abstraction.yield_all(**query_args)
    ]:
        stripped_device = strip_old_empty_trees(device)
        if results.outfile:
            logf = open(results.outfile, "a")
            logf.write(json.dumps(stripped_device, sort_keys=True))
        else:
            print(json.dumps(stripped_device, sort_keys=True))
Example #7
0
 def test_integration_devices_yield_all_date_phy_filter(self):
     here_dir = os.path.dirname(os.path.abspath(__file__))
     test_db = os.path.join(here_dir, "../assets/testdata.kismet_5")
     abstraction = kismetdb.Devices(test_db)
     for device in abstraction.yield_meta(first_time_gt="2018-01-01",
                                          phyname=[
                                              "Bluetooth", "IEEE802.11"
                                          ]):
         assert device
         assert "device" not in device
         assert isinstance(device["min_lat"], float)
         assert isinstance(device["min_lon"], float)
         assert isinstance(device["max_lat"], float)
         assert isinstance(device["max_lon"], float)
         assert isinstance(device["avg_lat"], float)
         assert isinstance(device["avg_lon"], float)
Example #8
0
 def test_integration_devices_instantiate(self):
     here_dir = os.path.dirname(os.path.abspath(__file__))
     test_db = os.path.join(here_dir, "../assets/testdata.kismet_5")
     abstraction = kismetdb.Devices(test_db)
     assert abstraction
Example #9
0
def main():
    parser = argparse.ArgumentParser(description="Kismet to KML Log Converter")
    parser.add_argument("--in",
                        action="store",
                        dest="infile",
                        help="Input (.kismet) file")
    parser.add_argument("--out",
                        action="store",
                        dest="outfile",
                        help="Output filename (optional)")
    parser.add_argument("--start-time",
                        action="store",
                        dest="starttime",
                        help="Only list devices seen after given time")
    parser.add_argument("--min-signal",
                        action="store",
                        dest="minsignal",
                        help=("Only list devices with a best signal higher "
                              "than min-signal"))
    parser.add_argument("--strongest-point",
                        action="store_true",
                        dest="strongest",
                        default=False,
                        help="Plot points based on strongest signal")
    parser.add_argument("--title",
                        action="store",
                        dest="title",
                        default="Kismet",
                        help="Title embedded in KML file")
    parser.add_argument("--ssid",
                        action="store",
                        dest="ssid",
                        help=("Only plot networks which match the SSID "
                              "(or SSID regex)"))

    results = parser.parse_args()

    query_args = {}

    if results.infile is None:
        print("Expected --in [file]")
        sys.exit(1)

    if results.starttime:
        query_args["first_time_gt"] = results.starttime

    if results.minsignal:
        query_args["strongest_signal_gt"] = results.minsignal

    kml = simplekml.Kml()

    kml.document.name = results.title

    num_plotted = 0

    devices = kismetdb.Devices(results.infile)

    for device in devices.yield_all(**query_args):
        try:
            dev = json.loads(device["device"])
            # Check for the SSID if we"re doing that; allow it to trip
            # a KeyError and jump out of processing this device
            if results.ssid is not None:
                matched = False
                for s in dev["dot11.device"][
                        "dot11.device.advertised_ssid_map"]:  # NOQA
                    adv_ssid = dev["dot11.device"][
                        "dot11.device.advertised_ssid_map"][s][
                            "dot11.advertisedssid.ssid"]  # NOQA
                    if re.match(results.ssid, adv_ssid):
                        matched = True
                        break

                if not matched:
                    print("Not a match on SSID!")
                    continue

            loc = None

            if results.strongest:
                loc = dev["kismet.device.base.signal"][
                    "kismet.common.signal.peak_loc"]  # NOQA
            else:
                loc = dev["kismet.device.base.location"][
                    "kismet.common.location.avg_loc"]  # NOQA

            if loc == 0:
                print("Null island...")
                continue

            mac = dev["kismet.device.base.macaddr"]

            title = ""

            if "kismet.device.base.name" in dev:
                title = dev["kismet.device.base.name"]

            if title == "":
                if "dot11.device" in dev:
                    if "dot11.device.last_beaconed_ssid" in dev[
                            "dot11.device"]:  # NOQA
                        title = dev["dot11.device"][
                            "dot11.device.last_beaconed_ssid"]  # NOQA

            if title == "":
                title = mac

            kml.newpoint(name=title,
                         coords=[(loc["kismet.common.location.lon"],
                                  loc["kismet.common.location.lat"],
                                  loc["kismet.common.location.alt"])])

            num_plotted = num_plotted + 1
        except TypeError:
            continue
        except KeyError:
            continue
    kml.save(results.outfile)
    print("Exported {} devices to {}".format(num_plotted, results.outfile))
Example #10
0
def main():
    parser = argparse.ArgumentParser(description="Kismet to CSV Log Converter")
    parser.add_argument("--in",
                        action="store",
                        dest="infile",
                        help="Input (.kismet) file")
    parser.add_argument("--out",
                        action="store",
                        dest="outfile",
                        help="Output CSV filename")
    parser.add_argument("--table",
                        action="store",
                        dest="srctable",
                        help="Select the table to output")

    results = parser.parse_args()
    replacements = {}

    if results.infile is None:
        print("Expected --in [file]")
        sys.exit(1)

    if not os.path.isfile(results.infile):
        print("Could not find input file \"{}\"".format(results.infile))
        sys.exit(1)

    if results.srctable is None:
        results.srctable = "devices"
    replacements["srctable"] = results.srctable

    if results.srctable == "devices":
        table_abstraction = kismetdb.Devices(results.infile)
        column_names = [
            "first_time", "last_time", "devkey", "phyname", "devmac",
            "strongest_signal", "min_lat", "min_lon", "max_lat", "max_lon",
            "avg_lat", "avg_lon", "bytes_data", "type"
        ]
    elif results.srctable == "packets":
        table_abstraction = kismetdb.Packets(results.infile)
        column_names = [
            "ts_sec", "ts_usec", "phyname", "sourcemac", "destmac", "transmac",
            "frequency", "devkey", "lat", "lon", "packet_len", "signal",
            "datasource", "dlt", "error"
        ]
    elif results.srctable == "datasources":
        table_abstraction = kismetdb.DataSources(results.infile)
        column_names = [
            "uuid", "typestring", "definition", "name", "interface"
        ]
    elif results.srctable == "alerts":
        table_abstraction = kismetdb.Alerts(results.infile)
        column_names = [
            "ts_sec", "ts_usec", "phyname", "devmac", "lat", "lon", "header"
        ]
    else:
        print("Invalid table entered, please retry with either devices, "
              "packets, datasources or alerts.")
        sys.exit(1)

    if results.outfile is None:
        results.outfile = "{}-{}.csv".format(results.infile,
                                             replacements["srctable"])

    csv_file_mode = "wb" if sys.version_info[0] < 3 else "w"

    with open(results.outfile, csv_file_mode) as csvfile:
        csvWriter = csv.DictWriter(csvfile,
                                   delimiter="\t",
                                   extrasaction="ignore",
                                   fieldnames=column_names)
        nrows = 0
        csvWriter.writeheader()
        for row in table_abstraction.yield_meta():
            csvWriter.writerow(row)
            nrows = nrows + 1
            if nrows % 1000 == 0:
                print("Wrote {} rows".format(nrows))