1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
|
//go:build linux
// +build linux
package wifi
import (
"bytes"
"crypto/sha1"
"net"
"os"
"time"
"unicode/utf8"
"github.com/mdlayher/genetlink"
"github.com/mdlayher/netlink"
"github.com/mdlayher/netlink/nlenc"
"golang.org/x/crypto/pbkdf2"
"golang.org/x/sys/unix"
)
// A client is the Linux implementation of osClient, which makes use of
// netlink, generic netlink, and nl80211 to provide access to WiFi device
// actions and statistics.
type client struct {
c *genetlink.Conn
familyID uint16
familyVersion uint8
}
// newClient dials a generic netlink connection and verifies that nl80211
// is available for use by this package.
func newClient() (*client, error) {
c, err := genetlink.Dial(nil)
if err != nil {
return nil, err
}
// Make a best effort to apply the strict options set to provide better
// errors and validation. We don't apply Strict in the constructor because
// this library is widely used on a range of kernels and we can't guarantee
// it will always work on older kernels.
for _, o := range []netlink.ConnOption{
netlink.ExtendedAcknowledge,
netlink.GetStrictCheck,
} {
_ = c.SetOption(o, true)
}
return initClient(c)
}
func initClient(c *genetlink.Conn) (*client, error) {
family, err := c.GetFamily(unix.NL80211_GENL_NAME)
if err != nil {
// Ensure the genl socket is closed on error to avoid leaking file
// descriptors.
_ = c.Close()
return nil, err
}
return &client{
c: c,
familyID: family.ID,
familyVersion: family.Version,
}, nil
}
// Close closes the client's generic netlink connection.
func (c *client) Close() error { return c.c.Close() }
// Interfaces requests that nl80211 return a list of all WiFi interfaces present
// on this system.
func (c *client) Interfaces() ([]*Interface, error) {
// Ask nl80211 to dump a list of all WiFi interfaces
msgs, err := c.get(
unix.NL80211_CMD_GET_INTERFACE,
netlink.Dump,
nil,
nil,
)
if err != nil {
return nil, err
}
return parseInterfaces(msgs)
}
// Connect starts connecting the interface to the specified ssid.
func (c *client) Connect(ifi *Interface, ssid string) error {
// Ask nl80211 to connect to the specified SSID.
_, err := c.get(
unix.NL80211_CMD_CONNECT,
netlink.Acknowledge,
ifi,
func(ae *netlink.AttributeEncoder) {
ae.Bytes(unix.NL80211_ATTR_SSID, []byte(ssid))
ae.Uint32(unix.NL80211_ATTR_AUTH_TYPE, unix.NL80211_AUTHTYPE_OPEN_SYSTEM)
},
)
return err
}
// Disconnect disconnects the interface.
func (c *client) Disconnect(ifi *Interface) error {
// Ask nl80211 to disconnect.
_, err := c.get(
unix.NL80211_CMD_DISCONNECT,
netlink.Acknowledge,
ifi,
nil,
)
return err
}
// ConnectWPAPSK starts connecting the interface to the specified SSID using
// WPA.
func (c *client) ConnectWPAPSK(ifi *Interface, ssid, psk string) error {
// Ask nl80211 to connect to the specified SSID with key..
_, err := c.get(
unix.NL80211_CMD_CONNECT,
netlink.Acknowledge,
ifi,
func(ae *netlink.AttributeEncoder) {
// TODO(mdlayher): document these or build from bitflags.
const (
cipherSuites = 0xfac04
akmSuites = 0xfac02
)
ae.Bytes(unix.NL80211_ATTR_SSID, []byte(ssid))
ae.Uint32(unix.NL80211_ATTR_WPA_VERSIONS, unix.NL80211_WPA_VERSION_2)
ae.Uint32(unix.NL80211_ATTR_CIPHER_SUITE_GROUP, cipherSuites)
ae.Uint32(unix.NL80211_ATTR_CIPHER_SUITES_PAIRWISE, cipherSuites)
ae.Uint32(unix.NL80211_ATTR_AKM_SUITES, akmSuites)
ae.Flag(unix.NL80211_ATTR_WANT_1X_4WAY_HS, true)
ae.Bytes(
unix.NL80211_ATTR_PMK,
wpaPassphrase([]byte(ssid), []byte(psk)),
)
ae.Uint32(unix.NL80211_ATTR_AUTH_TYPE, unix.NL80211_AUTHTYPE_OPEN_SYSTEM)
},
)
return err
}
// wpaPassphrase computes a WPA passphrase given an SSID and preshared key.
func wpaPassphrase(ssid, psk []byte) []byte {
return pbkdf2.Key(psk, ssid, 4096, 32, sha1.New)
}
// BSS requests that nl80211 return the BSS for the specified Interface.
func (c *client) BSS(ifi *Interface) (*BSS, error) {
msgs, err := c.get(
unix.NL80211_CMD_GET_SCAN,
netlink.Dump,
ifi,
func(ae *netlink.AttributeEncoder) {
if ifi.HardwareAddr != nil {
ae.Bytes(unix.NL80211_ATTR_MAC, ifi.HardwareAddr)
}
},
)
if err != nil {
return nil, err
}
return parseBSS(msgs)
}
// StationInfo requests that nl80211 return all station info for the specified
// Interface.
func (c *client) StationInfo(ifi *Interface) ([]*StationInfo, error) {
msgs, err := c.get(
unix.NL80211_CMD_GET_STATION,
netlink.Dump,
ifi,
func(ae *netlink.AttributeEncoder) {
if ifi.HardwareAddr != nil {
ae.Bytes(unix.NL80211_ATTR_MAC, ifi.HardwareAddr)
}
},
)
if err != nil {
return nil, err
}
if len(msgs) == 0 {
return nil, os.ErrNotExist
}
stations := make([]*StationInfo, len(msgs))
for i := range msgs {
if stations[i], err = parseStationInfo(msgs[i].Data); err != nil {
return nil, err
}
}
return stations, nil
}
// get performs a request/response interaction with nl80211.
func (c *client) get(
cmd uint8,
flags netlink.HeaderFlags,
ifi *Interface,
// May be nil; used to apply optional parameters.
params func(ae *netlink.AttributeEncoder),
) ([]genetlink.Message, error) {
ae := netlink.NewAttributeEncoder()
ifi.encode(ae)
if params != nil {
// Optionally apply more parameters to the attribute encoder.
params(ae)
}
// Note: don't send netlink.Acknowledge or we get an extra message back from
// the kernel which doesn't seem useful as of now.
return c.execute(cmd, flags, ae)
}
// execute executes the specified command with additional header flags and input
// netlink request attributes. The netlink.Request header flag is automatically
// set.
func (c *client) execute(
cmd uint8,
flags netlink.HeaderFlags,
ae *netlink.AttributeEncoder,
) ([]genetlink.Message, error) {
b, err := ae.Encode()
if err != nil {
return nil, err
}
return c.c.Execute(
genetlink.Message{
Header: genetlink.Header{
Command: cmd,
Version: c.familyVersion,
},
Data: b,
},
// Always pass the genetlink family ID and request flag.
c.familyID,
netlink.Request|flags,
)
}
// parseInterfaces parses zero or more Interfaces from nl80211 interface
// messages.
func parseInterfaces(msgs []genetlink.Message) ([]*Interface, error) {
ifis := make([]*Interface, 0, len(msgs))
for _, m := range msgs {
attrs, err := netlink.UnmarshalAttributes(m.Data)
if err != nil {
return nil, err
}
var ifi Interface
if err := (&ifi).parseAttributes(attrs); err != nil {
return nil, err
}
ifis = append(ifis, &ifi)
}
return ifis, nil
}
// encode provides an encoding function for ifi's attributes. If ifi is nil,
// encode is a no-op.
func (ifi *Interface) encode(ae *netlink.AttributeEncoder) {
if ifi == nil {
return
}
// Mandatory.
ae.Uint32(unix.NL80211_ATTR_IFINDEX, uint32(ifi.Index))
}
// idAttrs returns the netlink attributes required from an Interface to retrieve
// more data about it.
func (ifi *Interface) idAttrs() []netlink.Attribute {
return []netlink.Attribute{
{
Type: unix.NL80211_ATTR_IFINDEX,
Data: nlenc.Uint32Bytes(uint32(ifi.Index)),
},
{
Type: unix.NL80211_ATTR_MAC,
Data: ifi.HardwareAddr,
},
}
}
// parseAttributes parses netlink attributes into an Interface's fields.
func (ifi *Interface) parseAttributes(attrs []netlink.Attribute) error {
for _, a := range attrs {
switch a.Type {
case unix.NL80211_ATTR_IFINDEX:
ifi.Index = int(nlenc.Uint32(a.Data))
case unix.NL80211_ATTR_IFNAME:
ifi.Name = nlenc.String(a.Data)
case unix.NL80211_ATTR_MAC:
ifi.HardwareAddr = net.HardwareAddr(a.Data)
case unix.NL80211_ATTR_WIPHY:
ifi.PHY = int(nlenc.Uint32(a.Data))
case unix.NL80211_ATTR_IFTYPE:
// NOTE: InterfaceType copies the ordering of nl80211's interface type
// constants. This may not be the case on other operating systems.
ifi.Type = InterfaceType(nlenc.Uint32(a.Data))
case unix.NL80211_ATTR_WDEV:
ifi.Device = int(nlenc.Uint64(a.Data))
case unix.NL80211_ATTR_WIPHY_FREQ:
ifi.Frequency = int(nlenc.Uint32(a.Data))
}
}
return nil
}
// parseBSS parses a single BSS with a status attribute from nl80211 BSS messages.
func parseBSS(msgs []genetlink.Message) (*BSS, error) {
for _, m := range msgs {
attrs, err := netlink.UnmarshalAttributes(m.Data)
if err != nil {
return nil, err
}
for _, a := range attrs {
if a.Type != unix.NL80211_ATTR_BSS {
continue
}
nattrs, err := netlink.UnmarshalAttributes(a.Data)
if err != nil {
return nil, err
}
// The BSS which is associated with an interface will have a status
// attribute
if !attrsContain(nattrs, unix.NL80211_BSS_STATUS) {
continue
}
var bss BSS
if err := (&bss).parseAttributes(nattrs); err != nil {
return nil, err
}
return &bss, nil
}
}
return nil, os.ErrNotExist
}
// parseAttributes parses netlink attributes into a BSS's fields.
func (b *BSS) parseAttributes(attrs []netlink.Attribute) error {
for _, a := range attrs {
switch a.Type {
case unix.NL80211_BSS_BSSID:
b.BSSID = net.HardwareAddr(a.Data)
case unix.NL80211_BSS_FREQUENCY:
b.Frequency = int(nlenc.Uint32(a.Data))
case unix.NL80211_BSS_BEACON_INTERVAL:
// Raw value is in "Time Units (TU)". See:
// https://en.wikipedia.org/wiki/Beacon_frame
b.BeaconInterval = time.Duration(nlenc.Uint16(a.Data)) * 1024 * time.Microsecond
case unix.NL80211_BSS_SEEN_MS_AGO:
// * @NL80211_BSS_SEEN_MS_AGO: age of this BSS entry in ms
b.LastSeen = time.Duration(nlenc.Uint32(a.Data)) * time.Millisecond
case unix.NL80211_BSS_STATUS:
// NOTE: BSSStatus copies the ordering of nl80211's BSS status
// constants. This may not be the case on other operating systems.
b.Status = BSSStatus(nlenc.Uint32(a.Data))
case unix.NL80211_BSS_INFORMATION_ELEMENTS:
ies, err := parseIEs(a.Data)
if err != nil {
return err
}
// TODO(mdlayher): return more IEs if they end up being generally useful
for _, ie := range ies {
switch ie.ID {
case ieSSID:
b.SSID = decodeSSID(ie.Data)
}
}
}
}
return nil
}
// parseStationInfo parses StationInfo attributes from a byte slice of
// netlink attributes.
func parseStationInfo(b []byte) (*StationInfo, error) {
attrs, err := netlink.UnmarshalAttributes(b)
if err != nil {
return nil, err
}
var info StationInfo
for _, a := range attrs {
switch a.Type {
case unix.NL80211_ATTR_MAC:
info.HardwareAddr = net.HardwareAddr(a.Data)
case unix.NL80211_ATTR_STA_INFO:
nattrs, err := netlink.UnmarshalAttributes(a.Data)
if err != nil {
return nil, err
}
if err := (&info).parseAttributes(nattrs); err != nil {
return nil, err
}
// Parsed the necessary data.
return &info, nil
}
}
// No station info found
return nil, os.ErrNotExist
}
// parseAttributes parses netlink attributes into a StationInfo's fields.
func (info *StationInfo) parseAttributes(attrs []netlink.Attribute) error {
for _, a := range attrs {
switch a.Type {
case unix.NL80211_STA_INFO_CONNECTED_TIME:
// Though nl80211 does not specify, this value appears to be in seconds:
// * @NL80211_STA_INFO_CONNECTED_TIME: time since the station is last connected
info.Connected = time.Duration(nlenc.Uint32(a.Data)) * time.Second
case unix.NL80211_STA_INFO_INACTIVE_TIME:
// * @NL80211_STA_INFO_INACTIVE_TIME: time since last activity (u32, msecs)
info.Inactive = time.Duration(nlenc.Uint32(a.Data)) * time.Millisecond
case unix.NL80211_STA_INFO_RX_BYTES64:
info.ReceivedBytes = int(nlenc.Uint64(a.Data))
case unix.NL80211_STA_INFO_TX_BYTES64:
info.TransmittedBytes = int(nlenc.Uint64(a.Data))
case unix.NL80211_STA_INFO_SIGNAL:
// * @NL80211_STA_INFO_SIGNAL: signal strength of last received PPDU (u8, dBm)
// Should just be cast to int8, see code here: https://git.kernel.org/pub/scm/linux/kernel/git/jberg/iw.git/tree/station.c#n378
info.Signal = int(int8(a.Data[0]))
case unix.NL80211_STA_INFO_RX_PACKETS:
info.ReceivedPackets = int(nlenc.Uint32(a.Data))
case unix.NL80211_STA_INFO_TX_PACKETS:
info.TransmittedPackets = int(nlenc.Uint32(a.Data))
case unix.NL80211_STA_INFO_TX_RETRIES:
info.TransmitRetries = int(nlenc.Uint32(a.Data))
case unix.NL80211_STA_INFO_TX_FAILED:
info.TransmitFailed = int(nlenc.Uint32(a.Data))
case unix.NL80211_STA_INFO_BEACON_LOSS:
info.BeaconLoss = int(nlenc.Uint32(a.Data))
case unix.NL80211_STA_INFO_RX_BITRATE, unix.NL80211_STA_INFO_TX_BITRATE:
rate, err := parseRateInfo(a.Data)
if err != nil {
return err
}
// TODO(mdlayher): return more statistics if they end up being
// generally useful
switch a.Type {
case unix.NL80211_STA_INFO_RX_BITRATE:
info.ReceiveBitrate = rate.Bitrate
case unix.NL80211_STA_INFO_TX_BITRATE:
info.TransmitBitrate = rate.Bitrate
}
}
// Only use 32-bit counters if the 64-bit counters are not present.
// If the 64-bit counters appear later in the slice, they will overwrite
// these values.
if info.ReceivedBytes == 0 && a.Type == unix.NL80211_STA_INFO_RX_BYTES {
info.ReceivedBytes = int(nlenc.Uint32(a.Data))
}
if info.TransmittedBytes == 0 && a.Type == unix.NL80211_STA_INFO_TX_BYTES {
info.TransmittedBytes = int(nlenc.Uint32(a.Data))
}
}
return nil
}
// rateInfo provides statistics about the receive or transmit rate of
// an interface.
type rateInfo struct {
// Bitrate in bits per second.
Bitrate int
}
// parseRateInfo parses a rateInfo from netlink attributes.
func parseRateInfo(b []byte) (*rateInfo, error) {
attrs, err := netlink.UnmarshalAttributes(b)
if err != nil {
return nil, err
}
var info rateInfo
for _, a := range attrs {
switch a.Type {
case unix.NL80211_RATE_INFO_BITRATE32:
info.Bitrate = int(nlenc.Uint32(a.Data))
}
// Only use 16-bit counters if the 32-bit counters are not present.
// If the 32-bit counters appear later in the slice, they will overwrite
// these values.
if info.Bitrate == 0 && a.Type == unix.NL80211_RATE_INFO_BITRATE {
info.Bitrate = int(nlenc.Uint16(a.Data))
}
}
// Scale bitrate to bits/second as base unit instead of 100kbits/second.
// * @NL80211_RATE_INFO_BITRATE: total bitrate (u16, 100kbit/s)
info.Bitrate *= 100 * 1000
return &info, nil
}
// attrsContain checks if a slice of netlink attributes contains an attribute
// with the specified type.
func attrsContain(attrs []netlink.Attribute, typ uint16) bool {
for _, a := range attrs {
if a.Type == typ {
return true
}
}
return false
}
// decodeSSID safely parses a byte slice into UTF-8 runes, and returns the
// resulting string from the runes.
func decodeSSID(b []byte) string {
buf := bytes.NewBuffer(nil)
for len(b) > 0 {
r, size := utf8.DecodeRune(b)
b = b[size:]
buf.WriteRune(r)
}
return buf.String()
}
|