Debian Codegraph @

docs/PyRIC.tex

raw
1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2 % Copyright (C) 2016 Dale V. Patterson ([email protected])
3 %
4 %This program is free software: you can redistribute it and/or modify it under
5 %the terms of the GNU General Public License as published by the Free Software
6 %Foundation, either version 3 of the License, or (at your option) any later
7 %version.
8 %
9 %Redistribution and use in source and binary forms, with or without modifications,
10 %are permitted provided that the following conditions are met:
11 % o Redistributions of source code must retain the above copyright notice, this
12 % list of conditions and the following disclaimer.
13 % o Redistributions in binary form must reproduce the above copyright notice,
14 % this list of conditions and the following disclaimer in the documentation
15 % and/or other materials provided with the distribution.
16 % o Neither the name of the orginal author Dale V. Patterson nor the names of any
17 % contributors may be used to endorse or promote products derived from this
18 % software without specific prior written permission.
19 %
20 % __name__ = 'User Guide'
21 %__license__ = 'GPLv3'
22 %__version__ = '0.0.7'
23 %__date__ = 'December 2016'
24 %__author__ = 'Dale Patterson'
25 %__maintainer__ = 'Dale Patterson'
26 %__email__ = '[email protected]'
27 %__status__ = 'Production'
28 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
29
30 \documentclass[11pt]{article}
31 \usepackage[utf8]{inputenc}
32 \setlength{\parindent}{0pt}
33 \usepackage{graphicx}
34 \usepackage{listings}
35 \usepackage{caption}
36 \usepackage{geometry}
37 \usepackage{color}
38 \usepackage{graphicx}
39 \usepackage[titletoc,toc,title]{appendix}
40 \usepackage[T1]{fontenc}
41
42 \definecolor{codegreen}{rgb}{0,0.6,0}
43 \definecolor{codegray}{rgb}{0.5,0.5,0.5}
44 \definecolor{codepurple}{rgb}{0.58,0,0.82}
45 \definecolor{backcolour}{rgb}{0.95,0.95,0.92}
46
47 \geometry{left=1.0in,right=1.0in,top=1.0in,bottom=1.0in }
48
49 \lstset{
50 frame=top,
51 frame=bottom,
52 basicstyle=\small\normalfont\ ,
53 stepnumber=1,
54 numbersep=10pt,
55 tabsize=2,
56 extendedchars=true,
57 breaklines=true,
58 captionpos=b,
59 mathescape=true,
60 showspaces=false,
61 showtabs=false,
62 xleftmargin=17pt,
63 framexleftmargin=17pt,
64 framexrightmargin=17pt,
65 framexbottommargin=5pt,
66 framextopmargin=5pt,
67 showstringspaces=false,
68 backgroundcolor=\color{backcolour},
69 commentstyle=\color{codegreen},
70 keywordstyle=\color{magenta},
71 numberstyle=\tiny\color{codegray},
72 stringstyle=\color{codepurple},
73 basicstyle=\footnotesize
74 }
75
76 \title{\includegraphics[scale=1]{logo}\\ PyRIC v0.1.6.4: User Manual}
77 \author{Dale V. Patterson\\ [email protected]}
78
79 \begin{document}
80 \maketitle
81 \tableofcontents
82
83 \section{About PyRIC}\label{sec:About}
84 PyRIC (is a Linux only) library providing wireless developers and pentesters the
85 ability to identify, enumerate and manipulate their system's wireless cards
86 programmatically in Python. Pentesting applications and scripts written in Python
87 have increased dramatically in recent years. However, these tools still rely on
88 Linux command lines tools to setup and prepare and restore the system for use.
89 Until now. Why use subprocess.Popen, regular expressions and str.find to interact
90 with your wireless cards? PyRIC puts iw, ifconfig, rfkill, udevadm, airmon-ng and
91 macchanger in your hands (or your program). \\
92
93 PyRIC is designed with Python 2.7 in mind but has now been made compatible with
94 Python 3.5. It will also work on Python 3.0 but you will have to hard code the
95 command line options in the two examples as Python 3.0 does not include the module
96 argparse
97
98 PyRIC is:
99 \begin{enumerate}
100 \item \textbf{Pythonic}: No ctypes, SWIG etc. PyRIC redefines C header files as
101 Python and uses sockets to communicate with kernel.
102 \item \textbf{Self-sufficient}: No third-party files used, PyRIC is completely self-
103 contained
104 \item \textbf{Fast}: (relatively speaking) PyRIC is faster than using iw through
105 subprocess.Popen
106 \item \textbf{Parseless}: Get the output you without parsing output from iw. Never
107 worry about iw updates and rewriting your parsers.
108 \item \textbf{Easy}: If you can use iw, you can use PyRIC
109 \end{enumerate}
110
111 At it's heart, PyRIC is a Python port of (a subset of) iw and by extension, a
112 Python port of Netlink w.r.t nl80211 functionality. The original goal of PyRIC
113 was to provide a simple interface to the underlying nl80211 kernel support,
114 handling the complex operations of Netlink seamlessy while maintaining a minimum
115 of "code walking" to understand, modify and extend. But, why stop there? Since
116 it's initial inception, PyRIC has grown to include ioctl support to replicate
117 features of ifconfig such as getting or setting the mac address and has recently
118 implemented rkill support to soft block or unblock wireless cards.\\
119
120 While users can utilize libnl.py to communicate directly with the kernel, the
121 true utility of PyRIC is pyw.py. Like iw, pyw provides an interface/buffer
122 between the caller and the kernel, handling all message construction, parsing
123 and data transfer transparently and without requiring any Netlink knowledge or
124 experience. \\
125
126 At this time, PyRIC can:
127 \begin{itemize}
128 \item enumerate interfaces and wireless interfaces,
129 \item identify a cards driver, chipset and manufacturer,
130 \item get/set hardware address,
131 \item get/set ip4 address, netmask and or broadcast,
132 \item turn card on/off,
133 \item get supported standards, commands or modes,
134 \item get if info,
135 \item get dev info,
136 \item get phy info,
137 \item get link info,
138 \item get STA (connected AP) info,
139 \item get/set regulatory domain,
140 \item get/set mode,
141 \item get/set coverage class, RTS threshold, Fragmentation threshold and retry
142 limits,
143 \item add/delete interfaces,
144 \item determine if a card is connected,
145 \item get link info for a connected card,
146 \item enumerate ISM and UNII channels,
147 \item block/unblock rfkill devices.
148 \end{itemize}
149 And, through libnl.py and libio.py, users can extend the above functionality by
150 creating additional commands.
151
152 \subsection{Background}
153 PyRIC arose out of a need in Wraith (https://github.com/wraith-wireless/wraith)
154 for Python nl80211/netlink and ioctl functionality. Originally, Wraith used
155 ifconfig, iwconfig and iw via subprocess.Popen and parsed the output. There
156 are obvious shortfalls with this method, especially in terms of iw that is
157 actively changing (revisions break the parser) and I started looking for an
158 open source alternative. There are several open source projects out there
159 such as pyroute, pymnl (and the python files included in the libnl source) but
160 they generally have either not been maintained recently or come with warnings.
161 I desired a simple interface to the underlying nl80211 kernel support that
162 handles the complex operations of netlink seamlessy while maintaining a minimum
163 of "code walking" to understand, modify and extend. I decided to write my own
164 because I do not need complete netlink functionality, only that provided by
165 generic netlink and within the nl80221 family. Additionally, for Wraith, I do
166 not need a full blown port of iw et. al. functionality to Python but only
167 require the ability to turn a wireless nic on/off, get/set the hwaddr, get/set
168 the channel, determine some properties of the card and add/delete interfaces.
169
170 So, why did I do this and why is it done "this" way? When I first started to
171 explore the idea of moving away from iw output parsing, I looked at the source
172 for iw, and existing Python ports. Just to figure out how to get the family id
173 for nl80211 required reading through five different source files with no
174 comments. To that extent, I have attempted to keep subclassing to a minimum,
175 the total number of classes to a minimum, combine files where possible and where
176 it makes since and keep the number of files required to be open simultaneously
177 in order to understand the methodology and follow the program to a minimum. One
178 can understand the PyRIC program flow with only two files open at any time namely,
179 pyw and libnl. In fact, only an understanding of pyw is required to add additional
180 commands although an understanding of libnl.py is helpful especially, if for
181 example, the code is to be extended to handle multicast or callbacks.
182
183 \subsection{Naming Conventions}
184 The terms interface, device and radio are all used interchangeably throughout to
185 refer to a network interface controller (NIC). The following terms will always
186 have one meaning:
187 \begin{itemize}
188 \item \textbf{dev} - the device name i.e. wlan0 or eth0 of a NIC,
189 \item \textbf{phy} - the physical index of a NIC i.e. the 0 in phy0,
190 \item \textbf{ifindex} - the interface index of a NIC,
191 \item \textbf{card} or \textbf{Card} - a NIC abstraction, an object used in pyw
192 functions see the following section for a description.
193 \end{itemize}
194
195 \subsection{Cards}
196 A Card is merely a wrapper around a tuple t = (phy index,device name,ifindex).
197 Since the underlying Netlink calls sometimes require the physical index, sometimes
198 the device name, and sometimes the ifindex, pyw functions\footnote{Not all functions
199 accept only a Card, devinfo() accepts either a Card or a dev, devadd accepts either a
200 Card or a ifindex and phyadd accepts only a physical index} take a Card object which
201 doesn't require callers to know which identifier to use for each function. There are
202 four primary methods to creating a Card:
203 \begin{enumerate}
204 \item \textbf{pyw.getcard} returns a Card object from a given dev,
205 \item \textbf{pyw.devinfo} returns the dict info where info['card'] is the Card
206 object. (This function will take either a card or a ifindex),
207 \item \textbf{pyw.devadd} returns a new Card object (this function will only take
208 a phy),
209 \item \textbf{pyw.ifaces} returns a list of tuples t = (Card,mode) sharing the
210 same phy as a given dev.
211 \end{enumerate}
212
213 A side affect of using Cards is that many of the netlink calls require the ifindex.
214 The ifindex is found through the use of ioctl, meaning two sockets have to be
215 created and two messages have to be sent, received and parsed in order to execute
216 the command. With Cards, the ifindex is requested for only once. \\
217
218 Keep in mind that any identifier (phy, dev, ifindex) can be invalidated outside
219 of your control. Another program can rename your interface, that is change the
220 dev without your knowledge. Depending on what functions are being used this may
221 not be noticed right away as the phy will remain the same. Also for usb devices,
222 (if the usb is disconnected and reconnected) will have the same dev but the phy
223 and ifindex will be different.
224
225 \subsection{Benchmarks}
226 PyRIC makes use of several "extensions" to speed up pyw functions:
227 \begin{enumerate}
228 \item \textbf{Persistent sockets}: pyw provides the caller with functions and
229 the ability to pass their own netlink (or ioctl socket) to pyw functions
230 \item \textbf{One-time request for the nl80211 family id}: pyw stores the family
231 id in a global variable
232 \item \textbf{Consolidation} different "reference" values are consolidated in one
233 class (see the previous section)
234 \end{enumerate}
235
236 \begin{table}
237 \begin{center}
238 \begin{tabular}{| l | r | r | r | r|}
239 \hline
240 chset & Total & Avg & Longest & Shortest \\
241 \hline
242 Popen(iw) & 588.3059 & 0.0588 & 0.0682 & 0.0021 \\
243 \hline
244 one-time & 560.3559 & 0.0560 & 0.0645 & 0.0003 \\
245 \hline
246 persistent & 257.8293 & 0.0257 & 0.0354 & 0.0004 \\
247 \hline
248 \end{tabular}
249 \caption{Benchmark: Popen(iw) vs pyw}
250 \end{center}
251 \label{tab:benchmark}
252 \end{table}
253
254 While small, these changes can improve the performance of any programs using pyw.
255 Table 1 shows benchmarks for hop time on an Alfa AWUS036NH conducted 10000 times.
256 Note that we are not implying that PyRIC is faster than iw. Rather, the table
257 shows that PyRIC is faster than using Popen to execute iw. Using one-time sockets,
258 there is a difference of 28 seconds over Popen and iw with a small decrease in
259 the average hoptime. Not a big difference. However, the performance increased
260 dramatically when persistent netlink sockets are used with the total time and
261 average hop time nearly halved.
262
263 \section{Installing PyRIC}\label{sec:installing}
264 The easiest way to install PyRIC is through PyPI:\\
265
266 \texttt{sudo pip install PyRIC}\\
267
268 You can also install PyRIC from source. The tarball can be downloaded from:
269
270 \begin{itemize}
271 \item PyPi: https://pypi.python.org/pypi/PyRIC,
272 \item PyRIC Web: http://wraith-wireless.github.io/PyRIC, or
273 \item Github: https://github.com/wraith-wireless/PyRIC.
274 \end{itemize}
275
276 After downloading, extract and run:\\
277
278 \texttt{sudo python setup.py install}\\
279
280 If you just want to test PyRIC out, download your choice from above. After
281 extraction, move the pyric folder (the package directory) to your location of
282 choice and from there start Python and import pyw. It is very important that you
283 do not try and run it from PyRIC which is the distribution directory. This will
284 break the imports pyw.py uses. \\
285
286 You will only be able to test PyRIC from the pyric directory but, if you want to,
287 you can add it to your Python path and run it from any program or any location.
288 To do so, assume you untared PyRIC to /home/bob/PyRIC. Create a text file named
289 pyric.pth with one line \\
290
291 /home/bob/PyRIC \\
292
293 and save this file to /usr/lib/python2.7/dist-packages (or
294 /usr/lib/python3/dist-packages if you want to try it in Python 3).
295
296 \begin{table}
297 \begin{center}
298 \begin{tabular}{| l | r | r | r |}
299 \hline
300 Source & Stability & Recency & Installation \\
301 \hline
302 pip & 5 & 3 & 5\\
303 \hline
304 PyPI & 5 & 3 & 4\\
305 \hline
306 PyRIC Web & 4 & 4 & 4\\
307 \hline
308 Github & 3 & 5 & 3\\
309 \hline
310 \end{tabular}
311 \caption{Stability vs Recency vs Installation}
312 \end{center}
313 \label{tab:install}
314 \end{table}
315
316 \section{Using PyRIC}\label{sec:using}
317 As stated previously, PyRIC provides a set of functions to interact with your
318 system's radio(s) and the ability to interact directly with the kernel through
319 netlink and ioctl sockets.
320
321 \subsection{Interacting with the Wireless Core and Wireless NICs: pyw.py}
322 If you can use iw, you can use pyw. The easist way to explain how to use pyw is
323 with an example. Imagine your wireless network, on ch 6, has been experiencing
324 difficulties lately and you want to capture some traffic to analyse it. Listing
325 \ref{lst:pentest} shows how to set up a wireless pentest environment. \\
326
327 \begin{lstlisting}[caption={Setting up a Wireless Pentest Environment},
328 label={lst:pentest},
329 language=Python]
330 1: import pyric # pyric error (and ecode EUNDEF)
331 2: from pyric import pyw # for iw functionality
332 3: from pyric.utils.channels import rf2ch # rf to channel conversion
333 4:
334 5: dev = 'wlan0'
335 6: dinfo = pyw.devinfo(dev)
336 7: card = dinfo['card']
337 8:
338 9: pyw.down(card)
339 10: pyw.macset(card,'00:03:93:57:54:46')
340 11:
341 12: pdev = 'pent0'
342 13: pcard = pyw.devadd(card, pdev, 'monitor')
343 14: for iface in pyw.ifaces(card):
344 15: if iface[0].dev != pcard.dev:
345 16: pyw.devdel(iface[0])
346 17: pyw.up(pcard)
347 18:
348 19: pyw.chset(pcard,6,None)
349 20:
350 21: # DO stuff here
351 22:
352 23: card = pyw.devadd(pcard,card.dev,dinfo['mode'])
353 24: pyw.devdel(pcard)
354 25: pyw.macset(card,dinfo['mac'])
355 26: pyw.up(card)
356 \end{lstlisting}
357
358 Listing \ref{lst:pentest} shows basic pyw functions and is the basic shell used in
359 another project, Wraith\cite{wraith}, to instantiate a wireless (802.11) sensor -
360 (for a full listing of all pyw functions see Appendix \ref{sec:pywapi}) - with
361 scanning capabilities. \\
362
363 Lines 1 and 2 should always be included as they import the pyric error and pyw
364 functions. Line 3 imports the rf2ch conversion function. \\
365
366 In lines 5 through 10, a Card is created from the device wlan0. The info dict is save
367 IOT to restore later. Next, the mac address of wlan0 is changed. Note, the device has
368 to be brought down first. \\
369
370 Starting on line 12, a device named 'pent0' is created in monitor mode. First, a new
371 Card, pcard is create in monitor mode. Then, all interfaces on the same phy are
372 deleted \footnote{we have found that it is better to delete all interfaces on the
373 same phy ensuring that external processes don't interfere with the new device}. The
374 new Card is brought up and set to channel 6 NOHT.\\
375
376 Restoring the device starts on line 23, where the virtual interface is deleted,
377 the previous interface is restored, the mac address is reset and the old Card is
378 brought up. \\
379
380 An extended version of Listing \ref{lst:pentest} can be found in the examples
381 directory.
382
383 \subsubsection{One-time vs Persistent Sockets}
384 The example in Listing \ref{lst:pentest} uses one-time sockets (netlink and
385 ioctl). When using iw, there are several things that occur prior to the actual
386 command or request being submitted. First, iw creates a netlink socket. Then,
387 iw will request the family id for nl80211. The relative time spent doing this
388 is neglible but, it is redundant and it may become noticeable in programs that
389 repeatedly use the Netlink service. Once comlete, iw closes the socket. In some
390 cases, the ifindex of the device is needed and iw will also initiate an ioctl
391 call to retrieve it. PyRIC eliminates these redundancies by using a global
392 variable in pyw that stores the family id after the first time it is requested
393 and by providing callers the option to use persistent sockets.
394 \begin{itemize}
395 \item \textbf{One-time Sockets} Similar to iw. The command, creates the netlink
396 socket (or ioctl socket), composes the message, sends the message and receives
397 the response, parses the results, closes the socket and returns the results to
398 the caller. At no time does the caller need to be aware of any underlying Netlink
399 processes or structures.
400 \item \textbf{Persistent Sockets} Communication and parsing only. The onus of
401 socket creation and deletion is on the caller which allows them to create one
402 (or more) socket(s). The pyw functions will only handle message construction,
403 message sending and receiving and message parsing.
404 \end{itemize}
405 The caller needs to be cognizant of whether the function requires a netlink or
406 ioctl socket. Passing the wrong type will result in an error. \\
407
408 NOTE: One must remember that there is an upper limit to the number of open netlink
409 sockets. It is advised to use one-time functions as much as possible and save the
410 use of persistent sockets for use in code that repeatedly makes use of netlink. \\
411
412 The latest version of pyw.py (v 0.1.*) implements this functionality through the
413 use of what I call templates\footnote{I use templates and stubs for the lack
414 of any better naming convention}, Listing \ref{lst:template} and stubs Listing
415 \ref{lst:stub}.
416
417 \begin{lstlisting}[caption={A Basic Netlink Function Template},
418 label={lst:template},
419 language=Python]
420 def fcttemplate(arg0,arg1,..,argn,nlsock=None):
421 # put parameter validation (if any) here
422 if nlsock is None: _nlstub_(fcttemplate,arg0,arg1,...,argn)
423
424 # command execution
425 ...
426 return results
427 \end{lstlisting}
428
429 The template function in Listing \ref{lst:template} checks if nlsock is instantiatd
430 \footnote{ioctl calls operate in the same manner}. If so, it proceeds to execution.
431 If there is no socket, the stub is executed which creates one. If something other
432 than a netlink socket is at argv[0], an error will be raised during execution. \\
433
434 \begin{lstlisting}[caption={Function \_nlstub\_},
435 label={lst:stub},
436 language=Python]
437 def _nlstub_(fct,*argv):
438 nlsock = None
439 try:
440 nlsock = nlsock = nl.nl_socket_alloc()
441 argv = list(argv) + nlsock=None
442 return fct(*argv)
443 except pyric.error:
444 raise # catch & release
445 finally:
446 if nlsock: nl.nl_socket_free(nlsock)
447 \end{lstlisting}
448
449 The stub function, Listing \ref{lst:stub} allocates a netlink socket, executes
450 the original (now with a netlink socket) and then destroys the netlink socket.\\
451
452 \begin{lstlisting}[caption={Using Persistent Sockets},
453 label={lst:persistent},
454 language=Python]
455 1: import pyric # pyric errors
456 2: from pyric import pyw # for iw functionality
457 3: from pyric.lib import libnl as nl # for netlink sockets
458 4:
459 5: nlsock = nl.nl_socket_alloc(timeout=1)
460 6: card = pyw.getcard('wlan0',nlsock)
461 7: print pyw.devmodes(card,nlsock)
462 8: nl.nl_socket_free(nlsock)
463 \end{lstlisting}
464
465 Listing \ref{lst:persistent}, shows the creation of a persistent netlink socket
466 that is used in the creation of a card and in retrieved the card's supported
467 modes. \\
468
469 Use Python's built in help features on pyw functions or see Appendex \ref{sec:pywapi}
470 to determine what type of socket is needed.
471
472 \subsection{Additional Tools}
473 In the utils directory, PyRIC includes channels.py, hardware.py, rfkill.py and
474 ouifetch.py. These provide a port of rfkill, channel/frequency enumeration and
475 device chipset, driver retrieval as well as some mac address functions. More
476 information can be found in the Appendices and in README.md.
477
478 \subsection{Interacting with the Kernel: libnl.py and libio.py}
479 The kernel interfaces, libnl.py and libio.py are located in the lib directory.
480 They handle socket creation/deletion, message creation/parsing and kernel
481 communication. Aside from creating and deleting persistent sockets, there is
482 little need to access their functions unless you plan on extending pyw
483 functionality. As such, a further discussion of libnl.py and libio.py can be
484 found in the next section.
485
486 \section{Extending PyRIC}\label{sec:extending}
487 You may find that pyw does not offer some of the functionality you need. Using
488 libnl.py and/or libnl.io, additional functionality can be added to your program.\\
489
490 It is helpful if the reader has a basic knowledge of netlinks. For a review, see
491 "Communicating between the kernel and user-space in Linux using Netlink Sockets"
492 \cite{spae}.
493
494 \subsection{Porting C}
495 All Python ports of C header files can be found in the net directory. C Enums
496 and \#defines are ported using constants. C structs are ported using three
497 Python structures and the Python struct package:
498 \begin{enumerate}
499 \item a format string for packing and unpacking the struct
500 \item a constant specifying the size of the struct in bytes
501 \item a function taking the attributes of the struct as arguments and returning
502 a packed string
503 \end{enumerate}
504 Listing \ref{lst:cstruct} shows the C definition of the nlmsghdr found in netlink.h.
505
506 \begin{lstlisting}[caption={C Struct nlmsghdr},
507 label={lst:cstruct},
508 language=C]
509 struct nlmsghdr {
510 __u32 nlmsg_len;
511 __u16 nlmsg_type;
512 __u16 nlmsg_flags;
513 __u32 nlmsg_seq;
514 __u32 nlmsg_pid;
515 };
516 \end{lstlisting}
517
518 And Listing \ref{lst:pstruct} shows the ported version in Python.
519
520 \begin{lstlisting}[caption={Corresponding Python Definition},
521 label={lst:pstruct},
522 language=Python]
523 nl_nlmsghdr = "IHHII"
524 NLMSGHDRLEN = struct.calcsize(nl_nlmsghdr)
525 def nlmsghdr(mlen,nltype,flags,seq,pid):
526 return struct.pack(nl_nlmsghdr,NLMSGHDRLEN+mlen,nltype,flags,seq,pid)
527 \end{lstlisting}
528
529 When using pyw, dealing with these structures is handled transparently by libnl.py
530 and libio.py. When extending or customizing pyw, a basic understanding of the
531 definitions in netlink\_h.py, genetlink\_h.py and if\_h.py.
532
533 \subsection{Input/Output Control (ioctl)}
534 PyRIC provides more than just iw-related functions, it also implements functions
535 from ifconfig and iwconfig. These command line tools still use ioctl (or the proc
536 directory). For example, interfaces() reads from '/proc/net/dev' to retrieve all
537 system interfaces and winterfaces() use ioctl to check if a device is wireless.
538 Input/Output control calls have only been used when there was no viable alternative
539 and, it should not be necessary to have to add any further ioctl commands. If you
540 find that you need an ioctl related command, search through if\_h.py for the
541 appropriate structure and add it's definitions to ifreq.
542
543 \subsection{Netlink and nl80211}
544 Documentation on Netlink, and nl80211 in particular, is so minimal as to be
545 neglible. The clusterfuck of code and lack of comments in the iw source tree
546 make it impossible to use as any sort of roadmap. Fortunately Thomas Graf's
547 site\cite{libnl} has excellent coverage of libnl, the Netlink library. Using
548 this as a reference, a simple Netlink parser was put together which later became
549 libnl.py. Using the command line tool strace and libnl.py, Netlink messages could
550 be dissected and analyzed.\\
551
552 Let us consider adding a virtual interface with the command:\\
553
554 \texttt{sudo iw phy0 interface add test0 type monitor}\\
555
556 First, we need to see what is going on under the covers. Using strace:\\
557
558 \texttt{strace -f -x -s 4096 iw phy0 interface add test0 type monitor}\\
559
560 from a terminal will give a you a lot of output, most irrelevant (to us). Scroll
561 through this until the netlink socket creation as highlighted in Figure
562 \ref{fig:nlsock}. You can see that a socket of type PF\_NETLINK is created and
563 the send/receive buffers are set to 32768.
564 \begin{center}
565 \begin{figure}[h]
566 \includegraphics{nlsock}
567 \caption{Netlink socket creation}
568 \label{fig:nlsock}
569 \end{figure}
570 \end{center}
571 What we want to analyze are the messages sent and received over the netlink
572 socket. In Figure \ref{fig:nlsock}, iw is requesting the family id for nl80211.
573 This id will be used in subsequent requests related to nl80211 as we will see
574 shortly. The return message gives the nl80211 family id as 26 and returns other
575 nl80211 attributes. This is handled by the private function \_familyid\_ in
576 pyw.py.
577
578 Figure \ref{fig:nlsend} shows the add interface message being sent to the kernel.
579 \begin{center}
580 \begin{figure}[h]
581 \includegraphics{nlsend}
582 \caption{Netlink sendmsg}
583 \label{fig:nlsend}
584 \end{figure}
585 \end{center}
586 We are interested in the byte sequence following msg\_iov(1). Copy this and paste
587 into in a python variable as in Listing \ref{lst:nlparse} and pass it to the
588 function nlmsg\_fromstream which parses the byte stream and returns the GENLMsg.\\
589
590 \begin{lstlisting}[caption={Parsing netlink messages},
591 label={lst:nlparse},
592 language=Python]
593 >>> from pyric.lib import libnl as nl
594 >>> sent = "\x30\x00\x00\x00\x1a...\x00\x00"
595 >>> msg = nl.nlmsg_fromstream(sent)
596 >>> msg
597 nlmsghdr(len=48,type=26,flags=5,seq=1463268720,pid=10982)
598 genlmsghdr(cmd=7)
599 attributes:
600 0: type=1,datatype=3
601 value=0
602 1: type=4,datatype=5
603 value=test0
604 2: type=5,datatype=3
605 value=6
606 \end{lstlisting}
607
608 The first thing to notice is nlmsghdr type = 26, which of course is nl80211 family
609 id. The rest of the nlmsghdr components len, flags, seq, and pid are handled by
610 libnl.py although you can supply your own flags if desired. At this time, you can
611 manually look up what values the cmd, type and datatype correspond to in
612 nl80211\_h.py and netlink\_h.py or you can use the tools provided in nlhelp.py.\\
613
614 \begin{lstlisting}[caption={Parsing netlink messages continued},
615 label={lst:nlparse2},
616 language=Python]
617 >>> from pyric.net.netlink_h import NLA_DATATYPES
618 >>> from pyric.docs import nlhelp
619 >>> nlhelp.cmdbynum(7)
620 u'@NL80211_CMD_NEW_INTERFACE'
621 >>>
622 >>> for attr in msg.attrs:
623 ... print nlhelp.attrbynum(attr[0]), NLA_DATATYPES[attr[2]], attr[1]
624 ...
625 @NL80211_ATTR_WIPHY u32 0
626 @NL80211_ATTR_IFNAME string test0
627 @NL80211_ATTR_IFTYPE u32 6
628 >>>
629 >>> from pyric.net.wireless.nl80211_h import NL80211_IFTYPES
630 >>> NL80211_IFTYPES[6]
631 'monitor'
632 \end{lstlisting}
633
634 In Listing \ref{lst:nlparse2} command number 7 corresponds to
635 NL80211\_CMD\_NEW\_INTERFACE and the attributes that need to be passed to the
636 kernel are NL80211\_ATTR\_WIPHY, NL80211\_ATTR\_IFNAME and NL80211\_ATTR\_IFTYPE.
637 The IFTYPE is also known as the mode i.e. 'monitor' which can be found in
638 nl80211\_h.py NL80211\_IFTYPES. We don't parse the return message from the kernel
639 but, it follows the same SOP. In this case, it returns the attributes of the new
640 virtual interface. \\
641
642 With this information, we can now code our function. Recall the fcttemplate as
643 defined in Listing \ref{lst:template} and fill in the command execution as shown
644 in Listing \ref{lst:coding}. \\
645
646 \begin{lstlisting}[caption={Coding the function},
647 label={lst:coding},
648 language=Python]
649 # construct the message
650 msg = nl.nlmsg_new(nltype=_familyid_(nlsock),
651 cmd=nl80211h.NL80211_CMD_NEW_INTERFACE,
652 flags=nlh.NLM_F_REQUEST | nlh.NLM_F_ACK)
653 nl.nla_put_u32(msg,card.phy,nl80211h.NL80211_ATTR_WIPHY)
654 nl.nla_put_string(msg,vdev,nl80211h.NL80211_ATTR_IFNAME)
655 nl.nla_put_u32(msg,IFTYPES.index(mode),nl80211h.NL80211_ATTR_IFTYPE)
656
657 # send, receive and parse return results, returning the new Card
658 nl.nl_sendmsg(nlsock,msg)
659 rmsg = nl.nl_recvmsg(nlsock) # success returns new device attributes
660 return Card(card.phy,vdev,nl.nla_find(rmsg,nl80211h.NL80211_ATTR_IFINDEX))
661 \end{lstlisting}
662
663 We construct a new GENLMsg passing the nl80211 family id, the command we got
664 earlier and flags specifying that this is a request and we want to get an ACK
665 back\footnote{libnl.py always forces an ACK and handles the underlying process
666 of receiving it}. Now, add each attribute to the message. Note the order: value,
667 then attribute. With the message constructed, send it to the kernel, get the
668 results, parse and return them.\\
669
670 Rather simple, in fact the hardest part is figuring out what to send to the kernel.
671 Everything else is handled behind the scenes by libnl.py.
672
673 \begin{appendices}
674 \section{API: pyw.py}\label{sec:pywapi}
675
676 \subsection{Constants}
677 \begin{itemize}
678 \item \textbf{\_FAM80211ID\_}: Global netlink family id of nl80211. Do not touch
679 \item \textbf{IFTYPES}: redefined (from nl80211\_h.py) interface modes
680 \item \textbf{MNTRFLAGS}: redefined (from nl80211\_h.py) monitor mode flags
681 \item \textbf{TXPOWERSETTINGS}: redefined (from nl80211\_h.py) power level settings
682 \end{itemize}
683
684 \subsection{Objects/Classes}
685 \textbf{Card} A wrapper around a tuple
686 \texttt{t = (physical index,device name,interface index)}
687 which exposes the following properties through '.':
688 \begin{itemize}
689 \item \textbf{phy}: physical index
690 \item \textbf{dev}: device name
691 \item \textbf{idx}: interface index (ifindex)
692 \end{itemize}
693 Because the underlying Netlink calls will sometimes require the physical index,
694 sometimes the device name, and sometimes the ifindex, pyw functions accept a Card,
695 object. This allows callers to use pyw functions without having to remember which
696 identifier the function requires. However, in some cases the function requires
697 a dev or accepts both. See the next section on functions.\\
698
699 While callers could create their own Cards, it is recommend to use one of the
700 following
701 \begin{itemize}
702 \item \textbf{pyw.getcard} returns a Card object from a given dev
703 \item \textbf{pyw.devinfo} returns the dict info where info['card'] is the Card
704 object. This function will take either a card or a dev
705 \item \textbf{pyw.devadd} returns a new Card object
706 \item \textbf{pyw.devadd} returns a new Card object
707 \item \textbf{pyw.ifaces} returns a list of tuples t = (Card,mode) sharing the
708 same phy as a given device to do so. It is also recommended to periodically
709 validate the Card. On some cheaper usb wireless nics, there are periodic
710 disconnects which results in a new phy and ifindex.
711 \end{itemize}
712
713 \subsection{Functions}
714 \begin{itemize}
715 \item interfaces(): (ifconfig), type: filesystem, returns list of all network
716 device names
717 \item isinterface(dev): (ifconfig <dev>) type: filesystem, checks that dev is a
718 device name
719 \item winterfaces(iosock=None): (iwconfig), type: ioctl, list wireless device
720 names
721 \item iswireless(dev,iosock=None): (iwconfig <dev>), type: ioctl, check dev is a
722 wireless interface
723 \item phylist(): (iw phy | grep wiphy) type: N/A, list phy indexes and phy names
724 present on system
725 \item regget(nlsock=None: (iw reg get), type: netlink, get regulatory domain
726 \item regset(rd,nlsock=None): (iw reg set <rd>), type: netlink, set regulatory domain
727 to rd
728 \item getcard(dev,nlsock=None) (N/A), type: hybrid netlink and ioctl: get a Card
729 object for dev
730 \item validcard(card,nlsock=None): (N/A), type: (hyrbrid netlink and ioctl), verify
731 card is still valid
732 \item macget(card,iosock=None): (ifconfig), type: ioctl, determine if card is up
733 or down
734 \item macset(card,mac,iosock=None): (ifconfig card.<dev> hw ether <mac>), type:
735 ioctl, set card's hw address to mac
736 \item isup(card,iosock=None): (ifconfig card.<dev>)
737 \item up(card,iosock=None) (ifconfig card.<dev> up), type: ioctl, bring card up
738 \item down(card,iosock=None): (ifconfig card.<dev> down), type: ioctl, bring card
739 down
740 \item isblocked(card): (rfkill list <rfkill\_idx>): type N/A returns tuple
741 (Soft Block State, Hard Block State)
742 \item block(card): (rfkill block <rfkill\_idx>) type: N/A, soft blocks card
743 \item unblock(card): (rfkill unblock <rfkill\_idx>) type: N/A, removes the soft
744 block on card
745 \item pwrsaveget(card,nlsock=None) (iw dev card.<dev> get power\_save) type: netlink
746 get card's power save state True = on, False = off
747 \item pwrsaveset(card,on,nlsock=None) (iw dev card.<dev> set power\_save <on>) type:
748 netlink, set card's power save state True = on, False = off
749 \item covclassget(card,nlsock=None) (iw phy card.<phy> get coverage <cc>) type:
750 netlink get card's coverage class
751 \item covclassset(card,cc,nlsock=None) (iw phy card.<phy> set coverage <cc>) type:
752 netlink set card's coverage class
753 \item retryshortget(card,nlsock=None) (iw phy card.<phy> info | grep 'retry short')
754 type:netlink get card's retry short limit
755 \item retryshortset(card,lim,nlsock=None) (iw phy card.<phy> set retry short <lim>)
756 type:netlink set card's retry short limit. NOTE: although 255 is specified as the
757 max limit for this and the long retry, kernel v4 will not allow it.
758 \item retrylongget(card,nlsock=None) (iw phy card.<phy> info | grep 'retry long')
759 type:netlink get card's retry long limit
760 \item retrylongset(card,lim,nlsock=None) (iw phy card.<phy> set retry long <lim>)
761 type:netlink set card's retry long limit
762 \item rtsthreshget(card,nlsock=None) (iw phy card.<phy> info | grep rts) type:
763 netlink set card's RTS threshold
764 \item rtsthreshset(card,thresh,nlsock=None) (iw phy card.<phy> set rts <thresh>) type:
765 netlink set card's RTS threshold
766 \item fragthreshget(card,nlsock=None) (iw phy card.<phy> info | grep frag) type:
767 netlink get card's fragmentation threshold
768 \item fragthreshset(card,thresh,nlsock=None) (iw phy card.<phy> set frag <thresh>) type:
769 netlink set card's fragmentation threshold
770 \item ifaddrget(card,iosock=None): (ifconfig card.<dev>), type: ioctl, get ip4 address,
771 netmask and broadcast address of card
772 \item ifaddrset(card,ipaddr,netmask,broadcast,iosock=None): (ifconfig card/<dev>
773 <ipaddr> netmask <netmask> broadcast <broadcast>), type: ioctl, set the interface
774 addresses of the card
775 \item inetset(card,ipaddr,iosock=None): (ifconfig card.<dev> <ipaddr>), type: ioctl,
776 set the card's ip4 address
777 \item maskset(card,netmask,iosock=None): (ifconfig card.<dev> netmask <netmask>),
778 type: ioctl, set the card's netmask
779 \item bcastset(card,broadcast,iosock=None): (ifconfig card.<dev> broadcast
780 <broadcast>), type: ioctl, set the card's broadcast address
781 \item devfreqs(card,nlsock=None): (iw phy card.phy info), type: netlink, get card's
782 supported frequencies
783 \item devchs(card,nlsock=None): (iw phy card.phy info), type: netlink, get card's
784 supported channels
785 \item devstds(card,nlsock=None): (iwconfig card.<dev> | grep IEEE), type: nlsock,
786 returns a list of card's 802.11 supported standards by letter designator
787 \item devmodes(card,nlsock=None): (iw phy card.phy info | grep interface), type:
788 netlink, get card's supported modes
789 \item devcmds(card,nlsock=None): (iw phy card.phy info | grep commands), type:
790 netlink, get card's supported commands
791 \item ifinfo(card,iosock=None): (ifconfig card.<dev>), type: ioctl, get hardware
792 related info for card
793 \item devinfo(card,nlsock=None): (iw dev card.<dev> info), type: netlink, get info
794 for dev
795 \item phyinfo(card,nlsock=None): (iw phy card.<phy> info), type: netlink, get info
796 for phy
797 \item ifaces(card,nlsock=None): (APX iw card.dev | grep phy\#), type: netlink, get all
798 cards (w/ modes) of interfaces sharing the same phy as card
799 \item txset(card,pwr,lvl,nlsock=None) (iw phy phy0 set txpower <lvl> <pwr>), type:
800 netlink,sets the tx power to pwr (in dBm) with level setting lvl
801 \item txget(card,iosock=None): (iwconfig card.<dev> | grep Tx-Power card), type:
802 ioctl, get card's transmission power
803 \item chget(card,nlsock=None): (iw dev <card.dev> info | grep channel), type:
804 netlink, get card's current channel
805 \item chset(card,ch,chw=None,nlsock=None): iw phy <card.phy> set channel <ch> <chw>),
806 type: netlink, set card's current channel to ch with width chw
807 \item freqget(card,nlsock=None): (iw dev <card.dev> info | grep channel), type:
808 netlink, get card's current frequency
809 \item freqset(card,rf,chw=None,nlsock=None): iw phy <card.phy> set freq <rf> <chw>),
810 type: netlink, set card's current frequency to rf with width chw
811 \item devmodes(card,iosock=None): (iw phy card.<phy>), type: netlink, get modes
812 supported by card
813 \item modeset(card,mode,flags=None,nlsock=None): (iw dev card.<dev> set type <mode>
814 [flags]), type: netlink, set card's mode to mode with flags (if mode is monitor)
815 \item modeget(card,nlsock=None): (iw dev card.<dev> info | grep mode), type: netlink,
816 get card's mode
817 \item devset(card,ndev,nlsock=None): (N/A) sets the dev (name) of card to ndev
818 \item phyadd(phy,vnic,mode,flags=None,nlsock=None): (iw phy <phy> interface add <vnic>
819 type <mode> flags <flags>)\footnote{There is a bug in some kernel v4.4.0-x
820 where the given dev name is ignored and a system chosen one is used instead. See
821 https://wraithwireless.wordpress.com. Whenever possible, use devadd to create
822 interfaces instead.}, type: netlink, creates a new virtual interface with dev vdev,
823 in mode and using flags. Note: flags are only supported when creating a monitor mode
824 \item devadd(card (or ifindex),vnic,mode,[flags],nlsock=None): (iw phy card.<dev>
825 interface add <vnic> type <mode> flags <flags>), type: netlink, creates a new virtual
826 interface with dev vdev, in mode and using flags. Note: flags are only supported
827 when creating a monitor mode. This function accepts either a Card object or a
828 ifindex.
829 \item devdel(card,nlsock=None): (iw card.<dev> del), type: netlink, deletes card
830 \begin{itemize}
831 \item isconnected(card,nlsock=None): (iw dev card.<dev> info | grep channel), type:
832 netlink, determines if card is connected
833 \item connect(card,ssid,bssid=None,rf=None,nlsock=None): (iw dev card.<dev> connect <ssid>
834 <rf> <bssid>) connects to AP SSID with BSSID
835 \item disconnect(card, nlsock=None): (iw dev card.<dev> disconnect), type: netlink,
836 disconnects card from AP
837 \item link(card, nlsock=None): (iw dev card.<dev> link), type: netlink, displays
838 link specific details, i.e. AP details that card is connected to
839 \item stainfo(card, mac, nlsock=None): (iw dev card.<dev> link) type: netlink, displays
840 tx, rx metrics of the AP that card is connected to
841 \item \_hex2mac\_(v): returns a ':' separated mac address from byte stream v
842 \item \_mac2hex\_(v): returns a hex string corresponding to mac address v
843 \item \_hex2ip4\_(v): returns a '.' separated ip4 address from byte stream v
844 \item \_validip4\_(addr): determines if addr is a valid ip4 address
845 \item \_validmac\_(addr): determines if addr is a valid mac address
846 \item \_issetf\_(flags,flag): determines if flag is set in flags
847 \item \_setf\_(flags,flag): set flag in flags to on
848 \item \_unsetf\_(flags,flag): set flag in flags to off
849 \item \_familyid\_(nlsock): returns and sets the Netlink family id for nl80211,
850 only called once per module import
851 \item \_ifindex\_(dev,iosock=None): returns dev's ifindex
852 \item \_flagsget\_(dev,iosock=None): get's the dev's interface flags
853 \item \_flagsset\_(dev,flags,iosock=None): set's the dev's interface flags
854 \item \_iftypes\_(i): returns the mode corresponding to i
855 \item \_bands\_(band): futher parses band attribute returns dict of bands
856 containting rf information and rate information
857 \item \_band\_rates\_(rs): extracts list of rates from the unpacked rates rs
858 \item \_band\_rfs\_(rfs): extracts list of RFs (and other data) from the unpacked
859 frequencies rfs
860 \item \_unparsed\_rfs\_(band): (legacy) returns a list of frequencies from the
861 unparsed byte string band
862 \item \_commands\_(command): converts the list of numeric commands to a list of
863 commands as strings
864 \item \_ciphers\_(cipher): returns a list of ciphers from the packed byte string
865 cipher
866 \item \_rateinfo\_(ri): returns parsed rate info from the packed byte string ri
867 \item \_iostub\_(fct,*argv): ioctl stub function, calls fct with parameter list
868 argv and an allocated ioctl socket
869 \item \_nlstub\_(fct,*argv): netlink stub function, calls fct with parameter list
870 argv and an allocated netlink socket
871 \end{itemize}
872 \end{itemize}
873
874 \section{API: channels.py}\label{sec:channels.api}
875 Channel, Frequency enumeration and conversions can be found in channels.py.
876
877 \subsection{Constants}
878 \begin{enumerate}
879 \item \textbf{CHTYPES}: imported channel types from nl80211\_h
880 \item \textbf{CHWIDTHS}: imported channel widths from nl80211\_h
881 \item \textbf{ISM\_24\_C2F}: Dict containing ISM channel (key) to frequency (value)
882 pairs
883 \item \textbf{ISM\_24\_F2C}: Dict containing ISM frequency (key) to channel (value)
884 pairs
885 \item \textbf{UNII\_5\_C2F}: Dict containing UNII 5Ghz channel (key) to frequency
886 (value) pairs
887 \item \textbf{UNII\_5\_F2C}: Dict containing UNII 5Ghz frequency (key) to channel
888 (value) pairs
889 \item \textbf{UNII\_4\_C2F}: Dict containing UNII upper 4Ghz channel (key) to
890 frequency (value) pairs
891 \item \textbf{UNII\_4\_F2C}: Dict containing UNII upper 4Ghz frequency (key) to
892 channel (value) pairs
893 \end{enumerate}
894
895 \subsection{Functions}
896 \begin{enumerate}
897 \item channels(): returns a list of all channels
898 \item freqs(): returns a list of all frequencies
899 \item ch2rf(c): convert channel c to frequency
900 \item rf2ch(f): convert frequency f to channel
901 \end{enumerate}
902
903 \section{API: hardware.py}\label{sec:hardwareapi}
904 Hardware related: driver, chipset, manufacturer and mac address utility functions
905 can be found in device.py.
906
907 \subsection{Constants}
908 \begin{enumerate}
909 \item \textbf{dpath}: path to system device details
910 \item \textbf{drvpath}: path to device drivers
911 \end{enumerate}
912
913 \subsection{Functions}
914 \begin{enumerate}
915 \item oui(mac): returns the oui portion of address <mac>
916 \item ulm(mac): returns the ulm portion of address <mac>
917 \item manufacturer(ouis,mac): returns the manufacturer name of <mac> given the
918 dict of <ouis>
919 \item randhw([ouis]): returns a random mac address. If the dict ouis is specified
920 will select a random oui from the dict otherwise will generate one
921 \item ifcard(dev): returns the device driver and chipset
922 \item ifdriver(dev): returns the device driver
923 \item ifchipset(driver): returns the chipset associated with driver
924 \end{enumerate}
925
926 \section{API: ouifetch.py}
927 The file ouifetch.py retrieves and saves a tab seperated file of oui to
928 manufacturer name for use by hardware.py functions. From a command line, type: \\
929
930 \subsection{Constants}
931 \begin{enumerate}
932 \item \textbf{OUIURL}: url of IEEE oui file
933 \item \textbf{OUIPATH}: path to default location PyRIC oui.txt file
934 \end{enumerate}
935
936 \subsection{Functions}
937 \begin{enumerate}
938 \item load([opath]): returns a dict of oui:manufacturer key->value pairs stored
939 in the text file at opath. If opath is not specified, uses the default
940 \item fetch([opath]): retrieves oui.txt from the IEEE website, parses the files
941 and stores the results in a PyRIC friendly format in opath. If opath is not
942 specified, uses the default. User must have root permissions in order to write
943 to default opath
944 \end{enumerate}
945
946 \section{API: rfkill.py}\label{sec:rfkillapi}
947 A port of the command line tool rfkill, rfkill.py writes and reads rfkill\_event
948 structures to /dev/rfkill using fcntl providing functionality to block and unblock
949 devices.
950
951 \subsection{Constants}
952 \begin{enumerate}
953 \item \textbf{RFKILL\_STATE}: list of boolean values corresponding to blocked,
954 unblocked
955 \end{enumerate}
956
957 \subsection{Functions}
958 \begin{enumerate}
959 \item rfkill\_list(): corresponds to rkill list, returns a dict of dicts name ->
960 \{idx, type, soft, hard\}. If type is 'wireless', then name will be of the form
961 phy<n> such that n is the physical index of the wireless card
962 \item rfkill\_block(idx): soft blocks the device at rfkill index idx
963 \item rfkill\_blockby(rtype): soft blocks all devices of type rtype
964 \item rfkill\_unblock(idx): turns off the soft block at rfkill index idx
965 \item rfkill\_unblockby(rtype): turns off the soft blocks of all devices of type
966 rtype
967 \item soft\_blocked{idx}: determines soft block state of device at rfkill index idx
968 \item hard\_blocked{idx}: determines hard block state of device at rfkill index idx
969 \item getidx(phy): returns the rfkill index of the device with physical index phy
970 \item getname(idx): returns the name of the device at rfkill index idx
971 \item gettype(idx): returns the type of the device at rfkill index idx
972 \end{enumerate}
973
974 \section{API: libnl.py}\label{sec:libnlapi}
975 Providing libnl similar functionality, libnl.py provides the interface between
976 pyw and the underlying nl80211 core. It relates similarily to libnl by providing
977 functions handling netlink messages and sockets and where possible uses similarly
978 named functions as those libnl to ease any transitions from C to PyRIC. However,
979 several liberties have been taken as libnl.py handles only nl80211 generic netlink
980 messages.
981
982 \subsection{Constants}
983 \begin{itemize}
984 \item \textbf{BUFSZ} default rx and tx buffer size
985 \end{itemize}
986
987 \subsection{Classes/Objects}
988 The two classes in libnl.py, NLSocket and GENLMsg, discussed in the following
989 sections subclass Python's builtin dict. This has been done IOT to take advantage
990 of dict's already existing functions and primarily their mutability and Python's
991 'pass by name' i.e. modifications in a function will be reflected in the caller.
992 This makes the classes very similar to the use C pointers to structs in libnl.
993
994 \subsubsection{NLSocket}
995 NLSocket is a wrapper around a netlink socket which exposes the following
996 properties through '.':
997 \begin{itemize}
998 \item \textbf{sock}: the actual socket
999 \item \textbf{fd}: the socket's file descriptor (deprecated)
1000 \item \textbf{tx}: size of the send buffer
1001 \item \textbf{rx}: size of the receive buffer
1002 \item \textbf{pid}: port id
1003 \item \textbf{grpm}: group mask
1004 \item \textbf{seq}: sequence number
1005 \item \textbf{timeout}: socket timeout
1006 \end{itemize}
1007 and has the following methods:
1008 \begin{itemize}
1009 \item incr(): increment sequence number
1010 \item send(pkt): sends pkt returning bytes sent
1011 \item recv(): returns received message (will block unless timeout is set)
1012 \item close(): close the socket
1013 \end{itemize}
1014
1015 NLSockets are created with nl\_socket\_alloc and must be freed with nl\_socket\_free.
1016 See Section \ref{sec:libnlfct}.
1017
1018 \subsubsection{GENLMsg}
1019 GENLMsg is a wrapper around a dict with the following key->value pairs:
1020 \begin{itemize}
1021 \item \textbf{len}: total message length including the header
1022 \item \textbf{nltype}: netlink type
1023 \item \textbf{flags}: message flags
1024 \item \textbf{seq}: seq. \#
1025 \item \textbf{pid}: port id
1026 \item \textbf{cmd}: generic netlink command
1027 \item \textbf{attrs}: list of message attributes. Each attribute is a tuple t =
1028 (attribute,value,datatype) where:
1029 \begin{itemize}
1030 \item \textbf{attribute}: netlink attribute type i.e. CTRL\_ATTR\_FAMILY\_ID
1031 \item \textbf{value}: the unpacked attribute value
1032 \item \textbf{datatype}: datatype of the attribute as defined in nelink\_h i.e.
1033 NLA\_U8
1034 \end{itemize}
1035 \end{itemize}
1036 NOTE: as discussed below, on sending, the seq. \# and port id are overridden with
1037 values of the netlink socket.\\
1038
1039 GENLMsg exposes the following properties:
1040 \begin{itemize}
1041 \item \textbf{len}: length of the message (get only)
1042 \item \textbf{vers}: returns 1 (default version) (get only)
1043 \item \textbf{nltype}: message content i.e. generic or nl80211 (get or set)
1044 \item \textbf{flags}: message flags (get or set)
1045 \item \textbf{seq}: current sequence \# (get or set)
1046 \item \textbf{pid}: port id (get or set)
1047 \item \textbf{cmd}: netlink command (get or set)
1048 \item \textbf{attrs}: attribute list (get only)
1049 \item \textbf{numattrs}: number of attributes (get only)
1050 \end{itemize}
1051
1052 GENLMsg has the following methods:
1053 \begin{itemize}
1054 \item \_\_repr\_\_(): returns a string representation useful for debugging
1055 \item tostream(): returns a packed netlink message
1056
1057 There are two methods of creating a GENLMsg. Create a new message (to send) with
1058 nlmsg\_new and create a message from a received packet with nlmsg\_fromstream.
1059 These are discussed below.
1060
1061 \subsection{Functions}\label{sec:libnlfct}
1062 \begin{itemize}
1063 \item \textbf{Netlink Socket Related}
1064 \begin{itemize}
1065 \item nl\_socket\_alloc(pid,grps,seq,rx,tx,timeout): creates a netlink socket
1066 with port id = pid, group mask = grps, initial seq. \# = seq, send and receive
1067 buffer size = tx and rx respectively and blocking timeout = timeout
1068 \item nl\_socket\_free(sock): closes the socket
1069 \item nl\_socket\_pid(sock): (deprecated for NLSocket.pid) returns the port id
1070 \item nl\_socket\_grpmask(sock): (deprecated for NLSocket.grpmask) returns the
1071 group mask
1072 \item nl\_sendmsg(sock,msg,override=False): sends the netlink msg over socket.
1073 NOTE: NLSockets will automatically set the port id and seq. \# regardless of
1074 their value in the message. If override is True, the message's pid and seq. \#
1075 will be used instead.
1076 \item nl\_recvmsg(sock): returns a GENLMsg or blocks unless the socket's timeout
1077 is set. Should only be called once per every nl\_sendmsg.
1078 \end{itemize}
1079 \item \textbf{Netlink Message Related}
1080 \begin{itemize}
1081 \item nlmsg\_new(nltype=None,cmd=None,pid=None,flags=None,attrs=None): creates a
1082 new GENLMsg with zero or more attributes defined.
1083 \item nlmsg\_fromstream(stream): parses the message in stream returning the
1084 corresponding GENLMsg
1085 \item nla\_parse(msg,l,mtype,stream,idx): parses the attributes in stream appending
1086 them to the attribute list of message where msg = the GENLMsg, l = the total
1087 length of the message, mtype = the message content (i.e. netlink type) stream is
1088 the original byte stream and idx is the index of the start of the attribute list
1089 \item nla\_parse\_nested(nested): returns the list of packed nested attributes
1090 extracted from the stream nested. Callers must unpack and parse the returned
1091 attributes themselves
1092 \item nla\_put(msg,v,a,t): appends the attribute a, with value v and datatype t
1093 to the msg's attribute list
1094 \item nla\_put\_<DATATYPE>(msg,v,a): eight specialized functions that append
1095 attribute a with the value v and type <DATATYPE> to msg's attribute list
1096 \item nla\_putat(msg,i,v,a,d): puts attribute a, with value v and datatype d at
1097 index i in msg's attribute list.
1098 \item nla\_pop(msg,i): removes the attribute tuple at index i, returning the popped
1099 tuple
1100 \item nla\_find(msg,a,value=True): returns the first attribute a in msg's attribute
1101 list. If value returns only the value otherwise returns the attribute tuple
1102 \item nla\_get(msg,i,value=True): returns the attribute at index i. If value returns
1103 only the value otherwise returns the attribute tuple
1104 \item \_nla\_strip(v): (private) strips padding bytes from the end of v
1105 \item \_attrpack(a,v,d): (private) packs the attribute tuple
1106 \end{itemize}
1107 \item \_maxbufsz\_(): (private) returns the maximum allowable socket buffer size
1108 \end{itemize}
1109 \end{itemize}
1110
1111 \section{API: libio.py}\label{sec:libioapi}
1112 A very basic interface to ioctl, libio provides socket creation, deletion and
1113 transfer.
1114
1115 \subsection{Functions}
1116 \begin{enumerate}
1117 \item io\_socket\_alloc(): returns an ioctl socket
1118 \item io\_socket\_free(iosock): closes the ioctl socket iosock
1119 \item io\_transfer\_(iosock,flag,ifreq): sends the ifreq structure with sockios
1120 control call flag to the kernel and returns the received ifreq structure
1121 \end{enumerate}
1122
1123 \section{Copyright and License}\label{sec:copy}
1124 PYRIC: Python Radio Interface Controller v0.1.6.4\\
1125
1126 Copyright (C) 2016 Dale V. Patterson ([email protected])\\
1127
1128 This program is free software: you can redistribute it and/or modify it under
1129 the terms of the GNU General Public License\cite{gplv3} as published by the Free
1130 Software Foundation, either version 3 of the License, or (at your option) any
1131 later version.\\
1132
1133 Redistribution and use in source and binary forms, with or without modifications,
1134 are permitted provided that the following conditions are met:
1135 \begin{itemize}
1136 \item Redistributions of source code must retain the above copyright notice, this
1137 list of conditions and the following disclaimer.
1138 \item Redistributions in binary form must reproduce the above copyright notice,
1139 this list of conditions and the following disclaimer in the documentation and/or
1140 other materials provided with the distribution.
1141 \item Neither the name of the orginal author Dale V. Patterson nor the names of
1142 any contributors may be used to endorse or promote products derived from this
1143 software without specific prior written permission.
1144 \end{itemize}
1145
1146 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND
1147 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
1148 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
1149 IN NO EVENT SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
1150 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
1151 OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
1152 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
1153 STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
1154 OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\\
1155
1156 PyRIC is free software but use, duplication or disclosure by the United States
1157 Government is subject to the restrictions set forth in DFARS 252.227-7014.\\
1158
1159 Use of this software is governed by all applicable federal, state and local
1160 laws of the United States and subject to the laws of the country where you reside.
1161 The copyright owner and contributors will be not be held liable for use of this
1162 software in furtherance of or with intent to commit any fraudulent or other illegal
1163 activities, or otherwise in violation of any applicable law, regulation or legal
1164 agreement.\\
1165
1166 See http://www.gnu.org/licenses/licenses.html for a copy of the GNU General Public
1167 License.
1168 \end{appendices}
1169
1170 \bibliographystyle{acm}
1171 \bibliography{PyRIC}
1172 %\addcontentsline{toc}{chapter}{Bibliography}
1173
1174 \end{document}