-
Notifications
You must be signed in to change notification settings - Fork 85
/
hostcfgd
1800 lines (1499 loc) · 71.6 KB
/
hostcfgd
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import copy
import ipaddress
import os
import sys
import subprocess
import syslog
import signal
import re
import jinja2
import json
from shutil import copy2
from datetime import datetime
from sonic_py_common import device_info
from sonic_py_common.general import check_output_pipe
from swsscommon.swsscommon import ConfigDBConnector, DBConnector, Table
from swsscommon import swsscommon
from sonic_installer import bootloader
# FILE
PAM_AUTH_CONF = "/etc/pam.d/common-auth-sonic"
PAM_AUTH_CONF_TEMPLATE = "/usr/share/sonic/templates/common-auth-sonic.j2"
PAM_PASSWORD_CONF = "/etc/pam.d/common-password"
PAM_PASSWORD_CONF_TEMPLATE = "/usr/share/sonic/templates/common-password.j2"
SSH_CONFG = "/etc/ssh/sshd_config"
SSH_CONFG_TMP = SSH_CONFG + ".tmp"
NSS_TACPLUS_CONF = "/etc/tacplus_nss.conf"
NSS_TACPLUS_CONF_TEMPLATE = "/usr/share/sonic/templates/tacplus_nss.conf.j2"
NSS_RADIUS_CONF = "/etc/radius_nss.conf"
NSS_RADIUS_CONF_TEMPLATE = "/usr/share/sonic/templates/radius_nss.conf.j2"
PAM_RADIUS_AUTH_CONF_TEMPLATE = "/usr/share/sonic/templates/pam_radius_auth.conf.j2"
NSS_CONF = "/etc/nsswitch.conf"
ETC_PAMD_SSHD = "/etc/pam.d/sshd"
ETC_PAMD_LOGIN = "/etc/pam.d/login"
ETC_LOGIN_DEF = "/etc/login.defs"
# Linux login.def default values (password hardening disable)
LINUX_DEFAULT_PASS_MAX_DAYS = 99999
LINUX_DEFAULT_PASS_WARN_AGE = 7
# Ssh min-max values
SSH_MIN_VALUES={"authentication_retries": 3, "login_timeout": 1, "ports": 1}
SSH_MAX_VALUES={"authentication_retries": 100, "login_timeout": 600, "ports": 65535}
SSH_CONFIG_NAMES={"authentication_retries": "MaxAuthTries" , "login_timeout": "LoginGraceTime"}
ACCOUNT_NAME = 0 # index of account name
AGE_DICT = { 'MAX_DAYS': {'REGEX_DAYS': r'^PASS_MAX_DAYS[ \t]*(?P<max_days>\d*)', 'DAYS': 'max_days', 'CHAGE_FLAG': '-M '},
'WARN_DAYS': {'REGEX_DAYS': r'^PASS_WARN_AGE[ \t]*(?P<warn_days>\d*)', 'DAYS': 'warn_days', 'CHAGE_FLAG': '-W '}
}
PAM_LIMITS_CONF_TEMPLATE = "/usr/share/sonic/templates/pam_limits.j2"
LIMITS_CONF_TEMPLATE = "/usr/share/sonic/templates/limits.conf.j2"
PAM_LIMITS_CONF = "/etc/pam.d/pam-limits-conf"
LIMITS_CONF = "/etc/security/limits.conf"
# TACACS+
TACPLUS_SERVER_PASSKEY_DEFAULT = ""
TACPLUS_SERVER_TIMEOUT_DEFAULT = "5"
TACPLUS_SERVER_AUTH_TYPE_DEFAULT = "pap"
# RADIUS
RADIUS_SERVER_AUTH_PORT_DEFAULT = "1812"
RADIUS_SERVER_PASSKEY_DEFAULT = ""
RADIUS_SERVER_RETRANSMIT_DEFAULT = "3"
RADIUS_SERVER_TIMEOUT_DEFAULT = "5"
RADIUS_SERVER_AUTH_TYPE_DEFAULT = "pap"
RADIUS_PAM_AUTH_CONF_DIR = "/etc/pam_radius_auth.d/"
# FIPS
FIPS_CONFIG_FILE = '/etc/sonic/fips.json'
OPENSSL_FIPS_CONFIG_FILE = '/etc/fips/fips_enable'
DEFAULT_FIPS_RESTART_SERVICES = ['ssh', 'telemetry.service', 'restapi']
# MISC Constants
CFG_DB = "CONFIG_DB"
STATE_DB = "STATE_DB"
def signal_handler(sig, frame):
if sig == signal.SIGHUP:
syslog.syslog(syslog.LOG_INFO, "HostCfgd: signal 'SIGHUP' is caught and ignoring..")
elif sig == signal.SIGINT:
syslog.syslog(syslog.LOG_INFO, "HostCfgd: signal 'SIGINT' is caught and exiting...")
sys.exit(128 + sig)
elif sig == signal.SIGTERM:
syslog.syslog(syslog.LOG_INFO, "HostCfgd: signal 'SIGTERM' is caught and exiting...")
sys.exit(128 + sig)
else:
syslog.syslog(syslog.LOG_INFO, "HostCfgd: invalid signal - ignoring..")
def run_cmd(cmd, log_err=True, raise_exception=False):
try:
subprocess.check_call(cmd)
except Exception as err:
if log_err:
syslog.syslog(syslog.LOG_ERR, "{} - failed: return code - {}, output:\n{}"
.format(err.cmd, err.returncode, err.output))
if raise_exception:
raise
def run_cmd_pipe(cmd0, cmd1, cmd2, log_err=True, raise_exception=False):
try:
check_output_pipe(cmd0, cmd1, cmd2)
except Exception as err:
if log_err:
syslog.syslog(syslog.LOG_ERR, "{} - failed: return code - {}, output:\n{}"
.format(err.cmd, err.returncode, err.output))
if raise_exception:
raise
def run_cmd_output(cmd, log_err=True, raise_exception=False):
output = ''
try:
output = subprocess.check_output(cmd)
except Exception as err:
if log_err:
syslog.syslog(syslog.LOG_ERR, "{} - failed: return code - {}, output:\n{}"
.format(err.cmd, err.returncode, err.output))
if raise_exception:
raise
return output
def is_true(val):
if val == 'True' or val == 'true':
return True
elif val == 'False' or val == 'false':
return False
syslog.syslog(syslog.LOG_ERR, "Failed to get bool value, instead val= {}".format(val))
return False
def is_vlan_sub_interface(ifname):
ifname_split = ifname.split(".")
return (len(ifname_split) == 2)
def sub(l, start, end):
return l[start:end]
def obfuscate(data):
if data:
return data[0] + '*****'
else:
return data
def get_pid(procname):
for dirname in os.listdir('/proc'):
if dirname == 'curproc':
continue
try:
with open('/proc/{}/cmdline'.format(dirname), mode='r') as fd:
content = fd.read()
except Exception as ex:
continue
if procname in content:
return dirname
return ""
class Iptables(object):
def __init__(self):
'''
Default MSS to 1460 - (MTU 1500 - 40 (TCP/IP Overhead))
For IPv6, it would be 1440 - (MTU 1500 - 60 octects)
'''
self.tcpmss = 1460
self.tcp6mss = 1440
def is_ip_prefix_in_key(self, key):
'''
Function to check if IP address is present in the key. If it
is present, then the key would be a tuple or else, it shall be
be string
'''
return (isinstance(key, tuple))
def load(self, lpbk_table):
for row in lpbk_table:
self.iptables_handler(row, lpbk_table[row])
def command(self, chain, ip, ver, op):
cmd = ['iptables'] if ver == '4' else ['ip6tables']
cmd += ['-t', 'mangle', '--{}'.format(op), chain, "-p", "tcp", "--tcp-flags", 'SYN', 'SYN']
cmd += ['-d'] if chain == 'PREROUTING' else ['-s']
mss = str(self.tcpmss) if ver == '4' else str(self.tcp6mss)
cmd += [ip, "-j", "TCPMSS", "--set-mss", mss]
return cmd
def iptables_handler(self, key, data, add=True):
if not self.is_ip_prefix_in_key(key):
return
iface, ip = key
ip_str = ip.split("/")[0]
ip_addr = ipaddress.ip_address(ip_str)
if isinstance(ip_addr, ipaddress.IPv6Address):
ver = '6'
else:
ver = '4'
self.mangle_handler(ip_str, ver, add)
def mangle_handler(self, ip, ver, add):
if not add:
op = 'delete'
else:
op = 'check'
iptables_cmds = []
chains = ['PREROUTING', 'POSTROUTING']
for chain in chains:
cmd = self.command(chain, ip, ver, op)
if not add:
iptables_cmds.append(cmd)
else:
'''
For add case, first check if rule exists. Iptables just appends to the chain
as a new rule even if it is the same as an existing one. Check this and
do nothing if rule exists
'''
ret = subprocess.call(cmd)
if ret == 0:
syslog.syslog(syslog.LOG_INFO, "{} rule exists in {}".format(ip, chain))
else:
# Modify command from Check to Append
iptables_cmds.append([word.replace('check', 'append') for word in cmd])
for cmd in iptables_cmds:
syslog.syslog(syslog.LOG_INFO, "Running cmd - {}".format(cmd))
run_cmd(cmd)
class AaaCfg(object):
def __init__(self):
self.authentication_default = {
'login': 'local',
}
self.authorization_default = {
'login': 'local',
}
self.accounting_default = {
'login': 'disable',
}
self.tacplus_global_default = {
'auth_type': TACPLUS_SERVER_AUTH_TYPE_DEFAULT,
'timeout': TACPLUS_SERVER_TIMEOUT_DEFAULT,
'passkey': TACPLUS_SERVER_PASSKEY_DEFAULT
}
self.tacplus_global = {}
self.tacplus_servers = {}
self.radius_global_default = {
'priority': 0,
'auth_port': RADIUS_SERVER_AUTH_PORT_DEFAULT,
'auth_type': RADIUS_SERVER_AUTH_TYPE_DEFAULT,
'retransmit': RADIUS_SERVER_RETRANSMIT_DEFAULT,
'timeout': RADIUS_SERVER_TIMEOUT_DEFAULT,
'passkey': RADIUS_SERVER_PASSKEY_DEFAULT
}
self.radius_global = {}
self.radius_servers = {}
self.authentication = {}
self.authorization = {}
self.accounting = {}
self.debug = False
self.trace = False
self.hostname = ""
# Load conf from ConfigDb
def load(self, aaa_conf, tac_global_conf, tacplus_conf, rad_global_conf, radius_conf):
for row in aaa_conf:
self.aaa_update(row, aaa_conf[row], modify_conf=False)
for row in tac_global_conf:
self.tacacs_global_update(row, tac_global_conf[row], modify_conf=False)
for row in tacplus_conf:
self.tacacs_server_update(row, tacplus_conf[row], modify_conf=False)
for row in rad_global_conf:
self.radius_global_update(row, rad_global_conf[row], modify_conf=False)
for row in radius_conf:
self.radius_server_update(row, radius_conf[row], modify_conf=False)
self.modify_conf_file()
def aaa_update(self, key, data, modify_conf=True):
if key == 'authentication':
self.authentication = data
if 'failthrough' in data:
self.authentication['failthrough'] = is_true(data['failthrough'])
if 'debug' in data:
self.debug = is_true(data['debug'])
if key == 'authorization':
self.authorization = data
if key == 'accounting':
self.accounting = data
if modify_conf:
self.modify_conf_file()
def pick_src_intf_ipaddrs(self, keys, src_intf):
new_ipv4_addr = ""
new_ipv6_addr = ""
for it in keys:
if src_intf != it[0] or (isinstance(it, tuple) == False):
continue
if new_ipv4_addr != "" and new_ipv6_addr != "":
break
ip_str = it[1].split("/")[0]
ip_addr = ipaddress.IPAddress(ip_str)
# Pick the first IP address from the table that matches the source interface
if isinstance(ip_addr, ipaddress.IPv6Address):
if new_ipv6_addr != "":
continue
new_ipv6_addr = ip_str
else:
if new_ipv4_addr != "":
continue
new_ipv4_addr = ip_str
return(new_ipv4_addr, new_ipv6_addr)
def tacacs_global_update(self, key, data, modify_conf=True):
if key == 'global':
self.tacplus_global = data
if modify_conf:
self.modify_conf_file()
def tacacs_server_update(self, key, data, modify_conf=True):
if data == {}:
if key in self.tacplus_servers:
del self.tacplus_servers[key]
else:
self.tacplus_servers[key] = data
if modify_conf:
self.modify_conf_file()
def notify_audisp_tacplus_reload_config(self):
pid = get_pid("/sbin/audisp-tacplus")
syslog.syslog(syslog.LOG_INFO, "Found audisp-tacplus PID: {}".format(pid))
if pid == "":
return
# audisp-tacplus will reload TACACS+ config when receive SIGHUP
try:
os.kill(int(pid), signal.SIGHUP)
except Exception as ex:
syslog.syslog(syslog.LOG_WARNING, "Send SIGHUP to audisp-tacplus failed with exception: {}".format(ex))
def handle_radius_source_intf_ip_chg(self, key):
modify_conf=False
if 'src_intf' in self.radius_global:
if key[0] == self.radius_global['src_intf']:
modify_conf=True
for addr in self.radius_servers:
if ('src_intf' in self.radius_servers[addr]) and \
(key[0] == self.radius_servers[addr]['src_intf']):
modify_conf=True
break
if not modify_conf:
return
syslog.syslog(syslog.LOG_INFO, 'RADIUS IP change - key:{}, current server info {}'.format(key, self.radius_servers))
self.modify_conf_file()
def handle_radius_nas_ip_chg(self, key):
modify_conf=False
# Mgmt IP configuration affects only the default nas_ip
if 'nas_ip' not in self.radius_global:
for addr in self.radius_servers:
if 'nas_ip' not in self.radius_servers[addr]:
modify_conf=True
break
if not modify_conf:
return
syslog.syslog(syslog.LOG_INFO, 'RADIUS (NAS) IP change - key:{}, current global info {}'.format(key, self.radius_global))
self.modify_conf_file()
def radius_global_update(self, key, data, modify_conf=True):
if key == 'global':
self.radius_global = data
if 'statistics' in data:
self.radius_global['statistics'] = is_true(data['statistics'])
if modify_conf:
self.modify_conf_file()
def radius_server_update(self, key, data, modify_conf=True):
if data == {}:
if key in self.radius_servers:
del self.radius_servers[key]
else:
self.radius_servers[key] = data
if modify_conf:
self.modify_conf_file()
def hostname_update(self, hostname, modify_conf=True):
if self.hostname == hostname:
return
self.hostname = hostname
# Currently only used for RADIUS
if len(self.radius_servers) == 0:
return
if modify_conf:
self.modify_conf_file()
def get_hostname(self):
return self.hostname
def get_interface_ip(self, source, addr=None):
keys = None
try:
if source.startswith("Eth"):
if is_vlan_sub_interface(source):
keys = self.config_db.get_keys('VLAN_SUB_INTERFACE')
else:
keys = self.config_db.get_keys('INTERFACE')
elif source.startswith("Po"):
if is_vlan_sub_interface(source):
keys = self.config_db.get_keys('VLAN_SUB_INTERFACE')
else:
keys = self.config_db.get_keys('PORTCHANNEL_INTERFACE')
elif source.startswith("Vlan"):
keys = self.config_db.get_keys('VLAN_INTERFACE')
elif source.startswith("Loopback"):
keys = self.config_db.get_keys('LOOPBACK_INTERFACE')
elif source == "eth0":
keys = self.config_db.get_keys('MGMT_INTERFACE')
except Exception as e:
pass
interface_ip = ""
if keys != None:
ipv4_addr, ipv6_addr = self.pick_src_intf_ipaddrs(keys, source)
# Based on the type of addr, return v4 or v6
if addr and isinstance(addr, ipaddress.IPv6Address):
interface_ip = ipv6_addr
else:
# This could be tuned, but that involves a DNS query, so
# offline configuration might trip (or cause delays).
interface_ip = ipv4_addr
return interface_ip
def check_file_not_empty(self, filename):
exists = os.path.exists(filename)
if not exists:
syslog.syslog(syslog.LOG_ERR, "file size check failed: {} is missing".format(filename))
return
size = os.path.getsize(filename)
if size == 0:
syslog.syslog(syslog.LOG_ERR, "file size check failed: {} is empty, file corrupted".format(filename))
return
syslog.syslog(syslog.LOG_INFO, "file size check pass: {} size is ({}) bytes".format(filename, size))
def modify_single_file(self, filename, operations=None):
if operations:
e_list = ['-e'] * len(operations)
e_operations = [item for sublist in zip(e_list, operations) for item in sublist]
with open(filename+'.new', 'w') as f:
subprocess.call(["sed"] + e_operations + [filename], stdout=f)
subprocess.call(["mv", '-f', filename, filename+'.old'])
subprocess.call(['mv', '-f', filename+'.new', filename])
self.check_file_not_empty(filename)
def modify_conf_file(self):
authentication = self.authentication_default.copy()
authentication.update(self.authentication)
authorization = self.authorization_default.copy()
authorization.update(self.authorization)
accounting = self.accounting_default.copy()
accounting.update(self.accounting)
tacplus_global = self.tacplus_global_default.copy()
tacplus_global.update(self.tacplus_global)
if 'src_ip' in tacplus_global:
src_ip = tacplus_global['src_ip']
else:
src_ip = None
servers_conf = []
if self.tacplus_servers:
for addr in self.tacplus_servers:
server = tacplus_global.copy()
server['ip'] = addr
server.update(self.tacplus_servers[addr])
servers_conf.append(server)
servers_conf = sorted(servers_conf, key=lambda t: int(t['priority']), reverse=True)
radius_global = self.radius_global_default.copy()
radius_global.update(self.radius_global)
# RADIUS: Set the default nas_ip, and nas_id
if 'nas_ip' not in radius_global:
nas_ip = self.get_interface_ip("eth0")
if len(nas_ip) > 0:
radius_global['nas_ip'] = nas_ip
if 'nas_id' not in radius_global:
nas_id = self.get_hostname()
if len(nas_id) > 0:
radius_global['nas_id'] = nas_id
radsrvs_conf = []
if self.radius_servers:
for addr in self.radius_servers:
server = radius_global.copy()
server['ip'] = addr
server.update(self.radius_servers[addr])
if 'src_intf' in server:
# RADIUS: Log a message if src_ip is already defined.
if 'src_ip' in server:
syslog.syslog(syslog.LOG_INFO, \
"RADIUS_SERVER|{}: src_intf found. Ignoring src_ip".format(addr))
# RADIUS: If server.src_intf, then get the corresponding
# src_ip based on the server.ip, and set it.
src_ip = self.get_interface_ip(server['src_intf'], addr)
if len(src_ip) > 0:
server['src_ip'] = src_ip
elif 'src_ip' in server:
syslog.syslog(syslog.LOG_INFO, \
"RADIUS_SERVER|{}: src_intf has no usable IP addr.".format(addr))
del server['src_ip']
radsrvs_conf.append(server)
radsrvs_conf = sorted(radsrvs_conf, key=lambda t: int(t['priority']), reverse=True)
template_file = os.path.abspath(PAM_AUTH_CONF_TEMPLATE)
env = jinja2.Environment(loader=jinja2.FileSystemLoader('/'), trim_blocks=True)
env.filters['sub'] = sub
template = env.get_template(template_file)
if 'radius' in authentication['login']:
pam_conf = template.render(debug=self.debug, trace=self.trace, auth=authentication, servers=radsrvs_conf)
else:
pam_conf = template.render(auth=authentication, src_ip=src_ip, servers=servers_conf)
# Use rename(), which is atomic (on the same fs) to avoid empty file
with open(PAM_AUTH_CONF + ".tmp", 'w') as f:
f.write(pam_conf)
os.chmod(PAM_AUTH_CONF + ".tmp", 0o644)
os.rename(PAM_AUTH_CONF + ".tmp", PAM_AUTH_CONF)
# Modify common-auth include file in /etc/pam.d/login, sshd.
# /etc/pam.d/sudo is not handled, because it would change the existing
# behavior. It can be modified once a config knob is added for sudo.
if os.path.isfile(PAM_AUTH_CONF):
self.modify_single_file(ETC_PAMD_SSHD, [ "/^@include/s/common-auth$/common-auth-sonic/" ])
self.modify_single_file(ETC_PAMD_LOGIN, [ "/^@include/s/common-auth$/common-auth-sonic/" ])
else:
self.modify_single_file(ETC_PAMD_SSHD, [ "/^@include/s/common-auth-sonic$/common-auth/" ])
self.modify_single_file(ETC_PAMD_LOGIN, [ "/^@include/s/common-auth-sonic$/common-auth/" ])
# Add tacplus/radius in nsswitch.conf if TACACS+/RADIUS enable
if 'tacacs+' in authentication['login']:
if os.path.isfile(NSS_CONF):
self.modify_single_file(NSS_CONF, [ "/^passwd/s/ radius//" ])
self.modify_single_file(NSS_CONF, [ "/tacplus/b", "/^passwd/s/compat/tacplus &/", "/^passwd/s/files/tacplus &/" ])
elif 'radius' in authentication['login']:
if os.path.isfile(NSS_CONF):
self.modify_single_file(NSS_CONF, [ "'/^passwd/s/tacplus //'" ])
self.modify_single_file(NSS_CONF, [ "/radius/b", "/^passwd/s/compat/& radius/", "/^passwd/s/files/& radius/" ])
else:
if os.path.isfile(NSS_CONF):
self.modify_single_file(NSS_CONF, [ "/^passwd/s/tacplus //g" ])
self.modify_single_file(NSS_CONF, [ "/^passwd/s/ radius//" ])
# Add tacplus authorization configration in nsswitch.conf
tacacs_authorization_conf = None
local_authorization_conf = None
if 'tacacs+' in authorization['login']:
tacacs_authorization_conf = "on"
if 'local' in authorization['login']:
local_authorization_conf = "on"
# Add tacplus accounting configration in nsswitch.conf
tacacs_accounting_conf = None
local_accounting_conf = None
if 'tacacs+' in accounting['login']:
tacacs_accounting_conf = "on"
if 'local' in accounting['login']:
local_accounting_conf = "on"
# Set tacacs+ server in nss-tacplus conf
template_file = os.path.abspath(NSS_TACPLUS_CONF_TEMPLATE)
template = env.get_template(template_file)
nss_tacplus_conf = template.render(
debug=self.debug,
src_ip=src_ip,
servers=servers_conf,
local_accounting=local_accounting_conf,
tacacs_accounting=tacacs_accounting_conf,
local_authorization=local_authorization_conf,
tacacs_authorization=tacacs_authorization_conf)
with open(NSS_TACPLUS_CONF, 'w') as f:
f.write(nss_tacplus_conf)
# Notify auditd plugin to reload tacacs config.
self.notify_audisp_tacplus_reload_config()
# Set debug in nss-radius conf
template_file = os.path.abspath(NSS_RADIUS_CONF_TEMPLATE)
template = env.get_template(template_file)
nss_radius_conf = template.render(debug=self.debug, trace=self.trace, servers=radsrvs_conf)
with open(NSS_RADIUS_CONF, 'w') as f:
f.write(nss_radius_conf)
# Create the per server pam_radius_auth.conf
if radsrvs_conf:
for srv in radsrvs_conf:
# Configuration File
pam_radius_auth_file = RADIUS_PAM_AUTH_CONF_DIR + srv['ip'] + "_" + srv['auth_port'] + ".conf"
template_file = os.path.abspath(PAM_RADIUS_AUTH_CONF_TEMPLATE)
template = env.get_template(template_file)
pam_radius_auth_conf = template.render(server=srv)
open(pam_radius_auth_file, 'a').close()
os.chmod(pam_radius_auth_file, 0o600)
with open(pam_radius_auth_file, 'w+') as f:
f.write(pam_radius_auth_conf)
# Start the statistics service. Only RADIUS implemented
if ('radius' in authentication['login']) and ('statistics' in radius_global) and \
radius_global['statistics']:
cmd = ['service', 'aaastatsd', 'start']
else:
cmd = ['service', 'aaastatsd', 'stop']
syslog.syslog(syslog.LOG_INFO, "cmd - {}".format(cmd))
try:
subprocess.check_call(cmd)
except subprocess.CalledProcessError as err:
syslog.syslog(syslog.LOG_ERR,
"{} - failed: return code - {}, output:\n{}"
.format(err.cmd, err.returncode, err.output))
def modify_single_file_inplace(filename, operations=None):
if operations:
cmd = ["sed", '-i'] + operations + [filename]
syslog.syslog(syslog.LOG_DEBUG, "modify_single_file_inplace: cmd - {}".format(cmd))
subprocess.run(cmd)
class PasswHardening(object):
def __init__(self):
self.passw_policies_default = {}
self.passw_policies = {}
self.debug = False
self.trace = False
def load(self, policies_conf):
for row in policies_conf:
self.passw_policies_update(row, policies_conf[row], modify_conf=False)
self.modify_passw_conf_file()
def passw_policies_update(self, key, data, modify_conf=True):
syslog.syslog(syslog.LOG_DEBUG, "passw_policies_update - key: {}".format(key))
syslog.syslog(syslog.LOG_DEBUG, "passw_policies_update - data: {}".format(data))
if data == {}:
self.passw_policies = {}
else:
if 'reject_user_passw_match' in data:
data['reject_user_passw_match'] = is_true(data['reject_user_passw_match'])
if 'lower_class' in data:
data['lower_class'] = is_true(data['lower_class'])
if 'upper_class' in data:
data['upper_class'] = is_true(data['upper_class'])
if 'digits_class' in data:
data['digits_class'] = is_true(data['digits_class'])
if 'special_class' in data:
data['special_class'] = is_true(data['special_class'])
if key == 'POLICIES':
self.passw_policies = data
if modify_conf:
self.modify_passw_conf_file()
def set_passw_hardening_policies(self, passw_policies):
# Password Hardening flow
# When feature is enabled, the passw_policies from CONFIG_DB will be set in the pam files /etc/pam.d/common-password and /etc/login.def.
# When the feature is disabled, the files above will be generate with the linux default (without secured passw_policies).
syslog.syslog(syslog.LOG_DEBUG, "modify_conf_file: passw_policies - {}".format(passw_policies))
template_passwh_file = os.path.abspath(PAM_PASSWORD_CONF_TEMPLATE)
env = jinja2.Environment(loader=jinja2.FileSystemLoader('/'), trim_blocks=True)
env.filters['sub'] = sub
template_passwh = env.get_template(template_passwh_file)
# Render common-password file with passw hardening policies if any. Other render without them.
pam_passwh_conf = template_passwh.render(debug=self.debug, passw_policies=passw_policies)
# Use rename(), which is atomic (on the same fs) to avoid empty file
with open(PAM_PASSWORD_CONF + ".tmp", 'w') as f:
f.write(pam_passwh_conf)
os.chmod(PAM_PASSWORD_CONF + ".tmp", 0o644)
os.rename(PAM_PASSWORD_CONF + ".tmp", PAM_PASSWORD_CONF)
# Age policy
# When feature disabled or age policy disabled, expiry days policy should be as linux default, other, accoriding CONFIG_DB.
curr_expiration = LINUX_DEFAULT_PASS_MAX_DAYS
curr_expiration_warning = LINUX_DEFAULT_PASS_WARN_AGE
if passw_policies:
if 'state' in passw_policies:
if passw_policies['state'] == 'enabled':
if 'expiration' in passw_policies:
if int(self.passw_policies['expiration']) != 0: # value '0' meaning age policy is disabled
# the logic is to modify the expiration time according the last updated modificatiion
#
curr_expiration = int(passw_policies['expiration'])
if 'expiration_warning' in passw_policies:
if int(self.passw_policies['expiration_warning']) != 0: # value '0' meaning age policy is disabled
curr_expiration_warning = int(passw_policies['expiration_warning'])
if self.is_passwd_aging_expire_update(curr_expiration, 'MAX_DAYS'):
# Set aging policy for existing users
self.passwd_aging_expire_modify(curr_expiration, 'MAX_DAYS')
# Aging policy for new users
modify_single_file_inplace(ETC_LOGIN_DEF, ["/^PASS_MAX_DAYS/c\PASS_MAX_DAYS " +str(curr_expiration)])
if self.is_passwd_aging_expire_update(curr_expiration_warning, 'WARN_DAYS'):
# Aging policy for existing users
self.passwd_aging_expire_modify(curr_expiration_warning, 'WARN_DAYS')
# Aging policy for new users
modify_single_file_inplace(ETC_LOGIN_DEF, ["/^PASS_WARN_AGE/c\PASS_WARN_AGE " +str(curr_expiration_warning)])
def passwd_aging_expire_modify(self, curr_expiration, age_type):
normal_accounts = self.get_normal_accounts()
if not normal_accounts:
syslog.syslog(syslog.LOG_ERR,"failed, no normal users found in /etc/passwd")
return
chage_flag = AGE_DICT[age_type]['CHAGE_FLAG']
for normal_account in normal_accounts:
try:
chage_p_m = subprocess.Popen(('chage', chage_flag + str(curr_expiration), normal_account), stdout=subprocess.PIPE)
return_code_chage_p_m = chage_p_m.poll()
if return_code_chage_p_m != 0:
syslog.syslog(syslog.LOG_ERR, "failed: return code - {}".format(return_code_chage_p_m))
except subprocess.CalledProcessError as e:
syslog.syslog(syslog.LOG_ERR, "{} - failed: return code - {}, output:\n{}".format(e.cmd, e.returncode, e.output))
def is_passwd_aging_expire_update(self, curr_expiration, age_type):
""" Function verify that the current age expiry policy values are equal from the old one
Return update_age_status 'True' value meaning that was a modification from the last time, and vice versa.
"""
update_age_status = False
days_num = None
regex_days = AGE_DICT[age_type]['REGEX_DAYS']
days_type = AGE_DICT[age_type]['DAYS']
if os.path.exists(ETC_LOGIN_DEF):
with open(ETC_LOGIN_DEF, 'r') as f:
login_def_data = f.readlines()
for line in login_def_data:
m1 = re.match(regex_days, line)
if m1:
days_num = int(m1.group(days_type))
break
if curr_expiration != days_num:
update_age_status = True
return update_age_status
def get_normal_accounts(self):
# Get user list
try:
getent_out = subprocess.check_output(['getent', 'passwd']).decode('utf-8').split('\n')
except subprocess.CalledProcessError as err:
syslog.syslog(syslog.LOG_ERR, "{} - failed: return code - {}, output:\n{}".format(err.cmd, err.returncode, err.output))
return False
# Get range of normal users
REGEX_UID_MAX = r'^UID_MAX[ \t]*(?P<uid_max>\d*)'
REGEX_UID_MIN = r'^UID_MIN[ \t]*(?P<uid_min>\d*)'
uid_max = None
uid_min = None
if os.path.exists(ETC_LOGIN_DEF):
with open(ETC_LOGIN_DEF, 'r') as f:
login_def_data = f.readlines()
for line in login_def_data:
m1 = re.match(REGEX_UID_MAX, line)
m2 = re.match(REGEX_UID_MIN, line)
if m1:
uid_max = int(m1.group("uid_max"))
if m2:
uid_min = int(m2.group("uid_min"))
if not uid_max or not uid_min:
syslog.syslog(syslog.LOG_ERR,"failed, no UID_MAX/UID_MIN founded in login.def file")
return False
# Get normal user list
normal_accounts = []
for account in getent_out[0:-1]: # last item is always empty
account_spl = account.split(':')
account_number = int(account_spl[2])
if account_number >= uid_min and account_number <= uid_max:
normal_accounts.append(account_spl[ACCOUNT_NAME])
normal_accounts.append('root') # root is also a candidate to be age modify.
return normal_accounts
def modify_passw_conf_file(self):
passw_policies = self.passw_policies_default.copy()
passw_policies.update(self.passw_policies)
# set new Password Hardening policies.
self.set_passw_hardening_policies(passw_policies)
class SshServer(object):
def __init__(self):
self.policies = {}
def load(self, policies_conf):
if 'POLICIES' in policies_conf:
self.policies_update('POLICIES', policies_conf['POLICIES'], modify_conf=False)
else:
self.policies = {}
self.modify_conf_file()
def modify_conf_file(self):
ssh_policies = {}
ssh_policies.update(self.policies)
# set new SSH server policies.
if len(ssh_policies) > 0:
self.set_policies(ssh_policies)
def policies_update(self, key, data, modify_conf=True):
syslog.syslog(syslog.LOG_DEBUG, "ssh_policies_update - key: {}".format(key))
syslog.syslog(syslog.LOG_DEBUG, "ssh_policies_update - data: {}".format(data))
if data:
if 'ports' in data:
data['ports'] = data['ports'].split(',')
self.policies = data
if modify_conf:
self.modify_conf_file()
# return first line apperience of pattern - else return number of lines in the file
def get_line_num_of_pattern(self, pattern, file_path, find_commented=False):
syslog.syslog(syslog.LOG_DEBUG, "looking for pattern {} line in file {}".format(pattern, file_path))
return_value = 0
with open(file_path, 'r') as f:
for (i, line) in enumerate(f):
if re.match(pattern, line):
syslog.syslog(syslog.LOG_DEBUG, "found pattern {} in line {}".format(pattern, str(i)))
return i + 1
if find_commented and re.match('#' + pattern, line):
syslog.syslog(syslog.LOG_DEBUG, "found pattern {} in line {}".format('#' + pattern, str(i)))
return i + 1
return_value = i
return return_value
def handle_ports_set(self, values_list):
if len(values_list) == 0:
return False
key='ports'
for port_num in values_list:
if isinstance(port_num, int):
syslog.syslog(syslog.LOG_ERR, "port num value {} in wrong format".format(port_num))
return False
if int(port_num) < SSH_MIN_VALUES[key] or SSH_MAX_VALUES[key] < int(port_num):
syslog.syslog(syslog.LOG_ERR, "Ssh {} {} out of range".format('port', port_num))
return False
port_line_num = self.get_line_num_of_pattern("Port", SSH_CONFG_TMP, True)
modify_single_file_inplace(SSH_CONFG_TMP, ['-E', "/^(#)?Port [0-9]+$/d"])
for port_num in values_list:
# add port in original line
modify_single_file_inplace(SSH_CONFG_TMP, [f'{str(port_line_num)} i Port {str(port_num)}'])
return True
def set_policies(self, ssh_policies):
# Ssh server flow
# The ssh_policies from CONFIG_DB will be set in the ssh config files /etc/ssh/sshd_config
copy2(SSH_CONFG, SSH_CONFG_TMP)
for key, value in ssh_policies.items():
if key == 'ports':
if not self.handle_ports_set(value):
syslog.syslog(syslog.LOG_ERR, "Failed to update sshd config files - wrong port configuration")
return
elif int(value) < SSH_MIN_VALUES.get(key, 65535) or SSH_MAX_VALUES.get(key, -1) < int(value):
syslog.syslog(syslog.LOG_ERR, "Ssh {} {} out of range".format(key, value))
elif key in SSH_CONFIG_NAMES:
# search replace configuration - if not in config file - append
kv_str = "{} {}".format(SSH_CONFIG_NAMES[key], str(value)) # name +' '+ value format
modify_single_file_inplace(SSH_CONFG_TMP,['-E', "/^#?" + SSH_CONFIG_NAMES[key]+"/{h;s/.*/"+
kv_str + "/};${x;/^$/{s//" + kv_str + "/;H};x}"])
else:
syslog.syslog(syslog.LOG_ERR, "Failed to update sshd config file - wrong key {}".format(key))
ssh_verify_res = subprocess.run(['sudo', 'sshd', '-T', '-f', SSH_CONFG_TMP], capture_output=True)
if ssh_verify_res.returncode == 0:
os.rename(SSH_CONFG_TMP, SSH_CONFG)
try:
run_cmd(['systemctl', 'restart', 'ssh'],
log_err=True, raise_exception=True)
except Exception:
syslog.syslog(syslog.LOG_ERR, f'Failed to update sshd config file')
else:
syslog.syslog(syslog.LOG_ERR, f'Failed to update sshd config file - sshd -T returned {ssh_verify_res.returncode} with error {ssh_verify_res.stderr.decode()}')
os.remove(SSH_CONFG_TMP)
class KdumpCfg(object):
def __init__(self, CfgDb):
self.config_db = CfgDb
self.kdump_defaults = { "enabled" : "false",
"memory": "0M-2G:256M,2G-4G:320M,4G-8G:384M,8G-:448M",
"num_dumps": "3" }
def load(self, kdump_table):
"""
Set the KDUMP table in CFG DB to kdump_defaults if not set by the user
"""
syslog.syslog(syslog.LOG_INFO, "KdumpCfg init ...")
kdump_conf = kdump_table.get("config", {})
for row in self.kdump_defaults:
value = self.kdump_defaults.get(row)
if not kdump_conf.get(row):
self.config_db.mod_entry("KDUMP", "config", {row : value})
def kdump_update(self, key, data):
syslog.syslog(syslog.LOG_INFO, "Kdump global configuration update")
if key == "config":
# Admin mode
kdump_enabled = self.kdump_defaults["enabled"]
if data.get("enabled") is not None:
kdump_enabled = data.get("enabled")
if kdump_enabled.lower() == "true":
enabled = True
else:
enabled = False
if enabled:
run_cmd(["sonic-kdump-config", "--enable"])
else:
run_cmd(["sonic-kdump-config", "--disable"])
# Memory configuration
memory = self.kdump_defaults["memory"]
if data.get("memory") is not None:
memory = data.get("memory")
run_cmd(["sonic-kdump-config", "--memory", memory])
# Num dumps
num_dumps = self.kdump_defaults["num_dumps"]
if data.get("num_dumps") is not None:
num_dumps = data.get("num_dumps")
run_cmd(["sonic-kdump-config", "--num_dumps", num_dumps])
class NtpCfg(object):
"""
NtpCfg Config Daemon
1) ntp-config.service handles the configuration updates and then starts ntp.service
2) Both of them start after all the feature services start
3) Purpose of this daemon is to propagate runtime config changes in
NTP, NTP_SERVER, NTP_KEY, and LOOPBACK_INTERFACE
"""
NTP_CONF_RESTART = ['systemctl', 'restart', 'ntp-config']
def __init__(self):
self.cache = {}
def load(self, ntp_global_conf: dict, ntp_server_conf: dict,
ntp_key_conf: dict):
"""Load initial NTP configuration
Force load cache on init. NTP config should be taken at boot-time by
ntp and ntp-config services. So loading whole config here.
Args:
ntp_global_conf: Global configuration