From e5c6a2fc0ee5dd76ca2f68a996d8a73377d24d1d Mon Sep 17 00:00:00 2001 From: scandalist-trash Date: Tue, 27 Oct 2026 10:50:43 -0400 Subject: [PATCH] Add ALD Transition Console preview and Astra lab build workflow --- .gitignore | 13 + CMakeLists.txt | 53 + README.md | 6 + data/checklists/all.ru.json | 363 +++++ data/checklists/hardening.ru.json | 27 + data/checklists/initialization.ru.json | 90 ++ data/checklists/migration.ru.json | 216 +++ data/checklists/policies.ru.json | 48 + data/hardening/astra17-mappings.json | 248 ++++ data/hardening/fstec-linux-2022.catalog.json | 1369 ++++++++++++++++++ data/hardening/windows-baselines.json | 45 + data/sources.json | 259 ++++ docs/access-restoration.md | 28 + docs/astra-lab.ru.md | 113 ++ docs/build-artifacts.json | 19 + docs/compatibility-lock.json | 25 + docs/compatibility-matrix.md | 29 + docs/development-environment.json | 77 + docs/feasibility.md | 66 + docs/gui-scale-results.json | 14 + docs/gui-smoke-results.json | 51 + docs/gui-xcb-result.json | 19 + docs/implementation-status.md | 33 + docs/interface-review.md | 52 + docs/lab-manual.ru.md | 386 +++++ docs/local-check-results.json | 102 ++ docs/native-adapter-contracts.md | 83 ++ docs/next-steps.ru.md | 53 + docs/operator-guide.ru.md | 76 + docs/recovery-guide.ru.md | 40 + docs/requirements.md | 780 ++++++++++ docs/security-review.md | 69 + docs/test-results.md | 76 + packaging/README.md | 24 + packaging/ald-transition-console.desktop | 9 + packaging/debian/changelog | 5 + packaging/debian/control | 17 + packaging/debian/copyright | 11 + packaging/debian/rules | 10 + packaging/debian/source/format | 1 + resources/asset-manifest.json | 105 ++ resources/resources.qrc | 28 + resources/styles/dedsec.qss | 34 + resources/tasks/linux/README.md | 5 + resources/tasks/manifest.json | 53 + resources/tasks/windows/ad-inventory.ps1 | 44 + resources/tasks/windows/discovery.ps1 | 34 + schemas/checklist.schema.json | 201 +++ schemas/host.schema.json | 85 ++ schemas/inventory.schema.json | 225 +++ schemas/offline-bundle.schema.json | 89 ++ schemas/operation.schema.json | 80 + schemas/plan.schema.json | 207 +++ schemas/profile.schema.json | 134 ++ schemas/project.schema.json | 63 + schemas/source.schema.json | 92 ++ schemas/windows-discovery.schema.json | 112 ++ src/adapters/AdInventory.cpp | 24 + src/adapters/AdInventory.h | 3 + src/adapters/Ald31Administration.cpp | 3 + src/adapters/Ald31Administration.h | 3 + src/adapters/Ald31Deployment.cpp | 5 + src/adapters/Ald31Deployment.h | 3 + src/adapters/Ald31Migration.cpp | 2 + src/adapters/Ald31Migration.h | 3 + src/adapters/Ald31Policies.cpp | 3 + src/adapters/Ald31Policies.h | 3 + src/adapters/Astra17Discovery.cpp | 38 + src/adapters/Astra17Discovery.h | 10 + src/adapters/CompatibilityResolver.cpp | 10 + src/adapters/CompatibilityResolver.h | 4 + src/adapters/WindowsDiscovery.cpp | 6 + src/adapters/WindowsDiscovery.h | 3 + src/adapters/WindowsLocalPolicy.cpp | 2 + src/adapters/WindowsLocalPolicy.h | 3 + src/app/AppController.cpp | 184 +++ src/app/AppController.h | 54 + src/app/CapabilityRegistry.cpp | 20 + src/app/CapabilityRegistry.h | 3 + src/core/Rules.cpp | 170 +++ src/core/Rules.h | 62 + src/domain/AccessChange.h | 2 + src/domain/Capability.h | 2 + src/domain/Checklist.h | 2 + src/domain/Host.h | 2 + src/domain/IdentityMapping.h | 2 + src/domain/InventoryObject.h | 2 + src/domain/LogEvent.h | 2 + src/domain/MigrationItem.h | 2 + src/domain/Operation.h | 2 + src/domain/Plan.h | 2 + src/domain/PolicyProfile.h | 2 + src/domain/Project.h | 2 + src/domain/Run.h | 2 + src/domain/Types.h | 75 + src/execution/OperationRegistry.cpp | 45 + src/execution/OperationRegistry.h | 19 + src/execution/PlanExecutor.cpp | 38 + src/execution/PlanExecutor.h | 28 + src/execution/ProcessRunner.cpp | 45 + src/execution/ProcessRunner.h | 29 + src/execution/RunJournal.cpp | 3 + src/execution/RunJournal.h | 10 + src/execution/ShutdownCoordinator.cpp | 5 + src/execution/ShutdownCoordinator.h | 10 + src/main.cpp | 35 + src/privileged/ExecutorMain.cpp | 33 + src/privileged/OperationDispatcher.cpp | 38 + src/privileged/OperationDispatcher.h | 12 + src/security/AccessLedger.cpp | 18 + src/security/AccessLedger.h | 3 + src/security/PrivilegedClient.cpp | 43 + src/security/PrivilegedClient.h | 16 + src/security/SecretRedactor.cpp | 6 + src/security/SecretRedactor.h | 15 + src/storage/DatabaseMigrator.cpp | 26 + src/storage/DatabaseMigrator.h | 3 + src/storage/JsonValidator.cpp | 120 ++ src/storage/JsonValidator.h | 14 + src/storage/OfflineBundle.cpp | 26 + src/storage/OfflineBundle.h | 7 + src/storage/ProjectRepository.cpp | 130 ++ src/storage/ProjectRepository.h | 28 + src/transports/NativeSshTransport.cpp | 25 + src/transports/NativeSshTransport.h | 6 + src/ui/FlowLayout.cpp | 12 + src/ui/FlowLayout.h | 15 + src/ui/MainWindow.cpp | 71 + src/ui/MainWindow.h | 18 + src/ui/PixelDecoration.cpp | 10 + src/ui/PixelDecoration.h | 11 + src/ui/Theme.cpp | 14 + src/ui/Theme.h | 7 + src/ui/models/JsonTableModel.cpp | 41 + src/ui/models/JsonTableModel.h | 14 + src/ui/pages/AccessPage.cpp | 30 + src/ui/pages/AccessPage.h | 6 + src/ui/pages/ChecklistPage.cpp | 32 + src/ui/pages/ChecklistPage.h | 6 + src/ui/pages/DomainSettingsPage.cpp | 7 + src/ui/pages/DomainSettingsPage.h | 6 + src/ui/pages/EnvironmentPage.cpp | 14 + src/ui/pages/EnvironmentPage.h | 6 + src/ui/pages/InitializationPage.cpp | 11 + src/ui/pages/InitializationPage.h | 6 + src/ui/pages/LogsPage.cpp | 8 + src/ui/pages/LogsPage.h | 6 + src/ui/pages/MigrationPage.cpp | 15 + src/ui/pages/MigrationPage.h | 6 + src/ui/pages/OverviewPage.cpp | 13 + src/ui/pages/OverviewPage.h | 6 + src/ui/pages/PoliciesPage.cpp | 20 + src/ui/pages/PoliciesPage.h | 6 + src/ui/pages/RestorationPage.cpp | 14 + src/ui/pages/RestorationPage.h | 6 + src/ui/pages/WorkflowPage.cpp | 27 + src/ui/pages/WorkflowPage.h | 32 + src/workflows/AccessPreparation.cpp | 16 + src/workflows/AccessPreparation.h | 3 + src/workflows/AccessRestoration.cpp | 3 + src/workflows/AccessRestoration.h | 3 + src/workflows/ComplianceEvaluator.cpp | 2 + src/workflows/ComplianceEvaluator.h | 3 + src/workflows/CutoverPlanner.cpp | 2 + src/workflows/CutoverPlanner.h | 3 + src/workflows/HardeningPlanner.cpp | 3 + src/workflows/HardeningPlanner.h | 3 + src/workflows/IdentityMapper.cpp | 16 + src/workflows/IdentityMapper.h | 3 + src/workflows/InitializationPlanner.cpp | 12 + src/workflows/InitializationPlanner.h | 3 + src/workflows/MigrationPlanner.cpp | 22 + src/workflows/MigrationPlanner.h | 3 + src/workflows/PolicyPlanner.cpp | 13 + src/workflows/PolicyPlanner.h | 3 + tests/fixtures/cleanup_conflict.json | 6 + tests/fixtures/demo.inventory.json | 355 +++++ tests/fixtures/duplicate_names.json | 6 + tests/fixtures/incomplete_deployment.json | 6 + tests/fixtures/missing_media.json | 6 + tests/fixtures/offline_host.json | 6 + tests/fixtures/orphan_sid.json | 6 + tests/fixtures/same_name_dns.json | 6 + tests/fixtures/windows2025.json | 6 + tests/integration/README.md | 48 + tests/unit/test_rules.cpp | 82 ++ tests/unit/test_runtime.cpp | 41 + tests/unit/test_storage.cpp | 60 + tests/unit/test_ui.cpp | 49 + tools/build_astra_lab.py | 136 ++ tools/check_assets.py | 46 + tools/check_gui.py | 45 + tools/check_theme.py | 14 + tools/collect_compatibility.py | 16 + tools/make_source_archive.py | 44 + tools/run_portable_tests.py | 14 + tools/update_asset_manifest.py | 17 + tools/validate_local.py | 62 + tools/verify_release_lock.py | 23 + 199 files changed, 9866 insertions(+) create mode 100644 .gitignore create mode 100644 CMakeLists.txt create mode 100644 data/checklists/all.ru.json create mode 100644 data/checklists/hardening.ru.json create mode 100644 data/checklists/initialization.ru.json create mode 100644 data/checklists/migration.ru.json create mode 100644 data/checklists/policies.ru.json create mode 100644 data/hardening/astra17-mappings.json create mode 100644 data/hardening/fstec-linux-2022.catalog.json create mode 100644 data/hardening/windows-baselines.json create mode 100644 data/sources.json create mode 100644 docs/access-restoration.md create mode 100644 docs/astra-lab.ru.md create mode 100644 docs/build-artifacts.json create mode 100644 docs/compatibility-lock.json create mode 100644 docs/compatibility-matrix.md create mode 100644 docs/development-environment.json create mode 100644 docs/feasibility.md create mode 100644 docs/gui-scale-results.json create mode 100644 docs/gui-smoke-results.json create mode 100644 docs/gui-xcb-result.json create mode 100644 docs/implementation-status.md create mode 100644 docs/interface-review.md create mode 100644 docs/lab-manual.ru.md create mode 100644 docs/local-check-results.json create mode 100644 docs/native-adapter-contracts.md create mode 100644 docs/next-steps.ru.md create mode 100644 docs/operator-guide.ru.md create mode 100644 docs/recovery-guide.ru.md create mode 100644 docs/requirements.md create mode 100644 docs/security-review.md create mode 100644 docs/test-results.md create mode 100644 packaging/README.md create mode 100644 packaging/ald-transition-console.desktop create mode 100644 packaging/debian/changelog create mode 100644 packaging/debian/control create mode 100644 packaging/debian/copyright create mode 100644 packaging/debian/rules create mode 100644 packaging/debian/source/format create mode 100644 resources/asset-manifest.json create mode 100644 resources/resources.qrc create mode 100644 resources/styles/dedsec.qss create mode 100644 resources/tasks/linux/README.md create mode 100644 resources/tasks/manifest.json create mode 100644 resources/tasks/windows/ad-inventory.ps1 create mode 100644 resources/tasks/windows/discovery.ps1 create mode 100644 schemas/checklist.schema.json create mode 100644 schemas/host.schema.json create mode 100644 schemas/inventory.schema.json create mode 100644 schemas/offline-bundle.schema.json create mode 100644 schemas/operation.schema.json create mode 100644 schemas/plan.schema.json create mode 100644 schemas/profile.schema.json create mode 100644 schemas/project.schema.json create mode 100644 schemas/source.schema.json create mode 100644 schemas/windows-discovery.schema.json create mode 100644 src/adapters/AdInventory.cpp create mode 100644 src/adapters/AdInventory.h create mode 100644 src/adapters/Ald31Administration.cpp create mode 100644 src/adapters/Ald31Administration.h create mode 100644 src/adapters/Ald31Deployment.cpp create mode 100644 src/adapters/Ald31Deployment.h create mode 100644 src/adapters/Ald31Migration.cpp create mode 100644 src/adapters/Ald31Migration.h create mode 100644 src/adapters/Ald31Policies.cpp create mode 100644 src/adapters/Ald31Policies.h create mode 100644 src/adapters/Astra17Discovery.cpp create mode 100644 src/adapters/Astra17Discovery.h create mode 100644 src/adapters/CompatibilityResolver.cpp create mode 100644 src/adapters/CompatibilityResolver.h create mode 100644 src/adapters/WindowsDiscovery.cpp create mode 100644 src/adapters/WindowsDiscovery.h create mode 100644 src/adapters/WindowsLocalPolicy.cpp create mode 100644 src/adapters/WindowsLocalPolicy.h create mode 100644 src/app/AppController.cpp create mode 100644 src/app/AppController.h create mode 100644 src/app/CapabilityRegistry.cpp create mode 100644 src/app/CapabilityRegistry.h create mode 100644 src/core/Rules.cpp create mode 100644 src/core/Rules.h create mode 100644 src/domain/AccessChange.h create mode 100644 src/domain/Capability.h create mode 100644 src/domain/Checklist.h create mode 100644 src/domain/Host.h create mode 100644 src/domain/IdentityMapping.h create mode 100644 src/domain/InventoryObject.h create mode 100644 src/domain/LogEvent.h create mode 100644 src/domain/MigrationItem.h create mode 100644 src/domain/Operation.h create mode 100644 src/domain/Plan.h create mode 100644 src/domain/PolicyProfile.h create mode 100644 src/domain/Project.h create mode 100644 src/domain/Run.h create mode 100644 src/domain/Types.h create mode 100644 src/execution/OperationRegistry.cpp create mode 100644 src/execution/OperationRegistry.h create mode 100644 src/execution/PlanExecutor.cpp create mode 100644 src/execution/PlanExecutor.h create mode 100644 src/execution/ProcessRunner.cpp create mode 100644 src/execution/ProcessRunner.h create mode 100644 src/execution/RunJournal.cpp create mode 100644 src/execution/RunJournal.h create mode 100644 src/execution/ShutdownCoordinator.cpp create mode 100644 src/execution/ShutdownCoordinator.h create mode 100644 src/main.cpp create mode 100644 src/privileged/ExecutorMain.cpp create mode 100644 src/privileged/OperationDispatcher.cpp create mode 100644 src/privileged/OperationDispatcher.h create mode 100644 src/security/AccessLedger.cpp create mode 100644 src/security/AccessLedger.h create mode 100644 src/security/PrivilegedClient.cpp create mode 100644 src/security/PrivilegedClient.h create mode 100644 src/security/SecretRedactor.cpp create mode 100644 src/security/SecretRedactor.h create mode 100644 src/storage/DatabaseMigrator.cpp create mode 100644 src/storage/DatabaseMigrator.h create mode 100644 src/storage/JsonValidator.cpp create mode 100644 src/storage/JsonValidator.h create mode 100644 src/storage/OfflineBundle.cpp create mode 100644 src/storage/OfflineBundle.h create mode 100644 src/storage/ProjectRepository.cpp create mode 100644 src/storage/ProjectRepository.h create mode 100644 src/transports/NativeSshTransport.cpp create mode 100644 src/transports/NativeSshTransport.h create mode 100644 src/ui/FlowLayout.cpp create mode 100644 src/ui/FlowLayout.h create mode 100644 src/ui/MainWindow.cpp create mode 100644 src/ui/MainWindow.h create mode 100644 src/ui/PixelDecoration.cpp create mode 100644 src/ui/PixelDecoration.h create mode 100644 src/ui/Theme.cpp create mode 100644 src/ui/Theme.h create mode 100644 src/ui/models/JsonTableModel.cpp create mode 100644 src/ui/models/JsonTableModel.h create mode 100644 src/ui/pages/AccessPage.cpp create mode 100644 src/ui/pages/AccessPage.h create mode 100644 src/ui/pages/ChecklistPage.cpp create mode 100644 src/ui/pages/ChecklistPage.h create mode 100644 src/ui/pages/DomainSettingsPage.cpp create mode 100644 src/ui/pages/DomainSettingsPage.h create mode 100644 src/ui/pages/EnvironmentPage.cpp create mode 100644 src/ui/pages/EnvironmentPage.h create mode 100644 src/ui/pages/InitializationPage.cpp create mode 100644 src/ui/pages/InitializationPage.h create mode 100644 src/ui/pages/LogsPage.cpp create mode 100644 src/ui/pages/LogsPage.h create mode 100644 src/ui/pages/MigrationPage.cpp create mode 100644 src/ui/pages/MigrationPage.h create mode 100644 src/ui/pages/OverviewPage.cpp create mode 100644 src/ui/pages/OverviewPage.h create mode 100644 src/ui/pages/PoliciesPage.cpp create mode 100644 src/ui/pages/PoliciesPage.h create mode 100644 src/ui/pages/RestorationPage.cpp create mode 100644 src/ui/pages/RestorationPage.h create mode 100644 src/ui/pages/WorkflowPage.cpp create mode 100644 src/ui/pages/WorkflowPage.h create mode 100644 src/workflows/AccessPreparation.cpp create mode 100644 src/workflows/AccessPreparation.h create mode 100644 src/workflows/AccessRestoration.cpp create mode 100644 src/workflows/AccessRestoration.h create mode 100644 src/workflows/ComplianceEvaluator.cpp create mode 100644 src/workflows/ComplianceEvaluator.h create mode 100644 src/workflows/CutoverPlanner.cpp create mode 100644 src/workflows/CutoverPlanner.h create mode 100644 src/workflows/HardeningPlanner.cpp create mode 100644 src/workflows/HardeningPlanner.h create mode 100644 src/workflows/IdentityMapper.cpp create mode 100644 src/workflows/IdentityMapper.h create mode 100644 src/workflows/InitializationPlanner.cpp create mode 100644 src/workflows/InitializationPlanner.h create mode 100644 src/workflows/MigrationPlanner.cpp create mode 100644 src/workflows/MigrationPlanner.h create mode 100644 src/workflows/PolicyPlanner.cpp create mode 100644 src/workflows/PolicyPlanner.h create mode 100644 tests/fixtures/cleanup_conflict.json create mode 100644 tests/fixtures/demo.inventory.json create mode 100644 tests/fixtures/duplicate_names.json create mode 100644 tests/fixtures/incomplete_deployment.json create mode 100644 tests/fixtures/missing_media.json create mode 100644 tests/fixtures/offline_host.json create mode 100644 tests/fixtures/orphan_sid.json create mode 100644 tests/fixtures/same_name_dns.json create mode 100644 tests/fixtures/windows2025.json create mode 100644 tests/integration/README.md create mode 100644 tests/unit/test_rules.cpp create mode 100644 tests/unit/test_runtime.cpp create mode 100644 tests/unit/test_storage.cpp create mode 100644 tests/unit/test_ui.cpp create mode 100644 tools/build_astra_lab.py create mode 100644 tools/check_assets.py create mode 100644 tools/check_gui.py create mode 100644 tools/check_theme.py create mode 100644 tools/collect_compatibility.py create mode 100644 tools/make_source_archive.py create mode 100644 tools/run_portable_tests.py create mode 100644 tools/update_asset_manifest.py create mode 100644 tools/validate_local.py create mode 100644 tools/verify_release_lock.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4827138 --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +build*/ +*.user +*.sqlite* +*.lock +__pycache__/ +artifacts/ +astra-lab-project/ +astra-project/ +demo-project/ +*.sqlite-journal +*.db +*.db-wal +*.db-shm diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..6709685 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,53 @@ +cmake_minimum_required(VERSION 3.13) +project(ALDTransitionConsole VERSION 0.1.0 LANGUAGES CXX) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) +option(ALD_CORE_ONLY "Build portable decision engine and its tests only" OFF) +include(CTest) +add_library(ald_rules src/core/Rules.cpp) +target_include_directories(ald_rules PUBLIC src) +target_compile_options(ald_rules PRIVATE -Wall -Wextra -Wpedantic) +if(BUILD_TESTING) + add_executable(test_rules tests/unit/test_rules.cpp) + target_link_libraries(test_rules PRIVATE ald_rules) + add_test(NAME rules COMMAND test_rules) +endif() +if(ALD_CORE_ONLY) + return() +endif() +find_package(Qt5 5.15.2 REQUIRED COMPONENTS Core Gui Widgets Network Sql Test) +if(NOT Qt5Core_VERSION VERSION_LESS 5.16) + message(FATAL_ERROR "This project targets the Qt 5.15 API family") +endif() +set(CMAKE_AUTOMOC ON) +set(CMAKE_AUTORCC ON) +file(GLOB_RECURSE ALD_CORE_SOURCES CONFIGURE_DEPENDS src/app/*.cpp src/storage/*.cpp + src/execution/*.cpp src/security/*.cpp src/transports/*.cpp src/adapters/*.cpp src/workflows/*.cpp) +add_library(ald_core ${ALD_CORE_SOURCES} resources/resources.qrc) +target_include_directories(ald_core PUBLIC src) +target_link_libraries(ald_core PUBLIC ald_rules Qt5::Core Qt5::Network Qt5::Sql) +target_compile_definitions(ald_core PUBLIC QT_DISABLE_DEPRECATED_BEFORE=0x050F00) +target_compile_options(ald_core PRIVATE -Wall -Wextra -Wpedantic) +file(GLOB_RECURSE ALD_UI_SOURCES CONFIGURE_DEPENDS src/ui/*.cpp) +add_library(ald_ui ${ALD_UI_SOURCES}) +target_link_libraries(ald_ui PUBLIC ald_core Qt5::Widgets Qt5::Gui) +add_executable(ald-transition-console src/main.cpp) +target_link_libraries(ald-transition-console PRIVATE ald_ui) +add_executable(ald-transition-executor src/privileged/ExecutorMain.cpp src/privileged/OperationDispatcher.cpp) +target_link_libraries(ald-transition-executor PRIVATE Qt5::Core Qt5::Network) +target_include_directories(ald-transition-executor PRIVATE src) +if(BUILD_TESTING) + foreach(name storage runtime ui) + add_executable(test_${name} tests/unit/test_${name}.cpp) + target_link_libraries(test_${name} PRIVATE ald_ui Qt5::Test) + add_test(NAME ${name} COMMAND test_${name}) + set_tests_properties(${name} PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") + endforeach() +endif() +include(GNUInstallDirs) +install(TARGETS ald-transition-console RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) +# No setuid bit, daemon, package hook, or privileged operation enabled at install time. +install(TARGETS ald-transition-executor RUNTIME DESTINATION ${CMAKE_INSTALL_LIBEXECDIR}/ald-transition-console) +install(DIRECTORY docs data schemas resources/tasks DESTINATION ${CMAKE_INSTALL_DATADIR}/ald-transition-console) +install(FILES packaging/ald-transition-console.desktop DESTINATION ${CMAKE_INSTALL_DATADIR}/applications) diff --git a/README.md b/README.md index 4c0eed6..b7bbdc6 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,12 @@ replicates AD DS or preserves SIDs, passwords, Windows profiles or GPO effects. ## Build +For the Astra test machine, follow the [Russian laboratory guide](docs/astra-lab.ru.md). +The one-command handoff is `python3 tools/build_astra_lab.py`: it builds and runs +the four test suites, and saves a report archive even if a build stage fails. +It uses the Python standard library, installs nothing and never authorizes a +domain change or marks the release validated. + Use an approved toolchain with CMake >= 3.13, a C++17 compiler, Qt **5.15.x** (API floor/ceiling used by this source: 5.15.2), Core, Gui, Widgets, Network, Sql, Test, the QSQLITE plugin, and Qt build tools. Russian Qt translations are used diff --git a/data/checklists/all.ru.json b/data/checklists/all.ru.json new file mode 100644 index 0000000..ed1a067 --- /dev/null +++ b/data/checklists/all.ru.json @@ -0,0 +1,363 @@ +{ + "schema_version": 1, + "items": [ + { + "id": "source_baseline", + "phase": "source", + "title_ru": "Проверить исходный AD", + "purpose_ru": "Зафиксировать исходное поведение до любого изменения.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "На единственном исходном КД открыть Server Manager и DNS Manager. Проверить предупреждения AD DS/DNS и ошибки Directory Service/System в Event Viewer.", + "На тестовом клиенте выполнить вход обычным пользователем, открыть разрешённый ресурс; записать build ОС, пользователя, время и результат.", + "Сохранить доступный отчёт штатного dcdiag по процедуре для установленного Windows Server. Неполученные сведения отметить отдельно." + ], + "expected_result_ru": "Вход и штатные службы работают; известные ошибки описаны.", + "failure_guidance_ru": "Не переходить к изменению. Устранить или локализовать исходные отказы; сохранить диагностику.", + "evidence_ids": [] + }, + { + "id": "restore_rehearsal", + "phase": "source", + "title_ru": "Проверить восстановление одного КД", + "purpose_ru": "Наличие файла backup не доказывает восстановимость.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "Уточнить тип AD-aware backup, время, место хранения и версию Windows. Не помещать ключи и пароли в чеклист.", + "По документации этой версии составить isolated restore rehearsal: изоляция сети, ответственный, порядок возврата, критерии DNS/каталога/входа.", + "Выполнить отдельно согласованную репетицию на стенде и записать её результат, RPO/RTO и ссылку на доказательство." + ], + "expected_result_ru": "Поддержанная процедура восстановления воспроизведена на совместимой версии.", + "failure_guidance_ru": "Остановить изменение. Независимые снапшоты VM не считать универсальным восстановлением AD.", + "evidence_ids": [] + }, + { + "id": "baseline", + "phase": "initialization", + "title_ru": "Зафиксировать паспорт ALD и Astra", + "purpose_ru": "Разделить поддержку GUI, КД и операций.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "На Astra сверить /etc/astra/build_version и package metadata с поставкой ALD 3.1.0.", + "Зафиксировать точные ядро, архитектуру, уровень защищённости и версии Qt/компилятора/CMake/QSQLITE/OpenSSH.", + "Сверить ALSE 1.7.7 UU2, 6.1-generic, Смоленск с действующим руководством поставки. Подтвердить допустимость дополнительного GUI на КД." + ], + "expected_result_ru": "Все поля compatibility lock получены из реального стенда.", + "failure_guidance_ru": "Не подставлять версии по примеру; сохранить UNKNOWN и запретить выпуск пакета.", + "evidence_ids": [] + }, + { + "id": "namespace", + "phase": "initialization", + "title_ru": "Согласовать имя corp.local", + "purpose_ru": "Предотвратить конфликт авторитетного DNS в прежней сети.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "Зафиксировать текущие DNS authority, resolver и SRV для corp.local на КД и тестовом клиенте.", + "Получить процедуру именно ALD 3.1.0 для same-name перехода и единственного исходного AD DC.", + "Проверить последовательность в изолированном стенде; показать затрагиваемые службы, время простоя и контрольные точки восстановления." + ], + "expected_result_ru": "Подтверждены имя corp.local, исходная сеть и безопасная последовательность.", + "failure_guidance_ru": "План остаётся BLOCKED. Ручная отметка не заменяет поддержку функции.", + "evidence_ids": [] + }, + { + "id": "initialize", + "phase": "initialization", + "title_ru": "Выполнить штатную инициализацию после допуска", + "purpose_ru": "Запуск допустим только после всех проверок совместимости и namespace.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "Если это существующий, частично установленный или деградировавший КД — не выполнять чистую инициализацию.", + "На совместимом стенде сверить установленный aldpro-server-install --help с руководством поставки. Ввести реальные согласованные hostname/IP/domain в локальном терминале.", + "Использовать интерактивный запрос пароля. Не применять параметр admin_pwd, историю с паролем или запись секретного ввода. Перезагрузку согласовать отдельно." + ], + "expected_result_ru": "Инициализация и последующая проверка каждой службы подтверждены отдельными наблюдениями.", + "failure_guidance_ru": "Не стирать частично созданный домен и не повторять продвижение автоматически. Собрать журнал и использовать процедуру восстановления.", + "evidence_ids": [] + }, + { + "id": "native_services", + "phase": "initialization", + "title_ru": "Проверить службы после инициализации", + "purpose_ru": "Код завершения установщика не является проверкой домена.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "После согласованной перезагрузки открыть локальную административную консоль.", + "Выполнить sudo aldproctl status по ALD31_PROMOTION и проверить каждую ожидаемую роль.", + "Проверить портал, DNS/time и поддержанный путь регистрации пилотного клиента." + ], + "expected_result_ru": "Каждая нужная служба работает, портал и пилотный вход доступны.", + "failure_guidance_ru": "Отметить FAIL/PARTIAL для конкретной службы; не переинициализировать домен.", + "evidence_ids": [] + }, + { + "id": "mapping", + "phase": "migration", + "title_ru": "Проверить GUID/SID-сопоставления", + "purpose_ru": "Не перепутать одинаковые логины и отображаемые имена.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "Открыть исходный GUID, SID и DN объекта, сопоставить с целевым ID/SID/UID/GID.", + "Проверить вложенные группы, отключённые и привилегированные учётные записи.", + "Отдельно перечислить orphan SID, коллизии имён и несопоставленные атрибуты." + ], + "expected_result_ru": "Каждая преобразуемая ссылка ACL имеет проверенную стабильную карту.", + "failure_guidance_ru": "Не переносить ACL по совпадающему логину; блокировать зависимый ресурс.", + "evidence_ids": [] + }, + { + "id": "login", + "phase": "migration", + "title_ru": "Проверить прежний пароль и вход", + "purpose_ru": "Копирование записи пользователя не переносит автоматически пароль.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "Под обычной пилотной учётной записью войти старым паролем через предусмотренный поддержанный путь. Пароль в приложение не вводить.", + "Проверить смену пароля и повторный вход, не провоцируя блокировку серией попыток.", + "Раздельно записать онлайн-вход, требуемый offline logon и привилегированный вход." + ], + "expected_result_ru": "Неизменные обязательные сценарии входа подтверждены по каждому типу учётной записи.", + "failure_guidance_ru": "Сохранить FAIL и блокировать бесшовный переход. Не извлекать секреты из LSASS.", + "evidence_ids": [] + }, + { + "id": "profiles", + "phase": "migration", + "title_ru": "Проверить профиль Windows и зашифрованные данные", + "purpose_ru": "Путь каталога профиля не доказывает доступность DPAPI/EFS.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "До пилота зафиксировать профиль и контрольные пользовательские файлы без копирования секретов.", + "После поддержанного перехода проверить вход в прежний профиль, настройки приложений и необходимые сохранённые учётные данные.", + "Если использовались EFS/DPAPI, проверить открытие подготовленного тестового материала владельцем." + ], + "expected_result_ru": "Прежний профиль, данные и необходимые криптографически защищённые функции доступны.", + "failure_guidance_ru": "Вернуть пилот по проверенной процедуре. Не выдавать смену владельца каталога за миграцию DPAPI/EFS.", + "evidence_ids": [] + }, + { + "id": "acl", + "phase": "migration", + "title_ru": "Проверить разрешения и запреты", + "purpose_ru": "Сохранить фактические полномочия, включая deny.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "Войти обычным пользователем и проверить разрешённое чтение тестовой папки.", + "Попытаться изменить ресурс, где запись должна быть запрещена.", + "Под отдельной разрешённой учётной записью проверить запись; сверить вложенные группы и владельца." + ], + "expected_result_ru": "Разрешённые действия доступны, запрещённые отвергаются с ожидаемым результатом.", + "failure_guidance_ru": "Остановить волну; сверить GUID/SID mapping и исходные allow/deny ACL.", + "evidence_ids": [] + }, + { + "id": "applications", + "phase": "migration", + "title_ru": "Проверить приложения и сервисные учётные записи", + "purpose_ru": "Закрыть зависимости LDAP/Kerberos/NTLM/SPN/сертификатов.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "С владельцем приложения определить протокол входа и сервисную идентичность.", + "Выполнить пользовательский вход и типовую операцию с положительной и отрицательной ролью.", + "Проверить фоновые задания, доверие сертификатам, выдачу и продление там, где они обязательны." + ], + "expected_result_ru": "Приложение выполняет обязательные сценарии без скрытой зависимости от AD.", + "failure_guidance_ru": "Назначить владельца нерешённой зависимости, оставить AD retirement заблокированным.", + "evidence_ids": [] + }, + { + "id": "dns_time", + "phase": "migration", + "title_ru": "Проверить DNS и время", + "purpose_ru": "Ошибки разрешения/времени нарушают доменную аутентификацию.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "На КД и пилоте запросить прямую/обратную запись и используемые служебные SRV штатной утилитой nslookup.", + "Сверить фактические DNS-серверы, authority и доступность согласованного источника времени.", + "Повторить типовой вход после проверки; не выполнять policy refresh как часть read-only аудита." + ], + "expected_result_ru": "Согласованные ответы DNS и синхронизация времени доступны на всех проверяемых узлах.", + "failure_guidance_ru": "Вернуть resolver/authority только по плану; не запускать конфликтующие DNS-службы.", + "evidence_ids": [] + }, + { + "id": "policy_outcomes", + "phase": "policies", + "title_ru": "Проверить результат каждой политики", + "purpose_ru": "Назначение не доказывает эффективное применение.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "Сохранить исходный GPO report и scope: links/order/inheritance/filter/scripts/preferences.", + "Для каждого параметра записать владельца и per-build смысловую карту.", + "Отдельно подтвердить получение, включение в результирующую конфигурацию, применение, эффективное значение и поведение пользователя." + ], + "expected_result_ru": "Все обязательные эффекты подтверждены; несопоставленные параметры видимы.", + "failure_guidance_ru": "Не применять один параметр двумя конкурирующими владельцами; отметить пробелы.", + "evidence_ids": [] + }, + { + "id": "reboot", + "phase": "policies", + "title_ru": "Проверить поведение после перезагрузки", + "purpose_ru": "Разделить работающее и сохранённое состояние.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "По отдельному разрешению перезагрузить только пилотный узел.", + "Повторить вход, DNS/time, разрешения, приложения и ключевые политики.", + "Записать build, время и ссылку на предыдущее наблюдение." + ], + "expected_result_ru": "Ожидаемые настройки сохраняются и штатные службы работают.", + "failure_guidance_ru": "Не повторять изменение автоматически; проверить persistent state и журнал запуска.", + "evidence_ids": [] + }, + { + "id": "ad_unavailable", + "phase": "migration", + "title_ru": "Проверить работу при недоступном исходном AD", + "purpose_ru": "Доказать независимость перед планом вывода AD.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "Согласовать конкретную обратимую изоляцию исходного AD, доступ через консоль и критерии немедленного восстановления.", + "В разрешённом окне выполнить вход пилота, DNS, файлы, приложения, выдачу билетов и политику без AD.", + "Восстановить исходное сетевое состояние по процедуре и зафиксировать результат обоих этапов." + ], + "expected_result_ru": "Нет обязательных обращений к исходному AD; восстановление подтверждено.", + "failure_guidance_ru": "При любом отказе восстановить источник и оставить вывод AD заблокированным.", + "evidence_ids": [] + }, + { + "id": "cleanup", + "phase": "cleanup", + "title_ru": "Восстановить временный доступ", + "purpose_ru": "Не оставить временные права и не отключить чужой доступ.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "Открыть журнал каждого AccessChange. Сравнить текущее состояние с applied_state.", + "При совпадении выполнить только согласованный штатный обратный шаг, сохранить проверку; при расхождении отметить конфликт.", + "Сначала ключи/членства/правила, последний канал — в конце. Сохранить ручные инструкции до закрытия. Недоступный узел остаётся PENDING." + ], + "expected_result_ru": "Все собственные временные изменения восстановлены или явно перечислены как не закрытые.", + "failure_guidance_ru": "Не отмечать очистку успешной без доказательства. Использовать локальную консоль при отсутствии канала.", + "evidence_ids": [] + }, + { + "id": "hardening", + "phase": "hardening", + "title_ru": "Проверить применимость рекомендаций защиты", + "purpose_ru": "Технический чеклист не означает сертификацию.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "Сверить пункт 1.3 исходного документа и эксплуатационную документацию выбранной Astra.", + "Проверить роль узла, владельца настройки, побочные эффекты, версию ядра и обратимость.", + "Сравнить текущее и persistent-next-boot состояния; для ptrace_scope=3 предусмотреть восстановление через перезагрузку по испытанной процедуре." + ], + "expected_result_ru": "Есть версия карты Astra, обоснование роли и отдельные доказательства runtime/persistent состояния.", + "failure_guidance_ru": "UNKNOWN не заменять на NOT APPLICABLE. Автоизменение без проверенной карты недоступно.", + "evidence_ids": [] + } + ], + "observations": [] +} diff --git a/data/checklists/hardening.ru.json b/data/checklists/hardening.ru.json new file mode 100644 index 0000000..bbf02b6 --- /dev/null +++ b/data/checklists/hardening.ru.json @@ -0,0 +1,27 @@ +{ + "schema_version": 1, + "items": [ + { + "id": "hardening", + "phase": "hardening", + "title_ru": "Проверить применимость рекомендаций защиты", + "purpose_ru": "Технический чеклист не означает сертификацию.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "Сверить пункт 1.3 исходного документа и эксплуатационную документацию выбранной Astra.", + "Проверить роль узла, владельца настройки, побочные эффекты, версию ядра и обратимость.", + "Сравнить текущее и persistent-next-boot состояния; для ptrace_scope=3 предусмотреть восстановление через перезагрузку по испытанной процедуре." + ], + "expected_result_ru": "Есть версия карты Astra, обоснование роли и отдельные доказательства runtime/persistent состояния.", + "failure_guidance_ru": "UNKNOWN не заменять на NOT APPLICABLE. Автоизменение без проверенной карты недоступно.", + "evidence_ids": [] + } + ], + "observations": [] +} diff --git a/data/checklists/initialization.ru.json b/data/checklists/initialization.ru.json new file mode 100644 index 0000000..2799906 --- /dev/null +++ b/data/checklists/initialization.ru.json @@ -0,0 +1,90 @@ +{ + "schema_version": 1, + "items": [ + { + "id": "baseline", + "phase": "initialization", + "title_ru": "Зафиксировать паспорт ALD и Astra", + "purpose_ru": "Разделить поддержку GUI, КД и операций.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "На Astra сверить /etc/astra/build_version и package metadata с поставкой ALD 3.1.0.", + "Зафиксировать точные ядро, архитектуру, уровень защищённости и версии Qt/компилятора/CMake/QSQLITE/OpenSSH.", + "Сверить ALSE 1.7.7 UU2, 6.1-generic, Смоленск с действующим руководством поставки. Подтвердить допустимость дополнительного GUI на КД." + ], + "expected_result_ru": "Все поля compatibility lock получены из реального стенда.", + "failure_guidance_ru": "Не подставлять версии по примеру; сохранить UNKNOWN и запретить выпуск пакета.", + "evidence_ids": [] + }, + { + "id": "namespace", + "phase": "initialization", + "title_ru": "Согласовать имя corp.local", + "purpose_ru": "Предотвратить конфликт авторитетного DNS в прежней сети.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "Зафиксировать текущие DNS authority, resolver и SRV для corp.local на КД и тестовом клиенте.", + "Получить процедуру именно ALD 3.1.0 для same-name перехода и единственного исходного AD DC.", + "Проверить последовательность в изолированном стенде; показать затрагиваемые службы, время простоя и контрольные точки восстановления." + ], + "expected_result_ru": "Подтверждены имя corp.local, исходная сеть и безопасная последовательность.", + "failure_guidance_ru": "План остаётся BLOCKED. Ручная отметка не заменяет поддержку функции.", + "evidence_ids": [] + }, + { + "id": "initialize", + "phase": "initialization", + "title_ru": "Выполнить штатную инициализацию после допуска", + "purpose_ru": "Запуск допустим только после всех проверок совместимости и namespace.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "Если это существующий, частично установленный или деградировавший КД — не выполнять чистую инициализацию.", + "На совместимом стенде сверить установленный aldpro-server-install --help с руководством поставки. Ввести реальные согласованные hostname/IP/domain в локальном терминале.", + "Использовать интерактивный запрос пароля. Не применять параметр admin_pwd, историю с паролем или запись секретного ввода. Перезагрузку согласовать отдельно." + ], + "expected_result_ru": "Инициализация и последующая проверка каждой службы подтверждены отдельными наблюдениями.", + "failure_guidance_ru": "Не стирать частично созданный домен и не повторять продвижение автоматически. Собрать журнал и использовать процедуру восстановления.", + "evidence_ids": [] + }, + { + "id": "native_services", + "phase": "initialization", + "title_ru": "Проверить службы после инициализации", + "purpose_ru": "Код завершения установщика не является проверкой домена.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "После согласованной перезагрузки открыть локальную административную консоль.", + "Выполнить sudo aldproctl status по ALD31_PROMOTION и проверить каждую ожидаемую роль.", + "Проверить портал, DNS/time и поддержанный путь регистрации пилотного клиента." + ], + "expected_result_ru": "Каждая нужная служба работает, портал и пилотный вход доступны.", + "failure_guidance_ru": "Отметить FAIL/PARTIAL для конкретной службы; не переинициализировать домен.", + "evidence_ids": [] + } + ], + "observations": [] +} diff --git a/data/checklists/migration.ru.json b/data/checklists/migration.ru.json new file mode 100644 index 0000000..6aac760 --- /dev/null +++ b/data/checklists/migration.ru.json @@ -0,0 +1,216 @@ +{ + "schema_version": 1, + "items": [ + { + "id": "source_baseline", + "phase": "source", + "title_ru": "Проверить исходный AD", + "purpose_ru": "Зафиксировать исходное поведение до любого изменения.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "На единственном исходном КД открыть Server Manager и DNS Manager. Проверить предупреждения AD DS/DNS и ошибки Directory Service/System в Event Viewer.", + "На тестовом клиенте выполнить вход обычным пользователем, открыть разрешённый ресурс; записать build ОС, пользователя, время и результат.", + "Сохранить доступный отчёт штатного dcdiag по процедуре для установленного Windows Server. Неполученные сведения отметить отдельно." + ], + "expected_result_ru": "Вход и штатные службы работают; известные ошибки описаны.", + "failure_guidance_ru": "Не переходить к изменению. Устранить или локализовать исходные отказы; сохранить диагностику.", + "evidence_ids": [] + }, + { + "id": "restore_rehearsal", + "phase": "source", + "title_ru": "Проверить восстановление одного КД", + "purpose_ru": "Наличие файла backup не доказывает восстановимость.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "Уточнить тип AD-aware backup, время, место хранения и версию Windows. Не помещать ключи и пароли в чеклист.", + "По документации этой версии составить isolated restore rehearsal: изоляция сети, ответственный, порядок возврата, критерии DNS/каталога/входа.", + "Выполнить отдельно согласованную репетицию на стенде и записать её результат, RPO/RTO и ссылку на доказательство." + ], + "expected_result_ru": "Поддержанная процедура восстановления воспроизведена на совместимой версии.", + "failure_guidance_ru": "Остановить изменение. Независимые снапшоты VM не считать универсальным восстановлением AD.", + "evidence_ids": [] + }, + { + "id": "mapping", + "phase": "migration", + "title_ru": "Проверить GUID/SID-сопоставления", + "purpose_ru": "Не перепутать одинаковые логины и отображаемые имена.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "Открыть исходный GUID, SID и DN объекта, сопоставить с целевым ID/SID/UID/GID.", + "Проверить вложенные группы, отключённые и привилегированные учётные записи.", + "Отдельно перечислить orphan SID, коллизии имён и несопоставленные атрибуты." + ], + "expected_result_ru": "Каждая преобразуемая ссылка ACL имеет проверенную стабильную карту.", + "failure_guidance_ru": "Не переносить ACL по совпадающему логину; блокировать зависимый ресурс.", + "evidence_ids": [] + }, + { + "id": "login", + "phase": "migration", + "title_ru": "Проверить прежний пароль и вход", + "purpose_ru": "Копирование записи пользователя не переносит автоматически пароль.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "Под обычной пилотной учётной записью войти старым паролем через предусмотренный поддержанный путь. Пароль в приложение не вводить.", + "Проверить смену пароля и повторный вход, не провоцируя блокировку серией попыток.", + "Раздельно записать онлайн-вход, требуемый offline logon и привилегированный вход." + ], + "expected_result_ru": "Неизменные обязательные сценарии входа подтверждены по каждому типу учётной записи.", + "failure_guidance_ru": "Сохранить FAIL и блокировать бесшовный переход. Не извлекать секреты из LSASS.", + "evidence_ids": [] + }, + { + "id": "profiles", + "phase": "migration", + "title_ru": "Проверить профиль Windows и зашифрованные данные", + "purpose_ru": "Путь каталога профиля не доказывает доступность DPAPI/EFS.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "До пилота зафиксировать профиль и контрольные пользовательские файлы без копирования секретов.", + "После поддержанного перехода проверить вход в прежний профиль, настройки приложений и необходимые сохранённые учётные данные.", + "Если использовались EFS/DPAPI, проверить открытие подготовленного тестового материала владельцем." + ], + "expected_result_ru": "Прежний профиль, данные и необходимые криптографически защищённые функции доступны.", + "failure_guidance_ru": "Вернуть пилот по проверенной процедуре. Не выдавать смену владельца каталога за миграцию DPAPI/EFS.", + "evidence_ids": [] + }, + { + "id": "acl", + "phase": "migration", + "title_ru": "Проверить разрешения и запреты", + "purpose_ru": "Сохранить фактические полномочия, включая deny.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "Войти обычным пользователем и проверить разрешённое чтение тестовой папки.", + "Попытаться изменить ресурс, где запись должна быть запрещена.", + "Под отдельной разрешённой учётной записью проверить запись; сверить вложенные группы и владельца." + ], + "expected_result_ru": "Разрешённые действия доступны, запрещённые отвергаются с ожидаемым результатом.", + "failure_guidance_ru": "Остановить волну; сверить GUID/SID mapping и исходные allow/deny ACL.", + "evidence_ids": [] + }, + { + "id": "applications", + "phase": "migration", + "title_ru": "Проверить приложения и сервисные учётные записи", + "purpose_ru": "Закрыть зависимости LDAP/Kerberos/NTLM/SPN/сертификатов.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "С владельцем приложения определить протокол входа и сервисную идентичность.", + "Выполнить пользовательский вход и типовую операцию с положительной и отрицательной ролью.", + "Проверить фоновые задания, доверие сертификатам, выдачу и продление там, где они обязательны." + ], + "expected_result_ru": "Приложение выполняет обязательные сценарии без скрытой зависимости от AD.", + "failure_guidance_ru": "Назначить владельца нерешённой зависимости, оставить AD retirement заблокированным.", + "evidence_ids": [] + }, + { + "id": "dns_time", + "phase": "migration", + "title_ru": "Проверить DNS и время", + "purpose_ru": "Ошибки разрешения/времени нарушают доменную аутентификацию.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "На КД и пилоте запросить прямую/обратную запись и используемые служебные SRV штатной утилитой nslookup.", + "Сверить фактические DNS-серверы, authority и доступность согласованного источника времени.", + "Повторить типовой вход после проверки; не выполнять policy refresh как часть read-only аудита." + ], + "expected_result_ru": "Согласованные ответы DNS и синхронизация времени доступны на всех проверяемых узлах.", + "failure_guidance_ru": "Вернуть resolver/authority только по плану; не запускать конфликтующие DNS-службы.", + "evidence_ids": [] + }, + { + "id": "ad_unavailable", + "phase": "migration", + "title_ru": "Проверить работу при недоступном исходном AD", + "purpose_ru": "Доказать независимость перед планом вывода AD.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "Согласовать конкретную обратимую изоляцию исходного AD, доступ через консоль и критерии немедленного восстановления.", + "В разрешённом окне выполнить вход пилота, DNS, файлы, приложения, выдачу билетов и политику без AD.", + "Восстановить исходное сетевое состояние по процедуре и зафиксировать результат обоих этапов." + ], + "expected_result_ru": "Нет обязательных обращений к исходному AD; восстановление подтверждено.", + "failure_guidance_ru": "При любом отказе восстановить источник и оставить вывод AD заблокированным.", + "evidence_ids": [] + }, + { + "id": "cleanup", + "phase": "cleanup", + "title_ru": "Восстановить временный доступ", + "purpose_ru": "Не оставить временные права и не отключить чужой доступ.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "Открыть журнал каждого AccessChange. Сравнить текущее состояние с applied_state.", + "При совпадении выполнить только согласованный штатный обратный шаг, сохранить проверку; при расхождении отметить конфликт.", + "Сначала ключи/членства/правила, последний канал — в конце. Сохранить ручные инструкции до закрытия. Недоступный узел остаётся PENDING." + ], + "expected_result_ru": "Все собственные временные изменения восстановлены или явно перечислены как не закрытые.", + "failure_guidance_ru": "Не отмечать очистку успешной без доказательства. Использовать локальную консоль при отсутствии канала.", + "evidence_ids": [] + } + ], + "observations": [] +} diff --git a/data/checklists/policies.ru.json b/data/checklists/policies.ru.json new file mode 100644 index 0000000..f904cf9 --- /dev/null +++ b/data/checklists/policies.ru.json @@ -0,0 +1,48 @@ +{ + "schema_version": 1, + "items": [ + { + "id": "policy_outcomes", + "phase": "policies", + "title_ru": "Проверить результат каждой политики", + "purpose_ru": "Назначение не доказывает эффективное применение.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "Сохранить исходный GPO report и scope: links/order/inheritance/filter/scripts/preferences.", + "Для каждого параметра записать владельца и per-build смысловую карту.", + "Отдельно подтвердить получение, включение в результирующую конфигурацию, применение, эффективное значение и поведение пользователя." + ], + "expected_result_ru": "Все обязательные эффекты подтверждены; несопоставленные параметры видимы.", + "failure_guidance_ru": "Не применять один параметр двумя конкурирующими владельцами; отметить пробелы.", + "evidence_ids": [] + }, + { + "id": "reboot", + "phase": "policies", + "title_ru": "Проверить поведение после перезагрузки", + "purpose_ru": "Разделить работающее и сохранённое состояние.", + "host_scope": [ + "Выбранный узел / пилотный пользователь" + ], + "prerequisites": [ + "Согласованная область проверки", + "Доступ владельца проверяемой системы" + ], + "steps_ru": [ + "По отдельному разрешению перезагрузить только пилотный узел.", + "Повторить вход, DNS/time, разрешения, приложения и ключевые политики.", + "Записать build, время и ссылку на предыдущее наблюдение." + ], + "expected_result_ru": "Ожидаемые настройки сохраняются и штатные службы работают.", + "failure_guidance_ru": "Не повторять изменение автоматически; проверить persistent state и журнал запуска.", + "evidence_ids": [] + } + ], + "observations": [] +} diff --git a/data/hardening/astra17-mappings.json b/data/hardening/astra17-mappings.json new file mode 100644 index 0000000..f70d5e2 --- /dev/null +++ b/data/hardening/astra17-mappings.json @@ -0,0 +1,248 @@ +{ + "schema_version": 1, + "revision": 1, + "os": "ALSE 1.7.7 UU2", + "items": [ + { + "source_id": "fstec.2.1.1", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.1.2", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.2.1", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.2.2", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.3.1", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.3.2", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.3.3", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.3.4", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.3.5", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.3.6", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.3.7", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.3.8", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.3.9", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.3.10", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.3.11", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.4.1", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.4.2", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.4.3", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.4.4", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.4.5", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.4.6", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.4.7", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.4.8", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.5.1", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.5.2", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.5.3", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.5.4", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.5.5", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.5.6", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.5.7", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.5.8", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.5.9", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.5.10", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.5.11", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.6.1", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.6.2", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.6.3", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.6.4", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.6.5", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + }, + { + "source_id": "fstec.2.6.6", + "state": "UNKNOWN", + "vendor_section": null, + "supported_fix": null + } + ], + "note": "40 source cards do not mean 40 validated remediations." +} diff --git a/data/hardening/fstec-linux-2022.catalog.json b/data/hardening/fstec-linux-2022.catalog.json new file mode 100644 index 0000000..afdc50e --- /dev/null +++ b/data/hardening/fstec-linux-2022.catalog.json @@ -0,0 +1,1369 @@ +{ + "schema_version": 1, + "revision": 1, + "original_sha256": null, + "verification_state": "pending_original", + "items": [ + { + "id": "fstec.2.1.1", + "paragraph": "2.1.1", + "title_ru": "Пустые пароли", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: пустые пароли. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": null, + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "UNKNOWN", + "recovery_class": "MANUAL", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.1.2", + "paragraph": "2.1.2", + "title_ru": "Вход root по SSH", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: вход root по ssh. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": "PermitRootLogin=no", + "accepted_value": null, + "observed_state": null, + "read_only_check": "ssh.effective", + "manual_check_ru": "Проверить эффективный PermitRootLogin через sshd -T, учесть Match для конкретного подключения; сохранить разрешённый административный путь.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "UNKNOWN", + "recovery_class": "MANUAL", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.2.1", + "paragraph": "2.2.1", + "title_ru": "Доступ к su", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: доступ к su. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": null, + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "UNKNOWN", + "recovery_class": "MANUAL", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.2.2", + "paragraph": "2.2.2", + "title_ru": "Полномочия sudo", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: полномочия sudo. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": null, + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "UNKNOWN", + "recovery_class": "MANUAL", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.3.1", + "paragraph": "2.3.1", + "title_ru": "Файлы учётных записей", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: файлы учётных записей. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": null, + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "UNKNOWN", + "recovery_class": "MANUAL", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.3.2", + "paragraph": "2.3.2", + "title_ru": "Исполняемые процессы", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: исполняемые процессы. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": null, + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "UNKNOWN", + "recovery_class": "MANUAL", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.3.3", + "paragraph": "2.3.3", + "title_ru": "Задания cron: код", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: задания cron: код. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": null, + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "UNKNOWN", + "recovery_class": "MANUAL", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.3.4", + "paragraph": "2.3.4", + "title_ru": "Программы sudo", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: программы sudo. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": null, + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "UNKNOWN", + "recovery_class": "MANUAL", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.3.5", + "paragraph": "2.3.5", + "title_ru": "Стартовые сценарии", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: стартовые сценарии. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": null, + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "UNKNOWN", + "recovery_class": "MANUAL", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.3.6", + "paragraph": "2.3.6", + "title_ru": "Системные очереди cron", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: системные очереди cron. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": null, + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "UNKNOWN", + "recovery_class": "MANUAL", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.3.7", + "paragraph": "2.3.7", + "title_ru": "Пользовательский cron", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: пользовательский cron. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": null, + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "UNKNOWN", + "recovery_class": "MANUAL", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.3.8", + "paragraph": "2.3.8", + "title_ru": "Библиотеки и модули", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: библиотеки и модули. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": null, + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "UNKNOWN", + "recovery_class": "MANUAL", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.3.9", + "paragraph": "2.3.9", + "title_ru": "Набор SUID/SGID", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: набор suid/sgid. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": null, + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "UNKNOWN", + "recovery_class": "MANUAL", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.3.10", + "paragraph": "2.3.10", + "title_ru": "Содержимое профиля", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: содержимое профиля. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": null, + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "UNKNOWN", + "recovery_class": "MANUAL", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.3.11", + "paragraph": "2.3.11", + "title_ru": "Домашние каталоги", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: домашние каталоги. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": null, + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "UNKNOWN", + "recovery_class": "MANUAL", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.4.1", + "paragraph": "2.4.1", + "title_ru": "Журнал ядра", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: журнал ядра. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": "kernel.dmesg_restrict=1", + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "UNKNOWN", + "recovery_class": "MANUAL", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.4.2", + "paragraph": "2.4.2", + "title_ru": "Адреса ядра", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: адреса ядра. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": "kernel.kptr_restrict=2", + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "UNKNOWN", + "recovery_class": "MANUAL", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.4.3", + "paragraph": "2.4.3", + "title_ru": "Инициализация памяти", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: инициализация памяти. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": "init_on_alloc=1", + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "REBOOT", + "recovery_class": "REBOOT_REQUIRED", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.4.4", + "paragraph": "2.4.4", + "title_ru": "Разделение slab", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: разделение slab. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": "slab_nomerge", + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "REBOOT", + "recovery_class": "REBOOT_REQUIRED", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.4.5", + "paragraph": "2.4.5", + "title_ru": "Режим IOMMU", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: режим iommu. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": "iommu=force; iommu.strict=1; iommu.passthrough=0", + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "REBOOT", + "recovery_class": "REBOOT_REQUIRED", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.4.6", + "paragraph": "2.4.6", + "title_ru": "Стек ядра", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: стек ядра. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": "randomize_kstack_offset=1", + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "REBOOT", + "recovery_class": "REBOOT_REQUIRED", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.4.7", + "paragraph": "2.4.7", + "title_ru": "Защита процессора", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: защита процессора. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": "mitigations=auto,nosmt", + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "REBOOT", + "recovery_class": "REBOOT_REQUIRED", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.4.8", + "paragraph": "2.4.8", + "title_ru": "Защита BPF JIT", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: защита bpf jit. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": "net.core.bpf_jit_harden=2", + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "UNKNOWN", + "recovery_class": "MANUAL", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.5.1", + "paragraph": "2.5.1", + "title_ru": "Совместимость vsyscall", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: совместимость vsyscall. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": "vsyscall=none", + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "REBOOT", + "recovery_class": "REBOOT_REQUIRED", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.5.2", + "paragraph": "2.5.2", + "title_ru": "События производительности", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: события производительности. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": "kernel.perf_event_paranoid=3", + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "UNKNOWN", + "recovery_class": "MANUAL", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.5.3", + "paragraph": "2.5.3", + "title_ru": "Монтирование debugfs", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: монтирование debugfs. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": "debugfs=no-mount (off if possible)", + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "REBOOT", + "recovery_class": "REBOOT_REQUIRED", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.5.4", + "paragraph": "2.5.4", + "title_ru": "Вызов kexec", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: вызов kexec. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": "kernel.kexec_load_disabled=1", + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "UNKNOWN", + "recovery_class": "MANUAL", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.5.5", + "paragraph": "2.5.5", + "title_ru": "Пространства имён", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: пространства имён. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": "user.max_user_namespaces=0", + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "UNKNOWN", + "recovery_class": "MANUAL", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.5.6", + "paragraph": "2.5.6", + "title_ru": "Непривилегированный BPF", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: непривилегированный bpf. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": "kernel.unprivileged_bpf_disabled=1", + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "UNKNOWN", + "recovery_class": "MANUAL", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.5.7", + "paragraph": "2.5.7", + "title_ru": "Доступ userfaultfd", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: доступ userfaultfd. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": "vm.unprivileged_userfaultfd=0", + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "UNKNOWN", + "recovery_class": "MANUAL", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.5.8", + "paragraph": "2.5.8", + "title_ru": "Автозагрузка line discipline", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: автозагрузка line discipline. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": "dev.tty.ldisc_autoload=0", + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "UNKNOWN", + "recovery_class": "MANUAL", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.5.9", + "paragraph": "2.5.9", + "title_ru": "Транзакции TSX", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: транзакции tsx. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": "tsx=off", + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "REBOOT", + "recovery_class": "REBOOT_REQUIRED", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.5.10", + "paragraph": "2.5.10", + "title_ru": "Нижняя граница mmap", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: нижняя граница mmap. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": "vm.mmap_min_addr>=4096", + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "UNKNOWN", + "recovery_class": "MANUAL", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.5.11", + "paragraph": "2.5.11", + "title_ru": "Рандомизация адресов", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: рандомизация адресов. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": "kernel.randomize_va_space=2", + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "UNKNOWN", + "recovery_class": "MANUAL", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.6.1", + "paragraph": "2.6.1", + "title_ru": "Межпроцессный ptrace", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR", + "KERNEL_YAMA" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: межпроцессный ptrace. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": "kernel.yama.ptrace_scope=3", + "accepted_value": null, + "observed_state": null, + "read_only_check": "local.yama", + "manual_check_ru": "Прочитать /proc/sys/kernel/yama/ptrace_scope и отдельно persistent конфигурацию; отсутствие параметра не означает неприменимость.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "REBOOT", + "recovery_class": "REBOOT_REQUIRED", + "reversibility_ru": "При значении 3 немедленный обратный sysctl невозможен; нужен проверенный план persistent конфигурации и перезагрузки.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.6.2", + "paragraph": "2.6.2", + "title_ru": "Обработка symlink", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: обработка symlink. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": "fs.protected_symlinks=1", + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "UNKNOWN", + "recovery_class": "MANUAL", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.6.3", + "paragraph": "2.6.3", + "title_ru": "Обработка hardlink", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: обработка hardlink. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": "fs.protected_hardlinks=1", + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "UNKNOWN", + "recovery_class": "MANUAL", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.6.4", + "paragraph": "2.6.4", + "title_ru": "Запись FIFO", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: запись fifo. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": "fs.protected_fifos=2", + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "UNKNOWN", + "recovery_class": "MANUAL", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.6.5", + "paragraph": "2.6.5", + "title_ru": "Запись regular files", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: запись regular files. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": "fs.protected_regular=2", + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "UNKNOWN", + "recovery_class": "MANUAL", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + }, + { + "id": "fstec.2.6.6", + "paragraph": "2.6.6", + "title_ru": "Дампы привилегированных процессов", + "source_refs": [ + "FSTEC_LINUX_2022", + "FSTEC_TEXT_MIRROR" + ], + "verification_state": "pending_original", + "explanation_ru": "Предмет проверки: дампы привилегированных процессов. Для сертифицированной Astra нужен отдельный подтверждённый механизм из эксплуатационной документации; эта карточка сама не разрешает изменение.", + "applicable_versions": [ + "ALD 3.1 / ALSE 1.7.7 UU2: mapping pending" + ], + "roles": [ + "ALD_CONTROLLER", + "LINUX_APPLICATION_SERVER", + "WORKSTATION", + "ADMIN_WORKSTATION" + ], + "applicability": "UNKNOWN", + "mapping_state": "UNKNOWN", + "source_recommendation": "fs.suid_dumpable=0", + "accepted_value": null, + "observed_state": null, + "read_only_check": null, + "manual_check_ru": "Открыть пункт источника и документ Astra для этой роли. Зафиксировать фактическое значение/права, источник управления и время. Для загрузочных параметров проверить поддержку ядром и runtime эффект отдельно от строки cmdline.", + "configuration_path_ru": "Автоприменение закрыто до проверки документации Astra и пилота. Не менять генерируемый кэш политик.", + "impact_ru": "Требуется пилот доменной аутентификации, служб и приложений; влияние ещё не оценено.", + "restart_requirement": "UNKNOWN", + "recovery_class": "MANUAL", + "reversibility_ru": "Сохранить исходное состояние. Подтвердить обратимость на выбранном ядре; не обещать универсальный обратный шаг.", + "verification_ru": "Сохранить отдельные наблюдения текущего состояния, следующей загрузки и пользовательского поведения.", + "exceptions": [] + } + ] +} diff --git a/data/hardening/windows-baselines.json b/data/hardening/windows-baselines.json new file mode 100644 index 0000000..1319bac --- /dev/null +++ b/data/hardening/windows-baselines.json @@ -0,0 +1,45 @@ +{ + "schema_version": 1, + "revision": 1, + "profiles": [ + { + "os": "Windows 10", + "build": null, + "state": "UNKNOWN", + "roles": [ + "WORKSTATION" + ], + "source_refs": [ + "MS_SCT" + ], + "settings": [], + "reason_ru": "Нужны точная сборка, утверждённый baseline и проверка каждого native setting." + }, + { + "os": "Windows Server 2019", + "build": null, + "state": "UNKNOWN", + "roles": [ + "SERVER" + ], + "source_refs": [ + "MS_SCT" + ], + "settings": [], + "reason_ru": "Нужны точная сборка, утверждённый baseline и проверка каждого native setting." + }, + { + "os": "Windows Server 2025", + "build": null, + "state": "UNKNOWN", + "roles": [ + "SERVER" + ], + "source_refs": [ + "MS_SCT" + ], + "settings": [], + "reason_ru": "Нужны точная сборка, утверждённый baseline и проверка каждого native setting." + } + ] +} diff --git a/data/sources.json b/data/sources.json new file mode 100644 index 0000000..2061a9b --- /dev/null +++ b/data/sources.json @@ -0,0 +1,259 @@ +{ + "schema_version": 1, + "revision": 2, + "sources": [ + { + "id": "ALD31_ROOT", + "url": "https://www.aldpro.ru/materials/3.1.0/", + "title": "ALD Pro 3.1 documentation", + "product_version": "3.1.0", + "section": "Index", + "retrieved_at": "2026-10-27T12:36:07.143084+00:00", + "artifact_sha256": null, + "verification_state": "reviewed_web", + "notes": "Mutable documentation; no delivery artifact was supplied." + }, + { + "id": "ALD31_PROMOTION", + "url": "https://www.aldpro.ru/materials/3.1.0/%D0%A0%D1%83%D0%BA%D0%BE%D0%B2%D0%BE%D0%B4%D1%81%D1%82%D0%B2%D0%BE%20%D0%90%D0%B4%D0%BC%D0%B8%D0%BD%D0%B8%D1%81%D1%82%D1%80%D0%B0%D1%82%D0%BE%D1%80%D0%B0/2_subsystems_deployment/2.1/2.1.8.html", + "title": "First controller promotion", + "product_version": "3.1.0", + "section": "First controller", + "retrieved_at": "2026-10-27T12:36:07.143084+00:00", + "artifact_sha256": null, + "verification_state": "reviewed_web", + "notes": "Interactive password prompt documented; -d, -n, --ip, --no-reboot. Exact installed help and lab remain pending. Navigation mentions 3.2; freeze delivery before execution." + }, + { + "id": "ALD31_OS", + "url": "https://www.aldpro.ru/materials/3.1.0/%D0%A0%D1%83%D0%BA%D0%BE%D0%B2%D0%BE%D0%B4%D1%81%D1%82%D0%B2%D0%BE%20%D0%90%D0%B4%D0%BC%D0%B8%D0%BD%D0%B8%D1%81%D1%82%D1%80%D0%B0%D1%82%D0%BE%D1%80%D0%B0/2_subsystems_deployment/2.1/2.1.2.html", + "title": "Controller OS prerequisites", + "product_version": "3.1.0", + "section": "OS requirements", + "retrieved_at": "2026-10-27T12:36:07.143084+00:00", + "artifact_sha256": null, + "verification_state": "reviewed_web", + "notes": "Release support is not local laboratory evidence." + }, + { + "id": "ALD31_PACKAGES", + "url": "https://www.aldpro.ru/materials/3.1.0/%D0%A0%D1%83%D0%BA%D0%BE%D0%B2%D0%BE%D0%B4%D1%81%D1%82%D0%B2%D0%BE%20%D0%90%D0%B4%D0%BC%D0%B8%D0%BD%D0%B8%D1%81%D1%82%D1%80%D0%B0%D1%82%D0%BE%D1%80%D0%B0/2_subsystems_deployment/2.1/2.1.7.html", + "title": "Package installation", + "product_version": "3.1.0", + "section": "Package installation", + "retrieved_at": "2026-10-27T12:36:07.143084+00:00", + "artifact_sha256": null, + "verification_state": "reviewed_web", + "notes": "Repository and delivery must be verified on target; automatic installation disabled." + }, + { + "id": "ALD31_MIGRATION", + "url": "https://www.aldpro.ru/materials/3.1.0/%D0%A0%D1%83%D0%BA%D0%BE%D0%B2%D0%BE%D0%B4%D1%81%D1%82%D0%B2%D0%BE%20%D0%90%D0%B4%D0%BC%D0%B8%D0%BD%D0%B8%D1%81%D1%82%D1%80%D0%B0%D1%82%D0%BE%D1%80%D0%B0/9_userguide/%D0%A3%D0%BF%D1%80%D0%B0%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5%20%D0%B4%D0%BE%D0%BC%D0%B5%D0%BD%D0%BE%D0%BC/%D0%98%D0%BD%D1%82%D0%B5%D0%B3%D1%80%D0%B0%D1%86%D0%B8%D1%8F%20%D1%81%20%D0%B4%D0%BE%D0%BC%D0%B5%D0%BD%D0%B0%D0%BC%D0%B8/%D0%9C%D0%B8%D0%B3%D1%80%D0%B0%D1%86%D0%B8%D0%B8%20MS%20AD/%D0%9C%D0%B8%D0%B3%D1%80%D0%B0%D1%86%D0%B8%D1%8F%20%D0%BE%D0%B1%D1%8A%D0%B5%D0%BA%D1%82%D0%BE%D0%B2%20Active%20Directory/index.html", + "title": "AD object migration", + "product_version": "3.1.0", + "section": "Migration", + "retrieved_at": "2026-10-27T12:36:07.143084+00:00", + "artifact_sha256": null, + "verification_state": "reviewed_web", + "notes": "Portal workflow does not prove same-name full transition or all continuity requirements." + }, + { + "id": "ALD_DEPLOY_COURSE", + "url": "https://www.aldpro.ru/professional/ALD_Pro_Module_02/ALD_Pro_deployment.html", + "title": "Deployment course", + "product_version": "3.x.x", + "section": "ALD 3.1 example", + "retrieved_at": "2026-10-27T12:36:07.143084+00:00", + "artifact_sha256": null, + "verification_state": "reviewed_web", + "notes": "Selected laboratory baseline 1.7.7 UU2, 6.1-generic, Smolensk; mutable course." + }, + { + "id": "ALD_DIRECTORY_COURSE", + "url": "https://www.aldpro.ru/professional/ALD_Pro_Module_04/ALD_directory_services.html", + "title": "Directory course", + "product_version": "3.x.x", + "section": "Directory", + "retrieved_at": null, + "artifact_sha256": null, + "verification_state": "not_retrieved", + "notes": "Starting URL only." + }, + { + "id": "ALD_POLICIES_COURSE", + "url": "https://www.aldpro.ru/professional/ALD_Pro_Module_06b/ALD_Pro_group_policy.html", + "title": "Policy course", + "product_version": "3.x.x", + "section": "Policy", + "retrieved_at": null, + "artifact_sha256": null, + "verification_state": "not_retrieved", + "notes": "Starting URL only." + }, + { + "id": "ALD_MIGRATION_COURSE", + "url": "https://www.aldpro.ru/professional/ALD_Pro_Module_09/ALD_Pro_migration_hybrid_deployment.html", + "title": "Migration course", + "product_version": "3.x.x", + "section": "Migration", + "retrieved_at": null, + "artifact_sha256": null, + "verification_state": "not_retrieved", + "notes": "Local research read; page not independently retrieved in this implementation session." + }, + { + "id": "ALD_BACKUP_COURSE", + "url": "https://www.aldpro.ru/professional/ALD_Pro_Module_10/ALD_Pro_backup.html", + "title": "Backup course", + "product_version": "3.x.x", + "section": "Recovery", + "retrieved_at": null, + "artifact_sha256": null, + "verification_state": "not_retrieved", + "notes": "Starting URL only; no restore rehearsal." + }, + { + "id": "FSTEC_LINUX_2022", + "url": "https://fstec.ru/dokumenty/vse-dokumenty/spetsialnye-normativnye-dokumenty/metodicheskij-dokument-ot-25-dekabrya-2022-g", + "title": "Linux security recommendations, 25 December 2022", + "product_version": null, + "section": "1.3 and section 2", + "retrieved_at": null, + "artifact_sha256": null, + "verification_state": "pending_original", + "notes": "Fetch timed out; original not reviewed, hash null." + }, + { + "id": "FSTEC_TEXT_MIRROR", + "url": "https://legalacts.ru/doc/metodicheskii-dokument-rekomendatsii-po-bezopasnoi-nastroike-operatsionnykh-sistem-linux/", + "title": "Provisional text reproduction", + "product_version": null, + "section": "Section 2", + "retrieved_at": "2026-10-27T12:51:26.801571+00:00", + "artifact_sha256": null, + "verification_state": "reviewed_web", + "notes": "Provisional reproduction reviewed. Original still pending; no Astra remediation is enabled from this source." + }, + { + "id": "ASTRA_HARDENING", + "url": "https://docs.astra-automation.ru/2.1/solutions/protection/fstec/", + "title": "Astra hardening role", + "product_version": "2.1", + "section": "FSTEC role", + "retrieved_at": null, + "artifact_sha256": null, + "verification_state": "not_retrieved", + "notes": "Optional research only, not enabled on Astra 1.7." + }, + { + "id": "ASTRA_ROLE_INTRODUCTION", + "url": "https://docs.astra-automation.ru/1.2/releases/release-1.2/upd2/", + "title": "Role introduction", + "product_version": "1.2 upd2", + "section": "Release notes", + "retrieved_at": null, + "artifact_sha256": null, + "verification_state": "not_retrieved", + "notes": "Specification identifies Astra 1.8 / Technical Preview; not proof for 1.7." + }, + { + "id": "ASTRA_QT_PACKAGES", + "url": "https://wiki.astralinux.ru/spaces/flyingpdf/pdfpageexport.action?pageId=153490669", + "title": "Astra Qt package information", + "product_version": null, + "section": "Qt", + "retrieved_at": null, + "artifact_sha256": null, + "verification_state": "not_retrieved", + "notes": "Not a package lock." + }, + { + "id": "MS_OPENSSH", + "url": "https://learn.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse", + "title": "Windows native OpenSSH", + "product_version": "Windows 10 1809+ / Server 2019+", + "section": "Prerequisites", + "retrieved_at": "2026-10-27T12:36:07.143084+00:00", + "artifact_sha256": null, + "verification_state": "reviewed_web", + "notes": "Native command execution, not PowerShell SSH subsystem. Transport support is separate from ALD integration." + }, + { + "id": "MS_SCT", + "url": "https://learn.microsoft.com/en-us/windows/security/operating-system-security/device-management/windows-security-configuration-framework/security-compliance-toolkit-10", + "title": "Security Compliance Toolkit", + "product_version": null, + "section": "LGPO", + "retrieved_at": null, + "artifact_sha256": null, + "verification_state": "not_retrieved", + "notes": "No binary bundled or downloaded." + }, + { + "id": "MS_SID", + "url": "https://learn.microsoft.com/en-us/windows-server/identity/ad-ds/manage/understand-security-identifiers", + "title": "Security identifiers", + "product_version": null, + "section": "SID semantics", + "retrieved_at": "2026-10-27T12:36:07.143084+00:00", + "artifact_sha256": null, + "verification_state": "reviewed_web", + "notes": "Same DNS name is not domain or principal identity." + }, + { + "id": "QT_PROCESS", + "url": "https://doc.qt.io/archives/qt-5.15/qprocess.html", + "title": "QProcess", + "product_version": "5.15", + "section": "Execution", + "retrieved_at": "2026-10-27T12:36:07.143084+00:00", + "artifact_sha256": null, + "verification_state": "reviewed_web", + "notes": "Online archive currently describes 5.15.19; application API ceiling is 5.15.2." + }, + { + "id": "KERNEL_YAMA", + "url": "https://docs.kernel.org/admin-guide/LSM/Yama.html", + "title": "Yama", + "product_version": null, + "section": "ptrace_scope", + "retrieved_at": "2026-10-27T12:36:07.143084+00:00", + "artifact_sha256": null, + "verification_state": "reviewed_web", + "notes": "Value 3 cannot be reverted in the current kernel session." + }, + { + "id": "OPENSSH", + "url": "https://man.openbsd.org/ssh.1", + "title": "ssh manual", + "product_version": null, + "section": "Remote command", + "retrieved_at": "2026-10-27T12:36:07.143084+00:00", + "artifact_sha256": null, + "verification_state": "reviewed_web", + "notes": "Remote arguments are combined by SSH; fixed encoded payload only, no user input interpolated." + }, + { + "id": "MS_AD_OBJECT", + "url": "https://learn.microsoft.com/en-us/powershell/module/activedirectory/get-adobject?view=windowsserver2022-ps", + "title": "Get-ADObject", + "product_version": "ActiveDirectory module; documentation view Windows Server 2022", + "section": "Inventory", + "retrieved_at": "2026-10-27T13:36:14.771772+00:00", + "artifact_sha256": null, + "verification_state": "reviewed_web", + "notes": "Initial direct retrieval failed. Subsequently reviewed indexed Microsoft Learn content for Server, LDAPFilter, SearchBase, Properties and ResultSetSize. No frozen artifact or Windows 2019/2025 laboratory evidence." + }, + { + "id": "MS_AD_FOREST", + "url": "https://learn.microsoft.com/en-us/powershell/module/activedirectory/get-adforest?view=windowsserver2025-ps", + "title": "Get-ADForest — Microsoft Learn", + "product_version": "ActiveDirectory module; documentation view Windows Server 2025", + "section": "Server parameter and domain selection", + "retrieved_at": "2026-10-27T13:36:14.771772+00:00", + "artifact_sha256": null, + "verification_state": "reviewed_web", + "notes": "Explicit directory-server binding is supported by the documented parameter. Actual fixed task remains untested." + } + ] +} diff --git a/docs/access-restoration.md b/docs/access-restoration.md new file mode 100644 index 0000000..e9558b2 --- /dev/null +++ b/docs/access-restoration.md @@ -0,0 +1,28 @@ +# Access restoration ledger + +The preview does not automatically open remote access. The operator can record +manual changes with target, exact resource identity, original/applied state, +run, owner marker and restoration steps. These records are not automatic proof. +Never enter passwords, private keys or their file contents in a record. + +Each resource is independently assessed by AccessLedger: + +1. If the owner marker is not the relevant run's, preserve it. +2. If the host is unreachable, retain PENDING and manual instructions. +3. Observe current state through the relevant native mechanism. +4. If current differs from applied, record CONFLICT; do not overwrite newer work. +5. If equal, prepare the reviewed inverse and its concrete authorization. +6. Verify the effect separately. For the final access channel, record the need + for verification from the local console before closing it. + +A result READY_FOR_REVIEW is not RESTORED. Manual descriptions cannot authorize +an automatic inverse. Pre-existing SSH/WinRM services, firewall rules and keys +are preserved. Restoration order puts credentials/groups/rules before the final +channel. A resource-specific validated restoration adapter and its GUI execution +are not yet implemented; the application saves useful manual obligations and +never claims they were removed remotely. + +On normal exit, stop new read-only work, finish/cancel owned processes, persist +the project and show obligations. After a crash, mark interrupted runs +RECOVERY_REQUIRED and inspect actual state before any new change. Nothing +resumes by itself; no hidden cleanup agent is installed. diff --git a/docs/astra-lab.ru.md b/docs/astra-lab.ru.md new file mode 100644 index 0000000..5aa7914 --- /dev/null +++ b/docs/astra-lab.ru.md @@ -0,0 +1,113 @@ +# Первая сборка и проверка на Astra + +Для этого этапа достаточно одной тестовой Astra с графическим рабочим столом. +Развёртывать AD или устанавливать ALD ради компиляции не требуется. Целевая +лабораторная база проекта — ALSE 1.7.7 UU2, 6.1-generic, Смоленск; её соответствие +поставке ALD Pro 3.1.0 проверяется отдельно. Успешная компиляция на другой версии +подтверждает только проверенные функции приложения в этой среде. + +## Получить исходники + +Скопируйте и распакуйте архив исходников или получите репозиторий: + +```sh +git clone https://git.ctfleague.ru/scandal/popki.git +cd popki +``` + +Для приватного репозитория нужен ваш доступ к серверу Git. При переносе архива +Git и доступ к серверу на Astra не нужны. Проводите сборку из каталога обычного +пользователя, а не из `/root` или системного каталога. + +## Зависимости + +Нужны C++17, CMake >= 3.13, make, Qt 5.15.2–5.15.x с модулями Core, Gui, +Widgets, Network, Sql, Test, инструменты Qt и плагин QSQLITE. Сценарий сборки +использует Python >= 3.7 из штатной поставки, без pip и сторонних модулей. + +Проверьте установленные и доступные версии из одобренных репозиториев Astra: + +```sh +cat /etc/astra/build_version +uname -r +python3 --version +apt-cache policy build-essential cmake make python3 qtbase5-dev \ + qtbase5-dev-tools qt5-qmake libqt5sql5-sqlite +apt-get -s install --no-upgrade build-essential cmake make python3 \ + qtbase5-dev qtbase5-dev-tools qt5-qmake libqt5sql5-sqlite +``` + +Последняя команда только показывает предполагаемые изменения. Если версии +соответствуют требованиям и добавляются только недостающие пакеты, установите +их штатным способом из этих же репозиториев или локального носителя. Не меняйте +репозитории на Kali/Debian и не обновляйте систему, Qt, Python или ALD ради +сборки. Если доступен только Qt 5.11 либо требуется обновление уже установленного +ПО, сохраните вывод и остановитесь на этом этапе: нужен разбор состава поставки. +Установка дополнительного ПО на действующий КД требует отдельной проверки +допустимого состава. Первую сборку удобнее делать на отдельной тестовой ВМ. + +## Собрать и проверить + +Из корня исходников, **без sudo**: + +```sh +python3 tools/build_astra_lab.py +``` + +Сценарий сохраняет сведения об ОС, ядре, компиляторе, Qt и пакетах, конфигурирует +`build-astra/`, собирает два исполняемых файла и запускает четыре набора CTest +через Qt offscreen. На малой ВМ можно указать `--jobs 1`. Пакеты не скачиваются, +приложение не устанавливается в систему, привилегированный исполнитель не +запускается. Состояние `release_validated` остаётся `false`. + +Итог и путь к архиву появятся в конце, в том числе при ошибке. Архив находится +в `artifacts/astra-lab/` и содержит `result.json`, `environment.json` и журналы +этапов. Базы проектов, ключи и переменные окружения туда не включаются. Вывод +сборки может содержать локальные пути и имена узлов; просмотрите его перед +передачей. Эти отчёты исключены из Git. + +Ожидается `100% tests passed, 0 tests failed out of 4`. Ошибки загрузки QSQLITE, +Qt, компилятора или CMake сохраняются в журнале; успешного результата при этом +нет. Если ресурсов мало, повторите с `--jobs 1`. При остальных ошибках сначала +сохраните архив отчёта, а не меняйте системные библиотеки наугад. + +## Проверить приложение в рабочем столе + +После успешной сборки: + +```sh +./build-astra/ald-transition-console --project ./astra-lab-project +``` + +Это обычный режим с чтением фактического локального окружения. Каталог проекта +создаётся с закрытыми правами; не используйте каталог существующего demo-проекта. +При старте нет удалённых подключений или изменения доменных настроек. + +1. На странице «Проверка окружения» сравните версию ОС, ядро и обнаруженные + пакеты с системой. Неизвестная роль остаётся неизвестной до достаточных + наблюдений; её нельзя принимать за чистый контроллер. +2. Откройте все десять страниц, проверьте русский текст, переходы Tab/Shift+Tab, + видимый фокус, окно 1024×768 и отключение анимации. +3. Отметьте один пункт чек-листа как «Не проверено» с заметкой, закройте + приложение и откройте тот же проект. Убедитесь, что заметка сохранилась. + Экспортируйте HTML/JSON и проверьте читаемость. +4. Проверьте системный масштаб 150/200% в отдельном запуске. Offscreen-тесты + сами по себе не подтверждают работу графического сеанса Fly/X11. +5. Закройте приложение через экран завершения. Проверьте, что его процесс + завершился. Установленные доменные службы должны продолжать работать. + +Для отдельно выбранного просмотра синтетических примеров можно использовать +`--demo --project ./demo-project`; это не результаты испытания Astra или AD. + +## Что передать по итогам + +Передайте архив отчёта `artifacts/astra-lab/*.tar.gz`, результат запуска GUI и +текст ошибки, если она появилась. Если невозможно даже запустить Python-сценарий, +достаточно вывода команд проверки зависимостей и самой ошибки. + +Дальше последовательно проверяются нативная диагностика Astra, процедура +инициализации по установленной поставке, затем Windows и инвентаризация одного +исходного AD DC `corp.local`. Записи в чек-листе не разблокируют неподтверждённые +механизмы сохранения паролей, профилей и прав. Изменения домена проверяются только +по конкретному согласованному плану с восстановлением; программа сейчас не +включает автоматическое продвижение КД, полную миграцию или вывод AD из работы. diff --git a/docs/build-artifacts.json b/docs/build-artifacts.json new file mode 100644 index 0000000..bca68f6 --- /dev/null +++ b/docs/build-artifacts.json @@ -0,0 +1,19 @@ +{ + "observed_at": "2026-10-27T14:10:39.019463+00:00", + "platform": "Kali 2026.3 x86_64 development build", + "version": "ALD Transition Console 0.1.0-dev", + "binaries": [ + { + "path": "build/ald-transition-console", + "size": 15983680, + "sha256": "1ab423d76a75af99eb70bb84303477fa8f71eef12a3ce877d5c65feee5111620" + }, + { + "path": "build/ald-transition-executor", + "size": 1268424, + "sha256": "9623aee4e75046f1fa5c9e146e8226583254358badea1d7dbbd3aa237bfb49a1" + } + ], + "unprivileged_executor_exit": 77, + "astra_validated": false +} diff --git a/docs/compatibility-lock.json b/docs/compatibility-lock.json new file mode 100644 index 0000000..0ded8ad --- /dev/null +++ b/docs/compatibility-lock.json @@ -0,0 +1,25 @@ +{ + "schema_version": 1, + "release_validated": false, + "target": { + "os": "Astra Linux SE", + "release": "1.7.7", + "update": "UU2", + "kernel_family": "6.1-generic", + "protection_level": "Smolensk", + "ald_version": "3.1.0" + }, + "validated_target": { + "os_release": null, + "os_update": null, + "kernel": null, + "architecture": null, + "compiler": null, + "cmake": null, + "qt_packages": null, + "sqlite_driver": null, + "transports": null, + "ald_packages": null + }, + "reason": "No supported Astra VM or ALD delivery was available. Null values are intentional. Kali is development-only." +} diff --git a/docs/compatibility-matrix.md b/docs/compatibility-matrix.md new file mode 100644 index 0000000..4bec30a --- /dev/null +++ b/docs/compatibility-matrix.md @@ -0,0 +1,29 @@ +# Compatibility matrix — development preview + +| Environment | GUI | Controller | Client management | Migration/hardening | +|---|---|---|---|---| +| ALSE 1.7.7 UU2 / 6.1-generic / Smolensk / ALD 3.1.0 | Not built/tested | Selected documented laboratory baseline; not tested here | Per-operation validation pending | Same-name continuity blocked; no write adapter enabled | +| Other ALSE 1.7.x updates | Unknown | Not inferred from family | Unknown | Unknown | +| Windows 10 1809+ | Not a GUI host | Not applicable | Native SSH/PS prerequisites documented; actual edition/build/features pending | ALD integration/profile/policy outcomes unverified | +| Windows Server 2019 | Not a GUI host | Source AD role must be inventoried | Native SSH/PS prerequisites documented | Migration and decommissioning procedure pending | +| Windows Server 2025 | Not a GUI host | Source/managed role must be inventoried | Transport capability separate from ALD support | ALD integration UNKNOWN even with successful SSH | +| Kali rolling 2026.3 (development machine) | Built: CMake 4.3.4, GCC 16.2.0, Qt 5.15.19; offscreen DEMO tested | Not supported as ALD target | No remote targets contacted | Four CTest suites pass; no ALD mutations | + +The source uses Qt 5.15.2-era APIs and CMake language >=3.13. A newer installed +runtime is not proof of this source's target compatibility. Required Qt modules: +Core, Gui, Widgets, Network, Sql, Test; QSQLITE runtime plugin. No QtWebEngine, +Node, Chromium, ffmpeg, web server, persistent controller or Python runtime is +required by the shipped application. Python is used only for development asset +checks and evidence collection scripts. + +`compatibility-lock.json` deliberately contains null target revisions. The +actual development compiler/runtime observations are in +`development-environment.json`. Do not turn them into an Astra lock. + +Before packaging, inspect OS release/update, kernel, architecture, protection +level, compiler, CMake, all relevant Qt runtime/dev packages, SQLite driver, +OpenSSH, polkit and ALD/native packages. Confirm with the vendor whether this +additional desktop software and dependencies are permitted on the selected DC. +Isolation does not itself establish supported DC composition. No dependencies +are upgraded automatically. Package signatures/digests must come from the +approved target distribution channels. diff --git a/docs/development-environment.json b/docs/development-environment.json new file mode 100644 index 0000000..1d8da36 --- /dev/null +++ b/docs/development-environment.json @@ -0,0 +1,77 @@ +{ + "schema_version": 1, + "observed_at": "2026-10-27T14:04:17.108877+00:00", + "release_validated": false, + "os_release": "PRETTY_NAME=\"Kali GNU/Linux Rolling\"\nNAME=\"Kali GNU/Linux\"\nVERSION_ID=\"2026.3\"\nVERSION=\"2026.3\"\nVERSION_CODENAME=kali-rolling\nID=kali\nID_LIKE=debian\nHOME_URL=\"https://www.kali.org/\"\nSUPPORT_URL=\"https://forums.kali.org/\"\nBUG_REPORT_URL=\"https://bugs.kali.org/\"\nANSI_COLOR=\"1;31\"\n", + "astra_build": null, + "kernel": "7.1.5+kali-amd64", + "architecture": "x86_64", + "protection_level": null, + "commands": [ + { + "argv": [ + "g++", + "--version" + ], + "exit_code": 0, + "stdout": "g++ (Debian 16.2.0-3) 16.2.0\nCopyright (C) 2026 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n", + "stderr": "" + }, + { + "argv": [ + "cmake", + "--version" + ], + "exit_code": 0, + "stdout": "cmake version 4.3.4\n\nCMake suite maintained and supported by Kitware (kitware.com/cmake).\n", + "stderr": "" + }, + { + "argv": [ + "qmake", + "-query" + ], + "exit_code": 0, + "stdout": "QT_SYSROOT:\nQT_INSTALL_PREFIX:/usr\nQT_INSTALL_ARCHDATA:/usr/lib/x86_64-linux-gnu/qt5\nQT_INSTALL_DATA:/usr/share/qt5\nQT_INSTALL_DOCS:/usr/share/qt5/doc\nQT_INSTALL_HEADERS:/usr/include/x86_64-linux-gnu/qt5\nQT_INSTALL_LIBS:/usr/lib/x86_64-linux-gnu\nQT_INSTALL_LIBEXECS:/usr/lib/x86_64-linux-gnu/qt5/libexec\nQT_INSTALL_BINS:/usr/lib/qt5/bin\nQT_INSTALL_TESTS:/usr/tests\nQT_INSTALL_PLUGINS:/usr/lib/x86_64-linux-gnu/qt5/plugins\nQT_INSTALL_IMPORTS:/usr/lib/x86_64-linux-gnu/qt5/imports\nQT_INSTALL_QML:/usr/lib/x86_64-linux-gnu/qt5/qml\nQT_INSTALL_TRANSLATIONS:/usr/share/qt5/translations\nQT_INSTALL_CONFIGURATION:/etc/xdg\nQT_INSTALL_EXAMPLES:/usr/lib/x86_64-linux-gnu/qt5/examples\nQT_INSTALL_DEMOS:/usr/lib/x86_64-linux-gnu/qt5/examples\nQT_HOST_PREFIX:/usr\nQT_HOST_DATA:/usr/lib/x86_64-linux-gnu/qt5\nQT_HOST_BINS:/usr/lib/qt5/bin\nQT_HOST_LIBS:/usr/lib/x86_64-linux-gnu\nQMAKE_SPEC:linux-g++\nQMAKE_XSPEC:linux-g++\nQMAKE_VERSION:3.1\nQT_VERSION:5.15.19\n", + "stderr": "" + }, + { + "argv": [ + "ssh", + "-V" + ], + "exit_code": 0, + "stdout": "", + "stderr": "OpenSSH_10.6p1 Debian-1, OpenSSL 3.6.5 29 Sep 2026\n" + }, + { + "argv": [ + "dpkg-query", + "-W", + "-f=${binary:Package}\t${Version}\t${db:Status-Status}\n", + "g++", + "gcc", + "cmake", + "qtbase5-dev", + "qtbase5-dev-tools", + "qt5-qmake", + "libqt5core5*", + "libqt5gui5*", + "libqt5widgets5*", + "libqt5network5*", + "libqt5sql5*", + "libqt5test5*", + "openssh-client", + "policykit-1", + "aldpro*", + "astra-version", + "freeipa*", + "sssd*", + "samba*" + ], + "exit_code": 1, + "stdout": "cmake\t4.3.4-1\tinstalled\ng++\t4:16.1.0-3\tinstalled\ngcc\t4:16.1.0-3\tinstalled\nlibqt5core5a\t\tnot-installed\nlibqt5core5t64:amd64\t5.15.19+dfsg-5\tinstalled\nlibqt5gui5\t\tnot-installed\nlibqt5gui5-gles\t\tnot-installed\nlibqt5gui5t64:amd64\t5.15.19+dfsg-5\tinstalled\nlibqt5network5\t\tnot-installed\nlibqt5network5t64:amd64\t5.15.19+dfsg-5\tinstalled\nlibqt5sql5\t\tnot-installed\nlibqt5sql5-ibase\t\tnot-installed\nlibqt5sql5-mysql\t\tnot-installed\nlibqt5sql5-odbc\t\tnot-installed\nlibqt5sql5-psql\t\tnot-installed\nlibqt5sql5-sqlite:amd64\t5.15.19+dfsg-5\tinstalled\nlibqt5sql5-tds\t\tnot-installed\nlibqt5sql5t64:amd64\t5.15.19+dfsg-5\tinstalled\nlibqt5test5\t\tnot-installed\nlibqt5test5t64:amd64\t5.15.19+dfsg-5\tinstalled\nlibqt5widgets5\t\tnot-installed\nlibqt5widgets5t64:amd64\t5.15.19+dfsg-5\tinstalled\nopenssh-client\t1:10.6p1-1\tinstalled\npolicykit-1\t\tnot-installed\nqt5-qmake:amd64\t5.15.19+dfsg-5\tinstalled\nqtbase5-dev:amd64\t5.15.19+dfsg-5\tinstalled\nqtbase5-dev-tools\t5.15.19+dfsg-5\tinstalled\nsamba\t2:4.25.0+dfsg-1\tinstalled\nsamba-ad-dc\t\tnot-installed\nsamba-ad-provision\t\tnot-installed\nsamba-client\t\tnot-installed\nsamba-common\t2:4.25.0+dfsg-1\tinstalled\nsamba-common-bin\t2:4.25.0+dfsg-1\tinstalled\nsamba-libs:amd64\t2:4.25.0+dfsg-1\tinstalled\nsamba-vfs-ceph\t\tnot-installed\nsamba-vfs-glusterfs\t\tnot-installed\nsamba-vfs-modules\t\tnot-installed\nsssd-ad\t\tnot-installed\nsssd-ad-common\t\tnot-installed\nsssd-ipa\t\tnot-installed\n", + "stderr": "dpkg-query: no packages found matching aldpro*\ndpkg-query: no packages found matching astra-version\ndpkg-query: no packages found matching freeipa*\n" + } + ] +} diff --git a/docs/feasibility.md b/docs/feasibility.md new file mode 100644 index 0000000..fede601 --- /dev/null +++ b/docs/feasibility.md @@ -0,0 +1,66 @@ +# Feasibility and evidence register + +Status: **BLOCKED migration; source development can proceed.** Access date: +2026-10-27. The sources are recorded in `data/sources.json`. `reviewed_web` +means retrieved page text, not an immutable delivery artifact or a lab test. +No original artifact digest was obtained; no digest is invented. + +## Scope and questions + +The owner requires replacement of the single-DC `corp.local` AD domain, +retaining its name, existing subnet and separate login/password/profile/data/ +permission/application/policy outcomes. Research questions: supported 3.1 +initialization, same-name authority transition, retained identities/credentials, +Windows integration, and exact Astra/DC software compatibility. + +## Claims and open gates + +| ID | Finding | Evidence / confidence | Consequence | +|---|---|---|---| +| F1 | Interactive native promotion is described in the 3.1 branch | ALD31_PROMOTION; documented, not tested | Guided procedure available; automated invocation disabled | +| F2 | Selected lab baseline is ALD 3.1 / ALSE 1.7.7 UU2, 6.1-generic, Smolensk | ALD_DEPLOY_COURSE; single vendor course | Exact delivery, packages and test VM still required | +| F3 | Same-name complete transition has not been established | No verified delivery/lab method supplied | Block production mutation and AD retirement | +| F4 | A repeated DNS domain label does not establish principal identity | MS_SID plus separate owner acceptance requirements | Stable GUID/SID maps; no login-based merge | +| F5 | Native Windows OpenSSH has versioned OS/PowerShell prerequisites | MS_OPENSSH; vendor documentation, no local VM | Transport observation does not authorize ALD integration | +| F6 | FSTEC original was not obtained | FSTEC_LINUX_2022 fetch timeout | `artifact_sha256=null`, `pending_original` | +| F7 | Yama value 3 has no runtime inverse during the current kernel session | KERNEL_YAMA; documented | Reboot recovery classification; no fictional inverse | + +The mandatory requirements include same-name transition, credentials, computer +trust, Windows profiles (including applicable DPAPI/EFS), identity/permission +mapping, application authentication, policy outcomes and AD independence. +All are UNKNOWN / NOT_CHECKED in the released registry. Reachable SSH, +matching names, matching counts, exit zero or human checkmarks cannot turn +them into VERIFIED/PASS. A requirement change needs a new owner-reviewed +plan; there is no exception checkbox that removes these requirements. + +## Contradictions and source quality + +The 3.1 promotion page currently contains navigation naming a newer release; +its content describes interactive input, `-d`, `-n`, `--ip`, and `--no-reboot`. +The course uses a different long hostname option in its example. The application +retains the 3.1 page's short `-n` template and requires installed help and an +immutable delivery manual before enablement. Earlier local research includes +3.2/3.3-only content; those commands are not imported into an executable adapter. + +The mutable vendor course and vendor manual are not independent laboratory +confirmations. Microsoft supports the transport technology, not an ALD domain +integration scenario. The text reproduction of the FSTEC document is explicitly +provisional and is not presented as the official artifact. Source bias is +handled through per-operation support states and pending validation rather +than a vote among derivative pages. No community claim unlocks execution. + +## Next evidence needed + +Obtain the selected ALD delivery, exact ALSE VM, installed installer help and +vendor-approved procedure for two successive `corp.local` authorities in the +same network. Run isolated restore rehearsal for the only source DC and each +mandatory continuity test on the named Windows builds. Freeze the relevant +manuals with real digests. An unavailable path remains a visible blocker; +changing to another target name/subnet or keeping a hidden AD/Samba domain is +not an accepted workaround. + +Sources: [ALD 3.1 promotion](https://www.aldpro.ru/materials/3.1.0/Руководство%20Администратора/2_subsystems_deployment/2.1/2.1.8.html), +[deployment course](https://www.aldpro.ru/professional/ALD_Pro_Module_02/ALD_Pro_deployment.html), +[Microsoft OpenSSH](https://learn.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse), +[Microsoft SIDs](https://learn.microsoft.com/en-us/windows-server/identity/ad-ds/manage/understand-security-identifiers), +[Yama](https://docs.kernel.org/admin-guide/LSM/Yama.html). diff --git a/docs/gui-scale-results.json b/docs/gui-scale-results.json new file mode 100644 index 0000000..1404b11 --- /dev/null +++ b/docs/gui-scale-results.json @@ -0,0 +1,14 @@ +[ + { + "scale": "1.5", + "exit_code": 0, + "stdout": "********* Start testing of UiTests *********\nConfig: Using QtTest library 5.15.19, Qt 5.15.19 (x86_64-little_endian-lp64 shared (dynamic) release build; by GCC 16.2.0), kali 2026.3\nPASS : UiTests::initTestCase()\nPASS : UiTests::explicitDemoAndKeyboard()\nPASS : UiTests::importedTooltipEscaped()\nPASS : UiTests::narrowPagesKeepActionsReachable()\nPASS : UiTests::reducedMotionStopsDecoration()\nPASS : UiTests::manualPassDoesNotAuthorizeMigration()\nPASS : UiTests::cleanupTestCase()\nTotals: 7 passed, 0 failed, 0 skipped, 0 blacklisted, 1422ms\n********* Finished testing of UiTests *********\n", + "stderr": "" + }, + { + "scale": "2", + "exit_code": 0, + "stdout": "********* Start testing of UiTests *********\nConfig: Using QtTest library 5.15.19, Qt 5.15.19 (x86_64-little_endian-lp64 shared (dynamic) release build; by GCC 16.2.0), kali 2026.3\nPASS : UiTests::initTestCase()\nPASS : UiTests::explicitDemoAndKeyboard()\nPASS : UiTests::importedTooltipEscaped()\nPASS : UiTests::narrowPagesKeepActionsReachable()\nPASS : UiTests::reducedMotionStopsDecoration()\nPASS : UiTests::manualPassDoesNotAuthorizeMigration()\nPASS : UiTests::cleanupTestCase()\nTotals: 7 passed, 0 failed, 0 skipped, 0 blacklisted, 1720ms\n********* Finished testing of UiTests *********\n", + "stderr": "" + } +] diff --git a/docs/gui-smoke-results.json b/docs/gui-smoke-results.json new file mode 100644 index 0000000..6ae5e43 --- /dev/null +++ b/docs/gui-smoke-results.json @@ -0,0 +1,51 @@ +{ + "observed_at": "2026-10-27T14:10:19.357780+00:00", + "platform": "Qt offscreen", + "records": [ + { + "kind": "application_demo", + "scale": "1", + "exit_code": 0, + "stdout": "", + "stderr": "" + }, + { + "kind": "ui_suite", + "scale": "1", + "exit_code": 0, + "stdout": "********* Start testing of UiTests *********\nConfig: Using QtTest library 5.15.19, Qt 5.15.19 (x86_64-little_endian-lp64 shared (dynamic) release build; by GCC 16.2.0), kali 2026.3\nPASS : UiTests::initTestCase()\nPASS : UiTests::explicitDemoAndKeyboard()\nPASS : UiTests::importedTooltipEscaped()\nPASS : UiTests::narrowPagesKeepActionsReachable()\nPASS : UiTests::reducedMotionStopsDecoration()\nPASS : UiTests::manualPassDoesNotAuthorizeMigration()\nPASS : UiTests::cleanupTestCase()\nTotals: 7 passed, 0 failed, 0 skipped, 0 blacklisted, 1004ms\n********* Finished testing of UiTests *********\n", + "stderr": "" + }, + { + "kind": "application_demo", + "scale": "1.5", + "exit_code": 0, + "stdout": "", + "stderr": "" + }, + { + "kind": "ui_suite", + "scale": "1.5", + "exit_code": 0, + "stdout": "********* Start testing of UiTests *********\nConfig: Using QtTest library 5.15.19, Qt 5.15.19 (x86_64-little_endian-lp64 shared (dynamic) release build; by GCC 16.2.0), kali 2026.3\nPASS : UiTests::initTestCase()\nPASS : UiTests::explicitDemoAndKeyboard()\nPASS : UiTests::importedTooltipEscaped()\nPASS : UiTests::narrowPagesKeepActionsReachable()\nPASS : UiTests::reducedMotionStopsDecoration()\nPASS : UiTests::manualPassDoesNotAuthorizeMigration()\nPASS : UiTests::cleanupTestCase()\nTotals: 7 passed, 0 failed, 0 skipped, 0 blacklisted, 1219ms\n********* Finished testing of UiTests *********\n", + "stderr": "" + }, + { + "kind": "application_demo", + "scale": "2", + "exit_code": 0, + "stdout": "", + "stderr": "" + }, + { + "kind": "ui_suite", + "scale": "2", + "exit_code": 0, + "stdout": "********* Start testing of UiTests *********\nConfig: Using QtTest library 5.15.19, Qt 5.15.19 (x86_64-little_endian-lp64 shared (dynamic) release build; by GCC 16.2.0), kali 2026.3\nPASS : UiTests::initTestCase()\nPASS : UiTests::explicitDemoAndKeyboard()\nPASS : UiTests::importedTooltipEscaped()\nPASS : UiTests::narrowPagesKeepActionsReachable()\nPASS : UiTests::reducedMotionStopsDecoration()\nPASS : UiTests::manualPassDoesNotAuthorizeMigration()\nPASS : UiTests::cleanupTestCase()\nTotals: 7 passed, 0 failed, 0 skipped, 0 blacklisted, 1491ms\n********* Finished testing of UiTests *********\n", + "stderr": "" + } + ], + "astra_validated": false, + "x11_desktop_validated": false, + "screen_reader_validated": false +} diff --git a/docs/gui-xcb-result.json b/docs/gui-xcb-result.json new file mode 100644 index 0000000..0c64390 --- /dev/null +++ b/docs/gui-xcb-result.json @@ -0,0 +1,19 @@ +{ + "command": [ + "xvfb-run", + "-a", + "-s", + "-screen 0 3200x2000x24 -nolisten tcp", + "/home/scandalist/migration_ALD_pro/build/ald-transition-console", + "--project", + "/tmp/ald-xcb-xjk1lymr/project", + "--demo", + "--smoke-test", + "--capture", + "/home/scandalist/migration_ALD_pro/artifacts/screenshots/overview-xcb.png" + ], + "exit_code": 1, + "stdout": "", + "stderr": "qt.qpa.xcb: could not connect to display :109\nqt.qpa.plugin: Could not load the Qt platform plugin \"xcb\" in \"\" even though it was found.\nThis application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.\n\nAvailable platform plugins are: eglfs, linuxfb, minimal, minimalegl, offscreen, vnc, wayland-egl, wayland, wayland-xcomposite-egl, wayland-xcomposite-glx, xcb.\n\nAborted (core dumped)\n", + "diagnostic": "xdpyinfo also failed: Xvfb cannot create local/unix listening sockets in this environment. No missing libqxcb linked dependencies were found." +} diff --git a/docs/implementation-status.md b/docs/implementation-status.md new file mode 100644 index 0000000..419056d --- /dev/null +++ b/docs/implementation-status.md @@ -0,0 +1,33 @@ +# Implementation status and remaining work + +This is a source development preview, **not the first accepted production +release**. Missing Astra/Windows VMs block laboratory validation, not the +portable core. The C++/Qt application and helper now compile on Kali; all four CTest suites +and Qt offscreen scale checks pass. This does not validate Astra or Windows. No real infrastructure was changed. + +| Phase | Delivered source/data | Remaining acceptance | +|---|---|---| +| 0 | Requirements snapshot, feasibility, matrix, nullable lock, sources, adapter/access contracts | Exact delivery artifacts, real hashes and supported VM lock | +| 1 | CMake, domain records, closed JSON schemas, bounded validator, SQLite migrations/private projects | Disk-full and interrupted multi-document transaction fault injection | +| 2 | Allowlist, async read-only runner, dependency/error policies, redaction, journal, shutdown, authenticated temporary read-only helper | Helper IPC lab and privileged lifecycle validation; no mutating privileged adapter enabled | +| 3 | Local native probes, fixed Windows facts/AD inventory, strict SSH, guided access and restoration records | Actual Astra/Windows operation validation; DNS endpoints/resources/protection/locks still need fuller discovery | +| 4 | Russian native ten-page shell, model-backed tables, explicit demo, reduced motion, selectable text, keyboard controls | Offscreen screenshots and narrow navigation checked at 100/150/200%; real desktop and screen-reader inspection pending | +| 5 | Version-specific interactive initialization contract and conservative planner | Native delivery/help, namespace procedure, lab promotion/postconditions; no automatic installer | +| 6 | Import, stable identity map, item/scope gap coverage, ten-phase blocked plan, cutover preview | Real category collectors beyond directory, supported migration operations, continuity and AD independence | +| 7 | Guided domain paths, profile comparison/ownership conflicts, separate Windows guidance | Validated write/read adapters, authoritative/resultant policy collection and per-setting semantic maps | +| 8 | All 40 source cards, two specific observation paths, Astra/Windows catalogs, compliance separation | Original FSTEC artifact, version/role maps, verified remediation/restoration paths | +| 9 | Debian template/release gate, operator/recovery guide, unit sources, portable and asset checks | Astra build/install/uninstall; package artifact; all integration results | + +Additional limits: data bundles are staged with digest verification only, +signature verification is not implemented; no executable bundles are imported. +No generalized WinRM adapter, continuous monitoring, automatic updates or +telemetry exists. GUI-owned runtime work is read-only and serial. No imported +source, checkbox, waiver or editable manifest enables mutation. Compiled +capabilities remain UNKNOWN/DOCUMENTED_NOT_TESTED until a separately reviewed +implementation and evidence establish otherwise. + +The instruction list contains seventeen useful checks with history/export, +not complete automated acceptance of all enterprise dependencies. Hardware, +resource thresholds, package-lock acquisition, DNS forward/reverse/service +queries, complete GPO/ACL/PKI/DHCP collectors and typed mutations are unfinished +features, not silently counted as absent dependencies or passed checks. diff --git a/docs/interface-review.md b/docs/interface-review.md new file mode 100644 index 0000000..477d111 --- /dev/null +++ b/docs/interface-review.md @@ -0,0 +1,52 @@ +# Native interface build and DEMO review + +Scope: explicit synthetic DEMO startup → keyboard navigation through ten pages +→ checklist presentation → normal shutdown. Live mutation/error workflows and +screen-reader interaction are outside this rendered review. Stack: Qt Widgets/QPainter/QSS; the owner specification in +`requirements.md` defines layout, colors and motion. The `dedsec-motion` visual +language uses original geometry, with no third-party artwork or video runtime. +`better-interface` and its six domain instructions guided source inspection. + +| Domain | Evidence inspected | Result | +|---|---|---| +| Accessibility | MainWindow, WorkflowPage, ChecklistPage, PixelDecoration, UI test source | Native names/plain text, keyboard navigation and reduced-motion tests pass; screen reader not verified | +| Layout | Splitters, FlowLayout, scroll forms, collapsible diagnostics | Actual 1024×768 action containment tested at 100/150/200%; sidebar label wrapping corrected | +| Writing | Russian workflow titles, blockers, observations, recovery instructions | Human/machine history separated; raw native details remain expandable | +| Typography | Theme/QSS, deterministic DejaVu fonts | Actual Cyrillic screenshots inspected at normal/high scale | +| Colors | Central tokens, focus and primary controls | Declared contrast passes; inspected DEMO states remain readable; high-contrast theme pending | +| UI | Buttons, tables, model refresh, selection/history and shutdown | Qt UI suite passes at three scales; no live state claimed | + +## Source findings addressed + +| Severity | Domain | Location | Before | After | Why | +|---|---|---|---|---|---| +| HIGH | Layout | `src/ui/pages/WorkflowPage.cpp:11` | Fixed action row could clip at narrow width | Wrapping FlowLayout | Primary actions must remain reachable | +| HIGH | UI | `src/ui/models/JsonTableModel.cpp:30` | Imported tooltip text could be interpreted as rich text | Escape markup | Inventory content must stay literal | +| MEDIUM | Writing | `src/ui/pages/ChecklistPage.cpp` | Results visible only as raw JSON | Separate method/result/operator/time table, expandable full record | Operator must distinguish human checks from automatic evidence | +| MEDIUM | UI | `src/ui/pages/WorkflowPage.cpp` | Row-number restoration could select another object after refresh | Restore stable row identity | A refresh must not change the apparent subject | +| MEDIUM | Colors | `resources/styles/dedsec.qss` | Primary fill and focus indicator used the same accent | Distinct focused fill and 2 px accent outline | Keyboard focus needs visible contrast | + +## Verification + +Passed: `python3 tools/check_theme.py`, the four CTest suites and +`python3 tools/check_gui.py`. The actual C++ executable captures 1440×900 logical +screenshots and exits. Qt tests capture all ten pages at 1024×768, exercise +keyboard navigation, reduced motion and capability gates at scale 1, 1.5 and 2. +Image dimensions match the requested scaling. The screenshots are Qt renders, +not web or Python recreations. + +Visual inspection covered overview, access, blocked migration, checklist, +initialization and restoration at normal/high scale. It revealed truncated +sidebar labels; `NavigationList` now measures wrapping and keeps full labels. +The port editor now meets the height baseline and uses direct numeric input. + +Evidence: [GUI smoke results](gui-smoke-results.json), +[screenshots](../artifacts/screenshots/), and [test results](test-results.md). + +**Not verified:** actual X11 desktop (Xvfb could not bind local sockets), desktop +focus/assistive-technology behavior, screen-reader announcements, all live error +states, high-contrast themes and selection/scrolling under remote updates. + +**Verdict: Approve for the inspected offscreen DEMO scope.** This is not approval +of a production administration release; the excluded runtime and laboratory +checks remain open. diff --git a/docs/lab-manual.ru.md b/docs/lab-manual.ru.md new file mode 100644 index 0000000..13e2a58 --- /dev/null +++ b/docs/lab-manual.ru.md @@ -0,0 +1,386 @@ +# Ручная подготовка тестового MS AD для миграции в ALD Pro + +Документ предназначен только для изолированного тестового домена. Все объекты +создаются вручную через стандартные оснастки Windows. Не изменяйте `Default +Domain Policy`, `Default Domain Controllers Policy` и не добавляйте тестовые +группы в `Domain Admins`.таак + +## 1. Структура OU + +Откройте `dsa.msc`. В домене `corp.local` создайте корневой OU: + +```text +ALD-LAB +``` + +Внутри него создайте: + +```text +ALD-LAB +├── Users +├── Groups +├── Workstations +├── Servers +├── ServiceAccounts +├── Applications +└── Disabled +``` + +Все тестовые объекты должны находиться только внутри `ALD-LAB`. + +## 2. Тестовые пользователи + +В `OU=Users,OU=ALD-LAB` создайте: + +| Логин | Имя | Назначение | +|---|---|---| +| `ald.alice` | Alice Test | обычный пользователь | +| `ald.bob` | Bob Test | пользователь Helpdesk | +| `ald.carol` | Carol Test | ИТ-администратор | +| `ald.eve.priv` | Eve Privileged | привилегированная тестовая учетная запись | + +В `OU=Disabled,OU=ALD-LAB` создайте: + +```text +ald.dave.disabled +``` + +После создания отключите эту учетную запись. + +В `OU=ServiceAccounts,OU=ALD-LAB` создайте: + +```text +svc_ald_app +``` + +Для сервисной учетной записи в лаборатории можно включить `Password never +expires`, но не использовать её как интерактивную администраторскую учетную +запись. + +Для всех пользователей задайте один временный пароль стенда. Не используйте +его вне лаборатории. + +## 3. Тестовые группы + +В `OU=Groups,OU=ALD-LAB` создайте следующие группы. Все группы должны быть +типа `Security`. + +Глобальные: + +```text +GG-ALD-LAB-Employees +GG-ALD-LAB-IT +GG-ALD-LAB-Helpdesk +GG-ALD-LAB-AppUsers +GG-ALD-LAB-Privileged +``` + +Domain Local: + +```text +DL-ALD-LAB-File-Read +DL-ALD-LAB-File-Modify +``` + +Universal: + +```text +UG-ALD-LAB-AllTestUsers +``` + +### Членство + +```text +GG-ALD-LAB-Employees: + ald.alice + ald.bob + ald.carol + ald.dave.disabled + +GG-ALD-LAB-IT: + ald.carol + GG-ALD-LAB-Helpdesk + GG-ALD-LAB-Privileged + +GG-ALD-LAB-Helpdesk: + ald.bob + +GG-ALD-LAB-AppUsers: + ald.alice + ald.bob + +GG-ALD-LAB-Privileged: + ald.eve.priv + +DL-ALD-LAB-File-Read: + GG-ALD-LAB-Employees + +DL-ALD-LAB-File-Modify: + GG-ALD-LAB-IT + +UG-ALD-LAB-AllTestUsers: + GG-ALD-LAB-Employees + GG-ALD-LAB-IT +``` + +Такая схема проверяет прямое и вложенное членство, разные типы групп, +перенос групповых полномочий и преобразование ACL. + +## 4. Компьютеры + +В `OU=Workstations,OU=ALD-LAB` создайте: + +```text +WS-ALD-001 +WS-ALD-002 +``` + +В `OU=Servers,OU=ALD-LAB` создайте: + +```text +SRV-ALD-001 +``` + +Это предварительно созданные компьютерные объекты. Позже один Windows-клиент +можно реально ввести в домен и проверить применение GPO. + +## 5. Тестовые GPO + +Откройте `gpmc.msc` и создайте: + +```text +GPO-ALD-LAB-UI +GPO-ALD-LAB-Computer-Baseline +GPO-ALD-LAB-Application-Access +GPO-ALD-LAB-Disabled-Example +``` + +Не связывайте эти GPO с корнем домена. + +### GPO-ALD-LAB-UI + +Свяжите только с `OU=Users,OU=ALD-LAB`. + +Включите: + +```text +User Configuration + → Policies + → Administrative Templates + → Control Panel + → Prohibit access to Control Panel and PC settings +``` + +Для дополнительного маркера создайте Registry Preference: + +```text +User Configuration + → Preferences + → Windows Settings + → Registry +``` + +Создайте: + +```text +Hive: HKEY_CURRENT_USER +Key Path: Software\ALD-LAB +Value name: UIProfile +Type: REG_SZ +Value: ALD-LAB-Blue +``` + +И второе значение: + +```text +Value name: MigrationMarker +Type: REG_SZ +Value: USER-GPO-APPLIED +``` + +### GPO-ALD-LAB-Computer-Baseline + +Свяжите с `OU=Workstations,OU=ALD-LAB`. + +Создайте Registry Preference: + +```text +Hive: HKEY_LOCAL_MACHINE +Key Path: Software\ALD-LAB +Value name: ComputerBaseline +Type: REG_SZ +Value: COMPUTER-GPO-APPLIED +``` + +Второе значение: + +```text +Value name: ExpectedComputerOU +Type: REG_SZ +Value: OU=Workstations,OU=ALD-LAB +``` + +### GPO-ALD-LAB-Application-Access + +Свяжите с `OU=Users,OU=ALD-LAB`. + +В Security Filtering уберите `Authenticated Users` и добавьте: + +```text +GG-ALD-LAB-AppUsers +``` + +Для группы оставьте права `Read` и `Apply group policy`. + +Добавьте значение: + +```text +Hive: HKEY_CURRENT_USER +Key Path: Software\ALD-LAB\Applications +Value name: AppAccess +Type: REG_SZ +Value: ALD-LAB-APP-ALLOWED +``` + +### GPO-ALD-LAB-Disabled-Example + +Создайте GPO, но не связывайте его ни с одной OU. Он нужен для проверки +состояния link/unlink при миграции. + +## 6. DNS-записи + +Откройте `dnsmgmt.msc`. + +В зоне `corp.local` создайте: + +```text +A: +ald-lab-app → IP тестового приложения + +CNAME: +portal-ald-lab → ald-lab-app.corp.local +``` + +Не изменяйте существующие SRV-записи Kerberos и LDAP. + +## 7. Тестовый SPN + +Для учетной записи `svc_ald_app` зарегистрируйте SPN. Замените `CORP` на +фактическое NetBIOS-имя домена: + +```cmd +setspn -S HTTP/ald-lab-app.corp.local CORP\svc_ald_app +setspn -S HTTP/ald-lab-app CORP\svc_ald_app +``` + +Проверка: + +```cmd +setspn -L CORP\svc_ald_app +``` + +Это даст тест для переноса сервисной учетной записи, SPN и Kerberos-доступа. + +## 8. Файловый ресурс и ACL + +На отдельном тестовом файловом сервере создайте: + +```text +D:\ALD-LAB-Data +``` + +Внутри создайте: + +```text +readme.txt +modify.txt +``` + +В разрешениях SMB задайте: + +```text +DL-ALD-LAB-File-Read — Read +DL-ALD-LAB-File-Modify — Change +``` + +В NTFS задайте: + +```text +DL-ALD-LAB-File-Read — Read & Execute +DL-ALD-LAB-File-Modify — Modify +``` + +Не оставляйте `Everyone` с полными правами. + +Ожидаемый результат: + +- `ald.alice` читает файлы; +- `ald.bob` изменяет файлы; +- `ald.carol` изменяет файлы; +- пользователь вне групп доступа не получает доступ. + +## 9. Проверка GPO + +На тестовом Windows-клиенте: + +1. Введите компьютер в `corp.local`. +2. Переместите его объект в `OU=Workstations,OU=ALD-LAB`. +3. Войдите пользователем `ald.alice`. +4. Выполните: + +```cmd +gpupdate /force +gpresult /r +``` + +Проверьте значения: + +```cmd +reg query HKCU\Software\ALD-LAB +reg query HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer +reg query HKLM\Software\ALD-LAB +``` + +Ожидается: + +- у Alice запрещена панель управления; +- присутствует `UIProfile`; +- присутствует `USER-GPO-APPLIED`; +- присутствует `COMPUTER-GPO-APPLIED`; +- `GPO-ALD-LAB-Application-Access` применяется Alice и Bob; +- `GPO-ALD-LAB-Disabled-Example` не применяется. + +## 10. Baseline перед миграцией + +В GPMC для каждого GPO выполните `Back Up` и сохраните резервные копии. + +Зафиксируйте: + +- дерево OU; +- пользователей и их статусы Enabled/Disabled; +- группы и вложенное членство; +- компьютеры; +- GPO и их ссылки; +- порядок ссылок и Enforced/Block Inheritance; +- Security Filtering; +- DNS A/CNAME; +- SPN; +- SMB/NTFS ACL; +- результаты входа Alice, Bob и Carol; +- результаты `gpresult`; +- результаты доступа к файловой шаре. + +## 11. Что проверяется при последующей миграции в ALD Pro + +| Объект стенда | Что проверяем в ALD Pro | +|---|---| +| OU и пользователи | перенос идентичностей и атрибутов | +| Global/Universal/Domain Local-группы | сохранение членства и вложенности | +| Отключённый пользователь | корректный статус блокировки | +| Сервисная учетная запись | замена пароля, SPN и способа запуска сервиса | +| GPO | перенос в эквивалентные политики ALD/Salt/HBAC/SUDO | +| UI-маркеры | применение политики на тестовом клиенте | +| Компьютерные объекты | повторное подключение и enrollment клиента | +| DNS A/CNAME | перенос разрешения имен и зависимостей приложений | +| SMB/NTFS ACL | преобразование SID-доступа в новую модель идентификаторов | +| `GPO-ALD-LAB-Disabled-Example` | сохранение состояния неактивной политики | diff --git a/docs/local-check-results.json b/docs/local-check-results.json new file mode 100644 index 0000000..0cf8c30 --- /dev/null +++ b/docs/local-check-results.json @@ -0,0 +1,102 @@ +{ + "schema_version": 1, + "observed_at": "2026-10-27T14:09:30.257880+00:00", + "source_digest": "18f47ca67a6ba070d4288e2a29d2c24b26d68e65ae4c7270acf6e278bd7558ed", + "checks": [ + { + "name": "data_and_manifest", + "command": [ + "/usr/bin/python3", + "tools/check_assets.py" + ], + "expected_exit": 0, + "exit_code": 0, + "stdout": "PASS: schemas, 26 resources, 23 source references, 40 cards, 17 checklist instructions, task hashes and synthetic fixtures\n", + "stderr": "", + "status": "PASS" + }, + { + "name": "declared_theme_contrast", + "command": [ + "/usr/bin/python3", + "tools/check_theme.py" + ], + "expected_exit": 0, + "exit_code": 0, + "stdout": "text/background: 17.64:1 (required 4.5:1)\ntext/panel: 16.17:1 (required 4.5:1)\nsecondary/panel: 9.25:1 (required 4.5:1)\nwarning/panel: 11.55:1 (required 4.5:1)\nbackground/accent: 12.74:1 (required 4.5:1)\naccent/panel: 11.68:1 (required 4.5:1)\naccent/elevated: 10.67:1 (required 3:1)\nPASS: declared text/focus token contrast; rendered, high-contrast-mode and screen-reader checks remain pending\n", + "stderr": "", + "status": "PASS" + }, + { + "name": "portable_rules_asan_ubsan", + "command": [ + "/usr/bin/python3", + "tools/run_portable_tests.py" + ], + "expected_exit": 0, + "exit_code": 0, + "stdout": "PASS: 40457 assertions, including 1000 seeded chunk/DAG trials\n", + "stderr": "", + "status": "PASS" + }, + { + "name": "unvalidated_release_refused", + "command": [ + "/usr/bin/python3", + "tools/verify_release_lock.py" + ], + "expected_exit": 1, + "exit_code": 1, + "stdout": "", + "stderr": "RELEASE BLOCKED: supported Astra validation incomplete; missing: os_release, os_update, kernel, architecture, compiler, cmake, qt_packages, sqlite_driver, transports, ald_packages\n", + "status": "PASS" + }, + { + "name": "qt_configure", + "command": [ + "cmake", + "-S", + ".", + "-B", + "build", + "-DCMAKE_BUILD_TYPE=Debug" + ], + "expected_exit": 0, + "exit_code": 0, + "stdout": "-- Configuring done (0.0s)\n-- Generating done (0.1s)\n-- Build files have been written to: /home/scandalist/migration_ALD_pro/build\n", + "stderr": "", + "status": "PASS" + }, + { + "name": "qt_build", + "command": [ + "cmake", + "--build", + "build", + "--parallel", + "2" + ], + "expected_exit": 0, + "exit_code": 0, + "stdout": "[ 2%] Built target ald_rules\n[ 2%] Built target ald-transition-executor_autogen_timestamp_deps\n[ 4%] Built target test_rules\n[ 4%] Built target ald_core_autogen_timestamp_deps\n[ 5%] Built target ald-transition-executor_autogen\n[ 6%] Built target ald_core_autogen\n[ 12%] Built target ald-transition-executor\n[ 55%] Built target ald_core\n[ 55%] Built target ald_ui_autogen_timestamp_deps\n[ 56%] Automatic MOC for target ald_ui\n[ 56%] Built target ald_ui_autogen\n[ 57%] Building CXX object CMakeFiles/ald_ui.dir/src/ui/pages/WorkflowPage.cpp.o\n[ 58%] Linking CXX static library libald_ui.a\n[ 77%] Built target ald_ui\n[ 77%] Built target ald-transition-console_autogen_timestamp_deps\n[ 77%] Built target test_storage_autogen_timestamp_deps\n[ 77%] Built target test_runtime_autogen_timestamp_deps\n[ 77%] Built target test_ui_autogen_timestamp_deps\n[ 78%] Built target ald-transition-console_autogen\n[ 79%] Built target test_storage_autogen\n[ 80%] Built target test_runtime_autogen\n[ 82%] Built target test_ui_autogen\n[ 84%] Linking CXX executable ald-transition-console\n[ 84%] Linking CXX executable test_storage\n[ 87%] Built target test_storage\n[ 88%] Linking CXX executable test_runtime\n[ 92%] Built target ald-transition-console\n[ 93%] Linking CXX executable test_ui\n[ 96%] Built target test_runtime\n[100%] Built target test_ui\n", + "stderr": "", + "status": "PASS" + }, + { + "name": "qt_tests", + "command": [ + "ctest", + "--output-on-failure" + ], + "expected_exit": 0, + "exit_code": 0, + "stdout": "Test project /home/scandalist/migration_ALD_pro/build\n Start 1: rules\n1/4 Test #1: rules ............................ Passed 0.12 sec\n Start 2: storage\n2/4 Test #2: storage .......................... Passed 0.05 sec\n Start 3: runtime\n3/4 Test #3: runtime .......................... Passed 0.05 sec\n Start 4: ui\n4/4 Test #4: ui ............................... Passed 0.78 sec\n\n100% tests passed, 0 tests failed out of 4\n\nTotal Test time (real) = 1.00 sec\n", + "stderr": "", + "status": "PASS" + } + ], + "qt_validation": "PASS", + "astra_lab": "NOT_AVAILABLE", + "windows_lab": "NOT_AVAILABLE", + "release_validated": false +} diff --git a/docs/native-adapter-contracts.md b/docs/native-adapter-contracts.md new file mode 100644 index 0000000..a27fc3f --- /dev/null +++ b/docs/native-adapter-contracts.md @@ -0,0 +1,83 @@ +# Native adapter contracts — 0.1.0 + +All runtime operation identifiers are compiled allowlists. JSON carries data, +never executable text. ProcessRunner rejects every mutating ProcessSpec in this +preview. Schema acceptance and a user-edited capability file cannot grant root. + +| Adapter | Native execution | Limits / verification | Release state | +|---|---|---|---| +| Local OS/kernel | cat os-release; uname -r -m | Fixed files/args; bounded output; structure checks | Implemented; Astra untested | +| Packages | dpkg-query -W with fixed format | Installed status observed; ALD package versions filtered; package alone is not role | Implemented | +| Services | systemctl show fixed units | Read-only; health cannot be inferred from a stopped/installed unit | Implemented, unit-name validation pending on ALD | +| Network/time | ip -j address/route; timedatectl show; hostname -f; resolv.conf | No subnet scan, no resolver edit, no sync/restart | Implemented | +| Yama | cat /proc/sys/kernel/yama/ptrace_scope | Runtime observation only, no persistent-state or compliance PASS | Implemented | +| Windows facts | Fixed embedded discovery.ps1 over native SSH command execution | PS 5.1, CIM and optional-feature availability; JSON shape required | Implemented, Windows VMs untested | +| AD directory | Fixed embedded ad-inventory.ps1 | AD module; configured DC; fixed filter; 50000-object limit; no password attributes | Implemented, AD VM untested; incomplete total scope | +| SSH effective config | Temporary root helper, sshd -T | Global value only; Match-context not verified; no mutation | Implemented, helper IPC/runtime untested | +| ALD initialize | Documented interactive local installer | Installed help, exact delivery, same-name plan and lab required | GUIDED_NATIVE; automation disabled | +| ALD objects/settings/policies | Versioned manual/portal paths | No reverse-engineered APIs or generated-cache writes | Guided workflows; automation unimplemented | +| Windows policy writes | Separate per-build baseline | LGPO artifact and mapping not validated | UNKNOWN, no write enabled | + +## Execution and ownership + +QProcess uses absolute executables plus argument arrays, asynchronous signals, +separate output channels, bounded memory and timeouts. No shell, startDetached, +background jobs, cron, system timer, service or LAN listener is created. +Read-only child termination is scoped to the owned QProcess. No installer or +package manager is killed because neither is launched by the application. +A disconnected remote mutating operation would require reconciliation; none is +enabled. Remote read-only cancellation cannot prove the server stopped the +accepted command instantly; scripts contain no job/persistence mechanism. + +Batch scheduling is serial (including local changes); callers choose stop, +continue-independent or pause. Dependencies must have PASS before scheduling. +There is no automatic non-idempotent retry. Postcondition verifiers remain +separate from process exit. Pure decision functions support future plans, but +this build never grants production authorization from imported JSON. + +## SSH boundary + +`ssh -F /dev/null`, strict selected known_hosts, BatchMode, no forwarding, no +control master, finite timeouts. Host and user are validated; Unicode identity +values in inventory are preserved, while the current transport deliberately +rejects non-ASCII account syntax rather than transliterating it. Record this +transport limitation and use a supported manual path for such accounts. + +The remote command is a fixed PowerShell launcher and UTF-16LE/base64 encoding +of a compiled hash-checked task. Encoding is transport encoding, not encryption. +User/host/path/DN/policy values are never inserted into remote source code. +No SSH PowerShell subsystem or DefaultShell change is used. Native ssh-agent is +the only selected credential path in this adapter: already unlocked for this +session; no key material is imported or forwarded. The host key file requires +an independently verified fingerprint. SSH discovery output is not proof of +ALD-domain support. + +The AD task requires a domain-controller role, queries that node explicitly and +emits `source_domain`. Imports from domains other than `corp.local` are rejected. +The compiled remote command has a conservative 7,800-character bound; actual +Windows shell/servicing behavior remains a laboratory test. Version support for +Windows transport does not make a Windows 10 workstation an AD DC. + +Inventory DNs receive bounded syntax screening and remain opaque data. This is +not a complete RFC 4514 parser or authorization to apply them through LDAP. + +## Privileged boundary + +The non-root GUI starts only the installed fixed executor path through native +pkexec. The helper connects to a private 0700 session directory socket and +verifies SO_PEERCRED UID/PID against PKEXEC_UID and the expected GUI process. +The GUI verifies root UID and the owned pkexec PID. The request is <=16 KiB, +version 1, exact fields, fixed `ssh.effective` ID, empty parameters and the +hash of the local machine ID. The compiled dispatcher has no mutating IDs. +A single request is accepted; disconnect/timeout ends the helper. No polkit +permission file auto-grants access; the operating system requests authorization. +Only a trusted root-owned sshd binary is accepted. Lab peer-substitution and +lifecycle integration tests remain required before release. + +## Sources and limitations + +`data/sources.json`, `resources/tasks/manifest.json`, installed task hashes and +`docs/feasibility.md` are the evidence register. No source was executed as code. +Live AD inventory does not collect DNS zones, DHCP leases, file contents/ACLs, +GPO reports/SYSVOL, PKI or application bindings. Those categories remain UNKNOWN +and have human instructions. This is not a claim of complete discovery. diff --git a/docs/next-steps.ru.md b/docs/next-steps.ru.md new file mode 100644 index 0000000..9705201 --- /dev/null +++ b/docs/next-steps.ru.md @@ -0,0 +1,53 @@ +# Сборка и первый стенд + +Для следующего этапа на Astra используйте [инструкцию стенда](astra-lab.ru.md) +и `python3 tools/build_astra_lab.py`. Команды ниже описывают уже выполненную +сборку на машине разработки; переносить их пакеты на Astra не следует. + +Сборка на текущей Kali выполнена: `build/ald-transition-console` и +`build/ald-transition-executor`. Все четыре набора CTest проходят. GUI проверен +через Qt offscreen при масштабе 100/150/200%; запуск в обычном рабочем столе +и испытания Astra/Windows остаются следующими этапами. Подготовленного +стенда пока нет. Ниже — команды для воспроизведения сборки; пакеты уже установлены. + +```sh +sudo apt install cmake qtbase5-dev qtbase5-dev-tools qt5-qmake +cd /home/scandalist/migration_ALD_pro +python3 tools/validate_local.py +``` + +Это команда для машины разработки. Не переносите пакеты Kali на Astra и не +обновляйте ПО КД для удовлетворения зависимостей. QSQLITE уже обнаружен в текущей +среде; его наличие и фактические версии заново проверяются при сборке. Если +репозиторий недоступен, нужны пакеты с зависимостями именно из одобренного +репозитория этой ОС, а не произвольные бинарные файлы. + +После успешной сборки: + +```sh +mkdir -m 700 /tmp/ald-console-demo +./build/ald-transition-console --project /tmp/ald-console-demo --demo +``` + +Для лабораторной валидации отдельно потребуются: + +1. Штатные установочные материалы ALSE 1.7.7 UU2 и ALD Pro 3.1.0, соответствующая + инструкция поставки, реальные подписи/контрольные суммы. Уровень защиты и + ядро сверяются с процедурой; выбранный исходный пример — Смоленск/6.1-generic. +2. Изолированный AD-стенд: один лес, один домен `corp.local`, один исходный КД. + Второй исходный КД не предполагается. Адресную сеть не заменять обходным + вариантом. Изоляция от production DNS обязательна при исследовании конфликта. +3. Целевой узел Astra и тестовые Windows 10, Server 2019, Server 2025 с законными + установочными материалами. Зафиксировать edition/build/роль каждого образа. +4. Проверенный способ AD-aware резервного копирования и репетиция восстановления + единственного КД; независимый консольный доступ к ВМ. + +Материалы поставки ALD: [документация 3.1.0](https://www.aldpro.ru/materials/3.1.0/). +Документация не заменяет установочный дистрибутив и разрешённый состав ПО КД. +Порядок испытаний — [tests/integration/README.md](../tests/integration/README.md). +Каждое изменение стенда согласуется отдельно. Чтение документации и успешный +тест GUI не разблокируют миграцию с сохранением обязательного поведения. + +В `compatibility-lock.json` оставлены `null` для реально не измеренных полей. +Заполнять их следует по результатам целевого стенда, а не копированием версий +этой Kali или ручным переключением `release_validated` ради сборки пакета. diff --git a/docs/operator-guide.ru.md b/docs/operator-guide.ru.md new file mode 100644 index 0000000..edf965c --- /dev/null +++ b/docs/operator-guide.ru.md @@ -0,0 +1,76 @@ +# Руководство оператора — предварительная версия 0.1.0 + +Программа готовит обследование, план и инструкции. Полная миграция corp.local +с сохранением обязательного поведения пока заблокирована. Эта сборка не +включает автоматические изменения инфраструктуры. Поддержка на Astra и Windows +требует испытаний на указанных в матрице версиях. + +1. Запустите GUI без root. Выберите отдельный каталог проекта с владельцем — + текущим администратором и правами 0700. SQLite и журнал имеют закрытые права. + Второй писатель того же проекта не допускается. Режим проекта неизменяем: + для DEMO и LIVE нужны разные каталоги. +2. Для ознакомления явно включите DEMO. Объекты ALD-LAB и адреса 192.0.2.x + синтетические. В DEMO нативные операции отключены. Ошибка live-подключения + никогда не переключает режим на demo. +3. В LIVE сначала выполняются локальные read-only пробы. Нажмите «Обновить + наблюдения» для нового сбора. Выберите поведение при ошибке. Откройте строку + результата: фактическое значение, время, причина и следующий шаг. Установка + пакета сама не подтверждает роль. Для частичного/деградировавшего КД чистая + инициализация не разрешается. +4. На странице доступа выберите реальный конкретный Windows FQDN, учётную + запись и проверенный known_hosts. SSH и агент с разрешённым ключом должны + уже существовать. Приложение не принимает пароль. При отсутствии канала + выполните согласованную ручную подготовку через консоль, записав каждое + изменение. Не отключайте UAC, firewall, проверку сертификатов или host keys. +5. «Проверить Windows» собирает версию и prerequisites. «Обследовать каталог + AD» читает только ограниченную область directory objects выбранного КД. + Неохваченные категории остаются видимыми. Альтернатива — локальный запуск + поставленного фиксированного PowerShell task и импорт его UTF-8 JSON. + Право запуска на реальной машине подтверждается оператором отдельно. +6. В миграции изучите scope, объекты, карту зависимостей и обязательные + требования. Совпадение corp.local, логинов или числа объектов не сохраняет + идентичность домена. Стабильные ключи карты — source-system + GUID + SID. + Ручная отметка не разблокирует unsupported/unknown capability. +7. Инициализация содержит документированный интерактивный шаблон и условия. + Плейсхолдеры ``, ``, `` не являются + готовыми значениями. Не запускайте его при текущей блокировке namespace, + неизвестных пакетах или на существующем КД. Сам GUI его не запускает. +8. Профили можно импортировать как данные для сравнения и проверки владельцев. + Запись настроек ALD/Windows выполняется по штатным ручным путям; приложение + не реализует неподтверждённый API. 40 карточек Linux не означают 40 готовых + исправлений и не дают заключения об аттестации. +9. В «Проверки» выберите пункт, выполните его инструкцию, укажите область, + своё имя, результат и примечание без секретов. PASS/FAIL — явные ручные + результаты. «Не применимо» требует причины и не превращается в PASS. + Автоматические записи имеют method=AUTOMATIC, ручные — HUMAN. Новая + инвентаризация, карта, профиль, редакция или запуск делают прежнюю запись + STALE; история не удаляется. HTML/JSON экспорт содержит инструкции и историю. +10. В журнале фильтруйте по узлу/операции/уровню/времени/запуску. Нет процентов + прогресса без данных нативной утилиты. Ошибка инструмента не означает + успешное изменение. При паузе продолжение не пропускает зависимости. +11. В «Завершение…» запишите и сверьте временный доступ. При конфликте или + недоступности узла остаётся обязательство ручного восстановления. + Канал закрывается последним; существующие чужие правила сохраняются. + После остановки собственных процессов GUI показывает сводку перед выходом. + Если отменить выход, сеанс остаётся для просмотра: новые операции после + повторного открытия. После reboot GUI запускается вручную. + +Навигация доступна с клавиатуры: Tab/Shift+Tab, стрелки в списке разделов, +Alt+1…Alt+9. «Без анимации» сохраняется в обычных пользовательских настройках. +Раскрываемый журнал можно изменить по высоте разделителем. При 1024×768 +доступна кнопка скрытия боковой панели. Отрисовка Qt offscreen проверена при масштабе 100/150/200%; реальный +рабочий стол и скринридер ещё не проверены. См. отчёт испытаний. + +Без интернета доступны сохранённый проект, проверки, планирование и операции +с уже имеющимися инструментами. Подключение к AD/ALD требует локальной сети. +Отсутствующие пакеты/optional features требуют подходящего одобренного носителя +или репозитория; приложение ничего не скачивает и не обновляет скрытно. + +Offline data bundle — JSON по `schemas/offline-bundle.schema.json`, только +inventory/profile/checklist/source JSON, относительные безопасные пути, версии, +происхождение и реальные SHA-256. Максимальный вложенный документ — около +48 KiB (base64 до 65536 символов); большие инвентаризации импортируйте прямо. +Файлы с кодом, архивы и установочные пакеты не принимаются. Хэши проверяются, +подпись издателя остаётся NOT_VERIFIED; содержимое сохраняется для рассмотрения, +но не меняет принятый профиль. Сверить подпись одобренным штатным инструментом +и внести новое решение владельца — отдельные действия. diff --git a/docs/recovery-guide.ru.md b/docs/recovery-guide.ru.md new file mode 100644 index 0000000..c534f0d --- /dev/null +++ b/docs/recovery-guide.ru.md @@ -0,0 +1,40 @@ +# Восстановление сеанса + +Это руководство касается собственного состояния приложения. Восстановление +AD/ALD требует документации точной поставки и отдельного испытанного плана. + +При ошибке сохранения новые операции блокируются. Не считайте результат +сохранённым, даже если нативная команда успела завершиться. Проверьте свободное +место, права проекта и состояние диска; после закрытия сверяйте фактическое +состояние и журнал. Запись RECOVERY_REQUIRED создаётся только если SQLite ещё +позволяет запись. Автоматического исправления повреждённой базы нет. + +После разрыва SSH локальный процесс может закончиться раньше принятой удалённой +команды. Сводка выхода отмечает эту неопределённость; проверьте целевой узел +штатными средствами. Приложение не устанавливает фонового агента для такой проверки. + +- **Программа закрылась во время пробы.** Откройте тот же защищённый проект. + RUNNING/PREFLIGHT/PAUSED/VERIFYING/CLEANUP переводятся в RECOVERY_REQUIRED. + Ничего автоматически не повторяется. Сверьте эффект по штатным инструментам. +- **Потеря SSH.** Локальное завершение ssh не доказывает мгновенное завершение + принятой удалённой команды. В поставленных задачах нет фоновых заданий. + Повторный сбор запускайте явно, после проверки состояния канала. +- **Потеря канала после ручного изменения.** Используйте сохранённую инструкцию + через локальную консоль. Не отмечайте очистку успешной по timeout или exit=0. +- **Конфликт восстановления.** Сравните ресурс с прежним и внесённым состоянием. + Если его изменил другой администратор, сохраните новое состояние и согласуйте + отдельное решение. Автоматическое перезаписывание запрещено. +- **Ошибка SQLite / заполненный диск.** Остановите запуск новых операций. + Сохраните копию закрытого каталога проекта по принятой политике резервирования. + Не удаляйте lock-файл при работающем писателе и не правьте схему вручную. + Более новая версия schema блокирует старый клиент вместо отката схемы. +- **Частичный ALD.** Не стирайте конфигурацию и не повторяйте продвижение. + Сохраните редактированный журнал без секретов, установленные версии и факты. + Восстанавливайте по руководству именно этой версии и проверенному backup. +- **Yama ptrace_scope=3.** Запись меньшего значения в текущем сеансе ядра не + является откатом. Нужны проверка persistent конфигурации и согласованная + перезагрузка по процедуре конкретной Astra. Приложение этот параметр не пишет. + +Никакого service/timer/cron или агента возобновления нет. Пока GUI закрыт, +оно не доставляет политики, не проверяет дрейф и не исправляет доступ. Штатные +службы и ранее применённые постоянные настройки продолжают работать. diff --git a/docs/requirements.md b/docs/requirements.md new file mode 100644 index 0000000..88f063f --- /dev/null +++ b/docs/requirements.md @@ -0,0 +1,780 @@ +# Role & Objective + +You are a senior systems architect, C++/Qt desktop engineer, Astra Linux and ALD Pro administrator, Windows infrastructure engineer, and migration verification engineer. + +Build **ALD Transition Console**, a Russian-language desktop application that runs on the Astra Linux machine that is, or will become, an ALD Pro domain controller. It assists with discovery, supported initial deployment, Microsoft Active Directory migration, operational configuration, policy management, and subsequent hardening. + +This is an operational administration application. Implement real supported integrations and explicit, useful workflows for capabilities that cannot be automated. Do not produce a decorative dashboard with simulated success states. + +The owner's agreed requirements are: + +1. Target ALD Pro **3.1.0** and the Astra Linux SE **1.7.x** family, using an explicit tested compatibility matrix. +2. Preserve the domain name **corp.local** and the existing IP network. Do not substitute a differently named target domain or require a different subnet as an unapproved workaround. +3. Ultimately remove Microsoft AD. The intended user experience preserves existing logins, passwords, profiles, data, permissions, application access, and policy outcomes. Treat these as separate acceptance requirements, not as an assumed consequence of copying directory objects. +4. Inventory and migrate everything for which a supported, verified migration path exists. Every other discovered dependency must remain visible with its impact and unresolved status. +5. Support Windows 10, Windows Server 2019, and Windows Server 2025 as explicitly versioned source/managed-host targets. Management connectivity, directory migration, and Windows domain integration are separate capabilities. +6. The initial laboratory has one AD forest, one AD domain, and one AD DC. It also needs the Astra target and suitable test clients. Do not assume a second source DC exists. +7. A planned interruption is acceptable only after its scope and recovery plan are shown and the operator authorizes that particular change window. +8. Deliver initial deployment and migration first. Deliver general configuration and policies next, then hardening. +9. The application and its temporary executor run on the ALD node. When the operator finishes and closes the application, its own processes stop. Existing domain services and persistent client settings continue. +10. Prefer vendor-supported/native tools. Explain prerequisite access changes and how to restore them, so temporary administrative access is not accidentally left open. +11. Internet access is optional. Explain precisely which operations are unavailable without internet or local installation media. +12. The operator selects the batch error policy. Final validation is an instructional checklist with explicit human checkmarks and separately recorded automatic evidence. +13. Use the **dedsec-motion** skill's visual language, adapted for a readable administration interface. + +## Non-negotiable feasibility rule + +The requested end state is an objective, not an established product capability. Do not claim that ALD Pro 3.1.0 is an AD DS replica, that it can receive FSMO roles, or that reusing corp.local preserves domain identity, SIDs, computer trust, Windows profiles, or GPO behavior. + +Before allowing a migration plan to change production state, establish a documented, version-specific path for the same-name transition and all mandatory retained behavior. If a mandatory path is unsupported or unverified, return a **blocked migration plan**, explain the exact dependency, and continue building useful discovery, planning, configuration, and checklist functionality. Do not silently weaken the owner's requirements. Do not implement an unsupported replacement protocol to make the UI appear complete. + +No undocumented feature, placeholder integration, successful process exit, or manual checkbox may satisfy this feasibility gate. A deliberate change to the owner's target requirements creates a new version of the plan; it is not an ordinary exception checkbox. + +# Constraints & Tech Stack + +## Desktop and runtime + +Use the following stack: + +| Layer | Required choice | +|---|---| +| Application language | C++17 | +| GUI framework | Qt 5.15, using the Qt 5.15.2 API baseline and compatible Astra-maintained package revisions | +| Qt modules | Core, Gui, Widgets, Network, Sql; Test for tests | +| Build system | CMake, minimum language version 3.13; pin the actual tested build-tool package revision | +| Local state | SQLite through Qt SQL, transactions, explicit schema migrations, no database server | +| Data interchange | UTF-8 JSON, schema version 1, explicit validation of required fields and enums | +| Linux/native execution | QProcess with executable and argument arrays; no interpolated shell command strings | +| Default remote transport | System OpenSSH client, when supported and explicitly prepared on the target | +| Windows execution | Fixed, reviewed native PowerShell tasks over OpenSSH command execution; Windows PowerShell 5.1-compatible syntax | +| Additional transport | Optional WinRM adapter only through a verified existing implementation with locked dependencies; do not invent a WinRM implementation | +| Packaging | Debian package built against the supported Astra baseline; no installation-time execution of migration or hardening | +| Interface language | Russian; developer documentation and identifiers in English | +| Distribution mode | Local desktop application; no mandatory web server, browser, cloud backend, or telemetry | + +Do not replace this with Electron, Qt WebEngine, a React application, Kubernetes, AWX, or an always-on Astra Automation Controller. Do not install Node.js, Chromium, ffmpeg, or the motion-rendering toolchain on the domain controller for decorative effects. + +Qt 5.15 packages appear in Astra's published package information, but the exact package revisions for the target installation must still be inspected. Before producing a deployable package, create `docs/compatibility-lock.json` containing the actual OS release/update, kernel, architecture, compiler, CMake, Qt package revisions, SQLite driver, transport executables, and ALD packages used in validation. Never put an invented package revision or digest in that file. + +Use **ALD Pro 3.1.0 + ALSE 1.7.7 UU2**, with the kernel and protection level required by the matching vendor installation procedure, as the first laboratory baseline. The vendor course uses 6.1-generic and Smolensk for that example. This does not prove support for every ALSE 1.7.x release. Separate: + +- ability to run the GUI; +- support for installing/running the ALD controller; +- support for managing a client; +- support for each migration and hardening action. + +Never upgrade Astra, ALD Pro, the system Python, Qt, or security components automatically to satisfy this application's dependencies. Do not treat dependency isolation as proof of vendor support for additional software on a DC. Identify that deployment constraint explicitly in the compatibility report. + +Windows transport discovery must record OS edition, build, role, PowerShell version, and available optional features. Microsoft's in-box OpenSSH guidance covers Windows 10 build 1809 and later and Server 2019 onward; verify the actual feature and servicing prerequisites on each machine. This is not evidence that ALD Pro 3.1.0 supports every Windows domain-integration scenario. + +Use native OpenSSH command execution to launch Windows PowerShell tasks. Do not confuse that with the PowerShell SSH-remoting subsystem, whose prerequisites differ. Do not globally change the Windows default shell unless the validated adapter requires it and the change is recorded for restoration. + +## Privilege and lifecycle constraints + +The GUI is not a root process. Use a small, temporary, separately authorized native executor for allowlisted operations that genuinely need elevated privileges. Validate peer identity, operation IDs, typed parameters, target binding, and plan authorization at the privilege boundary. A user-editable rule file must never grant arbitrary root execution. + +Do not create an always-on service, cron entry, persistent OS timer, Windows scheduled task, or custom persistent agent. Ordinary in-process Qt timers are allowed while the application is running. Use per-session private IPC; do not expose an application listening port on the LAN. Avoid `startDetached` for operations owned by the application. + +Installed application files and protected logs remain between sessions. Passwords and private credentials do not belong in the project database, command arguments, process environment dumps, logs, screenshots, or exported checklists. Where persistent secrets are operationally unavoidable, use an explicitly selected native credential mechanism and document its lifetime; do not implement custom cryptography. + +The prompt author has not authorized changes to any real infrastructure. Build and test locally. Real infrastructure mutation requires the operator's explicit approval of a concrete plan inside the application or an explicit instruction in the development session. + +# SECTION 1: ASSETS & DATA + +## 1.1 Existing project material + +The current project root is `/home/scandalist/ALD_pro`. Read these if present: + +- `ALD-PRO-GUI-ARCHITECTURE.md`; +- `ALD-PRO-GUI-FSTEC-REQUIREMENTS.md`; +- `MS-AD-LAB-MANUAL.md`; +- `ald-pro-deploy-migrate/SKILL.md` and its referenced research; +- `research/module02.md` and `research/module03-migration.md`. + +These are research and design inputs, not proof that a command is valid for ALD Pro 3.1.0. Several research documents discuss newer product versions. Never copy a 3.2/3.3-only command or capability into the 3.1 adapter without independent 3.1 evidence. + +If earlier design notes conflict with this prompt, use the owner's latest requirements represented here. In particular, temporary application-created access must have an explicit restoration workflow; an existing unrelated SSH or WinRM deployment must be preserved. + +## 1.2 Source catalog + +Create a versioned source catalog. The following are exact starting URLs, not permission to scrape an entire domain or infer unpublished APIs: + +| Source ID | URL | Intended use | +|---|---|---| +| ALD31_ROOT | [ALD 3.1 documentation](https://www.aldpro.ru/materials/3.1.0/) | Find the documentation matching the installed delivery | +| ALD_DEPLOY_COURSE | [Deployment course](https://www.aldpro.ru/professional/ALD_Pro_Module_02/ALD_Pro_deployment.html) | Deployment explanation and initial laboratory baseline | +| ALD_DIRECTORY_COURSE | [Directory course](https://www.aldpro.ru/professional/ALD_Pro_Module_04/ALD_directory_services.html) | Directory concepts and documented administration | +| ALD_POLICIES_COURSE | [Policy course](https://www.aldpro.ru/professional/ALD_Pro_Module_06b/ALD_Pro_group_policy.html) | Policy lifecycle and diagnostic concepts | +| ALD_MIGRATION_COURSE | [Migration course](https://www.aldpro.ru/professional/ALD_Pro_Module_09/ALD_Pro_migration_hybrid_deployment.html) | Migration scenarios and application dependencies | +| ALD_BACKUP_COURSE | [Backup course](https://www.aldpro.ru/professional/ALD_Pro_Module_10/ALD_Pro_backup.html) | Backup and recovery research | +| FSTEC_LINUX_2022 | [Original publication](https://fstec.ru/dokumenty/vse-dokumenty/spetsialnye-normativnye-dokumenty/metodicheskij-dokument-ot-25-dekabrya-2022-g) | Original Linux hardening recommendations | +| FSTEC_TEXT_MIRROR | [Text reproduction](https://legalacts.ru/doc/metodicheskii-dokument-rekomendatsii-po-bezopasnoi-nastroike-operatsionnykh-sistem-linux/) | Provisional text reproduction, not a verified original artifact | +| ASTRA_HARDENING | [Role documentation](https://docs.astra-automation.ru/2.1/solutions/protection/fstec/) | Optional role research, not an ALSE 1.7 compatibility guarantee | +| ASTRA_ROLE_INTRODUCTION | [Role release notes](https://docs.astra-automation.ru/1.2/releases/release-1.2/upd2/) | Original role scope and preview status | +| ASTRA_QT_PACKAGES | [Astra package information](https://wiki.astralinux.ru/spaces/flyingpdf/pdfpageexport.action?pageId=153490669) | Evidence of the Qt 5.15 package family, not the current target package lock | +| MS_OPENSSH | [Native OpenSSH guidance](https://learn.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse) | Native Windows transport prerequisites | +| MS_SCT | [Security Compliance Toolkit](https://learn.microsoft.com/en-us/windows/security/operating-system-security/device-management/windows-security-configuration-framework/security-compliance-toolkit-10) | LGPO and policy comparison tools | +| MS_SID | [Security identifiers](https://learn.microsoft.com/en-us/windows-server/identity/ad-ds/manage/understand-security-identifiers) | Identity and ACL semantics | +| QT_PROCESS | [Qt QProcess](https://doc.qt.io/archives/qt-5.15/qprocess.html) | Process execution API; use only APIs available in the selected baseline | +| KERNEL_YAMA | [Kernel Yama documentation](https://docs.kernel.org/admin-guide/LSM/Yama.html) | Example of a setting with restricted runtime reversibility | + +The original FSTEC page could not be fetched during specification research. Record the original artifact hash as `null`, with verification state `pending_original`. Never manufacture a hash, publication status, or claim that an inaccessible page was reviewed. + +For each source store `id`, `url`, `title`, `product_version`, `section`, `retrieved_at`, `artifact_sha256`, `verification_state`, and `notes`. Retrieval time is not publication time. Course pages are mutable; freeze the relevant evidence for a released adapter. + +Download software only from the approved vendor distribution channel. Resolve release assets, versions, signatures, and digests before use. Do not use `latest` release URLs, unsigned arbitrary binaries, or `curl | sh` installation patterns. + +## 1.3 Visual assets + +Use the installed skill at `/home/scandalist/.codex/skills/dedsec-motion/SKILL.md`. Read its `references/style-bible.md` and relevant interface guidance. When the path is absent, discover the installed skill; the complete visual specification below is still sufficient to implement the application without the skill runtime. + +Create original decorative geometry with QPainter: 4-pixel stepped corners, short diagonal torn-label edges, simple pixel node/network motifs, and a four-tile application mark. No 3D is required. Do not import Ubisoft/Watch Dogs logos or restricted fan-kit stickers into this administration product. + +Use system DejaVu Sans for functional text and DejaVu Sans Mono for logs. Optional Onest and JetBrains Mono are permitted only when their real font files, Cyrillic coverage, redistribution licenses, versions, and hashes have been checked and bundled. No runtime font CDN. Fall back deterministically to the system fonts. + +No network-downloaded images are required. Native task payloads, schemas, icons, and checklists are application assets with an installed manifest and integrity checks. + +## 1.4 Data model + +Use explicit C++ domain types and validated JSON representations. Create schema files before UI forms. At minimum implement: + +| Entity | Required fields | +|---|---| +| Project | id, schema_version, target_domain, source_domain, desired_outcomes, lab_mode, created_at, updated_at, version | +| Host | id, fqdn, addresses, os_family, os_release, os_build, kernel, architecture, detected_roles, observed_at, evidence_ids | +| Capability | id, operation, supported_versions, state, evidence_ids, limitations, manual_alternative | +| InventoryObject | source_system_id, object_guid, sid, dn, object_type, attributes, memberships, observed_at | +| IdentityMapping | source_guid, source_sid, source_dn, target_id, target_sid, target_uid_gid, mapping_method, verification_state | +| MigrationItem | id, category, source_ref, target_ref, disposition, dependencies, acceptance_ids, blockers, evidence_ids | +| Plan | id, revision, inventory_digest, policy_digest, affected_hosts, graph, error_policy, downtime, authorization_state | +| Operation | id, adapter_id, adapter_version, target_id, typed_parameters, preconditions, effects, cancellation_class, recovery_class, postconditions | +| Run | id, plan_id, plan_revision, state, started_at, finished_at, per_host_results, cleanup_state | +| AccessChange | id, run_id, target_id, resource_type, resource_id, previous_state, applied_state, owner_marker, restoration_steps, verification_state | +| PolicyProfile | id, revision, os_constraints, role_constraints, settings, management_owner, exceptions, source_refs | +| ChecklistItem | id, phase, title_ru, purpose_ru, host_scope, prerequisites, steps_ru, expected_result_ru, failure_guidance_ru, evidence_ids | +| ChecklistObservation | item_id, host_id, result, checked_by, checked_at, method, note, plan_revision, profile_revision | +| LogEvent | sequence, timestamp_utc, run_id, host_id, operation_id, severity, stream, message_ru, redacted_detail, source_ref | + +Use stable source GUID/SID mappings. Never merge identities by display name, transliterated name, or login alone. Preserve unmapped attributes in inventory without assuming they can be applied to ALD. + +Allow unknown attributes in imported inventories as data, but reject unknown executable operation IDs and parameters. Validate lengths, nesting depth, file size, object counts, UUIDs, addresses, FQDNs, DN serialization, paths, and enums. Use explicit Unicode handling; do not silently alter usernames. + +Keep applicability, support, run status, and compliance as independent fields: + +```text +CapabilityState = VERIFIED | DOCUMENTED_NOT_TESTED | UNKNOWN | UNSUPPORTED +Applicability = APPLICABLE | NOT_APPLICABLE_WITH_REASON | UNKNOWN +ObservationResult = PASS | FAIL | PARTIAL | NOT_CHECKED | ERROR | STALE +RunState = DRAFT | PREFLIGHT | BLOCKED | READY | RUNNING | PAUSE_REQUESTED | + PAUSED | STOP_REQUESTED | VERIFYING | CLEANUP | COMPLETED | + COMPLETED_WITH_GAPS | FAILED | RECOVERY_REQUIRED +Disposition = AUTOMATED_NATIVE | GUIDED_NATIVE | MANUAL_RECONFIGURATION | + UNSUPPORTED | UNKNOWN +``` + +A waiver is a separate record with scope, owner, reason, and review date. It never changes FAIL into PASS or overrides a mandatory unsupported migration capability. + +## 1.5 Demonstration data + +Provide an explicitly selected offline demo mode, never an automatic substitute for a failed live connection. Use reserved documentation addresses such as `192.0.2.10` and `192.0.2.20`; never default live execution to them. + +Include synthetic corp.local examples corresponding to the existing manual lab guide when available: an ALD-LAB OU, ordinary/privileged/disabled users, nested groups, a test share, a DNS alias, a service identity, and linked/filtered/unlinked policy examples. Check the actual manual before reusing names. + +Provide fixtures for duplicate names, orphan SID references, an offline host, incomplete deployment, unknown Windows 2025 integration, missing media, same-name DNS conflict, and cleanup failure. Label all fixture observations as synthetic; do not present them as tested product capabilities. + +# SECTION 2: STYLES & LAYOUT + +## 2.1 Design tokens + +Use a restrained DedSec/ctOS aesthetic while preserving administrative clarity: + +| Token | Value | +|---|---| +| Window background | `#0A0A0A` | +| Panel background | `#141617` | +| Elevated panel | `#1C1F20` | +| Main text | `#F2F2EE` | +| Secondary text | `#B9B9B9` | +| Borders | `#454A4C` | +| Primary decorative accent | `#B0E010` | +| Error | `#FF5C6C` | +| Warning | `#F4C95D` | +| Informational status | `#70CFE8` | +| Focus indicator | 2 px `#B0E010` | +| Spacing scale | 4, 8, 12, 16, 24, 32 logical pixels | +| Base text | 14 px; scale with user font/DPI settings | +| Section title | 20 px, semibold | +| Page title | 28 px, bold | +| Log text | 13 px, monospaced | +| Control height | Minimum 36 px | +| Table row | Minimum 36 px, expanded details as needed | + +Semantic warning/error colors are not decorative second accents. Every status has a text label and icon, not color alone. Keep functional text antialiased and selectable; do not pixelate logs, commands, hostnames, data tables, passwords, or error instructions. + +Implement styling with Qt Style Sheets and QPainter, not browser CSS. Example QSS rules: + +```css +QMainWindow, QWidget#workspace { background: #0A0A0A; color: #F2F2EE; } +QFrame[panel="true"] { background: #141617; border: 1px solid #454A4C; } +QPushButton { min-height: 34px; padding: 0 14px; border: 1px solid #454A4C; } +QPushButton[role="primary"] { background: #B0E010; color: #0A0A0A; border-color: #B0E010; } +QPushButton:focus, QLineEdit:focus { border: 2px solid #B0E010; } +QLineEdit { background: #1C1F20; color: #F2F2EE; padding: 8px; } +QPlainTextEdit#logView { background: #0A0A0A; color: #F2F2EE; font-family: "DejaVu Sans Mono"; } +``` + +Do not rely on unsupported CSS variables, transforms, or web animation APIs in QSS. Store tokens centrally and build QSS from validated application constants. + +## 2.2 Main window + +Design at 1440×900 logical pixels and support 1024×768 without hiding primary actions. Use a splitter-based layout and scrolling detail forms. Sidebar width: 232 px normally, collapsible. Top bar: approximately 56 px. Main content padding: 24 px. The log drawer is collapsible and resizable, initially 220 px when opened. + +Sidebar pages, in this order: + +1. Обзор +2. Проверка окружения +3. Подготовка доступа +4. Инициализация ALD Pro +5. Миграция +6. Настройки домена +7. Политики и харденинг +8. Проверки +9. Журнал +10. Завершение и восстановление доступа + +The top bar shows project, actual detected node role, domain, mode (live/demo), and information freshness. Place major blockers in a persistent content banner with an explanation link. Never make a harmless decorative icon look like an error badge. + +Use a three-part workflow page: current facts, proposed changes, verification/recovery instructions. Advanced commands and package details belong in expandable diagnostics, not in the basic operator path. + +## 2.3 Motion and accessibility + +Use short stepped decorative transitions of 120–180 ms on page headers or original pixel motifs. Optional startup decoration is nonblocking, no longer than 600 ms, and skippable. No audio, full-window flashing, popup storms, idle video, permanent animated backgrounds, fake terminal output, or text scrambling on real data. + +Provide a persistent reduced-motion switch. With reduced motion enabled, all decorative movement stops; progress information remains readable and accurate. Pause decoration during mutation, error handling, and confirmation dialogs. Render static pages without continuous redraw loops. + +Support keyboard navigation, visible focus, readable Cyrillic, 100/150/200% scaling, and screen-reader names for controls. Do not move focused buttons when asynchronous results arrive. Preserve selection and scroll position in tables. User data must never be used as rich text without escaping. + +# SECTION 3: APPLICATION SHELL, PROJECTS & FRESHNESS + +Implement `AppController`, `ProjectRepository`, `CapabilityRegistry`, and page controllers independent of widgets. Widgets render models and dispatch typed intents; they do not run privileged commands. + +On startup: + +```text +openProjectOrCreate() +acquireSingleWriterLockForProject() +loadSchemaAndMigrateDatabaseTransactionally() +loadInterruptedRunsWithoutResumingThem() +markPreviousObservationsStaleWhenContextChanged() +loadInstalledAdaptersAndRuleManifests() +probeLocalEnvironmentReadOnly() +showCurrentStateAndPendingCleanup() +``` + +Never auto-connect to every previously known host or start changes merely because the application reopened. A refresh is explicit and cancellable. Prevent conflicting live runs from separate projects targeting the same local controller. + +Persist database and log data with restrictive permissions in an administrator-owned application data location. Use QStandardPaths for ordinary UI preferences, and an explicitly selected/provisioned protected project directory for infrastructure data. Do not silently use world-readable shared folders. + +# SECTION 4: DISCOVERY & COMPATIBILITY + +Classify the local node using multiple independent observations: + +```text +CLEAN_ASTRA +ALD_PACKAGES_NOT_INITIALIZED +AD_CLIENT +ALD_CLIENT +ALD_DC_HEALTHY +ALD_DC_DEGRADED +PARTIAL_OR_UNKNOWN +``` + +Inspect package metadata, hostname/FQDN, configured domains, service state, relevant configuration presence, and documented health indicators. An installed package or a stopped service alone does not prove a role. A degraded or partially installed controller must not be reinitialized automatically. + +Check OS/update/kernel/protection level against the selected ALD 3.1 delivery; resources; storage; time; resolvers; direct/reverse DNS; relevant domain discovery; trusted certificate paths; package sources; pending reboot; and package-manager locks. Probe only configured targets and required endpoints, not arbitrary subnet scans. + +Render each finding with actual value, expected value, evidence time, why it matters, supported fix path, and manual verification instructions. Do not present discovery results as editable text fields that directly rewrite files. + +Version support is per operation. A Windows 2025 host can be reachable for native configuration while its ALD-domain integration remains unverified. A GUI-compatible Astra release can still be unsuitable for installing ALD 3.1. + +# SECTION 5: TEMPORARY ACCESS PREPARATION & RESTORATION + +Provide a wizard for the source AD server, Linux clients, and Windows clients. Bootstrap cannot be automated over a channel that does not yet exist. When no supported channel is available, show precise native manual steps for execution on the target, then offer a connection test. + +Before an access change record the existing service startup mode and state, listener configuration, firewall rule identities/scopes, credential/key entries, temporary role memberships, and relevant configuration values. Record only the resources actually touched. + +Prefer existing approved administrative access. When creating temporary access, restrict it to required sources and purposes. Authenticate the target: use verified SSH host keys or trusted TLS certificate validation. Do not default to `StrictHostKeyChecking=no`, wildcard TrustedHosts, certificate-validation bypass, disabled UAC, or disabled endpoint protection. + +Each access change must show: + +- what changes and why; +- the exact target and affected resource; +- whether internet/media is required; +- before/after state; +- activation and verification instructions; +- restoration instructions; +- whether closing the channel will prevent remote verification. + +Use a restoration ledger, not a single “undo everything” shell script. Restore only application-owned changes. If a resource changed independently after preparation, stop automatic restoration for that resource and show a conflict instead of overwriting the administrator's newer state. + +```text +restoreAccess(change): + if !change.wasCreatedOrModifiedByThisRun: preserve() + current = observe(change.resource) + if current != change.appliedState: + recordRestorationConflict() + else: + executeReviewedInverse(change) + verifyOrRecordManualVerificationNeeded() +``` + +Default end-of-session workflow: complete/verify tasks, restore temporary credentials and rules, close the temporary channel last, and show remaining cleanup obligations. Persist manual restoration instructions before disabling the channel. If a machine is offline, mark cleanup pending; never claim access was removed remotely without evidence. + +Pre-existing SSH/WinRM services are not disabled merely because the application exits. For access created only for this session, present the concrete restoration plan and execute it when authorized. Crash recovery checks the ledger; do not install a hidden persistent cleanup agent. + +# SECTION 6: EXECUTION ENGINE, LOGS & ERROR POLICY + +Implement a typed operation registry. An operation identifies a known adapter method, not arbitrary executable text supplied by JSON or a UI field. Verify installed task manifests and protect privileged payloads from user modification. + +Use QProcess asynchronously. Never block the GUI thread waiting for subprocess output, DNS, network I/O, or file enumeration. Separate stdout/stderr, redact secrets before display and persistence, preserve ordering, and handle output split across chunks. Bound in-memory buffers and rotate protected logs. + +For remote execution, treat the remote shell as an additional injection boundary. Local argument arrays alone are not sufficient. Use fixed reviewed remote entry points and structured parameter transport; do not interpolate usernames, paths, DNs, passwords, or policy values into remote code. Do not build LDAP filters or PowerShell commands by unescaped concatenation. + +Every operation declares: + +- documented version constraints; +- read-only versus mutating behavior; +- required privilege; +- preconditions and expected effects; +- progress model, if available; +- expected exit/result codes and reboot semantics; +- timeout behavior; +- cancellation boundary; +- postconditions; +- recovery method and reversibility limits. + +Process exit zero is necessary only where the tool defines it as success; it never replaces postcondition verification. If native progress is unavailable, show elapsed time, phase, and completed item counts rather than invented percentages. + +Provide operator choices before a batch: stop on first error, continue independent hosts, or pause for a decision. Dependency failures always block dependent steps. Never retry destructive or non-idempotent operations automatically without reconciling actual state. + +```text +executePlan(plan): + verifyInventoryAndPlanRevisionStillMatch() + verifyCapabilityAndPrivilegeGates() + requireConcretePlanAuthorizationForMutations() + for step in topologicalOrder(plan): + if dependencyFailed(step): markBlocked(step); continue + if shutdownRequested: stopScheduling(); break + recheckPreconditions(step) + journalStart(step) + result = executeNativeStep(step) + observation = verifyPostconditions(step, result) + journalResult(step, result, observation) + applySelectedErrorPolicyWithoutBypassingDependencies() + reconcileAccessLedger() + generateChecklistFromObservedState() +``` + +Default concurrency: one host mutation at a time; independent read-only probes may use up to four workers. Serialize local controller changes. Make limits configurable within validated bounds. + +Provide human-readable summaries with an expandable redacted native output view. Filters: host, phase, operation, severity, time, run. Logs must explain failure and the next supported action, without fabricating native error interpretations. + +# SECTION 7: DOMAIN INITIALIZATION & EXISTING-CONTROLLER HANDLING + +The deployment wizard includes actual/desired hostname, FQDN, address/prefix, gateway, DNS, time source, domain/realm, approved repositories/media, protection level, resource checks, credentials, and backup/recovery prerequisites. + +Obtain input constraints and installer invocation from the actual ALD 3.1 documentation and installed tool help. Do not invent flags or include passwords in a recorded invocation. If the native tool cannot accept secrets through a safe supported channel, expose the documented interactive step rather than implementing an unsafe workaround. + +Distinguish: + +- clean preparation; +- package installation; +- native promotion/initialization; +- post-install checks; +- correction of a detected existing deployment. + +If the node is an existing healthy controller, open supported settings and diagnostics. Protect controller identity fields that cannot be changed in place. If renaming an existing DC is not supported, explain the documented replacement workflow; do not call `hostnamectl` and mark the domain renamed. + +If the node is an AD client, do not assume it must first be joined to AD to become an ALD controller. Resolve the correct documented sequence for the selected migration method. Never combine unrelated installer procedures. + +For corp.local already served by the source AD, detect the namespace collision before initializing an authoritative target. Require a documented resolver/authority/transition plan compatible with the same subnet and approved interruption. Do not advertise conflicting discovery records to production clients or invent a same-name trust. + +After initialization verify native domain services, resolution, time, administration access, and a test enrollment path. Record partial failures honestly; do not wipe and retry an incomplete domain automatically. + +# SECTION 8: MIGRATION INVENTORY & FEASIBILITY MATRIX + +Inventory the following categories when present and authorized: + +| Category | Required assessment | +|---|---| +| Users/groups/OUs | Attributes, account state, nesting, group scope, name collisions, mappings | +| Credentials | Supported preservation mechanism and per-account verification limits | +| Computer accounts | Re-enrollment, machine trust, client integration support | +| Windows profiles | Existing profile association, encrypted user material, application state | +| GPOs | Backup/report, links, ordering, inheritance, filtering, scripts, preferences, actual outcomes | +| DNS | Zones, records, dynamic update behavior, forwarders, service records and authority changes | +| DHCP | Scopes, reservations, options, leases and cutover ownership | +| Files/shares | Data, share permissions, NTFS ACLs, ownership, SID dependencies, special file semantics | +| Services/applications | Service identities, SPNs, scheduled tasks, LDAP/Kerberos/NTLM bindings and delegated access | +| Certificates/AD CS | CA dependencies, trust distribution, enrollment, private-key custody and renewal | +| Other AD-dependent services | Detect, classify, document owner and migration path; do not silently omit | + +Assign a disposition and evidence to every item. A present unsupported dependency required for unchanged behavior blocks AD retirement. “Not discovered” is not the same as “absent”; capture inventory scope and denied/unreachable areas. + +Separate transport support from capability to migrate the source AD version, and separate both from target domain support for Windows logon. + +Credentials require a vendor-documented mechanism. Do not assume LDAP export contains reusable passwords, that password-change synchronization captures existing passwords, or that plaintext passwords can be recovered. Do not dump LSASS or implement a custom password filter. If required credential preservation is not achievable, block the seamless outcome explicitly. + +Require a persistent source GUID/SID-to-target identity map before any permission transformation. Compare group membership and allow/deny access outcomes using representative ordinary and privileged test identities. Do not treat a matching username or matching object count as proof of equivalent authorization. + +Windows profile continuity must be tested independently, including applicable DPAPI/EFS/credential-store and application consequences. Never relabel ownership of a profile directory and claim that all encrypted profile material migrated successfully. + +Record any supported vendor Windows integration utility as a versioned artifact with build/ALD compatibility and verified integrity. A utility documented for ALD 3.3 is not automatically valid for 3.1 or Windows Server 2025. + +Convert Windows policies only through explicit per-setting semantic mappings. “Exported GPO” does not mean “imported and effective in ALD.” Preserve unmapped settings as visible gaps. A Windows-specific setting may require a Windows local policy or a documented application configuration, not a Linux policy. + +# SECTION 9: MIGRATION PLAN, CUTOVER & RECOVERY + +Present an ordered dependency graph with these phases: + +1. Source health, inventory, supported-path assessment. +2. Backup and recovery-readiness checks, including the single-DC risk. +3. Target preparation and version-correct initialization at the approved point in the namespace transition. +4. Supported object migration and verified identity mappings. +5. Resource/application migration and permission reconciliation. +6. Pilot client transition and continuity tests. +7. Approved DNS/service/client cutover window. +8. Validation with source AD unavailable, using a controlled reversible test where feasible. +9. Readiness assessment for supported AD decommissioning. +10. Temporary access restoration and final checklist. + +These are conceptual phases. The validated migration procedure determines which phases can happen before source interruption. Never impose a generic “initialize now, fix DNS later” ordering on same-name domains. + +The interruption preview includes affected services/users, expected unavailable functions, estimated duration or an honest unknown, prerequisites, recovery checkpoints, and the point beyond which rollback is no longer a simple reversal. + +Backup existence is insufficient. Store recovery procedure, verification status, location, applicable versions, and the result of an appropriate restore rehearsal. Do not describe arbitrary independent VM snapshot rollback as a universally valid recovery method for directory services. + +Do not expose a direct “delete AD” action as the normal migration completion step. Provide a version-correct decommissioning plan, with each remaining dependency visible and final action separately authorized. Never transfer FSMO roles to ALD or substitute a hidden permanent Samba AD domain for the requested target. + +If required continuity remains unverified, finish the current run as `COMPLETED_WITH_GAPS` or `BLOCKED`, not as a successful full migration. Implement every independently valid feature without falsely declaring the overall target achieved. + +# SECTION 10: GENERAL CONFIGURATION & POLICY MANAGEMENT + +Provide supported administration screens beyond migration: users, groups, organizational structure, host enrollment state, DNS/time settings, password policies, HBAC, sudo, policy assignments, and documented service settings. Show role/version applicability and links to the supported vendor portal/manual when the API is unavailable. + +Use ALD Pro's documented policy processing for Astra clients. Read and update the authoritative policy, not regenerated local policy cache files. Expose supported policy ordering/inheritance and resultant-setting diagnostics without borrowing newer-version features. + +An intended profile has a single management owner for each setting. Detect conflicting ownership between ALD policy, local configuration, and a separate automation tool. Do not run two writers that continually overwrite each other. + +For Windows, use validated native configuration and local policy tooling where appropriate. Record Windows edition/build-specific mappings. Native policy enforcement can continue after the GUI closes, but this application does not deliver new configurations or continuously detect drift while closed. + +Separate: + +```text +policy assigned +policy retrieved +setting included in resultant configuration +native application completed +effective value verified +user-visible behavior checked +``` + +Policy removal is not a universal rollback. Model restoration of persistent values explicitly, including settings that remain after assignment is removed. + +# SECTION 11: HARDENING & FSTEC RECOMMENDATION CATALOG + +Hardening follows migration verification. Keep distinct profiles for an ALD controller, Linux application server, ordinary workstation, administrative workstation, Windows workstation, and Windows server. + +The FSTEC Linux document dated 25 December 2022 contains 40 numbered configuration items across these ranges: + +```text +2.1.1–2.1.2: authorization +2.2.1–2.2.2: privilege acquisition +2.3.1–2.3.11: filesystem permissions +2.4.1–2.4.8: kernel protection +2.5.1–2.5.11: kernel attack surface +2.6.1–2.6.6: kernel-mediated userspace protection +``` + +Represent every item, even when its implementation is manual or unsupported. Paragraph 1.3 distinguishes certified operating systems, whose configuration follows the developer's operational documentation. Create a version-specific mapping to Astra's documentation rather than treating the general Linux document as a universal command list. + +For each recommendation implement a card containing source/paragraph, explanation, applicable versions/roles, expected state, observed state, read-only check, supported configuration path, impact, restart/reboot requirement, reversibility, verification instructions, and exceptions. + +Provide separate actions: explain, audit, prepare changes, apply to pilot, verify, and prepare restoration. An audit action must not run a policy refresh, install dependencies, or restart a service without being reclassified as a change. + +The optional `astra.hardening.fstec` role is documented as a Technical Preview and was introduced for Astra 1.8. Do not make it a mandatory executable dependency for the chosen Astra 1.7 target or infer that it implements this particular 40-item document completely. + +Example card requirements: + +- For paragraph 2.1.2, map the source recommendation `PermitRootLogin=no` to the effective SSH configuration and verify a permitted administrative access path remains available. +- For paragraph 2.6.1, the source value `kernel.yama.ptrace_scope=3` needs a special recovery classification. Kernel documentation states that this value cannot be changed once set in the current kernel session. Do not offer a fictitious immediate inverse operation. + +Check running state and persistent-next-boot configuration separately. An unsupported parameter is not automatically “not applicable.” A boot argument's presence is not proof that the kernel implements or enabled the feature. + +Windows gets a separate per-build baseline and native setting catalog. Do not apply Linux sysctl/PAM settings or label them Windows FSTEC compliance. Do not claim certification, attestation, or complete regulatory compliance from a completed technical checklist. + +# SECTION 12: INSTRUCTIONAL CHECKLIST + +The primary deliverable to the administrator is a saved, interactive checklist. It must remain useful without an automated test for every condition. + +Each item contains: + +- a short Russian title and reason; +- target host/user/service; +- prerequisites and required privilege; +- precise manual steps using native UI/tools; +- any command with placeholders clearly distinguished from real values; +- expected observations and an example failure condition; +- remediation or recovery guidance; +- state, operator identity, timestamp, note, and evidence reference; +- the plan/profile revision to which the observation applies. + +Provide explicit PASS, FAIL, NOT CHECKED, and NOT APPLICABLE WITH REASON actions. Human verification and machine verification must be visually distinct. Never automatically tick a manual check just because a process returned zero. + +Checklist groups include source baseline, initialization, object counts and identity mapping, password/login continuity, Windows profile continuity, file access allow/deny cases, service/application authentication, DNS/time, policy outcomes, post-reboot behavior, source-AD-unavailable validation, and access cleanup. + +After relevant changes or a new run, mark affected previous observations stale. Keep their history. Do not allow an old successful check to silently satisfy a new plan revision. + +Persist checklist state in the project database and support a simple local UTF-8 HTML/JSON export. PDF, cloud reporting, and enterprise compliance dashboards are not required for the initial release. Escape all exported text and exclude secrets. + +# SECTION 13: CONNECTIVITY, OFFLINE MODE & DOWNLOADS + +Determine connectivity per required service, not from a single internet ping. Distinguish local AD/ALD access, package repository reachability, documentation retrieval, optional-feature media, and artifact downloads. + +Before a plan starts, show an availability table: + +```text +Available offline: local inventory, installed-rule explanations, saved checklist, + planning, and operations whose tools/media are already present. +Requires network: access to configured target machines and domain services. +Requires internet or supplied media: missing packages, Windows optional features, + uncached vendor artifacts, source updates. +``` + +Offer importing an approved offline bundle with manifest, versions, signatures/digests, and provenance. Do not embed fabricated digest strings. Verify archive paths and reject path traversal or unexpected executable payloads. + +Updating the rule/source catalog creates a reviewable new version and never changes an accepted profile silently. No hidden downloads, automatic privileged package installation, or execution of downloaded documentation text. + +# SECTION 14: SHUTDOWN, INTERRUPTION & RECOVERY + +When no task is running, closing the application enters the access-restoration summary, persists the project, closes sessions, and terminates owned executors. Do not stop domain services or undo successfully applied persistent policies. + +When a task is active: + +```text +onCloseRequested(): + stopSchedulingNewOperations() + if activeOperation.canCancelSafelyNow: + requestSupportedCancellation() + else: + showWhichNativeOperationMustReachASafeBoundary() + waitAsynchronouslyForThatBoundary() + verifyCompletedEffectsOrMarkUnknown() + presentAndExecuteAuthorizedTemporaryAccessRestoration() + persistRunAndChecklist() + closeOwnedSessionsAndProcesses() + exit() +``` + +Do not use kill-all process matching or force-terminate package managers and directory installers as normal close behavior. Do not promise that killing the GUI cancels an already accepted remote command. + +After a crash, read the journal, inspect actual state, surface pending cleanup, and offer a reconstructed plan. Never blindly replay installation, password synchronization, ACL migration, promotion, or decommissioning. + +After a required reboot of the machine hosting the GUI, the operator relaunches the program manually. There is no background application service for automatic continuation. + +While closed, no new application audits, migrations, host retries, profile deliveries, or remediation jobs occur. The UI must explain this operational limit without implying that existing client settings disappear. + +# SECTION 15: VERIFICATION & ACCEPTANCE + +Use meaningful unit tests for state machines, plan dependencies, version gates, injection-resistant parameter handling, secret redaction, identity collision handling, and restoration conflict detection. Use Qt Test for GUI behavior where it validates real interaction, not screenshots of every decorative widget. + +Required tests include: + +1. A failed native process and a postcondition failure never produce migration success. +2. Same-name corp.local without a verified transition method blocks mutation but leaves inventory usable. +3. A degraded controller is never offered clean installation by inference from one stopped service. +4. Unsupported Windows 2025 domain integration stays blocked even if SSH execution succeeds. +5. A lost connection after a remote change produces unknown/needs-reconciliation, not automatic retry. +6. A pre-existing firewall rule/service/key is preserved during cleanup. +7. A temporary access change modified by another administrator creates a restoration conflict. +8. Secrets split across output chunks are not leaked by the log pipeline. +9. A renamed user or duplicate display name does not change the stable identity mapping. +10. Manual checklist completion cannot override a failed mandatory technical prerequisite. +11. Closing after completed work leaves no application-owned running process, listening port, timer, or remote background job. +12. Offline operation produces a specific missing-artifact explanation rather than a generic failure. +13. Motion disabled, Cyrillic text, keyboard navigation, and high DPI remain usable. +14. Repeated supported configuration is idempotent or explicitly classified otherwise. +15. A plan is invalidated when its relevant inventory, source mapping, or policy revision changes. + +Define lab integration tests for each verified adapter on actual supported VMs. Do not run them against live infrastructure without authorization. Include the named one-forest/one-domain/one-source-DC lab and the Windows targets. Record exact tested builds and untested combinations. + +Completion of the software implementation and successful migration of a real environment are separate outcomes. Report build/tests honestly, identify unimplemented integrations, and never describe a mocked fixture as a successful ALD migration. + +The first usable release must contain working discovery, planning, lifecycle management, instructional checks, and at least the documented baseline initialization integration once validated. Do not leave all native actions as placeholders. When a particular integration is genuinely unavailable, ship its explicit blocked/guided workflow with the reason while completing the independent modules. + +# SECTION 16: IMPLEMENTATION ORDER + +Work in the following sequence. Do not stop after drawing the GUI or writing a plan; implement and verify the authorized software scope. Do not change real infrastructure as part of generating the code. + +## Phase 0 — Evidence and compatibility + +Create: + +```text +docs/requirements.md +docs/feasibility.md +docs/compatibility-matrix.md +docs/compatibility-lock.json +docs/native-adapter-contracts.md +docs/access-restoration.md +data/sources.json +``` + +Extract actual ALD 3.1 native commands/API contracts from the delivery and documentation. Mark unresolved entries honestly. Inspect the target package manifest before choosing exact build revisions. The absence of a real Astra VM blocks release validation, not source-code development or unit tests. + +## Phase 1 — Build, types and storage + +Create: + +```text +CMakeLists.txt +README.md +src/main.cpp +src/app/AppController.{h,cpp} +src/domain/{Project,Host,Capability,Plan,Operation,Run,AccessChange,Checklist}.h +src/storage/ProjectRepository.{h,cpp} +src/storage/DatabaseMigrator.{h,cpp} +schemas/{project,inventory,plan,profile,checklist,source}.schema.json +tests/unit/ +``` + +Compile the minimal application and validate project persistence/migrations before adding privileged execution. + +## Phase 2 — Runtime and privilege boundary + +Create: + +```text +src/execution/OperationRegistry.{h,cpp} +src/execution/ProcessRunner.{h,cpp} +src/execution/PlanExecutor.{h,cpp} +src/execution/RunJournal.{h,cpp} +src/execution/ShutdownCoordinator.{h,cpp} +src/security/SecretRedactor.{h,cpp} +src/security/AccessLedger.{h,cpp} +src/transports/NativeSshTransport.{h,cpp} +src/privileged/ExecutorMain.cpp +src/privileged/OperationDispatcher.{h,cpp} +tests/fixtures/ +``` + +Implement safe fixed-task transport, session ownership, authorization checks, cancellation classes, and restoration semantics before enabling live mutations. + +## Phase 3 — Native discovery and preparation + +Create: + +```text +src/adapters/Astra17Discovery.{h,cpp} +src/adapters/WindowsDiscovery.{h,cpp} +src/adapters/CompatibilityResolver.{h,cpp} +src/workflows/AccessPreparation.{h,cpp} +src/workflows/AccessRestoration.{h,cpp} +resources/tasks/windows/ +resources/tasks/linux/ +resources/tasks/manifest.json +``` + +Every shipped task must have a purpose, version constraints, validated parameters, read/write classification, and native-tool evidence. Do not generate a general-purpose remote shell API. + +## Phase 4 — Readable desktop shell + +Create: + +```text +src/ui/MainWindow.{h,cpp} +src/ui/Theme.{h,cpp} +src/ui/PixelDecoration.{h,cpp} +src/ui/models/ +src/ui/pages/{Overview,Environment,Access,Logs,Checklist}Page.{h,cpp} +resources/styles/dedsec.qss +resources/resources.qrc +``` + +Connect real read-only state, logs, and checklist interactions. Review screenshots at normal and high DPI. Use the declared DedSec palette and restrained motion without installing the skill's video runtime. + +## Phase 5 — Initialization + +Create: + +```text +src/adapters/Ald31Deployment.{h,cpp} +src/workflows/InitializationPlanner.{h,cpp} +src/ui/pages/InitializationPage.{h,cpp} +data/checklists/initialization.ru.json +``` + +Implement the baseline deployment flow only after its exact native invocation is verified. Protect existing and partial domain states. Test plan generation independently from real promotion. + +## Phase 6 — Migration + +Create: + +```text +src/adapters/AdInventory.{h,cpp} +src/adapters/Ald31Migration.{h,cpp} +src/workflows/IdentityMapper.{h,cpp} +src/workflows/MigrationPlanner.{h,cpp} +src/workflows/CutoverPlanner.{h,cpp} +src/ui/pages/MigrationPage.{h,cpp} +data/checklists/migration.ru.json +``` + +Implement supported object/resource operations and their evidence. Keep homonymous-domain, credential, Windows profile, and unsupported application dependencies explicit. Exercise positive and negative access checks in the lab. Do not enable AD decommissioning while the unchanged-user-experience gates remain unresolved. + +## Phase 7 — General configuration and policies + +Create: + +```text +src/adapters/Ald31Administration.{h,cpp} +src/adapters/Ald31Policies.{h,cpp} +src/adapters/WindowsLocalPolicy.{h,cpp} +src/workflows/PolicyPlanner.{h,cpp} +src/ui/pages/DomainSettingsPage.{h,cpp} +src/ui/pages/PoliciesPage.{h,cpp} +data/checklists/policies.ru.json +``` + +Implement per-setting ownership, actual/resultant state, version limits, and explicit mappings. Keep Windows and Linux implementations separate behind a shared profile UI. + +## Phase 8 — Hardening and source mapping + +Create: + +```text +src/workflows/HardeningPlanner.{h,cpp} +src/workflows/ComplianceEvaluator.{h,cpp} +data/hardening/fstec-linux-2022.catalog.json +data/hardening/astra17-mappings.json +data/hardening/windows-baselines.json +data/checklists/hardening.ru.json +``` + +Represent all 40 Linux-source items with honest support states. Implement only verified remediation paths; provide useful manual guidance for the rest. Separate exact source recommendations from role-specific accepted profile values and explain deviations. + +## Phase 9 — Packaging and final verification + +Create: + +```text +packaging/debian/ +docs/operator-guide.ru.md +docs/recovery-guide.ru.md +docs/test-results.md +tests/integration/ +``` + +Build/install/uninstall on the validated Astra VM. Package installation must not enable remote access, start migrations, initialize a domain, install an always-on executor, or apply hardening. Verify shutdown, pending-cleanup recovery, offline operation, DPI/accessibility, and controller service health. + +Deliver source code, a reproducible build procedure, package artifacts when a supported build environment exists, and an honest verification report. Distinguish completed functionality, real laboratory evidence, manual workflows, and blocked requirements. Do not label the product or a migration “fully ready” while required work remains. diff --git a/docs/security-review.md b/docs/security-review.md new file mode 100644 index 0000000..d868fed --- /dev/null +++ b/docs/security-review.md @@ -0,0 +1,69 @@ +# Development boundary review + +Scope: source review of the GUI/executor boundary, fixed task construction, +project persistence, identity import, logs and shutdown. The `security-review` +skill was applied to this code. This was not a network assessment, exploitation +exercise or an independently reproduced security audit. + +## Reviewed controls + +- No GUI root operation, service, custom agent, installation hook or mutable + root command allowlist. Infrastructure mutations are rejected at the final + process boundary while their version/laboratory gates are unresolved. +- Native operations use executable/argument arrays. The remote command is a + compiled, hash-checked PowerShell payload; host/user data never becomes code. + AD inventory binds its native queries to the selected DC and checks + `corp.local`. Its output remains incomplete directory inventory. +- SSH uses strict host keys, an explicitly chosen protected known-hosts file, + no forwarded agent/ports, no shared control session and no password arguments. +- The one-shot privileged observation checks peer UID/PID, exact operation + fields, empty typed parameters, local machine binding and protected native + binary/parent ownership. It exposes only selected `sshd -T` output. IPC and + package installation have not been exercised in this session. +- JSON rejects duplicate decoded keys, excess sizes/depth, unknown executable + fields, wrong source domains and known secret-bearing attribute names. Unknown + directory attributes remain data. Source GUID/SID keys do not use display names. +- Output redaction handles split/overlapping known secrets and suppresses an + oversized sensitive suffix. No guarantee is made for arbitrary secrets typed + into free-text notes: operators must not put credentials there. +- Owned access changes are compared with observed applied state before proposing + restoration. The current application records manual obligations; it does not + execute unverified inverse operations or assert remote cleanup. + +## Issues corrected during source review + +| Location | Issue | Correction and validation limit | +|---|---|---| +| `src/ui/models/JsonTableModel.cpp` | Tooltips can interpret imported markup | Escape tooltip content; Qt regression test authored | +| `src/app/AppController.cpp`, `src/execution/PlanExecutor.cpp` | Journal failure could escape a signal handler or allow scheduling | Guard asynchronous result persistence, refuse the next native start, record recovery obligation where possible | +| `src/execution/ShutdownCoordinator.cpp`, `src/app/AppController.cpp` | Cleanup summary could precede final result persistence | Queue shutdown notification and emit once after owned work stops | +| `src/storage/ProjectRepository.cpp` | Rotation lost host/operation/run metadata; run snapshots overwrote history | Retain all event fields and append transactional run history | +| `src/privileged/OperationDispatcher.cpp` | Incomplete local binding/path checks | Reject unreadable/invalid machine ID, fractional schema version and writable parent paths | +| `src/adapters/AdInventory.cpp`, fixed AD task | Inventory domain was not explicitly bound to the accepted project | Require `source_domain`, bind native queries and reject other domains | +| `src/core/Rules.cpp` | Case variation and incomplete role observation could weaken a decision | Case-insensitive DNS comparison; require configuration observation before a clean-node classification; portable tests pass | + +## Remaining release restrictions + +The Qt regression suites now pass on Kali, including tooltip escaping, +fixed-task parameter rejection, owned-child cancellation, journal refusal before +native start, storage persistence and explicit demo/checklist gates. This does +not verify root IPC, remote Windows execution or production authorization. Required additional +work includes helper peer/error/disconnect tests, real process ownership checks, +database-full/permission failures, performance with bounded maximum inventories, +remote-shell behavior on each Windows build and package ownership validation on +Astra. Firmware/OS trust and a compromised same-user account are outside this +temporary local IPC isolation boundary. + +Signed vendor bundles, automatic access restoration, fully typed mutating +adapters and complete per-operation authorization are not implemented. Those +operations stay disabled; this review does not authorize them. A source archive +is not a production release. + +## Build-time defects corrected + +The first full Qt run exposed outstanding PRAGMA result sets that prevented a +SQLite schema transaction from committing, and null QString values bound to +NOT NULL log fields. Result sets now finish before the transaction; absent +optional log context is stored as an empty string. Storage and UI regressions, +including project reopen and schema-valid checklist export, pass on the +actual Qt 5.15.19/QSQLITE build. No user project was migrated during testing. diff --git a/docs/test-results.md b/docs/test-results.md new file mode 100644 index 0000000..61a230c --- /dev/null +++ b/docs/test-results.md @@ -0,0 +1,76 @@ +# Local verification — 2026-10-27 + +The application and temporary executor **build successfully on Kali 2026.3** +with GCC 16.2.0, CMake 4.3.4 and Qt 5.15.19. All four CTest suites pass. This is +a development build, not a validated Astra package or an ALD migration result. +No Astra/Windows laboratory or real-infrastructure change was involved. + +## Executed checks + +| Check | Actual result | Limit | +|---|---|---| +| CMake configure/build | PASS; `build/ald-transition-console`, `build/ald-transition-executor` | Kali toolchain; not an Astra binary | +| CTest: rules, storage, runtime, ui | 4/4 PASS | Local fixtures and owned read-only child processes | +| Portable production rules, ASan/UBSan, warnings as errors | 40,457 assertions PASS, including 1,000 seeded chunk/DAG trials | LeakSanitizer disabled under the managed sandbox | +| Schemas, manifests and data | PASS: 26 resources, 23 source references, 40 cards, 17 checklist items | Hashes do not establish vendor support | +| Qt DEMO startup, capture, normal shutdown | PASS at 100/150/200% | Real C++ binary, Qt offscreen platform | +| Ten-page keyboard navigation at 1024×768 logical pixels | PASS at 100/150/200%; primary actions remain inside their pages | Offscreen event delivery; not a screen-reader audit | +| Project reopen and checklist export | PASS; manual history persists, JSON matches schema, migration remains BLOCKED | Synthetic data | +| Rendered interface | Screenshots inspected at normal/high scale; navigation wrapping and port-field height corrected | Live Windows/Astra states not exercised | +| X11/Xvfb | NOT VERIFIED: local X server failed to create listening sockets; xdpyinfo also failed | xcb linked dependencies are present; no desktop success claimed | +| Release gate | PASS: still refuses unvalidated Astra lock | No deployable `.deb` produced | +| Astra handoff script | Fresh configure/build and 4/4 tests PASS; missing-tools case exits 1 and produces a failure report archive | Script exercised on Kali; actual Astra run pending | + +Machine-readable evidence: [local-check-results.json](local-check-results.json), +[gui-smoke-results.json](gui-smoke-results.json), +[gui-xcb-result.json](gui-xcb-result.json), and +[development-environment.json](development-environment.json). + +Reproduce: + +```sh +python3 tools/validate_local.py +python3 tools/check_gui.py +``` + +`check_gui.py` launches the actual application and Qt UI tests, saves screenshots +under `artifacts/screenshots`, verifies their pixel sizes and waits for normal +process exit. It never connects to an AD/ALD host. Its synthetic project and UI +preferences use temporary private directories. `--portable-only` remains +available for deliberately excluding the Qt build/tests. + +## Defects found by the first full build + +- Added the missing QVariant include and disambiguated QVector aggregate append. +- Finished PRAGMA result sets before SQLite schema commit; the active statements + had prevented initial project creation. +- Bound absent log context as empty strings instead of SQL NULL. Startup log + insertion now satisfies the schema and has a regression test. +- Wrapped sidebar labels using actual font/viewport measurements, retained full + labels and tooltips, and made the port editor meet the control-height baseline. + +## Required acceptance coverage + +| Requirement | Local evidence | Remaining validation | +|---|---|---| +| 1. Native failure/postcondition cannot produce success | Portable and actual ProcessRunner/PlanExecutor tests pass | Vendor operation postconditions | +| 2. Same-name migration stays blocked; discovery usable | Portable gate, DEMO and import checks pass | Verified transition procedure | +| 3. Degraded/unknown does not imply clean installation | Role rules and initialization planner tests pass | Astra role/configuration discovery | +| 4. Windows 2025 SSH is separate from ALD integration | Independent immutable capability state in source | Actual Server 2025 VM | +| 5. Lost connection requires reconciliation | Portable result tests; no automatic write retry; close warning implemented | Controlled remote disconnect | +| 6–7. Preserve existing access / detect external edits | Ownership and conflict tests pass | Native restore adapters are not implemented | +| 8. Split secrets are not leaked | Portable split/overlap bounds and Qt UTF-8 decoder tests pass | No guarantee for unknown secrets in arbitrary notes | +| 9. Stable identity across rename | Portable keys and Qt mapping collision tests pass | Real identity/permission migration | +| 10. Manual PASS cannot override technical gates | Qt checklist and project-reopen tests pass | Mandatory migration capabilities remain unresolved | +| 11. Close owns its local work | Local process cancellation and DEMO normal exit pass | Root IPC and remote-process lifecycle | +| 12. Offline failures are specific | Missing-tool, bundle traversal/hash rejection tests pass | Vendor/offline software artifact handling | +| 13. Motion/Cyrillic/keyboard/DPI | Qt offscreen tests and inspected images at 100/150/200% | Desktop keyboard focus, screen reader, high-contrast theme | +| 14. Idempotence classification | Profile ownership/comparison tests pass | Native configuration writers disabled | +| 15. Context changes invalidate plans | Portable digest/revision gates and storage history tests pass | Larger live inventory and source/profile update scenarios | + +Database schema version 3 and crash-recovery marking are exercised locally. +Disk-full, interrupted multi-document transactions, root helper peer validation, +large inventories and real network failures still need dedicated fault injection. +Follow [integration/README.md](../tests/integration/README.md) on explicitly +approved VMs. ALD promotion, migration, continuity, policy writes, decommissioning, +Astra package install/uninstall and domain service health remain NOT TESTED. diff --git a/packaging/README.md b/packaging/README.md new file mode 100644 index 0000000..4ddbd36 --- /dev/null +++ b/packaging/README.md @@ -0,0 +1,24 @@ +# Packaging gate + +`debian/` is a packaging template, not a validated deployable artifact. Stage a +clean source tree and copy `packaging/debian` to that tree's `debian/` directory. +Choose the actual maintainer/license and distribution version, then validate on +the approved Astra build VM. The default package rules refuse an incomplete +`docs/compatibility-lock.json`. Never mark it valid from a Kali build. + +The native source version is 0.1.0; the template changelog is intentionally +UNRELEASED and must be reviewed before release. A proper source package with an upstream tarball may +instead use `3.0 (quilt)` and a Debian revision. + +No maintainer script, service, timer, cron, default access rule, domain command, +polkit auto-grant or setuid bit is included. Installed helper is an ordinary +root-owned executable under `/usr/libexec/ald-transition-console`. It runs only +when a non-root operator requests the fixed read-only SSH audit and polkit +separately authorizes it. CMake installation prefix must be `/usr` so the fixed +helper path matches. Installing files alone does not authorize any operation. + +On the target lab: build, install, launch as the intended non-root account, +exercise private IPC, all Qt tests, shutdown and crash recovery, and uninstall. +Compare service/process/listener state before and after; existing domain health +must be unchanged. Archive real package versions, artifact hashes and results. +No .deb is emitted in this environment because the target validation is absent. diff --git a/packaging/ald-transition-console.desktop b/packaging/ald-transition-console.desktop new file mode 100644 index 0000000..4aee1de --- /dev/null +++ b/packaging/ald-transition-console.desktop @@ -0,0 +1,9 @@ +[Desktop Entry] +Type=Application +Name=ALD Transition Console +Name[ru]=ALD Transition Console +Comment[ru]=Обследование, план перехода и проверки ALD Pro +Exec=ald-transition-console +Terminal=false +Categories=System;Settings; +StartupNotify=true diff --git a/packaging/debian/changelog b/packaging/debian/changelog new file mode 100644 index 0000000..84d6239 --- /dev/null +++ b/packaging/debian/changelog @@ -0,0 +1,5 @@ +ald-transition-console (0.1.0) UNRELEASED; urgency=medium + + * Initial development source. Release blocked pending exact Astra validation. + + -- ALD Transition Console project Tue, 27 Oct 2026 12:00:00 +0000 diff --git a/packaging/debian/control b/packaging/debian/control new file mode 100644 index 0000000..f6e9d85 --- /dev/null +++ b/packaging/debian/control @@ -0,0 +1,17 @@ +Source: ald-transition-console +Section: admin +Priority: optional +Maintainer: ALD Transition Console project +Build-Depends: debhelper-compat (= 12), cmake (>= 3.13), g++, qtbase5-dev (>= 5.15.2), qtbase5-dev-tools, python3 +Standards-Version: 4.3.0 +Rules-Requires-Root: no + +Package: ald-transition-console +Architecture: any +Depends: ${shlibs:Depends}, ${misc:Depends}, libqt5sql5-sqlite +Recommends: openssh-client, qttranslations5-l10n +Suggests: policykit-1 +Description: Native preparation console for ALD Pro 3.1 transitions + Russian C++/Qt desktop application for read-only discovery, blocked migration + planning, instructional checks and temporary-access restoration records. + No service, migration, remote-access or hardening action runs at installation. diff --git a/packaging/debian/copyright b/packaging/debian/copyright new file mode 100644 index 0000000..f459982 --- /dev/null +++ b/packaging/debian/copyright @@ -0,0 +1,11 @@ +Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Upstream-Name: ALD Transition Console +Source: Local project + +Files: * +Copyright: 2026 project owner; ownership and redistribution terms to be confirmed +License: pending-owner-selection + No redistribution license has been inferred from local availability. + No Ubisoft/Watch Dogs artwork or external font files are bundled. + Qt and system fonts are runtime dependencies subject to their own licenses. + Release metadata must be reviewed before publishing a package. diff --git a/packaging/debian/rules b/packaging/debian/rules new file mode 100644 index 0000000..45191fa --- /dev/null +++ b/packaging/debian/rules @@ -0,0 +1,10 @@ +#!/usr/bin/make -f +%: + dh $@ --buildsystem=cmake + +override_dh_auto_configure: + python3 tools/verify_release_lock.py + dh_auto_configure -- -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_INSTALL_LIBEXECDIR=libexec + +override_dh_auto_test: + QT_QPA_PLATFORM=offscreen dh_auto_test diff --git a/packaging/debian/source/format b/packaging/debian/source/format new file mode 100644 index 0000000..89ae9db --- /dev/null +++ b/packaging/debian/source/format @@ -0,0 +1 @@ +3.0 (native) diff --git a/resources/asset-manifest.json b/resources/asset-manifest.json new file mode 100644 index 0000000..5ad9cee --- /dev/null +++ b/resources/asset-manifest.json @@ -0,0 +1,105 @@ +{ + "schema_version": 1, + "assets": [ + { + "path": "data/checklists/all.ru.json", + "sha256": "fa86faf3ad52d9627526683e0627620952f5a1fe870adca59dd3586b982ee58d" + }, + { + "path": "data/checklists/hardening.ru.json", + "sha256": "b4c162b1302387d566001585f12dfc990d072878ea9fb1d71610b61734cf5202" + }, + { + "path": "data/checklists/initialization.ru.json", + "sha256": "737a7d0f6b6072825daf27bfe6fbf281282e929cc92e1db9a52534889648b4e4" + }, + { + "path": "data/checklists/migration.ru.json", + "sha256": "76c189997f1434733e1a076b78b429e2857d3f929419d801d4c229dd9feefcc3" + }, + { + "path": "data/checklists/policies.ru.json", + "sha256": "91c26c5f2a29a153f5aa1f963f784c0dc7bb6e3024beb5c7b764c22be2c3b78e" + }, + { + "path": "data/hardening/astra17-mappings.json", + "sha256": "050c8509561e01beff6b9d0ef192b028df20ab281564709f9313f1c40f5487f6" + }, + { + "path": "data/hardening/fstec-linux-2022.catalog.json", + "sha256": "4112f84f16cb8861936d95f27689827d2a61bbaa5f81afec83a1a412ebe66d3c" + }, + { + "path": "data/hardening/windows-baselines.json", + "sha256": "a71e297de842613577e3b7d284b6155de21306e794ce6a67db945a5e46559663" + }, + { + "path": "data/sources.json", + "sha256": "aa5527de7b1e0b95ef65c51037d72a5ff09941b9c2b33941ed75e726ba6dcdf5" + }, + { + "path": "schemas/checklist.schema.json", + "sha256": "4baafe9294ce9b80cc64f360f2d82c3b0485eca3565919542db2b7964eba874d" + }, + { + "path": "schemas/host.schema.json", + "sha256": "df6dd7bdaaa1bb531e3ae5b758049363bd9fbc0bc604bad1dde2548e4c135a88" + }, + { + "path": "schemas/inventory.schema.json", + "sha256": "b469ea50e1737ab16777d52940042840e9f9e906c13b441c644f37cefce48bcd" + }, + { + "path": "schemas/offline-bundle.schema.json", + "sha256": "eebfbe5a1c14a796779811a8298cea42d9049977ad22b5ce129d1e1db9543bea" + }, + { + "path": "schemas/operation.schema.json", + "sha256": "2cf2448323742284ab8b8a67f6802ef37f244d8a54f6f6ae8a3f95bae0054df4" + }, + { + "path": "schemas/plan.schema.json", + "sha256": "b68d479ccbe5c4f7827bef62c3988086244fa421cdc7fa8475926c9b5d7c47fa" + }, + { + "path": "schemas/profile.schema.json", + "sha256": "49ce944c824a911e8204f3ee10c738fc47a93eb40a811404162908cec50f5d4e" + }, + { + "path": "schemas/project.schema.json", + "sha256": "bf8c039977eae1746bc2b46cf905aee911627a1bcd868a3ee3e7a6533232f73f" + }, + { + "path": "schemas/source.schema.json", + "sha256": "400426c9efc182eb6d074c3c9d2526b4d0c5ec23baca5215ce17860907618a68" + }, + { + "path": "schemas/windows-discovery.schema.json", + "sha256": "0c2cddbcf23591f308787cbf240b28b2dfc185cc4492fb434b0dcf56bff328bf" + }, + { + "path": "tasks/linux/README.md", + "sha256": "c28c1effd844cb0ed529f3e62b7ca3ae639cce558b45c0f83b6914317ba2d90a" + }, + { + "path": "tasks/manifest.json", + "sha256": "9bd3b9f4760c497a9efe3688cfdb7698b5793a843d73fa13bb5fd195e7d3b527" + }, + { + "path": "tasks/windows/ad-inventory.ps1", + "sha256": "bc5cab0a1cb0e5a6e6b298ee9508fa833767767129ff4c97d078ce21534c69d5" + }, + { + "path": "tasks/windows/discovery.ps1", + "sha256": "956ac1641eade610360c7f1417e75e916d46d8740cda81673d91e1050904ab24" + }, + { + "path": "styles/dedsec.qss", + "sha256": "05040ba4fc62a448ea20f472f6e8be32dd55da73b6784d4629c571107f176104" + }, + { + "path": "fixtures/demo.inventory.json", + "sha256": "7ebea1c8bcf6946d3a9f21c8724b22a28a9e5d8fc0ac355510622008fbb659c9" + } + ] +} diff --git a/resources/resources.qrc b/resources/resources.qrc new file mode 100644 index 0000000..36ff30c --- /dev/null +++ b/resources/resources.qrc @@ -0,0 +1,28 @@ + + ../data/checklists/all.ru.json + ../data/checklists/hardening.ru.json + ../data/checklists/initialization.ru.json + ../data/checklists/migration.ru.json + ../data/checklists/policies.ru.json + ../data/hardening/astra17-mappings.json + ../data/hardening/fstec-linux-2022.catalog.json + ../data/hardening/windows-baselines.json + ../data/sources.json + ../schemas/checklist.schema.json + ../schemas/host.schema.json + ../schemas/inventory.schema.json + ../schemas/offline-bundle.schema.json + ../schemas/operation.schema.json + ../schemas/plan.schema.json + ../schemas/profile.schema.json + ../schemas/project.schema.json + ../schemas/source.schema.json + ../schemas/windows-discovery.schema.json + tasks/linux/README.md + tasks/manifest.json + tasks/windows/ad-inventory.ps1 + tasks/windows/discovery.ps1 + styles/dedsec.qss + ../tests/fixtures/demo.inventory.json + asset-manifest.json + diff --git a/resources/styles/dedsec.qss b/resources/styles/dedsec.qss new file mode 100644 index 0000000..d05197b --- /dev/null +++ b/resources/styles/dedsec.qss @@ -0,0 +1,34 @@ +QMainWindow, QWidget#workspace { background: @BG@; color: @TEXT@; } +QWidget { color: @TEXT@; } +QFrame[panel="true"], QGroupBox { background: @PANEL@; border: 1px solid @BORDER@; padding: 12px; } +QLabel[muted="true"] { color: @MUTED@; } +QLabel[title="true"] { font-size: 21pt; font-weight: bold; } +QLabel[section="true"] { font-size: 15pt; font-weight: 600; } +QLabel#blocker { background: @PANEL@; color: @WARNING@; border-left: 4px solid @WARNING@; padding: 12px; } +QPushButton, QToolButton, QComboBox, QSpinBox { min-height: 34px; padding: 0 12px; border: 1px solid @BORDER@; background: @RAISED@; } +QPushButton:hover, QToolButton:hover { border-color: @MUTED@; } +QPushButton[role="primary"] { background: @ACCENT@; color: @BG@; border-color: @ACCENT@; font-weight: bold; } +QPushButton:disabled { color: @MUTED@; background: @PANEL@; border-color: @BORDER@; } +QPushButton:focus, QToolButton:focus, QLineEdit:focus, QPlainTextEdit:focus, QComboBox:focus, QCheckBox:focus, QListWidget:focus, QTableView:focus, QTabBar::tab:focus { border: 2px solid @ACCENT@; } +QLineEdit { min-height: 24px; background: @RAISED@; color: @TEXT@; padding: 6px; border: 1px solid @BORDER@; } +QPlainTextEdit, QTextBrowser { background: @PANEL@; border: 1px solid @BORDER@; padding: 8px; selection-background-color: @ACCENT@; selection-color: @BG@; } +QPlainTextEdit#logView { background: @BG@; font-family: "DejaVu Sans Mono"; font-size: 10pt; } +QTableView { background: @PANEL@; alternate-background-color: @RAISED@; gridline-color: @BORDER@; border: 1px solid @BORDER@; selection-background-color: @ACCENT@; selection-color: @BG@; } +QHeaderView::section { background: @RAISED@; color: @MUTED@; padding: 10px; border: none; border-bottom: 1px solid @BORDER@; } +QListWidget#navigation { background: @PANEL@; border: none; } +QListWidget#navigation::item { min-height: 36px; padding: 8px 10px; border-left: 3px solid transparent; } +QListWidget#navigation::item:selected { background: @RAISED@; color: @ACCENT@; border-left: 3px solid @ACCENT@; } +QSplitter::handle { background: @BORDER@; } +QScrollArea { border: none; } +QTabWidget::pane { border: 1px solid @BORDER@; } +QTabBar::tab { min-height: 32px; padding: 4px 16px; background: @PANEL@; border-bottom: 2px solid @BORDER@; } +QTabBar::tab:selected { color: @ACCENT@; border-bottom-color: @ACCENT@; } +QCheckBox { spacing: 8px; padding: 4px; min-height: 30px; } +QCheckBox::indicator { width: 18px; height: 18px; border: 1px solid @BORDER@; background: @RAISED@; } +QCheckBox::indicator:checked { background: @ACCENT@; border-color: @ACCENT@; } +QMenu { background: @PANEL@; border: 1px solid @BORDER@; } +QMenu::item:selected { background: @ACCENT@; color: @BG@; } +QToolTip { color: @TEXT@; background: @RAISED@; border: 1px solid @BORDER@; } + +QPushButton[role="primary"]:focus { background: @PANEL@; color: @ACCENT@; border: 2px solid @ACCENT@; } +QSpinBox:focus { border: 2px solid @ACCENT@; } diff --git a/resources/tasks/linux/README.md b/resources/tasks/linux/README.md new file mode 100644 index 0000000..eb17eb9 --- /dev/null +++ b/resources/tasks/linux/README.md @@ -0,0 +1,5 @@ +Linux probes use fixed executable/argument pairs compiled in OperationRegistry. +No shell script is executed. Missing tools produce a separate missing-artifact +finding. Read-only probes: os-release, uname, dpkg-query, hostname, systemctl show, +ip address/route JSON, timedatectl show, resolv.conf, Yama runtime value. +No read-only probe installs, refreshes policy, starts a service or changes state. diff --git a/resources/tasks/manifest.json b/resources/tasks/manifest.json new file mode 100644 index 0000000..be2ff2f --- /dev/null +++ b/resources/tasks/manifest.json @@ -0,0 +1,53 @@ +{ + "schema_version": 1, + "revision": 2, + "tasks": [ + { + "id": "windows.discovery", + "path": "windows/discovery.ps1", + "sha256": "956ac1641eade610360c7f1417e75e916d46d8740cda81673d91e1050904ab24", + "purpose": "Read Windows edition/build/role, PS version and optional features", + "adapter_version": "0.1.0", + "state": "DOCUMENTED_NOT_TESTED", + "versions": [ + "Windows 10 1809+", + "Server 2019", + "Server 2025" + ], + "parameters": {}, + "mutating": false, + "privilege": "Existing approved administrative SSH session; AD inventory requires RSAT ActiveDirectory", + "source_refs": [ + "MS_OPENSSH" + ], + "postcondition": "Validated structured JSON; every denied scope remains explicit", + "cancellation_class": "READ_ONLY_TERMINATE", + "recovery_class": "NONE", + "timeout_seconds": 120 + }, + { + "id": "ad.inventory", + "path": "windows/ad-inventory.ps1", + "sha256": "bc5cab0a1cb0e5a6e6b298ee9508fa833767767129ff4c97d078ce21534c69d5", + "purpose": "Bounded directory inventory from configured source DC", + "adapter_version": "0.1.0", + "state": "DOCUMENTED_NOT_TESTED", + "versions": [ + "Windows Server 2019 AD DC: NOT_TESTED", + "Windows Server 2025 AD DC: NOT_TESTED" + ], + "parameters": {}, + "mutating": false, + "privilege": "Existing approved administrative SSH session; AD inventory requires RSAT ActiveDirectory", + "source_refs": [ + "MS_OPENSSH", + "MS_AD_OBJECT", + "MS_AD_FOREST" + ], + "postcondition": "Validated structured JSON; every denied scope remains explicit", + "cancellation_class": "READ_ONLY_TERMINATE", + "recovery_class": "NONE", + "timeout_seconds": 120 + } + ] +} diff --git a/resources/tasks/windows/ad-inventory.ps1 b/resources/tasks/windows/ad-inventory.ps1 new file mode 100644 index 0000000..cccb8c5 --- /dev/null +++ b/resources/tasks/windows/ad-inventory.ps1 @@ -0,0 +1,44 @@ +# Fixed read-only AD DC inventory; no credentials. See manifest and adapter contract. +$ErrorActionPreference = 'Stop' +[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false) +Import-Module ActiveDirectory -ErrorAction Stop +$node = Get-CimInstance Win32_ComputerSystem +if ($node.DomainRole -lt 4) { throw 'Select the source AD domain controller.' } +$domain = Get-ADDomain -Server $node.Name +if ($domain.DNSRoot -ine 'corp.local') { throw 'Source domain must be corp.local.' } +$forest = Get-ADForest -Server $node.Name +$now = [DateTime]::UtcNow.ToString('o') +$source = $domain.ObjectGUID.ToString() +$objects = New-Object 'System.Collections.Generic.List[object]' +$truncated = $false +$allowed = @('objectSid','sAMAccountName','userPrincipalName','displayName','memberOf','groupType','userAccountControl','servicePrincipalName','gPLink','gPOptions') +Get-ADObject -Server $node.Name -LDAPFilter '(|(objectClass=user)(objectClass=group)(objectClass=organizationalUnit)(objectClass=groupPolicyContainer))' -SearchBase $domain.DistinguishedName -Properties $allowed -ResultSetSize 50001 | ForEach-Object { + if ($objects.Count -ge 50000) { $truncated = $true; return } + $item = $_ + $sid = '' + if ($null -ne $item.objectSid) { $sid = [string]$item.objectSid } + $kind = [string]$item.ObjectClass + if ($kind -eq 'groupPolicyContainer') { $kind = 'gpo' } + if (@('user','group','organizationalUnit','computer','gpo') -notcontains $kind) { $kind = 'other' } + $attributes = @{} + foreach ($name in $allowed) { + if ($name -ne 'objectSid' -and $name -ne 'memberOf' -and $null -ne $item.$name) { + $attributes[$name] = @($item.$name | ForEach-Object { [string]$_ }) + } + } + $objects.Add(@{ + source_system_id = $source; object_guid = $item.ObjectGUID.ToString(); sid = $sid + dn = $item.DistinguishedName; object_type = $kind; attributes = $attributes + memberships = @($item.memberOf | ForEach-Object { [string]$_ }); observed_at = $now + }) +} +@{ + schema_version = 1; source_system_id = $source; source_domain = $domain.DNSRoot; synthetic = $false + scope = @{ + description = ('Directory naming context: ' + $domain.DistinguishedName + '; forest mode: ' + $forest.ForestMode + '; domain mode: ' + $domain.DomainMode) + complete = $false + denied_or_unreachable = @('DNS/DHCP zone and lease content not collected','File data and ACLs not collected','GPO reports, SYSVOL and effective outcomes not collected','Service/application bindings and AD CS not collected','Password/profile continuity not evaluated',$(if ($truncated) { 'Object limit reached: partial inventory' } else { 'Directory ACL visibility must be verified by source owner' })) + categories = @('users','groups','ou','computers','gpo_links') + } + hosts = @(); objects = @($objects.ToArray()) +} | ConvertTo-Json -Depth 16 -Compress diff --git a/resources/tasks/windows/discovery.ps1 b/resources/tasks/windows/discovery.ps1 new file mode 100644 index 0000000..0188b09 --- /dev/null +++ b/resources/tasks/windows/discovery.ps1 @@ -0,0 +1,34 @@ +# ALD Transition Console / fixed read-only task / Windows PowerShell 5.1 +# No PowerShell SSH subsystem, profile, background job or persistent task. +$ErrorActionPreference = 'Stop' +[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false) +$errors = New-Object 'System.Collections.Generic.List[string]' +$os = Get-CimInstance -ClassName Win32_OperatingSystem +$computer = Get-CimInstance -ClassName Win32_ComputerSystem +$features = @() +try { + $features = @(Get-WindowsCapability -Online | Where-Object { $_.Name -like 'OpenSSH*' } | ForEach-Object { + @{ name = $_.Name; state = [string]$_.State } + }) +} catch { $errors.Add('Optional-feature inventory unavailable: elevation or servicing prerequisite required.') } +$ssh = Get-Service -Name sshd -ErrorAction SilentlyContinue +$result = @{ + schema_version = 1 + task = 'windows.discovery' + observed_at = [DateTime]::UtcNow.ToString('o') + os_edition = $os.Caption + os_release = $os.Version + os_build = $os.BuildNumber + architecture = $os.OSArchitecture + domain_role = [int]$computer.DomainRole + part_of_domain = [bool]$computer.PartOfDomain + domain = $computer.Domain + name = $computer.Name + powershell_version = $PSVersionTable.PSVersion.ToString() + optional_features = $features + feature_inventory_complete = ($errors.Count -eq 0) + sshd_state = $(if ($null -eq $ssh) { 'NOT_INSTALLED' } else { [string]$ssh.Status }) + errors = @($errors) + synthetic = $false +} +$result | ConvertTo-Json -Depth 8 -Compress diff --git a/schemas/checklist.schema.json b/schemas/checklist.schema.json new file mode 100644 index 0000000..823ad11 --- /dev/null +++ b/schemas/checklist.schema.json @@ -0,0 +1,201 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "urn:ald-transition:checklist", + "type": "object", + "properties": { + "schema_version": { + "const": 1 + }, + "items": { + "type": "array", + "maxItems": 1000, + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "maxLength": 128 + }, + "phase": { + "type": "string", + "maxLength": 128 + }, + "title_ru": { + "type": "string", + "maxLength": 4096 + }, + "purpose_ru": { + "type": "string", + "maxLength": 4096 + }, + "host_scope": { + "type": "array", + "maxItems": 10000, + "items": { + "type": "string", + "maxLength": 4096 + } + }, + "prerequisites": { + "type": "array", + "maxItems": 10000, + "items": { + "type": "string", + "maxLength": 4096 + } + }, + "steps_ru": { + "type": "array", + "maxItems": 10000, + "items": { + "type": "string", + "maxLength": 4096 + } + }, + "expected_result_ru": { + "type": "string", + "maxLength": 4096 + }, + "failure_guidance_ru": { + "type": "string", + "maxLength": 4096 + }, + "evidence_ids": { + "type": "array", + "maxItems": 10000, + "items": { + "type": "string", + "maxLength": 4096 + } + } + }, + "required": [ + "id", + "phase", + "title_ru", + "purpose_ru", + "host_scope", + "prerequisites", + "steps_ru", + "expected_result_ru", + "failure_guidance_ru", + "evidence_ids" + ], + "additionalProperties": false + } + }, + "observations": { + "type": "array", + "maxItems": 50000, + "items": { + "type": "object", + "properties": { + "item_id": { + "type": "string", + "maxLength": 4096 + }, + "host_id": { + "type": "string", + "maxLength": 4096 + }, + "result": { + "enum": [ + "PASS", + "FAIL", + "PARTIAL", + "NOT_CHECKED", + "ERROR", + "STALE" + ] + }, + "checked_by": { + "type": "string", + "maxLength": 4096 + }, + "checked_at": { + "type": "string", + "maxLength": 40, + "format": "date-time" + }, + "method": { + "enum": [ + "HUMAN", + "AUTOMATIC" + ] + }, + "note": { + "type": "string", + "maxLength": 4096 + }, + "plan_revision": { + "type": "integer", + "minimum": 1, + "maximum": 2147483647 + }, + "profile_revision": { + "type": "integer", + "minimum": 1, + "maximum": 2147483647 + }, + "applicability": { + "enum": [ + "APPLICABLE", + "NOT_APPLICABLE_WITH_REASON", + "UNKNOWN" + ] + }, + "evidence_ids": { + "type": "array", + "maxItems": 10000, + "items": { + "type": "string", + "maxLength": 4096 + } + }, + "original_result": { + "enum": [ + "PASS", + "FAIL", + "PARTIAL", + "NOT_CHECKED", + "ERROR", + "STALE" + ] + }, + "sequence": { + "type": "integer", + "minimum": 1 + } + }, + "required": [ + "item_id", + "host_id", + "result", + "checked_by", + "checked_at", + "method", + "note", + "plan_revision", + "profile_revision", + "applicability", + "evidence_ids" + ], + "additionalProperties": false + } + }, + "context_digest": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + }, + "exported_at": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "schema_version", + "items", + "observations" + ], + "additionalProperties": false +} diff --git a/schemas/host.schema.json b/schemas/host.schema.json new file mode 100644 index 0000000..a61c0e7 --- /dev/null +++ b/schemas/host.schema.json @@ -0,0 +1,85 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "urn:ald-transition:host", + "type": "object", + "properties": { + "id": { + "type": "string", + "maxLength": 36, + "format": "uuid" + }, + "fqdn": { + "type": "string", + "maxLength": 253, + "format": "hostname" + }, + "addresses": { + "type": "array", + "maxItems": 32, + "items": { + "type": "string", + "maxLength": 45, + "format": "ip-address" + } + }, + "os_family": { + "enum": [ + "WINDOWS", + "ASTRA", + "LINUX", + "UNKNOWN" + ] + }, + "os_release": { + "type": "string", + "maxLength": 4096 + }, + "os_build": { + "type": "string", + "maxLength": 4096 + }, + "kernel": { + "type": "string", + "maxLength": 4096 + }, + "architecture": { + "type": "string", + "maxLength": 4096 + }, + "detected_roles": { + "type": "array", + "maxItems": 10000, + "items": { + "type": "string", + "maxLength": 4096 + } + }, + "observed_at": { + "type": "string", + "maxLength": 40, + "format": "date-time" + }, + "evidence_ids": { + "type": "array", + "maxItems": 10000, + "items": { + "type": "string", + "maxLength": 4096 + } + } + }, + "required": [ + "id", + "fqdn", + "addresses", + "os_family", + "os_release", + "os_build", + "kernel", + "architecture", + "detected_roles", + "observed_at", + "evidence_ids" + ], + "additionalProperties": false +} diff --git a/schemas/inventory.schema.json b/schemas/inventory.schema.json new file mode 100644 index 0000000..18e46c5 --- /dev/null +++ b/schemas/inventory.schema.json @@ -0,0 +1,225 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "urn:ald-transition:inventory", + "type": "object", + "properties": { + "schema_version": { + "const": 1 + }, + "source_system_id": { + "type": "string", + "maxLength": 36, + "format": "uuid" + }, + "synthetic": { + "type": "boolean" + }, + "scope": { + "type": "object", + "properties": { + "description": { + "type": "string", + "maxLength": 4096 + }, + "complete": { + "type": "boolean" + }, + "denied_or_unreachable": { + "type": "array", + "maxItems": 10000, + "items": { + "type": "string", + "maxLength": 4096 + } + }, + "categories": { + "type": "array", + "maxItems": 32, + "items": { + "type": "string", + "maxLength": 128 + } + } + }, + "required": [ + "description", + "complete", + "denied_or_unreachable", + "categories" + ], + "additionalProperties": false + }, + "hosts": { + "type": "array", + "maxItems": 10000, + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "maxLength": 36, + "format": "uuid" + }, + "fqdn": { + "type": "string", + "maxLength": 253, + "format": "hostname" + }, + "addresses": { + "type": "array", + "maxItems": 32, + "items": { + "type": "string", + "maxLength": 45, + "format": "ip-address" + } + }, + "os_family": { + "enum": [ + "WINDOWS", + "ASTRA", + "LINUX", + "UNKNOWN" + ] + }, + "os_release": { + "type": "string", + "maxLength": 4096 + }, + "os_build": { + "type": "string", + "maxLength": 4096 + }, + "kernel": { + "type": "string", + "maxLength": 4096 + }, + "architecture": { + "type": "string", + "maxLength": 4096 + }, + "detected_roles": { + "type": "array", + "maxItems": 10000, + "items": { + "type": "string", + "maxLength": 4096 + } + }, + "observed_at": { + "type": "string", + "maxLength": 40, + "format": "date-time" + }, + "evidence_ids": { + "type": "array", + "maxItems": 10000, + "items": { + "type": "string", + "maxLength": 4096 + } + } + }, + "required": [ + "id", + "fqdn", + "addresses", + "os_family", + "os_release", + "os_build", + "kernel", + "architecture", + "detected_roles", + "observed_at", + "evidence_ids" + ], + "additionalProperties": false + } + }, + "objects": { + "type": "array", + "maxItems": 50000, + "items": { + "type": "object", + "properties": { + "source_system_id": { + "type": "string", + "maxLength": 36, + "format": "uuid" + }, + "object_guid": { + "type": "string", + "maxLength": 36, + "format": "uuid" + }, + "sid": { + "type": "string", + "maxLength": 184 + }, + "dn": { + "type": "string", + "maxLength": 4096 + }, + "object_type": { + "enum": [ + "user", + "group", + "organizationalUnit", + "computer", + "dns", + "gpo", + "share", + "service", + "dhcp", + "certificate", + "other" + ] + }, + "attributes": { + "type": "object", + "additionalProperties": true + }, + "memberships": { + "type": "array", + "maxItems": 10000, + "items": { + "type": "string", + "maxLength": 4096 + } + }, + "observed_at": { + "type": "string", + "maxLength": 40, + "format": "date-time" + } + }, + "required": [ + "source_system_id", + "object_guid", + "sid", + "dn", + "object_type", + "attributes", + "memberships", + "observed_at" + ], + "additionalProperties": false + } + }, + "source_domain": { + "type": "string", + "maxLength": 253, + "format": "hostname" + } + }, + "required": [ + "schema_version", + "source_system_id", + "synthetic", + "scope", + "hosts", + "objects", + "source_domain" + ], + "additionalProperties": false +} diff --git a/schemas/offline-bundle.schema.json b/schemas/offline-bundle.schema.json new file mode 100644 index 0000000..27e4c15 --- /dev/null +++ b/schemas/offline-bundle.schema.json @@ -0,0 +1,89 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "additionalProperties": false, + "required": [ + "schema_version", + "revision", + "provenance", + "artifacts" + ], + "properties": { + "schema_version": { + "const": 1 + }, + "revision": { + "type": "integer", + "minimum": 1 + }, + "provenance": { + "type": "object", + "additionalProperties": false, + "required": [ + "publisher", + "version", + "source_url", + "signature_reference" + ], + "properties": { + "publisher": { + "type": "string", + "maxLength": 4096 + }, + "version": { + "type": "string", + "maxLength": 4096 + }, + "source_url": { + "type": "string", + "maxLength": 4096 + }, + "signature_reference": { + "type": "string", + "maxLength": 4096 + } + } + }, + "artifacts": { + "type": "array", + "maxItems": 64, + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "path", + "kind", + "sha256", + "base64", + "source_id" + ], + "properties": { + "path": { + "type": "string", + "maxLength": 512 + }, + "kind": { + "enum": [ + "inventory", + "profile", + "checklist", + "source" + ] + }, + "sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + }, + "base64": { + "type": "string", + "maxLength": 65536 + }, + "source_id": { + "type": "string", + "maxLength": 4096 + } + } + } + } + } +} diff --git a/schemas/operation.schema.json b/schemas/operation.schema.json new file mode 100644 index 0000000..f419b55 --- /dev/null +++ b/schemas/operation.schema.json @@ -0,0 +1,80 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "urn:ald-transition:operation", + "type": "object", + "properties": { + "id": { + "type": "string", + "maxLength": 128 + }, + "adapter_id": { + "type": "string", + "maxLength": 128 + }, + "adapter_version": { + "type": "string", + "maxLength": 64 + }, + "target_id": { + "type": "string", + "maxLength": 128 + }, + "typed_parameters": { + "type": "object", + "additionalProperties": true + }, + "preconditions": { + "type": "array", + "maxItems": 10000, + "items": { + "type": "string", + "maxLength": 4096 + } + }, + "effects": { + "type": "array", + "maxItems": 10000, + "items": { + "type": "string", + "maxLength": 4096 + } + }, + "cancellation_class": { + "enum": [ + "READ_ONLY_TERMINATE", + "SAFE_BOUNDARY", + "NOT_CANCELLABLE" + ] + }, + "recovery_class": { + "enum": [ + "NONE", + "RECONCILE", + "REBOOT_REQUIRED", + "RESTORE_BACKUP", + "MANUAL" + ] + }, + "postconditions": { + "type": "array", + "maxItems": 10000, + "items": { + "type": "string", + "maxLength": 4096 + } + } + }, + "required": [ + "id", + "adapter_id", + "adapter_version", + "target_id", + "typed_parameters", + "preconditions", + "effects", + "cancellation_class", + "recovery_class", + "postconditions" + ], + "additionalProperties": false +} diff --git a/schemas/plan.schema.json b/schemas/plan.schema.json new file mode 100644 index 0000000..b0bb165 --- /dev/null +++ b/schemas/plan.schema.json @@ -0,0 +1,207 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "urn:ald-transition:plan", + "type": "object", + "properties": { + "schema_version": { + "const": 1 + }, + "id": { + "type": "string", + "maxLength": 36, + "format": "uuid" + }, + "revision": { + "type": "integer", + "minimum": 1, + "maximum": 2147483647 + }, + "inventory_digest": { + "type": "string", + "maxLength": 4096, + "pattern": "^[a-f0-9]{64}$" + }, + "policy_digest": { + "type": "string", + "maxLength": 4096, + "pattern": "^[a-f0-9]{64}$" + }, + "mapping_digest": { + "type": "string", + "maxLength": 4096, + "pattern": "^[a-f0-9]{64}$" + }, + "affected_hosts": { + "type": "array", + "maxItems": 10000, + "items": { + "type": "string", + "maxLength": 4096 + } + }, + "graph": { + "type": "array", + "maxItems": 1024, + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "maxLength": 128 + }, + "operation": { + "type": "object", + "properties": { + "id": { + "type": "string", + "maxLength": 128 + }, + "adapter_id": { + "type": "string", + "maxLength": 128 + }, + "adapter_version": { + "type": "string", + "maxLength": 64 + }, + "target_id": { + "type": "string", + "maxLength": 128 + }, + "typed_parameters": { + "type": "object", + "additionalProperties": true + }, + "preconditions": { + "type": "array", + "maxItems": 10000, + "items": { + "type": "string", + "maxLength": 4096 + } + }, + "effects": { + "type": "array", + "maxItems": 10000, + "items": { + "type": "string", + "maxLength": 4096 + } + }, + "cancellation_class": { + "enum": [ + "READ_ONLY_TERMINATE", + "SAFE_BOUNDARY", + "NOT_CANCELLABLE" + ] + }, + "recovery_class": { + "enum": [ + "NONE", + "RECONCILE", + "REBOOT_REQUIRED", + "RESTORE_BACKUP", + "MANUAL" + ] + }, + "postconditions": { + "type": "array", + "maxItems": 10000, + "items": { + "type": "string", + "maxLength": 4096 + } + } + }, + "required": [ + "id", + "adapter_id", + "adapter_version", + "target_id", + "typed_parameters", + "preconditions", + "effects", + "cancellation_class", + "recovery_class", + "postconditions" + ], + "additionalProperties": false + }, + "dependencies": { + "type": "array", + "maxItems": 1024, + "items": { + "type": "string", + "maxLength": 128 + } + } + }, + "required": [ + "id", + "operation", + "dependencies" + ], + "additionalProperties": false + } + }, + "error_policy": { + "enum": [ + "STOP_ON_ERROR", + "CONTINUE_INDEPENDENT", + "PAUSE_FOR_DECISION" + ] + }, + "downtime": { + "type": "object", + "properties": { + "duration_minutes": { + "type": [ + "integer", + "null" + ], + "minimum": 0 + }, + "impact_ru": { + "type": "string", + "maxLength": 4096 + }, + "recovery_ru": { + "type": "string", + "maxLength": 4096 + }, + "point_of_no_return_ru": { + "type": "string", + "maxLength": 4096 + } + }, + "required": [ + "duration_minutes", + "impact_ru", + "recovery_ru", + "point_of_no_return_ru" + ], + "additionalProperties": false + }, + "authorization_state": { + "enum": [ + "NOT_AUTHORIZED", + "AUTHORIZED", + "INVALIDATED" + ] + } + }, + "required": [ + "schema_version", + "id", + "revision", + "inventory_digest", + "policy_digest", + "mapping_digest", + "affected_hosts", + "graph", + "error_policy", + "downtime", + "authorization_state" + ], + "additionalProperties": false +} diff --git a/schemas/profile.schema.json b/schemas/profile.schema.json new file mode 100644 index 0000000..6062afb --- /dev/null +++ b/schemas/profile.schema.json @@ -0,0 +1,134 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "urn:ald-transition:profile", + "type": "object", + "properties": { + "schema_version": { + "const": 1 + }, + "id": { + "type": "string", + "maxLength": 36, + "format": "uuid" + }, + "revision": { + "type": "integer", + "minimum": 1, + "maximum": 2147483647 + }, + "os_constraints": { + "type": "array", + "maxItems": 10000, + "items": { + "type": "string", + "maxLength": 4096 + } + }, + "role_constraints": { + "type": "array", + "maxItems": 10000, + "items": { + "type": "string", + "maxLength": 4096 + } + }, + "settings": { + "type": "array", + "maxItems": 1000, + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "maxLength": 4096 + }, + "desired_value": {}, + "source_refs": { + "type": "array", + "maxItems": 10000, + "items": { + "type": "string", + "maxLength": 4096 + } + }, + "management_owner": { + "type": "string", + "maxLength": 4096 + }, + "applicability": { + "enum": [ + "APPLICABLE", + "NOT_APPLICABLE_WITH_REASON", + "UNKNOWN" + ] + } + }, + "required": [ + "id", + "desired_value", + "source_refs", + "management_owner", + "applicability" + ], + "additionalProperties": false + } + }, + "management_owner": { + "type": "string", + "maxLength": 4096 + }, + "exceptions": { + "type": "array", + "maxItems": 10000, + "items": { + "type": "object", + "properties": { + "scope": { + "type": "string", + "maxLength": 4096 + }, + "owner": { + "type": "string", + "maxLength": 4096 + }, + "reason": { + "type": "string", + "maxLength": 4096 + }, + "review_date": { + "type": "string", + "maxLength": 40, + "format": "date-time" + } + }, + "required": [ + "scope", + "owner", + "reason", + "review_date" + ], + "additionalProperties": false + } + }, + "source_refs": { + "type": "array", + "maxItems": 10000, + "items": { + "type": "string", + "maxLength": 4096 + } + } + }, + "required": [ + "schema_version", + "id", + "revision", + "os_constraints", + "role_constraints", + "settings", + "management_owner", + "exceptions", + "source_refs" + ], + "additionalProperties": false +} diff --git a/schemas/project.schema.json b/schemas/project.schema.json new file mode 100644 index 0000000..13f4509 --- /dev/null +++ b/schemas/project.schema.json @@ -0,0 +1,63 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "urn:ald-transition:project", + "type": "object", + "properties": { + "id": { + "type": "string", + "maxLength": 36, + "format": "uuid" + }, + "schema_version": { + "const": 1 + }, + "target_domain": { + "type": "string", + "maxLength": 253, + "format": "hostname" + }, + "source_domain": { + "type": "string", + "maxLength": 253, + "format": "hostname" + }, + "desired_outcomes": { + "type": "array", + "maxItems": 32, + "items": { + "type": "string", + "maxLength": 128 + } + }, + "lab_mode": { + "type": "boolean" + }, + "created_at": { + "type": "string", + "maxLength": 40, + "format": "date-time" + }, + "updated_at": { + "type": "string", + "maxLength": 40, + "format": "date-time" + }, + "version": { + "type": "integer", + "minimum": 1, + "maximum": 2147483647 + } + }, + "required": [ + "id", + "schema_version", + "target_domain", + "source_domain", + "desired_outcomes", + "lab_mode", + "created_at", + "updated_at", + "version" + ], + "additionalProperties": false +} diff --git a/schemas/source.schema.json b/schemas/source.schema.json new file mode 100644 index 0000000..25badf5 --- /dev/null +++ b/schemas/source.schema.json @@ -0,0 +1,92 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "urn:ald-transition:source", + "type": "object", + "properties": { + "schema_version": { + "const": 1 + }, + "revision": { + "type": "integer", + "minimum": 1, + "maximum": 2147483647 + }, + "sources": { + "type": "array", + "maxItems": 1000, + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "maxLength": 4096 + }, + "url": { + "type": "string", + "maxLength": 4096, + "format": "uri" + }, + "title": { + "type": "string", + "maxLength": 4096 + }, + "product_version": { + "type": [ + "string", + "null" + ], + "maxLength": 4096 + }, + "section": { + "type": "string", + "maxLength": 4096 + }, + "retrieved_at": { + "type": [ + "string", + "null" + ] + }, + "artifact_sha256": { + "type": [ + "string", + "null" + ], + "pattern": "^[a-f0-9]{64}$" + }, + "verification_state": { + "enum": [ + "reviewed_web", + "not_retrieved", + "retrieval_failed", + "pending_original", + "verified_artifact" + ] + }, + "notes": { + "type": "string", + "maxLength": 4096 + } + }, + "required": [ + "id", + "url", + "title", + "product_version", + "section", + "retrieved_at", + "artifact_sha256", + "verification_state", + "notes" + ], + "additionalProperties": false + } + } + }, + "required": [ + "schema_version", + "revision", + "sources" + ], + "additionalProperties": false +} diff --git a/schemas/windows-discovery.schema.json b/schemas/windows-discovery.schema.json new file mode 100644 index 0000000..5788fb2 --- /dev/null +++ b/schemas/windows-discovery.schema.json @@ -0,0 +1,112 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "properties": { + "schema_version": { + "const": 1 + }, + "task": { + "const": "windows.discovery" + }, + "observed_at": { + "type": "string", + "format": "date-time" + }, + "os_edition": { + "type": "string", + "maxLength": 4096 + }, + "os_release": { + "type": "string", + "maxLength": 4096 + }, + "os_build": { + "type": "string", + "maxLength": 4096 + }, + "architecture": { + "type": "string", + "maxLength": 4096 + }, + "domain_role": { + "type": "integer", + "minimum": 0, + "maximum": 5 + }, + "part_of_domain": { + "type": "boolean" + }, + "domain": { + "type": "string", + "maxLength": 4096 + }, + "name": { + "type": "string", + "maxLength": 4096 + }, + "powershell_version": { + "type": "string", + "maxLength": 4096 + }, + "optional_features": { + "type": "array", + "maxItems": 16, + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "maxLength": 4096 + }, + "state": { + "type": "string", + "maxLength": 4096 + } + }, + "required": [ + "name", + "state" + ], + "additionalProperties": false + } + }, + "feature_inventory_complete": { + "type": "boolean" + }, + "sshd_state": { + "type": "string", + "maxLength": 4096 + }, + "errors": { + "type": "array", + "maxItems": 100, + "items": { + "type": "string", + "maxLength": 4096 + } + }, + "synthetic": { + "const": false + } + }, + "required": [ + "schema_version", + "task", + "observed_at", + "os_edition", + "os_release", + "os_build", + "architecture", + "domain_role", + "part_of_domain", + "domain", + "name", + "powershell_version", + "optional_features", + "feature_inventory_complete", + "sshd_state", + "errors", + "synthetic" + ], + "additionalProperties": false +} diff --git a/src/adapters/AdInventory.cpp b/src/adapters/AdInventory.cpp new file mode 100644 index 0000000..e34a239 --- /dev/null +++ b/src/adapters/AdInventory.cpp @@ -0,0 +1,24 @@ +#include "AdInventory.h" +#include "storage/JsonValidator.h" +#include +#include +#include +#include +namespace ald { +QJsonObject AdInventory::parse(const QByteArray &bytes,bool demo) { + auto o=JsonValidator::parse(bytes,"inventory").object(); + if(o.value("synthetic").toBool()!=demo)throw std::runtime_error("Synthetic and live inventory cannot share a project"); + if(o.value("source_domain").toString().compare("corp.local",Qt::CaseInsensitive)!=0)throw std::runtime_error("Inventory source domain differs from the accepted corp.local project"); + QSet guids,sids; + for(const auto &v:o.value("objects").toArray()) { + const auto item=v.toObject();const auto guid=item.value("object_guid").toString().toLower(),sid=item.value("sid").toString(),dn=item.value("dn").toString(); + if(item.value("source_system_id")!=o.value("source_system_id")||guids.contains(guid))throw std::runtime_error("Duplicate or mismatched source GUID");guids.insert(guid); + if(!sid.isEmpty()) {if(!QRegularExpression("^S-1-[0-9]+(-[0-9]+){1,15}$").match(sid).hasMatch()||sids.contains(sid))throw std::runtime_error("Invalid or duplicate source SID");sids.insert(sid);} + // DN remains an opaque UTF-8 identifier, never concatenated into LDAP. + // Reject control characters, missing RDN syntax and dangling escape. + if(dn.isEmpty()||!dn.contains('=')||dn.contains(QRegularExpression("[\\x00-\\x1f\\x7f]")))throw std::runtime_error("Invalid DN serialization"); + int trailing=0;for(int i=dn.size()-1;i>=0&&dn[i]=='\\';--i)++trailing;if(trailing%2)throw std::runtime_error("Dangling DN escape"); + } + return o; +} +} diff --git a/src/adapters/AdInventory.h b/src/adapters/AdInventory.h new file mode 100644 index 0000000..144eca3 --- /dev/null +++ b/src/adapters/AdInventory.h @@ -0,0 +1,3 @@ +#pragma once +#include +namespace ald {class AdInventory {public:static QJsonObject parse(const QByteArray &bytes,bool demo);};} diff --git a/src/adapters/Ald31Administration.cpp b/src/adapters/Ald31Administration.cpp new file mode 100644 index 0000000..364df8d --- /dev/null +++ b/src/adapters/Ald31Administration.cpp @@ -0,0 +1,3 @@ +#include "Ald31Administration.h" +#include +namespace ald {QJsonArray Ald31Administration::workflows(){QJsonArray out;for(const auto *name:{"Пользователи и группы","Организационная структура","Регистрация компьютеров","DNS и время","Политика паролей","HBAC","Sudo","Службы домена"})out.append(QJsonObject{{"title_ru",name},{"support","DOCUMENTED_NOT_TESTED"},{"disposition","GUIDED_NATIVE"},{"source_ref","ALD31_ROOT"},{"facts_ru","Отдельное наблюдение текущего значения ещё не получено"},{"changes_ru","Открыть соответствующий раздел штатного портала/руководства ALD 3.1. Зафиксировать объект, исходное значение, назначение и владельца. API приложения для записи не реализован."},{"verification_ru","Проверить результат на целевом объекте и пилотном пользователе. Изменение имени существующего КД требует поддержанной процедуры замены; переименование hostname не предлагается."}});return out;}} diff --git a/src/adapters/Ald31Administration.h b/src/adapters/Ald31Administration.h new file mode 100644 index 0000000..8c31b95 --- /dev/null +++ b/src/adapters/Ald31Administration.h @@ -0,0 +1,3 @@ +#pragma once +#include +namespace ald {class Ald31Administration {public:static QJsonArray workflows();};} diff --git a/src/adapters/Ald31Deployment.cpp b/src/adapters/Ald31Deployment.cpp new file mode 100644 index 0000000..c173673 --- /dev/null +++ b/src/adapters/Ald31Deployment.cpp @@ -0,0 +1,5 @@ +#include "Ald31Deployment.h" +#include +namespace ald { +QJsonObject Ald31Deployment::guidedContract(){return {{"adapter_id","ald31.deployment"},{"adapter_version","0.1.0"},{"capability_state","DOCUMENTED_NOT_TESTED"},{"disposition","GUIDED_NATIVE"},{"source_refs",QJsonArray{"ALD31_PROMOTION","ALD31_OS","ALD31_PACKAGES"}},{"template","sudo aldpro-server-install -d -n --ip --no-reboot"},{"secret_channel","Штатный интерактивный запрос в локальном терминале; пароли не принимает GUI"},{"role_flags_ru","--setup_gc и --setup_syncer добавлять только для заранее установленных и предусмотренных планом ролей; не переносить флаги обновления на существующий КД"},{"postconditions",QJsonArray{"После контролируемой перезагрузки: sudo aldproctl status","Прямой/обратный DNS, SRV, синхронизация времени","Доступ к порталу, штатная клиентская регистрация и вход пилотного пользователя"}},{"cancellation_class","NOT_CANCELLABLE"},{"recovery_class","RESTORE_BACKUP"},{"execution_enabled",false},{"reason_ru","Страница подтверждает интерактивный ввод, но точные пакеты, help и лабораторная процедура не проверены. Автоматическая инициализация недоступна."}};} +} diff --git a/src/adapters/Ald31Deployment.h b/src/adapters/Ald31Deployment.h new file mode 100644 index 0000000..b8e2cca --- /dev/null +++ b/src/adapters/Ald31Deployment.h @@ -0,0 +1,3 @@ +#pragma once +#include +namespace ald {class Ald31Deployment {public:static QJsonObject guidedContract();};} diff --git a/src/adapters/Ald31Migration.cpp b/src/adapters/Ald31Migration.cpp new file mode 100644 index 0000000..3ae9d2a --- /dev/null +++ b/src/adapters/Ald31Migration.cpp @@ -0,0 +1,2 @@ +#include "Ald31Migration.h" +namespace ald {QJsonObject Ald31Migration::contract(){return {{"state","DOCUMENTED_NOT_TESTED"},{"source_ref","ALD31_MIGRATION"},{"disposition","GUIDED_NATIVE"},{"steps_ru","После подтверждения совместимого сценария: портал ALD → Управление доменом → Интеграция с доменами → Миграции MS AD. Проверить область и сопоставления в пилоте. corp.local сейчас не прошёл проверку реализуемости; запуск заблокирован."},{"execution_enabled",false}};}} diff --git a/src/adapters/Ald31Migration.h b/src/adapters/Ald31Migration.h new file mode 100644 index 0000000..9de2a36 --- /dev/null +++ b/src/adapters/Ald31Migration.h @@ -0,0 +1,3 @@ +#pragma once +#include +namespace ald {class Ald31Migration {public:static QJsonObject contract();};} diff --git a/src/adapters/Ald31Policies.cpp b/src/adapters/Ald31Policies.cpp new file mode 100644 index 0000000..3af1a8f --- /dev/null +++ b/src/adapters/Ald31Policies.cpp @@ -0,0 +1,3 @@ +#include "Ald31Policies.h" +#include +namespace ald {QJsonObject Ald31Policies::contract(){return {{"state","DOCUMENTED_NOT_TESTED"},{"owner","ALD_POLICY"},{"stages",QJsonArray{"назначена","получена","включена в результирующую конфигурацию","штатное применение завершено","эффективное значение проверено","поведение пользователя проверено"}},{"guidance_ru","Менять исходную политику в штатном портале ALD 3.1; не редактировать генерируемый локальный кэш. Отмена назначения не гарантирует возврат прежнего значения."}};}} diff --git a/src/adapters/Ald31Policies.h b/src/adapters/Ald31Policies.h new file mode 100644 index 0000000..3ae9baf --- /dev/null +++ b/src/adapters/Ald31Policies.h @@ -0,0 +1,3 @@ +#pragma once +#include +namespace ald {class Ald31Policies {public:static QJsonObject contract();};} diff --git a/src/adapters/Astra17Discovery.cpp b/src/adapters/Astra17Discovery.cpp new file mode 100644 index 0000000..d4f5ee0 --- /dev/null +++ b/src/adapters/Astra17Discovery.cpp @@ -0,0 +1,38 @@ +#include "Astra17Discovery.h" +#include +#include +#include +namespace ald { +QString Astra17Discovery::roleName(NodeRole r){switch(r){case NodeRole::CleanAstra:return "CLEAN_ASTRA";case NodeRole::PackagesOnly:return "ALD_PACKAGES_NOT_INITIALIZED";case NodeRole::AdClient:return "AD_CLIENT";case NodeRole::AldClient:return "ALD_CLIENT";case NodeRole::DcHealthy:return "ALD_DC_HEALTHY";case NodeRole::DcDegraded:return "ALD_DC_DEGRADED";default:return "PARTIAL_OR_UNKNOWN";}} +LocalDiscovery Astra17Discovery::interpret(const QMap &results) { + LocalDiscovery d;rules::RoleFacts role;QStringList aldPackages; + auto ok=[&](const QString &id){auto it=results.find(id);return it!=results.end()&&it->normalExit&&it->exitCode==0&&!it->timedOut&&!it->cancelled&&!it->outputExceeded&&!it->failedToStart;}; + const auto os=QString::fromUtf8(results.value("local.os").out);role.astra=QRegularExpression("(^|\n)ID=\"?astra\"?(\n|$)").match(os).hasMatch(); + role.packageQueryComplete=ok("local.packages"); + for(const auto &line:QString::fromUtf8(results.value("local.packages").out).split('\n')) { + auto parts=line.split('\t');if(parts.size()!=3||parts[2]!="installed")continue; + if(parts[0].startsWith("aldpro")){aldPackages<out).trimmed();if(it.key()=="local.packages")value=aldPackages.isEmpty()?"Пакеты ALD не найдены в доступной выдаче":aldPackages.join('\n'); + if(it.key()=="local.ssh_version")value=QString::fromUtf8(it->err).trimmed(); + const bool success=ok(it.key()); + d.findings.append(QJsonObject{{"check",it.key()},{"observed",value.left(16000)},{"expected","Сверить с ALD 3.1.0 / ALSE 1.7.7 UU2 и выбранной ролью"},{"result",success?"OBSERVED":"ERROR"},{"observed_at",utcNow()},{"why_ru","Наблюдение — вход для проверки совместимости; само по себе не подтверждает готовность"},{"next_ru",it->failedToStart?"Отсутствует штатная утилита: нужен одобренный пакет/носитель. Автоустановка отключена.":"Сверить значение с паспортом поставки; при ошибке открыть нативную диагностику"},{"exit_code",it->exitCode},{"native_error",QString::fromUtf8(it->err).left(4096)}}); + } + d.findings.append(QJsonObject{{"check","compatibility.delivery"},{"observed",role.astra?"Astra обнаружена; обновление и уровень защиты не подтверждены":"Текущая ОС не распознана как Astra"},{"expected","ALD Pro 3.1.0 + ALSE 1.7.7 UU2 / 6.1-generic / Смоленск"},{"result","NOT_CHECKED"},{"observed_at",utcNow()},{"why_ru","Работа GUI и поддержка КД проверяются отдельно"},{"next_ru","Сохранить точный паспорт пакетов, проверить установку в лаборатории; не обновлять ОС автоматически"}}); + return d; +} +} diff --git a/src/adapters/Astra17Discovery.h b/src/adapters/Astra17Discovery.h new file mode 100644 index 0000000..d4e9755 --- /dev/null +++ b/src/adapters/Astra17Discovery.h @@ -0,0 +1,10 @@ +#pragma once +#include "domain/Types.h" +#include "execution/ProcessRunner.h" +#include +namespace ald { +struct LocalDiscovery {QJsonArray findings;QJsonObject facts;NodeRole role=NodeRole::PartialOrUnknown;}; +class Astra17Discovery { +public:static LocalDiscovery interpret(const QMap &results);static QString roleName(NodeRole role); +}; +} diff --git a/src/adapters/CompatibilityResolver.cpp b/src/adapters/CompatibilityResolver.cpp new file mode 100644 index 0000000..a4c89b5 --- /dev/null +++ b/src/adapters/CompatibilityResolver.cpp @@ -0,0 +1,10 @@ +#include "CompatibilityResolver.h" +namespace ald { +QJsonArray CompatibilityResolver::evaluate(const QJsonObject &f){return QJsonArray{ + QJsonObject{{"operation","gui"},{"state","DOCUMENTED_NOT_TESTED"},{"reason_ru","Qt 5.15.2 API; точные пакеты и тестирование Astra ожидаются"}}, + QJsonObject{{"operation","controller.install"},{"state",f.value("astra").toBool()?"UNKNOWN":"UNSUPPORTED"},{"reason_ru","Требуются ALSE 1.7.7 UU2, 6.1-generic, Смоленск, ALD 3.1.0 и разрешённый состав ПО на КД"}}, + QJsonObject{{"operation","windows.ssh"},{"state","DOCUMENTED_NOT_TESTED"},{"reason_ru","OS build, edition, role, PowerShell и optional features проверяются на каждом узле"}}, + QJsonObject{{"operation","windows2025.domain_integration"},{"state","UNKNOWN"},{"reason_ru","Успешный SSH не снимает блокировку интеграции Windows Server 2025"}}, + QJsonObject{{"operation","migration.same_name"},{"state","UNKNOWN"},{"reason_ru","corp.local и сохранение пользовательского поведения требуют отдельной проверенной процедуры"}} +};} +} diff --git a/src/adapters/CompatibilityResolver.h b/src/adapters/CompatibilityResolver.h new file mode 100644 index 0000000..eec5d7a --- /dev/null +++ b/src/adapters/CompatibilityResolver.h @@ -0,0 +1,4 @@ +#pragma once +#include +#include +namespace ald {class CompatibilityResolver {public:static QJsonArray evaluate(const QJsonObject &facts);};} diff --git a/src/adapters/WindowsDiscovery.cpp b/src/adapters/WindowsDiscovery.cpp new file mode 100644 index 0000000..3ca6b61 --- /dev/null +++ b/src/adapters/WindowsDiscovery.cpp @@ -0,0 +1,6 @@ +#include "WindowsDiscovery.h" +#include "storage/JsonValidator.h" +#include +namespace ald { +QJsonObject WindowsDiscovery::parse(const QByteArray &bytes){auto o=JsonValidator::parse(bytes,"windows-discovery").object();o["ald_domain_integration"]="UNKNOWN";o["transport_observed"]=true;return o;} +} diff --git a/src/adapters/WindowsDiscovery.h b/src/adapters/WindowsDiscovery.h new file mode 100644 index 0000000..6752e7d --- /dev/null +++ b/src/adapters/WindowsDiscovery.h @@ -0,0 +1,3 @@ +#pragma once +#include +namespace ald {class WindowsDiscovery {public:static QJsonObject parse(const QByteArray &bytes);};} diff --git a/src/adapters/WindowsLocalPolicy.cpp b/src/adapters/WindowsLocalPolicy.cpp new file mode 100644 index 0000000..b41259b --- /dev/null +++ b/src/adapters/WindowsLocalPolicy.cpp @@ -0,0 +1,2 @@ +#include "WindowsLocalPolicy.h" +namespace ald {QJsonObject WindowsLocalPolicy::contract(const QString &build){return {{"os_build",build},{"state","UNKNOWN"},{"source_ref","MS_SCT"},{"guidance_ru","Сначала сохранить gpresult /r и отчёт GPO штатными средствами. Каждую настройку сопоставить с edition/build. LGPO допускается после проверки версии, происхождения, целостности и эффекта. Linux sysctl/PAM для Windows не применимы."},{"execution_enabled",false}};}} diff --git a/src/adapters/WindowsLocalPolicy.h b/src/adapters/WindowsLocalPolicy.h new file mode 100644 index 0000000..b30873f --- /dev/null +++ b/src/adapters/WindowsLocalPolicy.h @@ -0,0 +1,3 @@ +#pragma once +#include +namespace ald {class WindowsLocalPolicy {public:static QJsonObject contract(const QString &build);};} diff --git a/src/app/AppController.cpp b/src/app/AppController.cpp new file mode 100644 index 0000000..4207282 --- /dev/null +++ b/src/app/AppController.cpp @@ -0,0 +1,184 @@ +#include "AppController.h" +#include "domain/Types.h" +#include "storage/JsonValidator.h" +#include "storage/OfflineBundle.h" +#include "execution/OperationRegistry.h" +#include "adapters/AdInventory.h" +#include "adapters/WindowsDiscovery.h" +#include "workflows/IdentityMapper.h" +#include "workflows/MigrationPlanner.h" +#include "workflows/InitializationPlanner.h" +#include "workflows/PolicyPlanner.h" +#include +#include +#include +#include +#include + +static void initResources(){Q_INIT_RESOURCE(resources);} +namespace ald { +static QByteArray asset(const QString &path){QFile f(path);if(!f.open(QIODevice::ReadOnly))throw std::runtime_error("Missing installed asset");return f.readAll();} +AppController::AppController(QObject *parent):QObject(parent),executor_(this),shutdown_(executor_,this),privileged_(this) { + initResources(); + catalogDigest_=JsonValidator::digest(QJsonArray{ + QJsonDocument::fromJson(asset(":/data/sources.json")).object(), + QJsonDocument::fromJson(asset(":/data/hardening/fstec-linux-2022.catalog.json")).object(), + QJsonDocument::fromJson(asset(":/data/checklists/all.ru.json")).object(), + QJsonDocument::fromJson(asset(":/tasks/manifest.json")).object()}); + connect(&shutdown_,&ShutdownCoordinator::readyForRestorationSummary,this,&AppController::checkShutdown,Qt::QueuedConnection); + connect(&executor_,&PlanExecutor::stepStarted,this,[this](const QString &id){guarded([&]{currentOperation_=id;repository_.journalRun(runId_,"RUNNING",{{"operation_id",id},{"revision",revision_},{"started_at",utcNow()}});repository_.event(runId_,currentTarget_,id,"INFO","app","Начато наблюдение");emit changed();});}); + connect(&executor_,&PlanExecutor::stepFinished,this,[this](const QString &id,int status,const ProcessResult &p){guarded([&]{ + results_[id]=p;const bool ok=status==int(rules::Result::Pass); + remoteUnresolved_|=p.remote&&(p.cancelled||p.timedOut||p.exitCode==255); + repository_.journalRun(runId_,"RUNNING",{{"last_operation_result",QJsonObject{{"operation_id",id},{"target_id",currentTarget_},{"verified",ok},{"exit_code",p.exitCode},{"timed_out",p.timedOut},{"cancelled",p.cancelled},{"failed_to_start",p.failedToStart},{"elapsed_ms",double(p.elapsedMs)}}}}); + repository_.event(runId_,p.remote?currentTarget_:"local",id,ok?"INFO":"WARNING","app",ok?"Структура наблюдения проверена":"Наблюдение не подтверждено; откройте диагностику",QString("exit=%1; timeout=%2; cancelled=%3; output_limit=%4; elapsed_ms=%5").arg(p.exitCode).arg(p.timedOut).arg(p.cancelled).arg(p.outputExceeded).arg(p.elapsedMs)); + if(ok&&id=="windows.discovery") {windows_=WindowsDiscovery::parse(p.out);windows_["target_id"]=currentTarget_;windows_["run_id"]=runId_;repository_.save("windows","last",windows_);} + if(ok&&id=="ad.inventory") adoptInventory(AdInventory::parse(p.out,false)); + });}); + connect(&executor_,&PlanExecutor::output,this,[this](const QString &stream,const QString &text){ + // Structured inventory is retained in its own validated store. Avoid + // duplicating directory contents and all installed packages in logs. + if(stream=="stdout"&&(currentOperation_=="ad.inventory"||currentOperation_=="windows.discovery"||currentOperation_=="local.packages"))return; + guarded([&]{repository_.event(runId_,currentTarget_,currentOperation_,"INFO",stream,"Нативная диагностика",text);}); + }); + connect(&executor_,&PlanExecutor::blocked,this,[this](const QString&id,const QString&why){guarded([&]{repository_.event(runId_,currentTarget_,id,"WARNING","app",why);});}); + connect(&executor_,&PlanExecutor::pausedForDecision,this,[this]{guarded([&]{repository_.journalRun(runId_,"PAUSED",{{"operation_id",currentOperation_},{"revision",revision_}});emit activityChanged(true);emit changed();});}); + connect(&executor_,&PlanExecutor::finished,this,[this](bool complete){guarded([&]{finished(complete);});checkShutdown();}); + connect(&privileged_,&PrivilegedClient::completed,this,[this](const QJsonObject &o){guarded([&]{repository_.save("audit","ssh.effective",o);repository_.journalRun(runId_,o.value("result").toString()=="OBSERVED"?"COMPLETED":"COMPLETED_WITH_GAPS",{{"kind","ssh.effective"},{"finished_at",utcNow()}});repository_.event(runId_,"local","ssh.effective","INFO","app","Привилегированное наблюдение завершено",QString::fromUtf8(QJsonDocument(o).toJson()));emit activityChanged(busy());emit changed();});checkShutdown();}); +} +void AppController::guarded(const std::function &action) noexcept { + if(storageFailed_)return; + try{action();}catch(const std::exception &e){storageFailure(QString::fromUtf8(e.what()));} + catch(...){storageFailure("Неизвестная ошибка сохранения или обработки результата");} +} +void AppController::storageFailure(const QString &message) noexcept { + if(storageFailed_)return; + storageFailed_=true;executor_.stop();privileged_.cancel(); + try{if(!runId_.isEmpty())repository_.journalRun(runId_,"RECOVERY_REQUIRED",{{"reason","storage_or_result_failure"},{"migration_success",false}});}catch(...){} + QTimer::singleShot(0,this,[this,message]{emit failure("Результат не удалось надёжно сохранить. Новые операции заблокированы; после закрытия проверьте диск и откройте проект для сверки.\n"+message);emit activityChanged(busy());}); +} + +void AppController::open(const QString &directory,bool demo) { + OperationRegistry::verifyAssets();repository_.open(directory);demo_=demo;project_=repository_.load("project","current"); + if(project_.isEmpty()) { + project_={{"id",newId()},{"schema_version",1},{"target_domain","corp.local"},{"source_domain","corp.local"},{"desired_outcomes",QJsonArray{"logins","passwords","profiles","data","permissions","applications","policy_outcomes","remove_ad"}},{"lab_mode",demo_},{"created_at",utcNow()},{"updated_at",utcNow()},{"version",1}}; + repository_.save("project","current",project_); + } else {JsonValidator::parse(QJsonDocument(project_).toJson(),"project");if(project_.value("lab_mode").toBool()!=demo_)throw std::runtime_error("Project mode is fixed: choose the matching live/demo mode or another project directory");} + if(project_.value("target_domain").toString()!="corp.local"||project_.value("source_domain").toString()!="corp.local")throw std::runtime_error("This project requires corp.local; changing owner requirements needs a new reviewed plan version"); + revision_=project_.value("version").toInt(1);inventory_=repository_.load("inventory","current"); + mappings_=repository_.load("mappings","current").value("items").toArray(); + migrationPlan_=repository_.load("migration","current");policyPlan_=repository_.load("policy-plan","current");windows_=repository_.load("windows","last");stagedBundle_=repository_.load("staged-bundle","last"); + checklist_=JsonValidator::parse(asset(":/data/checklists/all.ru.json"),"checklist").object().value("items").toArray(); + if(!inventory_.isEmpty())inventory_=AdInventory::parse(QJsonDocument(inventory_).toJson(),demo_); + if(demo_&&inventory_.isEmpty())adoptInventory(AdInventory::parse(asset(":/fixtures/demo.inventory.json"),true)); + if(migrationPlan_.isEmpty()||migrationPlan_.value("inventory_digest").toString()!=JsonValidator::digest(inventory_)||migrationPlan_.value("mapping_digest").toString()!=JsonValidator::digest(mappings_))rebuildPlan(); + repository_.event("","local","session.open","INFO","app",demo_?"Открыт DEMO: все исходные примеры синтетические":"Открыт проект: автоматического подключения к удалённым узлам нет"); + emit changed(); + if(!demo_)QTimer::singleShot(0,this,[this]{guarded([&]{if(!closing_&&!busy())refreshLocal(rules::ErrorPolicy::Independent);});}); +} +bool AppController::busy()const{return executor_.active()||privileged_.active()||importer_;} +QString AppController::contextDigest()const{return JsonValidator::digest(QJsonObject{{"project_version",revision_},{"inventory",JsonValidator::digest(inventory_)},{"mappings",JsonValidator::digest(mappings_)},{"policy",JsonValidator::digest(policyPlan_)},{"run",runId_},{"catalog",catalogDigest_}});} +QJsonObject AppController::initializationPlan()const{return InitializationPlanner::build(local_.facts,local_.role);} +QJsonArray AppController::observations()const {try{return repository_.observations(contextDigest());}catch(const std::exception&e){const_cast(this)->storageFailure(QString::fromUtf8(e.what()));return {};}} +QJsonArray AppController::events()const {try{return repository_.events();}catch(const std::exception&e){const_cast(this)->storageFailure(QString::fromUtf8(e.what()));return {};}} +QJsonArray AppController::accessChanges()const {try{return repository_.accessChanges();}catch(const std::exception&e){const_cast(this)->storageFailure(QString::fromUtf8(e.what()));return {};}} +QJsonArray AppController::interruptedRuns()const {try{return repository_.interruptedRuns();}catch(const std::exception&e){const_cast(this)->storageFailure(QString::fromUtf8(e.what()));return {};}} +QJsonArray AppController::hardeningCards()const{return QJsonDocument::fromJson(asset(":/data/hardening/fstec-linux-2022.catalog.json")).object().value("items").toArray();} +void AppController::beginRun(const QString &kind) { + if(busy()||closing_||storageFailed_)throw std::runtime_error("Операция уже выполняется или приложение закрывается"); + runId_=newId();runKind_=kind;results_.clear();repository_.journalRun(runId_,"PREFLIGHT",{{"plan_revision",revision_},{"context",contextDigest()},{"started_at",utcNow()}});persistContext(); +} +void AppController::refreshLocal(rules::ErrorPolicy policy) { + if(demo_)throw std::runtime_error("DEMO не запускает нативные процессы; откройте отдельный live-проект");beginRun("local.discovery");currentTarget_="local"; + std::vector steps;QMap specs;QMap verifiers; + for(const auto &id:OperationRegistry::ids()) { + steps.push_back({id.toStdString(),"local",{},false});specs[id]=OperationRegistry::resolve(id); + verifiers[id]=[id](const ProcessResult &p){ + if(id=="local.addresses"||id=="local.routes")return QJsonDocument::fromJson(p.out).isArray()?rules::Result::Pass:rules::Result::Error; + if(id=="local.yama")return QRegularExpression("^[0-3]\\s*$").match(QString::fromUtf8(p.out)).hasMatch()?rules::Result::Pass:rules::Result::Error; + if(id=="local.os")return p.out.contains("ID=")?rules::Result::Pass:rules::Result::Error; + if(id=="local.packages")return p.out.contains('\t')?rules::Result::Pass:rules::Result::Error; + if(id=="local.ssh_version")return p.err.startsWith("OpenSSH_")?rules::Result::Pass:rules::Result::Error; + return p.out.trimmed().isEmpty()?rules::Result::NotChecked:rules::Result::Pass; + }; + } + repository_.journalRun(runId_,"READY",{{"target_id",currentTarget_}});executor_.start(steps,specs,verifiers,policy);emit activityChanged(true); +} +void AppController::runWindows(const SshTarget &target,const QString &task,rules::ErrorPolicy policy) { + if(demo_)throw std::runtime_error("DEMO не подключается к узлам");const auto spec=NativeSshTransport::windowsTask(target,task);beginRun(task);currentTarget_=target.host; + PlanExecutor::Verifier verifier=[task](const ProcessResult &p){try{if(task=="windows.discovery")WindowsDiscovery::parse(p.out);else AdInventory::parse(p.out,false);return rules::Result::Pass;}catch(...){return rules::Result::Error;}}; + repository_.journalRun(runId_,"READY",{{"target_id",currentTarget_}}); + executor_.start({{task.toStdString(),target.host.toStdString(),{},false}},{{task,spec}},{{task,verifier}},policy);emit activityChanged(true); +} +void AppController::finished(bool complete) { + if(runKind_=="local.discovery"){local_=Astra17Discovery::interpret(results_);repository_.save("environment","current",{{"facts",local_.facts},{"findings",local_.findings}});} + repository_.journalRun(runId_,complete?"COMPLETED":"COMPLETED_WITH_GAPS",{{"kind",runKind_},{"finished_at",utcNow()},{"plan_revision",revision_},{"migration_success",false},{"remote_reconciliation_required",remoteUnresolved_},{"cleanup_state",accessChanges().isEmpty()?"NO_APPLICATION_ACCESS_CHANGES":"REVIEW_REQUIRED"}}); + const QStringList checks=runKind_=="local.discovery"?QStringList{"baseline","dns_time","hardening"}:QStringList{"source_baseline"}; + for(const auto &id:checks) { + repository_.observe({{"item_id",id},{"host_id",runKind_=="local.discovery"?"local":currentTarget_},{"method","AUTOMATIC"},{"checked_by","adapter/0.1.0"},{"result",complete?"PARTIAL":"ERROR"},{"note",complete?"Получены отдельные read-only наблюдения. Полный сценарий ручной проверки этим не подтверждён; подробности в журнале запуска.":"Сбор не завершён без ошибок. Полный сценарий не проверен; подробности в журнале запуска."},{"plan_revision",revision_},{"profile_revision",revision_},{"applicability","UNKNOWN"},{"evidence_ids",QJsonArray{runId_}}},contextDigest()); + } + emit activityChanged(false);emit changed();checkShutdown(); +} +void AppController::adoptInventory(const QJsonObject &inventory) { + const auto mappings=IdentityMapper::reconcile(inventory.value("objects").toArray(),mappings_); + auto project=project_;project["version"]=revision_+1;project["updated_at"]=utcNow(); + auto plan=MigrationPlanner::build(inventory,mappings,revision_+1);plan["policy_digest"]=JsonValidator::digest(policyPlan_); + try{repository_.saveBatch({ + QJsonObject{{"kind","project"},{"id","current"},{"body",project}}, + QJsonObject{{"kind","inventory"},{"id","current"},{"body",inventory}}, + QJsonObject{{"kind","mappings"},{"id","current"},{"body",QJsonObject{{"items",mappings}}}}, + QJsonObject{{"kind","migration"},{"id","current"},{"body",plan}}}); + }catch(const std::exception &e){storageFailure(QString::fromUtf8(e.what()));throw;} + inventory_=inventory;mappings_=mappings;project_=project;migrationPlan_=plan;++revision_;emit changed(); +} +void AppController::persistContext() { + project_["version"]=revision_;project_["updated_at"]=utcNow(); + QJsonArray documents{QJsonObject{{"kind","project"},{"id","current"},{"body",project_}},QJsonObject{{"kind","mappings"},{"id","current"},{"body",QJsonObject{{"items",mappings_}}}}}; + if(!inventory_.isEmpty())documents.append(QJsonObject{{"kind","inventory"},{"id","current"},{"body",inventory_}}); + try{repository_.saveBatch(documents);}catch(const std::exception &e){storageFailure(QString::fromUtf8(e.what()));throw;} +} +void AppController::importInventory(const QString &path) { + if(busy()||closing_||storageFailed_)throw std::runtime_error("Дождитесь завершения текущей операции"); + importer_=QThread::create([this,path]{QJsonObject imported;QString error;try{QFile f(path);if(!f.open(QIODevice::ReadOnly)||f.size()>16*1024*1024)throw std::runtime_error("Импорт недоступен или превышает 16 MiB");imported=AdInventory::parse(f.read(16*1024*1024+1),demo_);}catch(const std::exception&e){error=QString::fromUtf8(e.what());} + QMetaObject::invokeMethod(this,[this,imported,error]{guarded([&]{if(error.isEmpty()){adoptInventory(imported);repository_.event("","","inventory.import","INFO","app","Инвентаризация импортирована; прежние проверки устарели");}else emit failure(error);});},Qt::QueuedConnection); + }); + connect(importer_,&QThread::finished,this,[this]{auto *done=importer_;importer_=nullptr;done->deleteLater();emit activityChanged(busy());emit changed();checkShutdown();}); + importer_->start();emit activityChanged(true); +} +void AppController::importBundle(const QString &path) { + if(busy()||storageFailed_)throw std::runtime_error("Дождитесь завершения операции");QFile f(path);if(!f.open(QIODevice::ReadOnly)||f.size()>16*1024*1024)throw std::runtime_error("Набор данных недоступен или превышает 16 MiB"); + auto bundle=OfflineBundle::inspect(f.readAll());repository_.saveBatch({QJsonObject{{"kind","staged-bundle"},{"id",newId()},{"body",bundle}},QJsonObject{{"kind","staged-bundle"},{"id","last"},{"body",bundle}}});stagedBundle_=bundle;repository_.event("","","bundle.import","INFO","app","Offline-набор проверен по хэшам и сохранён для отдельного рассмотрения; подпись не проверена, автоматической активации нет");emit changed(); +} +void AppController::importProfile(const QString &path) { + if(busy()||storageFailed_)throw std::runtime_error("Дождитесь завершения операции");QFile f(path);if(!f.open(QIODevice::ReadOnly)||f.size()>1024*1024)throw std::runtime_error("Профиль недоступен или превышает 1 MiB"); + const auto profile=JsonValidator::parse(f.readAll(),"profile").object(); + const auto policy=PolicyPlanner::compare(profile,{});auto project=project_;project["version"]=revision_+1;project["updated_at"]=utcNow(); + auto plan=MigrationPlanner::build(inventory_,mappings_,revision_+1);plan["policy_digest"]=JsonValidator::digest(policy); + try{repository_.saveBatch({ + QJsonObject{{"kind","profile"},{"id","current"},{"body",profile}}, + QJsonObject{{"kind","policy-plan"},{"id","current"},{"body",policy}}, + QJsonObject{{"kind","project"},{"id","current"},{"body",project}}, + QJsonObject{{"kind","migration"},{"id","current"},{"body",plan}}}); + }catch(const std::exception &e){storageFailure(QString::fromUtf8(e.what()));throw;} + policyPlan_=policy;project_=project;migrationPlan_=plan;++revision_;emit changed(); +} +void AppController::rebuildPlan() { + auto plan=MigrationPlanner::build(inventory_,mappings_,revision_);plan["policy_digest"]=JsonValidator::digest(policyPlan_); + try{repository_.save("migration","current",plan);}catch(const std::exception&e){storageFailure(QString::fromUtf8(e.what()));throw;} + migrationPlan_=plan;emit changed(); +} + +void AppController::recordHuman(QJsonObject o) { + if(busy()||storageFailed_)throw std::runtime_error("Проверка относится к завершённому состоянию; дождитесь операции"); + bool found=false;for(const auto &v:checklist_)found|=v.toObject().value("id")==o.value("item_id");if(!found)throw std::runtime_error("Неизвестный пункт чеклиста"); + if(!o.contains("applicability"))o["applicability"]="UNKNOWN"; + o["method"]="HUMAN";o["plan_revision"]=revision_;o["profile_revision"]=revision_;o["evidence_ids"]=QJsonArray{}; + repository_.observe(o,contextDigest());emit changed(); +} +void AppController::recordAccessChange(QJsonObject o){if(busy()||storageFailed_)throw std::runtime_error("Дождитесь завершения операции");o["id"]=newId();o["run_id"]=runId_;o["verification_state"]="MANUAL_RECORDED_NOT_VERIFIED";o["owner_marker"]="manual:"+project_.value("id").toString();repository_.saveAccessChange(o);emit changed();} +void AppController::exportChecklist(const QString &path,bool html){repository_.exportChecklist(path,checklist_,contextDigest(),html);} +void AppController::auditPrivilegedSsh(){if(demo_||busy())throw std::runtime_error("Привилегированный аудит доступен в свободном live-сеансе");beginRun("ssh.effective");privileged_.auditSsh();emit activityChanged(true);} +void AppController::pause(){executor_.pause();}void AppController::resume(){executor_.resume();emit activityChanged(busy());}void AppController::stop(){executor_.stop();privileged_.cancel();} +void AppController::requestShutdown(){closing_=true;shutdownEmitted_=false;privileged_.cancel();shutdown_.request();} +void AppController::checkShutdown(){if(closing_&&!busy()&&!shutdownEmitted_){guarded([this]{persistContext();});shutdownEmitted_=true;emit shutdownReady();}} +} diff --git a/src/app/AppController.h b/src/app/AppController.h new file mode 100644 index 0000000..dce7f22 --- /dev/null +++ b/src/app/AppController.h @@ -0,0 +1,54 @@ +#pragma once +#include "storage/ProjectRepository.h" +#include "execution/PlanExecutor.h" +#include "execution/ShutdownCoordinator.h" +#include "security/PrivilegedClient.h" +#include "adapters/Astra17Discovery.h" +#include "transports/NativeSshTransport.h" +#include +#include +namespace ald { +class AppController:public QObject { + Q_OBJECT +public: + explicit AppController(QObject *parent=nullptr); + void open(const QString &directory,bool demo); + bool demo()const{return demo_;}bool busy()const; + bool storageHealthy()const{return !storageFailed_;} + bool remoteReconciliationRequired()const{return remoteUnresolved_;} + QJsonObject windowsFacts()const{return windows_;} + QJsonObject stagedBundle()const{return stagedBundle_;} + bool paused()const{return executor_.paused();} + QString projectDirectory()const{return repository_.directory();} + QString contextDigest()const; + QJsonObject project()const{return project_;}QJsonObject inventory()const{return inventory_;} + QJsonObject migrationPlan()const{return migrationPlan_;}QJsonObject initializationPlan()const; + QJsonObject localFacts()const{return local_.facts;}QJsonArray findings()const{return local_.findings;} + QJsonArray mappings()const{return mappings_;}QJsonArray checklistItems()const{return checklist_;} + QJsonArray observations()const;QJsonArray events()const;QJsonArray accessChanges()const; + QJsonArray interruptedRuns()const;QJsonArray hardeningCards()const; + QJsonObject policyPlan()const{return policyPlan_;} + void refreshLocal(rules::ErrorPolicy policy); + void runWindows(const SshTarget &target,const QString &task,rules::ErrorPolicy policy); + void importInventory(const QString &path); + void importBundle(const QString &path); + void importProfile(const QString &path); + void rebuildPlan(); + void recordHuman(QJsonObject observation); + void recordAccessChange(QJsonObject change); + void exportChecklist(const QString &path,bool html); + void auditPrivilegedSsh(); + void pause();void resume();void stop();void requestShutdown(); +signals: + void changed();void activityChanged(bool busy);void failure(const QString &message);void shutdownReady(); +private: + void beginRun(const QString &kind);void finished(bool complete);void checkShutdown(); + void adoptInventory(const QJsonObject &inventory);void persistContext(); + void guarded(const std::function &action) noexcept; + void storageFailure(const QString &message) noexcept; + ProjectRepository repository_;PlanExecutor executor_;ShutdownCoordinator shutdown_;PrivilegedClient privileged_; + QJsonObject project_,inventory_,migrationPlan_,policyPlan_,windows_,stagedBundle_;QJsonArray mappings_,checklist_; + LocalDiscovery local_;QMap results_;QThread *importer_=nullptr; + QString runId_,runKind_,currentOperation_,currentTarget_,catalogDigest_;bool demo_=false,closing_=false,storageFailed_=false,shutdownEmitted_=false,remoteUnresolved_=false;int revision_=1; +}; +} diff --git a/src/app/CapabilityRegistry.cpp b/src/app/CapabilityRegistry.cpp new file mode 100644 index 0000000..4c74e9d --- /dev/null +++ b/src/app/CapabilityRegistry.cpp @@ -0,0 +1,20 @@ +#include "CapabilityRegistry.h" +namespace ald { +QVector CapabilityRegistry::all() { + return { + {"local.discovery","local.discovery",{"Linux; native tools must be present"},CapabilityState::DocumentedNotTested,{"QT_PROCESS"},{"Проверка на Astra ещё не выполнена; состав пакетов не доказывает роль"},"Сохранить паспорт версий штатными средствами"}, + {"windows.transport","windows.discovery",{"Windows 10 1809+","Server 2019","Server 2025"},CapabilityState::DocumentedNotTested,{"MS_OPENSSH"},{"Нужны проверенный ключ хоста, SSH и PowerShell 5.1; стенд не проверен"},"Выполнить приложенный read-only PowerShell task локально"}, + {"initialization","ald31.initialize",{"ALD Pro 3.1.0 / ALSE 1.7.7 UU2"},CapabilityState::DocumentedNotTested,{"ALD31_PROMOTION","ALD31_OS"},{"Нет пакетов стенда и сверки установленного --help; corp.local конфликтует с исходным AD"},"Документированный интерактивный установщик после проверки всех предусловий"}, + {"directory_objects","ald31.migrate_objects",{"ALD Pro 3.1.0"},CapabilityState::DocumentedNotTested,{"ALD31_MIGRATION"},{"Портал: импорт объектов не подтверждает SID, пароли или профили"},"Управление доменом → Интеграция с доменами → Миграции MS AD"}, + {"same_name_transition","migration.same_name",{"ALD Pro 3.1.0 / corp.local"},CapabilityState::Unknown,{}, {"Не подтверждён порядок смены DNS authority и инициализации в существующей сети"},"Получить у вендора процедуру для этой топологии и проверить восстановление"}, + {"credentials","migration.credentials",{"ALD Pro 3.1.0"},CapabilityState::Unknown,{}, {"Сохранение всех существующих паролей не доказано"},"Проверить документированный механизм отдельно от синхронизации объектов"}, + {"windows_profiles","migration.profiles",{"Windows 10","Server 2019","Server 2025"},CapabilityState::Unknown,{}, {"DPAPI/EFS и состояние приложений требуют отдельного испытания"},"Пилот прежних профилей и зашифрованных пользовательских данных"}, + {"computer_trust","migration.computers",{"Windows 10","Server 2019","Server 2025"},CapabilityState::Unknown,{}, {"Доступ по SSH не доказывает доменный вход Windows"},"Проверить версионную утилиту интеграции и машинное доверие"}, + {"identity_permissions","migration.acl",{"ALD Pro 3.1.0"},CapabilityState::Unknown,{"MS_SID"},{"Совпадение логина не сохраняет SID и ACL"},"GUID/SID mapping, пилот разрешающих и запрещающих ACL"}, + {"applications","migration.applications",{"Environment-specific"},CapabilityState::Unknown,{}, {"Нужно обследовать LDAP/Kerberos/NTLM, SPN, PKI и владельцев сервисов"},"Для каждого сервиса получить поддержанный путь"}, + {"policy_outcomes","migration.policies",{"ALD Pro 3.1.0; Windows per build"},CapabilityState::Unknown,{}, {"Экспорт GPO не равен переносу действующих настроек"},"Сопоставить каждый параметр и проверить итоговый эффект"}, + {"ad_independence","migration.retire_ad",{"Single source DC"},CapabilityState::Unknown,{}, {"Независимость от AD не проверена; действие вывода AD недоступно"},"Обратимое испытание недоступности AD по утверждённому плану"} + }; +} +Capability CapabilityRegistry::get(const QString &id){for(const auto &c:all())if(c.id==id)return c;return {id,id,{},CapabilityState::Unknown,{}, {"Неизвестная возможность"},"Требуется документированный контракт"};} +} diff --git a/src/app/CapabilityRegistry.h b/src/app/CapabilityRegistry.h new file mode 100644 index 0000000..340ce5e --- /dev/null +++ b/src/app/CapabilityRegistry.h @@ -0,0 +1,3 @@ +#pragma once +#include "domain/Types.h" +namespace ald {class CapabilityRegistry {public:static QVector all();static Capability get(const QString &id);};} diff --git a/src/core/Rules.cpp b/src/core/Rules.cpp new file mode 100644 index 0000000..c00691b --- /dev/null +++ b/src/core/Rules.cpp @@ -0,0 +1,170 @@ +#include "Rules.h" +#include +#include +#include +#include +#include + +namespace ald::rules { +NodeRole classify(const RoleFacts &f) { + if (!f.astra || !f.packageQueryComplete) return NodeRole::PartialOrUnknown; + if ((f.adJoined && f.aldJoined) || (f.serverConfig && !f.aldPackages)) return NodeRole::PartialOrUnknown; + if (f.serverConfig) { + if (f.servicesObserved && !f.servicesHealthy) return NodeRole::DcDegraded; + if (f.ipaConfig && f.servicesHealthy && f.healthVerified) return NodeRole::DcHealthy; + return NodeRole::PartialOrUnknown; + } + if (f.adJoined) return NodeRole::AdClient; + if (f.aldJoined && f.ipaConfig) return NodeRole::AldClient; + if (f.ipaConfig || f.aldJoined) return NodeRole::PartialOrUnknown; + if (!f.configurationObserved) return NodeRole::PartialOrUnknown; + if (f.aldPackages) return NodeRole::PackagesOnly; + return NodeRole::CleanAstra; +} +bool canInitialize(NodeRole role) { return role == NodeRole::CleanAstra || role == NodeRole::PackagesOnly; } +bool transitionAllowed(RunState a, RunState b) { + using S = RunState; + if (a == b) return false; + switch(a) { + case S::Draft: return b == S::Preflight; + case S::Preflight: return b == S::Ready || b == S::Blocked || b == S::Failed; + case S::Ready: return b == S::Running || b == S::Blocked; + case S::Running: return b == S::PauseRequested || b == S::StopRequested || b == S::Verifying || b == S::RecoveryRequired; + case S::PauseRequested: return b == S::Paused || b == S::StopRequested || b == S::RecoveryRequired; + case S::Paused: return b == S::Preflight || b == S::StopRequested; + case S::StopRequested: return b == S::Verifying || b == S::RecoveryRequired; + case S::Verifying: return b == S::Cleanup || b == S::RecoveryRequired; + case S::Cleanup: return b == S::Completed || b == S::CompletedWithGaps || b == S::Failed || b == S::RecoveryRequired; + default: return false; // Terminal runs are never replayed; create a new plan revision. + } +} +Result reconcile(int code, bool normal, Result post, bool lost, bool mutating) { + if (lost && mutating) return Result::Unknown; + if (lost || !normal || code != 0) return Result::Error; + return post; // exit zero cannot create a Pass. +} +RestoreDecision restoration(bool owned, bool reachable, const std::string ¤t, + const std::string &applied, bool closes) { + if (!owned) return RestoreDecision::Preserve; + if (!reachable) return RestoreDecision::Pending; + if (current != applied) return RestoreDecision::Conflict; + return closes ? RestoreDecision::ManualVerification : RestoreDecision::Restore; +} +bool PlanContext::operator==(const PlanContext &o) const { + return revision == o.revision && inventoryDigest == o.inventoryDigest && + policyDigest == o.policyDigest && mappingDigest == o.mappingDigest; +} +std::vector blockers(const GateInput &g) { + std::vector out; + if (!(g.accepted == g.current)) out.push_back("CONTEXT_CHANGED"); + if (!g.inventoryComplete) out.push_back("INVENTORY_INCOMPLETE"); + auto lower=[](std::string s){std::transform(s.begin(),s.end(),s.begin(),[](unsigned char c){return char(std::tolower(c));});return s;}; + if (lower(g.sourceDomain) == lower(g.targetDomain)) { + auto it = std::find_if(g.requirements.begin(), g.requirements.end(), [](const Requirement &r){return r.id == "same_name_transition";}); + if (it == g.requirements.end() || it->support != CapabilityState::Verified || it->evidence != Result::Pass) + out.push_back("SAME_NAME_TRANSITION_UNVERIFIED"); + } + for (const auto &r : g.requirements) + if (r.mandatory && (r.support != CapabilityState::Verified || r.evidence != Result::Pass)) + out.push_back("REQUIREMENT:" + r.id); + // Required outcomes cannot disappear from a crafted plan. + for (const auto *id : {"credentials", "windows_profiles", "computer_trust", "identity_permissions", "applications", "policy_outcomes", "ad_independence"}) { + if (std::none_of(g.requirements.begin(), g.requirements.end(), [id](const Requirement &r){return r.id == id && r.mandatory;})) + out.push_back(std::string("MISSING_REQUIREMENT:") + id); + } + if (g.mutations && !g.recoveryRehearsed) out.push_back("RECOVERY_NOT_REHEARSED"); + if (g.mutations && !g.windowAuthorized) out.push_back("CHANGE_WINDOW_NOT_AUTHORIZED"); + return out; +} +std::vector topological(const std::vector &steps) { + std::map byId; + for (const auto &s : steps) + if (s.id.empty() || !byId.emplace(s.id, &s).second) throw std::invalid_argument("duplicate or empty step"); + std::map marks; + std::vector order; + std::function visit = [&](const std::string &id) { + if (!byId.count(id)) throw std::invalid_argument("missing dependency"); + if (marks[id] == 1) throw std::invalid_argument("cycle"); + if (marks[id] == 2) return; + marks[id] = 1; + for (const auto &dep : byId[id]->dependencies) visit(dep); + marks[id] = 2; order.push_back(id); + }; + if (steps.size() > 1024) throw std::invalid_argument("plan exceeds 1024 steps"); + for (const auto &s : steps) visit(s.id); + return order; +} +bool dependenciesPassed(const Step &step, const std::map &results) { + return std::all_of(step.dependencies.begin(), step.dependencies.end(), [&](const std::string &id){ + const auto it=results.find(id); return it != results.end() && it->second == Result::Pass; + }); +} +BatchDecision afterResult(Result r, ErrorPolicy p) { + if (r == Result::Pass) return BatchDecision::Continue; + return p == ErrorPolicy::Independent ? BatchDecision::Continue : p == ErrorPolicy::Pause ? BatchDecision::Pause : BatchDecision::Stop; +} +std::string identityKey(const std::string &system, const std::string &guid, const std::string &sid) { + if (system.empty() || guid.empty()) throw std::invalid_argument("stable source identity missing"); + auto part=[](const std::string &s){return std::to_string(s.size()) + ":" + s;}; + std::string normalized = guid; + std::transform(normalized.begin(), normalized.end(), normalized.begin(), [](unsigned char c){return char(std::tolower(c));}); + return part(system)+part(normalized)+part(sid); +} +bool safeHost(const std::string &s) { + if (s.empty() || s.size()>253 || s.front()=='-' || s.back()=='.') return false; + std::size_t count=0; + char last=0; + for (unsigned char c:s) { + if (c=='.') {if (!count || last=='-') return false; count=0;} + else {if (!(std::isalnum(c) && c<128) && c!='-') return false; if (!count && c=='-') return false; if (++count>63) return false;} + last=char(c); + } + return count && last!='-'; +} +bool safeUser(const std::string &s) { + if (s.empty() || s.size()>128 || s.front()=='-') return false; + return std::all_of(s.begin(), s.end(), [](unsigned char c){return c<128 && (std::isalnum(c)|| c=='.'||c=='_'||c=='-'||c=='@'||c=='\\');}); +} +bool safeRelativePath(const std::string &s) { + if(s.empty() || s.size()>512 || s.front()=='/' || s.find('\\')!=std::string::npos || s.find(':')!=std::string::npos || s.find('\0')!=std::string::npos) return false; + std::size_t start=0; + do { auto end=s.find('/',start); auto p=s.substr(start,end-start); if(p.empty()||p==".."||p==".")return false; if(end==std::string::npos)break; start=end+1;}while(true); + return true; +} +SecretStream::SecretStream(std::vector s):secrets_(std::move(s)) { + for(const auto &v:secrets_) if(v.empty() || v.size()>4096) throw std::invalid_argument("invalid secret length"); + if(secrets_.size()>64)throw std::invalid_argument("too many secrets"); +} +std::string SecretStream::feed(const std::string &chunk, bool final) { + if(suppressed_) return {}; + pending_+=chunk; + std::string out; + std::size_t i=0; + while(i=s.size() && pending_.compare(i,s.size(),s)==0)span=std::max(span,s.size()); + if(!final && remaining=s.size() && pending_.compare(j,s.size(),s)==0)span=std::max(span,j-i+s.size()); + else if(!final && remaining8192) {out+="[REDACTED: oversized sensitive output]"; pending_.clear(); suppressed_=true;} + return out; +} +} diff --git a/src/core/Rules.h b/src/core/Rules.h new file mode 100644 index 0000000..2b5c409 --- /dev/null +++ b/src/core/Rules.h @@ -0,0 +1,62 @@ +#pragma once +#include +#include +#include +#include + +namespace ald::rules { +enum class CapabilityState { Verified, DocumentedNotTested, Unknown, Unsupported }; +enum class NodeRole { CleanAstra, PackagesOnly, AdClient, AldClient, DcHealthy, DcDegraded, PartialOrUnknown }; +enum class RunState { Draft, Preflight, Blocked, Ready, Running, PauseRequested, Paused, + StopRequested, Verifying, Cleanup, Completed, CompletedWithGaps, Failed, RecoveryRequired }; +enum class Result { Pass, Fail, Partial, NotChecked, Error, Stale, Unknown }; +enum class ErrorPolicy { Stop, Independent, Pause }; +enum class RestoreDecision { Preserve, Restore, Conflict, Pending, ManualVerification }; +struct RoleFacts { + bool astra = false, packageQueryComplete = false, aldPackages = false; + bool ipaConfig = false, serverConfig = false, adJoined = false, aldJoined = false; + bool servicesObserved = false, servicesHealthy = false, healthVerified = false; + bool configurationObserved = false; +}; +NodeRole classify(const RoleFacts &facts); +bool canInitialize(NodeRole role); +bool transitionAllowed(RunState from, RunState to); +Result reconcile(int exitCode, bool normalExit, Result postcondition, bool contactLost, bool mutating); +RestoreDecision restoration(bool owned, bool reachable, const std::string ¤t, + const std::string &applied, bool closesLastChannel); +struct Requirement { std::string id; CapabilityState support; Result evidence; bool mandatory = true; }; +struct PlanContext { + std::string inventoryDigest, policyDigest, mappingDigest; + unsigned revision = 1; + bool operator==(const PlanContext &other) const; +}; +struct GateInput { + std::string sourceDomain, targetDomain; + bool inventoryComplete = false, recoveryRehearsed = false, windowAuthorized = false; + bool mutations = true, production = true; + PlanContext accepted, current; + std::vector requirements; +}; +std::vector blockers(const GateInput &input); +struct Step { std::string id, host; std::vector dependencies; bool mutating = false; }; +std::vector topological(const std::vector &steps); +bool dependenciesPassed(const Step &step, const std::map &results); +enum class BatchDecision { Continue, Stop, Pause }; +BatchDecision afterResult(Result result, ErrorPolicy policy); +std::string identityKey(const std::string &system, const std::string &guid, const std::string &sid); +bool safeHost(const std::string &value); +bool safeUser(const std::string &value); +bool safeRelativePath(const std::string &value); + +// Bounded streaming redaction. Pending prefixes are never emitted until they cannot +// be part of a secret. Match spans are consumed atomically (including overlaps). +class SecretStream { +public: + explicit SecretStream(std::vector secrets = {}); + std::string feed(const std::string &chunk, bool final = false); +private: + std::vector secrets_; + std::string pending_; + bool suppressed_ = false; +}; +} diff --git a/src/domain/AccessChange.h b/src/domain/AccessChange.h new file mode 100644 index 0000000..75dd0a7 --- /dev/null +++ b/src/domain/AccessChange.h @@ -0,0 +1,2 @@ +#pragma once +#include "Types.h" diff --git a/src/domain/Capability.h b/src/domain/Capability.h new file mode 100644 index 0000000..75dd0a7 --- /dev/null +++ b/src/domain/Capability.h @@ -0,0 +1,2 @@ +#pragma once +#include "Types.h" diff --git a/src/domain/Checklist.h b/src/domain/Checklist.h new file mode 100644 index 0000000..75dd0a7 --- /dev/null +++ b/src/domain/Checklist.h @@ -0,0 +1,2 @@ +#pragma once +#include "Types.h" diff --git a/src/domain/Host.h b/src/domain/Host.h new file mode 100644 index 0000000..75dd0a7 --- /dev/null +++ b/src/domain/Host.h @@ -0,0 +1,2 @@ +#pragma once +#include "Types.h" diff --git a/src/domain/IdentityMapping.h b/src/domain/IdentityMapping.h new file mode 100644 index 0000000..75dd0a7 --- /dev/null +++ b/src/domain/IdentityMapping.h @@ -0,0 +1,2 @@ +#pragma once +#include "Types.h" diff --git a/src/domain/InventoryObject.h b/src/domain/InventoryObject.h new file mode 100644 index 0000000..75dd0a7 --- /dev/null +++ b/src/domain/InventoryObject.h @@ -0,0 +1,2 @@ +#pragma once +#include "Types.h" diff --git a/src/domain/LogEvent.h b/src/domain/LogEvent.h new file mode 100644 index 0000000..75dd0a7 --- /dev/null +++ b/src/domain/LogEvent.h @@ -0,0 +1,2 @@ +#pragma once +#include "Types.h" diff --git a/src/domain/MigrationItem.h b/src/domain/MigrationItem.h new file mode 100644 index 0000000..75dd0a7 --- /dev/null +++ b/src/domain/MigrationItem.h @@ -0,0 +1,2 @@ +#pragma once +#include "Types.h" diff --git a/src/domain/Operation.h b/src/domain/Operation.h new file mode 100644 index 0000000..75dd0a7 --- /dev/null +++ b/src/domain/Operation.h @@ -0,0 +1,2 @@ +#pragma once +#include "Types.h" diff --git a/src/domain/Plan.h b/src/domain/Plan.h new file mode 100644 index 0000000..75dd0a7 --- /dev/null +++ b/src/domain/Plan.h @@ -0,0 +1,2 @@ +#pragma once +#include "Types.h" diff --git a/src/domain/PolicyProfile.h b/src/domain/PolicyProfile.h new file mode 100644 index 0000000..75dd0a7 --- /dev/null +++ b/src/domain/PolicyProfile.h @@ -0,0 +1,2 @@ +#pragma once +#include "Types.h" diff --git a/src/domain/Project.h b/src/domain/Project.h new file mode 100644 index 0000000..75dd0a7 --- /dev/null +++ b/src/domain/Project.h @@ -0,0 +1,2 @@ +#pragma once +#include "Types.h" diff --git a/src/domain/Run.h b/src/domain/Run.h new file mode 100644 index 0000000..75dd0a7 --- /dev/null +++ b/src/domain/Run.h @@ -0,0 +1,2 @@ +#pragma once +#include "Types.h" diff --git a/src/domain/Types.h b/src/domain/Types.h new file mode 100644 index 0000000..0c9abf8 --- /dev/null +++ b/src/domain/Types.h @@ -0,0 +1,75 @@ +#pragma once +#include "core/Rules.h" +#include +#include +#include +#include +#include +#include + +namespace ald { +using CapabilityState = rules::CapabilityState; +using RunState = rules::RunState; +using NodeRole = rules::NodeRole; +using ObservationResult = rules::Result; +enum class Applicability { Applicable, NotApplicableWithReason, Unknown }; +enum class Disposition { AutomatedNative, GuidedNative, ManualReconfiguration, Unsupported, Unknown }; +inline QString newId() { return QUuid::createUuid().toString(QUuid::WithoutBraces); } +inline QString utcNow() { return QDateTime::currentDateTimeUtc().toString(Qt::ISODateWithMs); } +struct Project { + QString id = newId(); int schema_version = 1; QString target_domain = "corp.local", source_domain = "corp.local"; + QStringList desired_outcomes; bool lab_mode = false; QString created_at = utcNow(), updated_at = utcNow(); int version = 1; +}; +struct Host { + QString id, fqdn; QStringList addresses; QString os_family, os_release, os_build, kernel, architecture; + QStringList detected_roles; QString observed_at; QStringList evidence_ids; +}; +struct Capability { + QString id, operation; QStringList supported_versions; CapabilityState state = CapabilityState::Unknown; + QStringList evidence_ids, limitations; QString manual_alternative; +}; +struct InventoryObject { + QString source_system_id, object_guid, sid, dn, object_type; QJsonObject attributes; QStringList memberships; QString observed_at; +}; +struct IdentityMapping { + QString source_guid, source_sid, source_dn, target_id, target_sid; QJsonObject target_uid_gid; + QString mapping_method, verification_state; +}; +struct MigrationItem { + QString id, category, source_ref, target_ref; Disposition disposition = Disposition::Unknown; + QStringList dependencies, acceptance_ids, blockers, evidence_ids; +}; +struct Operation { + QString id, adapter_id, adapter_version, target_id; QJsonObject typed_parameters; + QStringList preconditions, effects; QString cancellation_class, recovery_class; QStringList postconditions; +}; +struct Plan { + QString id = newId(); int revision = 1; QString inventory_digest, policy_digest, mapping_digest; + QStringList affected_hosts; QJsonArray graph; rules::ErrorPolicy error_policy = rules::ErrorPolicy::Stop; + QJsonObject downtime; QString authorization_state = "NOT_AUTHORIZED"; +}; +struct Run { + QString id = newId(), plan_id; int plan_revision = 1; RunState state = RunState::Draft; + QString started_at, finished_at; QJsonObject per_host_results; QString cleanup_state = "NOT_CHECKED"; +}; +struct AccessChange { + QString id = newId(), run_id, target_id, resource_type, resource_id; + QJsonObject previous_state, applied_state; QString owner_marker; QStringList restoration_steps; + QString verification_state = "NOT_CHECKED"; +}; +struct PolicyProfile { + QString id = newId(); int revision = 1; QStringList os_constraints, role_constraints; + QJsonArray settings; QString management_owner; QJsonArray exceptions; QStringList source_refs; +}; +struct ChecklistItem { + QString id, phase, title_ru, purpose_ru; QStringList host_scope, prerequisites, steps_ru; + QString expected_result_ru, failure_guidance_ru; QStringList evidence_ids; +}; +struct ChecklistObservation { + QString item_id, host_id, result = "NOT_CHECKED", checked_by, checked_at = utcNow(), method = "HUMAN", note; + int plan_revision = 1, profile_revision = 1; Applicability applicability = Applicability::Unknown; QStringList evidence_ids; +}; +struct LogEvent { + qint64 sequence = 0; QString timestamp_utc = utcNow(), run_id, host_id, operation_id, severity, stream, message_ru, redacted_detail, source_ref; +}; +} diff --git a/src/execution/OperationRegistry.cpp b/src/execution/OperationRegistry.cpp new file mode 100644 index 0000000..64f60d9 --- /dev/null +++ b/src/execution/OperationRegistry.cpp @@ -0,0 +1,45 @@ +#include "OperationRegistry.h" +#include +#include +#include +#include +#include +namespace ald { +static QByteArray readAsset(const QString &path){QFile f(path);if(!f.open(QIODevice::ReadOnly))throw std::runtime_error("Missing immutable asset");return f.readAll();} +QStringList OperationRegistry::ids(){return {"local.os","local.kernel","local.packages","local.services","local.addresses","local.routes","local.time","local.hostname","local.resolvers","local.yama","local.machine","local.ssh_version"};} +ProcessSpec OperationRegistry::resolve(const QString &id,const QJsonObject ¶ms) { + if(!params.isEmpty())throw std::runtime_error("Unknown parameters: operation takes no input"); + ProcessSpec s;s.operationId=id; + if(id=="local.os"){s.program="/usr/bin/cat";s.arguments=QStringList{"/etc/os-release"};} + else if(id=="local.kernel"){s.program="/usr/bin/uname";s.arguments=QStringList{"-r","-m"};} + else if(id=="local.packages"){s.program="/usr/bin/dpkg-query";s.arguments=QStringList{"-W","-f=${binary:Package}\t${Version}\t${db:Status-Status}\n"};} + else if(id=="local.services"){s.program="/usr/bin/systemctl";s.arguments=QStringList{"show","--no-pager","--property=Id,LoadState,ActiveState,SubState","ipa.service","krb5-kdc.service","bind9.service","sssd.service","aldpro-mp-services.service"};} + else if(id=="local.addresses"){s.program="/usr/sbin/ip";s.arguments=QStringList{"-j","address","show"};} + else if(id=="local.routes"){s.program="/usr/sbin/ip";s.arguments=QStringList{"-j","route","show"};} + else if(id=="local.time"){s.program="/usr/bin/timedatectl";s.arguments=QStringList{"show","--property=NTPSynchronized,Timezone,TimeUSec"};} + else if(id=="local.hostname"){s.program="/usr/bin/hostname";s.arguments=QStringList{"-f"};} + else if(id=="local.resolvers"){s.program="/usr/bin/cat";s.arguments=QStringList{"/etc/resolv.conf"};} + else if(id=="local.yama"){s.program="/usr/bin/cat";s.arguments=QStringList{"/proc/sys/kernel/yama/ptrace_scope"};} + else if(id=="local.machine"){s.program="/usr/bin/cat";s.arguments=QStringList{"/etc/machine-id"};s.suppressOutput=true;} + else if(id=="local.ssh_version"){s.program="/usr/bin/ssh";s.arguments=QStringList{"-V"};} + else throw std::runtime_error("Unknown or unavailable executable operation ID"); + return s; +} +void OperationRegistry::verifyAssets() { + const auto assets=QJsonDocument::fromJson(readAsset(":/asset-manifest.json")).object(); + if(assets.value("schema_version").toInt()!=1)throw std::runtime_error("Unsupported asset manifest"); + for(const auto &v:assets.value("assets").toArray()){auto o=v.toObject();if(QCryptographicHash::hash(readAsset(":/"+o.value("path").toString()),QCryptographicHash::Sha256).toHex()!=o.value("sha256").toString().toLatin1())throw std::runtime_error("Installed asset integrity failed");} + const auto manifest=QJsonDocument::fromJson(readAsset(":/tasks/manifest.json")).object(); + if(manifest.value("schema_version").toInt()!=1)throw std::runtime_error("Unsupported task manifest"); + for(const auto &v:manifest.value("tasks").toArray()) { + const auto o=v.toObject();const auto bytes=readAsset(":/tasks/"+o.value("path").toString()); + if(QCryptographicHash::hash(bytes,QCryptographicHash::Sha256).toHex()!=o.value("sha256").toString().toLatin1())throw std::runtime_error("Task integrity verification failed"); + } +} +QByteArray OperationRegistry::task(const QString &id) { + verifyAssets(); + if(id=="windows.discovery")return readAsset(":/tasks/windows/discovery.ps1"); + if(id=="ad.inventory")return readAsset(":/tasks/windows/ad-inventory.ps1"); + throw std::runtime_error("Unknown fixed task"); +} +} diff --git a/src/execution/OperationRegistry.h b/src/execution/OperationRegistry.h new file mode 100644 index 0000000..24e3424 --- /dev/null +++ b/src/execution/OperationRegistry.h @@ -0,0 +1,19 @@ +#pragma once +#include +#include +#include +namespace ald { +struct ProcessSpec { + QString operationId,program;QStringList arguments; + int timeoutMs = 15000;qsizetype outputLimit = 4*1024*1024; + bool readOnly = true, remote = false, suppressOutput = false; + QByteArray input; +}; +class OperationRegistry { +public: + static ProcessSpec resolve(const QString &operation,const QJsonObject ¶meters = {}); + static QStringList ids(); + static QByteArray task(const QString &id); + static void verifyAssets(); +}; +} diff --git a/src/execution/PlanExecutor.cpp b/src/execution/PlanExecutor.cpp new file mode 100644 index 0000000..6a3504d --- /dev/null +++ b/src/execution/PlanExecutor.cpp @@ -0,0 +1,38 @@ +#include "PlanExecutor.h" +#include +#include +#include +namespace ald { +PlanExecutor::PlanExecutor(QObject *parent):QObject(parent),runner_(this){connect(&runner_,&ProcessRunner::finished,this,&PlanExecutor::onResult);connect(&runner_,&ProcessRunner::output,this,&PlanExecutor::output);} +void PlanExecutor::start(const std::vector &steps,const QMap &specs,const QMap &verifiers,rules::ErrorPolicy policy) { + if(running_)throw std::runtime_error("Run already active"); + auto order=rules::topological(steps); + for(const auto &s:steps) {auto id=QString::fromStdString(s.id);if(s.mutating||!specs.contains(id)||!specs[id].readOnly||!verifiers.contains(id))throw std::runtime_error("Unvalidated step or missing postcondition verifier");} + steps_=steps;order_=order;specs_=specs;verifiers_=verifiers;policy_=policy;results_.clear();index_=0;running_=true;stopping_=paused_=pauseRequested_=hasGaps_=false; + QTimer::singleShot(0,this,&PlanExecutor::next); +} +void PlanExecutor::next() { + if(!running_)return; + if(stopping_||index_==order_.size()){running_=false;paused_=false;emit finished(!hasGaps_&&!stopping_);return;} + if(pauseRequested_){paused_=true;emit pausedForDecision();return;} + current_=QString::fromStdString(order_[index_++]);const auto id=current_.toStdString(); + auto step=std::find_if(steps_.begin(),steps_.end(),[&](const rules::Step&s){return s.id==id;}); + if(!rules::dependenciesPassed(*step,results_)){results_[id]=rules::Result::NotChecked;hasGaps_=true;emit blocked(current_,"Предыдущая зависимая операция не подтверждена");QTimer::singleShot(0,this,&PlanExecutor::next);return;} + emit stepStarted(current_); + // A journal/authorization observer may refuse scheduling at this boundary. + if(stopping_){QTimer::singleShot(0,this,&PlanExecutor::next);return;} + try{runner_.start(specs_.value(current_));}catch(const std::exception&){ProcessResult r;r.operationId=specs_.value(current_).operationId;r.failedToStart=true;onResult(r);} +} +void PlanExecutor::onResult(const ProcessResult &p) { + rules::Result post=rules::Result::Error; + if(!p.cancelled&&!p.outputExceeded&&!p.timedOut&&!p.failedToStart){try{post=verifiers_.value(current_)(p);}catch(...){post=rules::Result::Error;}} + const auto result=rules::reconcile(p.exitCode,p.normalExit,post,p.remote&&(p.exitCode==255||p.timedOut),false); + results_[current_.toStdString()]=result;hasGaps_|=result!=rules::Result::Pass; + emit stepFinished(current_,int(result),p); + auto action=rules::afterResult(result,policy_);if(action==rules::BatchDecision::Stop)stopping_=true;else if(action==rules::BatchDecision::Pause)pauseRequested_=true; + QTimer::singleShot(0,this,&PlanExecutor::next); +} +void PlanExecutor::stop(){stopping_=true;pauseRequested_=paused_=false;if(runner_.active())runner_.cancel();else QTimer::singleShot(0,this,&PlanExecutor::next);} +void PlanExecutor::pause(){if(running_)pauseRequested_=true;} +void PlanExecutor::resume(){if(!paused_)return;paused_=pauseRequested_=false;QTimer::singleShot(0,this,&PlanExecutor::next);} +} diff --git a/src/execution/PlanExecutor.h b/src/execution/PlanExecutor.h new file mode 100644 index 0000000..4def5d5 --- /dev/null +++ b/src/execution/PlanExecutor.h @@ -0,0 +1,28 @@ +#pragma once +#include "ProcessRunner.h" +#include "core/Rules.h" +#include +#include +namespace ald { +class PlanExecutor : public QObject { + Q_OBJECT +public: + using Verifier=std::function; + explicit PlanExecutor(QObject *parent=nullptr); + void start(const std::vector &steps,const QMap &specs, + const QMap &verifiers,rules::ErrorPolicy policy); + void stop();void pause();void resume();bool active()const{return running_;}bool paused()const{return paused_;} +signals: + void stepStarted(const QString &id); + void stepFinished(const QString &id,int result,const ald::ProcessResult &process); + void blocked(const QString &id,const QString &reason); + void output(const QString &stream,const QString &redacted); + void pausedForDecision();void finished(bool complete); +private: + void next();void onResult(const ProcessResult &result); + ProcessRunner runner_;std::vector steps_;std::vector order_; + QMap specs_;QMap verifiers_; + std::map results_;rules::ErrorPolicy policy_=rules::ErrorPolicy::Stop; + std::size_t index_=0;QString current_;bool running_=false,stopping_=false,paused_=false,pauseRequested_=false,hasGaps_=false; +}; +} diff --git a/src/execution/ProcessRunner.cpp b/src/execution/ProcessRunner.cpp new file mode 100644 index 0000000..c3cfcc2 --- /dev/null +++ b/src/execution/ProcessRunner.cpp @@ -0,0 +1,45 @@ +#include "ProcessRunner.h" +#include +#include +namespace ald { +ProcessRunner::ProcessRunner(QObject *parent):QObject(parent) { + process_.setProcessChannelMode(QProcess::SeparateChannels);timeout_.setSingleShot(true);killTimer_.setSingleShot(true); + connect(&process_,&QProcess::readyReadStandardOutput,this,[this]{drain(false);}); + connect(&process_,&QProcess::readyReadStandardError,this,[this]{drain(true);}); + connect(&process_,QOverload::of(&QProcess::finished),this,&ProcessRunner::complete); + connect(&process_,&QProcess::errorOccurred,this,[this](QProcess::ProcessError e){if(e==QProcess::FailedToStart){result_.failedToStart=true;complete(-1,QProcess::CrashExit);}}); + connect(&timeout_,&QTimer::timeout,this,[this]{result_.timedOut=true;stopReadOnly();}); + connect(&killTimer_,&QTimer::timeout,this,[this]{if(active_&&spec_.readOnly)process_.kill();}); + connect(&process_,&QProcess::started,this,[this]{if(!spec_.input.isEmpty())process_.write(spec_.input);process_.closeWriteChannel();}); +} +void ProcessRunner::start(const ProcessSpec &spec,const QStringList &secrets) { + if(active_)throw std::runtime_error("Operation is already active"); + // This release has no validated automated mutation adapter. Deny at the final + // process boundary, even if a crafted plan bypasses UI or capability checks. + if(!spec.readOnly)throw std::runtime_error("Mutating adapter is not laboratory validated"); + if(!spec.program.startsWith('/')||spec.timeoutMs<100||spec.timeoutMs>300000||spec.outputLimit<1024||spec.outputLimit>16*1024*1024)throw std::runtime_error("Invalid process contract"); + spec_=spec;result_=ProcessResult{};result_.operationId=spec.operationId;result_.remote=spec.remote; + stdoutRedactor_=std::make_unique(secrets);stderrRedactor_=std::make_unique(secrets); + QProcessEnvironment env;env.insert("PATH","/usr/sbin:/usr/bin:/sbin:/bin");env.insert("LANG","C.UTF-8");env.insert("LC_ALL","C.UTF-8"); + // Explicit native credential mechanism: already unlocked session ssh-agent. + // Its socket is never logged, exported or forwarded. + if(spec.remote&&!qEnvironmentVariableIsEmpty("SSH_AUTH_SOCK"))env.insert("SSH_AUTH_SOCK",qEnvironmentVariable("SSH_AUTH_SOCK")); + process_.setProcessEnvironment(env);process_.setProgram(spec.program);process_.setArguments(spec.arguments); + process_.setWorkingDirectory("/");active_=true;done_=false;elapsed_.start();timeout_.start(spec.timeoutMs);process_.start(); +} +void ProcessRunner::drain(bool error) { + const auto bytes=error?process_.readAllStandardError():process_.readAllStandardOutput(); + auto &buffer=error?result_.err:result_.out; + if(result_.out.size()+result_.err.size()+bytes.size()>spec_.outputLimit){result_.outputExceeded=true;stopReadOnly();return;} + buffer+=bytes; + const auto text=(error?stderrRedactor_:stdoutRedactor_)->feed(bytes); + if(!spec_.suppressOutput&&!text.isEmpty())emit output(error?"stderr":"stdout",text); +} +void ProcessRunner::complete(int code,QProcess::ExitStatus status) { + if(done_)return;drain(false);drain(true);done_=true;timeout_.stop();killTimer_.stop();active_=false; + for(bool error:{false,true}){const auto text=(error?stderrRedactor_:stdoutRedactor_)->feed({},true);if(!spec_.suppressOutput&&!text.isEmpty())emit output(error?"stderr":"stdout",text);} + result_.exitCode=code;result_.normalExit=status==QProcess::NormalExit;result_.elapsedMs=elapsed_.elapsed();emit finished(result_); +} +void ProcessRunner::stopReadOnly(){if(active_&&spec_.readOnly){process_.terminate();killTimer_.start(2000);}} +void ProcessRunner::cancel(){if(!active_)return;result_.cancelled=true;stopReadOnly();} +} diff --git a/src/execution/ProcessRunner.h b/src/execution/ProcessRunner.h new file mode 100644 index 0000000..22851d1 --- /dev/null +++ b/src/execution/ProcessRunner.h @@ -0,0 +1,29 @@ +#pragma once +#include "OperationRegistry.h" +#include "security/SecretRedactor.h" +#include +#include +#include +#include +namespace ald { +struct ProcessResult { + QString operationId;int exitCode=-1;bool normalExit=false,timedOut=false,cancelled=false,outputExceeded=false,failedToStart=false,remote=false; + QByteArray out,err;qint64 elapsedMs=0; +}; +class ProcessRunner : public QObject { + Q_OBJECT +public: + explicit ProcessRunner(QObject *parent=nullptr); + void start(const ProcessSpec &spec,const QStringList &secrets = {}); + bool active()const{return active_;} + void cancel(); +signals: + void output(const QString &stream,const QString &redacted); + void finished(const ald::ProcessResult &result); +private: + void drain(bool err);void complete(int code,QProcess::ExitStatus status);void stopReadOnly(); + QProcess process_;QTimer timeout_,killTimer_;QElapsedTimer elapsed_;ProcessSpec spec_;ProcessResult result_; + std::unique_ptr stdoutRedactor_,stderrRedactor_;bool active_=false,done_=true; +}; +} +Q_DECLARE_METATYPE(ald::ProcessResult) diff --git a/src/execution/RunJournal.cpp b/src/execution/RunJournal.cpp new file mode 100644 index 0000000..f2f2917 --- /dev/null +++ b/src/execution/RunJournal.cpp @@ -0,0 +1,3 @@ +#include "RunJournal.h" +#include "domain/Types.h" +namespace ald {void RunJournal::write(const QString &id,const QString &state,const QString &operation,const QJsonObject &details){auto o=details;o["timestamp_utc"]=utcNow();o["operation_id"]=operation;repo_.journalRun(id,state,o);}} diff --git a/src/execution/RunJournal.h b/src/execution/RunJournal.h new file mode 100644 index 0000000..98ada8d --- /dev/null +++ b/src/execution/RunJournal.h @@ -0,0 +1,10 @@ +#pragma once +#include "storage/ProjectRepository.h" +namespace ald { +class RunJournal { +public: + explicit RunJournal(ProjectRepository &repo):repo_(repo){} + void write(const QString &id,const QString &state,const QString &operation,const QJsonObject &details={}); +private:ProjectRepository &repo_; +}; +} diff --git a/src/execution/ShutdownCoordinator.cpp b/src/execution/ShutdownCoordinator.cpp new file mode 100644 index 0000000..9757e8d --- /dev/null +++ b/src/execution/ShutdownCoordinator.cpp @@ -0,0 +1,5 @@ +#include "ShutdownCoordinator.h" +namespace ald { +ShutdownCoordinator::ShutdownCoordinator(PlanExecutor &e,QObject *p):QObject(p),executor_(e){connect(&e,&PlanExecutor::finished,this,[this]{if(requested_){requested_=false;emit readyForRestorationSummary();}});} +void ShutdownCoordinator::request(){requested_=true;if(executor_.active())executor_.stop();else{requested_=false;emit readyForRestorationSummary();}} +} diff --git a/src/execution/ShutdownCoordinator.h b/src/execution/ShutdownCoordinator.h new file mode 100644 index 0000000..95e4260 --- /dev/null +++ b/src/execution/ShutdownCoordinator.h @@ -0,0 +1,10 @@ +#pragma once +#include "PlanExecutor.h" +namespace ald { +class ShutdownCoordinator:public QObject { + Q_OBJECT +public:explicit ShutdownCoordinator(PlanExecutor &executor,QObject *parent=nullptr);void request(); +signals:void readyForRestorationSummary(); +private:PlanExecutor &executor_;bool requested_=false; +}; +} diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..1797b93 --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,35 @@ +#include "app/AppController.h" +#include "ui/MainWindow.h" +#include "ui/Theme.h" +#include "ui/pages/WorkflowPage.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int main(int argc,char **argv) { + QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); + QApplication app(argc,argv);QLocale::setDefault(QLocale(QLocale::Russian));QTranslator translator;if(translator.load("qtbase_ru",QLibraryInfo::location(QLibraryInfo::TranslationsPath)))app.installTranslator(&translator);app.setApplicationName("ALD Transition Console");app.setOrganizationName("ALDTransitionConsole");app.setApplicationVersion("0.1.0-dev"); + if(geteuid()==0){QMessageBox::critical(nullptr,"Запуск запрещён","GUI запускается обычным администратором без root. Для разрешённых операций используется отдельная временная авторизация.");return 77;} + QCommandLineParser parser;parser.setApplicationDescription("Локальная консоль подготовки перехода AD → ALD Pro 3.1");parser.addHelpOption();parser.addVersionOption(); + parser.addOption({"project","Явно выбранный защищённый каталог проекта (0700)","directory"});parser.addOption({"demo","Только синтетические offline-примеры, отдельный проект"});parser.addOption({"smoke-test","DEMO smoke test: close after rendering"});parser.addOption({"capture","DEMO screenshot destination","file"});parser.process(app); + try { + ald::AppController controller;ald::ui::Theme::apply(app);QString directory=parser.value("project");bool demo=parser.isSet("demo"); + if(directory.isEmpty()) { + QDialog dialog;dialog.setWindowTitle("Открыть проект ALD Transition Console");auto *layout=new QVBoxLayout(&dialog);layout->addWidget(ald::ui::plainLabel("Выберите отдельный защищённый каталог для инфраструктурных данных. Проект запоминает режим: смешивать live и demo нельзя."));auto *path=new QLineEdit;path->setAccessibleName("Защищённый каталог проекта");layout->addWidget(path);auto *browse=new QPushButton("Выбрать каталог…");layout->addWidget(browse);QObject::connect(browse,&QPushButton::clicked,&dialog,[&]{auto value=QFileDialog::getExistingDirectory(&dialog,"Каталог проекта, владелец — текущий администратор, права 0700");if(!value.isEmpty())path->setText(value);});auto *mode=new QCheckBox("Offline DEMO: синтетический ALD-LAB");mode->setChecked(demo);layout->addWidget(mode);auto *buttons=new QDialogButtonBox(QDialogButtonBox::Open|QDialogButtonBox::Cancel);layout->addWidget(buttons);QObject::connect(buttons,&QDialogButtonBox::accepted,&dialog,&QDialog::accept);QObject::connect(buttons,&QDialogButtonBox::rejected,&dialog,&QDialog::reject);if(dialog.exec()!=QDialog::Accepted)return 0;directory=path->text();demo=mode->isChecked();if(directory.trimmed().isEmpty())return 1; + } + if((parser.isSet("capture")||parser.isSet("smoke-test"))&&!demo)throw std::runtime_error("Capture/smoke test is restricted to explicit synthetic DEMO"); + controller.open(directory,demo);ald::ui::MainWindow window(controller);window.setSmokeTest(parser.isSet("smoke-test"));window.show(); + if(parser.isSet("capture"))QTimer::singleShot(800,&window,[&]{window.grab().save(parser.value("capture"));}); + if(parser.isSet("smoke-test"))QTimer::singleShot(1200,&window,&QWidget::close); + return app.exec(); + }catch(const std::exception &e){QMessageBox box(QMessageBox::Critical,"Проект не открыт",QString::fromUtf8(e.what()),QMessageBox::Ok);box.setTextFormat(Qt::PlainText);box.exec();return 1;} +} diff --git a/src/privileged/ExecutorMain.cpp b/src/privileged/ExecutorMain.cpp new file mode 100644 index 0000000..a13dbaa --- /dev/null +++ b/src/privileged/ExecutorMain.cpp @@ -0,0 +1,33 @@ +#include "OperationDispatcher.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int main(int argc,char **argv) { + QCoreApplication app(argc,argv); + if(geteuid()!=0||argc!=3)return 77; + bool ok=false;const auto caller=qEnvironmentVariable("PKEXEC_UID").toUInt(&ok);if(!ok||caller==0)return 77; + const auto parent=QString::fromLocal8Bit(argv[2]).toLongLong(&ok);if(!ok||parent<=1)return 77; + const QString path=QString::fromLocal8Bit(argv[1]);const QFileInfo info(path);struct stat st{}; + if(!info.isAbsolute()||path.size()>100||lstat(QFile::encodeName(info.absolutePath()).constData(),&st)!=0||!S_ISDIR(st.st_mode)||st.st_uid!=caller||(st.st_mode&0077))return 77; + if(lstat(QFile::encodeName(path).constData(),&st)!=0||!S_ISSOCK(st.st_mode)||st.st_uid!=caller)return 77; + QLocalSocket socket;ald::OperationDispatcher dispatcher;QByteArray input;bool handled=false,authenticated=false; + QObject::connect(&socket,&QLocalSocket::connected,&app,[&]{ + struct ucred credentials{};socklen_t size=sizeof(credentials); + if(getsockopt(int(socket.socketDescriptor()),SOL_SOCKET,SO_PEERCRED,&credentials,&size)!=0||credentials.uid!=caller||credentials.pid!=parent){app.exit(77);return;}authenticated=true; + }); + QObject::connect(&socket,&QLocalSocket::readyRead,&app,[&]{ + if(!authenticated){app.exit(77);return;}input+=socket.readAll();if(input.size()>16384||handled){app.exit(77);return;} + if(input.contains('\n')){handled=true;QJsonParseError error;auto document=QJsonDocument::fromJson(input,&error);if(error.error!=QJsonParseError::NoError||!document.isObject()){app.exit(77);return;}dispatcher.dispatch(document.object());} + }); + QObject::connect(&dispatcher,&ald::OperationDispatcher::completed,&app,[&](const QJsonObject &r){socket.write(QJsonDocument(r).toJson(QJsonDocument::Compact)+'\n');socket.disconnectFromServer();}); + QObject::connect(&socket,&QLocalSocket::disconnected,&app,&QCoreApplication::quit); + QTimer::singleShot(30000,&app,[&]{app.exit(124);}); + socket.connectToServer(path);return app.exec(); +} diff --git a/src/privileged/OperationDispatcher.cpp b/src/privileged/OperationDispatcher.cpp new file mode 100644 index 0000000..3897c8e --- /dev/null +++ b/src/privileged/OperationDispatcher.cpp @@ -0,0 +1,38 @@ +#include "OperationDispatcher.h" +#include +#include +#include +#include +#include +#include +#include +#include +namespace ald { +OperationDispatcher::OperationDispatcher(QObject *p):QObject(p) { + connect(&process_,&QProcess::readyReadStandardOutput,this,[this]{auto b=process_.readAllStandardOutput();if(output_.size()+b.size()>65536){exceeded_=true;process_.kill();}else output_+=b;}); + connect(&process_,&QProcess::readyReadStandardError,this,[this]{process_.readAllStandardError();}); // Native diagnostics may include paths: omit from privileged reply. + connect(&process_,&QProcess::errorOccurred,this,[this](QProcess::ProcessError e){if(e==QProcess::FailedToStart)emit completed({{"result","ERROR"},{"reason_ru","Штатный sshd не запущен; проверьте установку и права локально"}});}); + connect(&process_,QOverload::of(&QProcess::finished),this,[this](int code,QProcess::ExitStatus status){ + QString observed;for(const auto &line:QString::fromUtf8(output_).split('\n'))if(line.startsWith("permitrootlogin "))observed=line.mid(16).trimmed(); + bool ok=code==0&&status==QProcess::NormalExit&&!exceeded_&&!observed.isEmpty(); + emit completed({{"schema_version",1},{"operation_id","ssh.effective"},{"result",ok?"OBSERVED":"ERROR"},{"permitrootlogin",observed},{"limitations_ru","Глобальная эффективная конфигурация без Match-контекста подключения; не является заключением о соответствии"}}); + }); +} +void OperationDispatcher::dispatch(const QJsonObject &r) { + QFile machine("/etc/machine-id"); + if(!machine.open(QIODevice::ReadOnly)){emit completed({{"result","DENIED"},{"reason_ru","Нельзя проверить привязку локального узла"}});return;} + const auto machineId=machine.read(128).trimmed(); + if(!QRegularExpression("^[0-9a-f]{32}$").match(QString::fromLatin1(machineId)).hasMatch()){emit completed({{"result","DENIED"},{"reason_ru","Некорректная идентичность локального узла"}});return;} + const auto binding=QString::fromLatin1(QCryptographicHash::hash(machineId,QCryptographicHash::Sha256).toHex()); + auto keys=r.keys();auto expected=QStringList{"schema_version","operation_id","target_binding","parameters"};keys.sort();expected.sort(); + if(used_||keys!=expected||!r.value("schema_version").isDouble()||r.value("schema_version").toDouble()!=1.0||r.value("operation_id").toString()!="ssh.effective"||!r.value("parameters").isObject()||!r.value("parameters").toObject().isEmpty()||r.value("target_binding").toString()!=binding){emit completed({{"result","DENIED"},{"reason_ru","Неподдержанная операция, параметры или привязка узла"}});return;} + used_=true; + const auto binary=QFileInfo("/usr/sbin/sshd").canonicalFilePath();struct stat st{}; + if(binary.isEmpty()||stat(QFile::encodeName(binary).constData(),&st)!=0||!S_ISREG(st.st_mode)||st.st_uid!=0||(st.st_mode&0022)){emit completed({{"result","DENIED"},{"reason_ru","Нет доверенного штатного sshd"}});return;} + QString parent=QFileInfo(binary).absolutePath(); + for(;;){if(lstat(QFile::encodeName(parent).constData(),&st)!=0||!S_ISDIR(st.st_mode)||st.st_uid!=0||(st.st_mode&0022)){emit completed({{"result","DENIED"},{"reason_ru","Недоверенный каталог штатного sshd"}});return;}if(parent=="/")break;parent=QFileInfo(parent).absolutePath();} + QProcessEnvironment env;env.insert("PATH","/usr/sbin:/usr/bin:/sbin:/bin");env.insert("LC_ALL","C");process_.setProcessEnvironment(env);process_.setWorkingDirectory("/"); + process_.start(binary,QStringList{"-T"});process_.closeWriteChannel(); + QTimer::singleShot(10000,this,[this]{if(process_.state()!=QProcess::NotRunning)process_.kill();}); +} +} diff --git a/src/privileged/OperationDispatcher.h b/src/privileged/OperationDispatcher.h new file mode 100644 index 0000000..44211d1 --- /dev/null +++ b/src/privileged/OperationDispatcher.h @@ -0,0 +1,12 @@ +#pragma once +#include +#include +#include +namespace ald { +class OperationDispatcher:public QObject { + Q_OBJECT +public:explicit OperationDispatcher(QObject *parent=nullptr);void dispatch(const QJsonObject &request); +signals:void completed(const QJsonObject &response); +private:QProcess process_;QByteArray output_;bool exceeded_=false,used_=false; +}; +} diff --git a/src/security/AccessLedger.cpp b/src/security/AccessLedger.cpp new file mode 100644 index 0000000..a57f093 --- /dev/null +++ b/src/security/AccessLedger.cpp @@ -0,0 +1,18 @@ +#include "AccessLedger.h" +#include "storage/JsonValidator.h" +namespace ald { +QJsonObject AccessLedger::assess(const QJsonObject &change,const QJsonObject ¤t,bool reachable,const QString &runOwner) { + const bool owned=!runOwner.isEmpty()&&change.value("owner_marker").toString()==runOwner; + const bool last=change.value("resource_type").toString()=="LAST_ACCESS_CHANNEL"; + auto decision=rules::restoration(owned,reachable,JsonValidator::digest(current).toStdString(),JsonValidator::digest(change.value("applied_state")).toStdString(),last); + QString state,reason; + switch(decision){ + case rules::RestoreDecision::Preserve:state="PRESERVED";reason="Ресурс не принадлежит этому запуску. Оставить без изменений.";break; + case rules::RestoreDecision::Conflict:state="CONFLICT";reason="Текущее состояние отличается от внесённого. Автовосстановление запрещено.";break; + case rules::RestoreDecision::Pending:state="PENDING";reason="Узел недоступен. Восстановление не подтверждено; сохранить ручные шаги.";break; + case rules::RestoreDecision::ManualVerification:state="MANUAL_VERIFICATION_REQUIRED";reason="Закрывать канал последним. Проверка после закрытия — с локальной консоли.";break; + default:state="READY_FOR_REVIEW";reason="Состояние совпадает. Нужны проверенная обратная операция и разрешение конкретного изменения.";break; + } + return {{"change_id",change.value("id")},{"decision",state},{"reason_ru",reason},{"restoration_steps",change.value("restoration_steps")},{"observed_at",utcNow()}}; +} +} diff --git a/src/security/AccessLedger.h b/src/security/AccessLedger.h new file mode 100644 index 0000000..9e9dd09 --- /dev/null +++ b/src/security/AccessLedger.h @@ -0,0 +1,3 @@ +#pragma once +#include "domain/Types.h" +namespace ald {class AccessLedger {public:static QJsonObject assess(const QJsonObject &change,const QJsonObject ¤t,bool reachable,const QString &runOwner);};} diff --git a/src/security/PrivilegedClient.cpp b/src/security/PrivilegedClient.cpp new file mode 100644 index 0000000..9f94433 --- /dev/null +++ b/src/security/PrivilegedClient.cpp @@ -0,0 +1,43 @@ +#include "PrivilegedClient.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifndef ALD_EXECUTOR_PATH +#define ALD_EXECUTOR_PATH "/usr/libexec/ald-transition-console/ald-transition-executor" +#endif +namespace ald { +PrivilegedClient::PrivilegedClient(QObject *p):QObject(p) { + connect(&server_,&QLocalServer::newConnection,this,[this]{ + auto *peer=server_.nextPendingConnection();struct ucred credentials{};socklen_t size=sizeof(credentials); + if(socket_||getsockopt(int(peer->socketDescriptor()),SOL_SOCKET,SO_PEERCRED,&credentials,&size)!=0||credentials.uid!=0||credentials.pid!=process_.processId()){peer->abort();peer->deleteLater();return;} + socket_=peer;server_.close(); + connect(peer,&QLocalSocket::readyRead,this,[this]{input_+=socket_->readAll();if(input_.size()>16384){socket_->abort();return;}}); + QFile machine("/etc/machine-id");if(!machine.open(QIODevice::ReadOnly)){peer->abort();return;} + QJsonObject request{{"schema_version",1},{"operation_id","ssh.effective"},{"target_binding",QString::fromLatin1(QCryptographicHash::hash(machine.readAll().trimmed(),QCryptographicHash::Sha256).toHex())},{"parameters",QJsonObject{}}}; + peer->write(QJsonDocument(request).toJson(QJsonDocument::Compact)+'\n'); + }); + connect(&process_,QOverload::of(&QProcess::finished),this,[this](int code,QProcess::ExitStatus){ + if(socket_)input_+=socket_->readAll();auto doc=QJsonDocument::fromJson(input_);QJsonObject result=doc.object(); + if(code!=0||result.isEmpty())result={{"result","ERROR"},{"reason_ru","Авторизация/исполнитель не завершены. Проверьте установку пакета и локальный polkit. Изменений не выполнено."}}; + server_.close();if(socket_){socket_->deleteLater();socket_=nullptr;}directory_.reset();delivered_=true;emit completed(result); + }); + connect(&process_,&QProcess::errorOccurred,this,[this](QProcess::ProcessError e){if(e==QProcess::FailedToStart){server_.close();directory_.reset();delivered_=true;emit completed({{"result","ERROR"},{"reason_ru","Не удалось запустить pkexec. Выполните проверку локально."}});}}); +} +void PrivilegedClient::auditSsh() { + if(active())throw std::runtime_error("Privileged audit already active"); + if(!QFile::exists(ALD_EXECUTOR_PATH))throw std::runtime_error("Executor is not installed at the fixed protected path; use manual sshd -T inspection"); + directory_=std::make_unique(QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation)+"/ald-session-XXXXXX"); + if(!directory_->isValid())throw std::runtime_error("Private runtime directory unavailable"); + const auto path=directory_->path()+"/ipc";server_.setSocketOptions(QLocalServer::UserAccessOption);if(!server_.listen(path))throw std::runtime_error("Private IPC unavailable"); + input_.clear();delivered_=false; + process_.start("/usr/bin/pkexec",QStringList{ALD_EXECUTOR_PATH,path,QString::number(QCoreApplication::applicationPid())}); +} +bool PrivilegedClient::active()const{return process_.state()!=QProcess::NotRunning;} +void PrivilegedClient::cancel(){if(active()){process_.terminate();QTimer::singleShot(2000,this,[this]{if(active())process_.kill();});}} +} diff --git a/src/security/PrivilegedClient.h b/src/security/PrivilegedClient.h new file mode 100644 index 0000000..48a0f8e --- /dev/null +++ b/src/security/PrivilegedClient.h @@ -0,0 +1,16 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +namespace ald { +class PrivilegedClient:public QObject { + Q_OBJECT +public:explicit PrivilegedClient(QObject *parent=nullptr);void auditSsh();bool active()const;void cancel(); +signals:void completed(const QJsonObject &result); +private:QProcess process_;QLocalServer server_;QLocalSocket *socket_=nullptr;std::unique_ptr directory_;QByteArray input_;bool delivered_=false; +}; +} diff --git a/src/security/SecretRedactor.cpp b/src/security/SecretRedactor.cpp new file mode 100644 index 0000000..f931d85 --- /dev/null +++ b/src/security/SecretRedactor.cpp @@ -0,0 +1,6 @@ +#include "SecretRedactor.h" +namespace ald { +static std::vector utf8(const QStringList &list){std::vectors;for(const auto &v:list)s.push_back(v.toUtf8().toStdString());return s;} +SecretRedactor::SecretRedactor(const QStringList &secrets):stream_(utf8(secrets)),decoder_(QTextCodec::codecForName("UTF-8")->makeDecoder()){} +QString SecretRedactor::feed(const QByteArray &chunk,bool final){const auto redacted=stream_.feed(chunk.toStdString(),final);return decoder_->toUnicode(redacted.data(),int(redacted.size()));} +} diff --git a/src/security/SecretRedactor.h b/src/security/SecretRedactor.h new file mode 100644 index 0000000..945dcc7 --- /dev/null +++ b/src/security/SecretRedactor.h @@ -0,0 +1,15 @@ +#pragma once +#include "core/Rules.h" +#include +#include +#include +#include +namespace ald { +class SecretRedactor { +public: + explicit SecretRedactor(const QStringList &secrets = {}); + QString feed(const QByteArray &chunk,bool final=false); +private: + rules::SecretStream stream_;std::unique_ptr decoder_; +}; +} diff --git a/src/storage/DatabaseMigrator.cpp b/src/storage/DatabaseMigrator.cpp new file mode 100644 index 0000000..57998de --- /dev/null +++ b/src/storage/DatabaseMigrator.cpp @@ -0,0 +1,26 @@ +#include "DatabaseMigrator.h" +#include +#include +#include +#include +namespace ald { +void DatabaseMigrator::migrate(QSqlDatabase &db) { + auto exec=[&](const QString &sql){QSqlQuery q(db);if(!q.exec(sql))throw std::runtime_error(q.lastError().text().toStdString());}; + QSqlQuery version(db);if(!version.exec("PRAGMA user_version")||!version.next())throw std::runtime_error("Cannot read schema version"); + const int v=version.value(0).toInt();version.finish();if(v>3)throw std::runtime_error("Project created by newer software; refusing downgrade"); + if(!db.transaction())throw std::runtime_error("Cannot begin migration"); + try { + if(v<1) { + exec("CREATE TABLE documents(kind TEXT NOT NULL, id TEXT NOT NULL, body TEXT NOT NULL, updated_at TEXT NOT NULL, PRIMARY KEY(kind,id))"); + exec("CREATE TABLE observations(sequence INTEGER PRIMARY KEY AUTOINCREMENT, item_id TEXT NOT NULL, host_id TEXT NOT NULL, method TEXT NOT NULL CHECK(method IN ('HUMAN','AUTOMATIC')), context TEXT NOT NULL, body TEXT NOT NULL)"); + exec("CREATE TABLE events(sequence INTEGER PRIMARY KEY AUTOINCREMENT, timestamp_utc TEXT NOT NULL, run_id TEXT NOT NULL, host_id TEXT NOT NULL, operation_id TEXT NOT NULL, severity TEXT NOT NULL, stream TEXT NOT NULL, message_ru TEXT NOT NULL, redacted_detail TEXT NOT NULL)"); + exec("CREATE TABLE runs(id TEXT PRIMARY KEY, state TEXT NOT NULL, body TEXT NOT NULL)"); + exec("CREATE TABLE access_changes(id TEXT PRIMARY KEY, body TEXT NOT NULL)"); + } + if(v<2) {exec("CREATE INDEX observations_context ON observations(context,item_id,host_id,method)");exec("CREATE INDEX events_run ON events(run_id,sequence)");} + if(v<3){exec("CREATE TABLE run_history(sequence INTEGER PRIMARY KEY AUTOINCREMENT, run_id TEXT NOT NULL, timestamp_utc TEXT NOT NULL, state TEXT NOT NULL, body TEXT NOT NULL)");exec("CREATE INDEX run_history_id ON run_history(run_id,sequence)");} + exec("PRAGMA user_version=3"); + if(!db.commit())throw std::runtime_error(("Cannot commit migration: "+db.lastError().text()).toStdString()); + } catch(...) {db.rollback();throw;} +} +} diff --git a/src/storage/DatabaseMigrator.h b/src/storage/DatabaseMigrator.h new file mode 100644 index 0000000..b3fa06d --- /dev/null +++ b/src/storage/DatabaseMigrator.h @@ -0,0 +1,3 @@ +#pragma once +#include +namespace ald { class DatabaseMigrator {public: static void migrate(QSqlDatabase &db);}; } diff --git a/src/storage/JsonValidator.cpp b/src/storage/JsonValidator.cpp new file mode 100644 index 0000000..4236e70 --- /dev/null +++ b/src/storage/JsonValidator.cpp @@ -0,0 +1,120 @@ +#include "JsonValidator.h" +#include "core/Rules.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ald { +static void fail(const QString &s) { throw std::runtime_error(s.toStdString()); } +static bool typeMatch(const QJsonValue &v,const QString &t) { + return (t=="null"&&v.isNull())||(t=="string"&&v.isString())||(t=="object"&&v.isObject())|| + (t=="array"&&v.isArray())||(t=="boolean"&&v.isBool())||(t=="number"&&v.isDouble())|| + (t=="integer"&&v.isDouble()&&std::floor(v.toDouble())==v.toDouble()); +} +QJsonDocument JsonValidator::parse(const QByteArray &bytes,const QString &schemaName) { + if(bytes.size()>16*1024*1024)fail("JSON exceeds 16 MiB"); + QTextCodec::ConverterState utf8; + QTextCodec::codecForName("UTF-8")->toUnicode(bytes.constData(),bytes.size(),&utf8); + if(utf8.invalidChars || utf8.remainingChars)fail("Invalid UTF-8"); + // Bound nesting before Qt allocates the parsed tree. + int depth=0;bool quoted=false,escape=false; + for(char c:bytes) { + if(quoted) {if(escape)escape=false;else if(c=='\\')escape=true;else if(c=='"')quoted=false;} + else if(c=='"')quoted=true; + else if(c=='{'||c=='[') {if(++depth>32)fail("JSON nesting exceeds 32");} + else if(c=='}'||c==']')--depth; + } + struct Frame {bool object;QSet keys;};QVector frames; + for(int i=0;i32)fail(path+": nesting limit"); + const auto type=s.value("type"); + if(type.isString()&&!typeMatch(v,type.toString()))fail(path+": invalid type"); + if(type.isArray()) {bool found=false;for(const auto &t:type.toArray())found|=typeMatch(v,t.toString());if(!found)fail(path+": invalid type");} + if(s.contains("const")&&v!=s.value("const"))fail(path+": unsupported version or constant"); + if(s.contains("enum")&&!s.value("enum").toArray().contains(v))fail(path+": unknown enum"); + if(v.isString()) { + const auto str=v.toString(); + if(str.size()>s.value("maxLength").toInt(65536)||str.contains(QChar(0)))fail(path+": string limit or NUL"); + if(s.contains("pattern")&&!QRegularExpression(s.value("pattern").toString()).match(str).hasMatch())fail(path+": pattern mismatch"); + const auto fmt=s.value("format").toString(); + if(fmt=="uuid"&&!QRegularExpression("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$").match(str).hasMatch())fail(path+": invalid UUID"); + if(fmt=="hostname"&&(!rules::safeHost(str.toStdString())||!str.contains('.')))fail(path+": invalid FQDN (use explicit ASCII/IDNA)"); + if(fmt=="ip-address"&&QHostAddress(str).isNull())fail(path+": invalid address"); + if(fmt=="date-time"&&(!QDateTime::fromString(str,Qt::ISODateWithMs).isValid()||!QRegularExpression("(Z|[+-][0-9]{2}:[0-9]{2})$").match(str).hasMatch()))fail(path+": invalid timestamp"); + if(fmt=="uri"&&(!QUrl(str).isValid()||QUrl(str).scheme()!="https"))fail(path+": expected HTTPS URL"); + } + if(v.isDouble()) {if(s.contains("minimum")&&v.toDouble()s.value("maximum").toDouble())fail(path+": above maximum");} + if(v.isObject()) { + const auto o=v.toObject(),props=s.value("properties").toObject(); + if(o.size()>10000)fail(path+": too many fields"); + for(const auto &r:s.value("required").toArray())if(!o.contains(r.toString()))fail(path+": missing "+r.toString()); + for(auto it=o.begin();it!=o.end();++it) { + if(props.contains(it.key()))validate(it.value(),props.value(it.key()).toObject(),path+"."+it.key(),depth+1); + else if(s.contains("additionalProperties")&&!s.value("additionalProperties").toBool())fail(path+": unknown field "+it.key()); + } + } + if(v.isArray()) {const auto a=v.toArray();if(a.size()>s.value("maxItems").toInt(50000))fail(path+": too many items");int i=0;for(const auto &x:a)validate(x,s.value("items").toObject(),path+"["+QString::number(i++)+"]",depth+1);} +} +void JsonValidator::ensureDataOnly(const QJsonValue &v,int depth) { + if(depth>32)fail("Data depth exceeded"); + if(v.isString()&&(v.toString().size()>65536||v.toString().contains(QChar(0))))fail("Invalid data string"); + if(v.isObject()) { + const auto o=v.toObject(); + if(o.size()>10000)fail("Data object limit"); + for(auto it=o.begin();it!=o.end();++it) { + const auto key=it.key().toLower(); + if(QStringList{"password","passwd","unicodepwd","userpassword","private_key","privatekey","token","secret","ms-mcs-admpwd","mslaps-password","supplementalcredentials"}.contains(key)) + fail("Secret-bearing field is not permitted: "+it.key()); + if(it.key().size()>256)fail("Data key too long"); + ensureDataOnly(it.value(),depth+1); + } + } + if(v.isArray()) {if(v.toArray().size()>50000)fail("Data array limit");for(const auto &x:v.toArray())ensureDataOnly(x,depth+1);} +} +QByteArray JsonValidator::canonical(const QJsonValue &v) { + if(v.isObject()) { + auto o=v.toObject();auto keys=o.keys();std::sort(keys.begin(),keys.end());QByteArray b="{";bool first=true; + for(const auto &k:keys) {if(!first)b+=',';first=false;auto key=QJsonDocument(QJsonArray{k}).toJson(QJsonDocument::Compact);b+=key.mid(1,key.size()-2)+":"+canonical(o.value(k));}return b+"}"; + } + if(v.isArray()){QByteArray b="[";bool first=true;for(const auto &x:v.toArray()){if(!first)b+=',';first=false;b+=canonical(x);}return b+"]";} + auto b=QJsonDocument(QJsonArray{v}).toJson(QJsonDocument::Compact);return b.mid(1,b.size()-2); +} +QString JsonValidator::digest(const QJsonValue &v) {return QString::fromLatin1(QCryptographicHash::hash(canonical(v),QCryptographicHash::Sha256).toHex());} +} diff --git a/src/storage/JsonValidator.h b/src/storage/JsonValidator.h new file mode 100644 index 0000000..5c03cad --- /dev/null +++ b/src/storage/JsonValidator.h @@ -0,0 +1,14 @@ +#pragma once +#include +#include + +namespace ald { +class JsonValidator { +public: + static QJsonDocument parse(const QByteArray &bytes, const QString &schema); + static void validate(const QJsonValue &value, const QJsonObject &schema, const QString &path = "$", int depth = 0); + static void ensureDataOnly(const QJsonValue &value, int depth = 0); + static QString digest(const QJsonValue &value); + static QByteArray canonical(const QJsonValue &value); +}; +} diff --git a/src/storage/OfflineBundle.cpp b/src/storage/OfflineBundle.cpp new file mode 100644 index 0000000..7ab4f39 --- /dev/null +++ b/src/storage/OfflineBundle.cpp @@ -0,0 +1,26 @@ +#include "OfflineBundle.h" +#include "JsonValidator.h" +#include "core/Rules.h" +#include +#include +#include +#include +#include +namespace ald { +QJsonObject OfflineBundle::inspect(const QByteArray &bytes) { + const auto bundle=JsonValidator::parse(bytes,"offline-bundle").object();QSet paths;QJsonArray artifacts; + for(const auto &v:bundle.value("artifacts").toArray()) { + const auto a=v.toObject();const auto path=a.value("path").toString(),kind=a.value("kind").toString(); + if(!rules::safeRelativePath(path.toStdString())||!path.endsWith(".json")||paths.contains(path))throw std::runtime_error("Unsafe or repeated bundle path"); + paths.insert(path); + const auto encoded=a.value("base64").toString().toLatin1(); + if(!QRegularExpression("^[A-Za-z0-9+/]*={0,2}$").match(QString::fromLatin1(encoded)).hasMatch()||encoded.size()%4)throw std::runtime_error("Invalid bundle encoding"); + const auto data=QByteArray::fromBase64(encoded); + if(QCryptographicHash::hash(data,QCryptographicHash::Sha256).toHex()!=a.value("sha256").toString().toLatin1())throw std::runtime_error("Bundle digest mismatch"); + if(!QStringList{"inventory","profile","checklist","source"}.contains(kind))throw std::runtime_error("Executable or unsupported bundle artifact rejected"); + const auto parsed=JsonValidator::parse(data,kind); + artifacts.append(QJsonObject{{"path",path},{"kind",kind},{"sha256",a.value("sha256")},{"source_id",a.value("source_id")},{"body",parsed.object()}}); + } + return {{"schema_version",1},{"revision",bundle.value("revision")},{"provenance",bundle.value("provenance")},{"integrity_state","DIGESTS_MATCH"},{"publisher_signature_state","NOT_VERIFIED"},{"acceptance_state","REVIEW_REQUIRED"},{"artifacts",artifacts},{"note_ru","Хэш проверяет содержимое, но не личность издателя. Подпись и происхождение требуют отдельной проверки. Профили и каталог не активированы автоматически; исполняемые пакеты не импортируются."}}; +} +} diff --git a/src/storage/OfflineBundle.h b/src/storage/OfflineBundle.h new file mode 100644 index 0000000..f4eeef9 --- /dev/null +++ b/src/storage/OfflineBundle.h @@ -0,0 +1,7 @@ +#pragma once +#include +namespace ald { +// A reviewable JSON data bundle, not an installer or general archive extractor. +// Compiled schemas, executable tasks and accepted profiles are never replaced. +class OfflineBundle {public:static QJsonObject inspect(const QByteArray &bytes);}; +} diff --git a/src/storage/ProjectRepository.cpp b/src/storage/ProjectRepository.cpp new file mode 100644 index 0000000..57e4ff4 --- /dev/null +++ b/src/storage/ProjectRepository.cpp @@ -0,0 +1,130 @@ +#include "ProjectRepository.h" +#include "DatabaseMigrator.h" +#include "JsonValidator.h" +#include "domain/Types.h" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ald { +static void checked(QSqlQuery &q){if(!q.exec())throw std::runtime_error(q.lastError().text().toStdString());} +static QString json(const QJsonObject &o){return QString::fromUtf8(QJsonDocument(o).toJson(QJsonDocument::Compact));} +static QJsonObject unjson(const QVariant &v){ + QJsonParseError error;const auto doc=QJsonDocument::fromJson(v.toString().toUtf8(),&error); + if(error.error!=QJsonParseError::NoError||!doc.isObject())throw std::runtime_error("Corrupt project record; reconcile from a verified backup"); + JsonValidator::ensureDataOnly(doc.object());return doc.object(); +} +ProjectRepository::ProjectRepository():connection_(newId()){} +ProjectRepository::~ProjectRepository(){db_.close();db_=QSqlDatabase();QSqlDatabase::removeDatabase(connection_);} +void ProjectRepository::open(const QString &dir) { + if(db_.isOpen())throw std::runtime_error("Project already open"); + const auto path=QFileInfo(dir).absoluteFilePath(); + if(!QFileInfo::exists(path)) { + if(!QDir().mkdir(path) || !QFile::setPermissions(path,QFile::ReadOwner|QFile::WriteOwner|QFile::ExeOwner))throw std::runtime_error("Cannot create private project directory; choose an existing protected parent"); + } + struct stat st{}; + if(lstat(QFile::encodeName(path).constData(),&st)!=0||!S_ISDIR(st.st_mode)||st.st_uid!=getuid()||(st.st_mode&0077)) + throw std::runtime_error("Project directory must be owned by this administrator, mode 0700, and not a symlink"); + directory_=QFileInfo(path).canonicalFilePath(); + lock_=std::make_unique(directory_+"/writer.lock");lock_->setStaleLockTime(0); + if(!lock_->tryLock(0))throw std::runtime_error("Another writer holds this project"); + const QString file=directory_+"/project.sqlite"; + if(lstat(QFile::encodeName(file).constData(),&st)==0 && (!S_ISREG(st.st_mode)||st.st_uid!=getuid()||(st.st_mode&0077)||st.st_nlink!=1))throw std::runtime_error("Unsafe database file"); + const mode_t old=umask(0077); + db_=QSqlDatabase::addDatabase("QSQLITE",connection_);db_.setDatabaseName(file);db_.setConnectOptions("QSQLITE_BUSY_TIMEOUT=3000"); + const bool opened=db_.open();umask(old); + if(!opened)throw std::runtime_error(db_.lastError().text().toStdString()); + QSqlQuery pragma(db_);if(!pragma.exec("PRAGMA foreign_keys=ON")||!pragma.exec("PRAGMA journal_mode=DELETE"))throw std::runtime_error("SQLite pragma failed"); + pragma.finish(); + DatabaseMigrator::migrate(db_); + // A crash is a reconciliation obligation, never an implicit resume. + QSqlQuery recover(db_);recover.prepare("SELECT id,body,state FROM runs WHERE state IN ('RUNNING','PREFLIGHT','READY','PAUSED','PAUSE_REQUESTED','STOP_REQUESTED','VERIFYING','CLEANUP')");checked(recover); + QJsonArray interrupted;while(recover.next())interrupted.append(QJsonObject{{"id",recover.value(0).toString()},{"previous_state",recover.value(2).toString()}}); + recover.finish();for(const auto &v:interrupted){auto o=v.toObject();journalRun(o.value("id").toString(),"RECOVERY_REQUIRED",{{"previous_state",o.value("previous_state")},{"recovery_reason","Application interrupted; actual state must be reconciled"}});} + +} +void ProjectRepository::save(const QString &kind,const QString &id,const QJsonObject &body) { + JsonValidator::ensureDataOnly(body); + QSqlQuery q(db_);q.prepare("INSERT OR REPLACE INTO documents(kind,id,body,updated_at) VALUES(?,?,?,?)");q.addBindValue(kind);q.addBindValue(id);q.addBindValue(json(body));q.addBindValue(utcNow());checked(q); +} +void ProjectRepository::saveBatch(const QJsonArray &documents) { + if(!db_.transaction())throw std::runtime_error("Cannot begin project transaction"); + try {for(const auto &v:documents){auto o=v.toObject();save(o.value("kind").toString(),o.value("id").toString(),o.value("body").toObject());}if(!db_.commit())throw std::runtime_error("Cannot commit project transaction");} + catch(...){db_.rollback();throw;} +} +QJsonObject ProjectRepository::load(const QString &kind,const QString &id)const { + QSqlQuery q(db_);q.prepare("SELECT body FROM documents WHERE kind=? AND id=?");q.addBindValue(kind);q.addBindValue(id);checked(q);return q.next()?unjson(q.value(0)):QJsonObject{}; +} +void ProjectRepository::observe(QJsonObject o,const QString &context) { + JsonValidator::ensureDataOnly(o); + const auto method=o.value("method").toString(); + if(method!="HUMAN"&&method!="AUTOMATIC")throw std::runtime_error("Invalid observation method"); + if(!QStringList{"PASS","FAIL","PARTIAL","NOT_CHECKED","ERROR","STALE"}.contains(o.value("result").toString()))throw std::runtime_error("Invalid result"); + if(o.value("host_id").toString().isEmpty()||o.value("checked_by").toString().isEmpty())throw std::runtime_error("Host and operator/evaluator required"); + if(o.value("applicability").toString()=="NOT_APPLICABLE_WITH_REASON"&&(o.value("note").toString().trimmed().isEmpty()||o.value("result").toString()!="NOT_CHECKED"))throw std::runtime_error("Not applicable requires a reason and is not PASS"); + o["checked_at"]=utcNow();QSqlQuery q(db_);q.prepare("INSERT INTO observations(item_id,host_id,method,context,body) VALUES(?,?,?,?,?)"); + q.addBindValue(o.value("item_id").toString());q.addBindValue(o.value("host_id").toString());q.addBindValue(method);q.addBindValue(context);q.addBindValue(json(o));checked(q); +} +QJsonArray ProjectRepository::observations(const QString &context)const { + QSqlQuery q(db_);q.prepare("SELECT body,context,sequence FROM observations ORDER BY sequence");checked(q);QJsonArray a; + while(q.next()){auto o=unjson(q.value(0));o["original_result"]=o.value("result");if(q.value(1).toString()!=context)o["result"]="STALE";o["sequence"]=q.value(2).toDouble();a.append(o);}return a; +} +void ProjectRepository::event(const QString &run,const QString &host,const QString &op,const QString &severity,const QString &stream,const QString &message,const QString &detail) { + QSqlQuery q(db_);q.prepare("INSERT INTO events(timestamp_utc,run_id,host_id,operation_id,severity,stream,message_ru,redacted_detail) VALUES(?,?,?,?,?,?,?,?)"); + for(const auto &s:{utcNow(),run,host,op,severity,stream,message.left(4096),detail.left(32768)}) + q.addBindValue(s.isNull()?QStringLiteral(""):s); + checked(q); + // Keep bounded active DB logs; archive oldest batch atomically before deleting. + QSqlQuery count(db_);count.prepare("SELECT COUNT(*) FROM events");checked(count);count.next(); + if(count.value(0).toInt()>10000) { + QSqlQuery oldest(db_);oldest.prepare("SELECT sequence,timestamp_utc,run_id,host_id,operation_id,severity,stream,message_ru,redacted_detail FROM events ORDER BY sequence LIMIT 1000");checked(oldest); + const QStringList fields={"sequence","timestamp_utc","run_id","host_id","operation_id","severity","stream","message_ru","redacted_detail"}; + QByteArray lines;qint64 last=0; + while(oldest.next()){last=oldest.value(0).toLongLong();QJsonObject row;for(int i=0;iПроверки ALD Transition Console

Инструкционный чеклист

Ручные отметки не подтверждают поддержку миграции. Редакция: "+context.toHtmlEscaped()+"

"; + for(const auto &v:items) {const auto o=v.toObject();out+="

"+o.value("title_ru").toString().toHtmlEscaped()+"

"+o.value("purpose_ru").toString().toHtmlEscaped()+"

    ";for(const auto &s:o.value("steps_ru").toArray())out+="
  1. "+s.toString().toHtmlEscaped()+"
  2. ";out+="

Ожидается: "+o.value("expected_result_ru").toString().toHtmlEscaped()+"

При ошибке: "+o.value("failure_guidance_ru").toString().toHtmlEscaped()+"

"; + for(const auto &obs:observations_)if(obs.toObject().value("item_id")==o.value("id"))out+="
"+QString::fromUtf8(QJsonDocument(obs.toObject()).toJson()).toHtmlEscaped()+"
"; + out+="
";} + bytes=(out+"").toUtf8(); + } + QSaveFile f(file);if(!f.open(QIODevice::WriteOnly))throw std::runtime_error("Cannot create export");f.setPermissions(QFile::ReadOwner|QFile::WriteOwner);if(f.write(bytes)!=bytes.size()||!f.commit())throw std::runtime_error("Export failed"); +} +} diff --git a/src/storage/ProjectRepository.h b/src/storage/ProjectRepository.h new file mode 100644 index 0000000..f846547 --- /dev/null +++ b/src/storage/ProjectRepository.h @@ -0,0 +1,28 @@ +#pragma once +#include +#include +#include +#include +#include +namespace ald { +class ProjectRepository { +public: + ProjectRepository(); ~ProjectRepository(); + void open(const QString &directory); + void save(const QString &kind,const QString &id,const QJsonObject &body); + void saveBatch(const QJsonArray &documents); + QJsonObject load(const QString &kind,const QString &id) const; + void observe(QJsonObject observation,const QString &context); + QJsonArray observations(const QString &context) const; + void event(const QString &run,const QString &host,const QString &operation,const QString &severity,const QString &stream,const QString &message,const QString &detail = {}); + QJsonArray events(int limit=1000) const; + void journalRun(const QString &id,const QString &state,const QJsonObject &body); + QJsonArray interruptedRuns() const; + void saveAccessChange(const QJsonObject &change); + QJsonArray accessChanges() const; + QString directory() const {return directory_;} + void exportChecklist(const QString &file,const QJsonArray &items,const QString &context,bool html) const; +private: + QString connection_,directory_; QSqlDatabase db_;std::unique_ptr lock_; +}; +} diff --git a/src/transports/NativeSshTransport.cpp b/src/transports/NativeSshTransport.cpp new file mode 100644 index 0000000..ec35d31 --- /dev/null +++ b/src/transports/NativeSshTransport.cpp @@ -0,0 +1,25 @@ +#include "NativeSshTransport.h" +#include "core/Rules.h" +#include +#include +#include +#include +#include +#include +namespace ald { +ProcessSpec NativeSshTransport::windowsTask(const SshTarget &t,const QString &task) { + if(!rules::safeHost(t.host.toStdString())||!rules::safeUser(t.user.toStdString())||t.port==0)throw std::runtime_error("Invalid SSH target; no shell metacharacters accepted"); + QFileInfo info(t.knownHosts);struct stat st{}; + if(!info.isAbsolute()||lstat(QFile::encodeName(t.knownHosts).constData(),&st)!=0||!S_ISREG(st.st_mode)||(st.st_uid!=getuid()&&st.st_uid!=0)||(st.st_mode&0022))throw std::runtime_error("Select a verified, protected known_hosts file; do not trust a scan without independent fingerprint verification"); + // The ONLY remote command data is a compiled, hash-checked, fixed script. + // Host/user/known_hosts are local ssh argument values, never remote source code. + const auto script=QString::fromUtf8(OperationRegistry::task(task)); + QTextCodec::ConverterState state(QTextCodec::IgnoreHeader); + const auto encoded=QTextCodec::codecForName("UTF-16LE")->fromUnicode(script.constData(),script.size(),&state).toBase64(); + if(encoded.size()+64>7800)throw std::runtime_error("Fixed task exceeds the reviewed remote command size; a separately validated transport contract is required"); + ProcessSpec s;s.operationId=task;s.program="/usr/bin/ssh";s.remote=true;s.timeoutMs=120000;s.outputLimit=16*1024*1024; + s.arguments=QStringList{"-F","/dev/null","-T","-a","-x","-o","BatchMode=yes","-o","StrictHostKeyChecking=yes","-o","UserKnownHostsFile="+info.absoluteFilePath(),"-o","GlobalKnownHostsFile=/dev/null","-o","ClearAllForwardings=yes","-o","PermitLocalCommand=no","-o","ControlMaster=no","-o","ControlPath=none","-o","ConnectTimeout=10","-o","ServerAliveInterval=10","-o","ServerAliveCountMax=2","-p",QString::number(t.port),"-l",t.user,"--",t.host, + "powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand "+QString::fromLatin1(encoded)}; + return s; +} +} diff --git a/src/transports/NativeSshTransport.h b/src/transports/NativeSshTransport.h new file mode 100644 index 0000000..85e1833 --- /dev/null +++ b/src/transports/NativeSshTransport.h @@ -0,0 +1,6 @@ +#pragma once +#include "execution/OperationRegistry.h" +namespace ald { +struct SshTarget {QString host,user,knownHosts;quint16 port=22;}; +class NativeSshTransport {public:static ProcessSpec windowsTask(const SshTarget &target,const QString &task);}; +} diff --git a/src/ui/FlowLayout.cpp b/src/ui/FlowLayout.cpp new file mode 100644 index 0000000..76a7ad6 --- /dev/null +++ b/src/ui/FlowLayout.cpp @@ -0,0 +1,12 @@ +#include "FlowLayout.h" +namespace ald::ui { +FlowLayout::FlowLayout(QWidget *p):QLayout(p){setContentsMargins(0,0,0,0);setSpacing(8);} +FlowLayout::~FlowLayout(){while(auto *item=takeAt(0))delete item;} +void FlowLayout::addItem(QLayoutItem*i){items_.append(i);invalidate();}int FlowLayout::count()const{return items_.size();} +QLayoutItem *FlowLayout::itemAt(int i)const{return i>=0&&i=0&&iminimumSize());return s;} +QSize FlowLayout::sizeHint()const{return minimumSize();}int FlowLayout::heightForWidth(int w)const{return arrange(QRect(0,0,w,0),false);} +void FlowLayout::setGeometry(const QRect&r){QLayout::setGeometry(r);arrange(r,true);} +int FlowLayout::arrange(const QRect&r,bool apply)const{int x=r.x(),y=r.y(),height=0;for(auto *item:items_){if(item->isEmpty())continue;auto size=item->sizeHint();if(x>r.x()&&x+size.width()>r.x()+r.width()){x=r.x();y+=height+spacing();height=0;}if(apply)item->setGeometry(QRect(QPoint(x,y),size));x+=size.width()+spacing();height=qMax(height,size.height());}return y-r.y()+height;} +} diff --git a/src/ui/FlowLayout.h b/src/ui/FlowLayout.h new file mode 100644 index 0000000..6be8c77 --- /dev/null +++ b/src/ui/FlowLayout.h @@ -0,0 +1,15 @@ +#pragma once +#include +#include +namespace ald::ui { +// Keep every primary action reachable at narrow widths without truncating labels. +class FlowLayout:public QLayout { +public:explicit FlowLayout(QWidget *parent=nullptr);~FlowLayout()override; + void addItem(QLayoutItem *item)override;int count()const override; + QLayoutItem *itemAt(int index)const override;QLayoutItem *takeAt(int index)override; + QSize sizeHint()const override;QSize minimumSize()const override; + bool hasHeightForWidth()const override{return true;}int heightForWidth(int width)const override; + void setGeometry(const QRect &rect)override;Qt::Orientations expandingDirections()const override{return {};} +private:int arrange(const QRect &rect,bool apply)const;QVector items_; +}; +} diff --git a/src/ui/MainWindow.cpp b/src/ui/MainWindow.cpp new file mode 100644 index 0000000..64917de --- /dev/null +++ b/src/ui/MainWindow.cpp @@ -0,0 +1,71 @@ +#include "MainWindow.h" +#include "pages/OverviewPage.h" +#include "pages/EnvironmentPage.h" +#include "pages/AccessPage.h" +#include "pages/InitializationPage.h" +#include "pages/MigrationPage.h" +#include "pages/DomainSettingsPage.h" +#include "pages/PoliciesPage.h" +#include "pages/ChecklistPage.h" +#include "pages/LogsPage.h" +#include "pages/RestorationPage.h" +#include +#include +#include +#include +#include +#include +#include +#include +namespace ald::ui { +class NavigationList final:public QListWidget { +public: + NavigationList(){setTextElideMode(Qt::ElideNone);} +protected: + void resizeEvent(QResizeEvent *event)override { + QListWidget::resizeEvent(event); + const int textWidth=qMax(80,viewport()->width()-32); + for(int i=0;itext()); + entry->setSizeHint(QSize(0,qMax(52,bounds.height()+20))); + entry->setToolTip(entry->text().toHtmlEscaped()); + } + } +}; +MainWindow::MainWindow(AppController &a,QWidget*p):QMainWindow(p),app_(a) { + setWindowTitle("ALD Transition Console — corp.local");resize(1440,900);setMinimumSize(1024,768); + auto *workspace=new QWidget;workspace->setObjectName("workspace");setCentralWidget(workspace);auto *root=new QVBoxLayout(workspace);root->setContentsMargins(0,0,0,0);root->setSpacing(0); + auto *top=new QWidget;auto *bar=new QHBoxLayout(top);bar->setContentsMargins(16,4,16,4);top->setMinimumHeight(56);mark_=new PixelDecoration;bar->addWidget(mark_); + auto *collapse=new QToolButton;collapse->setText("☰");collapse->setAccessibleName("Показать или скрыть навигацию");bar->addWidget(collapse); + topInfo_=plainLabel("");bar->addWidget(topInfo_,1);reduced_=new QCheckBox("Без анимации");reduced_->setAccessibleName("Отключить декоративное движение");QSettings settings;reduced_->setChecked(settings.value("ui/reducedMotion",true).toBool());mark_->setReducedMotion(reduced_->isChecked());bar->addWidget(reduced_);root->addWidget(top); + auto *horizontal=new QSplitter;navigation_=new NavigationList;navigation_->setObjectName("navigation");navigation_->setAccessibleName("Разделы приложения");navigation_->setMinimumWidth(180);navigation_->setMaximumWidth(340);navigation_->setWordWrap(true); + navigation_->addItems({"01 Обзор","02 Проверка окружения","03 Подготовка доступа","04 Инициализация ALD Pro","05 Миграция","06 Настройки домена","07 Политики и харденинг","08 Проверки","09 Журнал","10 Завершение и восстановление доступа"});horizontal->addWidget(navigation_); + auto *right=new QWidget;auto *content=new QVBoxLayout(right);content->setContentsMargins(0,0,0,0);auto *banner=new QWidget;auto *bannerLayout=new QHBoxLayout(banner);auto *warning=plainLabel("⚠ Миграция заблокирована: переход corp.local и сохранение обязательного поведения не подтверждены.");warning->setObjectName("blocker");bannerLayout->addWidget(warning,1);auto *why=new QPushButton("Причины");why->setAccessibleName("Показать блокирующие требования миграции");bannerLayout->addWidget(why);content->addWidget(banner); + vertical_=new QSplitter(Qt::Vertical);pages_=new QStackedWidget;pages_->setAccessibleName("Рабочая область"); + for(QWidget *page:QVector{new OverviewPage(a),new EnvironmentPage(a),new AccessPage(a),new InitializationPage(a),new MigrationPage(a),new DomainSettingsPage(a),new PoliciesPage(a),new ChecklistPage(a),new LogsPage(a),new RestorationPage(a)})pages_->addWidget(page); + vertical_->addWidget(pages_);log_=new QPlainTextEdit;log_->setObjectName("logView");log_->setAccessibleName("Выдвижной журнал операций");log_->setReadOnly(true);log_->setMaximumBlockCount(2000);vertical_->addWidget(log_);vertical_->setSizes({600,220});log_->hide();content->addWidget(vertical_,1);horizontal->addWidget(right);horizontal->setSizes({232,1208});horizontal->setStretchFactor(1,1);root->addWidget(horizontal,1); + status_=plainLabel("");statusBar()->addWidget(status_,1);auto *logs=new QPushButton("Журнал");logs->setAccessibleName("Раскрыть или свернуть журнал");statusBar()->addPermanentWidget(logs);auto *pause=new QPushButton("Пауза");statusBar()->addPermanentWidget(pause);auto *resume=new QPushButton("Продолжить");statusBar()->addPermanentWidget(resume);auto *stop=new QPushButton("Остановить");statusBar()->addPermanentWidget(stop); + connect(collapse,&QToolButton::clicked,this,[this]{navigation_->setVisible(!navigation_->isVisible());}); + connect(navigation_,&QListWidget::currentRowChanged,pages_,&QStackedWidget::setCurrentIndex); + connect(navigation_,&QListWidget::currentRowChanged,this,[this]{if(!app_.busy()&&!closing_)mark_->pulse();});navigation_->setCurrentRow(0); + connect(why,&QPushButton::clicked,this,[this]{navigation_->setCurrentRow(4);}); + connect(logs,&QPushButton::clicked,this,[this]{log_->setVisible(!log_->isVisible());if(log_->isVisible())vertical_->setSizes({qMax(300,height()-400),220});}); + connect(reduced_,&QCheckBox::toggled,this,[this](bool value){QSettings().setValue("ui/reducedMotion",value);mark_->setReducedMotion(value||app_.busy());}); + connect(pause,&QPushButton::clicked,&a,&AppController::pause);connect(resume,&QPushButton::clicked,&a,&AppController::resume);connect(stop,&QPushButton::clicked,&a,&AppController::stop); + connect(&a,&AppController::activityChanged,this,[this,pause,resume,stop](bool busy){mark_->setReducedMotion(reduced_->isChecked()||busy);pause->setEnabled(busy&&!app_.paused());resume->setEnabled(app_.paused());stop->setEnabled(busy);refresh();});pause->setEnabled(false);resume->setEnabled(false);stop->setEnabled(false); + connect(&a,&AppController::changed,this,&MainWindow::refresh); + connect(&a,&AppController::failure,this,[this](const QString &message){mark_->setReducedMotion(true);QMessageBox box(QMessageBox::Warning,"Требуется внимание",message,QMessageBox::Ok,this);box.setTextFormat(Qt::PlainText);box.exec();mark_->setReducedMotion(reduced_->isChecked()||app_.busy());}); + connect(&a,&AppController::shutdownReady,this,&MainWindow::showCleanupSummary); + for(int i=0;i<9;++i){auto *shortcut=new QShortcut(QKeySequence(QString("Alt+%1").arg(i+1)),this);connect(shortcut,&QShortcut::activated,this,[this,i]{navigation_->setCurrentRow(i);});} + refresh(); +} +void MainWindow::refresh(){topInfo_->setText(QString("corp.local / %1\n%2 • наблюдение: %3").arg(app_.demo()?"DEMO · синтетические данные":"LIVE",app_.localFacts().value("role").toString("Роль не определена"),app_.localFacts().value("observed_at").toString("нет актуальных данных")));status_->setText(app_.busy()?"Выполняется наблюдение. Новые изменения не запускаются.":"Локальный проект • "+app_.projectDirectory());QStringList lines;for(const auto&v:app_.events()){auto o=v.toObject();lines<verticalScrollBar()->value();const bool atEnd=scroll==log_->verticalScrollBar()->maximum();log_->setPlainText(lines.join('\n'));log_->verticalScrollBar()->setValue(atEnd?log_->verticalScrollBar()->maximum():scroll);} +void MainWindow::closeEvent(QCloseEvent *e){if(acceptedClose_){e->accept();return;}e->ignore();if(closing_)return;closing_=true;mark_->setReducedMotion(true);app_.requestShutdown();} +void MainWindow::showCleanupSummary(){ + navigation_->setCurrentRow(9); + if(smokeTest_&&app_.demo()&&app_.accessChanges().isEmpty()){acceptedClose_=true;close();return;} + QMessageBox box(QMessageBox::Information,"Завершение сеанса",QString("Локальные процессы приложения остановлены. %2\n%3\n\nЗаписей доступа для ручной сверки: %1. Они останутся в проекте до проверки. Штатные доменные службы и сохранённые настройки продолжают работать.\n\nЗакрыть приложение?").arg(app_.accessChanges().size()).arg(app_.storageHealthy()?"Проект сохранён.":"Сохранение не подтверждено: проверьте состояние диска и восстановите проект из проверенной копии.").arg(app_.remoteReconciliationRequired()?"Завершение принятой удалённой команды не подтверждено после разрыва SSH; сверить процессы на целевом узле.":""),QMessageBox::Close|QMessageBox::Cancel,this);box.setTextFormat(Qt::PlainText);box.setDefaultButton(QMessageBox::Cancel); + if(box.exec()==QMessageBox::Close){acceptedClose_=true;close();}else{closing_=false;/* Application remains in review-only shutdown state; reopen to start a new run. */status_->setText("Сеанс завершён. Можно сверить журнал и инструкции; новые операции — после повторного открытия.");} +} +} diff --git a/src/ui/MainWindow.h b/src/ui/MainWindow.h new file mode 100644 index 0000000..1eb4dc3 --- /dev/null +++ b/src/ui/MainWindow.h @@ -0,0 +1,18 @@ +#pragma once +#include "app/AppController.h" +#include "PixelDecoration.h" +#include +#include +#include +#include +#include +#include +#include +namespace ald::ui { +class MainWindow:public QMainWindow { + Q_OBJECT +public:explicit MainWindow(AppController &app,QWidget *parent=nullptr);void setSmokeTest(bool enabled){smokeTest_=enabled;} +protected:void closeEvent(QCloseEvent *event)override; +private:void refresh();void showCleanupSummary();AppController &app_;QListWidget *navigation_;QStackedWidget *pages_;QLabel *topInfo_,*status_;QCheckBox *reduced_;PixelDecoration *mark_;QPlainTextEdit *log_;QSplitter *vertical_;bool acceptedClose_=false,closing_=false,smokeTest_=false; +}; +} diff --git a/src/ui/PixelDecoration.cpp b/src/ui/PixelDecoration.cpp new file mode 100644 index 0000000..bfbe401 --- /dev/null +++ b/src/ui/PixelDecoration.cpp @@ -0,0 +1,10 @@ +#include "PixelDecoration.h" +#include "Theme.h" +#include +namespace ald::ui { +PixelDecoration::PixelDecoration(QWidget *p):QWidget(p){setFixedSize(48,48);setFocusPolicy(Qt::NoFocus);setAccessibleName("Знак ALD Transition Console");animation_.setDuration(160);animation_.setStartValue(0);animation_.setEndValue(4);connect(&animation_,&QVariantAnimation::valueChanged,this,[this](const QVariant &v){step_=v.toInt();update();});} +void PixelDecoration::setReducedMotion(bool b){reduced_=b;if(b){animation_.stop();step_=4;update();}} +void PixelDecoration::pulse(){if(reduced_)return;animation_.stop();animation_.start();} +bool PixelDecoration::animating()const{return animation_.state()==QAbstractAnimation::Running;} +void PixelDecoration::paintEvent(QPaintEvent*){QPainter p(this);p.setRenderHint(QPainter::Antialiasing,false);p.setPen(Qt::NoPen);for(int i=0;i<4;++i){p.setBrush(QColor(i +#include +namespace ald::ui { +class PixelDecoration:public QWidget { + Q_OBJECT +public:explicit PixelDecoration(QWidget *parent=nullptr);void setReducedMotion(bool reduced);void pulse();bool animating()const; +protected:void paintEvent(QPaintEvent*)override; +private:QVariantAnimation animation_;int step_=4;bool reduced_=false; +}; +} diff --git a/src/ui/Theme.cpp b/src/ui/Theme.cpp new file mode 100644 index 0000000..2b0cc0e --- /dev/null +++ b/src/ui/Theme.cpp @@ -0,0 +1,14 @@ +#include "Theme.h" +#include +#include +#include +#include +#include +#include +namespace ald::ui { +void Theme::apply(QApplication &app){QFont f("DejaVu Sans");f.setPointSizeF(qMax(10.5,app.font().pointSizeF()));app.setFont(f);QPalette p;p.setColor(QPalette::Window,QColor(background));p.setColor(QPalette::WindowText,QColor(text));p.setColor(QPalette::Base,QColor(panel));p.setColor(QPalette::Text,QColor(text));p.setColor(QPalette::Button,QColor(elevated));p.setColor(QPalette::ButtonText,QColor(text));p.setColor(QPalette::Highlight,QColor(accent));p.setColor(QPalette::HighlightedText,QColor(background));p.setColor(QPalette::Disabled,QPalette::Text,QColor(secondary));app.setPalette(p); + QFile file(":/styles/dedsec.qss");file.open(QIODevice::ReadOnly);QString qss=QString::fromUtf8(file.readAll()); + for(const auto &pair:QVector>{{"BG",background},{"PANEL",panel},{"RAISED",elevated},{"TEXT",text},{"MUTED",secondary},{"BORDER",border},{"ACCENT",accent},{"ERROR",error},{"WARNING",warning},{"INFO",info}})qss.replace("@"+pair.first+"@",pair.second); + app.setStyleSheet(qss); +} +} diff --git a/src/ui/Theme.h b/src/ui/Theme.h new file mode 100644 index 0000000..49619b4 --- /dev/null +++ b/src/ui/Theme.h @@ -0,0 +1,7 @@ +#pragma once +#include +#include +class QApplication; +namespace ald::ui { +struct Theme {static constexpr const char *background="#0A0A0A",*panel="#141617",*elevated="#1C1F20",*text="#F2F2EE",*secondary="#B9B9B9",*border="#454A4C",*accent="#B0E010",*error="#FF5C6C",*warning="#F4C95D",*info="#70CFE8";static void apply(QApplication &app);}; +} diff --git a/src/ui/models/JsonTableModel.cpp b/src/ui/models/JsonTableModel.cpp new file mode 100644 index 0000000..6194bae --- /dev/null +++ b/src/ui/models/JsonTableModel.cpp @@ -0,0 +1,41 @@ +#include "JsonTableModel.h" +#include +#include +#include +namespace ald::ui { +JsonTableModel::JsonTableModel(QStringList k,QStringList h,QObject *p):QAbstractTableModel(p),keys_(std::move(k)),headers_(std::move(h)){} +int JsonTableModel::rowCount(const QModelIndex &p)const{return p.isValid()?0:rows_.size();}int JsonTableModel::columnCount(const QModelIndex&p)const{return p.isValid()?0:keys_.size();} +QVariant JsonTableModel::data(const QModelIndex &i,int role)const { + if(!i.isValid()||i.row()<0||i.column()<0||i.row()>=rows_.size()||i.column()>=keys_.size())return {}; + if(role!=Qt::DisplayRole&&role!=Qt::ToolTipRole&&role!=Qt::AccessibleTextRole)return {}; + const auto value=rows_[i.row()].toObject().value(keys_[i.column()]);QString text; + if(value.isString())text=value.toString(); + else if(value.isNull()||value.isUndefined())text="Не проверено"; + else if(value.isArray())text=QString::fromUtf8(QJsonDocument(value.toArray()).toJson(QJsonDocument::Compact)); + else if(value.isObject())text=QString::fromUtf8(QJsonDocument(value.toObject()).toJson(QJsonDocument::Compact)); + else text=value.toVariant().toString(); + const QStringList statusFields={"state","result","disposition","mapping_state","verification_state","method","decision","applicability"}; + if(statusFields.contains(keys_[i.column()])){ + static const QHash labels={ + {"PASS","✓ Подтверждено"},{"FAIL","× Не выполнено"},{"PARTIAL","◐ Частично"}, + {"ERROR","× Ошибка"},{"NOT_CHECKED","○ Не проверено"},{"STALE","◷ Устарело"}, + {"UNKNOWN","? Не подтверждено"},{"UNSUPPORTED","× Не поддерживается"}, + {"VERIFIED","✓ Проверено"},{"DOCUMENTED_NOT_TESTED","○ Описано, не испытано"}, + {"BLOCKED","⏸ Заблокировано"},{"OBSERVED","● Значение получено"}, + {"GUIDED_NATIVE","Штатная процедура с инструкцией"},{"MANUAL_RECONFIGURATION","Ручная перенастройка"}, + {"AUTOMATED_NATIVE","Штатная автоматизация"},{"HUMAN","Оператор"},{"AUTOMATIC","Автоматическое наблюдение"}, + {"APPLICABLE","Применимо"},{"NOT_APPLICABLE_WITH_REASON","Не применимо: см. причину"},{"CONFLICT","× Конфликт"},{"PENDING","○ Ожидает проверки"},{"PRESERVED","Сохранено без изменения"}}; + text=labels.value(text,text); + } + if(keys_[i.column()]=="phase"){ + static const QHash phases={{"source","Исходный AD"},{"initialization","Инициализация"},{"migration","Миграция"},{"policies","Политики"},{"hardening","Харденинг"},{"cleanup","Завершение"},{"validation","Приёмка"}}; + text=phases.value(text,text); + } + // QToolTip interprets rich text: never pass imported names/attributes as markup. + if(role==Qt::ToolTipRole)return "
"+text.toHtmlEscaped()+"
"; + return text; +} +QVariant JsonTableModel::headerData(int section,Qt::Orientation orientation,int role)const{if(role==Qt::DisplayRole&&orientation==Qt::Horizontal)return headers_.value(section);return {};} +void JsonTableModel::setRows(const QJsonArray &rows){if(rows_==rows)return;beginResetModel();rows_=rows;endResetModel();} +QJsonObject JsonTableModel::row(int i)const{return i>=0&&i +#include +#include +namespace ald::ui { +class JsonTableModel:public QAbstractTableModel { + Q_OBJECT +public:JsonTableModel(QStringList keys,QStringList headers,QObject *parent=nullptr); + int rowCount(const QModelIndex &parent={})const override;int columnCount(const QModelIndex &parent={})const override; + QVariant data(const QModelIndex &index,int role=Qt::DisplayRole)const override;QVariant headerData(int section,Qt::Orientation orientation,int role)const override; + void setRows(const QJsonArray &rows);QJsonObject row(int i)const;QStringList keys()const{return keys_;} +private:QStringList keys_,headers_;QJsonArray rows_; +}; +} diff --git a/src/ui/pages/AccessPage.cpp b/src/ui/pages/AccessPage.cpp new file mode 100644 index 0000000..9a33ee2 --- /dev/null +++ b/src/ui/pages/AccessPage.cpp @@ -0,0 +1,30 @@ +#include "AccessPage.h" +#include "workflows/AccessPreparation.h" +#include +#include +#include +#include +#include +namespace ald::ui { +AccessPage::AccessPage(AppController&a,QWidget*p):WorkflowPage(a,"Подготовка доступа","Подключение только к указанному узлу. Подлинность ключа проверяется до подключения.",p){ + auto *host=new QLineEdit,*user=new QLineEdit,*known=new QLineEdit;auto *port=new QSpinBox;port->setRange(1,65535);port->setButtonSymbols(QAbstractSpinBox::NoButtons);port->setValue(22);port->setAccessibleName("Порт SSH"); + host->setPlaceholderText("FQDN выбранного Windows-узла");user->setPlaceholderText("Разрешённая административная учётная запись"); + host->setAccessibleName("Целевой узел SSH");user->setAccessibleName("Пользователь SSH");known->setAccessibleName("Проверенный файл known_hosts"); + auto *form=new QFormLayout;form->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);form->addRow("&Узел",host);form->addRow("&Пользователь",user);form->addRow("П&орт",port);form->addRow("Ключи &хостов",known);body_->addLayout(form); + auto *browse=new QPushButton("Выбрать known_hosts…");browse->setAccessibleName(browse->text());form->addRow("",browse);connect(browse,&QPushButton::clicked,this,[this,known]{auto path=QFileDialog::getOpenFileName(this,"Файл с независимо проверенным ключом хоста");if(!path.isEmpty())known->setText(path);}); + auto target=[host,user,known,port]{return SshTarget{host->text().trimmed(),user->text(),known->text(),quint16(port->value())};}; + auto *test=button("Проверить Windows",[this,target]{app_.runWindows(target(),"windows.discovery",policy());},true); + auto *inventory=button("Обследовать каталог AD",[this,target]{app_.runWindows(target(),"ad.inventory",policy());}); + errorPolicyControl(); + auto *observed=section("Последнее наблюдение Windows","Узел ещё не обследован. Результат подключения не подтверждает поддержку входа Windows в ALD."); + auto *native=details("Наблюдение Windows: полная выдача и optional features"); + auto showObservation=[this,observed,native]{const auto o=app_.windowsFacts();if(o.isEmpty())return; + observed->setText(QString("Узел: %1\nОС: %2, build %3; PowerShell %4\nВремя: %5\nИнтеграция с доменом ALD 3.1.0: не подтверждена.\nЭто сохранённое наблюдение; для обновления запустите проверку выбранного узла.") + .arg(o.value("target_id").toString(),o.value("os_edition").toString(),o.value("os_build").toString(),o.value("powershell_version").toString(),o.value("observed_at").toString())); + native->setPlainText(QString::fromUtf8(QJsonDocument(o).toJson()));}; + connect(&a,&AppController::changed,this,showObservation);showObservation(); + section("Область чтения","Windows: edition/build/роль, PowerShell, optional features. AD: объекты каталога выбранного КД, максимум 50 000. Содержимое файлов, пароли, PKI, DHCP и эффективные GPO этим сбором не покрываются. Нужен уже разблокированный штатный ssh-agent. Пароли в приложение не вводятся."); + for(const auto &v:AccessPreparation::instructions(true)){const auto o=v.toObject();section(o.value("phase").toString(),o.value("steps_ru").toString());} + section("Linux: отдельный путь",AccessPreparation::instructions(false)[0].toObject().value("steps_ru").toString()+"\n"+AccessPreparation::instructions(false)[2].toObject().value("steps_ru").toString()); + auto update=[this,test,inventory]{test->setEnabled(!app_.demo()&&!app_.busy());inventory->setEnabled(!app_.demo()&&!app_.busy());};connect(&a,&AppController::activityChanged,this,[update](bool){update();});update(); +}} diff --git a/src/ui/pages/AccessPage.h b/src/ui/pages/AccessPage.h new file mode 100644 index 0000000..259b75f --- /dev/null +++ b/src/ui/pages/AccessPage.h @@ -0,0 +1,6 @@ +#pragma once +#include "WorkflowPage.h" +namespace ald::ui {class AccessPage:public WorkflowPage { + Q_OBJECT +public:explicit AccessPage(AppController &app,QWidget *parent=nullptr); +};} diff --git a/src/ui/pages/ChecklistPage.cpp b/src/ui/pages/ChecklistPage.cpp new file mode 100644 index 0000000..9c5afc7 --- /dev/null +++ b/src/ui/pages/ChecklistPage.cpp @@ -0,0 +1,32 @@ +#include "ChecklistPage.h" +#include +#include +#include +namespace ald::ui { +ChecklistPage::ChecklistPage(AppController&a,QWidget*p):WorkflowPage(a,"Проверки","Отметки оператора и автоматические доказательства — разные записи. История сохраняется.",p){ + button("Экспорт HTML…",[this]{auto path=QFileDialog::getSaveFileName(this,"Сохранить инструкционный чеклист",{},"HTML (*.html)");if(!path.isEmpty())app_.exportChecklist(path,true);},true); + button("Экспорт JSON…",[this]{auto path=QFileDialog::getSaveFileName(this,"Сохранить историю проверок",{},"JSON (*.json)");if(!path.isEmpty())app_.exportChecklist(path,false);}); + auto *model=new JsonTableModel({"phase","title_ru"},{"Этап","Ручная проверка"},this);auto *view=table(model,"Инструкционный чеклист");model->setRows(a.checklistItems()); + auto *instructions=section("Инструкция","Выберите проверку для подробных шагов, ожидаемого результата и восстановления."); + auto *host=new QLineEdit,*operator_=new QLineEdit;auto *note=new QPlainTextEdit;host->setAccessibleName("Проверенный узел, пользователь или сервис");operator_->setAccessibleName("Оператор проверки");note->setAccessibleName("Примечание и ссылка на доказательство без секретов");note->setMaximumHeight(100); + auto *result=new QComboBox;result->setAccessibleName("Результат ручной проверки");result->addItems({"Не проверено","PASS — подтверждено вручную","FAIL — не соответствует","Не применимо с обоснованием"}); + auto *form=new QFormLayout;form->addRow("&Узел / область",host);form->addRow("&Проверил",operator_);form->addRow("&Результат",result);form->addRow("&Примечание",note);body_->addLayout(form); + auto *save=new QPushButton("Сохранить ручную отметку");save->setAccessibleName(save->text());save->setProperty("role","primary");body_->addWidget(save); + section("История результатов","Отметки оператора и автоматические наблюдения показаны раздельными строками. Устаревшая запись сохраняет исходный результат, но не подтверждает текущую редакцию."); + auto *historyModel=new JsonTableModel({"method","result","applicability","host_id","checked_by","checked_at"},{"Кто проверял","Результат","Применимость","Область","Проверил","Время UTC"},this); + auto *history=table(historyModel,"Ручные отметки и автоматические наблюдения"); + auto *recordDetails=details("Примечание и полная запись выбранного результата"); + connect(history->selectionModel(),&QItemSelectionModel::currentRowChanged,this,[historyModel,recordDetails](const QModelIndex &i){recordDetails->setPlainText(QString::fromUtf8(QJsonDocument(historyModel->row(i.row())).toJson()));}); + auto select=[model,view,instructions,history,historyModel,this]{ + auto o=model->row(view->currentIndex().row());QStringList lines,prerequisites,scope; + for(const auto&v:o.value("steps_ru").toArray())lines<setText(o.value("purpose_ru").toString()+"\n\nОбласть: "+scope.join(", ")+"\n\nПредусловия: "+prerequisites.join("; ")+"\n\n"+lines.join("\n\n")+"\n\nОжидается: "+o.value("expected_result_ru").toString()+"\n\nПри отказе: "+o.value("failure_guidance_ru").toString()); + QJsonArray observations;for(const auto&v:app_.observations())if(v.toObject().value("item_id")==o.value("id"))observations.append(v); + rows(history,historyModel,observations); + }; + connect(view->selectionModel(),&QItemSelectionModel::currentRowChanged,this,[select,result,note](const QModelIndex&){result->setCurrentIndex(0);note->clear();select();}); + connect(save,&QPushButton::clicked,this,[this,model,view,host,operator_,result,note]{protect([&]{auto item=model->row(view->currentIndex().row());if(item.isEmpty())throw std::runtime_error("Выберите пункт чеклиста");app_.recordHuman({{"item_id",item.value("id")},{"host_id",host->text().trimmed()},{"checked_by",operator_->text().trimmed()},{"result",result->currentIndex()==1?"PASS":result->currentIndex()==2?"FAIL":"NOT_CHECKED"},{"applicability",result->currentIndex()==3?"NOT_APPLICABLE_WITH_REASON":"APPLICABLE"},{"note",note->toPlainText()}});});}); + connect(&a,&AppController::changed,this,select);connect(&a,&AppController::activityChanged,this,[save](bool b){save->setEnabled(!b);}); +}} diff --git a/src/ui/pages/ChecklistPage.h b/src/ui/pages/ChecklistPage.h new file mode 100644 index 0000000..05b1fb4 --- /dev/null +++ b/src/ui/pages/ChecklistPage.h @@ -0,0 +1,6 @@ +#pragma once +#include "WorkflowPage.h" +namespace ald::ui {class ChecklistPage:public WorkflowPage { + Q_OBJECT +public:explicit ChecklistPage(AppController &app,QWidget *parent=nullptr); +};} diff --git a/src/ui/pages/DomainSettingsPage.cpp b/src/ui/pages/DomainSettingsPage.cpp new file mode 100644 index 0000000..d54d58f --- /dev/null +++ b/src/ui/pages/DomainSettingsPage.cpp @@ -0,0 +1,7 @@ +#include "DomainSettingsPage.h" +#include "adapters/Ald31Administration.h" +namespace ald::ui { +DomainSettingsPage::DomainSettingsPage(AppController&a,QWidget*p):WorkflowPage(a,"Настройки домена","Ручные поддержанные пути управления; автоматическая запись API ещё не реализована.",p){ + section("Текущее состояние","Значения доменных настроек ещё не обследованы. Работа локального GUI не подтверждает здоровье каталога. Не изменяйте идентичность уже созданного контроллера через переименование hostname."); + for(const auto &v:Ald31Administration::workflows()){auto o=v.toObject();section(o.value("title_ru").toString(),o.value("changes_ru").toString()+"\n\nПроверка: "+o.value("verification_ru").toString());} +}} diff --git a/src/ui/pages/DomainSettingsPage.h b/src/ui/pages/DomainSettingsPage.h new file mode 100644 index 0000000..306fadf --- /dev/null +++ b/src/ui/pages/DomainSettingsPage.h @@ -0,0 +1,6 @@ +#pragma once +#include "WorkflowPage.h" +namespace ald::ui {class DomainSettingsPage:public WorkflowPage { + Q_OBJECT +public:explicit DomainSettingsPage(AppController &app,QWidget *parent=nullptr); +};} diff --git a/src/ui/pages/EnvironmentPage.cpp b/src/ui/pages/EnvironmentPage.cpp new file mode 100644 index 0000000..26f404f --- /dev/null +++ b/src/ui/pages/EnvironmentPage.cpp @@ -0,0 +1,14 @@ +#include "EnvironmentPage.h" +#include +namespace ald::ui { +EnvironmentPage::EnvironmentPage(AppController&a,QWidget*p):WorkflowPage(a,"Проверка окружения","Наблюдения локального узла. Проверка ничего не устанавливает и не перезапускает.",p){ + auto *refresh=button("Обновить наблюдения",[this]{app_.refreshLocal(policy());},true);refresh->setEnabled(!a.demo());errorPolicyControl(); + auto *stop=button("Остановить",[this]{app_.stop();}); + auto *model=new JsonTableModel({"check","observed","result","observed_at"},{"Проверка","Фактическое значение","Результат","Время UTC"},this); + auto *view=table(model,"Результаты проверки окружения"); + section("Ожидаемая платформа","Первый стенд: ALD Pro 3.1.0, ALSE 1.7.7 UU2, 6.1-generic, Смоленск. Совместимость GUI и поддержка контроллера — отдельные проверки. Недоступная команда не доказывает отсутствие роли."); + auto *instructions=section("Что проверить вручную","Выберите строку для объяснения и следующего действия."); + auto *native=details("Нативная диагностика выбранной проверки"); + connect(view->selectionModel(),&QItemSelectionModel::currentRowChanged,this,[model,native,instructions](const QModelIndex&i){auto o=model->row(i.row());instructions->setText(o.value("why_ru").toString()+"\n\n"+o.value("next_ru").toString());native->setPlainText(QString::fromUtf8(QJsonDocument(o).toJson()));}); + auto update=[this,model,view,refresh,stop]{rows(view,model,app_.findings());refresh->setEnabled(!app_.demo()&&!app_.busy());stop->setEnabled(app_.busy());};connect(&a,&AppController::changed,this,update);connect(&a,&AppController::activityChanged,this,[update](bool){update();});update(); +}} diff --git a/src/ui/pages/EnvironmentPage.h b/src/ui/pages/EnvironmentPage.h new file mode 100644 index 0000000..99a95a5 --- /dev/null +++ b/src/ui/pages/EnvironmentPage.h @@ -0,0 +1,6 @@ +#pragma once +#include "WorkflowPage.h" +namespace ald::ui {class EnvironmentPage:public WorkflowPage { + Q_OBJECT +public:explicit EnvironmentPage(AppController &app,QWidget *parent=nullptr); +};} diff --git a/src/ui/pages/InitializationPage.cpp b/src/ui/pages/InitializationPage.cpp new file mode 100644 index 0000000..44c41be --- /dev/null +++ b/src/ui/pages/InitializationPage.cpp @@ -0,0 +1,11 @@ +#include "InitializationPage.h" +#include +namespace ald::ui { +InitializationPage::InitializationPage(AppController&a,QWidget*p):WorkflowPage(a,"Инициализация ALD Pro","Подготовка первого контроллера по документации поставки 3.1.0",p){ + auto *facts=section("Текущие факты","");auto *blockers=section("До изменения",""); + section("Подготовить паспорт установки","Зафиксируйте текущие и желаемые hostname/FQDN, IP/prefix, gateway, DNS/resolver и источник времени. Затем — approved media/repositories, ресурсы, свободное место, уровень защиты, отсутствие package-manager locks, необходимость перезагрузки и проверенное восстановление. Сейчас мастер не применяет эти значения."); + section("Поддержанный ручной шаг","После подтверждения всех допусков откройте локальную консоль и выполните штатную интерактивную процедуру из ALD31_PROMOTION. Пароль вводится в установщике. Существующий или частично установленный контроллер нельзя автоматически переинициализировать."); + auto *contract=details("Документированный шаблон и условия инициализации"); + section("Проверка и восстановление","После согласованной перезагрузки проверить aldproctl status, DNS/time, портал и пилотную регистрацию. Частичный отказ сохраняется как пробел; повторное продвижение не запускается. Для corp.local сначала нужен подтверждённый план DNS authority в существующей сети."); + auto update=[this,facts,blockers,contract]{auto plan=app_.initializationPlan();facts->setText("Роль: "+app_.localFacts().value("role").toString("Не проверена")+"\nЦель: corp.local\nСтатус: ЗАБЛОКИРОВАНО");QStringList lines;for(const auto &v:plan.value("blockers").toArray())lines<setText(lines.join("\n\n"));contract->setPlainText(QString::fromUtf8(QJsonDocument(plan).toJson()));};connect(&a,&AppController::changed,this,update);update(); +}} diff --git a/src/ui/pages/InitializationPage.h b/src/ui/pages/InitializationPage.h new file mode 100644 index 0000000..0efb15b --- /dev/null +++ b/src/ui/pages/InitializationPage.h @@ -0,0 +1,6 @@ +#pragma once +#include "WorkflowPage.h" +namespace ald::ui {class InitializationPage:public WorkflowPage { + Q_OBJECT +public:explicit InitializationPage(AppController &app,QWidget *parent=nullptr); +};} diff --git a/src/ui/pages/LogsPage.cpp b/src/ui/pages/LogsPage.cpp new file mode 100644 index 0000000..f465a7b --- /dev/null +++ b/src/ui/pages/LogsPage.cpp @@ -0,0 +1,8 @@ +#include "LogsPage.h" +#include +namespace ald::ui { +LogsPage::LogsPage(AppController&a,QWidget*p):WorkflowPage(a,"Журнал","Упорядоченные события. Нативные сведения содержат только разрешённые данные.",p){ + auto *filter=new QLineEdit;filter->setAccessibleName("Фильтр по узлу, операции, серьёзности, времени или запуску");filter->setPlaceholderText("Поиск: узел, операция, уровень, время, запуск");actions_->addWidget(filter); + auto *log=details("Журнал событий",true);log->setObjectName("logView");log->setMinimumHeight(420); + auto update=[this,log,filter]{QStringList lines;for(const auto&v:app_.events()){auto o=v.toObject();QString line=QString("%1 [%2] %3 / %4 / %5\n%6\n%7").arg(o.value("timestamp_utc").toString(),o.value("severity").toString(),o.value("run_id").toString(),o.value("host_id").toString(),o.value("operation_id").toString(),o.value("message_ru").toString(),o.value("redacted_detail").toString());if(filter->text().isEmpty()||line.contains(filter->text(),Qt::CaseInsensitive))lines<textCursor();int pos=cursor.position();log->setPlainText(lines.join("\n\n"));cursor.setPosition(qMin(pos,log->document()->characterCount()-1));log->setTextCursor(cursor);};connect(filter,&QLineEdit::textChanged,this,[update]{update();});connect(&a,&AppController::changed,this,update);update(); +}} diff --git a/src/ui/pages/LogsPage.h b/src/ui/pages/LogsPage.h new file mode 100644 index 0000000..020eb52 --- /dev/null +++ b/src/ui/pages/LogsPage.h @@ -0,0 +1,6 @@ +#pragma once +#include "WorkflowPage.h" +namespace ald::ui {class LogsPage:public WorkflowPage { + Q_OBJECT +public:explicit LogsPage(AppController &app,QWidget *parent=nullptr); +};} diff --git a/src/ui/pages/MigrationPage.cpp b/src/ui/pages/MigrationPage.cpp new file mode 100644 index 0000000..07c2d6e --- /dev/null +++ b/src/ui/pages/MigrationPage.cpp @@ -0,0 +1,15 @@ +#include "MigrationPage.h" +#include +#include +namespace ald::ui { +MigrationPage::MigrationPage(AppController&a,QWidget*p):WorkflowPage(a,"Миграция corp.local","Полная замена AD: каждая зависимость и каждый требуемый результат остаются видимыми.",p){ + auto *import=button("Импортировать инвентаризацию…",[this]{auto path=QFileDialog::getOpenFileName(this,"UTF-8 JSON-инвентаризация",{},"JSON (*.json)");if(!path.isEmpty())app_.importInventory(path);},true); + button("Пересчитать план",[this]{app_.rebuildPlan();}); + auto *scope=section("Область обследования",""); + auto *requirements=new JsonTableModel({"id","state","reason_ru"},{"Обязательное требование","Поддержка","Что мешает переходу"},this);auto *rview=table(requirements,"Обязательные требования миграции"); + auto *objects=new JsonTableModel({"category","source_ref","disposition","blockers"},{"Категория","Источник","Путь","Нерешённые зависимости"},this);auto *oview=table(objects,"Инвентаризация и пути миграции"); + auto *detail=details("Подробности объекта миграции");connect(oview->selectionModel(),&QItemSelectionModel::currentRowChanged,this,[objects,detail](const QModelIndex&i){detail->setPlainText(QString::fromUtf8(QJsonDocument(objects->row(i.row())).toJson()));}); + auto *phases=section("Порядок и окно переключения",""); + section("Восстановление","Единственный исходный КД требует AD-aware backup и репетиции восстановления. Продолжительность окна и точка невозврата пока неизвестны. Ручной чеклист не снимает неподтверждённые обязательные требования. Вывод AD не доступен до доказанной независимости."); + auto update=[this,scope,requirements,rview,objects,oview,phases,import]{auto plan=app_.migrationPlan();rows(rview,requirements,plan.value("requirements").toArray());rows(oview,objects,plan.value("items").toArray());auto s=app_.inventory().value("scope").toObject();QStringList gaps;for(const auto&v:s.value("denied_or_unreachable").toArray())gaps<setText((app_.demo()?"СИНТЕТИЧЕСКИЕ ДАННЫЕ\n":"")+s.value("description").toString("Инвентаризация ещё не получена")+"\n\nНеполный охват:\n"+gaps.join("\n"));QStringList steps;for(const auto&v:plan.value("graph").toArray()){auto o=v.toObject();steps<setText(steps.join("\n"));import->setEnabled(!app_.busy());};connect(&a,&AppController::changed,this,update);connect(&a,&AppController::activityChanged,this,[update](bool){update();});update(); +}} diff --git a/src/ui/pages/MigrationPage.h b/src/ui/pages/MigrationPage.h new file mode 100644 index 0000000..efb1cfa --- /dev/null +++ b/src/ui/pages/MigrationPage.h @@ -0,0 +1,6 @@ +#pragma once +#include "WorkflowPage.h" +namespace ald::ui {class MigrationPage:public WorkflowPage { + Q_OBJECT +public:explicit MigrationPage(AppController &app,QWidget *parent=nullptr); +};} diff --git a/src/ui/pages/OverviewPage.cpp b/src/ui/pages/OverviewPage.cpp new file mode 100644 index 0000000..534e2ea --- /dev/null +++ b/src/ui/pages/OverviewPage.cpp @@ -0,0 +1,13 @@ +#include "OverviewPage.h" +namespace ald::ui { +OverviewPage::OverviewPage(AppController&a,QWidget*p):WorkflowPage(a,"Переход под контролем","Обследование → проверенный план → подтверждённые результаты",p){ + auto *facts=section("Текущее состояние",""); + auto *scope=section("Обязательная цель","corp.local • прежняя IP-сеть • один исходный AD DC\nПрежние логины, пароли, профили, данные, права, приложения и результаты политик проверяются отдельно."); + Q_UNUSED(scope); + section("Следующее действие","Откройте «Проверка окружения». Для источника AD подготовьте существующий разрешённый доступ или импортируйте JSON-инвентаризацию. Затем откройте «Миграция» и проверьте каждую зависимость."); + auto *cleanup=section("Восстановление и завершение",""); + section("Что работает без интернета","Сохранённые данные, планирование, инструкции и чеклист доступны локально. Доступ к заданным узлам требует сети. Недостающие пакеты, optional features и новые материалы требуют одобренного репозитория или носителя."); + section("После закрытия","Новые проверки и изменения не выполняются. Штатные доменные службы и уже сохранённые клиентские настройки продолжают работать. Автоматического продолжения после перезагрузки нет."); + auto update=[this,facts,cleanup]{const auto inventory=app_.inventory();facts->setText(QString("Режим: %1\nРоль локального узла: %2\nОбъектов в сохранённой инвентаризации: %3\nПолная миграция: ЗАБЛОКИРОВАНА — обязательные пути не подтверждены").arg(app_.demo()?"DEMO — синтетические примеры":"LIVE — реальные наблюдения").arg(app_.localFacts().value("role").toString("Не проверена")).arg(inventory.value("objects").toArray().size()));cleanup->setText(QString("Записей временного доступа: %1\nПрерванных запусков: %2\nПеред выходом проверьте обязательства восстановления. Не повторяйте прерванное изменение автоматически.").arg(app_.accessChanges().size()).arg(app_.interruptedRuns().size()));}; + connect(&a,&AppController::changed,this,update);update(); +}} diff --git a/src/ui/pages/OverviewPage.h b/src/ui/pages/OverviewPage.h new file mode 100644 index 0000000..c161091 --- /dev/null +++ b/src/ui/pages/OverviewPage.h @@ -0,0 +1,6 @@ +#pragma once +#include "WorkflowPage.h" +namespace ald::ui {class OverviewPage:public WorkflowPage { + Q_OBJECT +public:explicit OverviewPage(AppController &app,QWidget *parent=nullptr); +};} diff --git a/src/ui/pages/PoliciesPage.cpp b/src/ui/pages/PoliciesPage.cpp new file mode 100644 index 0000000..2802b30 --- /dev/null +++ b/src/ui/pages/PoliciesPage.cpp @@ -0,0 +1,20 @@ +#include "PoliciesPage.h" +#include "workflows/HardeningPlanner.h" +#include +#include +namespace ald::ui { +PoliciesPage::PoliciesPage(AppController&a,QWidget*p):WorkflowPage(a,"Политики и харденинг","Один владелец настройки. Результаты применения и наблюдения хранятся отдельно.",p){ + button("Импортировать профиль…",[this]{auto file=QFileDialog::getOpenFileName(this,"Проверенный профиль JSON",{},"JSON (*.json)");if(!file.isEmpty())app_.importProfile(file);}); + auto *audit=button("Прочитать SSH с авторизацией",[this]{app_.auditPrivilegedSsh();});audit->setEnabled(!a.demo()); + button("Проверить offline-набор…",[this]{auto file=QFileDialog::getOpenFileName(this,"Offline JSON data bundle",{},"JSON (*.json)");if(!file.isEmpty())app_.importBundle(file);}); + section("Прежде чем менять","Харденинг следует за проверкой миграции. Параметры Astra и Windows не взаимозаменяемы. Для ALD Controller, Linux-сервера, рабочей и административной станции нужны отдельные карты. Linux-документ ФСТЭК не является Windows baseline."); + auto *model=new JsonTableModel({"paragraph","title_ru","mapping_state","recovery_class"},{"Пункт","Предмет проверки","Карта Astra","Восстановление"},this);auto *view=table(model,"40 рекомендаций Linux");model->setRows(a.hardeningCards()); + auto *explanation=section("Карточка рекомендации","Выберите строку. Оригинал ФСТЭК ещё не сверён; 40 карточек не означают 40 поддержанных исправлений."); + auto *details_=details("Применимость, наблюдения и восстановление рекомендации"); + connect(view->selectionModel(),&QItemSelectionModel::currentRowChanged,this,[this,model,details_,explanation](const QModelIndex&i){auto card=model->row(i.row());explanation->setText(card.value("explanation_ru").toString()+"\n\nПроверка: "+card.value("manual_check_ru").toString()+"\n\nВосстановление: "+card.value("reversibility_ru").toString());auto data=card;data["prepared_plan"]=HardeningPlanner::prepare(card,false);details_->setPlainText(QString::fromUtf8(QJsonDocument(data).toJson()));}); + auto *policy=details("План сравнения импортированного профиля");auto update=[this,policy,audit]{policy->setPlainText(app_.policyPlan().isEmpty()?"Профиль не загружен. После импорта будут видны ожидаемые изменения и конфликты владельцев.":QString::fromUtf8(QJsonDocument(app_.policyPlan()).toJson()));audit->setEnabled(!app_.demo()&&!app_.busy());};connect(&a,&AppController::changed,this,update);connect(&a,&AppController::activityChanged,this,[update](bool){update();});update(); + auto *bundle=details("Последний offline-набор, ожидающий отдельной проверки происхождения"); + auto reviewBundle=[this,bundle]{bundle->setPlainText(app_.stagedBundle().isEmpty()?"Offline-набор не импортирован. Разрешены только данные JSON. Исполняемые пакеты не принимаются.":QString::fromUtf8(QJsonDocument(app_.stagedBundle()).toJson()));}; + connect(&a,&AppController::changed,this,reviewBundle);reviewBundle(); + section("Проверка результата и восстановление","Назначена → получена → вошла в результирующую конфигурацию → применена → эффективное значение проверено → поведение проверено. Снятие назначения не отменяет сохранённое значение. Для ptrace_scope=3 немедленная обратная запись невозможна в текущем сеансе ядра."); +}} diff --git a/src/ui/pages/PoliciesPage.h b/src/ui/pages/PoliciesPage.h new file mode 100644 index 0000000..824b110 --- /dev/null +++ b/src/ui/pages/PoliciesPage.h @@ -0,0 +1,6 @@ +#pragma once +#include "WorkflowPage.h" +namespace ald::ui {class PoliciesPage:public WorkflowPage { + Q_OBJECT +public:explicit PoliciesPage(AppController &app,QWidget *parent=nullptr); +};} diff --git a/src/ui/pages/RestorationPage.cpp b/src/ui/pages/RestorationPage.cpp new file mode 100644 index 0000000..d76bd48 --- /dev/null +++ b/src/ui/pages/RestorationPage.cpp @@ -0,0 +1,14 @@ +#include "RestorationPage.h" +#include "workflows/AccessRestoration.h" +#include +#include +#include +namespace ald::ui { +RestorationPage::RestorationPage(AppController&a,QWidget*p):WorkflowPage(a,"Завершение и восстановление доступа","Сначала собственные временные права и правила; последний канал закрывается в конце.",p){ + section("Границы восстановления","Приложение сейчас не создаёт удалённый доступ автоматически. Записывайте здесь выполненные вручную изменения, их исходное и внесённое состояние и точные шаги возврата. Эта запись не подтверждает факт изменения или очистки. Существующий SSH/WinRM сохраняется."); + auto *model=new JsonTableModel({"target_id","resource_id","verification_state"},{"Узел","Ресурс","Проверка"},this);auto *view=table(model,"Журнал обязательств восстановления");auto *details_=details("Исходное состояние и инструкция восстановления");connect(view->selectionModel(),&QItemSelectionModel::currentRowChanged,this,[model,details_](const QModelIndex&i){details_->setPlainText(QString::fromUtf8(QJsonDocument(model->row(i.row())).toJson()));}); + auto *target=new QLineEdit,*resource=new QLineEdit,*before=new QLineEdit,*after=new QLineEdit;auto *steps=new QPlainTextEdit;steps->setMaximumHeight(100);auto *type=new QComboBox;type->addItems({"FIREWALL_RULE","KEY_ENTRY","ROLE_MEMBERSHIP","SERVICE","LAST_ACCESS_CHANNEL"}); + auto *form=new QFormLayout;for(const auto &pair:QVector>{{"Узел",target},{"Ресурс / точный ID",resource},{"До изменения",before},{"После изменения",after}}){pair.second->setAccessibleName(pair.first);form->addRow(pair.first,pair.second);}type->setAccessibleName("Тип ресурса доступа");steps->setAccessibleName("Шаги восстановления без паролей и закрытых ключей");form->addRow("Тип ресурса",type);form->addRow("Шаги возврата",steps);body_->addLayout(form); + auto *save=new QPushButton("Записать ручное изменение");save->setAccessibleName(save->text());body_->addWidget(save);connect(save,&QPushButton::clicked,this,[this,target,resource,before,after,type,steps]{protect([&]{if(target->text().trimmed().isEmpty()||resource->text().trimmed().isEmpty()||before->text().isEmpty()||after->text().isEmpty()||steps->toPlainText().trimmed().isEmpty())throw std::runtime_error("Заполните узел, ID ресурса, оба состояния и шаги возврата без секретов");app_.recordAccessChange({{"target_id",target->text()},{"resource_type",type->currentText()},{"resource_id",resource->text()},{"previous_state",QJsonObject{{"operator_description",before->text()}}},{"applied_state",QJsonObject{{"operator_description",after->text()}}},{"restoration_steps",QJsonArray{steps->toPlainText()}}});});}); + auto *recovery=section("Прерванные операции","");auto update=[this,view,model,recovery]{rows(view,model,AccessRestoration::ordered(app_.accessChanges()));recovery->setText(QString("Требуют сверки фактического состояния: %1.\nПосле сбоя ничего не воспроизводится автоматически. Недоступный узел остаётся в обязательствах, даже если GUI закрыт.").arg(app_.interruptedRuns().size()));};connect(&a,&AppController::changed,this,update);update(); +}} diff --git a/src/ui/pages/RestorationPage.h b/src/ui/pages/RestorationPage.h new file mode 100644 index 0000000..7445ce0 --- /dev/null +++ b/src/ui/pages/RestorationPage.h @@ -0,0 +1,6 @@ +#pragma once +#include "WorkflowPage.h" +namespace ald::ui {class RestorationPage:public WorkflowPage { + Q_OBJECT +public:explicit RestorationPage(AppController &app,QWidget *parent=nullptr); +};} diff --git a/src/ui/pages/WorkflowPage.cpp b/src/ui/pages/WorkflowPage.cpp new file mode 100644 index 0000000..508259a --- /dev/null +++ b/src/ui/pages/WorkflowPage.cpp @@ -0,0 +1,27 @@ +#include "WorkflowPage.h" +#include +#include +#include +#include +#include +#include +#include +namespace ald::ui { +QLabel *plainLabel(const QString &s,QWidget *p){auto *l=new QLabel(p);l->setTextFormat(Qt::PlainText);l->setText(s);l->setWordWrap(true);l->setTextInteractionFlags(Qt::TextSelectableByMouse|Qt::TextSelectableByKeyboard);return l;} +WorkflowPage::WorkflowPage(AppController &a,const QString&t,const QString&s,QWidget*p):QWidget(p),app_(a){auto *outer=new QVBoxLayout(this);outer->setContentsMargins(24,16,24,16);outer->setSpacing(12);auto *title=plainLabel(t);title->setProperty("title",true);outer->addWidget(title);auto *subtitle=plainLabel(s);subtitle->setProperty("muted",true);outer->addWidget(subtitle);actions_=new FlowLayout;actions_->setSpacing(8);outer->addLayout(actions_);auto *scroll=new QScrollArea;scroll->setWidgetResizable(true);auto *content=new QWidget;body_=new QVBoxLayout(content);body_->setContentsMargins(0,8,0,8);body_->setSpacing(16);body_->setAlignment(Qt::AlignTop);scroll->setWidget(content);outer->addWidget(scroll,1);} +QLabel *WorkflowPage::section(const QString &title,const QString &text){auto *frame=new QFrame;frame->setProperty("panel",true);auto *layout=new QVBoxLayout(frame);auto *heading=plainLabel(title);heading->setProperty("section",true);layout->addWidget(heading);auto *label=plainLabel(text);layout->addWidget(label);body_->addWidget(frame);return label;} +QPushButton *WorkflowPage::button(const QString &text,std::function action,bool primary){auto *b=new QPushButton(text);b->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Preferred);b->setAccessibleName(text);b->setMinimumHeight(36);if(primary)b->setProperty("role","primary");connect(b,&QPushButton::clicked,this,[this,action]{protect(action);});actions_->addWidget(b);return b;} +QPlainTextEdit *WorkflowPage::details(const QString &name,bool expanded){auto *group=new QGroupBox(name);group->setCheckable(true);group->setChecked(expanded);group->setAccessibleName(name);auto *layout=new QVBoxLayout(group);auto *t=new QPlainTextEdit;t->setReadOnly(true);t->setAccessibleName(name);t->setMinimumHeight(160);t->setMaximumBlockCount(5000);layout->addWidget(t);t->setVisible(expanded);connect(group,&QGroupBox::toggled,t,&QWidget::setVisible);body_->addWidget(group);return t;} +QTableView *WorkflowPage::table(JsonTableModel *model,const QString &name,QPlainTextEdit *detail){auto *view=new QTableView;view->setModel(model);view->setAccessibleName(name);view->setSelectionBehavior(QAbstractItemView::SelectRows);view->setSelectionMode(QAbstractItemView::SingleSelection);view->setEditTriggers(QAbstractItemView::NoEditTriggers);view->setAlternatingRowColors(true);view->verticalHeader()->setDefaultSectionSize(36);view->verticalHeader()->hide();view->horizontalHeader()->setStretchLastSection(true);for(int column=0;columncolumnCount();++column)view->setColumnWidth(column,qMax(160,view->fontMetrics().horizontalAdvance(model->headerData(column,Qt::Horizontal,Qt::DisplayRole).toString())+24));view->setMinimumHeight(230);view->setWordWrap(false);body_->addWidget(view);view->setAccessibleDescription("Enter открывает полное содержимое выбранной строки");connect(view,&QTableView::activated,this,[this,model](const QModelIndex &index){QMessageBox box(QMessageBox::Information,"Подробности строки",QString::fromUtf8(QJsonDocument(model->row(index.row())).toJson()),QMessageBox::Ok,this);box.setTextFormat(Qt::PlainText);box.setTextInteractionFlags(Qt::TextSelectableByMouse|Qt::TextSelectableByKeyboard);box.exec();});if(detail)connect(view->selectionModel(),&QItemSelectionModel::currentRowChanged,this,[model,detail](const QModelIndex&i){detail->setPlainText(QString::fromUtf8(QJsonDocument(model->row(i.row())).toJson()));});return view;} +void WorkflowPage::rows(QTableView *v,JsonTableModel *m,const QJsonArray &data){ + const int previous=v->currentIndex().row(),scroll=v->verticalScrollBar()->value(); + const auto old=m->row(previous);QString identityField; + for(const auto &key:QStringList{"id","check","object_guid","item_id","paragraph"})if(old.contains(key)){identityField=key;break;} + m->setRows(data);int selected=previous; + if(!identityField.isEmpty()){selected=-1;for(int i=0;i=0&&selectedrowCount())v->selectRow(selected);v->verticalScrollBar()->setValue(scroll); +} +void WorkflowPage::protect(std::function action){try{action();}catch(const std::exception&e){QMessageBox box(QMessageBox::Warning,"Операция не выполнена",QString::fromUtf8(e.what()),QMessageBox::Ok,this);box.setTextFormat(Qt::PlainText);box.exec();}} +void WorkflowPage::errorPolicyControl(){errorPolicy_=new QComboBox;errorPolicy_->setAccessibleName("При ошибке пакета операций");errorPolicy_->addItems({"Остановить при ошибке","Продолжать независимые","Пауза для решения"});actions_->addWidget(errorPolicy_);} +rules::ErrorPolicy WorkflowPage::policy()const{return errorPolicy_&&errorPolicy_->currentIndex()==1?rules::ErrorPolicy::Independent:errorPolicy_&&errorPolicy_->currentIndex()==2?rules::ErrorPolicy::Pause:rules::ErrorPolicy::Stop;} +} diff --git a/src/ui/pages/WorkflowPage.h b/src/ui/pages/WorkflowPage.h new file mode 100644 index 0000000..a9e8eab --- /dev/null +++ b/src/ui/pages/WorkflowPage.h @@ -0,0 +1,32 @@ +#pragma once +#include "app/AppController.h" +#include "ui/models/JsonTableModel.h" +#include "ui/FlowLayout.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +namespace ald::ui { +QLabel *plainLabel(const QString &text,QWidget *parent=nullptr); +class WorkflowPage:public QWidget { + Q_OBJECT +public:WorkflowPage(AppController &app,const QString &title,const QString &subtitle,QWidget *parent=nullptr); +protected: + QLabel *section(const QString &title,const QString &text); + QPushButton *button(const QString &text,std::function action,bool primary=false); + QPlainTextEdit *details(const QString &name,bool expanded=false); + QTableView *table(JsonTableModel *model,const QString &name,QPlainTextEdit *detail=nullptr); + void rows(QTableView *view,JsonTableModel *model,const QJsonArray &data); + void protect(std::function action); + AppController &app_;QVBoxLayout *body_;FlowLayout *actions_;QComboBox *errorPolicy_=nullptr; + rules::ErrorPolicy policy()const; + void errorPolicyControl(); +}; +} diff --git a/src/workflows/AccessPreparation.cpp b/src/workflows/AccessPreparation.cpp new file mode 100644 index 0000000..e0f411d --- /dev/null +++ b/src/workflows/AccessPreparation.cpp @@ -0,0 +1,16 @@ +#include "AccessPreparation.h" +#include +namespace ald { +QJsonArray AccessPreparation::instructions(bool windows){return QJsonArray{ + QJsonObject{{"phase","Наблюдение"},{"steps_ru",windows? + "На целевом Windows открыть PowerShell 5.1. Проверить winver, $PSVersionTable.PSVersion, Get-Service sshd и Get-WindowsCapability -Online (последняя проверка требует администратора). Зафиксировать edition/build/роль и ошибки прав.": + "На целевом Linux проверить версию ОС, наличие sshd и эффективную конфигурацию штатной утилитой. Снять состояние существующего канала и его владельца."}}, + QJsonObject{{"phase","Перед изменением"},{"steps_ru","Если SSH уже разрешён администратором — использовать его. Сохранить точные идентификаторы правил firewall, диапазоны адресов, состояние и режим запуска службы, ключи и группы, которые предполагается менять. Существующий доступ не становится собственностью приложения."}}, + QJsonObject{{"phase","Подготовка при отсутствии канала"},{"steps_ru",windows? + "Через локальную консоль по MS_OPENSSH добавить штатную OpenSSH Server optional feature из одобренного источника. Отдельно согласовать временное правило только с адреса ALD, учётную запись и запуск sshd. До установки проверить уже существующие правила: установка компонента может создать широкое OpenSSH-Server-In-TCP. Не включать его без проверки области.": + "Через локальную консоль по документации дистрибутива подготовить штатный OpenSSH, ограничить правило источником ALD и добавить выбранный временный ключ. Записать прежние значения до применения."}}, + QJsonObject{{"phase","Проверка подлинности"},{"steps_ru","Сверить fingerprint ключа хоста по независимой консоли. Выбрать защищённый known_hosts и уже разблокированный нативный ssh-agent. Программа использует строгую проверку ключей; пароль и закрытый ключ в неё не вводятся. DefaultShell Windows не изменять."}}, + QJsonObject{{"phase","Восстановление"},{"steps_ru","Внести каждое ручное изменение в журнал доступа. Удалить только свой временный ключ/членство/правило после сравнения текущего состояния с внесённым. При расхождении остановиться. Последний канал закрыть после сохранения локальных инструкций. Исходный SSH/WinRM оставить."}}, + QJsonObject{{"phase","Носитель"},{"steps_ru","Уже установленный SSH и локальные инструкции доступны без интернета. Отсутствующая optional feature или пакет требуют доступного одобренного репозитория либо соответствующего версии установочного носителя."}} +};} +} diff --git a/src/workflows/AccessPreparation.h b/src/workflows/AccessPreparation.h new file mode 100644 index 0000000..ac35653 --- /dev/null +++ b/src/workflows/AccessPreparation.h @@ -0,0 +1,3 @@ +#pragma once +#include +namespace ald {class AccessPreparation {public:static QJsonArray instructions(bool windows);};} diff --git a/src/workflows/AccessRestoration.cpp b/src/workflows/AccessRestoration.cpp new file mode 100644 index 0000000..f07d8a5 --- /dev/null +++ b/src/workflows/AccessRestoration.cpp @@ -0,0 +1,3 @@ +#include "AccessRestoration.h" +#include +namespace ald {QJsonArray AccessRestoration::ordered(const QJsonArray &changes){QJsonArray a,last;for(const auto &v:changes){if(v.toObject().value("resource_type").toString()=="LAST_ACCESS_CHANNEL")last.append(v);else a.append(v);}for(const auto &v:last)a.append(v);return a;}} diff --git a/src/workflows/AccessRestoration.h b/src/workflows/AccessRestoration.h new file mode 100644 index 0000000..0357eb5 --- /dev/null +++ b/src/workflows/AccessRestoration.h @@ -0,0 +1,3 @@ +#pragma once +#include +namespace ald {class AccessRestoration {public:static QJsonArray ordered(const QJsonArray &changes);};} diff --git a/src/workflows/ComplianceEvaluator.cpp b/src/workflows/ComplianceEvaluator.cpp new file mode 100644 index 0000000..801df5d --- /dev/null +++ b/src/workflows/ComplianceEvaluator.cpp @@ -0,0 +1,2 @@ +#include "ComplianceEvaluator.h" +namespace ald {QJsonObject ComplianceEvaluator::evaluate(const QJsonObject &card,const QJsonValue &runtime,const QJsonValue &persistent){const bool verified=card.value("mapping_state").toString()=="VERIFIED";auto expected=card.value("accepted_value");QString result="NOT_CHECKED";if(verified&&!runtime.isUndefined()&&!runtime.isNull()&&!expected.isNull()){result=runtime==expected?"PARTIAL":"FAIL";if(runtime==expected&&persistent==expected)result="PASS";}return {{"result",result},{"applicability","UNKNOWN"},{"runtime",runtime},{"persistent_next_boot",persistent},{"certification_claim",false},{"reason_ru",verified?"Технический результат выбранного профиля":"Исходная рекомендация и профиль Astra ещё не сопоставлены; наблюдение не является соответствием"}};}} diff --git a/src/workflows/ComplianceEvaluator.h b/src/workflows/ComplianceEvaluator.h new file mode 100644 index 0000000..d1c41db --- /dev/null +++ b/src/workflows/ComplianceEvaluator.h @@ -0,0 +1,3 @@ +#pragma once +#include +namespace ald {class ComplianceEvaluator {public:static QJsonObject evaluate(const QJsonObject &card,const QJsonValue &runtime,const QJsonValue &persistent);};} diff --git a/src/workflows/CutoverPlanner.cpp b/src/workflows/CutoverPlanner.cpp new file mode 100644 index 0000000..0a48728 --- /dev/null +++ b/src/workflows/CutoverPlanner.cpp @@ -0,0 +1,2 @@ +#include "CutoverPlanner.h" +namespace ald {QJsonObject CutoverPlanner::preview(const QJsonObject &p){return {{"state","BLOCKED"},{"plan_revision",p.value("revision")},{"downtime",p.value("downtime")},{"reason_ru","Окно не разрешает неподдержанную миграцию. Необходимо подтвердить обязательные возможности, независимость от AD и восстановление единственного КД."},{"direct_ad_delete_available",false}};}} diff --git a/src/workflows/CutoverPlanner.h b/src/workflows/CutoverPlanner.h new file mode 100644 index 0000000..733e87f --- /dev/null +++ b/src/workflows/CutoverPlanner.h @@ -0,0 +1,3 @@ +#pragma once +#include +namespace ald {class CutoverPlanner {public:static QJsonObject preview(const QJsonObject &migration);};} diff --git a/src/workflows/HardeningPlanner.cpp b/src/workflows/HardeningPlanner.cpp new file mode 100644 index 0000000..067690a --- /dev/null +++ b/src/workflows/HardeningPlanner.cpp @@ -0,0 +1,3 @@ +#include "HardeningPlanner.h" +#include +namespace ald {QJsonObject HardeningPlanner::prepare(const QJsonObject &card,bool verified){QJsonArray blockers;if(!verified)blockers.append("Сначала завершить проверку миграции");if(card.value("mapping_state").toString()!="VERIFIED")blockers.append("Не подтверждено сопоставление с эксплуатационной документацией Astra 1.7.7 UU2");return {{"item_id",card.value("id")},{"state",blockers.isEmpty()?"REVIEW_REQUIRED":"BLOCKED"},{"blockers",blockers},{"recovery_class",card.value("recovery_class")},{"execution_enabled",false}};}} diff --git a/src/workflows/HardeningPlanner.h b/src/workflows/HardeningPlanner.h new file mode 100644 index 0000000..20a3525 --- /dev/null +++ b/src/workflows/HardeningPlanner.h @@ -0,0 +1,3 @@ +#pragma once +#include +namespace ald {class HardeningPlanner {public:static QJsonObject prepare(const QJsonObject &card,bool migrationVerified);};} diff --git a/src/workflows/IdentityMapper.cpp b/src/workflows/IdentityMapper.cpp new file mode 100644 index 0000000..7af9583 --- /dev/null +++ b/src/workflows/IdentityMapper.cpp @@ -0,0 +1,16 @@ +#include "IdentityMapper.h" +#include "core/Rules.h" +#include +#include +#include +namespace ald { +QJsonArray IdentityMapper::reconcile(const QJsonArray &inventory,const QJsonArray &existing) { + QMap map; + auto key=[](const QJsonObject &o){return QString::fromStdString(rules::identityKey(o.value("source_system_id").toString().toStdString(),o.value("source_guid").toString().toStdString(),o.value("source_sid").toString().toStdString()));}; + for(const auto &v:existing){auto o=v.toObject();auto k=key(o);if(map.contains(k))throw std::runtime_error("Duplicate identity mapping");map[k]=o;} + QJsonArray out; + for(const auto &v:inventory){const auto o=v.toObject();QJsonObject m{{"source_system_id",o.value("source_system_id")},{"source_guid",o.value("object_guid")},{"source_sid",o.value("sid")},{"source_dn",o.value("dn")},{"target_id",QJsonValue::Null},{"target_sid",QJsonValue::Null},{"target_uid_gid",QJsonObject{}},{"mapping_method","UNMAPPED"},{"verification_state","NOT_CHECKED"}};auto k=key(m);if(map.contains(k)){auto old=map.take(k);old["source_dn"]=o.value("dn");out.append(old);}else out.append(m);} + // Deleted/missing source identities remain visible; never silently drop ACL dependencies. + for(auto it=map.begin();it!=map.end();++it){auto o=it.value();o["verification_state"]="SOURCE_NOT_OBSERVED";out.append(o);}return out; +} +} diff --git a/src/workflows/IdentityMapper.h b/src/workflows/IdentityMapper.h new file mode 100644 index 0000000..22f6564 --- /dev/null +++ b/src/workflows/IdentityMapper.h @@ -0,0 +1,3 @@ +#pragma once +#include +namespace ald {class IdentityMapper {public:static QJsonArray reconcile(const QJsonArray &inventory,const QJsonArray &existing);};} diff --git a/src/workflows/InitializationPlanner.cpp b/src/workflows/InitializationPlanner.cpp new file mode 100644 index 0000000..d9d33dc --- /dev/null +++ b/src/workflows/InitializationPlanner.cpp @@ -0,0 +1,12 @@ +#include "InitializationPlanner.h" +#include "adapters/Ald31Deployment.h" +namespace ald { +QJsonObject InitializationPlanner::build(const QJsonObject &facts,NodeRole role){auto p=Ald31Deployment::guidedContract();QJsonArray blockers; + if(!rules::canInitialize(role))blockers.append("Текущая роль не допускает чистую установку. Сначала установить фактическое состояние и восстановить существующую конфигурацию."); + if(!facts.value("astra").toBool())blockers.append("Текущая ОС не подтверждена как совместимая Astra Linux SE."); + blockers.append("Не подтверждены ALSE 1.7.7 UU2, ядро, Смоленск, состав пакетов и допустимость установки GUI на КД."); + blockers.append("corp.local уже принадлежит исходному AD; нужен проверенный порядок authority/resolver/инициализации без смены сети."); + blockers.append("Требуются резервные копии, проверенное восстановление и отдельное согласование конкретного окна."); + p["state"]="BLOCKED";p["blockers"]=blockers;p["target_domain"]="corp.local";p["facts"]=facts;return p; +} +} diff --git a/src/workflows/InitializationPlanner.h b/src/workflows/InitializationPlanner.h new file mode 100644 index 0000000..4a8e19e --- /dev/null +++ b/src/workflows/InitializationPlanner.h @@ -0,0 +1,3 @@ +#pragma once +#include "domain/Types.h" +namespace ald {class InitializationPlanner {public:static QJsonObject build(const QJsonObject &facts,NodeRole role);};} diff --git a/src/workflows/MigrationPlanner.cpp b/src/workflows/MigrationPlanner.cpp new file mode 100644 index 0000000..a596335 --- /dev/null +++ b/src/workflows/MigrationPlanner.cpp @@ -0,0 +1,22 @@ +#include "MigrationPlanner.h" +#include "app/CapabilityRegistry.h" +#include "storage/JsonValidator.h" +namespace ald { +QJsonObject MigrationPlanner::build(const QJsonObject &inventory,const QJsonArray &mappings,int revision) { + rules::GateInput gate;gate.sourceDomain="corp.local";gate.targetDomain="corp.local"; + // Imported completeness is a claim; several non-directory categories are not + // covered by the implemented adapter. No imported boolean can close this gate. + gate.inventoryComplete=false;gate.current.revision=unsigned(revision);gate.current.inventoryDigest=JsonValidator::digest(inventory).toStdString();gate.current.mappingDigest=JsonValidator::digest(mappings).toStdString();gate.accepted=gate.current; + QJsonArray requirements,items,graph; + for(const auto &c:CapabilityRegistry::all())if(QStringList{"same_name_transition","credentials","windows_profiles","computer_trust","identity_permissions","applications","policy_outcomes","ad_independence"}.contains(c.id)) { + gate.requirements.push_back({c.id.toStdString(),c.state,rules::Result::NotChecked,true}); + requirements.append(QJsonObject{{"id",c.id},{"state","UNKNOWN"},{"mandatory",true},{"reason_ru",c.limitations.join("; ")},{"manual_alternative",c.manual_alternative}}); + } + for(const auto &v:inventory.value("objects").toArray()) {auto o=v.toObject();items.append(QJsonObject{{"id",o.value("object_guid")},{"category",o.value("object_type")},{"source_ref",o.value("dn")},{"target_ref",QJsonValue::Null},{"disposition","UNKNOWN"},{"dependencies",QJsonArray{"same_name_transition","identity_permissions"}},{"acceptance_ids",QJsonArray{"mapping","login"}},{"blockers",QJsonArray{"Поддержанный перенос и проверка целевой идентичности ещё не выполнены"}},{"evidence_ids",QJsonArray{}}});} + for(const auto *category:{"credentials","computers","profiles","gpo_effects","dns","dhcp","files_acl","services_applications","certificates_adcs","other_ad_dependencies"})items.append(QJsonObject{{"id",QString("scope.")+category},{"category",category},{"disposition","UNKNOWN"},{"blockers",QJsonArray{"Категория не обследована полностью. Это не доказательство отсутствия зависимости."}},{"evidence_ids",QJsonArray{}}}); + QStringList phases={"Обследование и поддержанный путь","Резервная копия и репетиция восстановления одного КД","Подготовка цели в согласованной последовательности DNS","Объекты и GUID/SID mapping","Ресурсы, приложения и права","Пилот клиентов и непрерывность работы","Утверждённое окно переключения","Обратимая проверка при недоступном AD","Готовность к штатному выводу AD","Восстановление временного доступа"}; + for(int i=0;i +namespace ald {class MigrationPlanner {public:static QJsonObject build(const QJsonObject &inventory,const QJsonArray &mappings,int revision);};} diff --git a/src/workflows/PolicyPlanner.cpp b/src/workflows/PolicyPlanner.cpp new file mode 100644 index 0000000..b3b056d --- /dev/null +++ b/src/workflows/PolicyPlanner.cpp @@ -0,0 +1,13 @@ +#include "PolicyPlanner.h" +#include "storage/JsonValidator.h" +#include +#include +namespace ald { +QJsonObject PolicyPlanner::compare(const QJsonObject &desired,const QJsonObject &observed){QJsonArray changes,conflicts;QSet ids; + for(const auto &v:desired.value("settings").toArray()){auto setting=v.toObject();auto id=setting.value("id").toString();auto owner=setting.value("management_owner").toString();auto current=observed.value(id).toObject(); + if(ids.contains(id)||owner.isEmpty()||(!current.value("management_owner").toString().isEmpty()&¤t.value("management_owner").toString()!=owner)){conflicts.append(id);continue;}ids.insert(id); + if(!current.contains("effective_value")||current.value("effective_value")!=setting.value("desired_value"))changes.append(QJsonObject{{"id",id},{"previous_state",current},{"desired_value",setting.value("desired_value")},{"owner",owner},{"state","NEEDS_VERSION_MAPPING"},{"restoration_ru","Восстановить сохранённое значение через прежнего владельца; снятие назначения не является обратной операцией"}}); + } + return {{"profile_digest",JsonValidator::digest(desired)},{"observed_digest",JsonValidator::digest(observed)},{"changes",changes},{"ownership_conflicts",conflicts},{"state",conflicts.isEmpty()?"REVIEW_REQUIRED":"BLOCKED"},{"execution_enabled",false}}; +} +} diff --git a/src/workflows/PolicyPlanner.h b/src/workflows/PolicyPlanner.h new file mode 100644 index 0000000..2f0eb8a --- /dev/null +++ b/src/workflows/PolicyPlanner.h @@ -0,0 +1,3 @@ +#pragma once +#include +namespace ald {class PolicyPlanner {public:static QJsonObject compare(const QJsonObject &desired,const QJsonObject &observed);};} diff --git a/tests/fixtures/cleanup_conflict.json b/tests/fixtures/cleanup_conflict.json new file mode 100644 index 0000000..8df945a --- /dev/null +++ b/tests/fixtures/cleanup_conflict.json @@ -0,0 +1,6 @@ +{ + "schema_version": 1, + "synthetic": true, + "scenario": "cleanup_conflict", + "expected_issue_ru": "Ресурс изменён администратором после подготовки" +} diff --git a/tests/fixtures/demo.inventory.json b/tests/fixtures/demo.inventory.json new file mode 100644 index 0000000..d0cd508 --- /dev/null +++ b/tests/fixtures/demo.inventory.json @@ -0,0 +1,355 @@ +{ + "schema_version": 1, + "source_system_id": "66ccac1b-250e-540b-bade-f791da120c9a", + "synthetic": true, + "scope": { + "description": "Синтетический ALD-LAB; не лабораторное доказательство", + "complete": false, + "denied_or_unreachable": [ + "offline.corp.local" + ], + "categories": [ + "users", + "groups", + "ou", + "gpo", + "dns", + "files", + "services" + ] + }, + "hosts": [ + { + "id": "f82f49bd-be8e-52c6-b45b-18999d545ad9", + "fqdn": "ad.corp.local", + "addresses": [ + "192.0.2.10" + ], + "os_family": "WINDOWS", + "os_release": "Server 2019", + "os_build": "synthetic", + "kernel": "", + "architecture": "x86_64", + "detected_roles": [ + "AD_DC" + ], + "observed_at": "2026-10-27T12:00:00Z", + "evidence_ids": [ + "synthetic-only" + ] + }, + { + "id": "1022603f-5a7c-5eff-a792-ae85e7e27a5e", + "fqdn": "ald.corp.local", + "addresses": [ + "192.0.2.20" + ], + "os_family": "ASTRA", + "os_release": "1.7.7 UU2", + "os_build": "synthetic", + "kernel": "synthetic", + "architecture": "x86_64", + "detected_roles": [ + "PARTIAL_OR_UNKNOWN" + ], + "observed_at": "2026-10-27T12:00:00Z", + "evidence_ids": [ + "synthetic-only" + ] + }, + { + "id": "1fbb12e0-7cf3-5bab-b27b-6fbf7d0432b7", + "fqdn": "ws2025.corp.local", + "addresses": [ + "192.0.2.30" + ], + "os_family": "WINDOWS", + "os_release": "Server 2025", + "os_build": "synthetic", + "kernel": "", + "architecture": "x86_64", + "detected_roles": [ + "UNKNOWN" + ], + "observed_at": "2026-10-27T12:00:00Z", + "evidence_ids": [ + "synthetic-only" + ] + } + ], + "objects": [ + { + "source_system_id": "66ccac1b-250e-540b-bade-f791da120c9a", + "object_guid": "2c9092ac-135c-5bac-836b-25826aca5c44", + "sid": "S-1-5-21-100-200-300-1000", + "dn": "CN=ald.alice,OU=ALD-LAB,DC=corp,DC=local", + "object_type": "user", + "attributes": { + "name": "ald.alice", + "enabled": true, + "privileged": false + }, + "memberships": [ + "CN=GG-ALD-LAB-Employees,OU=ALD-LAB,DC=corp,DC=local" + ], + "observed_at": "2026-10-27T12:00:00Z" + }, + { + "source_system_id": "66ccac1b-250e-540b-bade-f791da120c9a", + "object_guid": "4c075ce6-353e-5592-8cef-37db6b53579c", + "sid": "S-1-5-21-100-200-300-1001", + "dn": "CN=ald.bob,OU=ALD-LAB,DC=corp,DC=local", + "object_type": "user", + "attributes": { + "name": "ald.bob", + "enabled": true, + "privileged": false + }, + "memberships": [], + "observed_at": "2026-10-27T12:00:00Z" + }, + { + "source_system_id": "66ccac1b-250e-540b-bade-f791da120c9a", + "object_guid": "62741d22-dc14-58b1-9027-cb101de2e0ab", + "sid": "S-1-5-21-100-200-300-1002", + "dn": "CN=ald.carol,OU=ALD-LAB,DC=corp,DC=local", + "object_type": "user", + "attributes": { + "name": "ald.carol", + "enabled": true, + "privileged": false + }, + "memberships": [], + "observed_at": "2026-10-27T12:00:00Z" + }, + { + "source_system_id": "66ccac1b-250e-540b-bade-f791da120c9a", + "object_guid": "903dd718-ab40-5d84-9408-16227e326277", + "sid": "S-1-5-21-100-200-300-1003", + "dn": "CN=ald.eve.priv,OU=ALD-LAB,DC=corp,DC=local", + "object_type": "user", + "attributes": { + "name": "ald.eve.priv", + "enabled": true, + "privileged": true + }, + "memberships": [], + "observed_at": "2026-10-27T12:00:00Z" + }, + { + "source_system_id": "66ccac1b-250e-540b-bade-f791da120c9a", + "object_guid": "25b43933-72f5-5f50-b733-c5d71e6c47c2", + "sid": "S-1-5-21-100-200-300-1004", + "dn": "CN=ald.dave.disabled,OU=ALD-LAB,DC=corp,DC=local", + "object_type": "user", + "attributes": { + "name": "ald.dave.disabled", + "enabled": false, + "privileged": false + }, + "memberships": [], + "observed_at": "2026-10-27T12:00:00Z" + }, + { + "source_system_id": "66ccac1b-250e-540b-bade-f791da120c9a", + "object_guid": "b46397fb-b65c-5e50-b46a-d41346c92c06", + "sid": "", + "dn": "OU=ALD-LAB,OU=ALD-LAB,DC=corp,DC=local", + "object_type": "organizationalUnit", + "attributes": { + "name": "ALD-LAB" + }, + "memberships": [], + "observed_at": "2026-10-27T12:00:00Z" + }, + { + "source_system_id": "66ccac1b-250e-540b-bade-f791da120c9a", + "object_guid": "0a506d9c-baa5-599d-b47e-174db639009b", + "sid": "S-1-5-21-100-200-300-1006", + "dn": "CN=svc_ald_app,OU=ALD-LAB,DC=corp,DC=local", + "object_type": "service", + "attributes": { + "name": "svc_ald_app", + "spn": "HTTP/app.corp.local" + }, + "memberships": [], + "observed_at": "2026-10-27T12:00:00Z" + }, + { + "source_system_id": "66ccac1b-250e-540b-bade-f791da120c9a", + "object_guid": "158b9bba-bf72-55cc-a840-fb85d14833f3", + "sid": "S-1-5-21-100-200-300-1020", + "dn": "CN=GG-ALD-LAB-Employees,OU=ALD-LAB,DC=corp,DC=local", + "object_type": "group", + "attributes": { + "name": "GG-ALD-LAB-Employees", + "group_scope": "Global" + }, + "memberships": [], + "observed_at": "2026-10-27T12:00:00Z" + }, + { + "source_system_id": "66ccac1b-250e-540b-bade-f791da120c9a", + "object_guid": "bd97446a-7ed8-58d7-91c4-8e4801399762", + "sid": "S-1-5-21-100-200-300-1021", + "dn": "CN=GG-ALD-LAB-IT,OU=ALD-LAB,DC=corp,DC=local", + "object_type": "group", + "attributes": { + "name": "GG-ALD-LAB-IT", + "group_scope": "Global" + }, + "memberships": [], + "observed_at": "2026-10-27T12:00:00Z" + }, + { + "source_system_id": "66ccac1b-250e-540b-bade-f791da120c9a", + "object_guid": "ea0e9f58-79df-5e87-90a3-73ed44e94438", + "sid": "S-1-5-21-100-200-300-1022", + "dn": "CN=GG-ALD-LAB-Helpdesk,OU=ALD-LAB,DC=corp,DC=local", + "object_type": "group", + "attributes": { + "name": "GG-ALD-LAB-Helpdesk", + "group_scope": "Global" + }, + "memberships": [ + "CN=GG-ALD-LAB-IT,OU=ALD-LAB,DC=corp,DC=local" + ], + "observed_at": "2026-10-27T12:00:00Z" + }, + { + "source_system_id": "66ccac1b-250e-540b-bade-f791da120c9a", + "object_guid": "91b61720-5143-5b4f-a8b0-111c3eeeaa74", + "sid": "S-1-5-21-100-200-300-1023", + "dn": "CN=GG-ALD-LAB-AppUsers,OU=ALD-LAB,DC=corp,DC=local", + "object_type": "group", + "attributes": { + "name": "GG-ALD-LAB-AppUsers", + "group_scope": "Global" + }, + "memberships": [], + "observed_at": "2026-10-27T12:00:00Z" + }, + { + "source_system_id": "66ccac1b-250e-540b-bade-f791da120c9a", + "object_guid": "ef9a9376-7c2f-5c1f-8bdd-076a33145d40", + "sid": "S-1-5-21-100-200-300-1024", + "dn": "CN=GG-ALD-LAB-Privileged,OU=ALD-LAB,DC=corp,DC=local", + "object_type": "group", + "attributes": { + "name": "GG-ALD-LAB-Privileged", + "group_scope": "Global" + }, + "memberships": [], + "observed_at": "2026-10-27T12:00:00Z" + }, + { + "source_system_id": "66ccac1b-250e-540b-bade-f791da120c9a", + "object_guid": "73cc6dde-d791-523b-9847-d55b078ecf93", + "sid": "S-1-5-21-100-200-300-1025", + "dn": "CN=DL-ALD-LAB-File-Read,OU=ALD-LAB,DC=corp,DC=local", + "object_type": "group", + "attributes": { + "name": "DL-ALD-LAB-File-Read", + "group_scope": "DomainLocal" + }, + "memberships": [], + "observed_at": "2026-10-27T12:00:00Z" + }, + { + "source_system_id": "66ccac1b-250e-540b-bade-f791da120c9a", + "object_guid": "f4c84961-d5c7-58fe-b3b1-d17aac1bd04f", + "sid": "S-1-5-21-100-200-300-1026", + "dn": "CN=DL-ALD-LAB-File-Modify,OU=ALD-LAB,DC=corp,DC=local", + "object_type": "group", + "attributes": { + "name": "DL-ALD-LAB-File-Modify", + "group_scope": "DomainLocal" + }, + "memberships": [], + "observed_at": "2026-10-27T12:00:00Z" + }, + { + "source_system_id": "66ccac1b-250e-540b-bade-f791da120c9a", + "object_guid": "6fc2edfc-321e-5204-a15c-1a5a116ba8eb", + "sid": "S-1-5-21-100-200-300-1027", + "dn": "CN=UG-ALD-LAB-AllTestUsers,OU=ALD-LAB,DC=corp,DC=local", + "object_type": "group", + "attributes": { + "name": "UG-ALD-LAB-AllTestUsers", + "group_scope": "Universal" + }, + "memberships": [], + "observed_at": "2026-10-27T12:00:00Z" + }, + { + "source_system_id": "66ccac1b-250e-540b-bade-f791da120c9a", + "object_guid": "f8e41393-6401-55eb-aea4-5cefe012296f", + "sid": "", + "dn": "CN=ALD-LAB-Share,OU=ALD-LAB,DC=corp,DC=local", + "object_type": "share", + "attributes": { + "name": "ALD-LAB-Share", + "path": "\\\\ad.corp.local\\ALD-LAB", + "orphan_sids": [ + "S-1-5-21-100-200-300-9999" + ] + }, + "memberships": [], + "observed_at": "2026-10-27T12:00:00Z" + }, + { + "source_system_id": "66ccac1b-250e-540b-bade-f791da120c9a", + "object_guid": "32d977ac-0e11-55ab-9f4f-d00ef4074ea7", + "sid": "", + "dn": "CN=app.corp.local,OU=ALD-LAB,DC=corp,DC=local", + "object_type": "dns", + "attributes": { + "name": "app.corp.local", + "record_type": "CNAME", + "target": "ad.corp.local" + }, + "memberships": [], + "observed_at": "2026-10-27T12:00:00Z" + }, + { + "source_system_id": "66ccac1b-250e-540b-bade-f791da120c9a", + "object_guid": "0c02afbf-0f0f-5a0e-a07d-a695ae4f5a64", + "sid": "", + "dn": "CN=GPO-ALD-LAB-UI,OU=ALD-LAB,DC=corp,DC=local", + "object_type": "gpo", + "attributes": { + "name": "GPO-ALD-LAB-UI", + "linked": true + }, + "memberships": [], + "observed_at": "2026-10-27T12:00:00Z" + }, + { + "source_system_id": "66ccac1b-250e-540b-bade-f791da120c9a", + "object_guid": "5301cd2b-7eb8-5236-99c7-9b4f357b0abf", + "sid": "", + "dn": "CN=GPO-ALD-LAB-Application-Access,OU=ALD-LAB,DC=corp,DC=local", + "object_type": "gpo", + "attributes": { + "name": "GPO-ALD-LAB-Application-Access", + "filter": "GG-ALD-LAB-AppUsers" + }, + "memberships": [], + "observed_at": "2026-10-27T12:00:00Z" + }, + { + "source_system_id": "66ccac1b-250e-540b-bade-f791da120c9a", + "object_guid": "6e7e2c69-52cf-54b2-964c-de23697e444c", + "sid": "", + "dn": "CN=GPO-ALD-LAB-Disabled-Example,OU=ALD-LAB,DC=corp,DC=local", + "object_type": "gpo", + "attributes": { + "name": "GPO-ALD-LAB-Disabled-Example", + "linked": false + }, + "memberships": [], + "observed_at": "2026-10-27T12:00:00Z" + } + ], + "source_domain": "corp.local" +} diff --git a/tests/fixtures/duplicate_names.json b/tests/fixtures/duplicate_names.json new file mode 100644 index 0000000..e2f3b20 --- /dev/null +++ b/tests/fixtures/duplicate_names.json @@ -0,0 +1,6 @@ +{ + "schema_version": 1, + "synthetic": true, + "scenario": "duplicate_names", + "expected_issue_ru": "Одинаковые displayName при разных GUID/SID" +} diff --git a/tests/fixtures/incomplete_deployment.json b/tests/fixtures/incomplete_deployment.json new file mode 100644 index 0000000..7d10d3c --- /dev/null +++ b/tests/fixtures/incomplete_deployment.json @@ -0,0 +1,6 @@ +{ + "schema_version": 1, + "synthetic": true, + "scenario": "incomplete_deployment", + "expected_issue_ru": "Пакеты и конфигурация без доказательства здоровья" +} diff --git a/tests/fixtures/missing_media.json b/tests/fixtures/missing_media.json new file mode 100644 index 0000000..1caf6f0 --- /dev/null +++ b/tests/fixtures/missing_media.json @@ -0,0 +1,6 @@ +{ + "schema_version": 1, + "synthetic": true, + "scenario": "missing_media", + "expected_issue_ru": "Пакет aldpro-mp отсутствует, нужен проверенный носитель" +} diff --git a/tests/fixtures/offline_host.json b/tests/fixtures/offline_host.json new file mode 100644 index 0000000..4ec834e --- /dev/null +++ b/tests/fixtures/offline_host.json @@ -0,0 +1,6 @@ +{ + "schema_version": 1, + "synthetic": true, + "scenario": "offline_host", + "expected_issue_ru": "Узел недоступен, очистка ожидает связи" +} diff --git a/tests/fixtures/orphan_sid.json b/tests/fixtures/orphan_sid.json new file mode 100644 index 0000000..893a6db --- /dev/null +++ b/tests/fixtures/orphan_sid.json @@ -0,0 +1,6 @@ +{ + "schema_version": 1, + "synthetic": true, + "scenario": "orphan_sid", + "expected_issue_ru": "SID в ACL не сопоставлен" +} diff --git a/tests/fixtures/same_name_dns.json b/tests/fixtures/same_name_dns.json new file mode 100644 index 0000000..06e0577 --- /dev/null +++ b/tests/fixtures/same_name_dns.json @@ -0,0 +1,6 @@ +{ + "schema_version": 1, + "synthetic": true, + "scenario": "same_name_dns", + "expected_issue_ru": "corp.local обслуживает AD; переход не проверен" +} diff --git a/tests/fixtures/windows2025.json b/tests/fixtures/windows2025.json new file mode 100644 index 0000000..42e4da2 --- /dev/null +++ b/tests/fixtures/windows2025.json @@ -0,0 +1,6 @@ +{ + "schema_version": 1, + "synthetic": true, + "scenario": "windows2025", + "expected_issue_ru": "SSH не подтверждает интеграцию с ALD" +} diff --git a/tests/integration/README.md b/tests/integration/README.md new file mode 100644 index 0000000..7751b13 --- /dev/null +++ b/tests/integration/README.md @@ -0,0 +1,48 @@ +# Authorized laboratory verification — not executed + +Topology: one source forest/domain `corp.local`, one source AD DC, one Astra +ALD target, Windows 10, Server 2019 and Server 2025 test targets. Do not invent +a second source DC. Preserve the existing network in the actual scenario; +192.0.2.x in fixtures is documentation data, never a live default. + +Before running a native integration test, record concrete target authorization, +exact builds/roles/updates, installed tool help, snapshots only where valid, +AD-aware backup and a tested recovery procedure. No test auto-connects to hosts. + +1. Build Qt app on ALSE 1.7.7 UU2 / selected 6.1-generic / Smolensk with ALD 3.1. + Run all unit tests, update actual compatibility evidence, verify vendor + allowance for extra DC software. Test 1024×768 and 1440×900 at 100/150/200%. +2. Local discovery: clean, packages-only, AD client, ALD client, healthy, + degraded and partial DC. Corroborate membership/role independently; a single + stopped service must not offer clean installation. +3. On each named Windows build, run fixed discovery using prepared OpenSSH + native execution and Windows PowerShell 5.1. Verify edition/build/role, + optional feature permission failures, known-host mismatch, locked agent, + timeout, no DefaultShell change and no background jobs/listeners. +4. AD inventory: ordinary/privileged/disabled identities, nested group scopes, + rename/duplicate display names, OU, GPO links, scoped denial and 50000 limit. + Compare GUID/SID and counts against native UI. Record all uncollected areas. +5. Namespace/initialization: obtain vendor-supported same-name transition; + verify delivery's interactive installer/help, redacted secret handling, + exact prerequisites, planned downtime and partial failure recovery. Do not + enable the automated mutation adapter until this succeeds. +6. Continuity: old password, machine trust, original profile, DPAPI/EFS as + applicable, positive/negative file ACLs, application Kerberos/LDAP/NTLM/SPN, + CA/renewal, policy outcomes, post-reboot behavior. Each gets independent + manual and automatic evidence and its revision. +7. Private executor: root UID/PID peer substitution, wrong machine binding, + unknown ID/parameter, oversized/replayed request, altered binary/parent, + GUI disconnect, failed pkexec, timeout, no leftover helper/socket/process. +8. Access ledger: preserve pre-existing service/firewall/key; own temporary + resource restored only when unchanged, externally altered resource conflicts, + offline host stays pending, last-channel closure needs console verification. + Current preview guides these actions; automated inverse adapters are pending. +9. Controlled source-unavailable test with approved recovery and support. + AD retirement remains blocked on any missing mandatory outcome. There is no + FSMO-to-ALD or direct delete-AD test. +10. Install/uninstall: no domain-service/access changes from package hooks; + project persistence, incomplete schema rollback, disk-full handling, + shutdown during read-only process, no LAN ports/custom agents after close. + +Save machine-derived observations as separate evidence files; do not reuse +synthetic fixture observations as vendor or laboratory evidence. diff --git a/tests/unit/test_rules.cpp b/tests/unit/test_rules.cpp new file mode 100644 index 0000000..5b1b2d3 --- /dev/null +++ b/tests/unit/test_rules.cpp @@ -0,0 +1,82 @@ +#include "core/Rules.h" +#include +#include +#include +#include +#include +using namespace ald::rules; +static int checks=0; +#define CHECK(x) do { ++checks; if(!(x)) throw std::runtime_error("check failed at line " + std::to_string(__LINE__) + ": " #x); } while(false) +template void throws(F f){bool did=false;try{f();}catch(const std::invalid_argument&){did=true;}CHECK(did);} +int main(){try { + for(int exitCode:{0,1,127,255})for(bool normal:{false,true})for(Result post:{Result::Pass,Result::Fail,Result::NotChecked,Result::Error,Result::Unknown}) { + const auto r=reconcile(exitCode,normal,post,false,true); + CHECK((r==Result::Pass)==(exitCode==0&&normal&&post==Result::Pass)); + CHECK(reconcile(exitCode,normal,post,true,true)==Result::Unknown); + } + GateInput gate;gate.sourceDomain=gate.targetDomain="corp.local"; + gate.inventoryComplete=gate.recoveryRehearsed=gate.windowAuthorized=true; + for(const auto *id:{"same_name_transition","credentials","windows_profiles","computer_trust","identity_permissions","applications","policy_outcomes","ad_independence"})gate.requirements.push_back({id,CapabilityState::Verified,Result::Pass,true}); + CHECK(blockers(gate).empty()); + gate.requirements.front().support=CapabilityState::DocumentedNotTested; + CHECK(!blockers(gate).empty()); + gate.requirements.front().evidence=Result::Pass; // Human checkbox cannot change support. + CHECK(!blockers(gate).empty()); + gate.requirements.front().support=CapabilityState::Verified; + gate.current.mappingDigest="changed";CHECK(!blockers(gate).empty());gate.current=gate.accepted; + gate.current.inventoryDigest="changed";CHECK(!blockers(gate).empty());gate.current=gate.accepted; + gate.current.policyDigest="changed";CHECK(!blockers(gate).empty());gate.current=gate.accepted; + gate.current.revision++;CHECK(!blockers(gate).empty());gate.current=gate.accepted; + gate.requirements.clear();CHECK(!blockers(gate).empty()); + gate.sourceDomain="CORP.LOCAL";gate.targetDomain="corp.local"; + const auto mixedCase=blockers(gate); + CHECK(std::find(mixedCase.begin(),mixedCase.end(),"SAME_NAME_TRANSITION_UNVERIFIED")!=mixedCase.end()); + RoleFacts clean;clean.astra=clean.packageQueryComplete=true; + CHECK(classify(clean)==NodeRole::PartialOrUnknown); + clean.configurationObserved=true;CHECK(classify(clean)==NodeRole::CleanAstra); + + RoleFacts f;f.astra=f.packageQueryComplete=f.aldPackages=f.ipaConfig=f.serverConfig=f.servicesObserved=true; + CHECK(classify(f)==NodeRole::DcDegraded);CHECK(!canInitialize(classify(f))); + f.servicesHealthy=true;CHECK(classify(f)==NodeRole::PartialOrUnknown); + f.healthVerified=true;CHECK(classify(f)==NodeRole::DcHealthy);CHECK(!canInitialize(classify(f))); + for(bool reachable:{false,true})for(const auto &cur:{"old","applied","external"})CHECK(restoration(false,reachable,cur,"applied",false)==RestoreDecision::Preserve); + CHECK(restoration(true,true,"changed","applied",false)==RestoreDecision::Conflict); + CHECK(restoration(true,false,"applied","applied",false)==RestoreDecision::Pending); + CHECK(restoration(true,true,"applied","applied",true)==RestoreDecision::ManualVerification); + CHECK(identityKey("source","ABC","S-1-2")==identityKey("source","abc","S-1-2")); + CHECK(identityKey("source","abc","S-1-2")!=identityKey("source","def","S-1-2")); + CHECK(identityKey("source","abc","S-1-2")!=identityKey("other","abc","S-1-2")); + throws([]{identityKey("source","","sid");}); + CHECK(!transitionAllowed(RunState::Running,RunState::Completed)); + CHECK(!transitionAllowed(RunState::RecoveryRequired,RunState::Running)); + CHECK(transitionAllowed(RunState::Running,RunState::StopRequested)); + CHECK(!dependenciesPassed({"two","host",{"one"},true},{{"one",Result::Fail}})); + CHECK(!dependenciesPassed({"two","host",{"one"},true},{})); + CHECK(afterResult(Result::Fail,ErrorPolicy::Independent)==BatchDecision::Continue); + CHECK(afterResult(Result::Unknown,ErrorPolicy::Stop)==BatchDecision::Stop); + CHECK(afterResult(Result::Error,ErrorPolicy::Pause)==BatchDecision::Pause); + throws([]{topological({{"a","x",{"b"},false},{"b","y",{"a"},false}});}); + throws([]{topological({{"a","x",{"missing"},false}});}); + throws([]{topological({{"a","x",{},false},{"a","y",{},false}});}); + for(const auto *bad:{"--help","host;id","a\nwhoami","$(id)","a..b","a.-b","a_.b","a.'b","a/b","a:22","a\\b"})CHECK(!safeHost(bad)); + CHECK(safeHost("ald.corp.local"));CHECK(safeHost("192.0.2.10")); + for(const auto *bad:{"--help","x;id","a b","$x","a\n","a'"})CHECK(!safeUser(bad)); + CHECK(safeUser("CORP\\admin"));CHECK(safeUser("ald.alice")); + for(const auto *bad:{"/abs","../x","x/../y","x//y","C:\\x","x/./y"}) { CHECK(!safeRelativePath(bad)); } + CHECK(safeRelativePath("tasks/check.ps1")); + const std::vector secrets={"password-123","пароль123","abc","bcd"}; + const std::string input="before password-123 and пароль123 and abcd after"; + for(std::size_t split=0;split<=input.size();++split){SecretStream s(secrets);auto output=s.feed(input.substr(0,split));output+=s.feed(input.substr(split),true);for(const auto &secret:secrets)CHECK(output.find(secret)==std::string::npos);CHECK(output.find("before")!=std::string::npos);CHECK(output.find("after")!=std::string::npos);} + SecretStream overflow({"aaa"});std::string suppressed; + for(int i=0;i<10;++i)suppressed+=overflow.feed(std::string(1000,'a')); + suppressed+=overflow.feed("aaa after",true); + CHECK(suppressed.find("aaa")==std::string::npos); + CHECK(suppressed.find("oversized sensitive output")!=std::string::npos); + // Reproducible generative properties: chunk partition independence and DAG order. + std::mt19937 random(0xA1D310); + SecretStream whole(secrets);const auto expected=whole.feed(input,true); + for(int trial=0;trial<1000;++trial){SecretStream s(secrets);std::string output;for(std::size_t pos=0;pos steps;for(int i=0;i<20;++i){Step step{std::to_string(i),"host",{},false};for(int j=0;j +#include +#include "execution/OperationRegistry.h" +#include "execution/PlanExecutor.h" +#include "security/AccessLedger.h" +#include "security/SecretRedactor.h" +#include "transports/NativeSshTransport.h" +#include "workflows/InitializationPlanner.h" +#include "workflows/PolicyPlanner.h" +#include "workflows/ComplianceEvaluator.h" +#include "adapters/WindowsDiscovery.h" +#include +#include +#include +using namespace ald; +class RuntimeTests:public QObject { + Q_OBJECT +private slots: + void initTestCase(){Q_INIT_RESOURCE(resources);qRegisterMetaType();} + void rejectsUnknownExecution(){QVERIFY_EXCEPTION_THROWN(OperationRegistry::resolve("shell.run",{{"command","id"}}),std::runtime_error);QVERIFY_EXCEPTION_THROWN(OperationRegistry::resolve("local.os",{{"path","/etc/shadow"}}),std::runtime_error);OperationRegistry::verifyAssets();} + void failedProcessNeverPasses(){ProcessRunner runner;QSignalSpy spy(&runner,&ProcessRunner::finished);ProcessSpec spec;spec.operationId="test";spec.program="/usr/bin/false";runner.start(spec);QVERIFY(spy.wait(5000));auto r=qvariant_cast(spy[0][0]);QVERIFY(r.exitCode!=0);QVERIFY(!runner.active());} + void zeroExitFailedPostcondition(){PlanExecutor e;ProcessSpec spec;spec.operationId="test";spec.program="/usr/bin/true";QSignalSpy done(&e,&PlanExecutor::finished);e.start({{"test","local",{},false}},{{"test",spec}},{{"test",[](const ProcessResult&){return rules::Result::Fail;}}},rules::ErrorPolicy::Stop);QVERIFY(done.wait(5000));QVERIFY(!done[0][0].toBool());} + void journalRefusalStopsBeforeNativeStart(){ + PlanExecutor e;ProcessSpec spec;spec.operationId="test";spec.program="/usr/bin/true"; + QSignalSpy done(&e,&PlanExecutor::finished),results(&e,&PlanExecutor::stepFinished); + connect(&e,&PlanExecutor::stepStarted,&e,[&e]{e.stop();}); + e.start({{"test","local",{},false}},{{"test",spec}},{{"test",[](const ProcessResult&){return rules::Result::Pass;}}},rules::ErrorPolicy::Stop); + QVERIFY(done.wait(5000));QCOMPARE(results.size(),0);QVERIFY(!done[0][0].toBool()); + } + void missingToolExplained(){ProcessRunner r;ProcessSpec s;s.operationId="missing";s.program="/no-such-ald-tool";QSignalSpy done(&r,&ProcessRunner::finished);r.start(s);QVERIFY(done.wait(5000));QVERIFY(qvariant_cast(done[0][0]).failedToStart);} + void cancelOwnedProcess(){ProcessRunner r;ProcessSpec s;s.operationId="wait";s.program="/usr/bin/sleep";s.arguments=QStringList{"30"};QSignalSpy done(&r,&ProcessRunner::finished);r.start(s);QTest::qWait(30);r.cancel();QVERIFY(done.wait(5000));QVERIFY(qvariant_cast(done[0][0]).cancelled);QVERIFY(!r.active());} + void mutationDeniedAtFinalBoundary(){ProcessRunner r;ProcessSpec s;s.operationId="unknown.write";s.program="/usr/bin/true";s.readOnly=false;QVERIFY_EXCEPTION_THROWN(r.start(s),std::runtime_error);} + void sshHasNoInterpolation(){QTemporaryDir d;QString known=d.path()+"/known_hosts";QFile f(known);QVERIFY(f.open(QIODevice::WriteOnly));f.write("# explicit test fixture\n");f.close();f.setPermissions(QFile::ReadOwner|QFile::WriteOwner);SshTarget t{"dc.corp.local","CORP\\admin",known,22};auto spec=NativeSshTransport::windowsTask(t,"windows.discovery");QVERIFY(spec.arguments.contains("StrictHostKeyChecking=yes"));QVERIFY(!spec.arguments.last().contains(t.host));QVERIFY(!spec.arguments.last().contains(t.user));QVERIFY(spec.arguments.last().startsWith("powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand "));t.host="x;whoami";QVERIFY_EXCEPTION_THROWN(NativeSshTransport::windowsTask(t,"windows.discovery"),std::runtime_error);} + void restorationConflict(){QJsonObject c{{"id","1"},{"owner_marker","run"},{"applied_state",QJsonObject{{"state","on"}}}};QCOMPARE(AccessLedger::assess(c,{{"state","external"}},true,"run").value("decision").toString(),QString("CONFLICT"));QCOMPARE(AccessLedger::assess(c,{},false,"run").value("decision").toString(),QString("PENDING"));QCOMPARE(AccessLedger::assess(c,{},true,"other").value("decision").toString(),QString("PRESERVED"));} + void unicodeChunkRedaction(){auto bytes=QString("до пароль после").toUtf8();for(int split=0;split<=bytes.size();++split){SecretRedactor r({"пароль"});auto text=r.feed(bytes.left(split));text+=r.feed(bytes.mid(split),true);QVERIFY(!text.contains("пароль"));QVERIFY(text.contains("до"));QVERIFY(text.contains("после"));}} + void degradedInitialization(){auto p=InitializationPlanner::build({{"astra",true}},NodeRole::DcDegraded);QCOMPARE(p.value("state").toString(),QString("BLOCKED"));QVERIFY(!p.value("execution_enabled").toBool());} + void ownershipAndIdempotence(){QJsonObject profile{{"settings",QJsonArray{QJsonObject{{"id","x"},{"management_owner","ALD"},{"desired_value",1}}}}};auto conflict=PolicyPlanner::compare(profile,{{"x",QJsonObject{{"management_owner","LOCAL"},{"effective_value",1}}}});QCOMPARE(conflict.value("state").toString(),QString("BLOCKED"));auto same=PolicyPlanner::compare(profile,{{"x",QJsonObject{{"management_owner","ALD"},{"effective_value",1}}}});QVERIFY(same.value("changes").toArray().isEmpty());} + void runtimeDoesNotProvePersistent(){auto o=ComplianceEvaluator::evaluate({{"mapping_state","VERIFIED"},{"accepted_value",3}},3,QJsonValue::Undefined);QCOMPARE(o.value("result").toString(),QString("PARTIAL"));} +}; +QTEST_GUILESS_MAIN(RuntimeTests) +#include "test_runtime.moc" diff --git a/tests/unit/test_storage.cpp b/tests/unit/test_storage.cpp new file mode 100644 index 0000000..9249339 --- /dev/null +++ b/tests/unit/test_storage.cpp @@ -0,0 +1,60 @@ +#include +#include +#include "storage/ProjectRepository.h" +#include "storage/JsonValidator.h" +#include "storage/OfflineBundle.h" +#include +#include "adapters/AdInventory.h" +#include "workflows/IdentityMapper.h" +#include "app/AppController.h" +#include +#include +#include +#include +using namespace ald; +class StorageTests:public QObject { + Q_OBJECT +private slots: + void initTestCase(){Q_INIT_RESOURCE(resources);} + void logWithAbsentOptionalContext(){QTemporaryDir dir;ProjectRepository r;r.open(dir.path());r.event({}, {}, "session.open", "INFO", "app", "Открыт проект");const auto events=r.events();QCOMPARE(events.size(),1);const auto event=events[0].toObject();QCOMPARE(event.value("message_ru").toString(),QString("Открыт проект"));QVERIFY(event.value("run_id").isString());QCOMPARE(event.value("redacted_detail").toString(),QString(""));} + void checklistSurvivesReopenAndExportsSchema(){ + QTemporaryDir dir;const auto project=dir.path()+"/project",output=dir.path()+"/checklist.json"; + { + AppController c;c.open(project,true); + c.recordHuman({{"item_id","namespace"},{"host_id","corp.local"},{"checked_by","Тестовый оператор"},{"result","PASS"},{"note","Синтетическая проверка "}},"old");auto rows=r.observations("new");QCOMPARE(rows.size(),1);QCOMPARE(rows[0].toObject().value("result").toString(),QString("STALE"));QCOMPARE(rows[0].toObject().value("original_result").toString(),QString("PASS"));r.exportChecklist(dir.path()+"/out.html",QJsonArray{QJsonObject{{"id","login"},{"title_ru","Проверить