forked from mindcruzer/airvpn-cli
-
Notifications
You must be signed in to change notification settings - Fork 1
/
airvpn
executable file
·452 lines (356 loc) · 13.5 KB
/
airvpn
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
#!/usr/bin/python
# AirVPN CLI
# Copyright (C) 2013 Sean Stewart
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
AirVPN CLI.
Usage:
airvpn list [--local] [--openvpn-dir=DIR]
airvpn setup <server-name>... [--connect] [--openvpn-dir=DIR]
airvpn connect <server-name> [--openvpn-dir=DIR]
airvpn disconnect
airvpn remove <server-name> [--openvpn-dir=DIR]
airvpn status [<server-name>]
airvpn rules [--lan-ip-block=LAN] [--interface=IF] [--virtual-interface=VIF] [--openvpn-dir=DIR]
airvpn -h | --help
airvpn -v | --version
Options:
--connect Connect to server after setup.
-h --help Show this screen.
--interface=IF The physical network interface on your machine. [default: eth0]
--local List servers that are configured.
--lan-ip-block=LAN The IP block of your local area network. [default: 192.168.1.0/24]
--openvpn-dir=DIR Path to the OpenVPN config directory. [default: /etc/openvpn]
-v --version Show version.
--virtual-interface=VIF The virtual interface created by OpenVPN. [default: tun0]
"""
import os
import getpass
import time
from docopt import docopt
from sh import (chown, chmod, openvpn, kill)
import lxml.html
import requests
import texttable
PID_PATH = '/var/run/airvpn.pid'
LOG_PATH = '/var/log/airvpn.log'
# Utility Functions
# ----------
def is_root():
"""
Returns a boolean indicating if the application is running with root permissions.
"""
return os.geteuid() == 0
def login():
"""
Creates a session and logs the user into AirVPN, returning
the session on success.
"""
username = raw_input('Username: ')
password = getpass.getpass()
session = requests.Session()
response = session.get('https://airvpn.org/')
# grab the csrf token from the login form
page = lxml.html.fromstring(response.text)
auth_key = page.get_element_by_id('login').inputs['auth_key'].get('value')
login_data = {
'auth_key': auth_key,
'referer': 'https://airvpn.org/',
'ips_username': username,
'ips_password': password
}
response = session.post(
'https://airvpn.org/index.php?app=core&module=global§ion=login&do=process',
data=login_data,
allow_redirects=False
)
# If the login fails, the login page is re-rendered (200 response);
# if the login succeeds, the user is redirected (302 response)
if response.status_code == 302:
return session
def get_pid():
"""
Returns the PID of the currently running OpenVPN daemon process,
if any.
"""
try:
pid_file = open(PID_PATH, 'r')
except IOError:
return None
return pid_file.read().strip('\n')
def get_configured_servers(config_dir):
"""
Returns a list of the names of all configured AirVPN servers.
"""
servers = []
for root, dirs, files in os.walk(os.path.abspath(config_dir)):
for _file in files:
if _file.endswith('.ovpn'):
servers.append(_file.split('.')[0])
return servers
def get_configured_server_ips(config_dir):
"""
Returns a list of IPs for all configured AirVPN servers.
"""
servers = get_configured_servers(config_dir)
server_ips = []
for server in servers:
# grab the server ip from the config file
config_path = os.path.join(config_dir, server + '.ovpn')
config_file = open(config_path, 'r')
for line in config_file:
if line.startswith('remote'):
server_ips.append(line.split(' ')[1])
break
config_file.close()
return server_ips
# Command Functions
# ----------
def setup(server_names, connect_after, config_dir):
"""
Configures an AirVPN server.
"""
if not is_root():
print 'This command must be run as root.'
return
session = login()
if not session:
print 'Login failed.'
return
print 'Generating configuration...'
generator_url = 'https://airvpn.org/generator/'
response = session.get(generator_url)
page = lxml.html.fromstring(response.text)
for server_name in server_names:
time.sleep(2)
try:
# get the csrf token from the response
csrf_token = page.get_element_by_id('generator').inputs['csrf_token'].get('value')
except:
# the form doesn't get rendered if the user hasn't paid for access
print 'Account does not allow config generation. Have you tried giving AirVPN money?'
continue
config_data = {
'csrf_token': csrf_token,
'download_mode': 'list',
'download_index': 0,
'system': 'linux',
'server_%s' % server_name: 'on',
'proxy_mode': 'none',
'withbinary': '',
'fileprefix': '',
'customdirectives': '',
'protocol_1': 'on',
'tosaccept': 'on',
'tosaccept2': 'on'
}
response = session.post(generator_url, data=config_data)
if 'zero files in package' in response.text:
print 'Invalid server name.'
continue
config_path = os.path.join(config_dir, server_name + '.ovpn')
try:
# write config file to the openvpn config directory
config_file = open(config_path, 'w')
config_file.write(response.text)
config_file.close()
except:
print 'Writing config file failed.'
continue
try:
# set root ownership and exclusive rw permissions
chown('root', config_path)
chmod('600', config_path)
except:
print 'Setting permissions on configuration file failed.'
continue
print '%s server configured.' % server_name.capitalize()
if connect_after:
connect(server_name, config_dir)
def connect(server_name, config_dir):
"""
Connects to a configured AirVPN server.
"""
if not is_root():
print 'This command must be run as root.'
return
config_path = os.path.join(config_dir, server_name + '.ovpn')
if not os.path.exists(config_path):
print 'That server is not configured.'
return
if disconnect():
print 'Starting OpenVPN daemon with %s configuration...' % server_name
try:
openvpn('--config', os.path.abspath(config_path), '--writepid', PID_PATH, '--log', LOG_PATH, daemon=True)
except:
print 'Failed to start OpenVPN daemon.'
def disconnect():
"""
Disconnects from the VPN.
"""
if not is_root():
print 'This command must be run as root.'
return
pid = get_pid()
if pid:
print 'Shutting down OpenVPN daemon...'
try:
kill(pid)
# graceful shutdown takes a few seconds
time.sleep(8)
except:
print 'Unable to shut down existing OpenVPN daemon process.'
return
os.unlink(PID_PATH)
return True
def remove(server_name, config_dir):
"""
Removes the configuration of the specified server.
"""
if not is_root():
print 'This command must be run as root.'
return
servers = get_configured_servers(config_dir)
if server_name not in servers:
print 'That server is not configured.'
else:
os.unlink(os.path.join(config_dir, server_name + '.ovpn'))
print '%s server removed.' % server_name.capitalize()
def list_remote_servers():
"""
Displays the names and locations of all available AirVPN servers.
"""
response = requests.get('https://airvpn.org/status/')
if response.status_code == 200:
page = lxml.html.fromstring(response.text)
server_boxes = page.xpath('//div[@class="air_server_box_1"]')
server_table = texttable.Texttable()
server_table.header(['Server Name', 'Location'])
server_table.set_cols_width([12, 40])
server_table.set_deco(server_table.HEADER | server_table.VLINES)
for box in server_boxes:
name = box.xpath('div[1]/div[1]/div[1]/a[1]/text()')[0].strip()
country = box.xpath('div[1]/div[2]/text()')[0].strip()
city_state = box.xpath('div[1]/div[2]/span/text()')[0].strip()
server_table.add_row([name, '%s, %s' % (city_state, country)])
print server_table.draw()
else:
print 'Loading server list failed.'
def list_local_servers(config_dir):
"""
Displays the names of all locally configured servers.
"""
servers = get_configured_servers(config_dir)
for server in servers:
print server.capitalize()
def status(server_name):
"""
Displays the status (bandwidth, # users connected) of the current or specified
AirVPN server.
"""
response = requests.get('https://airvpn.org/status/')
if response.status_code == 200:
page = lxml.html.fromstring(response.text)
connected = False
if not server_name:
# get the current server name, if any
connection_status = page.xpath('//*[@id="header_info"]/span/b/a/img[@src="/img/icons/connected_yes.png"]/@alt')[0].strip()
if connection_status == 'Connected':
connected = True
server_name = page.xpath('//*[@id="header_info"]/span/b/a/text()')[0].strip().lower()
else:
print 'You are not connected to an AirVPN server.'
return
server_boxes = page.xpath('//div[@class="air_server_box_1"]')
for box in server_boxes:
name = box.xpath('div/div/div/a/text()')[0].strip().lower()
if name == server_name:
bandwidth = box.xpath('div/div/div/div[@class="server_status_load_caption"]/text()')[0].strip()
users = box.xpath('div/div/span[@class="server_status_item"]/text()')[0].strip()
if connected:
print 'Connected to %s' % name.capitalize()
else:
print name.capitalize()
print "--------------------"
print 'Bandwidth: %s' % bandwidth
print 'Users: %s' % users
break
else:
print 'Server not found.'
else:
print 'Loading server list failed.'
def print_rules(lan_ip_block, interface, virtual_interface, config_dir):
"""
Outputs rules for blocking non-VPN traffic in the form used by
iptables-persistent.
More specifically, these rules will block any traffic that isn't from/to
the LAN, loopback, or VPN.
"""
if not is_root():
print 'This command must be run as root.'
return
server_ips = get_configured_server_ips(config_dir)
print '*filter'
# default policy: drop all the things
print ':INPUT DROP [0:0]'
print ':FORWARD DROP [0:0]'
print ':OUTPUT DROP [0:0]'
# allow input from loopback
print '-A INPUT -i lo -j ACCEPT'
# allow input from LAN
print '-A INPUT -s %s -i %s -j ACCEPT' % (lan_ip_block, interface)
# allow input from virtual interface
print '-A INPUT -i %s -j ACCEPT' % virtual_interface
# allow input from VPN servers (ie. for initial connection)
for server_ip in server_ips:
print '-A INPUT -s %s/32 -i %s -p udp -m udp --sport 443 -j ACCEPT' % (server_ip, interface)
# allow output to loopback
print '-A OUTPUT -o lo -j ACCEPT'
# allow output to LAN
print '-A OUTPUT -d %s -o %s -j ACCEPT' % (lan_ip_block, interface)
# allow output to virtual interface
print '-A OUTPUT -o %s -j ACCEPT' % virtual_interface
# allow output to VPN servers (ie. for initial connection)
for server_ip in server_ips:
print '-A OUTPUT -d %s/32 -o %s -p udp -m udp --dport 443 -j ACCEPT' % (server_ip, interface)
print 'COMMIT'
def main(args):
if args['<server-name>']:
args['<server-name>'] = [x.lower() for x in args['<server-name>']]
else:
args['<server-name>'] = [ None ]
if args['setup']:
setup(args['<server-name>'],
args['--connect'],
args['--openvpn-dir'])
elif args['connect']:
connect(args['<server-name>'][0],
args['--openvpn-dir'])
elif args['disconnect']:
disconnect()
elif args['remove']:
remove(args['<server-name>'][0], args['--openvpn-dir'])
elif args['list']:
if args['--local']:
list_local_servers(args['--openvpn-dir'])
else:
list_remote_servers()
elif args['status']:
status(args['<server-name>'][0])
elif args['rules']:
print_rules(args['--lan-ip-block'],
args['--interface'],
args['--virtual-interface'],
args['--openvpn-dir'])
if __name__ == '__main__':
args = docopt(__doc__, version='AirVPN CLI v1.0.2')
main(args)