-
Notifications
You must be signed in to change notification settings - Fork 74
/
main.py
334 lines (289 loc) · 9.52 KB
/
main.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
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
#!/usr/bin/env python
#@author: Prahlad Yeri
#@description: Small daemon to create a wifi hotspot on linux
#@license: MIT
import sys
import os
import argparse
import cli
import json
import socket
import platform
import datetime
import time
class Proto:
pass
const = Proto()
#global const = Proto() #struct to hold startup parameters
#const.debug = False
#const.verbose = False
#const.command = 'start'
#const.argv = None
stores = Proto() #struct to dump misc variables
stores.running = False
def validate_ip(addr):
try:
socket.inet_aton(addr)
return True # legal
except socket.error:
return False # Not legal
def configure():
global wlan, ppp, IP, Netmask
#CHECK WHETHER WIFI IS SUPPORTED OR NOT
print 'Verifying connections'
wlan=''
ppp=''
s=cli.execute_shell('iwconfig')
if s!=None:
lines = s.splitlines()
#print 'and it is:' + s
for line in lines:
if not line.startswith(' ') and not line.startswith('mon.') and 'IEEE 802.11' in line:
wlan=line.split(' ')[0]
print 'Wifi interface found: ' + wlan
if wlan=='':
print 'Wireless interface could not be found on your device.'
return
#print 'Verifying Internet connections'
s=cli.execute_shell('ifconfig')
lines = s.splitlines()
iface=[]
for line in lines:
if not line.startswith(' ') and not line.startswith(wlan) and not line.startswith('lo') and not line.startswith('mon.') and len(line)>0:
iface.append(line.split(' ')[0])
#print 'f::' + line
if len(iface)==0:
print 'No network nic could be found on your deivce to interface with the LAN'
elif len(iface)==1:
ppp=iface[0]
print 'Network interface found: ' + ppp
else:
rniface=range(len(iface))
s=''
while True:
for i in rniface:
print i, iface[i]
try: s = int(input("Enter number for internet supplying NIC :"))
except: continue
if s not in rniface:
continue
ppp=iface[s]
break
while True:
IP= raw_input('Enter an IP address for your ap [192.168.45.1] :')
#except: continue
#print type(IP)
#sys.exit(0)
if IP==None or IP=='':
IP='192.168.45.1'
if not validate_ip(IP): continue
break
Netmask='255.255.255.0'
#CONFIGURE SSID, PASSWORD, ETC.
SSID=raw_input('Enter SSID [joe_ssid] :')
if SSID=='': SSID='joe_ssid'
password=raw_input('Enter 10 digit password [1234567890] :')
if password=='': password='1234567890'
f = open('run.dat','r')
lout=[]
for line in f.readlines():
lout.append(line.replace('<SSID>',SSID).replace('<PASS>',password))
f.close()
f = open('run.conf','w')
f.writelines(lout)
f.close()
print 'created hostapd configuration: run.conf'
dc = {'wlan': wlan, 'inet':ppp, 'ip':IP, 'netmask':Netmask, 'SSID':SSID, 'password':password}
json.dump(dc, open('hotspotd.json','wb'))
print dc
print 'Configuration saved. Run "hotspotd start" to start the router.'
#CHECK WIFI DRIVERS AND ISSUE WARNINGS
def check_dependencies():
#CHECK FOR DEPENDENCIES
if len(cli.check_sysfile('hostapd'))==0:
print 'hostapd executable not found. Make sure you have installed hostapd.'
return False
elif len(cli.check_sysfile('dnsmasq'))==0:
print 'dnsmasq executable not found. Make sure you have installed dnsmasq.'
return False
else:
return True
def check_interfaces():
global wlan, ppp
print 'Verifying interfaces'
s=cli.execute_shell('ifconfig')
lines = s.splitlines()
bwlan = False
bppp = False
for line in lines:
if not line.startswith(' ') and len(line)>0:
text=line.split(' ')[0]
if text.startswith(wlan):
bwlan = True
elif text.startswith(ppp):
bppp = True
if not bwlan:
print wlan + ' interface was not found. Make sure your wifi is on.'
return False
elif not bppp:
print ppp + ' interface was not found. Make sure you are connected to the internet.'
return False
else:
print 'done.'
return True
def pre_start():
try:
# oper = platform.linux_distribution()
# if oper[0].lower()=='ubuntu' and oper[2].lower()=='trusty':
# trusty patch
# print 'applying hostapd workaround for ubuntu trusty.'
#29-12-2014: Rather than patching individual distros, lets make it a default.
result = cli.execute_shell('nmcli radio wifi off')
if "error" in result.lower():
cli.execute_shell('nmcli nm wifi off')
cli.execute_shell('rfkill unblock wlan')
cli.execute_shell('sleep 1')
print 'done.'
except:
pass
def start_router():
if not check_dependencies():
return
elif not check_interfaces():
return
pre_start()
s = 'ifconfig ' + wlan + ' up ' + IP + ' netmask ' + Netmask
print 'created interface: mon.' + wlan + ' on IP: ' + IP
r = cli.execute_shell(s)
cli.writelog(r)
#cli.writelog('sleeping for 2 seconds.')
print 'wait..'
cli.execute_shell('sleep 2')
i = IP.rindex('.')
ipparts=IP[0:i]
#stop dnsmasq if already running.
if cli.is_process_running('dnsmasq')>0:
print 'stopping dnsmasq'
cli.execute_shell('killall dnsmasq')
#stop hostapd if already running.
if cli.is_process_running('hostapd')>0:
print 'stopping hostapd'
cli.execute_shell('killall hostapd')
#enable forwarding in sysctl.
print 'enabling forward in sysctl.'
r=cli.set_sysctl('net.ipv4.ip_forward','1')
print r.strip()
#enable forwarding in iptables.
print 'creating NAT using iptables: ' + wlan + '<->' + ppp
cli.execute_shell('iptables -P FORWARD ACCEPT')
#add iptables rules to create the NAT.
cli.execute_shell('iptables --table nat --delete-chain')
cli.execute_shell('iptables --table nat -F')
r=cli.execute_shell('iptables --table nat -X')
if len(r.strip())>0: print r.strip()
cli.execute_shell('iptables -t nat -A POSTROUTING -o ' + ppp + ' -j MASQUERADE')
cli.execute_shell('iptables -A FORWARD -i ' + ppp + ' -o ' + wlan + ' -j ACCEPT -m state --state RELATED,ESTABLISHED')
cli.execute_shell('iptables -A FORWARD -i ' + wlan + ' -o ' + ppp + ' -j ACCEPT')
#allow traffic to/from wlan
cli.execute_shell('iptables -A OUTPUT --out-interface ' + wlan + ' -j ACCEPT')
cli.execute_shell('iptables -A INPUT --in-interface ' + wlan + ' -j ACCEPT')
#start dnsmasq
s = 'dnsmasq --dhcp-authoritative --interface=' + wlan + ' --dhcp-range=' + ipparts + '.20,' + ipparts +'.100,' + Netmask + ',4h'
print 'running dnsmasq'
print s
r = cli.execute_shell(s)
cli.writelog(r)
#~ f = open(os.getcwd() + '/hostapd.tem','r')
#~ lout=[]
#~ for line in f.readlines():
#~ lout.append(line.replace('<SSID>',SSID).replace('<PASS>',password))
#~
#~ f.close()
#~ f = open(os.getcwd() + '/hostapd.conf','w')
#~ f.writelines(lout)
#~ f.close()
#writelog('created: ' + os.getcwd() + '/hostapd.conf')
#start hostapd
#s = 'hostapd -B ' + os.path.abspath('run.conf')
s = 'hostapd -B ' + os.getcwd() + '/run.conf'
print s
cli.writelog('running hostapd')
#cli.writelog('sleeping for 2 seconds.')
cli.writelog('wait..')
cli.execute_shell('sleep 2')
r = cli.execute_shell(s)
cli.writelog(r)
print 'hotspot is running.'
return
def stop_router():
#bring down the interface
cli.execute_shell('ifconfig mon.' + wlan + ' down')
#TODO: Find some workaround. killing hostapd brings down the wlan0 interface in ifconfig.
#~ #stop hostapd
#~ if cli.is_process_running('hostapd')>0:
#~ cli.writelog('stopping hostapd')
#~ cli.execute_shell('pkill hostapd')
#stop dnsmasq
if cli.is_process_running('dnsmasq')>0:
cli.writelog('stopping dnsmasq')
cli.execute_shell('killall dnsmasq')
#disable forwarding in iptables.
cli.writelog('disabling forward rules in iptables.')
cli.execute_shell('iptables -P FORWARD DROP')
#delete iptables rules that were added for wlan traffic.
if wlan != None:
cli.execute_shell('iptables -D OUTPUT --out-interface ' + wlan + ' -j ACCEPT')
cli.execute_shell('iptables -D INPUT --in-interface ' + wlan + ' -j ACCEPT')
cli.execute_shell('iptables --table nat --delete-chain')
cli.execute_shell('iptables --table nat -F')
cli.execute_shell('iptables --table nat -X')
#disable forwarding in sysctl.
cli.writelog('disabling forward in sysctl.')
r = cli.set_sysctl('net.ipv4.ip_forward','0')
print r.strip()
#cli.execute_shell('ifconfig ' + wlan + ' down' + IP + ' netmask ' + Netmask)
#cli.execute_shell('ip addr flush ' + wlan)
print 'hotspot has stopped.'
return
def main(args):
global wlan, ppp, IP, Netmask
the_version = open("VERSION").read().strip()
print "****"
print "Hotspotd " + the_version
print "A simple daemon to create wifi hotspot on Linux!"
print "****"
print "Copyright (c) 2014-2016"
print "Prahlad Yeri<prahladyeri@yahoo.com>\n"
scpath = os.path.realpath(__file__)
realdir = os.path.dirname(scpath)
os.chdir(realdir)
#print 'changed directory to ' + os.path.dirname(scpath)
#if an instance is already running, then quit
#const.verbose = args.verbose
#const.command = args.command
#const.blocking = args.blocking
#const.argv = [os.getcwd() + '/server.py'] + sys.argv[1:]
cli.arguments = args #initialize
newconfig = False
if not os.path.exists('hotspotd.json'):
configure()
newconfig=True
if len(cli.check_sysfile('hostapd'))==0:
print "hostapd is not installed on your system. This package will not work without it.\nTo install hostapd, run 'sudo apt-get install hostapd'\nor refer to http://wireless.kernel.org/en/users/Documentation/hostapd after this installation gets over."
time.sleep(2)
dc =json.load(open('hotspotd.json'))
wlan = dc['wlan']
ppp = dc['inet']
IP=dc['ip']
Netmask=dc['netmask']
SSID = dc['SSID']
password = dc['password']
if args.command == 'configure':
if not newconfig: configure()
elif args.command == 'stop':
stop_router()
elif args.command == 'start':
if (cli.is_process_running('hostapd') != 0 and cli.is_process_running('dnsmasq') != 0):
print 'hotspot is already running.'
else:
start_router()