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
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__VERSION__ = (1,5)
import os, stat
import argparse, glob
import pathlib, re, uuid
# Class holds all static variables
class Props(object):
_openvpn_conf_dir = '/etc/openvpn'
_login_config = '/etc/private-internet-access/login.conf'
_system_connection_conf = '/etc/private-internet-access/system-connection-example'
_connman_connection_conf = '/etc/private-internet-access/connman-config-example.config'
_nm_conf_dir = '/etc/NetworkManager/system-connections'
_cm_conf_dir = '/var/lib/connman-vpn'
_progs = {'cm':False,'nm':False, 'openvpn':False}
_openvpn_configs = {}
@property
def openvpn_conf_dir(self):
return self._openvpn_conf_dir
@property
def login_config(self):
return self._login_config
@property
def system_connection_conf(self):
return self._system_connection_conf
@property
def nm_conf_dir (self):
return self._nm_conf_dir
@property
def cm_conf_dir (self):
return self._cm_conf_dir
@property
def connman_connection_conf (self):
return self._connman_connection_conf
@property
def progs (self):
return self._progs
@progs.setter
def progs (self, prog, installed):
self._progs[prog] = installed
@property
def openvpn_configs(self):
return self._openvpn_configs
@openvpn_configs.setter
def openvpn_configs(self, configs):
self._openvpn_configs = configs
def __init__(self):
self.get_openvpn_configs()
def get_openvpn_configs(self):
openvpn_configs = {}
for filename in glob.glob(self.openvpn_conf_dir + '/*.conf') :
id = re.sub('_',' ', re.match(r"^/(.*/)*(.+)\.conf$", filename).group(2))
openvpn_configs[id] = [re.sub(' ', '_', id), filename]
self.openvpn_configs = openvpn_configs
def remove_configurations(self):
for config in self.openvpn_configs:
id,filename = self.openvpn_configs[config]
if (self.progs['nm']):
try:
os.remove(self.nm_conf_dir + "/" + id)
except IOError:
print('Cannot remove configuration for ' + id)
pass
if (self.progs['cm']):
try:
os.remove(self.cm_conf_dir + "/" + id + ".config")
except IOError:
print('Cannot delete configuration for ' + id + '. Skipping...')
pass
props = Props()
# Checks if script has root permissions only.
def has_proper_permissions(filepath):
st = os.stat(filepath)
return bool(st.st_uid == 0 & st.st_gid == 0 & int(oct(stat.S_IMODE(os.stat(filepath).st_mode)) == "0o600"))
# Modifies OpenVPN configurations in /etc/openvpn
def openvpn_autologin (id, filename, enable=True):
try:
p = pathlib.Path(filename)
with p.open() as f:
content = f.read()
if (enable):
content = re.sub("(auth-user-pass)(?:.*)","auth-user-pass " + props.login_config, content)
else:
content = re.sub("(auth-user-pass)(?:.*)","auth-user-pass", content)
with open(filename, "w") as f:
f.write(content)
except IOError:
print ('Cannot access ' + filename + '.')
exit (1)
def check_installed():
global props
if os.path.isfile('/usr/bin/nmcli'):
if os.path.isfile('/usr/lib/networkmanager/nm-openvpn-service'):
props.progs['nm'] = True
if os.path.isfile('/usr/bin/connmanctl'):
props.progs['cm'] = True
if os.path.isfile('/usr/bin/openvpn'):
props.progs['openvpn'] = True
# Modifies Network Connection configurations
def nm_autologin(id, filename):
# Creates dictionary to hold replacement values
re_dict = {}
try:
#Opens login.conf and reads login and passwords from file
p = pathlib.Path(props.login_config)
with p.open() as f:
content = f.read().splitlines()
except IOError:
print ('Cannot access ' + props.login_config + '. Please make sure the file is created and readable by root.')
else:
re_dict["##username##"] = content[0]
re_dict["##password##"] = content[1]
re_dict["##id##"] = id
# Creates uuid for configuration file
re_dict["##uuid##"] = str(uuid.uuid4())
# Retrieves remote address from OpenVPN configuration
re_dict["##remote##"] = get_remote_address(filename)
try:
p = pathlib.Path(props.system_connection_conf)
with p.open() as f:
content = f.read()
except IOError:
print('Network Manager template missing from ' + props.system_connection_conf)
else:
nm_conf = props.nm_conf_dir + "/" + id
try:
#Opens Network Configurations and replaces options from the "re_dict" dictionary
with open(nm_conf,"w") as f:
f.write(multiple_replace(re_dict,content))
os.chmod(nm_conf,0o600)
os.chown(nm_conf,0,0)
except IOError:
#No Network Manager installed?
pass
def cm_autologin(id, filename):
# Creates dictionary to hold replacement values
re_dict = {}
re_dict["##id##"] = id
re_dict["##filename##"] = filename
# Retrieves remote address from OpenVPN configuration
re_dict["##remote##"] = get_remote_address(filename)
try:
p = pathlib.Path(props.connman_connection_conf)
with p.open() as f:
content = f.read()
except IOError:
print('Connman template missing from ' + props.connman_connection_conf)
else:
cm_conf = props.cm_conf_dir + "/" + re.sub(' ','_',id) + ".config"
try:
#Opens Connman Configurations and replaces options from the "re_dict" dictionary
with open(cm_conf,"w") as f:
f.write(multiple_replace(re_dict,content))
os.chmod(cm_conf,0o600)
os.chown(cm_conf,0,0)
except IOError:
print('Cannot modify configuration for ' + id + '. Skipping...')
pass
# Gets remote address from OpenVPn files
def get_remote_address(filename):
p = pathlib.Path(filename)
with p.open() as f:
contents = f.read()
return ''.join(re.findall("(?:remote.)(.*)(?:.\d{4})",contents))
def multiple_replace(dict, text):
# Create a regular expression from the dictionary keys
regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
# For each match, look-up corresponding value in dictionary
return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Configures PIA VPN Services for Connman, Network Manager, and OpenVPN')
group = parser.add_mutually_exclusive_group(required=False)
group.add_argument('-a','--auto-configure', dest='configure', action='store_true',help='Automatically generates configurations')
group.add_argument('-r','--remove-configurations', dest='configure', action='store_false',help='Removes auto-generated configurations')
parser.add_argument('-e','--exclude', dest='exclude', choices=props.progs, action='append',
help='Excludes modifying the configurations of the listed program. Maybe used more then once.')
parser.add_argument('host',nargs='*', help='Lists of host names to configure')
parser.add_argument('-v','--verbose', dest='verbose', action='store_true',help='Enables more verbose logging')
parser.add_argument('--version', action='version', version='%(prog)s 1.5')
parser.parse_args(namespace=props)
if os.getuid() > 0:
print ('ERROR: You must run this script with administrative privilages!')
exit(1)
if not has_proper_permissions(props.login_config):
print ('ERROR: ' + props.login_config + ' must be owned by root and not world readable!')
exit(1)
check_installed()
if props.exclude:
for prog in props.exclude:
props.progs[prog] = False
custom_configs = {}
if props.host:
for id in props.host:
custom_configs[id] = props.openvpn_configs[id]
if custom_configs:
props.openvpn_configs = custom_configs
if props.configure:
for config in props.openvpn_configs:
id, filename = props.openvpn_configs[config]
if (props.verbose):
if (props.auto_login):
print ("Enabling auto-logins for " + config + " remote server...")
else:
print ("Disablig auto-logins for " + config + " remote server...")
if (props.configure):
if (props.progs['openvpn']):
openvpn_autologin(id, filename)
if (props.progs['nm']):
nm_autologin(id, filename)
if (props.progs['cm']):
cm_autologin(id, filename)
else:
props.remove_configurations()
|