-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy path__main__.py
380 lines (332 loc) · 11 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
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
from pritunl_client.constants import *
import optparse
import sys
import os
import subprocess
import signal
import time
import hashlib
import json
import requests
import uuid
def client_gui():
import pritunl_client
from pritunl_client import app
parser = optparse.OptionParser()
parser.add_option('--version', action='store_true', help='Print version')
(options, args) = parser.parse_args()
if options.version:
print '%s v%s' % (pritunl_client.__title__, pritunl_client.__version__)
else:
client_app = app.App()
client_app.main()
def client_shell():
from pritunl_client import constants
constants.set_shell()
from pritunl_client import click
def get_auth_headers(add_headers=None):
response = requests.get(
'http://localhost:9797/token',
headers={
'User-Agent': 'pritunl',
},
)
headers = {
'User-Agent': 'pritunl',
'Auth-Token': response.content,
}
if add_headers:
headers.update(add_headers)
return headers
@click.group()
def cli():
pass
@click.command('daemon',
help='Start client service daemon',
)
@click.option('--pidfile',
help='Path to create pid file',
default=None,
)
@click.option('--foreground',
help='Run daemon in foreground',
is_flag=True,
)
def daemon_cmd(pidfile, foreground):
if not foreground:
pid = os.fork()
if pid > 0:
if pidfile:
with open(pidfile, 'w') as pid_file:
pid_file.write('%s' % pid)
sys.exit(0)
else:
if pidfile:
with open(pidfile, 'w') as pid_file:
pid_file.write(str(os.getpid()))
from pritunl_client import shell_app
shell_app.ShellApp()
cli.add_command(daemon_cmd)
@click.command('list',
help='List imported profiles and status',
)
def list_cmd():
response = requests.get(
'http://localhost:9797/list',
headers=get_auth_headers(),
)
if response.status_code == 200:
click.echo(response.content)
else:
click.echo(response.content)
sys.exit(1)
cli.add_command(list_cmd)
@click.command(name='import',
help='Import new profile archive, conf or uri. Can be ' + \
'path to profile conf or path to archive or profile uri',
)
@click.argument('profile_ins',
nargs=-1,
)
def import_cmd(profile_ins):
for profile_in in profile_ins:
data = {}
if os.path.exists(profile_in):
data['profile_path'] = os.path.abspath(profile_in)
else:
data['profile_uri'] = profile_in
response = requests.post(
'http://localhost:9797/import',
headers=get_auth_headers({
'Content-type': 'application/json',
}),
data=json.dumps(data),
)
if response.status_code == 200:
click.echo('Successfully imported profile')
else:
click.echo(response.content)
sys.exit(1)
cli.add_command(import_cmd)
@click.command('remove',
help='Remove a profile by profile ID or space separated list of IDs',
)
@click.argument('profile_ids',
nargs=-1,
)
def remove_cmd(profile_ids):
for profile_id in profile_ids:
response = requests.delete(
'http://localhost:9797/remove/%s' % profile_id,
headers=get_auth_headers(),
)
if response.status_code == 200:
click.echo('Successfully removed profile')
else:
click.echo(response.content)
sys.exit(1)
cli.add_command(remove_cmd)
@click.command('start',
help='Start a profile by profile ID or space separated list of IDs',
)
@click.argument('profile_ids',
nargs=-1,
)
@click.option('--password',
help='Password for profile if required',
default=None,
)
def start_cmd(profile_ids, password):
for profile_id in profile_ids:
if password:
headers = {
'Content-type': 'application/json',
}
data = json.dumps({
'passwd': password,
})
else:
headers = None
data = None
response = requests.put(
'http://localhost:9797/start/%s' % profile_id,
headers=get_auth_headers(headers),
data=data,
)
if response.status_code == 200:
click.echo('Successfully started profile')
else:
click.echo(response.content)
sys.exit(1)
cli.add_command(start_cmd)
@click.command('stop',
help='Stop a profile by profile ID or space separated list of IDs',
)
@click.argument('profile_ids',
nargs=-1,
)
def stop_cmd(profile_ids):
for profile_id in profile_ids:
response = requests.put(
'http://localhost:9797/stop/%s' % profile_id,
headers=get_auth_headers(),
)
if response.status_code == 200:
click.echo('Successfully stopped profile')
else:
click.echo(response.content)
sys.exit(1)
cli.add_command(stop_cmd)
@click.command('enable',
help='Enable a profile to autostart by profile ID or space ' + \
'separated list of IDs',
)
@click.argument('profile_ids',
nargs=-1,
)
def enable_cmd(profile_ids):
for profile_id in profile_ids:
response = requests.put(
'http://localhost:9797/enable/%s' % profile_id,
headers=get_auth_headers(),
)
if response.status_code == 200:
click.echo('Successfully enabled profile')
else:
click.echo(response.content)
sys.exit(1)
cli.add_command(enable_cmd)
@click.command('disable',
help='Disable a profile to stop autostart by profile ID or space ' + \
'separated list of IDs',
)
@click.argument('profile_ids',
nargs=-1,
)
def disable_cmd(profile_ids):
for profile_id in profile_ids:
response = requests.put(
'http://localhost:9797/disable/%s' % profile_id,
headers=get_auth_headers(),
)
if response.status_code == 200:
click.echo('Successfully disabled profile')
else:
click.echo(response.content)
sys.exit(1)
cli.add_command(disable_cmd)
cli()
def get_env():
env_path = sys.argv[-1]
if not env_path.startswith('--env='):
return {}
env_path = env_path[6:]
with open(env_path, 'r') as env_file:
env = json.loads(env_file.read())
if not env.get('PRITUNL_CLIENT_ENV'):
raise ValueError('Invalid environment file')
os.remove(env_path)
return env
def _pk_start(autostart=False):
env = get_env()
conf_data = env.get('VPN_CONF')
passwd = env.get('VPN_PASSWORD')
if autostart:
profile_hash = hashlib.sha512(conf_data).hexdigest()
profile_hash_path = os.path.join(os.path.abspath(os.sep),
'etc', 'pritunl_client', profile_hash)
if not os.path.exists(profile_hash_path):
raise ValueError('Profile not authorized to autostart')
conf_path = os.path.join('/tmp', uuid.uuid4().hex + '.conf')
pass_path = None
args = ['openvpn', '--config', conf_path]
if passwd:
pass_path = os.path.join('/tmp', uuid.uuid4().hex + '.pass')
args.append('--auth-user-pass')
args.append(pass_path)
systemd_resolve = False
try:
subprocess.check_call(['which', 'systemd-resolve'])
with open('/etc/resolv.conf', 'r') as resolv_file:
data = resolv_file.read()
if 'systemd-resolved' in data or '127.0.0.53' in data:
systemd_resolve = True
except:
pass
if systemd_resolve:
script_path = os.path.join(SHARE_DIR, 'update-systemd-resolved.sh')
else:
script_path = os.path.join(SHARE_DIR, 'update-resolv-conf.sh')
args.extend(['--script-security', '2'])
args.append('--up-restart')
args.extend(['--up', script_path])
args.extend(['--down', script_path])
args.extend(['--route-pre-down', '/bin/true'])
args.extend(['--tls-verify', '/bin/true'])
args.extend(['--ipchange', '/bin/true'])
args.extend(['--route-up', '/bin/true'])
try:
with open(conf_path, 'w') as conf_file:
os.chmod(conf_path, 0600)
conf_file.write(conf_data)
if passwd:
with open(pass_path, 'w') as passwd_file:
os.chmod(pass_path, 0600)
passwd_file.write('pritunl_client\n')
passwd_file.write('%s\n' % passwd)
process = subprocess.Popen(args)
def sig_handler(signum, frame):
process.send_signal(signum)
signal.signal(signal.SIGINT, sig_handler)
signal.signal(signal.SIGTERM, sig_handler)
time.sleep(1)
os.remove(conf_path)
if passwd:
os.remove(pass_path)
sys.exit(process.wait())
finally:
try:
os.remove(conf_path)
except:
pass
if passwd:
try:
os.remove(pass_path)
except:
pass
def pk_start():
_pk_start(False)
def pk_autostart():
_pk_start(True)
def pk_stop():
pid = int(sys.argv[1])
cmdline_path = '/proc/%d/cmdline' % pid
if not os.path.exists(cmdline_path):
return
with open(cmdline_path, 'r') as cmdline_file:
cmdline = cmdline_file.read().strip().strip('\x00')
if not 'pritunl-client-pk-start' in cmdline and \
not 'pritunl-client-pk-autostart' in cmdline:
raise ValueError('Not a pritunl client process')
os.kill(pid, signal.SIGTERM)
for i in xrange(int(5 / 0.1)):
time.sleep(0.1)
if not os.path.exists('/proc/%d' % pid):
break
os.kill(pid, signal.SIGTERM)
def pk_set_autostart():
env = get_env()
conf_data = env.get('VPN_CONF')
profile_hash = hashlib.sha512(conf_data).hexdigest()
etc_dir = os.path.join(os.path.abspath(os.sep),
'etc', 'pritunl_client')
if not os.path.exists(etc_dir):
os.makedirs(etc_dir)
profile_hash_path = os.path.join(etc_dir, profile_hash)
with open(profile_hash_path, 'w') as _:
pass
def pk_clear_autostart():
profile_hash_path = os.path.join(os.path.abspath(os.sep),
'etc', 'pritunl_client', sys.argv[1])
if os.path.exists(profile_hash_path):
os.remove(profile_hash_path)