wlanstruct.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. package wifi
  2. /*
  3. Native WLAN API structures
  4. The Windows WLAN API (wlanapi.dll) returns its results as C structures.
  5. They are copied into Go byte slices by wlanapi_windows.go and decoded here
  6. at fixed offsets, so the layout does not depend on Go's struct alignment
  7. (which differs from the C layout on 32-bit targets) and the decoding can
  8. be tested on every platform.
  9. */
  10. import (
  11. "encoding/binary"
  12. "errors"
  13. "strconv"
  14. "strings"
  15. "unicode/utf16"
  16. )
  17. // Sizes of the fixed-size WLAN API structures, in bytes
  18. const (
  19. wlanInterfaceInfoSize = 532 //WLAN_INTERFACE_INFO
  20. wlanAvailableNetworkSize = 628 //WLAN_AVAILABLE_NETWORK
  21. wlanBSSEntrySize = 360 //WLAN_BSS_ENTRY
  22. wlanConnectionAttrSize = 604 //WLAN_CONNECTION_ATTRIBUTES
  23. dot11SSIDSize = 36 //DOT11_SSID
  24. )
  25. // WLAN_AVAILABLE_NETWORK flags
  26. const (
  27. wlanAvailableNetworkConnected = 0x1
  28. wlanAvailableNetworkHasProfile = 0x2
  29. )
  30. var errWlanTruncated = errors.New("truncated WLAN API structure")
  31. type wlanInterfaceInfo struct {
  32. GUID [16]byte
  33. Description string
  34. State uint32
  35. }
  36. type wlanAvailableNetwork struct {
  37. ProfileName string
  38. SSID []byte
  39. BSSType uint32
  40. SignalQuality uint32
  41. SecurityEnabled bool
  42. AuthAlgorithm uint32
  43. CipherAlgorithm uint32
  44. Flags uint32
  45. }
  46. type wlanBSSEntry struct {
  47. SSID []byte
  48. PhyID uint32
  49. BSSID [6]byte
  50. BSSType uint32
  51. PhyType uint32
  52. RSSI int32
  53. LinkQuality uint32
  54. InRegDomain bool
  55. BeaconPeriod uint16
  56. Timestamp uint64
  57. HostTimestamp uint64
  58. Capability uint16
  59. CenterFreqKHz uint32
  60. Rates []uint16
  61. InformationElt []byte
  62. }
  63. type wlanConnectionAttributes struct {
  64. State uint32
  65. Mode uint32
  66. ProfileName string
  67. SSID []byte
  68. BSSType uint32
  69. BSSID [6]byte
  70. PhyType uint32
  71. PhyIndex uint32
  72. SignalQuality uint32
  73. RxRateKbps uint32
  74. TxRateKbps uint32
  75. SecurityEnabled bool
  76. OneXEnabled bool
  77. AuthAlgorithm uint32
  78. CipherAlgorithm uint32
  79. }
  80. type wlanPhyRadioState struct {
  81. PhyIndex uint32
  82. Software uint32
  83. Hardware uint32
  84. }
  85. // utf16String decodes a fixed size, NUL terminated WCHAR array
  86. func utf16String(b []byte) string {
  87. u := make([]uint16, 0, len(b)/2)
  88. for i := 0; i+1 < len(b); i += 2 {
  89. c := binary.LittleEndian.Uint16(b[i:])
  90. if c == 0 {
  91. break
  92. }
  93. u = append(u, c)
  94. }
  95. return string(utf16.Decode(u))
  96. }
  97. // dot11SSID decodes a DOT11_SSID (length + 32 bytes)
  98. func dot11SSID(b []byte) []byte {
  99. if len(b) < dot11SSIDSize {
  100. return nil
  101. }
  102. n := binary.LittleEndian.Uint32(b[0:4])
  103. if n > 32 {
  104. n = 32
  105. }
  106. return append([]byte{}, b[4:4+n]...)
  107. }
  108. // guidString formats a Windows GUID stored in its in-memory byte order
  109. func guidString(g [16]byte) string {
  110. le := binary.LittleEndian
  111. return strings.ToUpper(
  112. "{" + hex32(le.Uint32(g[0:4])) + "-" + hex16(le.Uint16(g[4:6])) + "-" + hex16(le.Uint16(g[6:8])) + "-" +
  113. hexBytes(g[8:10]) + "-" + hexBytes(g[10:16]) + "}")
  114. }
  115. func hex32(v uint32) string {
  116. return hexBytes([]byte{byte(v >> 24), byte(v >> 16), byte(v >> 8), byte(v)})
  117. }
  118. func hex16(v uint16) string { return hexBytes([]byte{byte(v >> 8), byte(v)}) }
  119. func hexBytes(b []byte) string {
  120. const digits = "0123456789abcdef"
  121. s := make([]byte, 0, len(b)*2)
  122. for _, c := range b {
  123. s = append(s, digits[c>>4], digits[c&0x0F])
  124. }
  125. return string(s)
  126. }
  127. // parseWlanInterfaceList decodes a WLAN_INTERFACE_INFO_LIST
  128. func parseWlanInterfaceList(b []byte) ([]wlanInterfaceInfo, error) {
  129. if len(b) < 8 {
  130. return nil, errWlanTruncated
  131. }
  132. n := int(binary.LittleEndian.Uint32(b[0:4]))
  133. if n < 0 || n > (len(b)-8)/wlanInterfaceInfoSize {
  134. return nil, errWlanTruncated
  135. }
  136. list := []wlanInterfaceInfo{}
  137. for i := 0; i < n; i++ {
  138. e := b[8+i*wlanInterfaceInfoSize : 8+(i+1)*wlanInterfaceInfoSize]
  139. info := wlanInterfaceInfo{
  140. Description: utf16String(e[16:528]),
  141. State: binary.LittleEndian.Uint32(e[528:532]),
  142. }
  143. copy(info.GUID[:], e[0:16])
  144. list = append(list, info)
  145. }
  146. return list, nil
  147. }
  148. // parseWlanAvailableNetworkList decodes a WLAN_AVAILABLE_NETWORK_LIST
  149. func parseWlanAvailableNetworkList(b []byte) ([]wlanAvailableNetwork, error) {
  150. if len(b) < 8 {
  151. return nil, errWlanTruncated
  152. }
  153. n := int(binary.LittleEndian.Uint32(b[0:4]))
  154. if n < 0 || n > (len(b)-8)/wlanAvailableNetworkSize {
  155. return nil, errWlanTruncated
  156. }
  157. le := binary.LittleEndian
  158. list := []wlanAvailableNetwork{}
  159. for i := 0; i < n; i++ {
  160. e := b[8+i*wlanAvailableNetworkSize : 8+(i+1)*wlanAvailableNetworkSize]
  161. list = append(list, wlanAvailableNetwork{
  162. ProfileName: utf16String(e[0:512]),
  163. SSID: dot11SSID(e[512:548]),
  164. BSSType: le.Uint32(e[548:552]),
  165. SignalQuality: le.Uint32(e[604:608]),
  166. SecurityEnabled: le.Uint32(e[608:612]) != 0,
  167. AuthAlgorithm: le.Uint32(e[612:616]),
  168. CipherAlgorithm: le.Uint32(e[616:620]),
  169. Flags: le.Uint32(e[620:624]),
  170. })
  171. }
  172. return list, nil
  173. }
  174. // parseWlanBSSList decodes a WLAN_BSS_LIST, including the information
  175. // elements that follow each entry
  176. func parseWlanBSSList(b []byte) ([]wlanBSSEntry, error) {
  177. if len(b) < 8 {
  178. return nil, errWlanTruncated
  179. }
  180. le := binary.LittleEndian
  181. total := int(le.Uint32(b[0:4]))
  182. if total < 8 || total > len(b) {
  183. total = len(b)
  184. }
  185. b = b[:total]
  186. n := int(le.Uint32(b[4:8]))
  187. if n < 0 || n > (len(b)-8)/wlanBSSEntrySize {
  188. return nil, errWlanTruncated
  189. }
  190. list := []wlanBSSEntry{}
  191. for i := 0; i < n; i++ {
  192. start := 8 + i*wlanBSSEntrySize
  193. e := b[start : start+wlanBSSEntrySize]
  194. entry := wlanBSSEntry{
  195. SSID: dot11SSID(e[0:36]),
  196. PhyID: le.Uint32(e[36:40]),
  197. BSSType: le.Uint32(e[48:52]),
  198. PhyType: le.Uint32(e[52:56]),
  199. RSSI: int32(le.Uint32(e[56:60])),
  200. LinkQuality: le.Uint32(e[60:64]),
  201. InRegDomain: e[64] != 0,
  202. BeaconPeriod: le.Uint16(e[66:68]),
  203. Timestamp: le.Uint64(e[72:80]),
  204. HostTimestamp: le.Uint64(e[80:88]),
  205. Capability: le.Uint16(e[88:90]),
  206. CenterFreqKHz: le.Uint32(e[92:96]),
  207. }
  208. copy(entry.BSSID[:], e[40:46])
  209. //WLAN_RATE_SET: rate count (documented as a byte length, but
  210. //wlansvc reports the number of rates), then up to 126 USHORT rates
  211. rateCount := int(le.Uint32(e[96:100]))
  212. if rateCount > 126 {
  213. rateCount = 126
  214. }
  215. for r := 0; r < rateCount; r++ {
  216. entry.Rates = append(entry.Rates, le.Uint16(e[100+r*2:]))
  217. }
  218. //Information elements, offset relative to the start of this entry
  219. ieOffset := int64(le.Uint32(e[352:356]))
  220. ieSize := int64(le.Uint32(e[356:360]))
  221. ieStart := int64(start) + ieOffset
  222. if ieSize > 0 && ieOffset >= wlanBSSEntrySize && ieStart+ieSize <= int64(len(b)) {
  223. entry.InformationElt = append([]byte{}, b[ieStart:ieStart+ieSize]...)
  224. }
  225. list = append(list, entry)
  226. }
  227. return list, nil
  228. }
  229. // parseWlanConnectionAttributes decodes WLAN_CONNECTION_ATTRIBUTES
  230. func parseWlanConnectionAttributes(b []byte) (*wlanConnectionAttributes, error) {
  231. if len(b) < wlanConnectionAttrSize {
  232. return nil, errWlanTruncated
  233. }
  234. le := binary.LittleEndian
  235. c := &wlanConnectionAttributes{
  236. State: le.Uint32(b[0:4]),
  237. Mode: le.Uint32(b[4:8]),
  238. ProfileName: utf16String(b[8:520]),
  239. //WLAN_ASSOCIATION_ATTRIBUTES at 520
  240. SSID: dot11SSID(b[520:556]),
  241. BSSType: le.Uint32(b[556:560]),
  242. PhyType: le.Uint32(b[568:572]),
  243. PhyIndex: le.Uint32(b[572:576]),
  244. SignalQuality: le.Uint32(b[576:580]),
  245. RxRateKbps: le.Uint32(b[580:584]),
  246. TxRateKbps: le.Uint32(b[584:588]),
  247. //WLAN_SECURITY_ATTRIBUTES at 588
  248. SecurityEnabled: le.Uint32(b[588:592]) != 0,
  249. OneXEnabled: le.Uint32(b[592:596]) != 0,
  250. AuthAlgorithm: le.Uint32(b[596:600]),
  251. CipherAlgorithm: le.Uint32(b[600:604]),
  252. }
  253. copy(c.BSSID[:], b[560:566])
  254. return c, nil
  255. }
  256. // parseWlanRadioState decodes WLAN_RADIO_STATE
  257. func parseWlanRadioState(b []byte) ([]wlanPhyRadioState, error) {
  258. if len(b) < 4 {
  259. return nil, errWlanTruncated
  260. }
  261. le := binary.LittleEndian
  262. n := int(le.Uint32(b[0:4]))
  263. if n > 64 {
  264. n = 64
  265. }
  266. if n < 0 || n > (len(b)-4)/12 {
  267. return nil, errWlanTruncated
  268. }
  269. list := []wlanPhyRadioState{}
  270. for i := 0; i < n; i++ {
  271. e := b[4+i*12 : 4+(i+1)*12]
  272. list = append(list, wlanPhyRadioState{
  273. PhyIndex: le.Uint32(e[0:4]),
  274. Software: le.Uint32(e[4:8]),
  275. Hardware: le.Uint32(e[8:12]),
  276. })
  277. }
  278. return list, nil
  279. }
  280. // bssInfoFromEntry turns one WLAN_BSS_ENTRY into a WiFiInfo
  281. func bssInfoFromEntry(e wlanBSSEntry) WiFiInfo {
  282. ies := parseIEs(e.InformationElt)
  283. privacy := e.Capability&0x0010 != 0
  284. ssidBytes := e.SSID
  285. if len(ssidBytes) == 0 && ies.HasSSID {
  286. ssidBytes = ies.SSID
  287. }
  288. ssid, hidden := ssidString(ssidBytes)
  289. mhz := int(e.CenterFreqKHz / 1000)
  290. band := bandOfFrequency(mhz)
  291. channel := channelOfFrequency(mhz)
  292. if channel == 0 && ies.DSChannel > 0 {
  293. channel = ies.DSChannel
  294. }
  295. rates := e.Rates
  296. if len(rates) == 0 {
  297. rates = ratesFromIE(e.InformationElt)
  298. }
  299. basic, all, legacyMax := legacyRates(rates)
  300. phy, generation, width, center := ies.phyInfo(band, legacyMax)
  301. if phy == "" || len(e.InformationElt) == 0 && dot11PhyName(e.PhyType) != "" {
  302. //Without elements the PHY type reported by the driver is the better guess
  303. phy = dot11PhyName(e.PhyType)
  304. generation = generationOfPHY(phy, band)
  305. }
  306. streams := ies.spatialStreams()
  307. maxMCS := ies.heMaxMCS
  308. if phy == "802.11ac" {
  309. maxMCS = ies.vhtMaxMCS
  310. }
  311. if width <= 20 {
  312. center = 0
  313. }
  314. quality := int(e.LinkQuality)
  315. if quality > 100 {
  316. quality = 100
  317. }
  318. info := WiFiInfo{
  319. Address: formatMAC(e.BSSID[:]),
  320. Channel: channel,
  321. Frequency: formatFrequency(mhz),
  322. Quality: strconv.Itoa(quality) + "/100",
  323. SignalLevel: strconv.Itoa(int(e.RSSI)) + " dBm",
  324. ESSID: ssid,
  325. Hidden: hidden,
  326. SignalDBm: int(e.RSSI),
  327. QualityPercent: quality,
  328. FrequencyMHz: mhz,
  329. Band: band,
  330. ChannelWidth: width,
  331. CenterChannel: center,
  332. PHYType: phy,
  333. Generation: generation,
  334. BSSType: dot11BSSTypeName(e.BSSType),
  335. Security: ies.securityName(privacy),
  336. Cipher: ies.cipherName(privacy),
  337. PMF: ies.PMF,
  338. SpatialStreams: streams,
  339. MaxRateMbps: estimateMaxRate(phy, width, streams, maxMCS, legacyMax),
  340. BasicRates: basic,
  341. SupportedRates: all,
  342. BeaconInterval: int(e.BeaconPeriod),
  343. UptimeSeconds: int64(e.Timestamp / 1000000),
  344. Country: ies.Country,
  345. StationCount: ies.StationCount,
  346. ChannelUtilization: ies.ChannelUtilization,
  347. WPS: ies.WPS,
  348. Roaming: ies.Roaming,
  349. }
  350. info.EncryptionKey = info.Security != "Open" && info.Security != ""
  351. return info
  352. }
  353. /*
  354. DOT11 / WLAN enumeration names
  355. */
  356. func dot11PhyName(t uint32) string {
  357. switch t {
  358. case 1:
  359. return "802.11 FHSS"
  360. case 2:
  361. return "802.11 DSSS"
  362. case 3:
  363. return "802.11 IR"
  364. case 4:
  365. return "802.11a"
  366. case 5:
  367. return "802.11b"
  368. case 6:
  369. return "802.11g"
  370. case 7:
  371. return "802.11n"
  372. case 8:
  373. return "802.11ac"
  374. case 9:
  375. return "802.11ad"
  376. case 10:
  377. return "802.11ax"
  378. case 11:
  379. return "802.11be"
  380. }
  381. return ""
  382. }
  383. func dot11BSSTypeName(t uint32) string {
  384. switch t {
  385. case 1:
  386. return "Infrastructure"
  387. case 2:
  388. return "Ad hoc"
  389. }
  390. return ""
  391. }
  392. func dot11AuthName(t uint32) string {
  393. switch t {
  394. case 1:
  395. return "Open"
  396. case 2:
  397. return "Shared Key (WEP)"
  398. case 3:
  399. return "WPA-Enterprise"
  400. case 4:
  401. return "WPA-Personal"
  402. case 5:
  403. return "WPA-None"
  404. case 6:
  405. return "WPA2-Enterprise"
  406. case 7:
  407. return "WPA2-Personal"
  408. case 8:
  409. return "WPA3-Enterprise 192-bit"
  410. case 9:
  411. return "WPA3-Personal"
  412. case 10:
  413. return "Enhanced Open (OWE)"
  414. case 11:
  415. return "WPA3-Enterprise"
  416. }
  417. if t >= 0x80000000 {
  418. return "Vendor specific"
  419. }
  420. return ""
  421. }
  422. func dot11CipherName(t uint32) string {
  423. switch t {
  424. case 0x00:
  425. return "None"
  426. case 0x01:
  427. return "WEP-40"
  428. case 0x02:
  429. return "TKIP"
  430. case 0x04:
  431. return "AES-CCMP"
  432. case 0x05:
  433. return "WEP-104"
  434. case 0x06:
  435. return "BIP"
  436. case 0x08:
  437. return "AES-GCMP"
  438. case 0x09:
  439. return "AES-GCMP-256"
  440. case 0x0a:
  441. return "AES-CCMP-256"
  442. case 0x100:
  443. return "Group cipher"
  444. case 0x101:
  445. return "WEP"
  446. }
  447. if t >= 0x80000000 {
  448. return "Vendor specific"
  449. }
  450. return ""
  451. }
  452. func wlanInterfaceStateName(s uint32) string {
  453. switch s {
  454. case 0:
  455. return "not ready"
  456. case 1:
  457. return "connected"
  458. case 2:
  459. return "ad hoc network formed"
  460. case 3:
  461. return "disconnecting"
  462. case 4:
  463. return "disconnected"
  464. case 5:
  465. return "associating"
  466. case 6:
  467. return "discovering"
  468. case 7:
  469. return "authenticating"
  470. }
  471. return "unknown"
  472. }
  473. func wlanConnectionModeName(m uint32) string {
  474. switch m {
  475. case 0:
  476. return "Profile"
  477. case 1:
  478. return "Temporary profile"
  479. case 2:
  480. return "Secure discovery"
  481. case 3:
  482. return "Unsecure discovery"
  483. case 4:
  484. return "Automatic"
  485. }
  486. return ""
  487. }
  488. func dot11RadioStateName(s uint32) string {
  489. switch s {
  490. case 1:
  491. return "on"
  492. case 2:
  493. return "off"
  494. }
  495. return "unknown"
  496. }