-
-
Notifications
You must be signed in to change notification settings - Fork 90
/
startup.py
225 lines (191 loc) · 7.06 KB
/
startup.py
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
import subprocess
import signal
import string
import random
import re
import json
import time
import os
import socket
import requests
from flask import Flask, request, send_from_directory, jsonify, render_template, redirect
app = Flask(__name__, static_url_path='')
currentdir = os.path.dirname(os.path.abspath(__file__))
os.chdir(currentdir)
ssid_list = []
def getssid():
global ssid_list
if len(ssid_list) > 0:
return ssid_list
ssid_list = []
get_ssid_list = subprocess.check_output(('iw', 'dev', 'wlan0', 'scan', 'ap-force'))
ssids = get_ssid_list.splitlines()
for s in ssids:
s = s.strip().decode('utf-8')
if s.startswith("SSID"):
a = s.split(": ")
try:
ssid_list.append(a[1])
except:
pass
print(ssid_list)
ssid_list = sorted(list(set(ssid_list)))
return ssid_list
def id_generator(size=6, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
wpa_conf = """country=GB
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
network={
ssid="%s"
%s
}"""
wpa_conf_default = """country=GB
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
"""
@app.route('/')
def main():
piid = open('pi.id', 'r').read().strip()
return render_template('index.html', ssids=getssid(), message="Once connected you'll find IP address @ <a href='https://snaptext.live/{}' target='_blank'>snaptext.live/{}</a>.".format(piid,piid))
# Captive portal when connected with iOS or Android
@app.route('/generate_204')
def redirect204():
return redirect("http://192.168.4.1", code=302)
@app.route('/hotspot-detect.html')
def applecaptive():
return redirect("http://192.168.4.1", code=302)
# Not working for Windows, needs work!
@app.route('/ncsi.txt')
def windowscaptive():
return redirect("http://192.168.4.1", code=302)
def check_cred(ssid, password):
'''Validates ssid and password and returns True if valid and False if not valid'''
wpadir = currentdir + '/wpa/'
testconf = wpadir + 'test.conf'
wpalog = wpadir + 'wpa.log'
wpapid = wpadir + 'wpa.pid'
if not os.path.exists(wpadir):
os.mkdir(wpadir)
for _file in [testconf, wpalog, wpapid]:
if os.path.exists(_file):
os.remove(_file)
# Generate temp wpa.conf
result = subprocess.check_output(['wpa_passphrase', ssid, password])
with open(testconf, 'w') as f:
f.write(result.decode('utf-8'))
def stop_ap(stop):
if stop:
# Services need to be stopped to free up wlan0 interface
print(subprocess.check_output(['systemctl', "stop", "hostapd", "dnsmasq", "dhcpcd"]))
else:
print(subprocess.check_output(['systemctl', "restart", "dnsmasq", "dhcpcd"]))
time.sleep(15)
print(subprocess.check_output(['systemctl', "restart", "hostapd"]))
# Sentences to check for
fail = "pre-shared key may be incorrect"
success = "WPA: Key negotiation completed"
stop_ap(True)
result = subprocess.check_output(['wpa_supplicant',
"-Dnl80211",
"-iwlan0",
"-c/" + testconf,
"-f", wpalog,
"-B",
"-P", wpapid])
checkwpa = True
while checkwpa:
with open(wpalog, 'r') as f:
content = f.read()
if success in content:
valid_psk = True
checkwpa = False
elif fail in content:
valid_psk = False
checkwpa = False
else:
continue
# Kill wpa_supplicant to stop it from setting up dhcp, dns
with open(wpapid, 'r') as p:
pid = p.read()
pid = int(pid.strip())
os.kill(pid, signal.SIGTERM)
stop_ap(False) # Restart services
return valid_psk
@app.route('/static/<path:path>')
def send_static(path):
return send_from_directory('static', path)
@app.route('/signin', methods=['POST'])
def signin():
email = request.form['email']
ssid = request.form['ssid']
password = request.form['password']
pwd = 'psk="' + password + '"'
if password == "":
pwd = "key_mgmt=NONE" # If open AP
print(email, ssid, password)
valid_psk = check_cred(ssid, password)
if not valid_psk:
# User will not see this because they will be disconnected but we need to break here anyway
return render_template('ap.html', message="Wrong password!")
with open('wpa.conf', 'w') as f:
f.write(wpa_conf % (ssid, pwd))
with open('status.json', 'w') as f:
f.write(json.dumps({'status':'disconnected'}))
subprocess.Popen(["./disable_ap.sh"])
piid = open('pi.id', 'r').read().strip()
return render_template('index.html', message="Please wait 2 minutes to connect. Then your IP address will show up at <a href='https://snaptext.live/{}'>snaptext.live/{}</a>.".format(piid,piid))
def wificonnected():
result = subprocess.check_output(['iwconfig', 'wlan0'])
matches = re.findall(r'\"(.+?)\"', result.split(b'\n')[0].decode('utf-8'))
if len(matches) > 0:
print("got connected to " + matches[0])
return True
return False
if __name__ == "__main__":
# things to run the first time it boots
if not os.path.isfile('pi.id'):
with open('pi.id', 'w') as f:
f.write(id_generator())
subprocess.Popen("./expand_filesystem.sh")
time.sleep(300)
piid = open('pi.id', 'r').read().strip()
print(piid)
time.sleep(15)
# get status
s = {'status':'disconnected'}
if not os.path.isfile('status.json'):
with open('status.json', 'w') as f:
f.write(json.dumps(s))
else:
s = json.load(open('status.json'))
# check connection
if wificonnected():
s['status'] = 'connected'
if not wificonnected():
if s['status'] == 'connected': # Don't change if status in status.json is hostapd
s['status'] = 'disconnected'
with open('status.json', 'w') as f:
f.write(json.dumps(s))
if s['status'] == 'disconnected':
s['status'] = 'hostapd'
with open('status.json', 'w') as f:
f.write(json.dumps(s))
with open('wpa.conf', 'w') as f:
f.write(wpa_conf_default)
subprocess.Popen("./enable_ap.sh")
elif s['status'] == 'connected':
piid = open('pi.id', 'r').read().strip()
# get ip address
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ipaddress = s.getsockname()[0]
s.close()
# alert user on snaptext
r = requests.post("https://snaptext.live",data=json.dumps({"message":"Your Pi is online at {}".format(ipaddress),"to":piid,"from":"Raspberry Pi Turnkey"}))
print(r.json())
subprocess.Popen("./startup.sh")
while True:
time.sleep(60000)
else:
app.run(host="0.0.0.0", port=80, threaded=True)