Example #1
0
def read_function():
    # Initialize the message sent by netlink socket
    msg = nlmsg_alloc()
    # Use command CMD_GET_STATION to retreive the connected stations attributes
    # With Hostapd, the connected stations are the clients
    # See https://git.kernel.org/pub/scm/linux/kernel/git/linville/wireless.git/tree/include/uapi/linux/nl80211.h?id=HEAD#n222
    genlmsg_put(msg, 0, 0, DRIVER_ID, 0, NLM_F_DUMP,
                nl80211.NL80211_CMD_GET_STATION, 0)
    # Set the network interface of the device we are working with
    # See https://git.kernel.org/pub/scm/linux/kernel/git/linville/wireless.git/tree/include/uapi/linux/nl80211.h?id=HEAD#n1032
    nla_put_u32(msg, nl80211.NL80211_ATTR_IFINDEX, INTERFACEINDEX)
    # Finalize and transmit message
    nl_send_auto(SOCKET, msg)
    # This list will contain the results of the kernel
    results = []
    # Bind the callbacks methods for events NL_CB_VALID and NL_CB_FINISH
    cb = libnl.handlers.nl_cb_alloc(libnl.handlers.NL_CB_DEFAULT)
    libnl.handlers.nl_cb_set(cb, libnl.handlers.NL_CB_VALID,
                             libnl.handlers.NL_CB_CUSTOM,
                             getStationInfo_callback, results)
    libnl.handlers.nl_cb_set(cb, libnl.handlers.NL_CB_FINISH,
                             libnl.handlers.NL_CB_CUSTOM, finish_callback,
                             results)
    # Receive messages from Kernel
    nl_recvmsgs(SOCKET, cb)
    while len(results) == 0:
        continue
    # Configure the collectd data sending object
    VALUES.plugin = "hostapd"
    VALUES.plugin_instance = INTERFACE
    VALUES.type = 'gauge'
    VALUES.type_instance = 'stations-count'
    # If no clients are connected, just send 0 to the metrics storage backend,
    # otherwise, send the count and the attributes of clients
    if results[-1] == -1:
        VALUES.dispatch(values=[0])
    else:
        VALUES.dispatch(values=[len(results)])
        # Browse the stations returned by the kernel
        for station in results:
            # If we shouldn't send data for every clients, we check the MAC address
            if len(CLIENTS) > 0:
                if station.mac_addr in CLIENTS:
                    send_station_stats(station)
            # If not, just send the data
            else:
                send_station_stats(station)

    # Clean a few values to avoid memory leak
    del (msg)
    del (cb)
    del (results)
    def _do_scan_results(self, if_index, driver_id, results):
        # Retrieve the results of a successful scan (SSIDs and data about them).
        # This function does not require root privileges. It eventually calls a
        # callback that actually decodes data about SSIDs but this function
        # kicks that off. May exit the program (sys.exit()) if a fatal error
        # occurs.
        #
        # Positional arguments:
        # self._nl_sock -- nl_sock class instance (from nl_socket_alloc()).
        # if_index -- interface index (integer).
        # driver_id -- nl80211 driver ID from genl_ctrl_resolve() (integer).
        # results -- dictionary to populate with results. Keys are BSSIDs (MAC
        #            addresses) and values are dicts of data.
        # Returns:
        # 0 on success or a negative error code.

        msg = nlmsg_alloc()
        genlmsg_put(msg, 0, 0, driver_id, 0, NLM_F_DUMP,
                    nl80211.NL80211_CMD_GET_SCAN, 0)
        nla_put_u32(msg, nl80211.NL80211_ATTR_IFINDEX, if_index)
        cb = libnl.handlers.nl_cb_alloc(libnl.handlers.NL_CB_DEFAULT)
        libnl.handlers.nl_cb_set(cb, libnl.handlers.NL_CB_VALID,
                                 libnl.handlers.NL_CB_CUSTOM,
                                 self._callback_dump, results)
        logger.debug('Sending NL80211_CMD_GET_SCAN...')
        ret = nl_send_auto(self._nl_sock, msg)
        if ret >= 0:
            logger.debug('Retrieving NL80211_CMD_GET_SCAN response...')
            ret = nl_recvmsgs(self._nl_sock, cb)
        return ret
Example #3
0
def do_scan_results(sk, if_index, driver_id, results):
    """Retrieve the results of a successful scan (SSIDs and data about them).

    This function does not require root privileges. It eventually calls a callback that actually decodes data about
    SSIDs but this function kicks that off.

    May exit the program (sys.exit()) if a fatal error occurs.

    Positional arguments:
    sk -- nl_sock class instance (from nl_socket_alloc()).
    if_index -- interface index (integer).
    driver_id -- nl80211 driver ID from genl_ctrl_resolve() (integer).
    results -- dictionary to populate with results. Keys are BSSIDs (MAC addresses) and values are dicts of data.

    Returns:
    0 on success or a negative error code.
    """
    msg = nlmsg_alloc()
    genlmsg_put(msg, 0, 0, driver_id, 0, NLM_F_DUMP,
                nl80211.NL80211_CMD_GET_SCAN, 0)
    nla_put_u32(msg, nl80211.NL80211_ATTR_IFINDEX, if_index)
    cb = libnl.handlers.nl_cb_alloc(libnl.handlers.NL_CB_DEFAULT)
    libnl.handlers.nl_cb_set(cb, libnl.handlers.NL_CB_VALID,
                             libnl.handlers.NL_CB_CUSTOM, callback_dump,
                             results)
    ret = nl_send_auto(sk, msg)
    if ret >= 0:
        try:
            ret = nl_recvmsgs(sk, cb)
        except NotImplementedError:
            pass
    return ret
Example #4
0
def do_scan_results(sk, if_index, driver_id, results):
    """Retrieve the results of a successful scan (SSIDs and data about them).

    This function does not require root privileges. It eventually calls a callback that actually decodes data about
    SSIDs but this function kicks that off.

    May exit the program (sys.exit()) if a fatal error occurs.

    Positional arguments:
    sk -- nl_sock class instance (from nl_socket_alloc()).
    if_index -- interface index (integer).
    driver_id -- nl80211 driver ID from genl_ctrl_resolve() (integer).
    results -- dictionary to populate with results. Keys are BSSIDs (MAC addresses) and values are dicts of data.

    Returns:
    0 on success or a negative error code.
    """
    msg = nlmsg_alloc()
    genlmsg_put(msg, 0, 0, driver_id, 0, NLM_F_DUMP, nl80211.NL80211_CMD_GET_SCAN, 0)
    nla_put_u32(msg, nl80211.NL80211_ATTR_IFINDEX, if_index)
    cb = libnl.handlers.nl_cb_alloc(libnl.handlers.NL_CB_DEFAULT)
    libnl.handlers.nl_cb_set(cb, libnl.handlers.NL_CB_VALID, libnl.handlers.NL_CB_CUSTOM, callback_dump, results)
    _LOGGER.debug('Sending NL80211_CMD_GET_SCAN...')
    ret = nl_send_auto(sk, msg)
    if ret >= 0:
        _LOGGER.debug('Retrieving NL80211_CMD_GET_SCAN response...')
        ret = nl_recvmsgs(sk, cb)
    return ret
Example #5
0
def genl_ctrl_probe_by_name(sk, name):
    """Look up generic Netlink family by family name querying the kernel directly.

    https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/ctrl.c#L237

    Directly query's the kernel for a given family name.

    Note: This API call differs from genl_ctrl_search_by_name in that it queries the kernel directly, allowing for
    module autoload to take place to resolve the family request. Using an nl_cache prevents that operation.

    Positional arguments:
    sk -- Generic Netlink socket (nl_sock class instance).
    name -- family name (bytes).

    Returns:
    Generic Netlink family `genl_family` class instance or None if no match was found.
    """
    ret = genl_family_alloc()
    if not ret:
        return None

    genl_family_set_name(ret, name)
    msg = nlmsg_alloc()
    orig = nl_socket_get_cb(sk)
    cb = nl_cb_clone(orig)
    genlmsg_put(msg, NL_AUTO_PORT, NL_AUTO_SEQ, GENL_ID_CTRL, 0, 0,
                CTRL_CMD_GETFAMILY, 1)
    nla_put_string(msg, CTRL_ATTR_FAMILY_NAME, name)
    nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, probe_response, ret)

    if nl_send_auto(sk, msg) < 0:
        return None
    if nl_recvmsgs(sk, cb) < 0:
        return None
    if wait_for_ack(
            sk
    ) < 0:  # If search was successful, request may be ACKed after data.
        return None

    if genl_family_get_id(ret) != 0:
        return ret
Example #6
0
    def mcast_handler(self):
        mcid = self.ok(0, genl_ctrl_resolve_grp, self.sk, b'NRC-NL-FAM',
                       b'nrc-log')
        ret = nl_socket_add_membership(self.sk, mcid)
        err = ctypes.c_int(1)
        results = ctypes.c_int(-1)
        cb = libnl.handlers.nl_cb_alloc(libnl.handlers.NL_CB_DEFAULT)
        libnl.handlers.nl_cb_set(cb, libnl.handlers.NL_CB_VALID,
                                 libnl.handlers.NL_CB_CUSTOM,
                                 self.callback_trigger, results)
        libnl.handlers.nl_cb_set(cb, libnl.handlers.NL_CB_SEQ_CHECK,
                                 libnl.handlers.NL_CB_CUSTOM,
                                 lambda *_: libnl.handlers.NL_OK, None)

        try:
            while True:
                ret = nl_recvmsgs(self.sk, cb)
                if self.recovery: break
        except KeyboardInterrupt:
            self.keyboard = True
        finally:
            nl_socket_drop_membership(self.sk, mcid)
Example #7
0
File: ctrl.py Project: 0x90/libnl
def genl_ctrl_probe_by_name(sk, name):
    """Look up generic Netlink family by family name querying the kernel directly.

    https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/ctrl.c#L237

    Directly query's the kernel for a given family name.

    Note: This API call differs from genl_ctrl_search_by_name in that it queries the kernel directly, allowing for
    module autoload to take place to resolve the family request. Using an nl_cache prevents that operation.

    Positional arguments:
    sk -- Generic Netlink socket (nl_sock class instance).
    name -- family name (bytes).

    Returns:
    Generic Netlink family `genl_family` class instance or None if no match was found.
    """
    ret = genl_family_alloc()
    if not ret:
        return None

    genl_family_set_name(ret, name)
    msg = nlmsg_alloc()
    orig = nl_socket_get_cb(sk)
    cb = nl_cb_clone(orig)
    genlmsg_put(msg, NL_AUTO_PORT, NL_AUTO_SEQ, GENL_ID_CTRL, 0, 0, CTRL_CMD_GETFAMILY, 1)
    nla_put_string(msg, CTRL_ATTR_FAMILY_NAME, name)
    nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, probe_response, ret)

    if nl_send_auto(sk, msg) < 0:
        return None
    if nl_recvmsgs(sk, cb) < 0:
        return None
    if wait_for_ack(sk) < 0:  # If search was successful, request may be ACKed after data.
        return None

    if genl_family_get_id(ret) != 0:
        return ret
    def _do_scan_trigger(self, if_index, driver_id, mcid):
        # Issue a scan request to the kernel and wait for it to reply with a
        # signal.
        #
        # This function issues NL80211_CMD_TRIGGER_SCAN which requires root
        # privileges. The way NL80211 works is first you issue
        # NL80211_CMD_TRIGGER_SCAN and wait for the kernel to signal that the
        # scan is done. When that signal occurs, data is not yet available. The
        # signal tells us if the scan was aborted or if it was successful (if
        # new scan results are waiting). This function handles that simple
        # signal. May exit the program (sys.exit()) if a fatal error occurs.
        #
        # Positional arguments:
        # self._nl_sock -- nl_sock class instance (from nl_socket_alloc()).
        # if_index -- interface index (integer).
        # driver_id -- nl80211 driver ID from genl_ctrl_resolve() (integer).
        # mcid -- nl80211 scanning group ID from genl_ctrl_resolve_grp()
        #                (integer).
        #
        # Returns:
        # 0 on success or a negative error code.

        # First get the "scan" membership group ID and join the socket to the
        # group.
        logger.debug('Joining group %d.', mcid)
        # Listen for results of scan requests (aborted or new results).
        ret = nl_socket_add_membership(self._nl_sock, mcid)
        if ret < 0:
            return ret

        # Build the message to be sent to the kernel.
        msg = nlmsg_alloc()
        # Setup which command to run.
        genlmsg_put(msg, 0, 0, driver_id, 0, 0,
                    nl80211.NL80211_CMD_TRIGGER_SCAN, 0)
        # Setup which interface to use.
        nla_put_u32(msg, nl80211.NL80211_ATTR_IFINDEX, if_index)
        ssids_to_scan = nlmsg_alloc()
        nla_put(ssids_to_scan, 1, 0, b'')  # Scan all SSIDs.
        # Setup what kind of scan to perform.
        nla_put_nested(msg, nl80211.NL80211_ATTR_SCAN_SSIDS, ssids_to_scan)

        # Setup the callbacks to be used for triggering the scan only.
        # Used as a mutable integer to be updated by the callback function.
        # Signals end of messages.
        err = ctypes.c_int(1)
        # Signals if the scan was successful (new results) or aborted, or not
        # started.
        results = ctypes.c_int(-1)
        cb = libnl.handlers.nl_cb_alloc(libnl.handlers.NL_CB_DEFAULT)
        libnl.handlers.nl_cb_set(cb, libnl.handlers.NL_CB_VALID,
                                 libnl.handlers.NL_CB_CUSTOM,
                                 self._callback_trigger, results)
        libnl.handlers.nl_cb_err(cb, libnl.handlers.NL_CB_CUSTOM,
                                 self._error_handler, err)
        libnl.handlers.nl_cb_set(cb, libnl.handlers.NL_CB_ACK,
                                 libnl.handlers.NL_CB_CUSTOM,
                                 self._ack_handler, err)
        libnl.handlers.nl_cb_set(cb, libnl.handlers.NL_CB_SEQ_CHECK,
                                 libnl.handlers.NL_CB_CUSTOM,
                                 lambda *_: libnl.handlers.NL_OK,
                                 None)  # Ignore sequence checking.

        # Now we send the message to the kernel, and retrieve the
        # acknowledgement. The kernel takes a few seconds to finish scanning for
        # access points.
        logger.debug('Sending NL80211_CMD_TRIGGER_SCAN...')
        ret = nl_send_auto(self._nl_sock, msg)
        if ret < 0:
            return ret
        while err.value > 0:
            logger.debug(
                'Retrieving NL80211_CMD_TRIGGER_SCAN acknowledgement...')
            ret = nl_recvmsgs(self._nl_sock, cb)
            if ret < 0:
                return ret
        if err.value < 0:
            logger.warning('Unknown error {0} ({1})'.format(
                err.value, errmsg[abs(err.value)]))

        # Block until the kernel is done scanning or aborted the scan.
        while results.value < 0:
            logger.debug(
                'Retrieving NL80211_CMD_TRIGGER_SCAN final response...')
            ret = nl_recvmsgs(self._nl_sock, cb)
            if ret < 0:
                return ret
        if results.value > 0:
            logger.warning('The kernel aborted the scan.')

        # Done, cleaning up.
        logger.debug('Leaving group %d.', mcid)
        # No longer need to receive multicast messages.
        return nl_socket_drop_membership(self._nl_sock, mcid)
Example #9
0
def do_scan_trigger(sk, if_index, driver_id, mcid):
    """Issue a scan request to the kernel and wait for it to reply with a signal.

    This function issues NL80211_CMD_TRIGGER_SCAN which requires root privileges.

    The way NL80211 works is first you issue NL80211_CMD_TRIGGER_SCAN and wait for the kernel to signal that the scan is
    done. When that signal occurs, data is not yet available. The signal tells us if the scan was aborted or if it was
    successful (if new scan results are waiting). This function handles that simple signal.

    May exit the program (sys.exit()) if a fatal error occurs.

    Positional arguments:
    sk -- nl_sock class instance (from nl_socket_alloc()).
    if_index -- interface index (integer).
    driver_id -- nl80211 driver ID from genl_ctrl_resolve() (integer).
    mcid -- nl80211 scanning group ID from genl_ctrl_resolve_grp() (integer).

    Returns:
    0 on success or a negative error code.
    """
    # First get the "scan" membership group ID and join the socket to the group.
    ret = nl_socket_add_membership(
        sk,
        mcid)  # Listen for results of scan requests (aborted or new results).
    if ret < 0:
        return ret

    # Build the message to be sent to the kernel.
    msg = nlmsg_alloc()
    genlmsg_put(msg, 0, 0, driver_id, 0, 0, nl80211.NL80211_CMD_TRIGGER_SCAN,
                0)  # Setup which command to run.
    nla_put_u32(msg, nl80211.NL80211_ATTR_IFINDEX,
                if_index)  # Setup which interface to use.
    ssids_to_scan = nlmsg_alloc()
    nla_put(ssids_to_scan, 1, 0, b'')  # Scan all SSIDs.
    nla_put_nested(msg, nl80211.NL80211_ATTR_SCAN_SSIDS,
                   ssids_to_scan)  # Setup what kind of scan to perform.

    # Setup the callbacks to be used for triggering the scan only.
    err = ctypes.c_int(
        1
    )  # Used as a mutable integer to be updated by the callback function. Signals end of messages.
    results = ctypes.c_int(
        -1
    )  # Signals if the scan was successful (new results) or aborted, or not started.
    cb = libnl.handlers.nl_cb_alloc(libnl.handlers.NL_CB_DEFAULT)
    libnl.handlers.nl_cb_set(cb, libnl.handlers.NL_CB_VALID,
                             libnl.handlers.NL_CB_CUSTOM, callback_trigger,
                             results)
    libnl.handlers.nl_cb_err(cb, libnl.handlers.NL_CB_CUSTOM, error_handler,
                             err)
    libnl.handlers.nl_cb_set(cb, libnl.handlers.NL_CB_ACK,
                             libnl.handlers.NL_CB_CUSTOM, ack_handler, err)
    libnl.handlers.nl_cb_set(cb, libnl.handlers.NL_CB_SEQ_CHECK,
                             libnl.handlers.NL_CB_CUSTOM,
                             lambda *_: libnl.handlers.NL_OK,
                             None)  # Ignore sequence checking.

    # Now we send the message to the kernel, and retrieve the acknowledgement. The kernel takes a few seconds to finish
    # scanning for access points.
    ret = nl_send_auto(sk, msg)
    if ret < 0:
        return ret
    while err.value > 0:
        ret = nl_recvmsgs(sk, cb)
        if ret < 0:
            return ret
    if err.value < 0:
        raise RuntimeError("Unknown Error")

    # Block until the kernel is done scanning or aborted the scan.
    while results.value < 0:
        ret = nl_recvmsgs(sk, cb)
        if ret < 0:
            return ret
    if results.value > 0:
        raise RuntimeError('The kernel aborted the scan.')

    # Done, cleaning up.
    return nl_socket_drop_membership(
        sk, mcid)  # No longer need to receive multicast messages.
Example #10
0
def do_scan_trigger(sk, if_index, driver_id, mcid):
    """Issue a scan request to the kernel and wait for it to reply with a signal.

    This function issues NL80211_CMD_TRIGGER_SCAN which requires root privileges.

    The way NL80211 works is first you issue NL80211_CMD_TRIGGER_SCAN and wait for the kernel to signal that the scan is
    done. When that signal occurs, data is not yet available. The signal tells us if the scan was aborted or if it was
    successful (if new scan results are waiting). This function handles that simple signal.

    May exit the program (sys.exit()) if a fatal error occurs.

    Positional arguments:
    sk -- nl_sock class instance (from nl_socket_alloc()).
    if_index -- interface index (integer).
    driver_id -- nl80211 driver ID from genl_ctrl_resolve() (integer).
    mcid -- nl80211 scanning group ID from genl_ctrl_resolve_grp() (integer).

    Returns:
    0 on success or a negative error code.
    """
    # First get the "scan" membership group ID and join the socket to the group.
    _LOGGER.debug('Joining group %d.', mcid)
    ret = nl_socket_add_membership(sk, mcid)  # Listen for results of scan requests (aborted or new results).
    if ret < 0:
        return ret

    # Build the message to be sent to the kernel.
    msg = nlmsg_alloc()
    genlmsg_put(msg, 0, 0, driver_id, 0, 0, nl80211.NL80211_CMD_TRIGGER_SCAN, 0)  # Setup which command to run.
    nla_put_u32(msg, nl80211.NL80211_ATTR_IFINDEX, if_index)  # Setup which interface to use.
    ssids_to_scan = nlmsg_alloc()
    nla_put(ssids_to_scan, 1, 0, b'')  # Scan all SSIDs.
    nla_put_nested(msg, nl80211.NL80211_ATTR_SCAN_SSIDS, ssids_to_scan)  # Setup what kind of scan to perform.

    # Setup the callbacks to be used for triggering the scan only.
    err = ctypes.c_int(1)  # Used as a mutable integer to be updated by the callback function. Signals end of messages.
    results = ctypes.c_int(-1)  # Signals if the scan was successful (new results) or aborted, or not started.
    cb = libnl.handlers.nl_cb_alloc(libnl.handlers.NL_CB_DEFAULT)
    libnl.handlers.nl_cb_set(cb, libnl.handlers.NL_CB_VALID, libnl.handlers.NL_CB_CUSTOM, callback_trigger, results)
    libnl.handlers.nl_cb_err(cb, libnl.handlers.NL_CB_CUSTOM, error_handler, err)
    libnl.handlers.nl_cb_set(cb, libnl.handlers.NL_CB_ACK, libnl.handlers.NL_CB_CUSTOM, ack_handler, err)
    libnl.handlers.nl_cb_set(cb, libnl.handlers.NL_CB_SEQ_CHECK, libnl.handlers.NL_CB_CUSTOM,
                             lambda *_: libnl.handlers.NL_OK, None)  # Ignore sequence checking.

    # Now we send the message to the kernel, and retrieve the acknowledgement. The kernel takes a few seconds to finish
    # scanning for access points.
    _LOGGER.debug('Sending NL80211_CMD_TRIGGER_SCAN...')
    ret = nl_send_auto(sk, msg)
    if ret < 0:
        return ret
    while err.value > 0:
        _LOGGER.debug('Retrieving NL80211_CMD_TRIGGER_SCAN acknowledgement...')
        ret = nl_recvmsgs(sk, cb)
        if ret < 0:
            return ret
    if err.value < 0:
        error('Unknown error {0} ({1})'.format(err.value, errmsg[abs(err.value)]))

    # Block until the kernel is done scanning or aborted the scan.
    while results.value < 0:
        _LOGGER.debug('Retrieving NL80211_CMD_TRIGGER_SCAN final response...')
        ret = nl_recvmsgs(sk, cb)
        if ret < 0:
            return ret
    if results.value > 0:
        error('The kernel aborted the scan.')

    # Done, cleaning up.
    _LOGGER.debug('Leaving group %d.', mcid)
    return nl_socket_drop_membership(sk, mcid)  # No longer need to receive multicast messages.