Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Layer2auth #1343

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions pscheduler-test-dot1x/dot1x/cli-to-spec
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,10 @@ opt_parser.add_option("--password",
action="store", type="string",
dest="password")

opt_parser.add_option("--driver",
help="Wireless driver to use (defaults to system)",
opt_parser.add_option("--token",
help="File token(line identifier) that retrieves username/password",
action="store", type="string",
dest="driver")
dest="token")

opt_parser.add_option("--ssid",
help="Service set identifier (SSID) if using wireless",
Expand Down Expand Up @@ -141,8 +141,8 @@ if options.timeout is not None:
if options.interface is not None:
result['interface'] = options.interface

if options.driver is not None:
result['driver'] = options.driver
if options.token is not None:
result['token'] = options.token

if options.username is not None:
result['_username'] = options.username
Expand Down
4 changes: 4 additions & 0 deletions pscheduler-test-dot1x/dot1x/result-format
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,12 @@ result = input["result"]
# print().

if format == 'text/plain':
final = result["final"]
# Print results of the test here, in plaintext
print('Time: %s\n' % result['time'])
print('')
for each in final:
print(each)

elif format == 'text/html':
# Print results of the test here, in html
Expand Down
5 changes: 4 additions & 1 deletion pscheduler-test-dot1x/dot1x/validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
"host-node": { "$ref": "#/pScheduler/Host" },
"timeout": { "$ref": "#/pScheduler/Duration" },
"interface": { "$ref": "#/pScheduler/String" },
"driver": { "$ref": "#/pScheduler/String" },
"token": { "$ref": "#/pScheduler/String" },
"_username": { "$ref": "#/pScheduler/String" },
"_password": { "$ref": "#/pScheduler/String" },
"ssid": { "$ref": "#/pScheduler/String" },
Expand All @@ -61,6 +61,8 @@
# If listed here, these parameters MUST be in the test spec.
"required": [
"interface",
"ssid",
"key-management"
],
# Treat other properties as acceptable. This should
# ALWAYS be false.
Expand Down Expand Up @@ -126,6 +128,7 @@ def spec_is_valid(json):
"succeeded": { "$ref": "#/pScheduler/Boolean" },
"Authenticated": { "$ref": "#/pScheduler/Boolean" },
"time": { "$ref": "#/pScheduler/Duration" },
"final": { "type": "array", "items": { "$ref": "#/pScheduler/String" } }
},
"required": [
"succeeded",
Expand Down
183 changes: 94 additions & 89 deletions pscheduler-tool-bssidscanner/bssidscanner/run
Original file line number Diff line number Diff line change
Expand Up @@ -9,111 +9,116 @@
# back to the test. Both system and api are able to be used here.
#

import select
from os import getpid, makedirs, unlink, access, R_OK, system, listdir, path
from socket import socket, AF_UNIX, SOCK_DGRAM
import datetime
import subprocess
import json
import sys
import time
import argparse
import time
from wifi import Cell #make sure that you have pip installed wifi

import pscheduler

# from stdin
input = pscheduler.json_load(exit_on_error=True)

# Take input from test spec
try:
interface = input['test']['spec']['interface']
ssid = input['test']['spec']['ssid']
except KeyError:
pscheduler.fail('Missing data in input')

# convert the comma separated ssids to a list
ssid = list(ssid.split(','))

duration = input['test']['spec'].get('duration', 'PT5S')
duration = pscheduler.timedelta_as_seconds( pscheduler.iso8601_as_timedelta(duration) )
timeout_iso = input['test']['spec'].get('timeout', 'PT10S')
timeout = pscheduler.timedelta_as_seconds( pscheduler.iso8601_as_timedelta(timeout_iso) )
import os

#temp file preserved between consecutive runs but not reboots
WPA_CONFIG_PATH = '/tmp/wpa_supplicant/wpa_supplicant.conf'
#initializes only when wpa_supplicant starts
WPA_CTRL_IFACE_BASE = '/var/run/wpa_supplicant'
interface = 'wlan0'
timeout = 3000
ssid_set = set()

# parse config
pscheduler_input = pscheduler.json_load(exit_on_error=True)
get_ssid = pscheduler_input['test']['spec'].get('ssid', None)
ssid_set = set(get_ssid.split(',')) if get_ssid else None
duration_iso = pscheduler_input['test']['spec'].get('duration', 'PT5S')
timeout_iso = pscheduler_input['test']['spec'].get('timeout', 'PT10S')
timeout = pscheduler.timedelta_as_seconds(pscheduler.iso8601_as_timedelta(timeout_iso))
duration = pscheduler.timedelta_as_seconds(pscheduler.iso8601_as_timedelta(duration_iso))
start_time = datetime.datetime.now()
succeeded = False
error = ''
diags = ''

# Run the actual task here:
def get_all_bssids(interface):
"""
Scan the given interface for all bssids
Return a list of all bssids
"""
start_time = time.time()
cells = Cell.all(interface) # Specify interface to scan on
wifi_list = []
for cell in cells:
bssid = {}
bssid['ssid'] = cell.ssid
bssid['signal'] = cell.signal
bssid['address'] = cell.address
bssid['frequency'] = pscheduler.si_as_number(cell.frequency[:-2])
quality_num,quality_denom = cell.quality.split('/')
bssid['quality'] = float(quality_num) / float(quality_denom)
bssid['bitrates'] = sorted(map(lambda v : pscheduler.si_as_number(v[:-3]), cell.bitrates))
bssid['encrypted'] = cell.encrypted
bssid['channel'] = cell.channel
bssid['mode'] = cell.mode
wifi_list.append(bssid)

end_time = time.time()
elapsed_time = end_time - start_time
log_msg = "Scan finished in " + str(elapsed_time)
return wifi_list, elapsed_time

"""
Scan on the given interface
Output a list of all bssids in json format with the given ssid
"""
all_bssids, elapsed_time = get_all_bssids(interface)
ssid_list = []

# Check complete list for matching ssids
for bssid in all_bssids:
#if no ssids were given then append all the ssids
if not ssid:
ssid_list.append(bssid)
else:
#if ssid/ssids were given then only append those
if bssid['ssid'] in ssid:
ssid_list.append(bssid)

succeeded = True

# IMPORTANT NOTE: This code puts the process to sleep until the
# scheduled start time has arrived. It should be placed after all
# preparatory code has been executed and immediately before the tool
# is invoked (for plugins that run other programs) or any activity
# that does a measurement (for those that don't).

try:
pscheduler.sleep_until(input['schedule']['start'])
except KeyError:
pscheduler.fail("Unable to find start time in input")


dir_path = path.dirname(WPA_CONFIG_PATH)

#check if interface already exists
# interface_path = path.join(WPA_CTRL_IFACE_BASE,interface)
# os.system('killall wpa_supplicant')
# os.remove(interface_path)
if not access(f'{WPA_CTRL_IFACE_BASE}/{interface}', R_OK):
#create config file and start wpa_supplicant
if not path.exists(dir_path):
makedirs(dir_path)
with open(WPA_CONFIG_PATH, 'w') as f:
f.write('ctrl_interface='+WPA_CTRL_IFACE_BASE+'\r\n')
f.write('update_config=1\r\n')
os.system('wpa_supplicant -B -i '+interface+' -c '+WPA_CONFIG_PATH)

# print('set up config file')
#setting up socket
sock = socket(AF_UNIX, SOCK_DGRAM)
sock.settimeout(3)
start = datetime.datetime.now()
# response will be written to this socket
recv_sock = "/tmp/wpa_ctrl_{}".format(os.getpid())
sock.bind(recv_sock)
# print('set up and bind receive socket')

ctrl_interface = f"{WPA_CTRL_IFACE_BASE}/{interface}"
# os.chmod(ctrl_interface, 0o777)
sock.connect(ctrl_interface)
# print('start attaching at', datetime.datetime.now() - start)
# attach to wpa_supplicant
sock.send(b'ATTACH')

if sock.recv(3) != b'OK\n':
raise OSError(f"error attaching to {ctrl_interface}")

# start scan
sock.send(bytes("SCAN", 'utf-8'))
# polling for scan results
poll = select.poll()
poll.register(sock, select.POLLIN)

data = []
# wait for scan to complete
while poll.poll(timeout):
result = sock.recv(4096)
if result.endswith(b'<3>CTRL-EVENT-SCAN-RESULTS '):
sock.send(bytes("SCAN_RESULTS", 'utf-8'))
break

# gather scan results
while poll.poll(200):
result = sock.recv(8192)
if result:
data.append(result)

blob = data[1].decode('utf-8')
result = [s.split('\t') for s in blob.split('\n')][1:-1]

for bssid, freq, signal, flags, ssid in result:
if not ssid_set or ssid in ssid_set:
ssid_list.append({
'ssid': ssid,
'bssid': bssid,
'freq': int(freq),
'signal': int(signal),
'flags': flags
})
end_time = datetime.datetime.now()

# Organize results into json data
results = {
'succeeded': succeeded,
'result': {
'schema': 1,
'time': pscheduler.timedelta_as_iso8601( end_time - start_time),
'time': pscheduler.timedelta_as_iso8601(end_time - start_time),
'succeeded': succeeded,
'ssid_list': ssid_list
},
'error': error,
'diags': diags }

pscheduler.succeed_json(results)
'diags': diags
}

# pscheduler.succeed_json(results)
# print(results)
# print('finished at', datetime.datetime.now() - start)
106 changes: 106 additions & 0 deletions pscheduler-tool-bssidscanner/run
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
#!/usr/bin/env python3
import select
from os import getpid, unlink, access, R_OK, listdir, path
from socket import socket, AF_UNIX, SOCK_DGRAM
import datetime
import pscheduler
import os

#temp file preserved between consecutive runs but not reboots
WPA_CONFIG_PATH = '/tmp/wpa_supplicant/wpa_supplicant.conf'
#initializes only when wpa_supplicant starts
WPA_CTRL_IFACE_BASE = '/var/run/wpa_supplicant'
interface = 'wlan0'
timeout = 3000
ssid_set = set()

# parse config
pscheduler_input = pscheduler.json_load(exit_on_error=True)
get_ssid = pscheduler_input['test']['spec'].get('ssid', None)
ssid_set = set(get_ssid.split(',')) if get_ssid else set()
duration_iso = pscheduler_input['test']['spec'].get('duration', 'PT5S')
timeout_iso = pscheduler_input['test']['spec'].get('timeout', 'PT10S')
timeout = pscheduler.timedelta_as_seconds(pscheduler.iso8601_as_timedelta(timeout_iso))
duration = pscheduler.timedelta_as_seconds(pscheduler.iso8601_as_timedelta(duration_iso))
start_time = datetime.datetime.now()
succeeded = False
error = ''
diags = ''
ssid_list = []

#check if interface already exists
if not access(f'{WPA_CTRL_IFACE_BASE}/{interface}', R_OK):
#create config file and start wpa_supplicant
with open(WPA_CONFIG_PATH, 'w') as f:
f.write('ctrl_interface='+WPA_CTRL_IFACE_BASE+'\r\n')
f.write('update_config=1\r\n')
os.system('wpa_supplicant -B -i '+interface+' -c '+WPA_CONFIG_PATH)

#setting up socket
sock = socket(AF_UNIX, SOCK_DGRAM)
sock.settimeout(3)
start = datetime.datetime.now()
# response will be written to this socket
recv_sock = f"/tmp/wpa_ctrl_{getpid()}"
sock.bind(recv_sock)

ctrl_interface = f"{WPA_CTRL_IFACE_BASE}/{interface}"

sock.connect(ctrl_interface)
print('start attaching at', datetime.datetime.now() - start)
# attach to wpa_supplicant
sock.send(b'ATTACH')

if sock.recv(3) != b'OK\n':
raise OSError(f"error attaching to {ctrl_interface}")

# start scan
sock.send(bytes("SCAN", 'utf-8'))
# polling for scan results
poll = select.poll()
poll.register(sock, select.POLLIN)

data = []
# wait for scan to complete
while poll.poll(timeout):
result = sock.recv(4096)
if result.endswith(b'<3>CTRL-EVENT-SCAN-RESULTS '):
sock.send(bytes("SCAN_RESULTS", 'utf-8'))
break

# gather scan results
while poll.poll(200):
result = sock.recv(8192)
if result:
data.append(result)

blob = data[1].decode('utf-8')
result = [s.split('\t') for s in blob.split('\n')][1:-1]

for bssid, freq, signal, flags, ssid in result:
if not ssid_set or ssid in ssid_set:
ssid_list.append({
'ssid': ssid,
'bssid': bssid,
'freq': int(freq),
'signal': int(signal),
'flags': flags
})
end_time = datetime.datetime.now()

# Organize results into json data
results = {
'succeeded': succeeded,
'result': {
'schema': 1,
'time': pscheduler.timedelta_as_iso8601(end_time - start_time),
'succeeded': succeeded,
'ssid_list': ssid_list
},
'error': error,
'diags': diags
}

# pscheduler.succeed_json(results)
print(results)
print('finished at', datetime.datetime.now() - start)
1 change: 0 additions & 1 deletion pscheduler-tool-umichwpa/umichwpa/duration
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ json = pscheduler.json_load(exit_on_error=True);

timeout_iso = json.get("timeout", "PT10S")
timeout = pscheduler.iso8601_as_timedelta(timeout_iso) + datetime.timedelta(seconds=5)

pscheduler.succeed_json({
"duration": pscheduler.timedelta_as_iso8601( timeout )
})
Loading