Repository navigation
Expand file tree
/
Copy pathsystemUserManager.py
More file actions
1143 lines (947 loc) · 39 KB
/
Copy pathsystemUserManager.py
File metadata and controls
1143 lines (947 loc) · 39 KB
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
from .lng.default import *
from .helper import loadLng
loadLng()
import os, pwd, grp, subprocess
import subprocess
from libs.JBLibs.input import get_username, get_pwd_confirm, confirm, anyKey, get_input
from libs.JBLibs.helper import userExists,getLogger,getUserList
from libs.JBLibs.term import cls
from typing import Union,List
log = getLogger(__name__)
class sshMng:
# kam ukládat per-user ssh policy
SSHD_D_DIR = "/etc/ssh/sshd_config.d"
SSHD_USER_PREFIX = "90-jb-user-"
# kam ukládat per-user sudo policy
SUDOERS_D_DIR = "/etc/sudoers.d"
SUDO_USER_PREFIX = "90-jb-user-"
@staticmethod
def getUserHome(username:str)->str|None:
"""Získá domovský adresář uživatele.
Args:
username (str): uživatelské jméno
Returns:
str|None: cesta k domovskému adresáři nebo None pokud uživatel neexistuje
"""
try:
pw = pwd.getpwnam(username)
except KeyError:
return None
return pw.pw_dir
@staticmethod
def getUserShell(username:str)->str|None:
"""Return the configured login shell for a system user."""
try:
return pwd.getpwnam(username).pw_shell or None
except KeyError:
return None
@staticmethod
def userUsesBash(username:str)->bool:
"""True when the user's configured login shell is Bash."""
shell = sshMng.getUserShell(username)
return bool(shell) and os.path.basename(shell) == "bash"
@staticmethod
def setUserShell(username:str, shell:str="/bin/bash")->Union[str, None]:
"""Set a system user's login shell. Returns an error string on failure."""
if not userExists(username):
return f"System user does not exist: {username}"
if not isinstance(shell, str) or not os.path.isabs(shell) or not os.path.isfile(shell):
return f"Invalid login shell: {shell}"
try:
subprocess.run(['usermod', '-s', shell, username], check=True)
except (OSError, subprocess.CalledProcessError) as e:
log.error(f"Error changing login shell for user {username} to {shell}: {e}", exc_info=True)
return f"Error changing login shell for user {username}: {e}"
return None
@staticmethod
def getFilePath_auth(username, check:bool=False) -> Union[str, None]:
"""
Vrací cestu k souboru authorized_keys pro zadaného uživatele
Parameters:
username (str): jméno uživatele
check (bool): pokud True, tak vrací cestu pouze pokud soubor existuje
Returns:
str: cesta k souboru authorized_keys
None: pokud soubor neexistuje
"""
x = os.path.join(sshMng.getUserHome(username), ".ssh", "authorized_keys")
return x if not check or os.path.isfile(x) else None
@staticmethod
def getDirPath_ssh(username, check:bool=False) -> Union[str, None]:
"""
Vrací cestu k adresáři .ssh pro zadaného uživatele
Parameters:
username (str): jméno uživatele
check (bool): pokud True, tak vrací cestu pouze pokud adresář existuje
Returns:
str: cesta k adresáři .ssh
None: pokud adresář neexistuje
"""
x= os.path.join(sshMng.getUserHome(username), ".ssh")
return x if not check or os.path.isdir(x) else None
@staticmethod
def getDirPath_sshManager(username, check:bool=False) -> Union[str, None]:
"""
Vrací cestu k adresáři sshManager pro zadaného uživatele
Parameters:
username (str): jméno uživatele
check (bool): pokud True, tak vrací cestu pouze pokud adresář existuje
Returns:
str: cesta k adresáři sshManager
None: pokud adresář neexistuje
"""
x= os.path.join(sshMng.getDirPath_ssh(username), "sshManager")
return x if not check or os.path.isdir(x) else None
@staticmethod
def createSysUser():
"""
Create a new system user.
"""
username = get_username(f"{TXT_SSH_MNG_001}: ",True)
if not username:
return TXT_ABORTED
username = username.strip()
if userExists(username):
print(TXT_SSH_MNG_002.format(name=username))
anyKey()
return TXT_ABORTED
pwd = get_pwd_confirm(f"{TXT_SSH_MNG_005}: ")
if not pwd:
return TXT_ABORTED
try:
# Vytváření systémového uživatele
log.debug(TXT_SSH_MNG_003.format(name=username))
subprocess.run(['useradd', '-m', '-s', '/bin/bash', username], check=True)
subprocess.run(['chpasswd'], input=f"{username}:{pwd}", text=True, check=True)
# Nastavení SSH adresáře
sshMng.repairSshFile(username)
print(TXT_SSH_MNG_004.format(name=username))
except subprocess.CalledProcessError as e:
log.error(f"Error creating user {username}: {e}", exc_info=True)
return f"{TXT_ERROR_OCCURRED}: {e}"
print(TXT_SSH_MNG_006)
anyKey()
@staticmethod
def repairSshFile(username) -> bool:
"""
Funkce opraví adresář .ssh a soubor authorized_keys pro zadaného uživatele.
1. Pokud neexistuje adresář .ssh, vytvoří ho
2. Pokud neexistuje soubor authorized_keys, vytvoří ho
3. Pokud neexistuje adresář sshManager, vytvoří ho
4. Nastaví vlastníka a práva na adresář .ssh a soubor authorized_keys
"""
ssh_dir = sshMng.getDirPath_ssh(username)
ssh_manager_dir = sshMng.getDirPath_sshManager(username)
authorized_keys = sshMng.getFilePath_auth(username)
try:
# Vytvoření adresáře .ssh, sshManager a souboru authorized_keys pokud neexistují
os.makedirs(ssh_dir, mode=0o700, exist_ok=True)
os.makedirs(ssh_manager_dir, mode=0o700, exist_ok=True)
if not sshMng.getFilePath_auth(username,True):
open(authorized_keys, 'a').close()
# Nastavení vlastníka a práv
subprocess.run(['chown', '-R', f"{username}:{username}", ssh_dir], check=True)
subprocess.run(['chmod', '700', ssh_dir], check=True)
subprocess.run(['chmod', '700', ssh_manager_dir], check=True)
subprocess.run(['chmod', '600', authorized_keys], check=True)
except Exception as e:
log.error(f"{TXT_SSH_MNG_007} {username}: {e}", exc_info=True)
raise
@staticmethod
def certExists(username:str,certName:str) -> bool:
"""
Kontroluje, zda certifikáty pro uživatele již existují v sshManager adresáři
Parameters:
username (str): jméno uživatele
certName (str): název certifikátu, tj jméno souboru bez přípony
Returns:
bool: True pokud certifikáty existují
"""
ssh_manager_dir = sshMng.getDirPath_sshManager(username,True)
if not ssh_manager_dir:
return False
private_key = os.path.join(ssh_manager_dir, certName)
public_key = f"{private_key}.pub"
return os.path.isfile(private_key) and os.path.isfile(public_key)
@staticmethod
def createCert(username:str)->Union[str, None]:
"""
Vytvoří pár SSH klíčů pro uživatele a uloží je do adresáře sshManager
Parameters:
username (str): jméno uživatele
Returns:
str: chyba, pokud došlo k chybě
None: pokud OK
"""
if not (ssh_manager_dir:=sshMng.getDirPath_sshManager(username,True)):
log.error(f"SSH Manager directory for user {username} does not exist.")
return TXT_SSH_MNG_008
cert_name = get_input(f"{TXT_SSH_MNG_010}: ").strip()
cert_name += "_key"
private_key = os.path.join(ssh_manager_dir, f"{cert_name}")
public_key = f"{private_key}.pub"
if sshMng.certExists(username, cert_name):
log.error(f"Certificate for user {username} already exists.")
return TXT_SSH_MNG_009.format(key=cert_name)
pwd=None
if confirm(TXT_SSH_MNG_011):
pwd = get_pwd_confirm(f"{TXT_SSH_MNG_005}: ")
if not pwd:
return TXT_ABORTED
try:
# Vytvoření SSH klíče pomocí ssh-keygen
cmd = [
'ssh-keygen', '-t', 'rsa', '-b', '2048', '-f', private_key
]
if pwd:
cmd += ['-N', pwd]
else:
cmd += ['-N', '']
subprocess.run(cmd, check=True)
# Nastavení vlastníka a práv
subprocess.run(['chown', f"{username}:{username}", private_key, public_key], check=True)
subprocess.run(['chmod', '600', private_key], check=True)
subprocess.run(['chmod', '644', public_key], check=True)
print(TXT_SSH_MNG_012.format(name=username, cert=cert_name))
anyKey()
except subprocess.CalledProcessError as e:
log.error(f"Error creating SSH key for user {username}: {e}", exc_info=True)
raise
return None
@staticmethod
def deleCert(userName:str, certName:str)->Union[str, None]:
"""Smazání certifikátu z sshManager adresáře uživatele
Parameters:
userName (str): jméno uživatele
certName (str): název certifikátu, tj jméno souboru bez přípony
Returns:
str: chyba, pokud došlo k chybě
None: pokud OK
"""
if not (ssh_manager_dir:=sshMng.getDirPath_sshManager(userName,True)):
log.error(f"SSH Manager directory for user {userName} does not exist.")
return TXT_SSH_MNG_014
if confirm(TXT_SSH_MNG_013.format(name=userName, cert=certName)):
if (e:=sshMng.delKey(userName, certName, False, True)):
return e
private_key = os.path.join(ssh_manager_dir, f"{certName}")
public_key = f"{private_key}.pub"
if not os.path.isfile(private_key):
print(TXT_SSH_MNG_015.format(key=private_key))
if not os.path.isfile(public_key):
print(TXT_SSH_MNG_016.format(key=public_key))
try:
if os.path.isfile(private_key):
os.remove(private_key)
if os.path.isfile(public_key):
os.remove(public_key)
print(TXT_SSH_MNG_017.format(name=userName, cert=certName))
anyKey()
except Exception as e:
log.error(f"Error deleting certificate for user {userName}: {e}", exc_info=True)
return TXT_SSH_MNG_018
return None
@staticmethod
def _validate_ssh_private_key(key_text: str) -> tuple[bool, bool]:
"""
Validuje SSH privátní klíč.
Returns:
(is_valid, is_encrypted)
"""
import tempfile, subprocess, os
path = None
try:
with tempfile.NamedTemporaryFile("w", delete=False) as f:
f.write(key_text)
path = f.name
os.chmod(path, 0o600)
subprocess.run(
["ssh-keygen", "-yf", path],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
# ssh-keygen -y prošlo => validní a NEencrypted
return True, False
except subprocess.CalledProcessError:
# ssh-keygen selhalo:
# - buď encrypted
# - nebo neplatný formát
#
# Rozlišení řešíme níž
return True, True
except Exception:
# sem padne cokoliv jiného (IO, FS, práva…)
return False, False
finally:
if path and os.path.isfile(path):
try:
os.remove(path)
except Exception:
pass
@staticmethod
def _validate_ssh_public_key(key_text: str) -> bool:
"""
Validuje SSH veřejný klíč.
Parameters:
key_text (str): text klíče
Returns:
bool: True pokud je klíč platný
"""
import tempfile, subprocess, os
key_text = key_text.strip()
if not key_text.startswith(("ssh-", "ecdsa-")):
return False
path = None
try:
with tempfile.NamedTemporaryFile("w", delete=False) as f:
f.write(key_text + "\n")
path = f.name
subprocess.run(
["ssh-keygen", "-lf", path],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
return True
except Exception:
return False
finally:
if path and os.path.isfile(path):
try:
os.remove(path)
except Exception:
pass
@staticmethod
def import_certificate(username:str)-> Union[str, None]:
"""
Importuje SSH klíč do sshManager adresáře uživatele
- zažádá o vložení jména klíče: a-Z 0-9 _ -
- otestuje název existenece klíče
- Zavolá input password pro vložení dat klíče
- zkontroluje jeho validitu, že se jedná o platný SSH klíč - veřejný !
- uloží do sshManager adresáře, kde musí vytvořit dummy private key any nám pak fungovalo mazání přes managera
Parameters:
username (str): jméno uživatele
Returns:
str: chyba, pokud došlo k chybě
None: pokud OK
"""
print(TXT_KEY_IMPORT_HEADER_TXT)
keyname = get_input(
f"{TXT_INP_PUB_KEY_KEYNAME}: ",
accept_empty=False,
rgx= lambda x: r"^[a-zA-Z0-9_-]+$".match(x),
errTx=TXT_INP_PUB_KEY_KEYNAME_ERR
)
if not keyname:
return TXT_ABORTED
if sshMng.certExists(username, keyname):
log.error(f"Certificate for user {username} already exists.")
return TXT_SSH_MNG_009.format(key=keyname)
print(TXT_INP_PUB_KEY_STREAM)
key_data = get_input(
f"{TXT_INP_PUB_KEY_STREAM_INLINE_TXT}:\n",
accept_empty=False,
rgx= lambda x: sshMng._validate_ssh_public_key(x),
errTx=TXT_INP_PUB_KEY_STREAM_FORMAT_ERR
)
if not key_data:
return TXT_ABORTED
if not (ssh_manager_dir:=sshMng.getDirPath_sshManager(username,True)):
log.error(f"SSH Manager directory for user {username} does not exist.")
return TXT_SSH_MNG_008
private_key_path = os.path.join(ssh_manager_dir, f"{keyname}")
public_key_path = f"{private_key_path}.pub"
try:
# Vytvoření dummy private key
with open(private_key_path, 'w') as f:
f.write("DUMMY PRIVATE KEY - IMPORTED PUBLIC KEY ONLY\n")
os.chmod(private_key_path, 0o600)
# Uložení veřejného klíče
with open(public_key_path, 'w') as f:
f.write(key_data.strip() + '\n')
os.chmod(public_key_path, 0o644)
subprocess.run(['chown', f"{username}:{username}", private_key_path, public_key_path], check=True)
print(TXT_INP_PUB_KEY_SUCC_IMPORT.format(name=username, cert=keyname))
anyKey()
except Exception as e:
log.error(f"Error importing SSH key for user {username}: {e}", exc_info=True)
return f"{TXT_ERROR_OCCURRED}: {e}"
return None
@staticmethod
def checkKeyIncluded(username, fileName) -> bool:
"""
Kontroluje, zda klíč s daným názvem je přítomen v authorized_keys souboru
Parameters:
username (str): jméno uživatele
fileName (str): název klíče, tzn jméno souboru bez přípony
Returns:
bool: True pokud klíč existuje v authorized_keys
"""
if not (authorized_keys := sshMng.getFilePath_auth(username, True)):
return False
# read public key do var for comparison
if not (pub := sshMng.getDirPath_sshManager(username,True)):
return False
pub = os.path.join(pub, f"{fileName}.pub")
if not os.path.isfile(pub):
return False
pub = open(pub, 'r').read().strip()
with open(authorized_keys, 'r') as f:
keys = f.readlines()
keys = [key.strip() for key in keys]
for key in keys:
if pub == key:
return True
return False
@staticmethod
def addKey(username, fileName) -> Union[str, None]:
"""
Přidá klíč do authorized_keys, pokud tam ještě není
Parameters:
username (str): jméno uživatele
fileName (str): název klíče
Returns:
str: chyba, pokud došlo k chybě
None: pokud OK
"""
if sshMng.checkKeyIncluded(username, fileName):
return TXT_SSH_MNG_019
if not (ssh_manager_dir := sshMng.getDirPath_sshManager(username, True)):
return TXT_SSH_MNG_020
public_key_path = os.path.join(ssh_manager_dir, f"{fileName}.pub")
if not os.path.isfile(public_key_path):
return TXT_SSH_MNG_021.format(key_path=public_key_path)
with open(public_key_path, 'r') as key_file:
public_key = key_file.read().strip()
authorized_keys = f"/home/{username}/.ssh/authorized_keys"
with open(authorized_keys, 'a') as f:
f.write(public_key + '\n')
print(TXT_SSH_MNG_022.format(key=fileName, name=username))
anyKey()
return None
@staticmethod
def delKey(username:str, fileName:str, any_key:bool=True,ignoreKeyNotIncluded=False) -> Union[str, None]:
"""
Smaže klíč z authorized_keys, pokud je přítomen
Parameters:
username (str): jméno uživatele
fileName (str): název klíče
any_key (bool): pokud True, zobrazí se zpráva pro stisknutí klávesy
Returns:
str: chyba, pokud došlo k chybě
None: pokud OK
"""
# read public key do var for comparison
if not (pub := sshMng.getDirPath_sshManager(username,True)):
return TXT_SSH_MNG_023
if not (authorized_keys := sshMng.getFilePath_auth(username)):
return TXT_SSH_MNG_024.format(name=username)
pub = os.path.join(pub, f"{fileName}.pub")
if not os.path.isfile(pub):
return TXT_SSH_MNG_025.format(pub=pub)
pub = open(pub, 'r').read().strip()
with open(authorized_keys, 'r') as f:
keys = f.readlines()
keys = [key.strip() for key in keys]
l=len(keys)
keys = [k for k in keys if k != pub ]
key_found = len(keys) != l
keys = "\n".join(keys)
with open(authorized_keys, 'w') as f:
f.write(keys)
if key_found:
print(TXT_SSH_MNG_026.format(key=fileName, name=username))
if any_key:
anyKey()
return None
else:
if ignoreKeyNotIncluded:
return None
return TXT_SSH_MNG_027.format(key=fileName, name=username)
@staticmethod
def getKeyList(username) -> Union['listKeyRow', None]:
"""
Vypíše klíče z authorized_keys
Parameters:
username (str): jméno uživatele
Returns:
str: obsah authorized_keys
None: pokud neexistuje
"""
if not (d := sshMng.getDirPath_sshManager(username,True)):
return None
lst = os.listdir(d)
# Vytvoření seznamu klíčů
keys = []
for f in lst:
if f.endswith('.pub'):
keys.append(listKeyRow(f[:-4], username))
return keys
@staticmethod
def showKey(username:str, fileName:str, clear:bool=True)->Union[str, None]:
"""
Vypíše obsah klíče, public key, tento je na serveru pro ověření
Parameters:
username (str): jméno uživatele
fileName (str): název klíče
"""
cls()
if not (d := sshMng.getDirPath_sshManager(username)):
return TXT_SSH_MNG_028.format(name=username)
public_key_path = os.path.join(d, f"{fileName}.pub")
if not os.path.isfile(public_key_path):
return TXT_SSH_MNG_029.format(key_path=public_key_path)
with open(public_key_path, 'r') as f:
print(f.read())
anyKey()
return None
@staticmethod
def showCert(username:str, fileName:str, clear:bool=True)->Union[str, None]:
"""
Vypíše obsah certifikátu, tento je potřebný pro klienta který se bude připojovat
Parameters:
username (str): jméno uživatele
fileName (str): název klíče
"""
cls()
if not (d := sshMng.getDirPath_sshManager(username)):
return TXT_SSH_MNG_030.format(name=username)
private_key_path = os.path.join(d, f"{fileName}")
if not os.path.isfile(private_key_path):
return TXT_SSH_MNG_031.format(key_path=private_key_path)
with open(private_key_path, 'r') as f:
print(f.read())
anyKey()
return None
@staticmethod
def changeSystemUserPwd(username: str) -> Union[str, None]:
"""
Změní heslo systémového uživatele
Parameters:
username (str): jméno uživatele
Returns:
str: chyba, pokud došlo k chybě
None: pokud OK
"""
# Získání nového hesla od uživatele
pwd = get_pwd_confirm(f"{TXT_SSH_MNG_032}: ")
if not pwd:
return TXT_ABORTED
try:
# Použití chpasswd pro změnu hesla uživatele
subprocess.run(['chpasswd'], input=f"{username}:{pwd}", text=True, check=True)
print( TXT_SSH_MNG_033.format(name=username))
except subprocess.CalledProcessError as e:
log.error(
TXT_SSH_MNG_034.format(name=username, e=e),
exc_info=True
)
return TXT_ERROR_OCCURRED
anyKey()
return None
@staticmethod
def add_sudo_privileges(username)->Union[str, None]:
"""Přidá uživateli sudo práva
Parameters:
username (str): jméno uživatele
Returns:
str: chyba, pokud došlo k chybě
None: pokud OK
"""
x=sshMng.is_sudoer(username)
if isinstance(x,str):
return x
elif x:
return None
try:
subprocess.run(['usermod', '-aG', 'sudo', username], check=True)
return None
except subprocess.CalledProcessError as e:
log.error(f"Error adding user {username} to sudo group: {e}", exc_info=True)
return TXT_ERROR_OCCURRED
def remove_sudo_privileges(username:str)->Union[str, None]:
"""Odebere uživateli sudo práva
Parameters:
username (str): jméno uživatele
Returns:
str: chyba, pokud došlo k chybě
None: pokud OK
"""
x=sshMng.is_sudoer(username)
if isinstance(x,str):
return x
elif not x:
return None
try:
subprocess.run(['sudo', 'deluser', username, 'sudo'], check=True)
return None
except subprocess.CalledProcessError as e:
log.error(f"Chyba při odebírání uživatele ze skupiny sudo: {e}", exc_info=True)
return TXT_ERROR_OCCURRED
@staticmethod
def _run(cmd:list[str]) -> tuple[int,str,str]:
"""Spustí příkaz a vrátí návratový kód, stdout a stderr.
Args:
cmd (list[str]): příkaz a jeho argumenty jako seznam
Returns:
tuple[int,str,str]: (returncode, stdout, stderr)
"""
p = subprocess.run(cmd, capture_output=True, text=True)
return p.returncode, p.stdout or "", p.stderr or ""
# ---------- SUDO state ----------
@staticmethod
def is_sudoer(username: str) -> bool:
"""True, pokud uživatel patří do sudo (sekundárně nebo primárně).
Args:
username (str): uživatelské jméno
Returns:
bool: True pokud je uživatel sudoer, jinak False
"""
try:
# primární group
primary_gid = pwd.getpwnam(username).pw_gid
primary_group = grp.getgrgid(primary_gid).gr_name
if primary_group == "sudo":
return True
# sekundární group membership
sudo_gr = grp.getgrnam("sudo")
return username in sudo_gr.gr_mem
except KeyError:
# user nebo group neexistuje
return False
@staticmethod
def _sudo_nopasswd_path(username: str) -> str:
"""Cesta k sudoers.d souboru pro NOPASSWD pravidlo uživatele.
Args:
username (str): uživatelské jméno
Returns:
str: cesta k souboru
"""
return os.path.join(sshMng.SUDOERS_D_DIR, f"{sshMng.SUDO_USER_PREFIX}{username}-nopasswd")
@staticmethod
def has_sudo_nopasswd(username: str) -> bool:
"""True, pokud má uživatel NOPASSWD pravidlo v sudoers.d.
Args:
username (str): uživatelské jméno
Returns:
bool: True pokud má NOPASSWD pravidlo, jinak False
"""
return os.path.isfile(sshMng._sudo_nopasswd_path(username))
@staticmethod
def enforce_sudo_nopasswd(username: str, enable: bool) -> str|None:
"""
Vytvoří nebo odstraní NOPASSWD pravidlo v sudoers.d pro uživatele.
Args:
username (str): uživatelské jméno
enable (bool): True pro vytvoření NOPASSWD pravidla, False pro odstranění
enable=True -> vytvoří NOPASSWD jen pokud je user sudoer, jinak odstraní
enable=False -> vždy odstraní
Returns:
str|None: chyba, pokud došlo k chybě, jinak None
"""
path = sshMng._sudo_nopasswd_path(username)
def _remove():
if os.path.exists(path):
try:
os.remove(path)
except Exception as e:
return f"{TXT_ERROR_OCCURRED}: {e}"
return None
if not enable:
return _remove()
# enable == True
if not sshMng.is_sudoer(username):
# uklid: nemá být NOPASSWD, když není sudoer
return _remove()
try:
content = f"{username} ALL=(ALL) NOPASSWD: ALL\n"
with open(path, "w", encoding="utf-8") as f:
f.write(content)
subprocess.run(["chown", "root:root", path], check=True)
subprocess.run(["chmod", "0440", path], check=True)
# validace přes visudo
subprocess.run(["visudo", "-cf", path], check=True)
return None
except subprocess.CalledProcessError as e:
# když visudo failne, radši soubor smaž a vrať chybu
try:
if os.path.exists(path):
os.remove(path)
except:
pass
return f"{TXT_ERROR_OCCURRED}: {e}"
except Exception as e:
return f"{TXT_ERROR_OCCURRED}: {e}"
# ---------- SSH password login policy ----------
@staticmethod
def _sshd_user_path(username: str) -> str:
"""Cesta k sshd_config.d souboru pro per-user SSH policy.
Args:
username (str): uživatelské jméno
Returns:
str: cesta k souboru
"""
return os.path.join(sshMng.SSHD_D_DIR, f"{sshMng.SSHD_USER_PREFIX}{username}.conf")
@staticmethod
def is_password_login_disabled(username: str) -> bool:
"""True, pokud má uživatel per-user SSH policy zakazující PasswordAuthentication.
Args:
username (str): uživatelské jméno
Returns:
bool: True pokud má per-user SSH policy, jinak False
"""
return os.path.isfile(sshMng._sshd_user_path(username))
@staticmethod
def _reload_sshd() -> str|None:
"""Reload SSH server služby (ssh / sshd)."""
try:
subprocess.run(
["systemctl", "reload", "ssh"],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
return None
except subprocess.CalledProcessError:
try:
subprocess.run(
["systemctl", "reload", "sshd"],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
return None
except subprocess.CalledProcessError as e:
return f"{TXT_ERROR_OCCURRED}: {e}"
@staticmethod
def set_password_login(username: str, enable: bool, require_totp: bool=True) -> str|None:
"""
Per-user policy přes sshd_config.d.
Args:
username (str): uživatelské jméno
enable (bool): True pro povolení PasswordAuthentication (odstraní per-user soubor),
False pro zakázání PasswordAuthentication
require_totp (bool): pokud True, vynutí publickey + keyboard-interactive
Returns:
str|None: chyba, pokud došlo k chybě, jinak None
"""
path = sshMng._sshd_user_path(username)
if enable:
# smazat per-user override
try:
if os.path.exists(path):
os.remove(path)
# reload sshd
err = sshMng._reload_sshd()
if err:
return err
return None
except Exception as e:
return f"{TXT_ERROR_OCCURRED}: {e}"
# enable == False
# bezpečnost: bez klíčů tohle nedovol (aspoň autorizované klíče existují a nejsou prázdné)
u = sshUser(username)
if u.enabledKeysCount == 0:
return TXT_SSH_MNG_024.format(name=username) # nebo vlastní text: "authorized_keys empty"
try:
os.makedirs(sshMng.SSHD_D_DIR, exist_ok=True)
if require_totp:
methods = "publickey,keyboard-interactive"
kbd = "yes"
else:
methods = "publickey"
kbd = "no"
conf = (
f"Match User {username}\n"
f" PasswordAuthentication no\n"
f" PubkeyAuthentication yes\n"
f" KbdInteractiveAuthentication {kbd}\n"
f" AuthenticationMethods {methods}\n"
)
with open(path, "w", encoding="utf-8") as f:
f.write(conf)
subprocess.run(["chown", "root:root", path], check=True)
subprocess.run(["chmod", "0644", path], check=True)
# validace sshd konfigurace
subprocess.run(["sshd", "-t"], check=True)
# reload sshd
err = sshMng._reload_sshd()
if err:
return err
return None
except subprocess.CalledProcessError as e:
# revert soubor při failu
try:
if os.path.exists(path):
os.remove(path)
except:
pass
return f"{TXT_ERROR_OCCURRED}: {e}"
except Exception as e:
return f"{TXT_ERROR_OCCURRED}: {e}"
class listKeyRow:
userName:str=""
"""Systémový uživatel"""
fileName:str=""
"""jen jméno souboru bez přípony"""
included:bool=False
haveCert:bool=False
def __init__(self, fileName:str, userName:str):
self.fileName=fileName
self.userName=userName
self.check()
def __repr__(self):
return f"{self.fileName} {'inSSH' if self.included else ''} {'+cert' if self.haveCert else ''}"
def showKey(self)->Union[str, None]:
"""zobrazí obsah klíče - public key
Returns:
str: chyba, pokud došlo k chybě
None: pokud OK
"""
return sshMng.showKey(self.userName,self.fileName)
def showCert(self)->Union[str, None]:
"""zobrazí obsah certifikátu - private key pro připojujícího se klienta
"""
return sshMng.showCert(self.userName,self.fileName)
def check(self):
"""aktualizuje properties podle aktuálního stavu
"""
self.included=False
self.haveCert=False
if not sshMng.getFilePath_auth(self.userName):
return
self.included=sshMng.checkKeyIncluded(self.userName,self.fileName)
self.haveCert=sshMng.certExists(self.userName,self.fileName)
def addKey(self)->Union[str, None]:
"""přidá klíč do authorized_keys
Returns:
str: chyba, pokud došlo k chybě
None: pokud OK
"""
return sshMng.addKey(self.userName,self.fileName)
def remKey(self)->Union[str, None]:
"""smaže klíč z authorized_keys
Returns:
str: chyba, pokud došlo k chybě
None: pokud OK
"""
return sshMng.delKey(self.userName,self.fileName)
def delMe(self)->Union[str, None]:
"""smaže klíč a certifikát
Returns:
str: chyba, pokud došlo k chybě
None: pokud OK