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
|
#!/usr/bin/env python3
#
# Copyright (C) 2020 VyOS maintainers and contributors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or later as
# published by the Free Software Foundation.
#
# 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/>.
import sys
import os
import jinja2
from pwd import getpwall, getpwnam
from grp import getgrnam
from stat import S_IRUSR, S_IWUSR, S_IRWXU, S_IRGRP, S_IXGRP
from subprocess import Popen, PIPE, STDOUT
from vyos.config import Config
from vyos.configdict import list_diff
from vyos import ConfigError
radius_config_file = "/etc/pam_radius_auth.conf"
radius_config_tmpl = """
# Automatically generated by VyOS
# RADIUS configuration file
# server[:port] shared_secret timeout (s) source_ip
{% if radius_server -%}
{% for s in radius_server -%}
{{ s.address }}:{{ s.port }} {{ s.key }} {{ s.timeout }} {% if radius_source -%}{{ radius_source }}{% endif %}
{% endfor -%}
priv-lvl 15
mapped_priv_user radius_priv_user
{% endif %}
"""
default_config_data = {
'deleted': False,
'radius_server': [],
'radius_source': '',
'add_users': [],
'del_users': []
}
def get_local_users():
"""Returns list of dynamically allocated users (see Debian Policy Manual)"""
local_users = []
for p in getpwall():
username = p[0]
uid = getpwnam(username).pw_uid
if uid in range(1000, 29999):
if username not in ['radius_user', 'radius_priv_user']:
local_users.append(username)
return local_users
def get_crypt_pw(password):
command = '/usr/bin/mkpasswd --method=sha-512 {}'.format(password)
p = Popen(command, stdout=PIPE, stderr=STDOUT, shell=True)
tmp = p.communicate()[0].strip()
return tmp.decode()
def get_config():
login = default_config_data
conf = Config()
base_level = ['system', 'login']
if not conf.exists(base_level):
login['deleted'] = True
return login
conf.set_level(base_level)
if conf.exists(['radius', 'source-address']):
login['radius_source'] = conf.return_value(['radius', 'source-address'])
# Read in all RADIUS servers and store to list
for server in conf.list_nodes(['radius', 'server']):
radius = {
'address': server,
'key': '',
'port': '1812',
'timeout': '2'
}
conf.set_level(base_level + ['radius', 'server', server])
# RADIUS shared secret
if conf.exists(['key']):
radius['key'] = conf.return_value(['key'])
# RADIUS authentication port
if conf.exists(['port']):
radius['port'] = conf.return_value(['port'])
# RADIUS session timeout
if conf.exists(['timeout']):
radius['timeout'] = conf.return_value(['timeout'])
# Append individual RADIUS server configuration to global server list
login['radius_server'].append(radius)
# Read in all local users and store to list
conf.set_level(base_level)
for username in conf.list_nodes(['user']):
user = {
'name': username,
'password_plaintext': '',
'password_encrypted': '!',
'public_keys': [],
'full_name': '',
'home_dir': '/home/' + username,
}
conf.set_level(base_level + ['user', username])
# Plaintext password
if conf.exists(['authentication', 'plaintext-password']):
user['password_plaintext'] = conf.return_value(['authentication', 'plaintext-password'])
# Encrypted password
if conf.exists(['authentication', 'encrypted-password']):
user['password_encrypted'] = conf.return_value(['authentication', 'encrypted-password'])
# User real name
if conf.exists(['full-name']):
user['full_name'] = conf.return_value(['full-name'])
# User home-directory
if conf.exists(['home-directory']):
user['home_dir'] = conf.return_value(['home-directory'])
# Read in public keys
for id in conf.list_nodes(['authentication', 'public-keys']):
key = {
'name': id,
'key': '',
'options': '',
'type': ''
}
conf.set_level(base_level + ['user', username, 'authentication', 'public-keys', id])
# Public Key portion
if conf.exists(['key']):
key['key'] = conf.return_value(['key'])
# Options for individual public key
if conf.exists(['options']):
key['options'] = conf.return_value(['options'])
# Type of public key
if conf.exists(['type']):
key['type'] = conf.return_value(['type'])
# Append individual public key to list of user keys
user['public_keys'].append(key)
login['add_users'].append(user)
return login
def verify(login):
pass
def generate(login):
# users no longer existing in the running configuration need to be deleted
local_users = get_local_users()
cli_users = [tmp['name'] for tmp in login['add_users']]
# create a list of all users, cli and users
all_users = list(set(local_users+cli_users))
# Remove any normal users that dos not exist in the current configuration.
# This can happen if user is added but configuration was not saved and
# system is rebooted.
login['del_users'] = [tmp for tmp in all_users if tmp not in cli_users]
# calculate users encrypted password
for user in login['add_users']:
if user['password_plaintext']:
user['password_encrypted'] = get_crypt_pw(user['password_plaintext'])
user['password_plaintext'] = ''
# remove old plaintext password
# and set new encrypted password
os.system("vyos_libexec_dir=/usr/libexec/vyos /opt/vyatta/sbin/my_set system login user '{}' authentication plaintext-password '' >/dev/null".format(user['name']))
os.system("vyos_libexec_dir=/usr/libexec/vyos /opt/vyatta/sbin/my_set system login user '{}' authentication encrypted-password '{}' >/dev/null".format(user['name'], user['password_encrypted']))
uid = getpwnam(user['name']).pw_uid
gid = getpwnam(user['name']).pw_gid
# install ssh keys
key_dir = '{}/.ssh'.format(user['home_dir'])
if not os.path.isdir(key_dir):
os.mkdir(key_dir)
os.chown(key_dir, uid, gid)
os.chmod(key_dir, S_IRWXU | S_IRGRP | S_IXGRP)
key_file = key_dir + '/authorized_keys';
with open(key_file, 'w') as f:
f.write("# Automatically generated by VyOS\n")
f.write("# Do not edit, all changes will be lost\n")
for id in user['public_keys']:
line = ''
if id['options']:
line = '{} '.format(id['options'])
line += '{} {} {}\n'.format(id['type'], id['key'], id['name'])
f.write(line)
os.chown(key_file, uid, gid)
os.chmod(key_file, S_IRUSR | S_IWUSR)
#
# RADIUS
#
if len(login['radius_server']) > 0:
tmpl = jinja2.Template(radius_config_tmpl)
config_text = tmpl.render(login)
with open(radius_config_file, 'w') as f:
f.write(config_text)
uid = getpwnam('root').pw_uid
gid = getpwnam('root').pw_gid
os.chown(radius_config_file, uid, gid)
os.chmod(radius_config_file, S_IRUSR | S_IWUSR)
else:
os.unlink(radius_config_file)
pass
def apply(login):
for user in login['add_users']:
# make new user using vyatta shell and make home directory (-m),
# default group of 100 (users)
cmd = "useradd -m -N"
# check if user already exists:
if user['name'] in get_local_users():
# update existing account
cmd = "usermod"
# encrypted password must be quited in '' else it won't work!
cmd += " -p '{}'".format(user['password_encrypted'])
cmd += " -s /bin/vbash"
if user['full_name']:
cmd += " -c {}".format(user['full_name'])
if user['home_dir']:
cmd += " -d '{}'".format(user['home_dir'])
cmd += " -G frrvty,vyattacfg,sudo,adm,dip,disk"
cmd += " {}".format(user['name'])
try:
os.system(cmd)
except Exception as e:
print('Adding user "{}" raised an exception'.format(user))
for user in login['del_users']:
try:
# Remove user account but leave home directory to be safe
os.system('userdel {}'.format(user))
except Exception as e:
print('Deleting user "{}" raised an exception'.format(user))
#
# RADIUS
#
if len(login['radius_server']) > 0:
# Enable RADIUS in PAM
os.system("DEBIAN_FRONTEND=noninteractive pam-auth-update --package --enable radius")
else:
# Disable RADIUS in PAM
os.system("DEBIAN_FRONTEND=noninteractive pam-auth-update --package --remove radius")
pass
if __name__ == '__main__':
try:
c = get_config()
verify(c)
generate(c)
apply(c)
except ConfigError as e:
print(e)
sys.exit(1)
|