Beispiel #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
Beispiel #3
0
def ncsi_set_interface(ifindex, package, channel):

    sk = nl_socket_alloc()
    ret = genl_connect(sk)
    if ret < 0:
        return ret

    driver_id = genl_ctrl_resolve(sk, b'NCSI')
    if driver_id < 0:
        return driver_id

    msg = nlmsg_alloc()
    if package or package and channel:
        genlmsg_put(msg, 0, 0, driver_id, 0, 0, NCSI_CMD_SET_INTERFACE, 0)
        ret = nla_put_u32(msg, NCSI_ATTR_PACKAGE_ID, int(package))
        if channel:
            ret = nla_put_u32(msg, NCSI_ATTR_CHANNEL_ID, int(channel))
    else:
        genlmsg_put(msg, 0, 0, driver_id, 0, 0, NCSI_CMD_CLEAR_INTERFACE, 0)
    ret = nla_put_u32(msg, NCSI_ATTR_IFINDEX, ifindex)

    nl_socket_modify_cb(sk, NL_CB_VALID, NL_CB_CUSTOM, dump_callback, None)

    ret = nl_send_auto(sk, msg)
    if ret < 0:
        print("Failed to send message: {}".format(ret))
        return ret

    ret = nl_recvmsgs_default(sk)  # blocks
    if ret < 0:
        reason = errmsg[abs(ret)]
        print("recvmsg returned {}, {}".format(ret, reason))
Beispiel #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
Beispiel #5
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
Beispiel #6
0
    def update_iface_details(self, cmd):
        # Send a command specified by CMD to the kernel and attach a callback to
        # process the returned values into our own datastructure

        self._nl_sock = nl_socket_alloc()  # Creates an `nl_sock` instance.
        # Create file descriptor and bind socket.
        ret = genl_connect(self._nl_sock)
        if ret < 0:
            reason = errmsg[abs(ret)]
            logger.error('genl_connect() returned {0} ({1})'.format(
                ret, reason))
            return {}

        # Now get the nl80211 driver ID. Handle errors here.
        # Find the nl80211 driver ID.
        driver_id = genl_ctrl_resolve(self._nl_sock, b'nl80211')
        if driver_id < 0:
            reason = errmsg[abs(driver_id)]
            logger.error('genl_ctrl_resolve() returned {0} ({1})'.format(
                driver_id, reason))
            return {}

        # Setup the Generic Netlink message.
        msg = nlmsg_alloc()  # Allocate a message.
        if self.if_idx == None:
            # Ask kernel to send info for all wireless interfaces.
            genlmsg_put(msg, 0, 0, driver_id, 0, NLM_F_DUMP,
                        nl80211.NL80211_CMD_GET_INTERFACE, 0)
        else:
            genlmsg_put(msg, 0, 0, driver_id, 0, NLM_F_DUMP, cmd, 0)
            # This is the interface we care about.
            nla_put_u32(msg, nl80211.NL80211_ATTR_IFINDEX, self.if_idx)
            #nla_put_u32(msg, nl80211.NL80211_ATTR_MAC, 2199023255552)

        # Add the callback function to the self._nl_sock.
        nl_socket_modify_cb(self._nl_sock, NL_CB_VALID, NL_CB_CUSTOM,
                            self._iface_callback, False)

        # Now send the message to the kernel, and get its response,
        # automatically calling the callback.
        ret = nl_send_auto(self._nl_sock, msg)
        if ret < 0:
            reason = errmsg[abs(ret)]
            logger.error('nl_send_auto() returned {0} ({1})'.format(
                ret, reason))
            return {}
        logger.debug('Sent {0} bytes to the kernel.'.format(ret))
        # Blocks until the kernel replies. Usually it's instant.
        ret = nl_recvmsgs_default(self._nl_sock)
        if ret < 0:
            reason = errmsg[abs(ret)]
            logger.error('nl_recvmsgs_default() returned {0} ({1})'.format(
                ret, reason))
            return {}
def main():
    """Main function called upon script execution."""
    # First get the wireless interface index.
    if OPTIONS['<interface>']:
        pack = struct.pack('16sI', OPTIONS['<interface>'].encode('ascii'), 0)
        sk = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        try:
            info = struct.unpack('16sI', fcntl.ioctl(sk.fileno(), 0x8933, pack))
        except OSError:
            return error('Wireless interface {0} does not exist.'.format(OPTIONS['<interface>']))
        finally:
            sk.close()
        if_index = int(info[1])
    else:
        if_index = -1

    # Then open a socket to the kernel. Same one used for sending and receiving.
    sk = nl_socket_alloc()  # Creates an `nl_sock` instance.
    ret = genl_connect(sk)  # Create file descriptor and bind socket.
    if ret < 0:
        reason = errmsg[abs(ret)]
        return error('genl_connect() returned {0} ({1})'.format(ret, reason))

    # Now get the nl80211 driver ID. Handle errors here.
    driver_id = genl_ctrl_resolve(sk, b'nl80211')  # Find the nl80211 driver ID.
    if driver_id < 0:
        reason = errmsg[abs(driver_id)]
        return error('genl_ctrl_resolve() returned {0} ({1})'.format(driver_id, reason))

    # Setup the Generic Netlink message.
    msg = nlmsg_alloc()  # Allocate a message.
    if OPTIONS['<interface>']:
        genlmsg_put(msg, 0, 0, driver_id, 0, 0, nl80211.NL80211_CMD_GET_INTERFACE, 0)  # Tell kernel: send iface info.
        nla_put_u32(msg, nl80211.NL80211_ATTR_IFINDEX, if_index)  # This is the interface we care about.
    else:
        # Ask kernel to send info for all wireless interfaces.
        genlmsg_put(msg, 0, 0, driver_id, 0, NLM_F_DUMP, nl80211.NL80211_CMD_GET_INTERFACE, 0)

    # Add the callback function to the nl_sock.
    has_printed = list()
    nl_socket_modify_cb(sk, NL_CB_VALID, NL_CB_CUSTOM, callback, has_printed)

    # Now send the message to the kernel, and get its response, automatically calling the callback.
    ret = nl_send_auto(sk, msg)
    if ret < 0:
        reason = errmsg[abs(ret)]
        return error('nl_send_auto() returned {0} ({1})'.format(ret, reason))
    print('Sent {0} bytes to the kernel.'.format(ret))
    ret = nl_recvmsgs_default(sk)  # Blocks until the kernel replies. Usually it's instant.
    if ret < 0:
        reason = errmsg[abs(ret)]
        return error('nl_recvmsgs_default() returned {0} ({1})'.format(ret, reason))
Beispiel #8
0
def ncsi_get_info(ifindex, package):

    # Open socket to kernel
    sk = nl_socket_alloc()
    ret = genl_connect(sk)
    if ret < 0:
        print("Failed to open socket")
        return -1

    # Find NCSI
    driver_id = genl_ctrl_resolve(sk, b'NCSI')
    if driver_id < 0:
        print("Could not resolve NCSI")
        return -1

    # Setup up a Generic Netlink message
    msg = nlmsg_alloc()
    if package is None:
        ret = genlmsg_put(msg, 0, 0, driver_id, 0, NLM_F_DUMP,
                          NCSI_CMD_PKG_INFO, 0)
    else:
        ret = genlmsg_put(msg, 0, 0, driver_id, 0, 0, NCSI_CMD_PKG_INFO, 0)
        nla_put_u32(msg, NCSI_ATTR_PACKAGE_ID, int(package))

    if ret < 0:
        reason = errmsg[abs(ret)]
        print("genlmsg_put returned {}, {}".format(ret, reason))
        return -1

    nla_put_u32(msg, NCSI_ATTR_IFINDEX, ifindex)

    # Add a callback function to the socket
    nl_socket_modify_cb(sk, NL_CB_VALID, NL_CB_CUSTOM, info_callback, None)

    ret = nl_send_auto(sk, msg)
    if ret < 0:
        print("Failed to send message: {}".format(ret))
        return ret
    ret = nl_recvmsgs_default(sk)  # blocks
    if ret < 0:
        reason = errmsg[abs(ret)]
        print("recvmsg returned {}, {}".format(ret, reason))
Beispiel #9
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
Beispiel #10
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
Beispiel #11
0
def test_nl_cache_ops_associate_safe():
    r"""C code to test against.

    // gcc a.c $(pkg-config --cflags --libs libnl-genl-3.0) && ./a.out
    #include <netlink/genl/family.h>
    struct nl_sock {
        struct sockaddr_nl s_local; struct sockaddr_nl s_peer; int s_fd; int s_proto; unsigned int s_seq_next;
        unsigned int s_seq_expect; int s_flags; struct nl_cb *s_cb; size_t s_bufsize;
    };
    struct nl_cache_ops {
        char *co_name; int co_hdrsize; int co_protocol; int co_hash_size; unsigned int co_flags; unsigned int co_refcnt;
        struct nl_af_group *co_groups; int (*co_request_update)(struct nl_cache*, struct nl_sock*);
        int (*co_msg_parser)(struct nl_cache_ops*, struct sockaddr_nl*, struct nlmsghdr*, struct nl_parser_param*);
        int (*co_event_filter)(struct nl_cache*, struct nl_object *obj);
        int (*co_include_event)(struct nl_cache *cache, struct nl_object *obj, change_func_t change_cb, void *data);
        void (*reserved_1)(void); void (*reserved_2)(void); void (*reserved_3)(void); void (*reserved_4)(void);
        void (*reserved_5)(void); void (*reserved_6)(void); void (*reserved_7)(void); void (*reserved_8)(void);
        struct nl_object_ops *co_obj_ops;
    };
    struct nl_object_ops { char *oo_name; size_t oo_size; uint32_t oo_id_attrs; };
    struct nl_msgtype { int mt_id; int mt_act; char *mt_name; };
    static int callback(struct nl_sock *sk, struct nl_msg *msg) {
        struct nlmsghdr *nlh = nlmsg_hdr(msg);
        printf("%d == nlh.nlmsg_len\n", nlh->nlmsg_len);
        printf("%d == nlh.nlmsg_type\n", nlh->nlmsg_type);
        printf("%d == nlh.nlmsg_flags\n", nlh->nlmsg_flags);
        struct nl_cache_ops *ops = nl_cache_ops_associate_safe(NETLINK_GENERIC, nlh->nlmsg_type);
        printf("'%s' == ops.co_name\n", ops->co_name);
        printf("%d == ops.co_hdrsize\n", ops->co_hdrsize);
        printf("%d == ops.co_protocol\n", ops->co_protocol);
        printf("%d == ops.co_hash_size\n", ops->co_hash_size);
        printf("%d == ops.co_flags\n", ops->co_flags);
        printf("'%s' == ops.co_obj_ops.oo_name\n", ops->co_obj_ops->oo_name);
        printf("%d == ops.co_obj_ops.oo_size\n", ops->co_obj_ops->oo_size);
        printf("%d == ops.co_obj_ops.oo_id_attrs\n", ops->co_obj_ops->oo_id_attrs);
        printf("%d == nlmsg_attrlen(nlh, ops.co_hdrsize)\n", nlmsg_attrlen(nlh, ops->co_hdrsize));
        struct nl_msgtype *mt = nl_msgtype_lookup(ops, nlh->nlmsg_type);
        printf("%d == mt.mt_id\n", mt->mt_id);
        printf("%d == mt.mt_act\n", mt->mt_act);
        printf("'%s' == mt.mt_name\n", mt->mt_name);
        return NL_STOP;
    }
    int main() {
        struct nl_sock *sk = nl_socket_alloc();
        nl_cb_overwrite_send(sk->s_cb, callback);

        struct genl_family *ret = genl_family_alloc();
        genl_family_set_name(ret, "nl80211");
        struct nl_msg *msg = nlmsg_alloc();
        genlmsg_put(msg, NL_AUTO_PORT, NL_AUTO_SEQ, GENL_ID_CTRL, 0, 0, CTRL_CMD_GETFAMILY, 1);
        printf("%d == nl_send_auto(sk, msg)\n", nl_send_auto(sk, msg));
        return 0;
    }
    // Expected output:
    // 20 == nlh.nlmsg_len
    // 16 == nlh.nlmsg_type
    // 5 == nlh.nlmsg_flags
    // 'genl/family' == ops.co_name
    // 4 == ops.co_hdrsize
    // 16 == ops.co_protocol
    // 0 == ops.co_hash_size
    // 0 == ops.co_flags
    // 'genl/family' == ops.co_obj_ops.oo_name
    // 80 == ops.co_obj_ops.oo_size
    // 1 == ops.co_obj_ops.oo_id_attrs
    // 0 == nlmsg_attrlen(nlh, ops.co_hdrsize)
    // 16 == mt.mt_id
    // 0 == mt.mt_act
    // 'nlctrl' == mt.mt_name
    // 2 == nl_send_auto(sk, msg)
    """
    called = list()

    def callback(_, msg_):
        nlh = nlmsg_hdr(msg_)
        assert 20 == nlh.nlmsg_len
        assert 16 == nlh.nlmsg_type
        assert 5 == nlh.nlmsg_flags
        ops = nl_cache_ops_associate_safe(NETLINK_GENERIC, nlh.nlmsg_type)
        assert 'genl/family' == ops.co_name
        assert 4 == ops.co_hdrsize
        assert 16 == ops.co_protocol
        assert 0 == ops.co_hash_size
        assert 0 == ops.co_flags
        assert 'genl/family' == ops.co_obj_ops.oo_name
        assert 80 == ops.co_obj_ops.oo_size
        assert 1 == ops.co_obj_ops.oo_id_attrs
        assert 0 == nlmsg_attrlen(nlh, ops.co_hdrsize)
        mt = nl_msgtype_lookup(ops, nlh.nlmsg_type)
        assert 16 == mt.mt_id
        assert 0 == mt.mt_act
        assert 'nlctrl' == mt.mt_name
        called.append(True)
        return NL_STOP

    sk = nl_socket_alloc()
    nl_cb_overwrite_send(sk.s_cb, callback)
    ret = genl_family_alloc()
    genl_family_set_name(ret, 'nl80211')
    msg = nlmsg_alloc()
    genlmsg_put(msg, NL_AUTO_PORT, NL_AUTO_SEQ, GENL_ID_CTRL, 0, 0,
                CTRL_CMD_GETFAMILY, 1)
    assert 2 == nl_send_auto(sk, msg)
    assert [True] == called
Beispiel #12
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.
Beispiel #13
0
def test_ctrl_cmd_getfamily_hex_dump(log):
    r"""C code to test against.

    // gcc a.c $(pkg-config --cflags --libs libnl-genl-3.0) && NLDBG=4 ./a.out
    #include <netlink/msg.h>
    struct nl_sock {
        struct sockaddr_nl s_local; struct sockaddr_nl s_peer; int s_fd; int s_proto; unsigned int s_seq_next;
        unsigned int s_seq_expect; int s_flags; struct nl_cb *s_cb; size_t s_bufsize;
    };
    static void prefix_line(FILE *ofd, int prefix) { int i; for (i = 0; i < prefix; i++) fprintf(ofd, "  "); }
    static inline void dump_hex(FILE *ofd, char *start, int len, int prefix) {
        int i, a, c, limit; char ascii[21] = {0}; limit = 16 - (prefix * 2); prefix_line(ofd, prefix);
        fprintf(ofd, "    ");
        for (i = 0, a = 0, c = 0; i < len; i++) {
            int v = *(uint8_t *) (start + i); fprintf(ofd, "%02x ", v); ascii[a++] = isprint(v) ? v : '.';
            if (++c >= limit) {
                fprintf(ofd, "%s\n", ascii);
                if (i < (len - 1)) { prefix_line(ofd, prefix); fprintf(ofd, "    "); }
                a = c = 0;
                memset(ascii, 0, sizeof(ascii));
            }
        }
        if (c != 0) { for (i = 0; i < (limit - c); i++) fprintf(ofd, "   "); fprintf(ofd, "%s\n", ascii); }
    }
    struct ucred { pid_t pid; uid_t uid; gid_t gid; };
    struct nl_msg {
        int nm_protocol; int nm_flags; struct sockaddr_nl nm_src; struct sockaddr_nl nm_dst; struct ucred nm_creds;
        struct nlmsghdr *nm_nlh; size_t nm_size; int nm_refcnt;
    };
    static int callback_send(struct nl_sock *sk, struct nl_msg *msg) {
        printf("%d == msg.nm_protocol\n", msg->nm_protocol);
        printf("%d == msg.nm_flags\n", msg->nm_flags);
        printf("%d == msg.nm_src.nl_family\n", msg->nm_src.nl_family);
        printf("%d == msg.nm_src.nl_pid\n", msg->nm_src.nl_pid);
        printf("%d == msg.nm_src.nl_groups\n", msg->nm_src.nl_groups);
        printf("%d == msg.nm_dst.nl_family\n", msg->nm_dst.nl_family);
        printf("%d == msg.nm_dst.nl_pid\n", msg->nm_dst.nl_pid);
        printf("%d == msg.nm_dst.nl_groups\n", msg->nm_dst.nl_groups);
        printf("%d == msg.nm_creds.pid\n", msg->nm_creds.pid);
        printf("%d == msg.nm_creds.uid\n", msg->nm_creds.uid);
        printf("%d == msg.nm_creds.gid\n", msg->nm_creds.gid);
        printf("%d == msg.nm_nlh.nlmsg_type\n", msg->nm_nlh->nlmsg_type);
        printf("%d == msg.nm_nlh.nlmsg_flags\n", msg->nm_nlh->nlmsg_flags);
        printf("%d == msg.nm_nlh.nlmsg_pid\n", msg->nm_nlh->nlmsg_pid);
        printf("%d == msg.nm_size\n", msg->nm_size);
        printf("%d == msg.nm_refcnt\n", msg->nm_refcnt);
        struct iovec iov = { .iov_base = (void *) nlmsg_hdr(msg), .iov_len = nlmsg_hdr(msg)->nlmsg_len, };
        dump_hex(stdout, iov.iov_base, iov.iov_len, 0);
        return nl_send_iovec(sk, msg, &iov, 1);
    }
    static int callback_recv(struct nl_sock *sk, struct sockaddr_nl *nla, unsigned char **buf, struct ucred **creds) {
        int n = nl_recv(sk, nla, buf, creds);
        dump_hex(stdout, (void *) *buf, n, 0);
        return n;
    }
    static int callback_recv_msg(struct nl_msg *msg, void *arg) {
        printf("%d == msg.nm_protocol\n", msg->nm_protocol);
        printf("%d == msg.nm_flags\n", msg->nm_flags);
        printf("%d == msg.nm_src.nl_family\n", msg->nm_src.nl_family);
        printf("%d == msg.nm_src.nl_pid\n", msg->nm_src.nl_pid);
        printf("%d == msg.nm_src.nl_groups\n", msg->nm_src.nl_groups);
        printf("%d == msg.nm_dst.nl_family\n", msg->nm_dst.nl_family);
        printf("%d == msg.nm_dst.nl_pid\n", msg->nm_dst.nl_pid);
        printf("%d == msg.nm_dst.nl_groups\n", msg->nm_dst.nl_groups);
        printf("%d == msg.nm_creds.pid\n", msg->nm_creds.pid);
        printf("%d == msg.nm_creds.uid\n", msg->nm_creds.uid);
        printf("%d == msg.nm_creds.gid\n", msg->nm_creds.gid);
        printf("%d == msg.nm_nlh.nlmsg_type\n", msg->nm_nlh->nlmsg_type);
        printf("%d == msg.nm_nlh.nlmsg_flags\n", msg->nm_nlh->nlmsg_flags);
        printf("%d == msg.nm_nlh.nlmsg_pid\n", msg->nm_nlh->nlmsg_pid);
        printf("%d == msg.nm_size\n", msg->nm_size);
        printf("%d == msg.nm_refcnt\n", msg->nm_refcnt);
        dump_hex(stdout, (char *) msg->nm_nlh, nlmsg_datalen(msg->nm_nlh), 0);
        return NL_OK;
    }
    int main() {
        struct nl_sock *sk = nl_socket_alloc();
        nl_cb_overwrite_send(sk->s_cb, callback_send);
        nl_cb_overwrite_recv(sk->s_cb, callback_recv);
        printf("%d == genl_connect(sk)\n", genl_connect(sk));
        struct genl_family *ret = (struct genl_family *) genl_family_alloc();
        genl_family_set_name(ret, "nl80211");
        struct nl_msg *msg = nlmsg_alloc();
        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, "nl80211");
        nl_socket_modify_cb(sk, NL_CB_VALID, NL_CB_CUSTOM, callback_recv_msg, NULL);
        printf("%d == nl_send_auto(sk, msg)\n", nl_send_auto(sk, msg));
        printf("%d == nl_recvmsgs_default(sk)\n", nl_recvmsgs_default(sk));
        nl_socket_free(sk);
        return 0;
    }
    // Expected output (trimmed):
    // nl_cache_mngt_register: Registered cache operations genl/family
    // 0 == genl_connect(sk)
    //  nl_object_alloc: Allocated new object 0x2b50b8
    // __nlmsg_alloc: msg 0x2b5110: Allocated new message, maxlen=4096
    // nlmsg_put: msg 0x2b5110: Added netlink header type=16, flags=0, pid=0, seq=0
    // nlmsg_reserve: msg 0x2b5110: Reserved 4 (4) bytes, pad=4, nlmsg_len=20
    // genlmsg_put: msg 0x2b5110: Added generic netlink header cmd=3 version=1
    // nla_reserve: msg 0x2b5110: attr <0x2b5164> 2: Reserved 12 (8) bytes at offset +4 nlmsg_len=32
    // nla_put: msg 0x2b5110: attr <0x2b5164> 2: Wrote 8 bytes at offset +4
    // 16 == msg.nm_protocol
    // 0 == msg.nm_flags
    // 0 == msg.nm_src.nl_family
    // 0 == msg.nm_src.nl_pid
    // 0 == msg.nm_src.nl_groups
    // 0 == msg.nm_dst.nl_family
    // 0 == msg.nm_dst.nl_pid
    // 0 == msg.nm_dst.nl_groups
    // 0 == msg.nm_creds.pid
    // 0 == msg.nm_creds.uid
    // 0 == msg.nm_creds.gid
    // 16 == msg.nm_nlh.nlmsg_type
    // 5 == msg.nm_nlh.nlmsg_flags
    // 14272 == msg.nm_nlh.nlmsg_pid
    // 4096 == msg.nm_size
    // 1 == msg.nm_refcnt
    //     20 00 00 00 10 00 05 00 af aa f6 54 c0 37 00 00  ..........T.7..
    //     03 01 00 00 0c 00 02 00 6e 6c 38 30 32 31 31 00 ........nl80211.
    // nl_sendmsg: sent 32 bytes
    // 32 == nl_send_auto(sk, msg)
    // recvmsgs: Attempting to read from 0x2b5080
    //     2c 07 00 00 10 00 00 00 af aa f6 54 c0 37 00 00 ,..........T.7..
    //     01 02 00 00 0c 00 02 00 6e 6c 38 30 32 31 31 00 ........nl80211.
    //     06 00 01 00 16 00 00 00 08 00 03 00 01 00 00 00 ................
    //     08 00 04 00 00 00 00 00 08 00 05 00 d5 00 00 00 ................
    //     6c 06 06 00 14 00 01 00 08 00 01 00 01 00 00 00 l...............
    //     08 00 02 00 0e 00 00 00 14 00 02 00 08 00 01 00 ................
    //     <trimmed>
    //     63 6f 6e 66 69 67 00 00 18 00 02 00 08 00 02 00 config..........
    //     04 00 00 00 09 00 01 00 73 63 61 6e 00 00 00 00 ........scan....
    //     1c 00 03 00 08 00 02 00 05 00 00 00 0f 00 01 00 ................
    //     72 65 67 75 6c 61 74 6f 72 79 00 00 18 00 04 00 regulatory......
    //     08 00 02 00 06 00 00 00 09 00 01 00 6d 6c 6d 65 ............mlme
    //     00 00 00 00 18 00 05 00 08 00 02 00 07 00 00 00 ................
    //     0b 00 01 00 76 65 6e 64 6f 72 00 00             ....vendor..
    // recvmsgs: recvmsgs(0x2b5080): Read 1836 bytes
    // recvmsgs: recvmsgs(0x2b5080): Processing valid message...
    // __nlmsg_alloc: msg 0x2ba160: Allocated new message, maxlen=1836
    // 16 == msg.nm_protocol
    // 0 == msg.nm_flags
    // 16 == msg.nm_src.nl_family
    // 0 == msg.nm_src.nl_pid
    // 0 == msg.nm_src.nl_groups
    // 0 == msg.nm_dst.nl_family
    // 0 == msg.nm_dst.nl_pid
    // 0 == msg.nm_dst.nl_groups
    // 0 == msg.nm_creds.pid
    // 0 == msg.nm_creds.uid
    // 0 == msg.nm_creds.gid
    // 16 == msg.nm_nlh.nlmsg_type
    // 0 == msg.nm_nlh.nlmsg_flags
    // 14272 == msg.nm_nlh.nlmsg_pid
    // 1836 == msg.nm_size
    // 1 == msg.nm_refcnt
    //     2c 07 00 00 10 00 00 00 af aa f6 54 c0 37 00 00 ,..........T.7..
    //     01 02 00 00 0c 00 02 00 6e 6c 38 30 32 31 31 00 ........nl80211.
    //     06 00 01 00 16 00 00 00 08 00 03 00 01 00 00 00 ................
    //     08 00 04 00 00 00 00 00 08 00 05 00 d5 00 00 00 ................
    //     6c 06 06 00 14 00 01 00 08 00 01 00 01 00 00 00 l...............
    //     08 00 02 00 0e 00 00 00 14 00 02 00 08 00 01 00 ................
    //     <trimmed>
    //     63 6f 6e 66 69 67 00 00 18 00 02 00 08 00 02 00 config..........
    //     04 00 00 00 09 00 01 00 73 63 61 6e 00 00 00 00 ........scan....
    //     1c 00 03 00 08 00 02 00 05 00 00 00 0f 00 01 00 ................
    //     72 65 67 75 6c 61 74 6f 72 79 00 00 18 00 04 00 regulatory......
    //     08 00 02 00 06 00 00 00 09 00 01 00 6d 6c 6d 65 ............mlme
    //     00 00 00 00 18 00 05 00 08 00 02 00             ............
    // nlmsg_free: Returned message reference 0x2ba160, 0 remaining
    // nlmsg_free: msg 0x2ba160: Freed
    // 0 == nl_recvmsgs_default(sk)
    // nl_cache_mngt_unregister: Unregistered cache operations genl/family
    """
    def callback_send(sk, msg):
        assert 16 == msg.nm_protocol
        assert 0 == msg.nm_flags
        assert 0 == msg.nm_src.nl_family
        assert 0 == msg.nm_src.nl_pid
        assert 0 == msg.nm_src.nl_groups
        assert 0 == msg.nm_dst.nl_family
        assert 0 == msg.nm_dst.nl_pid
        assert 0 == msg.nm_dst.nl_groups
        assert msg.nm_creds is None
        assert 16 == msg.nm_nlh.nlmsg_type
        assert 5 == msg.nm_nlh.nlmsg_flags
        assert 100 < msg.nm_nlh.nlmsg_pid
        assert 1 == msg.nm_refcnt
        hdr = nlmsg_hdr(msg)
        iov = hdr.bytearray[:hdr.nlmsg_len]
        dump_hex(logging.getLogger().debug, iov, len(iov), 0)
        return nl_send_iovec(sk, msg, iov, 1)

    def callback_recv(sk, nla, buf, creds):
        n = nl_recv(sk, nla, buf, creds)
        dump_hex(logging.getLogger().debug, buf, len(buf), 0)
        return n

    def callback_recv_msg(msg, _):
        assert 16 == msg.nm_protocol
        assert 0 == msg.nm_flags
        assert 16 == msg.nm_src.nl_family
        assert 0 == msg.nm_src.nl_pid
        assert 0 == msg.nm_src.nl_groups
        assert 0 == msg.nm_dst.nl_family
        assert 0 == msg.nm_dst.nl_pid
        assert 0 == msg.nm_dst.nl_groups
        assert msg.nm_creds is None
        assert 16 == msg.nm_nlh.nlmsg_type
        assert 0 == msg.nm_nlh.nlmsg_flags
        assert 100 < msg.nm_nlh.nlmsg_pid
        assert 1000 < msg.nm_size
        assert 1 == msg.nm_refcnt
        dump_hex(logging.getLogger().debug, msg.nm_nlh.bytearray, nlmsg_datalen(msg.nm_nlh), 0)
        return NL_OK

    del log[:]
    sk_main = nl_socket_alloc()
    nl_cb_overwrite_send(sk_main.s_cb, callback_send)
    nl_cb_overwrite_recv(sk_main.s_cb, callback_recv)
    genl_connect(sk_main)
    ret = genl_family_alloc()
    genl_family_set_name(ret, b'nl80211')
    msg_main = nlmsg_alloc()
    genlmsg_put(msg_main, NL_AUTO_PORT, NL_AUTO_SEQ, GENL_ID_CTRL, 0, 0, CTRL_CMD_GETFAMILY, 1)
    nla_put_string(msg_main, CTRL_ATTR_FAMILY_NAME, b'nl80211')
    nl_socket_modify_cb(sk_main, NL_CB_VALID, NL_CB_CUSTOM, callback_recv_msg, None)
    assert 32 == nl_send_auto(sk_main, msg_main)
    assert 0 == nl_recvmsgs_default(sk_main)
    nl_socket_free(sk_main)

    assert match('nl_object_alloc: Allocated new object 0x[a-f0-9]+', log, True)
    assert match('nlmsg_alloc: msg 0x[a-f0-9]+: Allocated new message, maxlen=4096', log, True)
    assert match('nlmsg_put: msg 0x[a-f0-9]+: Added netlink header type=16, flags=0, pid=0, seq=0', log, True)
    assert match('nlmsg_reserve: msg 0x[a-f0-9]+: Reserved 4 \(4\) bytes, pad=4, nlmsg_len=20', log, True)
    assert match('genlmsg_put: msg 0x[a-f0-9]+: Added generic netlink header cmd=3 version=1', log, True)
    assert match(
        'nla_reserve: msg 0x[a-f0-9]+: attr <0x[a-f0-9]+> 2: Reserved 12 \(8\) bytes at offset \+4 nlmsg_len=32',
        log, True)
    assert match('nla_put: msg 0x[a-f0-9]+: attr <0x[a-f0-9]+> 2: Wrote 8 bytes at offset \+4', log, True)

    assert match('dump_hex:     20 00 00 00 10 00 05 00 .. .. .. .. .. .. 00 00  ...............', log, True)
    assert match('dump_hex:     03 01 00 00 0c 00 02 00 6e 6c 38 30 32 31 31 00 ........nl80211.', log)

    assert match('nl_sendmsg: sent 32 bytes', log)
    assert match('recvmsgs: Attempting to read from 0x[a-f0-9]+', log, True)

    assert match('dump_hex:     .. .. 00 00 10 00 00 00 .. .. .. .. .. .. 00 00 ................', log, True)
    assert match('dump_hex:     01 02 00 00 0c 00 02 00 6e 6c 38 30 32 31 31 00 ........nl80211.', log)
    assert match('dump_hex:     06 00 01 00 .. 00 00 00 08 00 03 00 01 00 00 00 ................', log, True)
    assert match('dump_hex:     08 00 04 00 00 00 00 00 08 00 05 00 .. 00 00 00 ................', log, True)

    for i in range(len(log)):
        if re.match(r'recvmsgs: recvmsgs\(0x[a-f0-9]+\): Read \d{4,} bytes', log[i]):
            log = log[i:]
            break

    assert match('recvmsgs: recvmsgs\(0x[a-f0-9]+\): Read \d{3,} bytes', log, True)
    assert match('recvmsgs: recvmsgs\(0x[a-f0-9]+\): Processing valid message...', log, True)
    assert match('nlmsg_alloc: msg 0x[a-f0-9]+: Allocated new message, maxlen=\d{3,}', log, True)

    assert match('dump_hex:     .. .. 00 00 10 00 00 00 .. .. .. .. .. .. 00 00 ................', log, True)
    assert match('dump_hex:     01 02 00 00 0c 00 02 00 6e 6c 38 30 32 31 31 00 ........nl80211.', log)
    assert match('dump_hex:     06 00 01 00 .. 00 00 00 08 00 03 00 01 00 00 00 ................', log, True)
    assert match('dump_hex:     08 00 04 00 00 00 00 00 08 00 05 00 .. 00 00 00 ................', log, True)

    while log and log[0].startswith('dump_hex:'):
        log.pop(0)
    assert not log
Beispiel #14
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.
Beispiel #15
0
def test_nl_cache_ops_associate_safe():
    r"""C code to test against.

    // gcc a.c $(pkg-config --cflags --libs libnl-genl-3.0) && ./a.out
    #include <netlink/genl/family.h>
    struct nl_sock {
        struct sockaddr_nl s_local; struct sockaddr_nl s_peer; int s_fd; int s_proto; unsigned int s_seq_next;
        unsigned int s_seq_expect; int s_flags; struct nl_cb *s_cb; size_t s_bufsize;
    };
    struct nl_cache_ops {
        char *co_name; int co_hdrsize; int co_protocol; int co_hash_size; unsigned int co_flags; unsigned int co_refcnt;
        struct nl_af_group *co_groups; int (*co_request_update)(struct nl_cache*, struct nl_sock*);
        int (*co_msg_parser)(struct nl_cache_ops*, struct sockaddr_nl*, struct nlmsghdr*, struct nl_parser_param*);
        int (*co_event_filter)(struct nl_cache*, struct nl_object *obj);
        int (*co_include_event)(struct nl_cache *cache, struct nl_object *obj, change_func_t change_cb, void *data);
        void (*reserved_1)(void); void (*reserved_2)(void); void (*reserved_3)(void); void (*reserved_4)(void);
        void (*reserved_5)(void); void (*reserved_6)(void); void (*reserved_7)(void); void (*reserved_8)(void);
        struct nl_object_ops *co_obj_ops;
    };
    struct nl_object_ops { char *oo_name; size_t oo_size; uint32_t oo_id_attrs; };
    struct nl_msgtype { int mt_id; int mt_act; char *mt_name; };
    static int callback(struct nl_sock *sk, struct nl_msg *msg) {
        struct nlmsghdr *nlh = nlmsg_hdr(msg);
        printf("%d == nlh.nlmsg_len\n", nlh->nlmsg_len);
        printf("%d == nlh.nlmsg_type\n", nlh->nlmsg_type);
        printf("%d == nlh.nlmsg_flags\n", nlh->nlmsg_flags);
        struct nl_cache_ops *ops = nl_cache_ops_associate_safe(NETLINK_GENERIC, nlh->nlmsg_type);
        printf("'%s' == ops.co_name\n", ops->co_name);
        printf("%d == ops.co_hdrsize\n", ops->co_hdrsize);
        printf("%d == ops.co_protocol\n", ops->co_protocol);
        printf("%d == ops.co_hash_size\n", ops->co_hash_size);
        printf("%d == ops.co_flags\n", ops->co_flags);
        printf("'%s' == ops.co_obj_ops.oo_name\n", ops->co_obj_ops->oo_name);
        printf("%d == ops.co_obj_ops.oo_size\n", ops->co_obj_ops->oo_size);
        printf("%d == ops.co_obj_ops.oo_id_attrs\n", ops->co_obj_ops->oo_id_attrs);
        printf("%d == nlmsg_attrlen(nlh, ops.co_hdrsize)\n", nlmsg_attrlen(nlh, ops->co_hdrsize));
        struct nl_msgtype *mt = nl_msgtype_lookup(ops, nlh->nlmsg_type);
        printf("%d == mt.mt_id\n", mt->mt_id);
        printf("%d == mt.mt_act\n", mt->mt_act);
        printf("'%s' == mt.mt_name\n", mt->mt_name);
        return NL_STOP;
    }
    int main() {
        struct nl_sock *sk = nl_socket_alloc();
        nl_cb_overwrite_send(sk->s_cb, callback);

        struct genl_family *ret = genl_family_alloc();
        genl_family_set_name(ret, "nl80211");
        struct nl_msg *msg = nlmsg_alloc();
        genlmsg_put(msg, NL_AUTO_PORT, NL_AUTO_SEQ, GENL_ID_CTRL, 0, 0, CTRL_CMD_GETFAMILY, 1);
        printf("%d == nl_send_auto(sk, msg)\n", nl_send_auto(sk, msg));
        return 0;
    }
    // Expected output:
    // 20 == nlh.nlmsg_len
    // 16 == nlh.nlmsg_type
    // 5 == nlh.nlmsg_flags
    // 'genl/family' == ops.co_name
    // 4 == ops.co_hdrsize
    // 16 == ops.co_protocol
    // 0 == ops.co_hash_size
    // 0 == ops.co_flags
    // 'genl/family' == ops.co_obj_ops.oo_name
    // 80 == ops.co_obj_ops.oo_size
    // 1 == ops.co_obj_ops.oo_id_attrs
    // 0 == nlmsg_attrlen(nlh, ops.co_hdrsize)
    // 16 == mt.mt_id
    // 0 == mt.mt_act
    // 'nlctrl' == mt.mt_name
    // 2 == nl_send_auto(sk, msg)
    """
    called = list()

    def callback(_, msg_):
        nlh = nlmsg_hdr(msg_)
        assert 20 == nlh.nlmsg_len
        assert 16 == nlh.nlmsg_type
        assert 5 == nlh.nlmsg_flags
        ops = nl_cache_ops_associate_safe(NETLINK_GENERIC, nlh.nlmsg_type)
        assert 'genl/family' == ops.co_name
        assert 4 == ops.co_hdrsize
        assert 16 == ops.co_protocol
        assert 0 == ops.co_hash_size
        assert 0 == ops.co_flags
        assert 'genl/family' == ops.co_obj_ops.oo_name
        assert 80 == ops.co_obj_ops.oo_size
        assert 1 == ops.co_obj_ops.oo_id_attrs
        assert 0 == nlmsg_attrlen(nlh, ops.co_hdrsize)
        mt = nl_msgtype_lookup(ops, nlh.nlmsg_type)
        assert 16 == mt.mt_id
        assert 0 == mt.mt_act
        assert 'nlctrl' == mt.mt_name
        called.append(True)
        return NL_STOP

    sk = nl_socket_alloc()
    nl_cb_overwrite_send(sk.s_cb, callback)
    ret = genl_family_alloc()
    genl_family_set_name(ret, 'nl80211')
    msg = nlmsg_alloc()
    genlmsg_put(msg, NL_AUTO_PORT, NL_AUTO_SEQ, GENL_ID_CTRL, 0, 0, CTRL_CMD_GETFAMILY, 1)
    assert 2 == nl_send_auto(sk, msg)
    assert [True] == called
    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)
Beispiel #17
0
def test_ctrl_cmd_getfamily_hex_dump(log):
    r"""C code to test against.

    // gcc a.c $(pkg-config --cflags --libs libnl-genl-3.0) && NLDBG=4 ./a.out
    #include <netlink/msg.h>
    struct nl_sock {
        struct sockaddr_nl s_local; struct sockaddr_nl s_peer; int s_fd; int s_proto; unsigned int s_seq_next;
        unsigned int s_seq_expect; int s_flags; struct nl_cb *s_cb; size_t s_bufsize;
    };
    static void prefix_line(FILE *ofd, int prefix) { int i; for (i = 0; i < prefix; i++) fprintf(ofd, "  "); }
    static inline void dump_hex(FILE *ofd, char *start, int len, int prefix) {
        int i, a, c, limit; char ascii[21] = {0}; limit = 16 - (prefix * 2); prefix_line(ofd, prefix);
        fprintf(ofd, "    ");
        for (i = 0, a = 0, c = 0; i < len; i++) {
            int v = *(uint8_t *) (start + i); fprintf(ofd, "%02x ", v); ascii[a++] = isprint(v) ? v : '.';
            if (++c >= limit) {
                fprintf(ofd, "%s\n", ascii);
                if (i < (len - 1)) { prefix_line(ofd, prefix); fprintf(ofd, "    "); }
                a = c = 0;
                memset(ascii, 0, sizeof(ascii));
            }
        }
        if (c != 0) { for (i = 0; i < (limit - c); i++) fprintf(ofd, "   "); fprintf(ofd, "%s\n", ascii); }
    }
    struct ucred { pid_t pid; uid_t uid; gid_t gid; };
    struct nl_msg {
        int nm_protocol; int nm_flags; struct sockaddr_nl nm_src; struct sockaddr_nl nm_dst; struct ucred nm_creds;
        struct nlmsghdr *nm_nlh; size_t nm_size; int nm_refcnt;
    };
    static int callback_send(struct nl_sock *sk, struct nl_msg *msg) {
        printf("%d == msg.nm_protocol\n", msg->nm_protocol);
        printf("%d == msg.nm_flags\n", msg->nm_flags);
        printf("%d == msg.nm_src.nl_family\n", msg->nm_src.nl_family);
        printf("%d == msg.nm_src.nl_pid\n", msg->nm_src.nl_pid);
        printf("%d == msg.nm_src.nl_groups\n", msg->nm_src.nl_groups);
        printf("%d == msg.nm_dst.nl_family\n", msg->nm_dst.nl_family);
        printf("%d == msg.nm_dst.nl_pid\n", msg->nm_dst.nl_pid);
        printf("%d == msg.nm_dst.nl_groups\n", msg->nm_dst.nl_groups);
        printf("%d == msg.nm_creds.pid\n", msg->nm_creds.pid);
        printf("%d == msg.nm_creds.uid\n", msg->nm_creds.uid);
        printf("%d == msg.nm_creds.gid\n", msg->nm_creds.gid);
        printf("%d == msg.nm_nlh.nlmsg_type\n", msg->nm_nlh->nlmsg_type);
        printf("%d == msg.nm_nlh.nlmsg_flags\n", msg->nm_nlh->nlmsg_flags);
        printf("%d == msg.nm_nlh.nlmsg_pid\n", msg->nm_nlh->nlmsg_pid);
        printf("%d == msg.nm_size\n", msg->nm_size);
        printf("%d == msg.nm_refcnt\n", msg->nm_refcnt);
        struct iovec iov = { .iov_base = (void *) nlmsg_hdr(msg), .iov_len = nlmsg_hdr(msg)->nlmsg_len, };
        dump_hex(stdout, iov.iov_base, iov.iov_len, 0);
        return nl_send_iovec(sk, msg, &iov, 1);
    }
    static int callback_recv(struct nl_sock *sk, struct sockaddr_nl *nla, unsigned char **buf, struct ucred **creds) {
        int n = nl_recv(sk, nla, buf, creds);
        dump_hex(stdout, (void *) *buf, n, 0);
        return n;
    }
    static int callback_recv_msg(struct nl_msg *msg, void *arg) {
        printf("%d == msg.nm_protocol\n", msg->nm_protocol);
        printf("%d == msg.nm_flags\n", msg->nm_flags);
        printf("%d == msg.nm_src.nl_family\n", msg->nm_src.nl_family);
        printf("%d == msg.nm_src.nl_pid\n", msg->nm_src.nl_pid);
        printf("%d == msg.nm_src.nl_groups\n", msg->nm_src.nl_groups);
        printf("%d == msg.nm_dst.nl_family\n", msg->nm_dst.nl_family);
        printf("%d == msg.nm_dst.nl_pid\n", msg->nm_dst.nl_pid);
        printf("%d == msg.nm_dst.nl_groups\n", msg->nm_dst.nl_groups);
        printf("%d == msg.nm_creds.pid\n", msg->nm_creds.pid);
        printf("%d == msg.nm_creds.uid\n", msg->nm_creds.uid);
        printf("%d == msg.nm_creds.gid\n", msg->nm_creds.gid);
        printf("%d == msg.nm_nlh.nlmsg_type\n", msg->nm_nlh->nlmsg_type);
        printf("%d == msg.nm_nlh.nlmsg_flags\n", msg->nm_nlh->nlmsg_flags);
        printf("%d == msg.nm_nlh.nlmsg_pid\n", msg->nm_nlh->nlmsg_pid);
        printf("%d == msg.nm_size\n", msg->nm_size);
        printf("%d == msg.nm_refcnt\n", msg->nm_refcnt);
        dump_hex(stdout, (char *) msg->nm_nlh, nlmsg_datalen(msg->nm_nlh), 0);
        return NL_OK;
    }
    int main() {
        struct nl_sock *sk = nl_socket_alloc();
        nl_cb_overwrite_send(sk->s_cb, callback_send);
        nl_cb_overwrite_recv(sk->s_cb, callback_recv);
        printf("%d == genl_connect(sk)\n", genl_connect(sk));
        struct genl_family *ret = (struct genl_family *) genl_family_alloc();
        genl_family_set_name(ret, "nl80211");
        struct nl_msg *msg = nlmsg_alloc();
        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, "nl80211");
        nl_socket_modify_cb(sk, NL_CB_VALID, NL_CB_CUSTOM, callback_recv_msg, NULL);
        printf("%d == nl_send_auto(sk, msg)\n", nl_send_auto(sk, msg));
        printf("%d == nl_recvmsgs_default(sk)\n", nl_recvmsgs_default(sk));
        nl_socket_free(sk);
        return 0;
    }
    // Expected output (trimmed):
    // nl_cache_mngt_register: Registered cache operations genl/family
    // 0 == genl_connect(sk)
    //  nl_object_alloc: Allocated new object 0x2b50b8
    // __nlmsg_alloc: msg 0x2b5110: Allocated new message, maxlen=4096
    // nlmsg_put: msg 0x2b5110: Added netlink header type=16, flags=0, pid=0, seq=0
    // nlmsg_reserve: msg 0x2b5110: Reserved 4 (4) bytes, pad=4, nlmsg_len=20
    // genlmsg_put: msg 0x2b5110: Added generic netlink header cmd=3 version=1
    // nla_reserve: msg 0x2b5110: attr <0x2b5164> 2: Reserved 12 (8) bytes at offset +4 nlmsg_len=32
    // nla_put: msg 0x2b5110: attr <0x2b5164> 2: Wrote 8 bytes at offset +4
    // 16 == msg.nm_protocol
    // 0 == msg.nm_flags
    // 0 == msg.nm_src.nl_family
    // 0 == msg.nm_src.nl_pid
    // 0 == msg.nm_src.nl_groups
    // 0 == msg.nm_dst.nl_family
    // 0 == msg.nm_dst.nl_pid
    // 0 == msg.nm_dst.nl_groups
    // 0 == msg.nm_creds.pid
    // 0 == msg.nm_creds.uid
    // 0 == msg.nm_creds.gid
    // 16 == msg.nm_nlh.nlmsg_type
    // 5 == msg.nm_nlh.nlmsg_flags
    // 14272 == msg.nm_nlh.nlmsg_pid
    // 4096 == msg.nm_size
    // 1 == msg.nm_refcnt
    //     20 00 00 00 10 00 05 00 af aa f6 54 c0 37 00 00  ..........T.7..
    //     03 01 00 00 0c 00 02 00 6e 6c 38 30 32 31 31 00 ........nl80211.
    // nl_sendmsg: sent 32 bytes
    // 32 == nl_send_auto(sk, msg)
    // recvmsgs: Attempting to read from 0x2b5080
    //     2c 07 00 00 10 00 00 00 af aa f6 54 c0 37 00 00 ,..........T.7..
    //     01 02 00 00 0c 00 02 00 6e 6c 38 30 32 31 31 00 ........nl80211.
    //     06 00 01 00 16 00 00 00 08 00 03 00 01 00 00 00 ................
    //     08 00 04 00 00 00 00 00 08 00 05 00 d5 00 00 00 ................
    //     6c 06 06 00 14 00 01 00 08 00 01 00 01 00 00 00 l...............
    //     08 00 02 00 0e 00 00 00 14 00 02 00 08 00 01 00 ................
    //     <trimmed>
    //     63 6f 6e 66 69 67 00 00 18 00 02 00 08 00 02 00 config..........
    //     04 00 00 00 09 00 01 00 73 63 61 6e 00 00 00 00 ........scan....
    //     1c 00 03 00 08 00 02 00 05 00 00 00 0f 00 01 00 ................
    //     72 65 67 75 6c 61 74 6f 72 79 00 00 18 00 04 00 regulatory......
    //     08 00 02 00 06 00 00 00 09 00 01 00 6d 6c 6d 65 ............mlme
    //     00 00 00 00 18 00 05 00 08 00 02 00 07 00 00 00 ................
    //     0b 00 01 00 76 65 6e 64 6f 72 00 00             ....vendor..
    // recvmsgs: recvmsgs(0x2b5080): Read 1836 bytes
    // recvmsgs: recvmsgs(0x2b5080): Processing valid message...
    // __nlmsg_alloc: msg 0x2ba160: Allocated new message, maxlen=1836
    // 16 == msg.nm_protocol
    // 0 == msg.nm_flags
    // 16 == msg.nm_src.nl_family
    // 0 == msg.nm_src.nl_pid
    // 0 == msg.nm_src.nl_groups
    // 0 == msg.nm_dst.nl_family
    // 0 == msg.nm_dst.nl_pid
    // 0 == msg.nm_dst.nl_groups
    // 0 == msg.nm_creds.pid
    // 0 == msg.nm_creds.uid
    // 0 == msg.nm_creds.gid
    // 16 == msg.nm_nlh.nlmsg_type
    // 0 == msg.nm_nlh.nlmsg_flags
    // 14272 == msg.nm_nlh.nlmsg_pid
    // 1836 == msg.nm_size
    // 1 == msg.nm_refcnt
    //     2c 07 00 00 10 00 00 00 af aa f6 54 c0 37 00 00 ,..........T.7..
    //     01 02 00 00 0c 00 02 00 6e 6c 38 30 32 31 31 00 ........nl80211.
    //     06 00 01 00 16 00 00 00 08 00 03 00 01 00 00 00 ................
    //     08 00 04 00 00 00 00 00 08 00 05 00 d5 00 00 00 ................
    //     6c 06 06 00 14 00 01 00 08 00 01 00 01 00 00 00 l...............
    //     08 00 02 00 0e 00 00 00 14 00 02 00 08 00 01 00 ................
    //     <trimmed>
    //     63 6f 6e 66 69 67 00 00 18 00 02 00 08 00 02 00 config..........
    //     04 00 00 00 09 00 01 00 73 63 61 6e 00 00 00 00 ........scan....
    //     1c 00 03 00 08 00 02 00 05 00 00 00 0f 00 01 00 ................
    //     72 65 67 75 6c 61 74 6f 72 79 00 00 18 00 04 00 regulatory......
    //     08 00 02 00 06 00 00 00 09 00 01 00 6d 6c 6d 65 ............mlme
    //     00 00 00 00 18 00 05 00 08 00 02 00             ............
    // nlmsg_free: Returned message reference 0x2ba160, 0 remaining
    // nlmsg_free: msg 0x2ba160: Freed
    // 0 == nl_recvmsgs_default(sk)
    // nl_cache_mngt_unregister: Unregistered cache operations genl/family
    """
    def callback_send(sk, msg):
        assert 16 == msg.nm_protocol
        assert 0 == msg.nm_flags
        assert 0 == msg.nm_src.nl_family
        assert 0 == msg.nm_src.nl_pid
        assert 0 == msg.nm_src.nl_groups
        assert 0 == msg.nm_dst.nl_family
        assert 0 == msg.nm_dst.nl_pid
        assert 0 == msg.nm_dst.nl_groups
        assert msg.nm_creds is None
        assert 16 == msg.nm_nlh.nlmsg_type
        assert 5 == msg.nm_nlh.nlmsg_flags
        assert 100 < msg.nm_nlh.nlmsg_pid
        assert 1 == msg.nm_refcnt
        hdr = nlmsg_hdr(msg)
        iov = hdr.bytearray[:hdr.nlmsg_len]
        dump_hex(logging.getLogger().debug, iov, len(iov), 0)
        return nl_send_iovec(sk, msg, iov, 1)

    def callback_recv(sk, nla, buf, creds):
        n = nl_recv(sk, nla, buf, creds)
        dump_hex(logging.getLogger().debug, buf, len(buf), 0)
        return n

    def callback_recv_msg(msg, _):
        assert 16 == msg.nm_protocol
        assert 0 == msg.nm_flags
        assert 16 == msg.nm_src.nl_family
        assert 0 == msg.nm_src.nl_pid
        assert 0 == msg.nm_src.nl_groups
        assert 0 == msg.nm_dst.nl_family
        assert 0 == msg.nm_dst.nl_pid
        assert 0 == msg.nm_dst.nl_groups
        assert msg.nm_creds is None
        assert 16 == msg.nm_nlh.nlmsg_type
        assert 0 == msg.nm_nlh.nlmsg_flags
        assert 100 < msg.nm_nlh.nlmsg_pid
        assert 1000 < msg.nm_size
        assert 1 == msg.nm_refcnt
        dump_hex(logging.getLogger().debug, msg.nm_nlh.bytearray,
                 nlmsg_datalen(msg.nm_nlh), 0)
        return NL_OK

    del log[:]
    sk_main = nl_socket_alloc()
    nl_cb_overwrite_send(sk_main.s_cb, callback_send)
    nl_cb_overwrite_recv(sk_main.s_cb, callback_recv)
    genl_connect(sk_main)
    ret = genl_family_alloc()
    genl_family_set_name(ret, b'nl80211')
    msg_main = nlmsg_alloc()
    genlmsg_put(msg_main, NL_AUTO_PORT, NL_AUTO_SEQ, GENL_ID_CTRL, 0, 0,
                CTRL_CMD_GETFAMILY, 1)
    nla_put_string(msg_main, CTRL_ATTR_FAMILY_NAME, b'nl80211')
    nl_socket_modify_cb(sk_main, NL_CB_VALID, NL_CB_CUSTOM, callback_recv_msg,
                        None)
    assert 32 == nl_send_auto(sk_main, msg_main)
    assert 0 == nl_recvmsgs_default(sk_main)
    nl_socket_free(sk_main)

    assert match('nl_object_alloc: Allocated new object 0x[a-f0-9]+', log,
                 True)
    assert match(
        'nlmsg_alloc: msg 0x[a-f0-9]+: Allocated new message, maxlen=4096',
        log, True)
    assert match(
        'nlmsg_put: msg 0x[a-f0-9]+: Added netlink header type=16, flags=0, pid=0, seq=0',
        log, True)
    assert match(
        'nlmsg_reserve: msg 0x[a-f0-9]+: Reserved 4 \(4\) bytes, pad=4, nlmsg_len=20',
        log, True)
    assert match(
        'genlmsg_put: msg 0x[a-f0-9]+: Added generic netlink header cmd=3 version=1',
        log, True)
    assert match(
        'nla_reserve: msg 0x[a-f0-9]+: attr <0x[a-f0-9]+> 2: Reserved 12 \(8\) bytes at offset \+4 nlmsg_len=32',
        log, True)
    assert match(
        'nla_put: msg 0x[a-f0-9]+: attr <0x[a-f0-9]+> 2: Wrote 8 bytes at offset \+4',
        log, True)

    assert match(
        'dump_hex:     20 00 00 00 10 00 05 00 .. .. .. .. .. .. 00 00  ...............',
        log, True)
    assert match(
        'dump_hex:     03 01 00 00 0c 00 02 00 6e 6c 38 30 32 31 31 00 ........nl80211.',
        log)

    assert match('nl_sendmsg: sent 32 bytes', log)
    assert match('recvmsgs: Attempting to read from 0x[a-f0-9]+', log, True)

    assert match(
        'dump_hex:     .. .. 00 00 10 00 00 00 .. .. .. .. .. .. 00 00 ................',
        log, True)
    assert match(
        'dump_hex:     01 02 00 00 0c 00 02 00 6e 6c 38 30 32 31 31 00 ........nl80211.',
        log)
    assert match(
        'dump_hex:     06 00 01 00 .. 00 00 00 08 00 03 00 01 00 00 00 ................',
        log, True)
    assert match(
        'dump_hex:     08 00 04 00 00 00 00 00 08 00 05 00 .. 00 00 00 ................',
        log, True)

    for i in range(len(log)):
        if re.match(r'recvmsgs: recvmsgs\(0x[a-f0-9]+\): Read \d{4,} bytes',
                    log[i]):
            log = log[i:]
            break

    assert match('recvmsgs: recvmsgs\(0x[a-f0-9]+\): Read \d{3,} bytes', log,
                 True)
    assert match(
        'recvmsgs: recvmsgs\(0x[a-f0-9]+\): Processing valid message...', log,
        True)
    assert match(
        'nlmsg_alloc: msg 0x[a-f0-9]+: Allocated new message, maxlen=\d{3,}',
        log, True)

    assert match(
        'dump_hex:     .. .. 00 00 10 00 00 00 .. .. .. .. .. .. 00 00 ................',
        log, True)
    assert match(
        'dump_hex:     01 02 00 00 0c 00 02 00 6e 6c 38 30 32 31 31 00 ........nl80211.',
        log)
    assert match(
        'dump_hex:     06 00 01 00 .. 00 00 00 08 00 03 00 01 00 00 00 ................',
        log, True)
    assert match(
        'dump_hex:     08 00 04 00 00 00 00 00 08 00 05 00 .. 00 00 00 ................',
        log, True)

    while log and log[0].startswith('dump_hex:'):
        log.pop(0)
    assert not log
def main():
    """Main function called upon script execution."""
    # First get the wireless interface index.
    if OPTIONS['<interface>']:
        pack = struct.pack('16sI', OPTIONS['<interface>'].encode('ascii'), 0)
        sk = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        try:
            info = struct.unpack('16sI', fcntl.ioctl(sk.fileno(), 0x8933,
                                                     pack))
        except OSError:
            return error('Wireless interface {0} does not exist.'.format(
                OPTIONS['<interface>']))
        finally:
            sk.close()
        if_index = int(info[1])
    else:
        if_index = -1

    # Then open a socket to the kernel. Same one used for sending and receiving.
    sk = nl_socket_alloc()  # Creates an `nl_sock` instance.
    ret = genl_connect(sk)  # Create file descriptor and bind socket.
    if ret < 0:
        reason = errmsg[abs(ret)]
        return error('genl_connect() returned {0} ({1})'.format(ret, reason))

    # Now get the nl80211 driver ID. Handle errors here.
    driver_id = genl_ctrl_resolve(sk,
                                  b'nl80211')  # Find the nl80211 driver ID.
    if driver_id < 0:
        reason = errmsg[abs(driver_id)]
        return error('genl_ctrl_resolve() returned {0} ({1})'.format(
            driver_id, reason))

    # Setup the Generic Netlink message.
    msg = nlmsg_alloc()  # Allocate a message.
    if OPTIONS['<interface>']:
        genlmsg_put(msg, 0, 0, driver_id, 0, 0,
                    nl80211.NL80211_CMD_GET_INTERFACE,
                    0)  # Tell kernel: send iface info.
        nla_put_u32(msg, nl80211.NL80211_ATTR_IFINDEX,
                    if_index)  # This is the interface we care about.
    else:
        # Ask kernel to send info for all wireless interfaces.
        genlmsg_put(msg, 0, 0, driver_id, 0, NLM_F_DUMP,
                    nl80211.NL80211_CMD_GET_INTERFACE, 0)

    # Add the callback function to the nl_sock.
    has_printed = list()
    nl_socket_modify_cb(sk, NL_CB_VALID, NL_CB_CUSTOM, callback, has_printed)

    # Now send the message to the kernel, and get its response, automatically calling the callback.
    ret = nl_send_auto(sk, msg)
    if ret < 0:
        reason = errmsg[abs(ret)]
        return error('nl_send_auto() returned {0} ({1})'.format(ret, reason))
    print('Sent {0} bytes to the kernel.'.format(ret))
    ret = nl_recvmsgs_default(
        sk)  # Blocks until the kernel replies. Usually it's instant.
    if ret < 0:
        reason = errmsg[abs(ret)]
        return error('nl_recvmsgs_default() returned {0} ({1})'.format(
            ret, reason))
def channel_hopper():
    global count

    # Get the index of the interface
    pack = struct.pack('16sI', interface, 0)
    sk = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        info = struct.unpack('16sI', fcntl.ioctl(sk.fileno(), 0x8933, pack))
    except (OSError, IOError):
        error('wireless interface {0} does not exist.'.format(interface))
        return -1
    finally:
        sk.close()

    if_index = int(info[1])

    # Open a socket to the kernel
    sk = nl_socket_alloc()
    ret = genl_connect(sk)
    if ret < 0:
        reason = errmsg[abs(ret)]
        error('genl_connect() failed: {0} ({1})'.format(ret, reason))
        return -1

    # Now get the nl80211 driver ID
    driver_id = genl_ctrl_resolve(sk, b'nl80211')
    if driver_id < 0:
        reason = errmsg[abs(driver_id)]
        error('genl_ctrl_resolve() failed: {0} ({1})'.format(
            driver_id, reason))
        return -1

    # Iterate over channels using the corresponding dwell time
    supported_channels = [x for x in channels if x not in unsupported_channels]
    for ch in supported_channels:

        if not sniffing:
            break

        # Set new channel
        msg = nlmsg_alloc()
        genlmsg_put(msg, 0, 0, driver_id, 0, 0,
                    nl80211.NL80211_CMD_SET_CHANNEL, 0)
        nla_put_u32(msg, nl80211.NL80211_ATTR_IFINDEX, if_index)
        nla_put_u32(msg, nl80211.NL80211_ATTR_WIPHY_FREQ,
                    channel_to_frequency(ch))
        nla_put_u32(msg, nl80211.NL80211_ATTR_WIPHY_CHANNEL_TYPE,
                    nl80211.NL80211_CHAN_WIDTH_20)

        if nl_send_auto(sk, msg) < 0:
            unsupported_channels.add(ch)
            time.sleep(0.02)
        else:
            count = 0
            time.sleep(dwelltimes[ch])
            if count == 0:
                dwelltimes[ch] = mindwelltime
            else:
                dwelltimes[ch] = maxdwelltime

    return 0