-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin_tool_EN.py
More file actions
2577 lines (2282 loc) · 107 KB
/
admin_tool_EN.py
File metadata and controls
2577 lines (2282 loc) · 107 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
#!/usr/bin/env python3
"""
Pro Admin Tool — NTFS & CD/DVD & Users
Advanced NTFS tab inspired by NTFS Permissions Tools
"""
import sys
import os
import ctypes
import winreg
import subprocess
import win32net
import win32netcon
import win32security
import win32api
import ntsecuritycon as con
import ntsecuritycon
from datetime import datetime
from PySide6 import QtWidgets, QtCore, QtGui
# ---------------------------------------------------------------------------
# STYL
# ---------------------------------------------------------------------------
DARK_STYLE = """
QMainWindow { background: #0d1117; color: #e6e6e6; }
QTabWidget::pane { border: 1px solid #21262d; border-radius: 8px; background: #0d1117; }
QTabBar::tab {
background: #161b22; color: #8b949e;
border: 1px solid #21262d; border-bottom: none;
padding: 8px 20px; margin-right: 2px;
border-radius: 6px 6px 0 0; font-weight: bold;
}
QTabBar::tab:selected { background: #1f6feb; color: #ffffff; border-color: #1f6feb; }
QTabBar::tab:hover:!selected { background: #21262d; color: #e6e6e6; }
QGroupBox {
border: 1px solid #21262d; border-radius: 8px;
margin-top: 12px; padding: 10px 8px 8px 8px;
font-weight: bold; color: #58a6ff;
}
QGroupBox::title { subcontrol-origin: margin; left: 10px; }
QLineEdit, QTextEdit, QTreeView, QTableWidget, QComboBox, QListWidget {
background: #161b22; border: 1px solid #21262d;
border-radius: 6px; padding: 5px; color: #e6e6e6;
}
QLineEdit:focus, QComboBox:focus { border-color: #1f6feb; }
QComboBox::drop-down { border: none; }
QComboBox QAbstractItemView {
background: #161b22; selection-background-color: #1f6feb; color: #e6e6e6;
}
QHeaderView::section {
background: #161b22; color: #58a6ff;
border: 1px solid #21262d; padding: 5px; font-weight: bold;
}
QPushButton {
background: #21262d; border: 1px solid #30363d;
border-radius: 6px; padding: 7px 14px;
color: #e6e6e6; font-weight: bold;
}
QPushButton:hover { background: #30363d; border-color: #58a6ff; }
QPushButton:disabled { background: #161b22; color: #484f58; border-color: #21262d; }
QPushButton#btnGreen { background: #238636; border-color: #2ea043; color: #fff; }
QPushButton#btnGreen:hover { background: #2ea043; }
QPushButton#btnRed { background: #8b1a1a; border-color: #b91c1c; color: #fff; }
QPushButton#btnRed:hover { background: #b91c1c; }
QPushButton#btnBlue { background: #1f6feb; border-color: #388bfd; color: #fff; }
QPushButton#btnBlue:hover { background: #388bfd; }
QPushButton#btnOrange { background: #9a6700; border-color: #d29922; color: #fff; }
QPushButton#btnOrange:hover { background: #d29922; }
QPushButton#btnPlus {
background: #238636; border-color: #2ea043; color: #fff;
font-size: 18px; padding: 2px 12px;
border-radius: 6px; min-width: 32px; max-width: 32px;
}
QPushButton#btnPlus:hover { background: #2ea043; }
QCheckBox { color: #c9d1d9; spacing: 6px; }
QCheckBox::indicator {
width: 16px; height: 16px;
border: 1px solid #30363d; border-radius: 3px; background: #161b22;
}
QCheckBox::indicator:checked { background: #1f6feb; border-color: #1f6feb; }
QLabel { color: #c9d1d9; }
QScrollBar:vertical { background: #0d1117; width: 8px; border-radius: 4px; }
QScrollBar::handle:vertical { background: #30363d; border-radius: 4px; min-height: 20px; }
QTableWidget { gridline-color: #21262d; }
QTableWidget::item:selected { background: #1f6feb40; }
QDialog { background: #0d1117; color: #e6e6e6; }
QToolBar { background: #161b22; border-bottom: 1px solid #21262d; spacing: 4px; padding: 4px; }
QToolButton {
background: #21262d; border: 1px solid #30363d;
border-radius: 6px; padding: 6px 10px;
color: #e6e6e6; font-weight: bold; font-size: 11px;
}
QToolButton:hover { background: #30363d; border-color: #58a6ff; }
QToolButton:disabled { background: #161b22; color: #484f58; }
QSplitter::handle { background: #21262d; }
"""
# ---------------------------------------------------------------------------
# HELPER: CHECKBOX WYCENTROWANY
# ---------------------------------------------------------------------------
def centered_cb(checked=False):
cb = QtWidgets.QCheckBox()
cb.setChecked(checked)
w = QtWidgets.QWidget()
lay = QtWidgets.QHBoxLayout(w)
lay.addWidget(cb)
lay.setAlignment(QtCore.Qt.AlignCenter)
lay.setContentsMargins(0, 0, 0, 0)
return w, cb
# ---------------------------------------------------------------------------
# HELPER: ACCESS MASK → HUMAN READABLE TEXT
# ---------------------------------------------------------------------------
def mask_to_str(mask: int) -> str:
if (mask & con.FILE_ALL_ACCESS) == con.FILE_ALL_ACCESS:
return "Full Control"
parts = []
if mask & con.FILE_GENERIC_READ: parts.append("Odczyt")
if mask & con.FILE_GENERIC_WRITE: parts.append("Zapis")
if mask & con.FILE_GENERIC_EXECUTE: parts.append("Wykonanie")
if mask & con.DELETE: parts.append("Usuwanie")
if mask & con.READ_CONTROL: parts.append("Read Permissions")
if mask & con.WRITE_DAC: parts.append("Change Permissions")
if mask & con.WRITE_OWNER: parts.append("Change Owner")
return ", ".join(parts) if parts else f"Spec. (0x{mask:08X})"
# ---------------------------------------------------------------------------
# HELPER: LOCAL USER LIST
# ---------------------------------------------------------------------------
def get_local_users() -> list:
"""Returns list of local accounts and system groups."""
SKIP = {"guest", "wdagutilityaccount", "defaultaccount"}
names = []
try:
users, _, _ = win32net.NetUserEnum(None, 0)
for u in users:
name = u.get("name", "")
if name.lower() not in SKIP:
names.append(name)
except Exception:
pass
system_principals = ["Administratorzy", "Administrators", "SYSTEM",
"Users", "Users", "Wszyscy", "Everyone"]
for p in system_principals:
if p not in names:
names.append(p)
return names
def windows_select_user(parent=None) -> str:
"""Otwiera dialog wyboru lokalnego uzytkownika."""
dlg = UserPickerDialog(title='Select owner', multi=False, parent=parent)
if dlg.exec() == QtWidgets.QDialog.Accepted and dlg.selected_users:
return dlg.selected_users[0].strip()
return ''
# ---------------------------------------------------------------------------
# DIALOG: USER PICKER
# ---------------------------------------------------------------------------
class UserPickerDialog(QtWidgets.QDialog):
"""Dialog with list of local accounts instead of text field."""
def __init__(self, title="Select User", multi=False, parent=None):
super().__init__(parent)
self.setWindowTitle(title)
self.setMinimumSize(420, 480)
self.setStyleSheet(DARK_STYLE)
self.selected_users = []
self._multi = multi
self._build_ui()
self._load_users()
def _build_ui(self):
layout = QtWidgets.QVBoxLayout(self)
layout.setSpacing(8)
layout.addWidget(QtWidgets.QLabel("Konta lokalne i grupy systemowe:"))
self.filter_edit = QtWidgets.QLineEdit()
self.filter_edit.setPlaceholderText("Szukaj...")
self.filter_edit.textChanged.connect(self._filter)
layout.addWidget(self.filter_edit)
self.list_widget = QtWidgets.QListWidget()
if self._multi:
self.list_widget.setSelectionMode(
QtWidgets.QAbstractItemView.ExtendedSelection)
layout.addWidget(self.list_widget, 1)
self.list_widget.doubleClicked.connect(self.accept)
btn_row = QtWidgets.QHBoxLayout()
btn_ok = QtWidgets.QPushButton("✅ Select")
btn_ok.setObjectName("btnBlue")
btn_ok.clicked.connect(self.accept)
btn_cancel = QtWidgets.QPushButton("Cancel")
btn_cancel.clicked.connect(self.reject)
btn_row.addStretch()
btn_row.addWidget(btn_ok)
btn_row.addWidget(btn_cancel)
layout.addLayout(btn_row)
def _load_users(self):
self._all_users = get_local_users()
self.list_widget.clear()
for u in self._all_users:
self.list_widget.addItem(u)
if self.list_widget.count() > 0:
self.list_widget.setCurrentRow(0)
def _filter(self, text):
self.list_widget.clear()
for u in self._all_users:
if text.lower() in u.lower():
self.list_widget.addItem(u)
def accept(self):
self.selected_users = [i.text() for i in self.list_widget.selectedItems()]
super().accept()
# ---------------------------------------------------------------------------
# HELPER: CHANGE OWNER WITH PRIVILEGES
# ---------------------------------------------------------------------------
def enable_privilege(priv_name: str) -> bool:
try:
token = win32security.OpenProcessToken(
win32api.GetCurrentProcess(),
win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY
)
luid = win32security.LookupPrivilegeValue(None, priv_name)
win32security.AdjustTokenPrivileges(
token, False, [(luid, win32security.SE_PRIVILEGE_ENABLED)])
return True
except Exception:
return False
def _get_account_full_name(sid) -> str:
user_name, domain, _ = win32security.LookupAccountSid(None, sid)
return (domain + "\\" + user_name) if domain else user_name
def set_owner_with_privileges(path: str, new_sid) -> None:
# Zmienia wlasciciela przez ctypes - omija ograniczenia pywin32 i PowerShell
import ctypes, ctypes.wintypes as wt
advapi = ctypes.windll.advapi32
kernel = ctypes.windll.kernel32
SE_FILE_OBJECT = 1
OWNER_SECURITY_INFO = 0x00000001
TOKEN_ADJUST_PRIVS = 0x0020
TOKEN_QUERY = 0x0008
SE_PRIVILEGE_ENABLED = 0x00000002
def _enable_priv(name):
hToken = wt.HANDLE()
kernel.OpenProcessToken(
kernel.GetCurrentProcess(),
TOKEN_ADJUST_PRIVS | TOKEN_QUERY,
ctypes.byref(hToken))
luid = wt.LARGE_INTEGER()
advapi.LookupPrivilegeValueW(None, name, ctypes.byref(luid))
class LUID_ATTR(ctypes.Structure):
_fields_ = [("Luid", wt.LARGE_INTEGER), ("Attr", wt.DWORD)]
class TOKEN_P(ctypes.Structure):
_fields_ = [("Count", wt.DWORD), ("Privs", LUID_ATTR * 1)]
tp = TOKEN_P()
tp.Count = 1
tp.Privs[0].Luid = luid
tp.Privs[0].Attr = SE_PRIVILEGE_ENABLED
advapi.AdjustTokenPrivileges(
hToken, False, ctypes.byref(tp), 0, None, None)
kernel.CloseHandle(hToken)
for p in ("SeYeseOwnershipPrivilege", "SeRestorePrivilege", "SeBackupPrivilege"):
_enable_priv(p)
# Konwertuj pywin32 SID na bytes
sid_bytes = bytes(new_sid)
sid_buf = ctypes.create_string_buffer(sid_bytes)
rc = advapi.SetNamedSecurityInfoW(
ctypes.c_wchar_p(path),
SE_FILE_OBJECT,
OWNER_SECURITY_INFO,
sid_buf, # owner
None, # group
None, # dacl
None # sacl
)
if rc == 0:
return # ERROR_SUCCESS
# Fallback: pywin32
try:
enable_privilege("SeYeseOwnershipPrivilege")
enable_privilege("SeRestorePrivilege")
enable_privilege("SeBackupPrivilege")
win32security.SetNamedSecurityInfo(
path, win32security.SE_FILE_OBJECT,
win32security.OWNER_SECURITY_INFORMATION,
new_sid, None, None, None)
return
except Exception as e2:
pass
try:
full_name = _get_account_full_name(new_sid)
except Exception:
full_name = "?"
raise RuntimeError(
"SetNamedSecurityInfo blad " + str(rc) + " dla '" + full_name + "'.")
def secure_home_folder(path: str, user_login: str) -> None:
"""
Sets home folder ACL: access ONLY for owner + SYSTEM.
Removes inheritance, blocks access for Users/Everyone.
"""
enable_privilege("SeYeseOwnershipPrivilege")
enable_privilege("SeRestorePrivilege")
enable_privilege("SeBackupPrivilege")
try:
user_sid, _, _ = win32security.LookupAccountName(None, user_login)
except Exception:
return # Account jeszcze nie istnieje — nie ustawiaj ACL
try:
system_sid = win32security.CreateWellKnownSid(
win32security.WinLocalSystemSid, None)
except Exception:
system_sid, _, _ = win32security.LookupAccountName(None, "SYSTEM")
# New DACL — owner only (full control) + SYSTEM (full control)
new_dacl = win32security.ACL()
new_dacl.AddAccessAllowedAce(
win32security.ACL_REVISION, ntsecuritycon.FILE_ALL_ACCESS, user_sid)
new_dacl.AddAccessAllowedAce(
win32security.ACL_REVISION, ntsecuritycon.FILE_ALL_ACCESS, system_sid)
# Apply without inheritance (PROTECTED_DACL = disable parent inheritance)
win32security.SetNamedSecurityInfo(
path,
win32security.SE_FILE_OBJECT,
win32security.DACL_SECURITY_INFORMATION |
win32security.OWNER_SECURITY_INFORMATION |
win32security.PROTECTED_DACL_SECURITY_INFORMATION,
user_sid, # set owner
None,
new_dacl,
None
)
# ===========================================================================
# DIALOG: ADVANCED SECURITY SETTINGS
# ===========================================================================
class AdvancedSecurityDialog(QtWidgets.QDialog):
"""Okno Advanced Security Settings — wzorowane na oryginale NTFS Permissions Tools."""
APPLY_OPTIONS = [
"This folder only",
"This folder,subfolders and files",
"This folder and subfolders",
"This folder and files",
"Subfolders and files only",
"Subfolders only",
"Files only",
]
def __init__(self, path: str, parent=None):
super().__init__(parent)
self.path = path
self.setWindowTitle("Advanced Security Settings")
self.setMinimumSize(950, 600)
self.setStyleSheet(DARK_STYLE)
self._ace_data = []
self._build_ui()
self._load()
# ─────────────────────────────────────────────────────────────────────────
def _build_ui(self):
lay = QtWidgets.QVBoxLayout(self)
lay.setSpacing(6)
# Header — Object name + Owner in one row
hdr = QtWidgets.QFormLayout()
hdr.setHorizontalSpacing(10)
self.lbl_object = QtWidgets.QLineEdit(self.path)
self.lbl_object.setReadOnly(True)
self.lbl_owner = QtWidgets.QLineEdit("—")
self.lbl_owner.setReadOnly(True)
hdr.addRow("Object name:", self.lbl_object)
hdr.addRow("Current Owner:", self.lbl_owner)
lay.addLayout(hdr)
# ── Tabela ACE: Type | Principal | Allow | Deny | Inherited From | Apply to | Remove ──
self.ace_table = QtWidgets.QTableWidget(0, 7)
self.ace_table.setHorizontalHeaderLabels([
"Type", "Principal", "Allow", "Deny", "Inherited From", "Apply to", ""])
hv = self.ace_table.horizontalHeader()
hv.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
hv.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
hv.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
hv.setSectionResizeMode(4, QtWidgets.QHeaderView.ResizeToContents)
hv.setSectionResizeMode(5, QtWidgets.QHeaderView.ResizeToContents)
hv.setSectionResizeMode(6, QtWidgets.QHeaderView.ResizeToContents)
self.ace_table.verticalHeader().setVisible(False)
self.ace_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
self.ace_table.setAlternatingRowColors(True)
lay.addWidget(self.ace_table, 1)
# ── Add user ───────────────────────────────────────────────────
add_frame = QtWidgets.QGroupBox("Add Permission")
add_lay = QtWidgets.QHBoxLayout(add_frame)
add_lay.addWidget(QtWidgets.QLabel("User:"))
self.add_user_combo = QtWidgets.QComboBox()
self.add_user_combo.setMinimumWidth(180)
self._reload_user_combo()
add_lay.addWidget(self.add_user_combo, 1)
btn_reload_u = QtWidgets.QPushButton("🔄")
btn_reload_u.setFixedWidth(32)
btn_reload_u.setToolTip("Refresh account list")
btn_reload_u.clicked.connect(self._reload_user_combo)
add_lay.addWidget(btn_reload_u)
add_lay.addWidget(QtWidgets.QLabel("Access:"))
self.add_access_combo = QtWidgets.QComboBox()
self.add_access_combo.addItems([
"Full Control",
"Odczyt",
"Odczyt i wykonanie",
"Zapis",
"Odczyt + Zapis",
"Deny — Full Block",
])
add_lay.addWidget(self.add_access_combo)
add_lay.addWidget(QtWidgets.QLabel("Apply to:"))
self.add_apply_combo = QtWidgets.QComboBox()
self.add_apply_combo.addItems(self.APPLY_OPTIONS)
self.add_apply_combo.setCurrentIndex(1)
add_lay.addWidget(self.add_apply_combo)
btn_add = QtWidgets.QPushButton("➕ Add")
btn_add.setObjectName("btnGreen")
btn_add.clicked.connect(self._add_ace_from_combo)
add_lay.addWidget(btn_add)
lay.addWidget(add_frame)
# ── Checkboxy dziedziczenia ───────────────────────────────────────
self.cb_include = QtWidgets.QCheckBox(
"Include inheritable permissions from this object's parent")
self.cb_replace = QtWidgets.QCheckBox(
"Replace all child object permissions with inheritable permissions from this object")
lay.addWidget(self.cb_include)
lay.addWidget(self.cb_replace)
# ── Przyciski dolne ───────────────────────────────────────────────
btn_row = QtWidgets.QHBoxLayout()
self.btn_change_owner = QtWidgets.QPushButton("Change Owner")
self.btn_change_owner.clicked.connect(self._change_owner)
btn_apply = QtWidgets.QPushButton("Apply")
btn_apply.setObjectName("btnGreen")
btn_apply.clicked.connect(self._apply)
btn_apply.setEnabled(False)
self.btn_apply = btn_apply
btn_ok = QtWidgets.QPushButton("OK")
btn_ok.setObjectName("btnBlue")
btn_ok.clicked.connect(self._on_ok)
btn_cancel = QtWidgets.QPushButton("Cancel")
btn_cancel.clicked.connect(self.reject)
# Activate Apply when something changed
self.ace_table.itemChanged.connect(lambda: self.btn_apply.setEnabled(True))
btn_row.addWidget(self.btn_change_owner)
btn_row.addStretch()
btn_row.addWidget(btn_apply)
btn_row.addWidget(btn_ok)
btn_row.addWidget(btn_cancel)
lay.addLayout(btn_row)
# ─────────────────────────────────────────────────────────────────────────
def _load(self):
self.ace_table.setRowCount(0)
self._ace_data = []
self.btn_apply.setEnabled(False)
try:
sd = win32security.GetFileSecurity(
self.path,
win32security.DACL_SECURITY_INFORMATION |
win32security.OWNER_SECURITY_INFORMATION
)
owner_sid = sd.GetSecurityDescriptorOwner()
try:
on, od, _ = win32security.LookupAccountSid(None, owner_sid)
self.lbl_owner.setText(f"{od}\\{on}")
except Exception:
self.lbl_owner.setText(str(owner_sid))
dacl = sd.GetSecurityDescriptorDacl()
if not dacl:
return
for i in range(dacl.GetAceCount()):
ace = dacl.GetAce(i)
header, mask, sid = ace
try:
name, dom, _ = win32security.LookupAccountSid(None, sid)
principal = name
except Exception:
principal = str(sid)
is_deny = header[0] in [
win32security.ACCESS_DENIED_ACE_TYPE,
win32security.ACCESS_DENIED_OBJECT_ACE_TYPE
]
is_inherited = bool(header[1] & win32security.INHERITED_ACE)
# Inheritance source — parent or this object
inherited_from = os.path.dirname(self.path) if is_inherited else ""
self._insert_ace_row(principal, sid, mask, is_deny,
is_inherited, inherited_from)
except Exception as e:
QtWidgets.QMessageBox.warning(self, "Error",
f"Cannot read permissions:\n{e}")
def _insert_ace_row(self, principal: str, sid, mask: int,
is_deny: bool, is_inherited: bool,
inherited_from: str = ""):
row = self.ace_table.rowCount()
self.ace_table.insertRow(row)
# Kol 0: Type (Allow/Deny)
type_str = "Deny" if is_deny else "Allow"
type_item = QtWidgets.QTableWidgetItem(type_str)
type_item.setForeground(
QtGui.QColor("#ff7b72") if is_deny else QtGui.QColor("#7ee787"))
type_item.setTextAlignment(QtCore.Qt.AlignCenter)
type_item.setFlags(type_item.flags() & ~QtCore.Qt.ItemIsEditable)
self.ace_table.setItem(row, 0, type_item)
# Kol 1: Principal
p_item = QtWidgets.QTableWidgetItem(principal)
p_item.setFlags(p_item.flags() & ~QtCore.Qt.ItemIsEditable)
self.ace_table.setItem(row, 1, p_item)
# Kol 2: Allow checkbox
w_allow, cb_allow = centered_cb(not is_deny)
self.ace_table.setCellWidget(row, 2, w_allow)
# Kol 3: Deny checkbox
w_deny, cb_deny = centered_cb(is_deny)
self.ace_table.setCellWidget(row, 3, w_deny)
def _sync_type(is_deny_now, ti=type_item):
ti.setText("Deny" if is_deny_now else "Allow")
ti.setForeground(QtGui.QColor(
"#ff7b72" if is_deny_now else "#7ee787"))
self.btn_apply.setEnabled(True)
cb_allow.toggled.connect(lambda c, d=cb_deny: (d.setChecked(False), _sync_type(False)) if c else None)
cb_deny.toggled.connect( lambda c, a=cb_allow: (a.setChecked(False), _sync_type(True)) if c else None)
# Kol 4: Inherited From
inh_item = QtWidgets.QTableWidgetItem(inherited_from if inherited_from else "—")
inh_item.setForeground(QtGui.QColor("#8b949e" if is_inherited else "#c9d1d9"))
inh_item.setFlags(inh_item.flags() & ~QtCore.Qt.ItemIsEditable)
self.ace_table.setItem(row, 4, inh_item)
# Kol 5: Apply to — combo
apply_combo = QtWidgets.QComboBox()
apply_combo.addItems(self.APPLY_OPTIONS)
apply_combo.setCurrentIndex(1) # "This folder,subfolders and files"
apply_combo.currentIndexChanged.connect(lambda _: self.btn_apply.setEnabled(True))
self.ace_table.setCellWidget(row, 5, apply_combo)
# Kol 6: Remove
btn_del = QtWidgets.QPushButton("✕")
btn_del.setObjectName("btnRed")
btn_del.setFixedWidth(32)
btn_del.clicked.connect(self._delete_ace_row)
self.ace_table.setCellWidget(row, 6, btn_del)
self._ace_data.append({
'sid': sid, 'mask': mask,
'cb_allow': cb_allow, 'cb_deny': cb_deny,
'inherited': is_inherited,
'apply_combo': apply_combo,
})
def _reload_user_combo(self):
current = self.add_user_combo.currentText()
self.add_user_combo.blockSignals(True)
self.add_user_combo.clear()
for u in get_local_users():
self.add_user_combo.addItem(u)
idx = self.add_user_combo.findText(current)
if idx >= 0:
self.add_user_combo.setCurrentIndex(idx)
self.add_user_combo.blockSignals(False)
def _delete_ace_row(self):
sender = self.sender()
for r in range(self.ace_table.rowCount()):
if self.ace_table.cellWidget(r, 6) is sender:
self.ace_table.removeRow(r)
if r < len(self._ace_data):
self._ace_data.pop(r)
self.btn_apply.setEnabled(True)
return
def _add_ace_from_combo(self):
name = self.add_user_combo.currentText().strip()
if not name:
return
access_idx = self.add_access_combo.currentIndex()
is_deny = (access_idx == 5)
mask_map = {
0: ntsecuritycon.FILE_ALL_ACCESS,
1: ntsecuritycon.FILE_GENERIC_READ,
2: ntsecuritycon.FILE_GENERIC_READ | ntsecuritycon.FILE_GENERIC_EXECUTE,
3: ntsecuritycon.FILE_GENERIC_WRITE,
4: ntsecuritycon.FILE_GENERIC_READ | ntsecuritycon.FILE_GENERIC_WRITE,
5: ntsecuritycon.FILE_ALL_ACCESS, # Deny
}
mask = mask_map.get(access_idx, ntsecuritycon.FILE_ALL_ACCESS)
try:
sid, _, _ = win32security.LookupAccountName(None, name)
self._insert_ace_row(name, sid, mask, is_deny, False, "")
self.btn_apply.setEnabled(True)
except Exception as e:
QtWidgets.QMessageBox.warning(
self, "Error", f"Cannot find account \'{name}\':\n{e}")
def _apply(self):
enable_privilege("SeRestorePrivilege")
enable_privilege("SeBackupPrivilege")
try:
new_dacl = win32security.ACL()
for d in self._ace_data:
is_deny = d['cb_deny'].isChecked()
if is_deny:
new_dacl.AddAccessDeniedAce(
win32security.ACL_REVISION, d['mask'], d['sid'])
else:
new_dacl.AddAccessAllowedAce(
win32security.ACL_REVISION, d['mask'], d['sid'])
flags = win32security.DACL_SECURITY_INFORMATION
if self.cb_replace.isChecked():
flags |= win32security.PROTECTED_DACL_SECURITY_INFORMATION
win32security.SetNamedSecurityInfo(
self.path, win32security.SE_FILE_OBJECT,
flags, None, None, new_dacl, None)
self.btn_apply.setEnabled(False)
QtWidgets.QMessageBox.information(self, "OK",
"Permissions have been applied.")
self._load()
except Exception as e:
QtWidgets.QMessageBox.critical(self, "Error",
f"Cannot apply permissions:\n{e}")
def _on_ok(self):
if self.btn_apply.isEnabled():
self._apply()
else:
self.accept()
def _change_owner(self):
name = windows_select_user(self).strip()
if not name:
return
try:
new_sid, _, _ = win32security.LookupAccountName(None, name)
set_owner_with_privileges(self.path, new_sid)
QtWidgets.QMessageBox.information(
self, "OK", f"Owner changed to: {name}")
self._load()
except Exception as e:
QtWidgets.QMessageBox.critical(self, "Error",
f"Cannot change owner:\n{e}")
# ===========================================================================
# DIALOG: OPTIONS — Allow/ReadOnly/Deny with user list and Apply To
# ===========================================================================
class AccessOptionsDialog(QtWidgets.QDialog):
"""Dialog 'Options' wzorowany na NTFS Permissions Tools."""
APPLY_FLAGS = {
"This folder only": 0x00000003, # OI nie, CI nie — tylko ten obiekt
"This folder, subfolders and files": 0x00000013, # OI+CI
"This folder and subfolders": 0x00000012, # CI only
"This folder and files": 0x00000011, # OI only (folder+pliki)
"Subfolders and files only": 0x00000010, # inherit only
"Subfolders only": 0x00000010,
"Files only": 0x00000003,
}
def __init__(self, mode: str, paths: list, parent=None):
super().__init__(parent)
self.mode = mode # "allow" | "readonly" | "deny"
self.paths = paths
self.selected_user = ""
self.apply_to = "This folder, subfolders and files"
titles = {"allow": "Options — Allow Access",
"readonly": "Options — Read Only",
"deny": "Options — Deny Access"}
self.setWindowTitle(titles.get(mode, "Options"))
self.setMinimumWidth(420)
self.setStyleSheet(DARK_STYLE)
self._build_ui()
def _build_ui(self):
lay = QtWidgets.QVBoxLayout(self)
lay.setSpacing(12)
# ── User selection ──────────────────────────────────────────────
name_row = QtWidgets.QHBoxLayout()
name_row.addWidget(QtWidgets.QLabel("Name:"))
self.user_combo = QtWidgets.QComboBox()
self.user_combo.setMinimumWidth(200)
for u in get_local_users():
self.user_combo.addItem(u)
name_row.addWidget(self.user_combo, 1)
btn_reload = QtWidgets.QPushButton("🔄")
btn_reload.setFixedWidth(32)
btn_reload.setToolTip("Refresh list")
btn_reload.clicked.connect(self._reload_users)
name_row.addWidget(btn_reload)
lay.addLayout(name_row)
# ── Apply To ─────────────────────────────────────────────────────
lay.addWidget(QtWidgets.QLabel("Apply To:"))
self.apply_group = QtWidgets.QButtonGroup(self)
apply_options = [
"This folder only",
"This folder, subfolders and files",
"This folder and subfolders",
"This folder and files",
"Subfolders and files only",
"Subfolders only",
"Files only",
]
for i, opt in enumerate(apply_options):
rb = QtWidgets.QRadioButton(opt)
if opt == "This folder, subfolders and files":
rb.setChecked(True)
self.apply_group.addButton(rb, i)
lay.addWidget(rb)
lay.addSpacing(8)
# ── Przyciski ────────────────────────────────────────────────────
btn_row = QtWidgets.QHBoxLayout()
btn_ok = QtWidgets.QPushButton("OK")
btn_ok.setObjectName("btnBlue")
btn_ok.setMinimumWidth(90)
btn_ok.clicked.connect(self._on_ok)
btn_cancel = QtWidgets.QPushButton("Cancel")
btn_cancel.setMinimumWidth(90)
btn_cancel.clicked.connect(self.reject)
btn_row.addStretch()
btn_row.addWidget(btn_ok)
btn_row.addWidget(btn_cancel)
lay.addLayout(btn_row)
def _reload_users(self):
cur = self.user_combo.currentText()
self.user_combo.blockSignals(True)
self.user_combo.clear()
for u in get_local_users():
self.user_combo.addItem(u)
idx = self.user_combo.findText(cur)
if idx >= 0:
self.user_combo.setCurrentIndex(idx)
self.user_combo.blockSignals(False)
def _on_ok(self):
self.selected_user = self.user_combo.currentText().strip()
btn = self.apply_group.checkedButton()
self.apply_to = btn.text() if btn else "This folder, subfolders and files"
self.accept()
# ===========================================================================
# NTFS TAB — main file/folder list
# ===========================================================================
class NtfsTab(QtWidgets.QWidget):
"""NTFS tab with file list, toolbar and columns."""
def __init__(self, log_fn, parent=None):
super().__init__(parent)
self._log = log_fn
self._current_path = ""
self._build_ui()
self._load_drives()
def _build_ui(self):
layout = QtWidgets.QVBoxLayout(self)
layout.setContentsMargins(6, 6, 6, 6)
layout.setSpacing(6)
# ── TOOLBAR ─────────────────────────────────────────────────────────
toolbar = QtWidgets.QHBoxLayout()
toolbar.setSpacing(4)
def make_tool_btn(icon_char, label, color=None):
btn = QtWidgets.QToolButton()
btn.setText(f" {icon_char} {label}")
btn.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly)
if color:
btn.setStyleSheet(
f"QToolButton {{ background: {color}; color: #fff; "
f"border: 1px solid {color}; border-radius: 6px; "
f"padding: 6px 10px; font-weight: bold; font-size: 11px; }}"
f"QToolButton:hover {{ opacity: 0.8; }}"
)
return btn
self.btn_add = make_tool_btn("📂", "Add Files or Folders")
self.btn_allow = make_tool_btn("✅", "Allow Access", "#238636")
self.btn_readonly = make_tool_btn("🔒", "Read Only", "#9a6700")
self.btn_deny = make_tool_btn("🚫", "Deny Access", "#8b1a1a")
self.btn_owner = make_tool_btn("👤", "Change Owner", "#1f6feb")
self.btn_advanced = make_tool_btn("⚙", "Advanced", "#444")
self.btn_add.clicked.connect(self._browse_add)
self.btn_allow.clicked.connect(lambda: self._set_access_quick("allow"))
self.btn_readonly.clicked.connect(lambda: self._set_access_quick("readonly"))
self.btn_deny.clicked.connect(lambda: self._set_access_quick("deny"))
self.btn_owner.clicked.connect(self._change_owner_quick)
self.btn_advanced.clicked.connect(self._open_advanced)
for btn in [self.btn_add, self.btn_allow, self.btn_readonly,
self.btn_deny, self.btn_owner, self.btn_advanced]:
toolbar.addWidget(btn)
toolbar.addStretch()
layout.addLayout(toolbar)
# ── PATH BAR ────────────────────────────────────────────────────────
path_row = QtWidgets.QHBoxLayout()
self.drive_combo = QtWidgets.QComboBox()
self.drive_combo.setFixedWidth(130)
self.drive_combo.currentIndexChanged.connect(self._on_drive_changed)
path_row.addWidget(QtWidgets.QLabel("📁"))
path_row.addWidget(self.drive_combo)
self.path_edit = QtWidgets.QLineEdit()
self.path_edit.setPlaceholderText("Folder path...")
self.path_edit.returnPressed.connect(lambda: self._load_path(self.path_edit.text()))
path_row.addWidget(self.path_edit, 1)
btn_up = QtWidgets.QPushButton("⬆ Up")
btn_up.clicked.connect(self._go_up)
btn_refresh = QtWidgets.QPushButton("🔄")
btn_refresh.setFixedWidth(36)
btn_refresh.clicked.connect(lambda: self._load_path(self._current_path))
path_row.addWidget(btn_up)
path_row.addWidget(btn_refresh)
layout.addLayout(path_row)
# ── FILE/FOLDER TABLE ───────────────────────────────────────────────
self.file_table = QtWidgets.QTableWidget(0, 6)
self.file_table.setHorizontalHeaderLabels([
"Name", "Type", "Date created", "File system",
"Access rights of current user", "Owner"
])
hv = self.file_table.horizontalHeader()
hv.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)
hv.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
hv.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
hv.setSectionResizeMode(4, QtWidgets.QHeaderView.ResizeToContents)
hv.setSectionResizeMode(5, QtWidgets.QHeaderView.Stretch)
self.file_table.verticalHeader().setVisible(False)
self.file_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
self.file_table.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
self.file_table.doubleClicked.connect(self._on_double_click)
self.file_table.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.file_table.customContextMenuRequested.connect(self._context_menu)
layout.addWidget(self.file_table, 1)
# ── PASEK STATUSU ──────────────────────────────────────────────────
status_row = QtWidgets.QHBoxLayout()
self.lbl_status = QtWidgets.QLabel("Selected 0 / Total 0")
self.lbl_status.setStyleSheet("color: #8b949e; font-size: 11px;")
self.file_table.itemSelectionChanged.connect(self._update_status)
status_row.addStretch()
status_row.addWidget(self.lbl_status)
layout.addLayout(status_row)
# ── INICJALIZACJA ─────────────────────────────────────────────────────
def _load_drives(self):
self.drive_combo.blockSignals(True)
self.drive_combo.clear()
try:
drives = win32api.GetLogicalDriveStrings().split('\000')
for d in drives:
d = d.strip()
if not d:
continue
try:
vol = win32api.GetVolumeInformation(d)
label = vol[0] or ""
letter = d.rstrip("\\")
display = f"{label} ({letter})" if label else letter
except Exception:
display = d.rstrip("\\")
self.drive_combo.addItem(display, d)
except Exception:
for ltr in "CDEFGHIJKLMNOPQRSTUVWXYZ":
p = f"{ltr}:\\"
if os.path.exists(p):
self.drive_combo.addItem(p, p)
self.drive_combo.blockSignals(False)
if self.drive_combo.count() > 0:
self._on_drive_changed(0)
def _on_drive_changed(self, idx):
path = self.drive_combo.itemData(idx)
if path:
self._load_path(path)
def _go_up(self):
parent = os.path.dirname(self._current_path.rstrip("\\"))
if parent and parent != self._current_path:
self._load_path(parent)
def _browse_add(self):
path = QtWidgets.QFileDialog.getExistingDirectory(self, "Wybierz folder")
if path:
self._load_path(path.replace("/", "\\"))
# ── LOADING DIRECTORY CONTENTS ───────────────────────────────────────
def _load_path(self, path: str):
if not path:
return
path = path.replace("/", "\\")
if not os.path.exists(path):
self._log(f"Path does not exist: {path}", "#ff7b72")
return
self._current_path = path
self.path_edit.setText(path)
self.file_table.setRowCount(0)
try:
entries = []
# If root drive, add all subfolders and files
for name in os.listdir(path):
full = os.path.join(path, name)
entries.append((name, full))
except PermissionError:
self._log(f"No read permissions: {path}", "#e3b341")
return
except Exception as e:
self._log(f"Error listowania: {e}", "#ff7b72")
return
# Sortuj: foldery najpierw, potem pliki, alfanumerycznie
entries.sort(key=lambda x: (0 if os.path.isdir(x[1]) else 1, x[0].lower()))
for name, full in entries:
self._add_entry_row(name, full)
self._update_status()
self._log(f"Loaded: {path} ({len(entries)} items)")
def _add_entry_row(self, name: str, full_path: str):
"""Adde jeden wiersz do tabeli."""
is_dir = os.path.isdir(full_path)
row = self.file_table.rowCount()
self.file_table.insertRow(row)
# Ikona + Nazwa
icon = "📁" if is_dir else "📄"
name_item = QtWidgets.QTableWidgetItem(f"{icon} {name}")
name_item.setData(QtCore.Qt.UserRole, full_path)