1
0
mirror of https://github.com/altlinux/gpupdate.git synced 2025-10-22 07:33:27 +03:00

Compare commits

...

541 Commits

Author SHA1 Message Date
Evgeny Sinelnikov
a8bc2dbcb5 Fix gsettings_applier arrays processing for machine 2021-10-25 12:48:13 +04:00
Valery Sinelnikov
585811e282 Added work with arrays in gsettings 2021-10-22 20:23:05 +04:00
Valery Sinelnikov
0b497bcc02 Fixed bug for authentication-methods in org.gnome.Vino 2021-10-21 19:17:02 +04:00
Valery Sinelnikov
e6f19a2116 Fixed bug for alternative-port in org.gnome.Vino 2021-10-21 19:16:43 +04:00
Evgeny Sinelnikov
86c240b9df VERSION: Bump version up to 0.9.8... 2021-09-29 08:43:27 +04:00
Evgeny Sinelnikov
dae3cf2c6c 0.9.7-alt1
- Fix regression with kestroy for user credential cache
- Update system-policy-gpupdate PAM-rules to ignore applying group policies
  for local users and system users with uid less than 500
- Add control facilities to rule system-policy-gpupdate rules:
  + gpupdate-group-users
  + gpupdate-localusers
  + gpupdate-system-uids
2021-09-29 08:42:25 +04:00
Evgeny Sinelnikov
4fe7d0a73e system-policy-gpupdate: fix with tested rules and add two special
controls facilities gpupdate-group-users and gpupdate-system-uids.
2021-09-29 08:35:04 +04:00
Evgeny Sinelnikov
54d0c7c2cb util/kerberos.py: fix regression with kestroy for user credential cache
in forked process with droped privileges.
2021-09-29 02:45:03 +04:00
Evgeny Sinelnikov
954a5598fb system-policy-gpupdate: apply group policy to users in users group only 2021-09-27 01:15:00 +04:00
Evgeny Sinelnikov
ba4eb4bf28 Add control gpupdate-localusers facility for group policy applying to local users 2021-09-26 20:01:41 +04:00
Evgeny Sinelnikov
aa10d5bbf9 system-policy-gpupdate: add PAM-rules for ignore applying group policies
for local users and system users with uid less than 500
2021-09-26 19:56:13 +04:00
Evgeny Sinelnikov
f3062668fa VERSION: Bump version up to 0.9.7... 2021-09-20 08:08:20 +04:00
Evgeny Sinelnikov
046079d4c9 0.9.6-alt1
- Add support changed GPO List Processing for '**DelVals.' value name
2021-09-20 07:57:50 +04:00
Evgeny Sinelnikov
414a827eb8 Add support changed GPO List Processing for '**DelVals.' value name 2021-09-20 07:56:04 +04:00
Evgeny Sinelnikov
8ce322d552 VERSION: Bump version up to 0.9.6... 2021-09-20 07:23:13 +04:00
Evgeny Sinelnikov
84d5122319 0.9.5-alt1
- Refix local policy path detection
- gpupdate-setup: revert settings to default when disabled
2021-09-20 03:31:30 +04:00
Evgeny Sinelnikov
436eeb3760 gpupdate-setup: revert settings to default when disabled 2021-09-14 06:56:27 +04:00
Evgeny Sinelnikov
4b9ef4335a Refix local policy path detection 2021-09-14 06:39:13 +04:00
Evgeny Sinelnikov
929f9678ad 0.9.4-alt1
- Add improvement with new local-policy system-policy control
- Fix gpupdate-setup and user service installation regressions
- Set empty local policy and local backend by default
- Fix local policy path detection
2021-09-14 04:00:27 +04:00
Evgeny Sinelnikov
03cada30cf Add gpo file_sys_path to common logs 2021-09-14 03:57:16 +04:00
Evgeny Sinelnikov
8199cac510 Fix local policy path detection 2021-09-14 02:22:34 +04:00
Evgeny Sinelnikov
e050889a07 Set empty local policy and local backend by default 2021-09-14 01:45:15 +04:00
Evgeny Sinelnikov
1bf2bd053d Fix gupdate-user.service installation 2021-09-14 00:58:33 +04:00
Evgeny Sinelnikov
950e132e2a gpupdate-setup: fix local policy setup regression after code moving 2021-09-14 00:46:26 +04:00
Evgeny Sinelnikov
82e255efc9 0.9.3-alt1
- Use NetBIOS name for Kerberos authentification
- Add support actions (create, update, delete, replace) for Shortcuts
- Add support GSettings with locks feature
- Add support file cache for special GSettings policy:
  Software\BaseALT\Policies\GSettings\org.mate.background.picture-filename
  (requires python smbc module with use_kerberos option support)
2021-09-09 18:10:18 +04:00
Evgeny Sinelnikov
011a3fbed3 gpupdate.service: add starting After syslog and network-online targets 2021-09-09 18:10:18 +04:00
Valery Sinelnikov
8eda2fbedb Fixed GSettings blocking errors 2021-09-09 17:50:08 +04:00
Evgeny Sinelnikov
3f3fa5f7d9 Merge pull request #140 from altlinux/file_cache
File cache
2021-09-06 15:18:00 +04:00
Evgeny Sinelnikov
0210f97e0d Fix GSettings locks profile db generating 2021-09-06 15:12:09 +04:00
Evgeny Sinelnikov
7e6dec6b3d Update file cache functionality for GSettings 2021-09-06 11:37:45 +04:00
Evgeny Sinelnikov
5e4ed2f655 Fix pathlib PosixPath type conversion, clean code from unused json import 2021-09-06 06:38:23 +04:00
Evgeny Sinelnikov
721ba96559 Add exception handling for not UNC path case in picture_fetch() 2021-09-06 05:29:24 +04:00
Evgeny Sinelnikov
c83568cc70 Fix bad raise Exception during UNCPath construction 2021-09-06 00:44:05 +04:00
Evgeny Sinelnikov
15f99e0171 Fix not unusefull logging 2021-09-03 05:12:54 +04:00
Evgeny Sinelnikov
f84af7e0e8 Fix gpupdate_file_cache directory name in gpupdate.spec 2021-09-03 03:47:34 +04:00
7bd1131d5d fs_file_cache() object moved to gsettings_applier.py 2021-09-02 18:12:09 +04:00
5fb8e6ff74 Create file cache directory on install 2021-09-02 17:49:21 +04:00
ce2797e5f1 File cache introduced for frontend
Introduced file cache for GSettings, specifically for wallpapers.
It is needed to work with wallpapers on remote resources.
2021-09-02 17:49:20 +04:00
6d9417fb94 storage.fs_file_cache.fs_file_cache
File caching mechanism utilizing /var/cache/gpupdate_file_cache
directory to cache files from remote locations, specifically, to
cache files specified as UNC paths.
2021-09-02 17:49:20 +04:00
301a77e90a util.paths: UNCPath primitive introduced
It is needed to allow parsing and conversion of UNC paths
2021-09-02 17:47:15 +04:00
Evgeny Sinelnikov
274d9d8555 Merge pull request #146 from altlinux/gsettings_locks
Add support GSettings locks with local profile
2021-09-02 17:43:55 +04:00
Evgeny Sinelnikov
04f5f98681 Merge pull request #145 from altlinux/realm_from_smb_conf
Use default realm taken from smb.conf, not krb5.conf
2021-09-02 17:43:32 +04:00
Evgeny Sinelnikov
9638e5fabb Merge pull request #141 from altlinux/netbios_name
Use NetBIOS name for Kerberos authentification
2021-09-02 17:43:12 +04:00
Evgeny Sinelnikov
393fd25cdb Merge pull request #139 from altlinux/gpo_initial
Fix startup user and computer gpoa initialization
2021-09-02 17:42:59 +04:00
Valery Sinelnikov
23f862f9a5 Add support GSettings locks with local profile 2021-08-20 16:48:43 +04:00
a85fed7cff Use default realm taken from smb.conf, not krb5.conf 2021-08-18 15:52:32 +04:00
bbcb98bb94 Use NetBIOS name for Kerberos authentification 2021-08-16 14:49:52 +04:00
Evgeny Sinelnikov
57f4f0678a Fix startup user and computer gpoa initialization 2021-08-06 09:21:38 +04:00
Evgeny Sinelnikov
306b8db34a Merge pull request #138 from altlinux/shortcuts_actions
Shortcuts actions
2021-08-02 12:22:47 +04:00
Evgeny Sinelnikov
7c8f9892b5 Fix Shortcuts update logic with reading firstly 2021-07-29 00:02:04 +04:00
Evgeny Sinelnikov
4c6a099529 Add support actions (create, update, delete, replace) for Shortcuts 2021-07-28 23:50:36 +04:00
Evgeny Sinelnikov
e6c563e540 0.9.2-alt1
- Fix Shortcuts applier double running in user context
- Add LogonUser variable to expand_windows_var() function
- Add support of path variable expansion to Shortcuts applier
2021-07-28 21:47:38 +04:00
Evgeny Sinelnikov
d67d472b1c Merge pull request #137 from altlinux/user_shortcuts
User shortcuts (fix usercontext and support of path expansion)
2021-07-27 20:54:41 +04:00
Evgeny Sinelnikov
ac8aba2212 Add support of path variable expansion to Shortcuts applier 2021-07-27 07:44:39 +04:00
Evgeny Sinelnikov
39241bc625 util.windows: add LogonUser variable to expand_windows_var() function. 2021-07-27 07:42:28 +04:00
Evgeny Sinelnikov
9206a0b732 Fix Shortcuts applier double running in user context. 2021-07-27 06:49:57 +04:00
Evgeny Sinelnikov
cdb7306d65 0.9.1-alt1
- Fix GSettings applier user part support
- Add support additional firefox appliers
- Add new windows policies mapping capability feature ruled by:
  Software\BaseALT\Policies\GPUpdate\WindowsPoliciesMapping
- Improve drop privileges mechanism with fork and dbus session
2021-07-18 20:33:36 +04:00
Evgeny Sinelnikov
e0ac5f98ac Revert "Added keys sleep-computer-ac and sleep-display-ac"
This reverts commit 389bad4382.

Revert untested Windows mapping.
2021-07-18 20:31:55 +04:00
Evgeny Sinelnikov
96db0a2200 Merge pull request #136 from altlinux/windows_mapping
Windows mapping feature and dbus fixes
2021-07-18 01:05:28 +04:00
Evgeny Sinelnikov
f3e4d463b9 Add new Software\BaseALT\Policies\GPUpdate\WindowsPoliciesMapping feature 2021-07-18 00:59:41 +04:00
Evgeny Sinelnikov
0fded79484 Fix debug info for GSetting applying 2021-07-18 00:58:16 +04:00
Evgeny Sinelnikov
a6e8f0b352 Avoid error in forked process with dconf-service killing 2021-07-18 00:56:13 +04:00
Evgeny Sinelnikov
c8542fa477 Avoid multiple debug info from appliers/gsettings.py 2021-07-18 00:53:10 +04:00
Evgeny Sinelnikov
31183afa60 Merge pull request #135 from altlinux/dbus_session_kill
Dbus session kill
2021-07-17 22:17:53 +04:00
Evgeny Sinelnikov
17cd27b73e Fix dbus session daemon and dconf service killing in user context 2021-07-17 03:17:37 +04:00
Evgeny Sinelnikov
cf82fae5ec Replace with_privileges function to separate system module 2021-07-17 02:31:30 +04:00
Evgeny Sinelnikov
00abee6f7c Fix Gio.Settings synchronization step due dbus races 2021-07-17 02:25:15 +04:00
Evgeny Sinelnikov
760585f3fb Merge pull request #134 from altlinux/drop_privs_for_gsettings
Run user-mode functions in correct environment
2021-07-16 22:47:58 +04:00
Evgeny Sinelnikov
28b4cd7d11 Merge pull request #133 from alenka26/mapping
Added keys sleep-computer-ac and sleep-display-ac
2021-07-16 22:47:29 +04:00
Evgeny Sinelnikov
14153c6272 Remove uneeded hacks with DBUS_SESSION_BUS_ADDRESS 2021-07-16 21:45:42 +04:00
Evgeny Sinelnikov
b2801eec07 Improve drop privileges mechanism 2021-07-16 21:45:41 +04:00
Evgeny Sinelnikov
ae414993e7 Fix GSettings applier user part initialization 2021-07-16 21:45:40 +04:00
Evgeny Sinelnikov
26e5126312 Replace user context applying to single cycle 2021-07-16 21:45:19 +04:00
Evgeny Sinelnikov
45a5df32c3 Merge pull request #132 from altlinux/firefox_applier_fix
Add support additional firefox appliers
2021-07-16 21:39:52 +04:00
c842ce0e07 Run D-Bus session daemon 2021-07-12 20:25:22 +04:00
Evgeny Sinelnikov
2327952896 Add fork for drop privileges 2021-07-12 20:20:14 +04:00
Evgeny Sinelnikov
ee656f52f6 Fix user part of GSettings applier 2021-07-12 20:16:18 +04:00
Alenka Glukhovskaya
389bad4382 Added keys sleep-computer-ac and sleep-display-ac 2021-07-10 10:30:13 +04:00
Evgeny Sinelnikov
eca3fb43c6 Add support additional firefox appliers 2021-07-06 07:03:27 +04:00
Evgeny Sinelnikov
8367fcba99 0.9.0-alt1
- Change policies.json location for Firefox
- Set GSettings, Chromium and Firefox appliers
  not experimental and enabled by default
2021-07-05 22:35:32 +04:00
Evgeny Sinelnikov
0480e88e69 Set GSettingsUser, Chromium and Firefox appliers not experimental and enabled by default 2021-07-04 05:32:13 +04:00
110aee3970 Change policies.json location for Firefox
Mozilla Firefox version 78 changed its default `policies.json` file
location to `/etc/firefox/policies/policies.json`. Previous location
does not work despite changelog ensuring it will continue working.
2021-06-28 15:40:07 +04:00
Evgeny Sinelnikov
f0f3152d86 GSettings applier: final and enable by default system part applied to machine 2021-06-28 15:39:42 +04:00
NIR
4bd03585db Merge pull request #122 from altlinux/Envvars_applier
environment variables applier
2021-03-18 13:53:44 +04:00
NIR
e1a30a1436 Merge branch 'master' into Envvars_applier 2021-03-18 13:53:16 +04:00
NIR
4dbb290f73 Merge pull request #115 from altlinux/default_policy_detector
Automatically detect local policy name
2021-03-18 13:50:38 +04:00
NIR
7a588e9b68 Merge pull request #127 from altlinux/case_insensitive_keys
Make registry keys case-insensitive like in Windows registry
2021-03-18 13:49:54 +04:00
Evgeny Sinelnikov
c367b04f55 Merge pull request #123 from altlinux/Handle_kinit_error
Catch exception in case kinit is not successful
2021-02-24 20:16:58 +04:00
eaee242639 Make registry keys case-insensitive like in Windows registry 2021-02-20 11:41:56 +04:00
8009467a87 0.8.2-alt1
- Increased D-Bus timeouts on calls
- Minor logging fixes
2020-12-22 19:01:11 +04:00
NIR
22c3a9f06e Merge pull request #125 from altlinux/logging_bugfixes
Logging bugfixes
2020-12-22 18:20:47 +04:00
NIR
b213c83854 Merge pull request #124 from altlinux/dbus_runner_timeouts
Increase D-Bus timeout
2020-12-22 18:19:34 +04:00
9480f41469 Fix for gsettings_applier logging 2020-12-22 18:18:32 +04:00
a984e896a5 Re-raise exceptions from applier 2020-12-22 18:14:08 +04:00
702aead8b5 Fix for envvars parser 2020-12-22 18:13:12 +04:00
01de884037 Missing comma added 2020-12-21 20:05:48 +04:00
fba30c9b0e Increase D-Bus timeout
`python-dbus` `Interface` and `Object` primitives are unable to provide
methods allowing to set synchronous blocking call timeout. The problem
is that default D-Bus timeout is only 25 seconds while application of
Group Policy Objects takes 2-5 minutes. It was decided to set blocking
call timeout to 10 minutes using `call_blocking` method of `Connection`
primitive to solve the problem.
2020-12-07 20:15:20 +04:00
Rustem Bapin
2d92b5cb6e Environment variables: optimization for actions update and replace 2020-10-23 19:14:50 +04:00
Rustem Bapin
02632b1c88 replacing slashes in value only if value contains variables
using split instead startswith
2020-10-21 22:13:18 +04:00
Rustem Bapin
d781a257e9 added translation for debug message about environment variables 2020-10-21 21:54:14 +04:00
Rustem Bapin
4b80dc13cf fix debug code for adding environment variables into storage 2020-10-21 21:43:48 +04:00
Rustem Bapin
e45cd1fd18 refactor, add update and replace actions 2020-10-21 20:36:32 +04:00
Rustem Bapin
ca01b20464 Catch exception in case kinit is not successful 2020-10-16 22:16:02 +04:00
Rustem Bapin
590fd8c464 environment variables applier 2020-10-16 22:08:46 +04:00
Evgeny Sinelnikov
d967c0786d 0.8.1-alt3
- Fixed compatibility upgrade trigger condition
2020-10-07 06:33:05 +04:00
Evgeny Sinelnikov
b426ab5b36 0.8.1-alt2
- Fixed compatibility upgrade trigger from 0.7 releases for update
  active local-policy in new gpupdate.ini configuartion file
2020-10-07 05:47:22 +04:00
Evgeny Sinelnikov
bb54d3e01e 0.8.1-alt1
- Workaround for control names with special symbols
- Improved logging on Kerberos errors
2020-09-11 22:05:50 +04:00
NIR
e2c386b6d0 Merge pull request #119 from altlinux/fix_kerberos_logging
Improved logging on Kerberos errors
2020-09-11 19:08:37 +04:00
66c2303069 Improved logging on Kerberos errors 2020-09-11 19:06:02 +04:00
NIR
e9cf33855c Merge pull request #117 from altlinux/control_spec_workaround
Workaround for control names with special symbols
2020-09-11 18:56:07 +04:00
3eae206e6f Workaround for control names with special symbols 2020-09-11 18:39:36 +04:00
536d989497 Automatically detect local policy name 2020-09-11 14:26:25 +04:00
Evgeny Sinelnikov
6cf0a7b136 0.8.0-alt1
- Improve gpo applier logging
- Add new configuration file /etc/gpupdate/gpupdate.ini
- Fix folders applier regression
- kinit move to samba backend
- Replace gpupdate-setup utility with new implementation
2020-09-10 00:40:48 +04:00
Evgeny Sinelnikov
48e484937e Set gpupdate-setup enable options not positional 2020-09-10 00:40:13 +04:00
Evgeny Sinelnikov
150ed3d29f Fix write action arguments 2020-09-09 23:11:23 +04:00
NIR
cff5ed1932 control 'system-policy global' changed to 'system-policy remote' 2020-09-09 23:02:29 +04:00
Evgeny Sinelnikov
b6a41c3843 Merge pull request #114 from altlinux/gpsetup_active_backend
Active backend selection fixes in gpupdate-setup
2020-09-09 20:53:10 +04:00
564d324b53 gpupdate-setup: Added set-backend and default-backend commands 2020-09-09 19:58:20 +04:00
41de03e6e8 Fix DC selection logging 2020-09-09 19:57:46 +04:00
828f6099da Fix logging for Kerberos 2020-09-09 19:57:27 +04:00
0a5af77655 Eliminate unused variable in util.windows 2020-09-09 19:57:08 +04:00
4abea3cc32 Make samba default backend in code 2020-09-09 19:56:38 +04:00
2597ae46cd Handle GPT retrieval error on incorrect DC specification 2020-09-09 19:56:10 +04:00
fdec0dc765 Two new FATAL-level messages added 2020-09-09 19:55:25 +04:00
8f96b1be85 Don't do anything if log metadata is not JSON-encodable 2020-09-09 19:54:43 +04:00
1f6b7d4cb7 Changed default backend to samba in configuration file 2020-09-09 19:52:21 +04:00
NIR
adea356f1b Merge pull request #113 from altlinux/dc_fix_log
Omit missing variable from log
2020-09-08 15:18:05 +04:00
75bb669ce7 Omit missing variable from log 2020-09-08 15:15:46 +04:00
NIR
e7967e5cc4 Merge pull request #112 from altlinux/avoid_dc_search
Avoid DC search on DC specification (either as CLI or config option)
2020-09-07 17:41:16 +04:00
d99ec2d890 Avoid DC search on DC specification (either as CLI or config option) 2020-09-07 17:11:07 +04:00
NIR
91b5c7f858 Merge pull request #111 from altlinux/dc_in_config
Added functionality to tune Samba backend via INI file
2020-09-07 16:53:56 +04:00
cb5101fc48 Added functionality to tune Samba backend via INI file
It is now possible to write in `/etc/gpupdate/gpupdate.ini`:

```
[samba]
dc = your.buggy.dc
```

To avoid auto-selection of Domain Controller for policy replication.
2020-09-07 16:51:38 +04:00
Evgeny Sinelnikov
a9f9689032 Merge pull request #108 from altlinux/freeipa_backend_stub
gpupdate-setup and other improvements
2020-09-02 20:31:40 +04:00
508fbe4dd5 Kinit functionality moved to Samba backend 2020-08-28 22:10:09 +04:00
ea379c3181 Correctly handle backend initialization 2020-08-28 21:52:40 +04:00
Evgeny Sinelnikov
ccfba4b592 Merge pull request #109 from altlinux/update-desktop-database
Shortcuts applier improvement
2020-08-26 17:57:30 +04:00
Evgeny Sinelnikov
3dcebe25e2 Merge pull request #110 from altlinux/storage_trigger
Postinst trigger introduced
2020-08-26 17:56:33 +04:00
37416ab77d Postinst trigger introduced
There are situations when we might lose storage compatibility between
versions due to SQLite3 table structure changes. This commit introduces
trigger which removes old storage in case of specific version change.

The storage will be regenerated on next GPOA run.
2020-08-21 16:34:21 +04:00
22cd8844ba Logic fix for shortcuts applier 2020-08-21 16:03:34 +04:00
c8cfd51915 Shortcuts applier improvement
Run update-desktop-database utility only in case there are
shortcuts for processing present in storage.
2020-08-21 16:00:39 +04:00
1a4ae69cdf Install gpupdate.ini 2020-08-20 18:33:33 +04:00
e1170d2096 FreeIPA backend stub added 2020-08-20 18:30:24 +04:00
e44b3c96ec gpupdate-setup: Fixed GPOA call 2020-08-20 18:29:41 +04:00
7e7450d52a gpupdate-setup: Retain behavior of active-policy option 2020-08-20 18:29:29 +04:00
e4113e971f gpupdate-setup: Check for gpupdate-user.service correctly 2020-08-20 18:29:01 +04:00
57607d1311 gpupdate-setup.is_unit_enabled(): Fixed stdout check 2020-08-20 18:28:30 +04:00
103110bdef gpupdate-setup.is_unit_enabled(): Work with global units too 2020-08-20 18:28:05 +04:00
126f2ffd7d backend: Fixed incorrect variable reference error 2020-08-20 18:27:15 +04:00
914a20b244 Operate on configuration file instead of symlinks 2020-08-20 15:09:40 +04:00
55dbdfc246 Numerous config parser fixes 2020-08-20 15:08:37 +04:00
b5059620a7 gpupdate-setup functions for local policy setup moved to util.util 2020-08-20 15:01:23 +04:00
af1e756037 gpupdate-setup: Docstrings added for functions 2020-08-20 15:00:39 +04:00
e1bc549a51 Fixed CLI definitions in gpupdate-setup 2020-08-19 19:38:46 +04:00
NIR
43b1ea392f Merge pull request #103 from altlinux/folders_regression_fix
Folders regression fix
2020-08-19 18:15:29 +04:00
NIR
b29c13b8dd Merge pull request #107 from altlinux/fix_set_dc
Fixed set_dc()
2020-08-19 18:14:42 +04:00
035950f234 Configuration file wrapper added 2020-08-19 17:50:03 +04:00
44545943ac gpupdate.ini: gpupdate configuration file template added 2020-08-19 16:49:40 +04:00
14bc3f3f96 gpupdate-setup: Status checks improved 2020-08-18 16:12:45 +04:00
e01e6f511a gpupdate-setup: Switch implementation for CLI options 2020-08-17 19:35:45 +04:00
79927743ca Use rollback_on_error() function in gpupdate-setup 2020-08-17 19:34:44 +04:00
f9cef07151 gpupdate-setup/rollback_on_error()
This is helper function for consistent Group Policy disabling in case
of any errors while enabling Group Policies.
2020-08-17 19:19:22 +04:00
53b94246a8 gpupdate-setup: Check return codes 2020-08-17 18:47:25 +04:00
3f1edd2791 runcmd(): Run program and check return code 2020-08-17 18:40:45 +04:00
165f0defa7 Install symlink to gpupdate-setup 2020-08-13 16:38:59 +04:00
0808128b5f gpupdate-setup became necessary utility 2020-08-13 16:37:10 +04:00
c40ae95a08 Fixed set_dc() 2020-08-13 15:59:10 +04:00
NIR
a1bd67f7d2 Merge pull request #105 from altlinux/gsettings_fixes
Improved logging in GSettings applier
2020-08-13 08:31:47 +04:00
NIR
30b942d32d Merge pull request #104 from altlinux/testing_data
Testing data
2020-08-13 08:31:11 +04:00
NIR
84b7977351 Merge pull request #102 from altlinux/extra_error_handling
Extra error handling
2020-08-13 08:30:44 +04:00
4c37b15dde Improved logging in GSettings applier 2020-08-13 08:28:42 +04:00
3dfb37313d GPT test data 2020-08-13 08:22:58 +04:00
81b9e88d91 test_xdg.py 2020-08-13 08:22:34 +04:00
2bcfd75a5b Folders applier: Fixed regression and added path expansion 2020-08-13 08:16:48 +04:00
53ad06b787 Folders applier: update action support added 2020-08-13 08:15:09 +04:00
505f0152f7 Fixed typo in Folders storage 2020-08-13 08:12:32 +04:00
0ba273ee0e Fixed typo in Folders.xml parser 2020-08-13 08:11:28 +04:00
ef55a63c7e Set default values for missing XML parameters 2020-08-13 08:10:38 +04:00
6ebbf5f59d Stub 2020-08-13 08:05:46 +04:00
dff80ba14d Extra information for E10 added 2020-08-11 15:26:48 +04:00
6c5c22a932 Two more error handlers for GPT merging so bugs in mergers won't block backend 2020-08-10 15:56:56 +04:00
c67487b56c GPT merging error handlers added 2020-08-05 13:16:55 +04:00
abe943f399 New error messages translated 2020-08-05 13:16:29 +04:00
353082a6bb Two more error codes added 2020-08-05 13:16:04 +04:00
NIR
e37796e5b4 Merge pull request #28 from altlinux/l10n
Initial translation
2020-08-04 16:14:31 +04:00
3afe965b75 Translation leftovers removed 2020-08-03 21:38:43 +04:00
aa93d95012 Fix for translation install 2020-08-03 21:29:02 +04:00
0bc7144da9 gpupdate localized 2020-08-03 21:28:30 +04:00
ffbef2d18f Install language packages 2020-08-03 21:04:04 +04:00
6429b3c290 Russian translations added 2020-08-03 20:58:26 +04:00
05320f86b3 Messages internationalized 2020-08-03 20:57:56 +04:00
b10b965287 GPOA: Initialize gettext 2020-08-03 20:56:35 +04:00
716862201e Initial translation 2020-07-30 17:15:44 +04:00
NIR
c701565325 Merge pull request #95 from altlinux/gsettings_expansion
Appliers for GSettings expanded with Windows key support
2020-07-30 17:13:08 +04:00
NIR
09553a1c9e Merge pull request #99 from altlinux/logging_codes
Logging codes
2020-07-30 17:12:22 +04:00
674f07569e util.logging: Show milliseconds in logs and handle parameter errors 2020-07-30 15:36:08 +04:00
3d39e1f010 backend.samba_backend: Logging improved 2020-07-29 18:07:18 +04:00
c45fa3e552 util.windows: Logging improved 2020-07-29 18:07:01 +04:00
8135b21cd3 messages: Message list expanded 2020-07-29 18:06:44 +04:00
758421b611 util.logging.log(): Introduced function to wrap log data 2020-07-29 17:49:23 +04:00
25b1774d49 gpupdate: Logging improved 2020-07-29 17:48:44 +04:00
70ef7ef384 gpoa: Logging improved 2020-07-29 17:48:26 +04:00
3517f3a67b util.sid: Leftovers eliminated 2020-07-29 17:47:50 +04:00
2f6a287727 gpt.gpt: Logging improved 2020-07-29 17:47:28 +04:00
586528f8e9 frontend.frontend_manager: Logging improved 2020-07-29 17:47:03 +04:00
68910679e6 backend.samba_backend: Logging improved 2020-07-29 17:46:27 +04:00
8cb1278f04 backend: Logging improved 2020-07-29 17:46:03 +04:00
e12042fb2c storage.sqlite_cache: Logging improved 2020-07-29 17:45:37 +04:00
8d351dde63 storage.sqlite_cache: Logging improved 2020-07-29 17:44:53 +04:00
ae3672dbdc util.dbus: Logging improved 2020-07-29 17:35:01 +04:00
bc8b6369c2 util.kerberos: Logging improved 2020-07-29 17:34:16 +04:00
99c7a305de util.preg: Logging improved 2020-07-29 17:33:50 +04:00
4f6f17024e util.users: Logging improved 2020-07-29 17:33:09 +04:00
0d7a1e9740 util.windows: Logging improved 2020-07-29 17:30:22 +04:00
f203a48bee util.xdg: Logging improved 2020-07-29 17:29:49 +04:00
df22fe21f5 Message code lists expanded 2020-07-29 17:27:45 +04:00
c4d89921aa util.exceptions: Error metadata adjusted 2020-07-28 12:14:55 +04:00
0851f96c6f gpoa: Logging improved 2020-07-28 12:10:55 +04:00
23de5b63f6 gpupdate: Logging improved 2020-07-28 12:10:25 +04:00
6f6612862d plugin.adp: Logging improved 2020-07-28 12:10:01 +04:00
70886bd605 plugin.plugin_manager: Logging improved 2020-07-28 12:09:40 +04:00
d3caf73dac frontend.frontend_manager: Logging improved 2020-07-28 12:09:09 +04:00
551020f074 backend.samba_backend: Logging improved 2020-07-28 12:08:41 +04:00
1bf4687d41 gpt.gpt: Logging improved 2020-07-28 12:06:43 +04:00
d9afe438bc storage.sqlite_cache: Logging improved 2020-07-28 12:05:19 +04:00
067f1831ac util.arguments: Logging improved 2020-07-28 12:04:54 +04:00
fcdf3af1de util.dbus: Logging improved 2020-07-28 12:02:10 +04:00
d776cbbc7a util.kerberos: Logging improved 2020-07-28 12:01:31 +04:00
58a609f0bf util.preg: Logging improved 2020-07-28 11:59:53 +04:00
ec0d6fc81a util.windows: Logging improved 2020-07-28 11:58:23 +04:00
5d51ea63ed Storage logging improved 2020-07-27 20:11:21 +04:00
67e3a18547 Logging format changed (separator is now '|') 2020-07-27 20:07:51 +04:00
93017b2766 Structured logging improved (message list expanded) 2020-07-27 20:06:43 +04:00
18aae2995b Improved logging of plugins 2020-07-24 15:48:17 +04:00
3e2e90be5b Backend improved with numbered log messages 2020-07-24 14:02:16 +04:00
955d15622f Log message list expanded 2020-07-24 14:02:16 +04:00
4bf59442ac Log message fixes 2020-07-24 14:02:16 +04:00
749ce49bf5 Improved logging in gpoa and gpupdate utilities 2020-07-24 14:02:16 +04:00
bbb46f941f Switch to new log message format 2020-07-24 14:02:16 +04:00
d608864f8a Initial debugging improved 2020-07-24 14:02:16 +04:00
24bce0f38b Expand the list of log messages 2020-07-24 14:02:15 +04:00
NIR
efa5573d6c Merge pull request #100 from altlinux/exception_handling
util.exceptions.geterr() - function to fetch erxception information
2020-07-24 14:01:32 +04:00
118a0ad398 util.exceptions.geterr() - function to fetch erxception information 2020-07-24 14:00:42 +04:00
NIR
70af7e9504 Merge pull request #96 from altlinux/ntp_applier
NTP applier
2020-07-24 13:43:52 +04:00
NIR
7b3e2b7968 Merge pull request #94 from altlinux/firewall_applier_switch_support
Support for Windows firewall switch added
2020-07-23 17:29:13 +04:00
f22de34634 NTP applier logic fix 2020-07-23 17:22:36 +04:00
149f929616 NTP applier expanded with simple start mechanism 2020-07-21 18:54:40 +04:00
211568e345 NTP applier enabled 2020-07-20 16:13:37 +04:00
3b70363fbe NTP applier stub added 2020-07-20 16:13:28 +04:00
0cb273a7d0 Utility module for wallpapers added 2020-07-13 16:10:53 +04:00
26772794a5 GSettings applier: functionality to apply PReg settings to GSettings added 2020-07-13 16:03:39 +04:00
8219013b8a GSettingsMapping - class to map Windows registry keys to GSettings 2020-07-13 16:02:45 +04:00
eeb8c3ce52 GSettings property application mechanism fixes and expansion 2020-07-13 16:00:22 +04:00
ace949d4ec glib_map function to convert Python data to GLib (GSettings) type system 2020-07-13 15:59:10 +04:00
NIR
a37d87ae98 Merge pull request #47 from altlinux/sid_module
Module to operate on SIDs
2020-07-06 17:24:55 +04:00
63e7dab1ee Appliers for GSettings expanded with Windows key support 2020-07-03 23:41:42 +04:00
6f68917355 Apply firewall rules only if firewall is explicitly enabled 2020-07-03 18:23:42 +04:00
a6defe8c41 Support for Windows firewall switch added 2020-07-03 17:09:15 +04:00
Evgeny Sinelnikov
48532716ac 0.7.0-alt1
- Add multiple appliers, part of which marks as experimental yet
2020-07-01 01:40:53 +04:00
Evgeny Sinelnikov
e8f72eeab4 Merge pull request #93 from altlinux/kinit_check_retcode
Check kinit and kdestroy for errors
2020-07-01 01:17:16 +04:00
Evgeny Sinelnikov
5525cf014e Avoid printing about setting log level 2020-07-01 01:00:07 +04:00
Evgeny Sinelnikov
18422ff986 Set kdestroy more silent
Avoid kdestroy output like:
Other credential caches present, use -A to destroy all
2020-07-01 01:00:06 +04:00
Evgeny Sinelnikov
3c061169bc Replace KRB5CCNAME to machine_kinit() 2020-07-01 00:59:57 +04:00
883ee62017 Check kinit and kdestroy for errors 2020-06-30 21:16:29 +04:00
Evgeny Sinelnikov
adf4ca4614 Merge pull request #92 from altlinux/switch_fixes
Switch fixes
2020-06-30 20:21:53 +04:00
a36fe32e05 Fixed polkit_applier_user module experimental check 2020-06-30 20:17:31 +04:00
3b258a5b71 Module enablement flag fix 2020-06-30 20:16:02 +04:00
NIR
7a90f3c0e6 Merge pull request #79 from altlinux/firewall_applier
Firewall applier
2020-06-30 17:56:49 +04:00
272785a780 Firewall applier logging improved 2020-06-30 17:55:56 +04:00
95e2f5dbb1 Feature switch for firewall applier 2020-06-30 17:47:15 +04:00
6df2f45b89 Fastfix for port opening 2020-06-30 17:42:52 +04:00
beb3ae9359 Firewall applier working with host mode 2020-06-30 17:42:52 +04:00
0f8db2fdcb frontend.appliers.firewall_rule: fix comment length 2020-06-30 17:42:52 +04:00
12516b2a4b Firewall rule wrapper initial implementation 2020-06-30 17:42:52 +04:00
a92d6c25b9 Enabled firewall applier 2020-06-30 17:42:52 +04:00
283825ecc2 Initial firewall applier implementation 2020-06-30 17:42:51 +04:00
2369384a2a Firewall applier stub 2020-06-30 17:42:48 +04:00
NIR
d1e9c31bef Merge pull request #88 from altlinux/experimental_feature
Experimental frontend modules' switch
2020-06-30 17:40:33 +04:00
NIR
63e4dd0767 Merge pull request #91 from altlinux/fix_ownership_problem
Fix TALLOC ownership problem in PReg parser
2020-06-30 17:38:56 +04:00
d0c13547a4 Loglevel changed 2020-06-30 16:07:05 +04:00
5880ac963e Fix TALLOC ownership problem in PReg parser
This commit fixes the following error:

```
2020-06-30 00:18:25:add_hkcu_entry: S-1-5-21-1609667327-4120075585-2415302043-1109 Software\BaseALT\Policies\GPUpdate 0 4
Traceback (most recent call last):
  File "/usr/sbin/gpoa", line 145, in <module>
    main()
  File "/usr/sbin/gpoa", line 140, in main
    controller.run()
  File "/usr/sbin/gpoa", line 97, in run
    self.start_backend()
  File "/usr/sbin/gpoa", line 115, in start_backend
    back.retrieve_and_store()
  File "/usr/lib/python3/site-packages/gpoa/backend/samba_backend.py", line 71, in retrieve_and_store
    gptobj.merge()
  File "/usr/lib/python3/site-packages/gpoa/gpt/gpt.py", line 219, in merge
    preference_merger(self.storage, self.sid, preference_objects, self.name)
  File "/usr/lib/python3/site-packages/gpoa/gpt/polfile.py", line 31, in merge_polfile
    storage.add_hkcu_entry(entry, sid, policy_name)
  File "/usr/lib/python3/site-packages/gpoa/storage/sqlite_registry.py", line 242, in add_hkcu_entry
    valname = preg_entry.valuename
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd2 in position 0: invalid continuation byte
```

This is the critical bug related to ownership problem in objects
managed by LIBTALLOC which leads to object destruction and freeing the
memory used by the object (and also corruption of this memory).

It is needed to transfer memory ownership from TALLOC to Python ASAP so
we're creating Python-managed object and copy the data into it.
2020-06-30 00:51:05 +04:00
d4119b47d4 Fixes for module checks 2020-06-29 21:18:29 +04:00
daf074d8dd frontend_manager logging removed due to redundancy 2020-06-29 20:07:22 +04:00
e1df2dde54 chromium applier logging improved 2020-06-29 20:06:55 +04:00
e8c71aa913 cifs applier logging improved 2020-06-29 20:06:39 +04:00
3a16e6eb7e control applier logging improved 2020-06-29 20:06:23 +04:00
44ec5ecc93 cups applier logging improved 2020-06-29 20:06:05 +04:00
0352da6d58 firefox applier logging improved 2020-06-29 20:05:44 +04:00
ac2ec348f2 folder applier fixes and logging improvements 2020-06-29 20:05:28 +04:00
fadd7de447 gsettings applier fixes and logging improvement 2020-06-29 20:05:03 +04:00
7c753098cd package applier fix and logging improved 2020-06-29 20:04:30 +04:00
28637d099b polkit applier logging improved 2020-06-29 20:04:06 +04:00
e4f17f2704 shortcut applier logging improved 2020-06-29 20:03:45 +04:00
1be13ea8ed systemd applier logging improved 2020-06-29 20:03:23 +04:00
59743d7957 Return result! 2020-06-29 18:55:51 +04:00
Evgeny Sinelnikov
2d27c5580a Merge pull request #90 from altlinux/hkcu_fix
sqlite_registry: Fixed samba_hkcu_preg mapping in query
2020-06-29 17:06:21 +04:00
23983f7316 sqlite_storage.get_hkcu_entry() 2020-06-29 16:59:30 +04:00
b616221562 sqlite_registry: Fixed samba_hkcu_preg mapping in query 2020-06-29 16:22:53 +04:00
292fd9238c frontend: Bunch of fixes to make it work 2020-06-29 16:21:17 +04:00
36d0a92247 frontend: All-in-one fixes for module switches 2020-06-29 12:59:22 +04:00
f680a3025e cups_applier: Run only if it is enabled 2020-06-26 20:18:23 +04:00
41f49e5bab firefox_applier: Run only if it is enabled 2020-06-26 20:17:45 +04:00
f5b94ed02d folder_applier: Run only if it is enabled 2020-06-26 20:17:09 +04:00
98b7346bf1 gsettings_applier: Run only if it is enabled 2020-06-26 20:16:44 +04:00
f275583874 shortcut_applier: Run only if it is enabled 2020-06-26 20:16:13 +04:00
7f8d495b1b systemd_applier: Run only in case it is enabled 2020-06-26 20:07:28 +04:00
00c1aaeb55 control_applier: Run module only in case it is enabled 2020-06-26 20:06:56 +04:00
08a09eca81 .gitignore updated 2020-06-26 18:30:06 +04:00
02aa2cdbc6 firefox_applier: Check if module is enabled via group policy 2020-06-26 18:29:23 +04:00
f460ba3ae6 cups_applier: Check if module is enabled via group policy 2020-06-26 18:28:58 +04:00
917f1b27fb control_applier: Check if module is enabled via group policy 2020-06-26 18:28:34 +04:00
9121534de3 folder_applier: Check if module is enabled via group policy 2020-06-26 18:27:47 +04:00
8230781e3d cifs_applier: Check if module is enabled via group policy 2020-06-26 18:27:03 +04:00
db200e2668 package_applier: Check if module is enabled via policy 2020-06-26 18:08:11 +04:00
a74e29d335 polkit_applier: Check if module is enabled via policy 2020-06-26 18:01:04 +04:00
023739444b shortcut_applier: Check if module is enabled via policy 2020-06-26 17:59:22 +04:00
eb8cf25690 systemd_applier: Check if module is enabled via policy 2020-06-26 17:58:16 +04:00
c0a2b13da5 cifs_applier: Check if module is enabled via policy 2020-06-26 17:56:59 +04:00
1f09cb2c2d chromium_applier: Check if module is enabled via policy 2020-06-26 17:55:58 +04:00
08abbc57a9 Frontend functions to check for experimental modules added 2020-06-26 17:52:43 +04:00
NIR
8c87a22ac0 Merge pull request #77 from altlinux/error_codes
Error codes
2020-06-26 14:34:23 +04:00
Evgeny Sinelnikov
343ef0d9ff Merge pull request #85 from altlinux/krb5_fix
gpoa: Fixed KRB5CCNAME usage
2020-06-25 21:03:23 +04:00
7f88857227 gpoa: Fixed KRB5CCNAME usage 2020-06-25 20:36:11 +04:00
Evgeny Sinelnikov
d155769cda Merge pull request #83 from altlinux/polkit_user
Add user policy implementation for deny all removable storages
2020-06-25 19:25:48 +04:00
NIR
3d1d21ffa1 Merge pull request #84 from altlinux/krb5cache_destroy
KRB5CCACHE destroy
2020-06-25 17:00:25 +04:00
21f4d9514e Improved SIGINT handling mechanism 2020-06-25 16:06:55 +04:00
49f900b2a9 gpoa: Use KRB5CCNAME implicitly 2020-06-25 14:57:42 +04:00
2803d2be72 Remove Kerberos 5 credential cache on interrupt 2020-06-25 14:45:47 +04:00
9bc426fa0c util.kerberos: Update for old Python3 compatibility 2020-06-25 14:39:01 +04:00
6f5db26688 Install cache directory for credentials 2020-06-25 14:33:15 +04:00
fa8c50f665 gpoa: Perform kdestroy on finish 2020-06-25 13:39:29 +04:00
02e4da1758 util.kerberos: machine_kdestroy() introduced, used specific krb5 cache path 2020-06-25 13:38:30 +04:00
NIR
004fc38962 Merge pull request #81 from altlinux/printer_applier
Enable Printers.xml parser and merger
2020-06-25 13:24:18 +04:00
Rustem Bapin
1d3f4feec9 Add user policy implementation for deny all removable storages 2020-06-25 11:39:31 +04:00
20bafa3e58 Multiple fixes for CUPS applier 2020-06-23 16:29:26 +04:00
c0d82c6d22 gpt.gpt: Enable printer settings search 2020-06-23 16:29:13 +04:00
Evgeny Sinelnikov
17e65a680d Merge pull request #82 from altlinux/autofs_use_correct_variable
Use USER variable instead of unstable AUTOFS_UID
2020-06-08 16:49:21 +04:00
76308961bd autofs: Ignore local permissions 2020-06-08 16:48:23 +04:00
1a1442386d Use USER variable instead of unstable AUTOFS_UID 2020-06-08 16:42:48 +04:00
158240614f cups_applier: Use pycups to manage printer connection 2020-06-04 19:20:48 +04:00
923bf039bf Enable Printers.xml parser and merger 2020-06-04 19:20:48 +04:00
NIR
bfd383659f Merge pull request #78 from altlinux/packages_nir
Another package install implementation
2020-06-04 19:16:03 +04:00
94e2c5fb59 Fixed package abstration object 2020-06-04 19:14:41 +04:00
433f4c063e Printer search disabled due to missing implementation 2020-06-04 19:13:14 +04:00
455bcf727b Package applier for user imported to frontend manager 2020-06-04 19:11:16 +04:00
7713e3c460 Package applier adjusted to work with multiline package entries 2020-06-04 19:10:41 +04:00
1cc6dbb784 Multiple fixes for package applier 2020-05-29 18:40:46 +04:00
319e0fcf1d Wiki index updated 2020-05-28 14:28:19 +04:00
b5b6fe7478 User part of package applier implemented 2020-05-25 18:28:54 +04:00
8132622866 frontend.appliers.rpm removed 2020-05-25 18:28:31 +04:00
3af33dca4b util.rpm.install_rpm(): Don't update package database implicitly 2020-05-25 18:20:28 +04:00
Rustem Bapin
6c06638138 Use apt-shell for install/remove packages
Add small unit test
2020-05-25 18:19:05 +04:00
Rustem Bapin
d9cad51f52 Add packages installation/removing 2020-05-25 18:19:02 +04:00
NIR
400ea0aced Merge pull request #75 from altlinux/folder_applier
Applier for Folders.xml
2020-05-25 16:10:25 +04:00
4fb6f83eb1 folder_applier enabled 2020-05-22 22:06:45 +04:00
0f6851601a folder_applier: Basic functionality implemented 2020-05-22 22:06:44 +04:00
89412cc8e4 frontend.appliers.folder - Folder object added for frontend 2020-05-22 22:06:44 +04:00
580bc0c6b2 gpt.folders - FileAction expanded to mention all CRUD operations 2020-05-22 22:06:36 +04:00
Evgeny Sinelnikov
1332409dc2 Merge pull request #74 from altlinux/backend_refactoring
Backend refactoring
2020-05-22 20:28:04 +04:00
b6fb9abfa1 gpupdate: Use new messaging mechanism
This will allow user to see coded messages like:

```
[E00001]: Insufficient permissions to run gpupdate
[E00002]: gpupdate will not be started
```

Now you may easily refer to the specific error code/message when asking
for technical support.
2020-05-22 03:42:41 +04:00
7941157235 Introduce new messaging mechanism
The logging mechanism of gpupdate is in poor state at the moment.
This commit introduces Oracle-style messages with codes. The messages
are not format strings and may be easily localized and it is also
easy to refer to specific problem.

The original idea is to permanently assign error codes only expanding
code lists during time in order to deliver reliable product.
2020-05-22 03:38:49 +04:00
cb38da0e09 Frontend manager: Running machine appliers made a little bit more flexible
At the start of the project the demands were pretty simple and the
functionality required was rather restricted. Now we have some
architecture and demands are growing accordingly so this commit
eliminated hardcode in favor of iteration over flexible lists.
2020-05-21 16:48:08 +04:00
2b86ab87eb gpt.gpt: More modular approach to scanning GPT
At start I thought I will need to implement only one PReg
parser/interpreter and that's it. At the moment it is demanded all
parser to be implemented, all GPT settings covered and ADMX files to
be extended to work with Linux (ALT) specific cases.

Now I have more expertise in the domain so this PR doint simple thing
despite lots of code:

* There is "parser" for each file type in corresponding module.
* There is also "merger" for each object parsed from file in
  corresponding module.

We're doing this:

* Determine file type by its name (stupid and working!)
* Call the corresponding parser to get objects
* Call the corresponding merger for objects
2020-05-21 16:48:08 +04:00
6325382155 gpt.gpt: Eliminated unused functions
This commit fixes the problem of multiple unused functions in GPT
lurker. The most strange function here is obviously __str__ which was
used for testing purposes in early days but made obsolete because of
introduction of unit testing.
2020-05-21 16:48:08 +04:00
1665ab92f3 gpt.gpt: Use simplified settings search function 2020-05-21 16:48:08 +04:00
773b8d032f Implemented parser and merger for Folders.xml 2020-05-21 16:48:07 +04:00
6b8a1a4d0b gpt.drives: Drives merger implemented 2020-05-21 16:48:07 +04:00
59f2b3703f gpt.shortcuts: Shortcuts merger implemented 2020-05-21 16:48:07 +04:00
4892843c52 gpt.*: merger stubs implemented 2020-05-21 16:48:07 +04:00
61eec97b68 gpt.tasks: ScheduledTasks.xml parser and merger stub implemented 2020-05-21 16:48:07 +04:00
0696b68085 gpt.polfile: Polfile parser and merger implemented as part of GPT 2020-05-21 16:48:07 +04:00
c67e3b7674 gpt.gpt: Introduced functions to find file in Preferences directory
During research done about Active Directory and GPTs I found out that
There is no need for specialized search functions for each type of
Preference and GPTs has pretty simple structure so I implemented the
generalized way to find yet another XML file in "Preferences" directory.
2020-05-21 16:48:07 +04:00
9592100218 util.preg.merge_polfile(): Pass policy_name
The renewed storage requires Policy Name to be passed as well. This is
needed to simplify debugging of GPT merging problems.
2020-05-21 16:48:06 +04:00
1fab02a274 sqlite_registry: General refactoring
There were tons of duplicated code in storage related to object wipe
and upsert functionality. In general, all this commit does - duplicate
code elimination.

It is also `add_folder()` function added in order to store Folder.xml
object in the database.
2020-05-21 16:45:55 +04:00
c765077b2f storage.record_types: folder_entry added and general refactoring
The new architecture demands "Policy Name" to be passed along with
GPT object in order to ease debugging of GPT merge problems so
this commit introduces additional parameter to constructor of each
record type.

It is also `folder_entry` record type added.

During rework of large part of code I found out that lots of upsert
code were duplicated and contained update row constructors for
SQLAlchemy. I decided that record objects may know which fields it
is needed to update in case of UPDATE calls so I introduced
`update_fields()` function which returns update dictionary thus making
hardcoded row constructors in `sqlite_storage` obsolete.
2020-05-21 16:41:10 +04:00
Evgeny Sinelnikov
baafb18971 Merge pull request #68 from altlinux/wipe_logic_fix
Wipe logic fix
2020-05-21 15:54:30 +04:00
8b7e8547e6 Catch exceptions from backend 2020-05-21 15:46:04 +04:00
19cb5c072a util.windows: Re-raise exceptions when working with domain
This is needed to prevent wipe of settings done by backend in case of
successful GPO retrieval by Samba. This commit re-raises exceptions
which must be caught by backend runner in `gpoa`.
2020-05-21 15:44:46 +04:00
Evgeny Sinelnikov
a4607c75eb Remove duplicated requires to local-policy from spec 2020-05-20 20:51:19 +04:00
Evgeny Sinelnikov
c6f0397f51 0.6.0-alt2
- Update system-policy PAM-rules (clean system-auth-common, add pam_env support)
- Add dependency to pam-config later than 1.9.0 release
2020-05-20 01:06:28 +04:00
Evgeny Sinelnikov
01c7e29a87 0.6.0-alt1
- Add drives policy for shared folders with cifs applier using autofs
- Update shortcuts policy with xdg-users-dir support for DESKTOP
2020-05-15 23:29:18 +04:00
NIR
d36b92e49f Merge pull request #64 from altlinux/get_localized_desktop
Get localized path to Desktop directory
2020-05-15 23:06:03 +04:00
Evgeny Sinelnikov
62f3c5dd96 Fix xdg-users-dirs getting for shortcuts 2020-05-15 22:57:51 +04:00
Evgeny Sinelnikov
2f3fb8810e gpt/shortcuts: fix getting iconPath from properties 2020-05-15 19:33:58 +04:00
Evgeny Sinelnikov
9ac94df0b5 shortcut_applier: skip shortcut with no substituted variables 2020-05-15 18:47:38 +04:00
Evgeny Sinelnikov
43c1728a43 shortcut_applier: append HOME substitution to path if it not absolute 2020-05-15 18:46:44 +04:00
Evgeny Sinelnikov
5de5ad9801 Merge pull request #67 from altlinux/wipe_drives
Wipe drives along with other tables
2020-05-15 15:51:07 +04:00
05f13610bf Wipe drives along with other tables 2020-05-15 00:37:32 +04:00
8fce5e7dd6 Strange fixes for shortcut address resolution 2020-05-15 00:13:27 +04:00
ee81010f82 Added icon name support for .desktop files 2020-05-14 23:37:32 +04:00
Evgeny Sinelnikov
9d40910890 Merge pull request #59 from altlinux/share_automount
Autofs/CIFS applier for mounting Samba shares
2020-05-14 23:27:02 +04:00
8b322748a7 CIFS applier file cleanup 2020-05-14 23:20:12 +04:00
338cc5d80f Don't generate autofs configuration if no drive mappings present 2020-05-14 22:57:17 +04:00
8c88f825dc cifs_applier: restart autofs daemon on configuration change 2020-05-14 22:19:53 +04:00
047d72dbd1 Added autofs dependency for CIFS applier 2020-05-14 22:18:31 +04:00
70c233a0df Add newline when writing to /etc/auto.master 2020-05-14 22:12:02 +04:00
e864235761 autofs templates' fixes 2020-05-14 21:53:39 +04:00
7d01e331fe cifs_applier typo fixes 2020-05-14 21:53:12 +04:00
ccd429a632 CIFS applier imporved with map support 2020-05-14 21:30:24 +04:00
e6d9867443 Fixed storage upsert for drives 2020-05-14 21:29:56 +04:00
87f21867f6 Drives.xml parser improved 2020-05-14 21:29:18 +04:00
f3b1b68f87 Drives.xml finding mechanism improvement 2020-05-14 21:28:49 +04:00
5012917412 autofs templates expanded 2020-05-14 21:28:08 +04:00
816c40ce40 cifs_applier: Fixed template name 2020-05-14 19:46:06 +04:00
6843690340 gpupdate_mount template 2020-05-14 19:39:53 +04:00
b3fa7f2868 cifs_applier: get_homedir imported 2020-05-14 19:33:21 +04:00
6d45289e1a gpt.gpt: Don't check if path exists 2020-05-14 19:24:12 +04:00
fd7fc8cb1f cifs_applier: Expand variables for templating 2020-05-14 19:03:22 +04:00
5f516d2726 cifs_applier: Imported missing 'os' module 2020-05-14 18:52:58 +04:00
6d3904ea93 Password decryption for Drives.xml fixed 2020-05-14 18:52:16 +04:00
fd42505f33 CIFS applier refactored 2020-05-14 18:17:08 +04:00
Evgeny Sinelnikov
1762a23a22 Merge pull request #62 from altlinux/exclude_tests
Excludes for unit tests added
2020-05-14 17:02:43 +04:00
6170a0dd85 util.xdg.xdg_get_desktop_user(): Function to resolve localized path to Desktop directory 2020-05-14 16:11:08 +04:00
087248d172 util.windows.expand_windows_var(): The default(machine) HOME is /etc/skel 2020-05-14 16:02:48 +04:00
2bd533acb8 util.users.with_privileges(): return function result 2020-05-14 16:02:01 +04:00
d96b28025d Fix typo in Drives.xml parser 2020-05-12 22:48:17 +04:00
d240ff2542 CIFS applier implemented 2020-05-12 22:43:13 +04:00
a12d771efd Excludes for unit tests added 2020-05-12 01:15:49 +04:00
bf22d58139 Unit test for Drives.xml parser 2020-05-12 01:08:11 +04:00
963fd22f83 CIFS applier enabled in frontend manager 2020-05-12 00:26:43 +04:00
2053e26c53 CIFS applier stub implemented 2020-05-12 00:26:26 +04:00
4d28a42120 Storage expanded to work with drives 2020-05-12 00:26:04 +04:00
bf9eeb22eb Drive.xml parser expanded 2020-05-12 00:25:33 +04:00
Evgeny Sinelnikov
ad3624d73e Merge pull request #53 from altlinux/active_policy
gpupdate-setup: add default-policy and update active-policy commands
2020-05-06 23:21:15 +04:00
Evgeny Sinelnikov
957823b264 gpupdate-setup: fix active directory domain controller detection 2020-05-06 23:06:23 +04:00
4f1c45970c storage.record_types: Stub for drive record added 2020-05-06 13:43:52 +04:00
bfb68aa483 storage.sqlite_registry: Table for Drive mappings added 2020-05-06 13:43:27 +04:00
fc7cc603cf CIFS applier slightly expanded 2020-05-06 13:42:42 +04:00
4e57823983 gpt.gpt: Functionality to find Drives.xml added 2020-05-06 13:40:54 +04:00
faf9e9a8cf Stub for autofs/CIFS applier 2020-04-28 16:47:06 +04:00
NIR
0328afa788 Merge pull request #55 from altlinux/rpm_install_improvement
RPM helper improved
2020-04-28 00:10:27 +04:00
edead53d7e RPM test improved accordingly 2020-04-28 00:07:04 +04:00
db1a82f930 util.rpm: Removed strange and ugly functions and introduced simple functions instead 2020-04-28 00:02:27 +04:00
fd7cfe2b83 util.rpm: Package.reinstall() command added 2020-04-28 00:01:46 +04:00
b3694a8b4d RPM module improved with corner case checks 2020-04-24 15:19:28 +04:00
060f125258 Half-assed test for RPM 2020-04-24 15:18:51 +04:00
1f4960cb48 RPM helper improved 2020-04-23 23:10:08 +04:00
Evgeny Sinelnikov
9bcff54817 gpupdate-setup: add default-policy and update active-policy commands
Command active-policy revert only name now and "unknown" if policy is not setted.
2020-04-23 01:19:20 +04:00
Evgeny Sinelnikov
a0c5b1a2b1 Merge pull request #45 from altlinux/preg_key_deletion
Skip branch deletion keys
2020-04-23 01:14:16 +04:00
Evgeny Sinelnikov
2f7e6f3a98 0.5.0-alt1
- Update samba format: local.xml -> Machine/Registry.pol.xml
- Add support of ad-domain-controller local policy profile
- Set properly URL of project
2020-04-22 00:54:48 +04:00
Evgeny Sinelnikov
393529f0af Merge pull request #46 from altlinux/proper_dist
Proper dist as installation directory
2020-04-22 00:43:33 +04:00
Evgeny Sinelnikov
ccf73c4fc6 Merge pull request #51 from altlinux/gpupdate_suppress
Suppress extra output of gpupdate-setup
2020-04-22 00:37:51 +04:00
Evgeny Sinelnikov
a7aa12d42d Merge pull request #49 from altlinux/samba_format
Samba format: local.xml -> Machine/Registry.pol.xml
2020-04-22 00:36:15 +04:00
Evgeny Sinelnikov
d12d4c4227 Merge pull request #52 from altlinux/gpoa_fixes_for_server
Bunch of fixes for bugs found while testing GPOA on ALT Server
2020-04-22 00:32:00 +04:00
e8833ddee0 There were two systemctl calls in gpupdate-setup 2020-04-21 23:58:05 +04:00
18e1911bb5 desktop-file-utils is missing from ALT Server by default 2020-04-21 23:56:43 +04:00
fa34dc9e96 python3-module-dbus does not added to dependencies automatically 2020-04-21 23:56:11 +04:00
34ed296546 Set GPOA loglevel to FATAL in gpupdate-setup 2020-04-21 23:41:25 +04:00
Evgeny Sinelnikov
8b63d294d3 gpupdate-setup: fix break symlink recreate during enable 2020-04-21 23:14:10 +04:00
Evgeny Sinelnikov
d38e937e22 gpupdate-setup: add support domain_controller local policy profile 2020-04-21 22:20:14 +04:00
Evgeny Sinelnikov
c70280a964 Get machine local Registry policy in Samba backup format 2020-04-21 22:20:14 +04:00
41e950172b Created directory for temporary testing files 2020-04-21 22:17:35 +04:00
8c7d106191 Module to operate on SIDs 2020-04-21 22:07:36 +04:00
25381e1a04 Updated specfile to install supplementary files from ./dist 2020-04-21 21:01:11 +04:00
f7233c539e Moved system-policy-gpupdate to ./dist 2020-04-21 20:58:49 +04:00
0b3c004d0b Moved gpupdate.service to ./dist 2020-04-21 20:58:20 +04:00
ac37d736cb Moved gpupdate-user.service to ./dist 2020-04-21 20:57:54 +04:00
91da6ff912 test.storage.test_preg_special_values - half-assed unit test for starred PReg value names 2020-04-21 20:47:21 +04:00
ae7d1ed0dc util.merge_polfile(): accept registry name and path to ease testing 2020-04-21 20:46:32 +04:00
ce0e3f1901 storage.registry_factory(): accept target registry directory 2020-04-21 20:45:51 +04:00
edfca0e31d storage.sqlite_registry: Accept target registry directory 2020-04-21 20:45:01 +04:00
77da991c6f storage.sqlite_registry: use record types from separate module 2020-04-21 20:42:43 +04:00
d61583e704 Storage testing module created 2020-04-21 20:41:23 +04:00
1d31f17bb3 Records from sqlite_registry moved into separate module to ease testing and adding storages 2020-04-21 20:40:33 +04:00
3276be53cc Testing data for storage added 2020-04-21 20:39:45 +04:00
442e7986d5 Skip branch deletion keys 2020-04-21 19:08:03 +04:00
Evgeny Sinelnikov
faa0265fd7 Merge pull request #44 from altlinux/gpupdate_setup_fix
Correct systemctl run for global enable gpupdate-user.service
2020-04-21 14:13:10 +04:00
0150e60f3d Correct systemctl call 2020-04-21 12:29:33 +04:00
Evgeny Sinelnikov
7572fa1ed7 0.4.5-alt1
- Add support for control system-policy and requires to new pam-config
2020-04-20 03:13:23 +04:00
Evgeny Sinelnikov
1fa9b67fb2 Correctly enable and disable system-policy for gpupdate 2020-04-20 03:13:10 +04:00
Evgeny Sinelnikov
0be9e4b317 0.4.4-alt1
- Add gpupdate-setup initialization script supported local-policy profiles
2020-04-19 12:45:42 +04:00
Evgeny Sinelnikov
c16312161f Merge pull request #41 from altlinux/gpsetup
Ok, prepare to new prerelease.
2020-04-16 20:49:40 +04:00
Evgeny Sinelnikov
ed9477c0fc gpupdate-setup: adjust get_active_policy() 2020-04-16 15:56:08 +04:00
Evgeny Sinelnikov
75485eeb62 gpupdate-setup: get default localpolicy from /etc/altlinux-release 2020-04-16 06:31:45 +04:00
Evgeny Sinelnikov
633637bee2 gpupdate-setup: add enable and disable actions 2020-04-16 06:29:41 +04:00
Evgeny Sinelnikov
7d46cd69e0 Add version requires to libnss-role and local-policy 2020-04-16 04:33:00 +04:00
Evgeny Sinelnikov
2901f54830 Replace os.system with checked call of subprocess 2020-04-16 04:16:30 +04:00
Evgeny Sinelnikov
8f349a96c7 gpupdate-setup: set status as default action 2020-04-16 04:15:13 +04:00
ebbdf7c033 Fixed symlink update functionality 2020-04-14 16:08:06 +04:00
4e8888086f Added check for /etc/local-policy path for gpupdate 2020-04-14 16:07:32 +04:00
2571e27235 gpsetup 2020-04-03 19:01:38 +04:00
207b7eb029 Minifix for testing policy existence 2020-03-27 15:50:09 +04:00
5668dae81e gpupdate-setup updated with interface for backend 2020-03-26 17:10:33 +04:00
ce9891802f gpupdate-setup installed in /usr/sbin 2020-03-23 16:14:25 +04:00
d0ff27c45c gpupdate-setup script added to atomize actions of Group Policy switch 2020-03-23 16:07:18 +04:00
Evgeny Sinelnikov
e66f1fd5a4 0.4.3-alt1
- Fix polfile merging
- Add support controls with strings values
- Initial SIGINT signal handling
2020-03-06 19:30:13 +04:00
Evgeny Sinelnikov
c383631fde Merge pull request #39 from altlinux/initial_signal_handling
Initial signal handling tested.
2020-03-06 19:05:43 +04:00
Evgeny Sinelnikov
b519249aff Merge pull request #38 from altlinux/controls_with_strings_testing
Controls with strings testing tested.
2020-03-06 19:05:14 +04:00
b52c14a66f Signal handlers for gpoa and gpupdate introduced 2020-03-06 18:57:31 +04:00
c205940b08 Signal handling function introduced 2020-03-06 18:57:04 +04:00
a4e2b3638d New exit code value introduced 2020-03-06 18:56:41 +04:00
34344d66d8 Unit test for out-of-range control 2020-03-06 18:43:23 +04:00
32d7546a5a Numerous Popen fixes in control applier
This commit fixes errors caused by missed .wait() in Popen calls like:

```
/usr/lib64/python3.7/subprocess.py:858: ResourceWarning: subprocess 4955 is still running
  ResourceWarning, source=self)
ResourceWarning: Enable tracemalloc to get the object allocation traceback
/mnt/sda1/github.com/gpupdate/gpoa/frontend/appliers/control.py:30: ResourceWarning: unclosed file <_io.BufferedReader name=3>
  self.possible_values = self._query_control_values()
ResourceWarning: Enable tracemalloc to get the object allocation traceback
```
2020-03-06 16:08:13 +04:00
d63740f5de Basic (non-unit) tests added for controls 2020-03-06 16:06:50 +04:00
Rustem Bapin
c4197da64f Control applier is not breaking in case input value is not in possible values 2020-03-05 19:43:40 +04:00
056554c35c Fix service state handling
This commit fixes error on `gpupdate.service` unit start:

```
Unable to start systemd unit gpupdate.service
```

This error was caused by limited functionality on handling unit
states, especially for restartable units.
2020-03-04 16:24:46 +04:00
Rustem Bapin
d9bd6f663b Control applier handle both number and string values 2020-03-03 21:16:11 +04:00
NIR
ae156bcb92 Merge pull request #34 from altlinux/dbus_exception_catch
D-Bus exception catch
2020-03-03 19:20:48 +04:00
71107f72f7 Catch DBusException in dbus_runner when reply is timed out
When we try to start `oddjobd` via `D-Bus` using gpupdate we may
get the following traceback:

```
Traceback (most recent call last):
  File "/usr/bin/gpupdate", line 144, in <module>
    main()
  File "/usr/bin/gpupdate", line 139, in main
    gpo_appliers[1].run()
  File "/usr/lib/python3/site-packages/gpoa/util/dbus.py", line 48, in run
    result = self.interface.gpupdate()
  File "/usr/lib64/python3/site-packages/dbus/proxies.py", line 72, in __call__
    return self._proxy_method(*args, **keywords)
  File "/usr/lib64/python3/site-packages/dbus/proxies.py", line 147, in __call__
    **keywords)
  File "/usr/lib64/python3/site-packages/dbus/connection.py", line 653, in call_blocking
    message, timeout)
dbus.exceptions.DBusException: org.freedesktop.DBus.Error.NoReply: Did not receive a reply. Possible causes include: the remote application did not send a reply, the message bus security policy blocked the reply, the reply timeout expired, or the network connection was broken.
```

This commit catches this traceback, re-raises the exception and
establishes contract for `gpupdate` utility exit codes on fatal errors.
2020-03-03 19:18:56 +04:00
17411de005 Wiki submodule index bump 2020-03-03 17:22:19 +04:00
7ae1912455 gpupdate exit codes documented in manpage 2020-03-03 17:21:53 +04:00
7fbd1a3c40 gpt.gpt: Polfile merging quickfix 2020-03-03 17:20:50 +04:00
7b856f3d44 util.arguments.ExitCodeUpdater: Exit code contract for gpupdate utility 2020-03-03 17:18:34 +04:00
44b51fd05c .gitignore updated 2020-03-03 17:17:51 +04:00
Evgeny Sinelnikov
2778e2a043 0.4.2-alt1
- Change service type to 'simple' because gpoa is not systemd-aware
- Shortcuts fixes and improvements
2020-02-19 16:35:25 +04:00
Evgeny Sinelnikov
44f68020c5 Merge pull request #24 from altlinux/shortcuts_testing
Shortcuts fixes and improvements
2020-02-19 16:32:44 +04:00
Evgeny Sinelnikov
9ab8f41b77 Merge pull request #26 from altlinux/systemd_start_fixes
Change service type to 'simple' because gpoa is not systemd-aware
2020-02-19 16:31:33 +04:00
17467b5488 shortcut_applier: Don't try to operate on non-existent home directory for user 2020-02-19 16:09:15 +04:00
8c42f00f89 util.util: homedir_exists to check if home directory is created for user 2020-02-19 16:08:30 +04:00
a60a9d6b94 Fix for directory entry types in gpt.gpt 2020-02-19 15:23:54 +04:00
285fdae5e6 gpt.gpt: Find shortcuts and other directories without workarounds 2020-02-18 14:30:06 +04:00
be38594d07 gpt.shortcuts: Added functionality to store .desktop file type 2020-02-18 14:27:52 +04:00
fbc90b7e88 gpt.gpt: find_file improvement for cases when no root directory passed 2020-02-18 14:26:50 +04:00
a3172af037 gpt.gpt: find_dir for case-insensitive search for directory 2020-02-18 14:25:57 +04:00
6130973a09 ttype2str: function to transform TargetType object into string for JSON 2020-02-17 19:07:28 +04:00
5bcc38f80a Use RestartSec since gpupdate is not systemd-aware 2020-02-14 18:41:08 +04:00
d1cbba1834 Implement REAL unit test for shortcuts 2020-02-14 16:18:38 +04:00
33e7417811 Disable role module test 2020-02-14 16:16:53 +04:00
0c0caa4906 Fix for shortcut processor after unit-test 2020-02-14 16:16:53 +04:00
a384991be0 Test for shortcut of Type=Link added 2020-02-14 16:16:45 +04:00
38e70647f7 Unnecessary test removed 2020-02-14 16:16:13 +04:00
59ccecd457 Shortcuts fixes and improvements
- It was found that shortcut files must be executable in order to
  work correctly
- Added some checks for URL links. This should allow to create
  links pointing to network shares.
2020-02-14 16:16:07 +04:00
28da08eb24 Change service type to 'simple' because gpoa is not systemd-aware 2020-02-13 18:26:42 +04:00
Evgeny Sinelnikov
4c5aa6bc7f 0.4.1-alt1
- Update license to GPLv3+
- Run gpudate as root without user argument for Computer target only
- Fix chromium applier
2020-02-12 19:52:40 +04:00
NIR
88ef8359f7 Merge pull request #25 from altlinux/gpupdate_username_fix
Fix for 'None' username dropping to runner_factory
2020-02-12 18:20:49 +04:00
NIR
0a6d65790d Merge pull request #19 from altlinux/wiki_submodule
GitHub wiki added as submodule
2020-02-12 18:20:04 +04:00
24e32f5790 Fix for 'None' username dropping to runner_factory 2020-02-12 17:49:46 +04:00
Evgeny Sinelnikov
003848e0bf Merge pull request #18 from altlinux/license_upgrade_for_samba_deps
License upgrade for samba deps
2020-02-11 19:58:59 +04:00
Evgeny Sinelnikov
409a888e9f Merge pull request #14 from altlinux/chromium_fix
Chromium fix
2020-02-11 19:54:14 +04:00
f6c42c5f0b License updated in ALT specfile 2020-02-11 19:52:10 +04:00
0ac3b54b81 GitHub wiki added as submodule 2020-02-11 15:29:44 +04:00
9fff2e33d1 Source files licensing information changed 2020-02-11 15:23:09 +04:00
0c8846b538 Licensing information added to Jinja2 template 2020-02-11 15:13:55 +04:00
7ad0b4276e License added to manpages 2020-02-11 15:12:28 +04:00
57d62a04ca License changed to GPLv3+ in README.md 2020-02-11 15:11:48 +04:00
a631ea1c3e License file changed to contain GPLv3+
This change is needed because we use parts of Samba which is in turn
licensed as GPLv3+ project and is incompatible with GPLv2+ licensed
code.

This problem is reported by Alexander Bokovoy (ab at samba.org).
2020-02-11 15:08:07 +04:00
NIR
eb9a801b32 Merge pull request #16 from altlinux/license_file
License file
2020-02-05 16:08:43 +04:00
NIR
32e112dcf1 Merge pull request #17 from altlinux/mailing_list
Contributing information added
2020-02-05 16:08:25 +04:00
327b46d4e0 Contributing information added 2020-02-05 15:57:34 +04:00
fa259d9db9 LICENSE.md added 2020-02-04 20:05:51 +04:00
9e397770c3 chromium_applier: Homepage retrieval fix (reported by ekorneechev@basealt.ru) 2020-01-30 15:40:04 +04:00
d0bf345554 chromium_applier: Changed HKLM key path in accordance with Chromium ADMX 2020-01-30 15:38:43 +04:00
133 changed files with 7176 additions and 1163 deletions

4
.gitignore vendored
View File

@@ -1,2 +1,6 @@
__pycache__
*~
_opam
_build
*.pyc

3
.gitmodules vendored Normal file
View File

@@ -0,0 +1,3 @@
[submodule "wiki"]
path = wiki
url = https://github.com/altlinux/gpupdate.wiki.git

596
LICENSE.md Normal file
View File

@@ -0,0 +1,596 @@
GNU General Public License
==========================
_Version 3, 29 June 2007_
_Copyright © 2007 Free Software Foundation, Inc. &lt;<http://fsf.org/>&gt;_
Everyone is permitted to copy and distribute verbatim copies of this license
document, but changing it is not allowed.
## Preamble
The GNU General Public License is a free, copyleft license for software and other
kinds of works.
The licenses for most software and other practical works are designed to take away
your freedom to share and change the works. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change all versions of a
program--to make sure it remains free software for all its users. We, the Free
Software Foundation, use the GNU General Public License for most of our software; it
applies also to any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General
Public Licenses are designed to make sure that you have the freedom to distribute
copies of free software (and charge for them if you wish), that you receive source
code or can get it if you want it, that you can change the software or use pieces of
it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or
asking you to surrender the rights. Therefore, you have certain responsibilities if
you distribute copies of the software, or if you modify it: responsibilities to
respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee,
you must pass on to the recipients the same freedoms that you received. You must make
sure that they, too, receive or can get the source code. And you must show them these
terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: **(1)** assert
copyright on the software, and **(2)** offer you this License giving you legal permission
to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is
no warranty for this free software. For both users' and authors' sake, the GPL
requires that modified versions be marked as changed, so that their problems will not
be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of
the software inside them, although the manufacturer can do so. This is fundamentally
incompatible with the aim of protecting users' freedom to change the software. The
systematic pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we have designed
this version of the GPL to prohibit the practice for those products. If such problems
arise substantially in other domains, we stand ready to extend this provision to
those domains in future versions of the GPL, as needed to protect the freedom of
users.
Finally, every program is threatened constantly by software patents. States should
not allow patents to restrict development and use of software on general-purpose
computers, but in those that do, we wish to avoid the special danger that patents
applied to a free program could make it effectively proprietary. To prevent this, the
GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
## TERMS AND CONDITIONS
### 0. Definitions
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this
License. Each licensee is addressed as “you”. “Licensees” and
“recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in
a fashion requiring copyright permission, other than the making of an exact copy. The
resulting work is called a “modified version” of the earlier work or a
work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on
the Program.
To “propagate” a work means to do anything with it that, without
permission, would make you directly or secondarily liable for infringement under
applicable copyright law, except executing it on a computer or modifying a private
copy. Propagation includes copying, distribution (with or without modification),
making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through a computer
network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the
extent that it includes a convenient and prominently visible feature that **(1)**
displays an appropriate copyright notice, and **(2)** tells the user that there is no
warranty for the work (except to the extent that warranties are provided), that
licensees may convey the work under this License, and how to view a copy of this
License. If the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
### 1. Source Code
The “source code” for a work means the preferred form of the work for
making modifications to it. “Object code” means any non-source form of a
work.
A “Standard Interface” means an interface that either is an official
standard defined by a recognized standards body, or, in the case of interfaces
specified for a particular programming language, one that is widely used among
developers working in that language.
The “System Libraries” of an executable work include anything, other than
the work as a whole, that **(a)** is included in the normal form of packaging a Major
Component, but which is not part of that Major Component, and **(b)** serves only to
enable use of the work with that Major Component, or to implement a Standard
Interface for which an implementation is available to the public in source code form.
A “Major Component”, in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system (if any) on which
the executable work runs, or a compiler used to produce the work, or an object code
interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the
source code needed to generate, install, and (for an executable work) run the object
code and to modify the work, including scripts to control those activities. However,
it does not include the work's System Libraries, or general-purpose tools or
generally available free programs which are used unmodified in performing those
activities but which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for the work, and
the source code for shared libraries and dynamically linked subprograms that the work
is specifically designed to require, such as by intimate data communication or
control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate
automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
### 2. Basic Permissions
All rights granted under this License are granted for the term of copyright on the
Program, and are irrevocable provided the stated conditions are met. This License
explicitly affirms your unlimited permission to run the unmodified Program. The
output from running a covered work is covered by this License only if the output,
given its content, constitutes a covered work. This License acknowledges your rights
of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without
conditions so long as your license otherwise remains in force. You may convey covered
works to others for the sole purpose of having them make modifications exclusively
for you, or provide you with facilities for running those works, provided that you
comply with the terms of this License in conveying all material for which you do not
control copyright. Those thus making or running the covered works for you must do so
exclusively on your behalf, under your direction and control, on terms that prohibit
them from making any copies of your copyrighted material outside their relationship
with you.
Conveying under any other circumstances is permitted solely under the conditions
stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
### 3. Protecting Users' Legal Rights From Anti-Circumvention Law
No covered work shall be deemed part of an effective technological measure under any
applicable law fulfilling obligations under article 11 of the WIPO copyright treaty
adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention
of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of
technological measures to the extent such circumvention is effected by exercising
rights under this License with respect to the covered work, and you disclaim any
intention to limit operation or modification of the work as a means of enforcing,
against the work's users, your or third parties' legal rights to forbid circumvention
of technological measures.
### 4. Conveying Verbatim Copies
You may convey verbatim copies of the Program's source code as you receive it, in any
medium, provided that you conspicuously and appropriately publish on each copy an
appropriate copyright notice; keep intact all notices stating that this License and
any non-permissive terms added in accord with section 7 apply to the code; keep
intact all notices of the absence of any warranty; and give all recipients a copy of
this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer
support or warranty protection for a fee.
### 5. Conveying Modified Source Versions
You may convey a work based on the Program, or the modifications to produce it from
the Program, in the form of source code under the terms of section 4, provided that
you also meet all of these conditions:
* **a)** The work must carry prominent notices stating that you modified it, and giving a
relevant date.
* **b)** The work must carry prominent notices stating that it is released under this
License and any conditions added under section 7. This requirement modifies the
requirement in section 4 to “keep intact all notices”.
* **c)** You must license the entire work, as a whole, under this License to anyone who
comes into possession of a copy. This License will therefore apply, along with any
applicable section 7 additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no permission to license the
work in any other way, but it does not invalidate such permission if you have
separately received it.
* **d)** If the work has interactive user interfaces, each must display Appropriate Legal
Notices; however, if the Program has interactive interfaces that do not display
Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are
not by their nature extensions of the covered work, and which are not combined with
it such as to form a larger program, in or on a volume of a storage or distribution
medium, is called an “aggregate” if the compilation and its resulting
copyright are not used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work in an aggregate
does not cause this License to apply to the other parts of the aggregate.
### 6. Conveying Non-Source Forms
You may convey a covered work in object code form under the terms of sections 4 and
5, provided that you also convey the machine-readable Corresponding Source under the
terms of this License, in one of these ways:
* **a)** Convey the object code in, or embodied in, a physical product (including a
physical distribution medium), accompanied by the Corresponding Source fixed on a
durable physical medium customarily used for software interchange.
* **b)** Convey the object code in, or embodied in, a physical product (including a
physical distribution medium), accompanied by a written offer, valid for at least
three years and valid for as long as you offer spare parts or customer support for
that product model, to give anyone who possesses the object code either **(1)** a copy of
the Corresponding Source for all the software in the product that is covered by this
License, on a durable physical medium customarily used for software interchange, for
a price no more than your reasonable cost of physically performing this conveying of
source, or **(2)** access to copy the Corresponding Source from a network server at no
charge.
* **c)** Convey individual copies of the object code with a copy of the written offer to
provide the Corresponding Source. This alternative is allowed only occasionally and
noncommercially, and only if you received the object code with such an offer, in
accord with subsection 6b.
* **d)** Convey the object code by offering access from a designated place (gratis or for
a charge), and offer equivalent access to the Corresponding Source in the same way
through the same place at no further charge. You need not require recipients to copy
the Corresponding Source along with the object code. If the place to copy the object
code is a network server, the Corresponding Source may be on a different server
(operated by you or a third party) that supports equivalent copying facilities,
provided you maintain clear directions next to the object code saying where to find
the Corresponding Source. Regardless of what server hosts the Corresponding Source,
you remain obligated to ensure that it is available for as long as needed to satisfy
these requirements.
* **e)** Convey the object code using peer-to-peer transmission, provided you inform
other peers where the object code and Corresponding Source of the work are being
offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the
Corresponding Source as a System Library, need not be included in conveying the
object code work.
A “User Product” is either **(1)** a “consumer product”, which
means any tangible personal property which is normally used for personal, family, or
household purposes, or **(2)** anything designed or sold for incorporation into a
dwelling. In determining whether a product is a consumer product, doubtful cases
shall be resolved in favor of coverage. For a particular product received by a
particular user, “normally used” refers to a typical or common use of
that class of product, regardless of the status of the particular user or of the way
in which the particular user actually uses, or expects or is expected to use, the
product. A product is a consumer product regardless of whether the product has
substantial commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
“Installation Information” for a User Product means any methods,
procedures, authorization keys, or other information required to install and execute
modified versions of a covered work in that User Product from a modified version of
its Corresponding Source. The information must suffice to ensure that the continued
functioning of the modified object code is in no case prevented or interfered with
solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for
use in, a User Product, and the conveying occurs as part of a transaction in which
the right of possession and use of the User Product is transferred to the recipient
in perpetuity or for a fixed term (regardless of how the transaction is
characterized), the Corresponding Source conveyed under this section must be
accompanied by the Installation Information. But this requirement does not apply if
neither you nor any third party retains the ability to install modified object code
on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to
continue to provide support service, warranty, or updates for a work that has been
modified or installed by the recipient, or for the User Product in which it has been
modified or installed. Access to a network may be denied when the modification itself
materially and adversely affects the operation of the network or violates the rules
and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with
this section must be in a format that is publicly documented (and with an
implementation available to the public in source code form), and must require no
special password or key for unpacking, reading or copying.
### 7. Additional Terms
“Additional permissions” are terms that supplement the terms of this
License by making exceptions from one or more of its conditions. Additional
permissions that are applicable to the entire Program shall be treated as though they
were included in this License, to the extent that they are valid under applicable
law. If additional permissions apply only to part of the Program, that part may be
used separately under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any
additional permissions from that copy, or from any part of it. (Additional
permissions may be written to require their own removal in certain cases when you
modify the work.) You may place additional permissions on material, added by you to a
covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a
covered work, you may (if authorized by the copyright holders of that material)
supplement the terms of this License with terms:
* **a)** Disclaiming warranty or limiting liability differently from the terms of
sections 15 and 16 of this License; or
* **b)** Requiring preservation of specified reasonable legal notices or author
attributions in that material or in the Appropriate Legal Notices displayed by works
containing it; or
* **c)** Prohibiting misrepresentation of the origin of that material, or requiring that
modified versions of such material be marked in reasonable ways as different from the
original version; or
* **d)** Limiting the use for publicity purposes of names of licensors or authors of the
material; or
* **e)** Declining to grant rights under trademark law for use of some trade names,
trademarks, or service marks; or
* **f)** Requiring indemnification of licensors and authors of that material by anyone
who conveys the material (or modified versions of it) with contractual assumptions of
liability to the recipient, for any liability that these contractual assumptions
directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further
restrictions” within the meaning of section 10. If the Program as you received
it, or any part of it, contains a notice stating that it is governed by this License
along with a term that is a further restriction, you may remove that term. If a
license document contains a further restriction but permits relicensing or conveying
under this License, you may add to a covered work material governed by the terms of
that license document, provided that the further restriction does not survive such
relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in
the relevant source files, a statement of the additional terms that apply to those
files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a
separately written license, or stated as exceptions; the above requirements apply
either way.
### 8. Termination
You may not propagate or modify a covered work except as expressly provided under
this License. Any attempt otherwise to propagate or modify it is void, and will
automatically terminate your rights under this License (including any patent licenses
granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a
particular copyright holder is reinstated **(a)** provisionally, unless and until the
copyright holder explicitly and finally terminates your license, and **(b)** permanently,
if the copyright holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently
if the copyright holder notifies you of the violation by some reasonable means, this
is the first time you have received notice of violation of this License (for any
work) from that copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of
parties who have received copies or rights from you under this License. If your
rights have been terminated and not permanently reinstated, you do not qualify to
receive new licenses for the same material under section 10.
### 9. Acceptance Not Required for Having Copies
You are not required to accept this License in order to receive or run a copy of the
Program. Ancillary propagation of a covered work occurring solely as a consequence of
using peer-to-peer transmission to receive a copy likewise does not require
acceptance. However, nothing other than this License grants you permission to
propagate or modify any covered work. These actions infringe copyright if you do not
accept this License. Therefore, by modifying or propagating a covered work, you
indicate your acceptance of this License to do so.
### 10. Automatic Licensing of Downstream Recipients
Each time you convey a covered work, the recipient automatically receives a license
from the original licensors, to run, modify and propagate that work, subject to this
License. You are not responsible for enforcing compliance by third parties with this
License.
An “entity transaction” is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an organization, or
merging organizations. If propagation of a covered work results from an entity
transaction, each party to that transaction who receives a copy of the work also
receives whatever licenses to the work the party's predecessor in interest had or
could give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if the predecessor
has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or
affirmed under this License. For example, you may not impose a license fee, royalty,
or other charge for exercise of rights granted under this License, and you may not
initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging
that any patent claim is infringed by making, using, selling, offering for sale, or
importing the Program or any portion of it.
### 11. Patents
A “contributor” is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The work thus
licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or
controlled by the contributor, whether already acquired or hereafter acquired, that
would be infringed by some manner, permitted by this License, of making, using, or
selling its contributor version, but do not include claims that would be infringed
only as a consequence of further modification of the contributor version. For
purposes of this definition, “control” includes the right to grant patent
sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license
under the contributor's essential patent claims, to make, use, sell, offer for sale,
import and otherwise run, modify and propagate the contents of its contributor
version.
In the following three paragraphs, a “patent license” is any express
agreement or commitment, however denominated, not to enforce a patent (such as an
express permission to practice a patent or covenant not to sue for patent
infringement). To “grant” such a patent license to a party means to make
such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the
Corresponding Source of the work is not available for anyone to copy, free of charge
and under the terms of this License, through a publicly available network server or
other readily accessible means, then you must either **(1)** cause the Corresponding
Source to be so available, or **(2)** arrange to deprive yourself of the benefit of the
patent license for this particular work, or **(3)** arrange, in a manner consistent with
the requirements of this License, to extend the patent license to downstream
recipients. “Knowingly relying” means you have actual knowledge that, but
for the patent license, your conveying the covered work in a country, or your
recipient's use of the covered work in a country, would infringe one or more
identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you
convey, or propagate by procuring conveyance of, a covered work, and grant a patent
license to some of the parties receiving the covered work authorizing them to use,
propagate, modify or convey a specific copy of the covered work, then the patent
license you grant is automatically extended to all recipients of the covered work and
works based on it.
A patent license is “discriminatory” if it does not include within the
scope of its coverage, prohibits the exercise of, or is conditioned on the
non-exercise of one or more of the rights that are specifically granted under this
License. You may not convey a covered work if you are a party to an arrangement with
a third party that is in the business of distributing software, under which you make
payment to the third party based on the extent of your activity of conveying the
work, and under which the third party grants, to any of the parties who would receive
the covered work from you, a discriminatory patent license **(a)** in connection with
copies of the covered work conveyed by you (or copies made from those copies), or **(b)**
primarily for and in connection with specific products or compilations that contain
the covered work, unless you entered into that arrangement, or that patent license
was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied
license or other defenses to infringement that may otherwise be available to you
under applicable patent law.
### 12. No Surrender of Others' Freedom
If conditions are imposed on you (whether by court order, agreement or otherwise)
that contradict the conditions of this License, they do not excuse you from the
conditions of this License. If you cannot convey a covered work so as to satisfy
simultaneously your obligations under this License and any other pertinent
obligations, then as a consequence you may not convey it at all. For example, if you
agree to terms that obligate you to collect a royalty for further conveying from
those to whom you convey the Program, the only way you could satisfy both those terms
and this License would be to refrain entirely from conveying the Program.
### 13. Use with the GNU Affero General Public License
Notwithstanding any other provision of this License, you have permission to link or
combine any covered work with a work licensed under version 3 of the GNU Affero
General Public License into a single combined work, and to convey the resulting work.
The terms of this License will continue to apply to the part which is the covered
work, but the special requirements of the GNU Affero General Public License, section
13, concerning interaction through a network will apply to the combination as such.
### 14. Revised Versions of this License
The Free Software Foundation may publish revised and/or new versions of the GNU
General Public License from time to time. Such new versions will be similar in spirit
to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that
a certain numbered version of the GNU General Public License “or any later
version” applies to it, you have the option of following the terms and
conditions either of that numbered version or of any later version published by the
Free Software Foundation. If the Program does not specify a version number of the GNU
General Public License, you may choose any version ever published by the Free
Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU
General Public License can be used, that proxy's public statement of acceptance of a
version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no
additional obligations are imposed on any author or copyright holder as a result of
your choosing to follow a later version.
### 15. Disclaimer of Warranty
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE
QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
### 16. Limitation of Liability
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY
COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS
PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE
OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE
WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
### 17. Interpretation of Sections 15 and 16
If the disclaimer of warranty and limitation of liability provided above cannot be
given local legal effect according to their terms, reviewing courts shall apply local
law that most closely approximates an absolute waiver of all civil liability in
connection with the Program, unless a warranty or assumption of liability accompanies
a copy of the Program in return for a fee.
_END OF TERMS AND CONDITIONS_
## How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to
the public, the best way to achieve this is to make it free software which everyone
can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them
to the start of each source file to most effectively state the exclusion of warranty;
and each file should have at least the “copyright” line and a pointer to
where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this
when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type 'show c' for details.
The hypothetical commands `show w` and `show c` should show the appropriate parts of
the General Public License. Of course, your program's commands might be different;
for a GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school, if any, to
sign a “copyright disclaimer” for the program, if necessary. For more
information on this, and how to apply and follow the GNU GPL, see
&lt;<http://www.gnu.org/licenses/>&gt;.
The GNU General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may consider it
more useful to permit linking proprietary applications with the library. If this is
what you want to do, use the GNU Lesser General Public License instead of this
License. But first, please read
&lt;<http://www.gnu.org/philosophy/why-not-lgpl.html>&gt;.

View File

@@ -4,6 +4,7 @@
* [Introduction](#introduction)
* [Development](#development)
* [Contributing](#contributing)
* [License](#license)
* * *
@@ -28,13 +29,24 @@ And then you may install prospector like:
# pip install prospector[with_pyroma]
```
## Contributing
The main communication channel for GPOA is
[Samba@ALT Linux mailing lists](https://lists.altlinux.org/mailman/listinfo/samba).
The mailing list is in Russian but you may also send e-mail in English
or German.
## License
GPOA - GPO Applier for Linux
Copyright (C) 2019-2020 BaseALT Ltd.
This program is free software; you can redistribute it and/or modify
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
@@ -42,7 +54,6 @@ but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

19
dist/gpupdate-group-users vendored Executable file
View File

@@ -0,0 +1,19 @@
#!/bin/sh
. /etc/control.d/functions
CONFIG=/etc/pam.d/system-policy-gpupdate
new_subst disabled \
'^[[:space:]]*session[[:space:]]+\[.*default=1.*\][[:space:]]+pam_succeed_if.so user ingroup users.*' \
's,^\([[:space:]]*session[[:space:]]\+\[.*\)default=[[:alnum:]]\+\(.*pam_succeed_if.so user ingroup users.*\)$,\1default=1\2,'
new_subst enabled \
'^[[:space:]]*session[[:space:]]+\[.*default=ignore.*\][[:space:]]+pam_succeed_if.so user ingroup users.*' \
's,^\([[:space:]]*session[[:space:]]\+\[.*\)default=[[:alnum:]]\+\(.*pam_succeed_if.so user ingroup users.*\)$,\1default=ignore\2,'
new_help disabled "Disable group policy applying for users in 'users' group only"
new_help enabled "Enable group policy applying for users in 'users' group only"
new_summary "Group policy applying for users in 'users' group only"
control_subst "$CONFIG" "$*"

19
dist/gpupdate-localusers vendored Executable file
View File

@@ -0,0 +1,19 @@
#!/bin/sh
. /etc/control.d/functions
CONFIG=/etc/pam.d/system-policy-gpupdate
new_subst disabled \
'^[[:space:]]*session[[:space:]]+\[.*success=2.*\][[:space:]]+pam_localuser.so' \
's,^\([[:space:]]*session[[:space:]]\+\[.*\)success=[[:alnum:]]\+\(.*pam_localuser.so.*\)$,\1success=2\2,'
new_subst enabled \
'^[[:space:]]*session[[:space:]]+\[.*success=1.*\][[:space:]]+pam_localuser.so' \
's,^\([[:space:]]*session[[:space:]]\+\[.*\)success=[[:alnum:]]\+\(.*pam_localuser.so.*\)$,\1success=1\2,'
new_help disabled 'Disable group policy applying for local users'
new_help enabled 'Enable group policy applying for local users'
new_summary 'Group policy applying for local users'
control_subst "$CONFIG" "$*"

19
dist/gpupdate-system-uids vendored Executable file
View File

@@ -0,0 +1,19 @@
#!/bin/sh
. /etc/control.d/functions
CONFIG=/etc/pam.d/system-policy-gpupdate
new_subst disabled \
'^[[:space:]]*session[[:space:]]+\[.*default=1.*\][[:space:]]+pam_succeed_if.so uid >= 500.*' \
's,^\([[:space:]]*session[[:space:]]\+\[.*\)default=[[:alnum:]]\+\(.*pam_succeed_if.so uid >= 500.*\)$,\1default=1\2,'
new_subst enabled \
'^[[:space:]]*session[[:space:]]+\[.*default=ignore.*\][[:space:]]+pam_succeed_if.so uid >= 500.*' \
's,^\([[:space:]]*session[[:space:]]\+\[.*\)default=[[:alnum:]]\+\(.*pam_succeed_if.so uid >= 500.*\)$,\1default=ignore\2,'
new_help disabled "Disable group policy applying for users with not system uids only"
new_help enabled "Enable group policy applying for users with not system uids only"
new_summary "Group policy applying for users with not system uids (greater or equal 500) only"
control_subst "$CONFIG" "$*"

View File

@@ -5,8 +5,8 @@ Description=gpupdate in userspace
# gpupdate on Windows runs once per hour
[Service]
Environment="PATH=/bin:/sbin:/usr/bin:/usr/sbin"
Type=notify
WatchdogSec=3600
Type=simple
RestartSec=3600
TimeoutSec=3000
Restart=always
ExecStart=/usr/sbin/gpoa

4
dist/gpupdate.ini vendored Normal file
View File

@@ -0,0 +1,4 @@
[gpoa]
backend = local
local-policy = default

View File

@@ -1,11 +1,11 @@
[Unit]
Description=Group policy update for machine
After=sssd.service
After=syslog.target network-online.target sssd.service
[Service]
Environment="PATH=/bin:/sbin:/usr/bin:/usr/sbin"
Type=notify
WatchdogSec=3600
Type=simple
RestartSec=3600
TimeoutSec=3000
Restart=always
ExecStart=/usr/bin/gpupdate

12
dist/system-policy-gpupdate vendored Normal file
View File

@@ -0,0 +1,12 @@
#%PAM-1.0
session [success=2 perm_denied=ignore default=die] pam_localuser.so
session required pam_mkhomedir.so silent
session [default=1] pam_permit.so
session [default=6] pam_permit.so
session [success=1 default=ignore] pam_succeed_if.so user ingroup users quiet
session [default=4] pam_permit.so
session [success=1 default=ignore] pam_succeed_if.so uid >= 500 quiet
session [default=2] pam_permit.so
-session required pam_oddjob_gpupdate.so
session optional pam_env.so user_readenv=1 conffile=/etc/gpupdate/environment user_envfile=.gpupdate_environment
session required pam_permit.so

View File

@@ -1,3 +1,19 @@
.\" GPOA - GPO Applier for Linux
.\"
.\" Copyright (C) 2019-2020 BaseALT Ltd.
.\"
.\" This program is free software: you can redistribute it and/or modify
.\" it under the terms of the GNU General Public License as published by
.\" the Free Software Foundation, either version 3 of the License, or
.\" (at your option) any later version.
.\"
.\" This program is distributed in the hope that it will be useful,
.\" but WITHOUT ANY WARRANTY; without even the implied warranty of
.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
.\" GNU General Public License for more details.
.\"
.\" You should have received a copy of the GNU General Public License
.\" along with this program. If not, see <http://www.gnu.org/licenses/>.
.TH GPOA 1
.
.SH NAME

View File

@@ -0,0 +1,17 @@
.\" GPOA - GPO Applier for Linux
.\"
.\" Copyright (C) 2019-2020 BaseALT Ltd.
.\"
.\" This program is free software: you can redistribute it and/or modify
.\" it under the terms of the GNU General Public License as published by
.\" the Free Software Foundation, either version 3 of the License, or
.\" (at your option) any later version.
.\"
.\" This program is distributed in the hope that it will be useful,
.\" but WITHOUT ANY WARRANTY; without even the implied warranty of
.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
.\" GNU General Public License for more details.
.\"
.\" You should have received a copy of the GNU General Public License
.\" along with this program. If not, see <http://www.gnu.org/licenses/>.

View File

@@ -1,3 +1,19 @@
.\" GPOA - GPO Applier for Linux
.\"
.\" Copyright (C) 2019-2020 BaseALT Ltd.
.\"
.\" This program is free software: you can redistribute it and/or modify
.\" it under the terms of the GNU General Public License as published by
.\" the Free Software Foundation, either version 3 of the License, or
.\" (at your option) any later version.
.\"
.\" This program is distributed in the hope that it will be useful,
.\" but WITHOUT ANY WARRANTY; without even the implied warranty of
.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
.\" GNU General Public License for more details.
.\"
.\" You should have received a copy of the GNU General Public License
.\" along with this program. If not, see <http://www.gnu.org/licenses/>.
.TH GPUPDATE-USER.SERVICE 1
.
.SH NAME

View File

@@ -1,3 +1,19 @@
.\" GPOA - GPO Applier for Linux
.\"
.\" Copyright (C) 2019-2020 BaseALT Ltd.
.\"
.\" This program is free software: you can redistribute it and/or modify
.\" it under the terms of the GNU General Public License as published by
.\" the Free Software Foundation, either version 3 of the License, or
.\" (at your option) any later version.
.\"
.\" This program is distributed in the hope that it will be useful,
.\" but WITHOUT ANY WARRANTY; without even the implied warranty of
.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
.\" GNU General Public License for more details.
.\"
.\" You should have received a copy of the GNU General Public License
.\" along with this program. If not, see <http://www.gnu.org/licenses/>.
.TH GPUPDATE 1
.
.SH NAME
@@ -28,6 +44,22 @@ Show help.
\fB--user \fIusername\fR
Run \fBgpupdate\fP for \fIusername\fP.
.
.SS "EXIT CODES"
.TP
\fB0\fR
Application exited successfully.
.TP
\fB1\fR
No runner is able to start \fBgpoa\fR.
.TP
\fB2\fR
No reply from \fID-Bus\fR when starting \fBgpoa\fR for computer using
\fBoddjobd\fR via \fID-Bus\fR.
.TP
\fB3\fR
No reply from \fID-Bus\fR when starting \fBgpoa\fR for user using
\fBoddjobd\fR via \fID-Bus\fR.
.
.SH "SEE ALSO"
gpoa(1)
.SH BUGS

View File

@@ -0,0 +1,17 @@
.\" GPOA - GPO Applier for Linux
.\"
.\" Copyright (C) 2019-2020 BaseALT Ltd.
.\"
.\" This program is free software: you can redistribute it and/or modify
.\" it under the terms of the GNU General Public License as published by
.\" the Free Software Foundation, either version 3 of the License, or
.\" (at your option) any later version.
.\"
.\" This program is distributed in the hope that it will be useful,
.\" but WITHOUT ANY WARRANTY; without even the implied warranty of
.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
.\" GNU General Public License for more details.
.\"
.\" You should have received a copy of the GNU General Public License
.\" along with this program. If not, see <http://www.gnu.org/licenses/>.

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,15 +13,15 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
from util.windows import smbcreds
from .samba_backend import samba_backend
from .nodomain_backend import nodomain_backend
from util.logging import log
from util.config import GPConfig
def backend_factory(dc, username, is_machine, no_domain = False):
'''
@@ -29,23 +31,31 @@ def backend_factory(dc, username, is_machine, no_domain = False):
policies enforced by domain administrators.
'''
back = None
domain = None
if not no_domain:
config = GPConfig()
if config.get_backend() == 'samba' and not no_domain:
if not dc:
dc = config.get_dc()
if dc:
ld = dict({'dc': dc})
log('D52', ld)
sc = smbcreds(dc)
domain = sc.get_domain()
if domain:
logging.debug('Initialize Samba backend for domain: {}'.format(domain))
ldata = dict({'domain': domain, "username": username, 'is_machine': is_machine})
log('D9', ldata)
try:
back = samba_backend(sc, username, domain, is_machine)
except Exception as exc:
logging.error('Unable to initialize Samba backend: {}'.format(exc))
else:
logging.debug('Initialize local backend with no domain')
logdata = dict({'error': str(exc)})
log('E7', logdata)
if config.get_backend() == 'local' or no_domain:
log('D8')
try:
back = nodomain_backend()
except Exception as exc:
logging.error('Unable to initialize no-domain backend: {}'.format(exc))
logdata = dict({'error': str(exc)})
log('E8', logdata)
return back

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,9 +13,8 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from abc import ABC

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,20 +13,13 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from util.rpm import (
install_rpm,
remove_rpm
)
class rpm:
def __init__(self, name, action):
self.name = name
self.action = action
from .applier_backend import applier_backend
def apply(self):
class freeipa_backend(applier_backend):
def __init__(self):
pass

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,9 +13,8 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
import os

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,11 +13,9 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
import os
# Facility to determine GPTs for user
from samba.gpclass import check_safe_path, check_refresh_gpo_list
@@ -27,13 +27,21 @@ from util.util import (
get_machine_name,
is_machine_name
)
from util.kerberos import (
machine_kinit
, machine_kdestroy
)
from util.windows import get_sid
import util.preg
from util.logging import slogm
from util.logging import log
class samba_backend(applier_backend):
def __init__(self, sambacreds, username, domain, is_machine):
self.cache_path = '/var/cache/gpupdate/creds/krb5cc_{}'.format(os.getpid())
self.__kinit_successful = machine_kinit(self.cache_path)
if not self.__kinit_successful:
raise Exception('kinit is not successful')
self.storage = registry_factory('registry')
self.storage.set_info('domain', domain)
machine_name = get_machine_name()
@@ -56,26 +64,51 @@ class samba_backend(applier_backend):
self.sambacreds = sambacreds
self.cache_dir = self.sambacreds.get_cache_dir()
logging.debug(slogm('Cache directory is: {}'.format(self.cache_dir)))
logdata = dict({'cachedir': self.cache_dir})
log('D7', logdata)
def __del__(self):
if self.__kinit_successful:
machine_kdestroy()
def retrieve_and_store(self):
'''
Retrieve settings and strore it in a database
'''
# Get policies for machine at first.
machine_gpts = self._get_gpts(get_machine_name(), self.storage.get_info('machine_sid'))
machine_gpts = list()
try:
machine_gpts = self._get_gpts(get_machine_name(), self.storage.get_info('machine_sid'))
except Exception as exc:
log('F2')
raise exc
self.storage.wipe_hklm()
self.storage.wipe_user(self.storage.get_info('machine_sid'))
for gptobj in machine_gpts:
gptobj.merge()
try:
gptobj.merge()
except Exception as exc:
logdata = dict()
logdata['msg'] = str(exc)
log('E26', logdata)
# Load user GPT values in case user's name specified
# This is a buggy implementation and should be tested more
if not self._is_machine_username:
user_gpts = self._get_gpts(self.username, self.sid)
user_gpts = list()
try:
user_gpts = self._get_gpts(self.username, self.sid)
except Exception as exc:
log('F3')
raise exc
self.storage.wipe_user(self.sid)
for gptobj in user_gpts:
gptobj.merge()
try:
gptobj.merge()
except Exception as exc:
logdata = dict()
logdata['msg'] = str(exc)
log('E27', logdata)
def _check_sysvol_present(self, gpo):
'''
@@ -85,19 +118,23 @@ class samba_backend(applier_backend):
# GPO named "Local Policy" has no entry by its nature so
# no reason to print warning.
if 'Local Policy' != gpo.name:
logging.warning(slogm('No SYSVOL entry assigned to GPO {}'.format(gpo.name)))
logdata = dict({'gponame': gpo.name})
log('W4', logdata)
return False
return True
def _get_gpts(self, username, sid):
gpts = list()
log('D45', {'username': username, 'sid': sid})
# util.windows.smbcreds
gpos = self.sambacreds.update_gpos(username)
log('D46')
for gpo in gpos:
if self._check_sysvol_present(gpo):
logging.debug(slogm('Found SYSVOL entry "{}" for GPO "{}"'.format(gpo.file_sys_path, gpo.display_name)))
path = check_safe_path(gpo.file_sys_path).upper()
logging.debug(slogm('Path: {}'.format(path)))
slogdata = dict({'sysvol_path': gpo.file_sys_path, 'gpo_name': gpo.display_name, 'gpo_path': path})
log('D30', slogdata)
gpt_abspath = os.path.join(self.cache_dir, 'gpo_cache', path)
obj = gpt(gpt_abspath, sid)
obj.set_name(gpo.display_name)

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,9 +13,8 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from .frontend_manager import (
frontend_manager as applier

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,12 +13,67 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from abc import ABC
import logging
from util.logging import slogm
def check_experimental_enabled(storage):
experimental_enable_flag = 'Software\\BaseALT\\Policies\\GPUpdate\\GlobalExperimental'
flag = storage.get_hklm_entry(experimental_enable_flag)
result = False
if flag and '1' == flag.data:
result = True
return result
def check_windows_mapping_enabled(storage):
windows_mapping_enable_flag = 'Software\\BaseALT\\Policies\\GPUpdate\\WindowsPoliciesMapping'
flag = storage.get_hklm_entry(windows_mapping_enable_flag)
result = True
if flag and '0' == flag.data:
result = False
return result
def check_module_enabled(storage, module_name):
gpupdate_module_enable_branch = 'Software\\BaseALT\\Policies\\GPUpdate'
gpupdate_module_flag = '{}\\{}'.format(gpupdate_module_enable_branch, module_name)
flag = storage.get_hklm_entry(gpupdate_module_flag)
result = None
if flag:
if '1' == flag.data:
result = True
if '0' == flag.data:
result = False
return result
def check_enabled(storage, module_name, is_experimental):
module_enabled = check_module_enabled(storage, module_name)
exp_enabled = check_experimental_enabled(storage)
result = False
if None == module_enabled:
if is_experimental and exp_enabled:
result = True
if not is_experimental:
result = True
else:
result = module_enabled
return result
class applier_frontend(ABC):
@classmethod
def __init__(self, regobj):

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,7 +13,6 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,47 +13,100 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import subprocess
import threading
import logging
from util.logging import slogm
def control_subst(preg_name):
'''
This is a workaround for control names which can't be used in
PReg/ADMX files.
'''
control_triggers = dict()
control_triggers['dvd_rw-format'] = 'dvd+rw-format'
control_triggers['dvd_rw-mediainfo'] = 'dvd+rw-mediainfo'
control_triggers['dvd_rw-booktype'] = 'dvd+rw-booktype'
result = preg_name
if preg_name in control_triggers:
result = control_triggers[preg_name]
return result
class control:
def __init__(self, name, value):
self.control_name = name
if type(value) != int and type(value) != str:
raise Exception('Unknown type of value for control')
self.control_name = control_subst(name)
self.control_value = value
self.possible_values = self._query_control_values()
if self.possible_values == None:
raise Exception('Unable to query possible values')
def _query_control_values(self):
proc = subprocess.Popen(['/usr/sbin/control', self.control_name, 'list'], stdout=subprocess.PIPE)
for line in proc.stdout:
values = line.split()
return values
'''
Query possible values from control in order to perform check of
parameter passed to constructor.
'''
values = list()
popen_call = ['/usr/sbin/control', self.control_name, 'list']
with subprocess.Popen(popen_call, stdout=subprocess.PIPE) as proc:
values = proc.stdout.readline().decode('utf-8').split()
proc.wait()
return values
def _map_control_status(self, int_status):
str_status = self.possible_values[int_status].decode()
'''
Get control's string value by numeric index
'''
try:
str_status = self.possible_values[int_status]
except IndexError as exc:
logging.error(slogm('Error getting control ({}) value from {} by index {}'.format(self.control_name, self.possible_values, int_status)))
str_status = None
return str_status
def get_control_name(self):
return self.control_name
def get_control_status(self):
proc = subprocess.Popen(['/usr/sbin/control', self.control_name], stdout=subprocess.PIPE)
for line in proc.stdout:
return line.rstrip('\n\r')
'''
Get current control value
'''
line = None
popen_call = ['/usr/sbin/control', self.control_name]
with subprocess.Popen(popen_call, stdout=subprocess.PIPE) as proc:
line = proc.stdout.readline().decode('utf-8').rstrip('\n\r')
proc.wait()
return line
def set_control_status(self):
status = self._map_control_status(self.control_value)
if type(self.control_value) == int:
status = self._map_control_status(self.control_value)
if status == None:
logging.error(slogm('\'{}\' is not in possible values for control {}'.format(self.control_value, self.control_name)))
return
elif type(self.control_value) == str:
if self.control_value not in self.possible_values:
logging.error(slogm('\'{}\' is not in possible values for control {}'.format(self.control_value, self.control_name)))
return
status = self.control_value
logging.debug(slogm('Setting control {} to {}'.format(self.control_name, status)))
try:
proc = subprocess.Popen(['/usr/sbin/control', self.control_name, status], stdout=subprocess.PIPE)
popen_call = ['/usr/sbin/control', self.control_name, status]
with subprocess.Popen(popen_call, stdout=subprocess.PIPE) as proc:
proc.wait()
except:
logging.error(slogm('Unable to set {} to {}'.format(self.control_name, status)))

View File

@@ -0,0 +1,118 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from os.path import isfile
from util.logging import slogm
import logging
from gpt.envvars import (
FileAction
, action_letter2enum
)
from util.windows import expand_windows_var
from util.util import (
get_homedir,
homedir_exists
)
class Envvar:
def __init__(self, envvars, username=''):
self.username = username
self.envvars = envvars
if self.username == 'root':
self.envvar_file_path = '/etc/gpupdate/environment'
else:
self.envvar_file_path = get_homedir(self.username) + '/.gpupdate_environment'
def _open_envvar_file(self):
fd = None
if isfile(self.envvar_file_path):
fd = open(self.envvar_file_path, 'r+')
else:
fd = open(self.envvar_file_path, 'w')
fd.close()
fd = open(self.envvar_file_path, 'r+')
return fd
def _create_action(self, create_dict, envvar_file):
lines_old = envvar_file.readlines()
lines_new = list()
for name in create_dict:
exist = False
for line in lines_old:
if line.startswith(name + '='):
exist = True
break
if not exist:
lines_new.append(name + '=' + create_dict[name] + '\n')
if len(lines_new) > 0:
envvar_file.writelines(lines_new)
def _delete_action(self, delete_dict, envvar_file):
lines = envvar_file.readlines()
deleted = False
for name in delete_dict:
for line in lines:
if line.startswith(name + '='):
lines.remove(line)
deleted = True
break
if deleted:
envvar_file.writelines(lines)
def act(self):
if isfile(self.envvar_file_path):
with open(self.envvar_file_path, 'r') as f:
lines = f.readlines()
else:
lines = list()
file_changed = False
for envvar_object in self.envvars:
action = action_letter2enum(envvar_object.action)
name = envvar_object.name
value = expand_windows_var(envvar_object.value, self.username)
if value != envvar_object.value:
#slashes are replaced only if the change of variables was performed and we consider the variable as a path to a file or directory
value = value.replace('\\', '/')
exist_line = None
for line in lines:
if line.split()[0] == name:
exist_line = line
break
if exist_line != None:
if action == FileAction.CREATE:
pass
if action == FileAction.DELETE:
lines.remove(exist_line)
file_changed = True
if action == FileAction.UPDATE or action == FileAction.REPLACE:
if exist_line.split()[1].split('=')[1].replace('"', '') != value: #from 'NAME DEFAULT=value' cut value and compare, don`t change if it matches
lines.remove(exist_line)
lines.append(name + ' ' + 'DEFAULT=\"' + value + '\"\n')
file_changed = True
else:
if action == FileAction.CREATE or action == FileAction.UPDATE or action == FileAction.REPLACE:
lines.append(name + ' ' + 'DEFAULT=\"' + value + '\"\n')
file_changed = True
if action == FileAction.DELETE:
pass
if file_changed:
with open(self.envvar_file_path, 'w') as f:
f.writelines(lines)

View File

@@ -0,0 +1,97 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from enum import Enum
import subprocess
def getprops(param_list):
props = dict()
for entry in param_list:
lentry = entry.lower()
if lentry.startswith('action'):
props['action'] = lentry.rpartition('=')[2]
if lentry.startswith('protocol'):
props['protocol'] = lentry.rpartition('=')[2]
if lentry.startswith('dir'):
props['dir'] = lentry.rpartition('=')[2]
return props
def get_ports(param_list):
portlist = list()
for entry in param_list:
lentry = entry.lower()
if lentry.startswith('lport'):
port = lentry.rpartition('=')[2]
portlist.append(port)
return portlist
class PortState(Enum):
OPEN = 'Allow'
CLOSE = 'Deny'
class Protocol(Enum):
TCP = 'tcp'
UDP = 'udp'
class FirewallMode(Enum):
ROUTER = 'router'
GATEWAY = 'gateway'
HOST = 'host'
# This shi^Wthing named alterator-net-iptables is unable to work in
# multi-threaded environment
class FirewallRule:
__alterator_command = '/usr/bin/alterator-net-iptables'
def __init__(self, data):
data_array = data.split('|')
self.version = data_array[0]
self.ports = get_ports(data_array[1:])
self.properties = getprops(data_array[1:])
def apply(self):
tcp_command = []
udp_command = []
for port in self.ports:
tcp_port = '{}'.format(port)
udp_port = '{}'.format(port)
if PortState.OPEN.value == self.properties['action']:
tcp_port = '+' + tcp_port
udp_port = '+' + udp_port
if PortState.CLOSE.value == self.properties['action']:
tcp_port = '-' + tcp_port
udp_port = '-' + udp_port
portcmd = [
self.__alterator_command
, 'write'
, '-m', FirewallMode.HOST.value
, '-t', tcp_port
, '-u', udp_port
]
proc = subprocess.Popen(portcmd)
proc.wait()

View File

@@ -0,0 +1,75 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from pathlib import Path
from gpt.folders import (
FileAction
, action_letter2enum
)
from util.windows import expand_windows_var
def remove_dir_tree(path, delete_files=False, delete_folder=False, delete_sub_folders=False):
for entry in path.iterdir():
if entry.is_file():
entry.unlink()
if entry.is_dir():
if delete_sub_folders:
remove_dir_tree(entry,
delete_files,
delete_folder,
delete_sub_folders)
if delete_folder:
path.rmdir()
def str2bool(boolstr):
if boolstr.lower in ['true', 'yes', '1']:
return True
return False
class Folder:
def __init__(self, folder_object, username):
self.folder_path = Path(expand_windows_var(folder_object.path, username).replace('\\', '/'))
self.action = action_letter2enum(folder_object.action)
self.delete_files = str2bool(folder_object.delete_files)
self.delete_folder = str2bool(folder_object.delete_folder)
self.delete_sub_folders = str2bool(folder_object.delete_sub_folders)
def _create_action(self):
self.folder_path.mkdir(parents=True, exist_ok=True)
def _delete_action(self):
remove_dir_tree(self.folder_path,
self.delete_files,
self.delete_folders,
self.delete_sub_folders)
def act(self):
if self.action == FileAction.CREATE:
self._create_action()
if self.action == FileAction.UPDATE:
self._create_action()
if self.action == FileAction.DELETE:
self._delete_action()
if self.action == FileAction.REPLACE:
self._delete_action()
self._create_action()

View File

@@ -1,9 +1,11 @@
#
# Copyright (C) 2019-2020 BaseALT Ltd.
# GPOA - GPO Applier for Linux
#
# This program is free software; you can redistribute it and/or modify
# Copyright (C) 2019-2021 BaseALT Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,9 +13,8 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import configparser
import os
@@ -23,44 +24,115 @@ from gi.repository import Gio, GLib
from util.logging import slogm
class system_gsetting:
__global_schema = '/usr/share/glib-2.0/schemas'
def __init__(self, schema, path, value, override_priority='0'):
def __init__(self, schema, path, value, lock, helper_function=None):
self.schema = schema
self.path = path
self.value = value
self.override_priority = override_priority
self.filename = '{}_policy.gschema.override'.format(self.override_priority)
self.file_path = os.path.join(self.__global_schema, self.filename)
self.lock = lock
self.helper_function = helper_function
def apply(self, settings, config, locks):
try:
config.add_section(self.schema)
except configparser.DuplicateSectionError:
pass
value = self.value
if self.helper_function:
value = self.helper_function(self.schema, self.path, value)
result = glib_value(self.schema, self.path, value, settings)
config.set(self.schema, self.path, str(result))
if self.lock:
lock_path = dconf_path(settings, self.path)
locks.append(lock_path)
class system_gsettings:
__path_local_dir = '/etc/dconf/db/local.d'
__path_locks = '/etc/dconf/db/policy.d/locks/policy'
__path_profile = '/etc/dconf/profile/user'
__profile_data = 'user-db:user\nsystem-db:policy\nsystem-db:local\n'
def __init__(self, override_file_path):
self.gsettings = list()
self.locks = list()
self.override_file_path = override_file_path
def append(self, schema, path, data, lock, helper):
self.gsettings.append(system_gsetting(schema, path, data, lock, helper))
def pop(self):
self.gsettings.pop()
def apply(self):
config = configparser.ConfigParser()
try:
config.read(self.file_path)
except Exception as exc:
logging.error(slogm(exc))
config.add_section(self.schema)
config.set(self.schema, self.path, self.value)
with open(self.file_path, 'w') as f:
for gsetting in self.gsettings:
settings = Gio.Settings(schema=gsetting.schema)
logging.debug(slogm('Applying machine setting {}.{} to {} {}'.format(gsetting.schema,
gsetting.path,
gsetting.value,
gsetting.value,
'locked' if gsetting.lock else 'unlocked')))
gsetting.apply(settings, config, self.locks)
with open(self.override_file_path, 'w') as f:
config.write(f)
os.makedirs(self.__path_local_dir, mode=0o755, exist_ok=True)
os.makedirs(os.path.dirname(self.__path_locks), mode=0o755, exist_ok=True)
os.makedirs(os.path.dirname(self.__path_profile), mode=0o755, exist_ok=True)
try:
os.remove(self.__path_locks)
except OSError as error:
pass
file_locks = open(self.__path_locks,'w')
for lock in self.locks:
file_locks.write(lock +'\n')
file_locks.close()
profile = open(self.__path_profile ,'w')
profile.write(self.__profile_data)
profile.close()
def glib_map(value, glib_type):
result_value = value
if glib_type == 'i' or glib_type == 'b' or glib_type == 'q':
result_value = GLib.Variant(glib_type, int(value))
else:
result_value = GLib.Variant(glib_type, value)
return result_value
def dconf_path(settings, path):
return settings.get_property("path") + path
def glib_value(schema, path, value, settings):
# Get the key to modify
key = settings.get_value(path)
# Query the data type for the key
glib_value_type = key.get_type_string()
# Build the new value with the determined type
return glib_map(value, glib_value_type)
class user_gsetting:
def __init__(self, schema, path, value):
def __init__(self, schema, path, value, helper_function=None):
self.schema = schema
self.path = path
self.value = value
self.helper_function = helper_function
def apply(self):
source = Gio.SettingsSchemaSource.get_default()
schema = source.lookup(self.schema, True)
key = schema.get_key(self.path)
gvformat = key.get_value_type()
val = GLib.Variant(gvformat.dup_string(), self.value)
schema.set_value(self.path, val)
#gso = Gio.Settings.new(self.schema)
#variants = gso.get_property(self.path)
#if (variants.has_key(self.path)):
# key = variants.get_key(self.path)
# print(key.get_range())
# Access the current schema
settings = Gio.Settings(schema=self.schema)
# Update result with helper function
value = self.value
if self.helper_function:
value = self.helper_function(self.schema, self.path, value)
# Get typed value by schema
result = glib_value(self.schema, self.path, value, settings)
# Set the value
settings.set_value(self.path, result)
settings.sync()

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,9 +13,8 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import jinja2
@@ -27,11 +28,15 @@ class polkit:
__template_loader = jinja2.FileSystemLoader(searchpath=__template_path)
__template_environment = jinja2.Environment(loader=__template_loader)
def __init__(self, template_name, arglist):
def __init__(self, template_name, arglist, username=None):
self.template_name = template_name
self.args = arglist
self.username = username
self.infilename = '{}.rules.j2'.format(self.template_name)
self.outfile = os.path.join(self.__policy_dir, '{}.rules'.format(self.template_name))
if self.username:
self.outfile = os.path.join(self.__policy_dir, '{}.{}.rules'.format(self.template_name, self.username))
else:
self.outfile = os.path.join(self.__policy_dir, '{}.rules'.format(self.template_name))
def generate(self):
try:

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,9 +13,8 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import dbus
import logging
@@ -39,14 +40,23 @@ class systemd_unit:
self.manager.EnableUnitFiles([self.unit_name], dbus.Boolean(False), dbus.Boolean(True))
self.manager.StartUnit(self.unit_name, 'replace')
logging.info(slogm('Starting systemd unit: {}'.format(self.unit_name)))
if self._get_state() != 'active':
# In case the service has 'RestartSec' property set it
# switches to 'activating (auto-restart)' state instead of
# 'active' so we consider 'activating' a valid state too.
service_state = self._get_state()
if not service_state in ['active', 'activating']:
logging.error(slogm('Unable to start systemd unit {}'.format(self.unit_name)))
else:
self.manager.StopUnit(self.unit_name, 'replace')
self.manager.DisableUnitFiles([self.unit_name], dbus.Boolean(False))
self.manager.MaskUnitFiles([self.unit_name], dbus.Boolean(False), dbus.Boolean(True))
logging.info(slogm('Stopping systemd unit: {}'.format(self.unit_name)))
if self._get_state() != 'stopped':
service_state = self._get_state()
if not service_state in ['stopped']:
logging.error(slogm('Unable to stop systemd unit {}'.format(self.unit_name)))
def _get_state(self):

View File

@@ -0,0 +1,23 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from enum import Enum
class WallpaperStretchMode(Enum):
STRETCH = 2

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,11 +13,13 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from .applier_frontend import applier_frontend
from .applier_frontend import (
applier_frontend
, check_enabled
)
import logging
import json
@@ -25,7 +29,10 @@ from util.logging import slogm
from util.util import is_machine_name
class chromium_applier(applier_frontend):
__registry_branch = 'Software\\Policies\\Chromium'
__module_name = 'ChromiumApplier'
__module_enabled = True
__module_experimental = False
__registry_branch = 'Software\\Policies\\Google\\Chrome'
__managed_policies_path = '/etc/chromium/policies/managed'
__recommended_policies_path = '/etc/chromium/policies/recommended'
# JSON file where Chromium stores its settings (and which is
@@ -38,6 +45,11 @@ class chromium_applier(applier_frontend):
self.username = username
self._is_machine_name = is_machine_name(self.username)
self.policies = dict()
self.__module_enabled = check_enabled(
self.storage
, self.__module_name
, self.__module_experimental
)
def get_hklm_string_entry(self, hive_subkey):
query_str = '{}\\{}'.format(self.__registry_branch, hive_subkey)
@@ -101,7 +113,11 @@ class chromium_applier(applier_frontend):
logging.info(slogm('Set user ({}) property \'{}\' to {}'.format(self.username, name, obj)))
def get_home_page(self, hkcu=False):
return self.get_hklm_string_entry('HomepageLocation')
response = self.get_hklm_string_entry('HomepageLocation')
result = 'about:blank'
if response:
result = response.data
return result
def machine_apply(self):
'''
@@ -126,7 +142,12 @@ class chromium_applier(applier_frontend):
'''
All actual job done here.
'''
self.machine_apply()
if self.__module_enabled:
logging.debug(slogm('Running Chromium applier for machine'))
self.machine_apply()
else:
logging.debug(slogm('Chromium applier for machine will not be started'))
#if not self._is_machine_name:
# logging.debug('Running user applier for Chromium')
# self.user_apply()

View File

@@ -0,0 +1,164 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import fileinput
import jinja2
import os
import subprocess
import logging
from pathlib import Path
from .applier_frontend import (
applier_frontend
, check_enabled
)
from gpt.drives import json2drive
from util.util import get_homedir
from util.logging import slogm
def storage_get_drives(storage, sid):
drives = storage.get_drives(sid)
drive_list = list()
for drv_obj in drives:
drive_list.append(drv_obj)
return drive_list
def add_line_if_missing(filename, ins_line):
with open(filename, 'r+') as f:
for line in f:
if ins_line == line.strip():
break
else:
f.write(ins_line + '\n')
f.flush()
class cifs_applier(applier_frontend):
def __init__(self, storage):
pass
def apply(self):
pass
class cifs_applier_user(applier_frontend):
__module_name = 'CIFSApplierUser'
__module_enabled = False
__module_experimental = True
__auto_file = '/etc/auto.master'
__auto_dir = '/etc/auto.master.gpupdate.d'
__template_path = '/usr/share/gpupdate/templates'
__template_mountpoints = 'autofs_mountpoints.j2'
__template_identity = 'autofs_identity.j2'
__template_auto = 'autofs_auto.j2'
def __init__(self, storage, sid, username):
self.storage = storage
self.sid = sid
self.username = username
self.home = get_homedir(username)
conf_file = '{}.conf'.format(sid)
autofs_file = '{}.autofs'.format(sid)
cred_file = '{}.creds'.format(sid)
self.auto_master_d = Path(self.__auto_dir)
self.user_config = self.auto_master_d / conf_file
if os.path.exists(self.user_config.resolve()):
self.user_config.unlink()
self.user_autofs = self.auto_master_d / autofs_file
if os.path.exists(self.user_autofs.resolve()):
self.user_autofs.unlink()
self.user_creds = self.auto_master_d / cred_file
self.mount_dir = Path(os.path.join(self.home, 'net'))
self.drives = storage_get_drives(self.storage, self.sid)
self.template_loader = jinja2.FileSystemLoader(searchpath=self.__template_path)
self.template_env = jinja2.Environment(loader=self.template_loader)
self.template_mountpoints = self.template_env.get_template(self.__template_mountpoints)
self.template_indentity = self.template_env.get_template(self.__template_identity)
self.template_auto = self.template_env.get_template(self.__template_auto)
self.__module_enabled = check_enabled(
self.storage
, self.__module_name
, self.__module_experimental
)
def user_context_apply(self):
'''
Nothing to implement.
'''
pass
def __admin_context_apply(self):
# Create /etc/auto.master.gpupdate.d directory
self.auto_master_d.mkdir(parents=True, exist_ok=True)
# Create user's destination mount directory
self.mount_dir.mkdir(parents=True, exist_ok=True)
# Add pointer to /etc/auto.master.gpiupdate.d in /etc/auto.master
auto_destdir = '+dir:{}'.format(self.__auto_dir)
add_line_if_missing(self.__auto_file, auto_destdir)
# Collect data for drive settings
drive_list = list()
for drv in self.drives:
drive_settings = dict()
drive_settings['dir'] = drv.dir
drive_settings['login'] = drv.login
drive_settings['password'] = drv.password
drive_settings['path'] = drv.path.replace('\\', '/')
drive_list.append(drive_settings)
if len(drive_list) > 0:
mount_settings = dict()
mount_settings['drives'] = drive_list
mount_text = self.template_mountpoints.render(**mount_settings)
with open(self.user_config.resolve(), 'w') as f:
f.truncate()
f.write(mount_text)
f.flush()
autofs_settings = dict()
autofs_settings['home_dir'] = self.home
autofs_settings['mount_file'] = self.user_config.resolve()
autofs_text = self.template_auto.render(**autofs_settings)
with open(self.user_autofs.resolve(), 'w') as f:
f.truncate()
f.write(autofs_text)
f.flush()
subprocess.check_call(['/bin/systemctl', 'restart', 'autofs'])
def admin_context_apply(self):
if self.__module_enabled:
logging.debug(slogm('Running CIFS applier for user in administrator context'))
self.__admin_context_apply()
else:
logging.debug(slogm('CIFS applier for user in administrator context will not be started'))

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,33 +13,43 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from .applier_frontend import applier_frontend
from .applier_frontend import (
applier_frontend
, check_enabled
)
from .appliers.control import control
from util.logging import slogm
import logging
class control_applier(applier_frontend):
__module_name = 'ControlApplier'
__module_experimental = False
__module_enabled = True
_registry_branch = 'Software\\BaseALT\\Policies\\Control'
def __init__(self, storage):
self.storage = storage
self.control_settings = self.storage.filter_hklm_entries('Software\\BaseALT\\Policies\\Control%')
self.controls = list()
self.__module_enabled = check_enabled(
self.storage
, self.__module_name
, self.__module_experimental
)
def apply(self):
'''
Trigger control facility invocation.
'''
def run(self):
for setting in self.control_settings:
valuename = setting.hive_key.rpartition('\\')[2]
try:
self.controls.append(control(valuename, int(setting.data)))
logging.info(slogm('Working with control {}'.format(valuename)))
except ValueError as exc:
self.controls.append(control(valuename, setting.data))
logging.info(slogm('Working with control {} with string value'.format(valuename)))
except Exception as exc:
logging.info(slogm('Unable to work with control {}: {}'.format(valuename, exc)))
#for e in polfile.pol_file.entries:
@@ -45,3 +57,13 @@ class control_applier(applier_frontend):
for cont in self.controls:
cont.set_control_status()
def apply(self):
'''
Trigger control facility invocation.
'''
if self.__module_enabled:
logging.debug(slogm('Running Control applier for machine'))
self.run()
else:
logging.debug(slogm('Control applier for machine will not be started'))

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,14 +13,19 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
import os
import json
from .applier_frontend import applier_frontend
import cups
from .applier_frontend import (
applier_frontend
, check_enabled
)
from gpt.printers import json2printer
from util.rpm import is_rpm_installed
from util.logging import slogm
@@ -31,42 +38,81 @@ def storage_get_printers(storage, sid):
printers = list()
for prnj in printer_objs:
prn_obj = json2printer(prnj)
printers.append(prn_obj)
printers.append(prnj)
return printers
def write_printer(prn):
def connect_printer(connection, prn):
'''
Dump printer cinfiguration to disk as CUPS config
'''
printer_config_path = os.path.join('/etc/cups', prn.name)
with open(printer_config_path, 'r') as f:
print(prn.cups_config(), file=f)
# PPD file location
printer_driver = 'generic'
pjson = json.loads(prn.printer)
printer_parts = pjson['printer']['path'].partition(' ')
# Printer queue name in CUPS
printer_name = printer_parts[2].replace('(', '').replace(')', '')
# Printer description in CUPS
printer_info = printer_name
printer_uri = printer_parts[0].replace('\\', '/')
printer_uri = 'smb:' + printer_uri
connection.addPrinter(
name=printer_name
, info=printer_info
, device=printer_uri
#filename=printer_driver
)
class cups_applier(applier_frontend):
__module_name = 'CUPSApplier'
__module_experimental = True
__module_enabled = False
def __init__(self, storage):
self.storage = storage
self.__module_enabled = check_enabled(
self.storage
, self.__module_name
, self.__module_experimental
)
def run(self):
if not is_rpm_installed('cups'):
logging.warning(slogm('CUPS is not installed: no printer settings will be deployed'))
return
self.cups_connection = cups.Connection()
self.printers = storage_get_printers(self.storage, self.storage.get_info('machine_sid'))
if self.printers:
for prn in self.printers:
connect_printer(self.cups_connection, prn)
def apply(self):
'''
Perform configuration of printer which is assigned to computer.
'''
if not is_rpm_installed('cups'):
logging.warning(slogm('CUPS is not installed: no printer settings will be deployed'))
return
printers = storage_get_printers(self.storage, self.storage.get_info('machine_sid'))
if printers:
for prn in printers:
write_printer(prn)
if self.__module_enabled:
logging.debug(slogm('Running CUPS applier for machine'))
self.run()
else:
logging.debug(slogm('CUPS applier for machine will not be started'))
class cups_applier_user(applier_frontend):
__module_name = 'CUPSApplierUser'
__module_experimental = True
__module_enabled = False
def __init__(self, storage, sid, username):
self.storage = storage
self.sid = sid
self.username = username
self.__module_enabled = check_enabled(
self.storage
, self.__module_name
, self.__module_enabled
)
def user_context_apply(self):
'''
@@ -75,17 +121,25 @@ class cups_applier_user(applier_frontend):
'''
pass
def admin_context_apply(self):
'''
Perform printer configuration assigned for user.
'''
def run(self):
if not is_rpm_installed('cups'):
logging.warning(slogm('CUPS is not installed: no printer settings will be deployed'))
return
printers = storage_get_printers(self.storage, self.sid)
self.cups_connection = cups.Connection()
self.printers = storage_get_printers(self.storage, self.sid)
if printers:
for prn in printers:
write_printer(prn)
if self.printers:
for prn in self.printers:
connect_printer(self.cups_connection, prn)
def admin_context_apply(self):
'''
Perform printer configuration assigned for user.
'''
if self.__module_enabled:
logging.debug(slogm('Running CUPS applier for user in administrator context'))
self.run()
else:
logging.debug(slogm('CUPS applier for user in administrator context will not be started'))

View File

@@ -0,0 +1,69 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from .applier_frontend import (
applier_frontend
, check_enabled
)
from .appliers.envvar import Envvar
from util.logging import slogm
import logging
class envvar_applier(applier_frontend):
__module_name = 'EnvvarsApplier'
__module_experimental = False
__module_enabled = True
def __init__(self, storage, sid):
self.storage = storage
self.sid = sid
self.envvars = self.storage.get_envvars(self.sid)
#self.__module_enabled = check_enabled(self.storage, self.__module_name, self.__module_enabled)
def apply(self):
if self.__module_enabled:
logging.debug(slogm('Running Envvar applier for machine'))
ev = Envvar(self.envvars, 'root')
ev.act()
else:
logging.debug(slogm('Envvar applier for machine will not be started'))
class envvar_applier_user(applier_frontend):
__module_name = 'EnvvarsApplierUser'
__module_experimental = False
__module_enabled = True
def __init__(self, storage, sid, username):
self.storage = storage
self.sid = sid
self.username = username
self.envvars = self.storage.get_envvars(self.sid)
#self.__module_enabled = check_enabled(self.storage, self.__module_name, self.__module_experimental)
def admin_context_apply(self):
pass
def user_context_apply(self):
if self.__module_enabled:
logging.debug(slogm('Running Envvar applier for user in user context'))
ev = Envvar(self.envvars, self.username)
ev.act()
else:
logging.debug(slogm('Envvar applier for user in user context will not be started'))

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,9 +13,8 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# This file is the preferred way to configure Firefox browser in multi-OS
# enterprise environments.
@@ -29,13 +30,20 @@ import json
import os
import configparser
from .applier_frontend import applier_frontend
from .applier_frontend import (
applier_frontend
, check_enabled
)
from util.logging import slogm
from util.util import is_machine_name
class firefox_applier(applier_frontend):
__module_name = 'FirefoxApplier'
__module_experimental = False
__module_enabled = True
__registry_branch = 'Software\\Policies\\Mozilla\\Firefox'
__firefox_installdir = '/usr/lib64/firefox/distribution'
__firefox_installdir1 = '/usr/lib64/firefox/distribution'
__firefox_installdir2 = '/etc/firefox/policies'
__user_settings_dir = '.mozilla/firefox'
def __init__(self, storage, sid, username):
@@ -45,6 +53,11 @@ class firefox_applier(applier_frontend):
self._is_machine_name = is_machine_name(self.username)
self.policies = dict()
self.policies_json = dict({ 'policies': self.policies })
self.__module_enabled = check_enabled(
self.storage
, self.__module_name
, self.__module_experimental
)
def get_profiles(self):
'''
@@ -102,28 +115,78 @@ class firefox_applier(applier_frontend):
return homepage
return None
def get_block_about_config(self):
def get_boolean_config(self, name):
'''
Query BlockAboutConfig boolean property from the storage.
Query boolean property from the storage.
'''
response = self.get_hklm_string_entry('BlockAboutConfig')
response = self.get_hklm_string_entry(name)
if response:
if response.data.lower() in ['0', 'false', False, None, 'None']:
data = response.data if isinstance(response.data, int) else str(response.data).lower()
if data in ['0', 'false', None, 'none', 0]:
return False
return True
if data in ['1', 'true', 1]:
return True
return None
def set_boolean_policy(self, name):
'''
Add boolean entry to policy set.
'''
obj = self.get_boolean_config(name)
if obj is not None:
self.policies[name] = obj
logging.info(slogm('Firefox policy \'{}\' set to {}'.format(name, obj)))
def machine_apply(self):
'''
Write policies.json to Firefox installdir.
'''
self.set_policy('Homepage', self.get_home_page())
self.set_policy('BlockAboutConfig', self.get_block_about_config())
self.set_boolean_policy('BlockAboutConfig')
self.set_boolean_policy('BlockAboutProfiles')
self.set_boolean_policy('BlockAboutSupport')
self.set_boolean_policy('CaptivePortal')
self.set_boolean_policy('DisableSetDesktopBackground')
self.set_boolean_policy('DisableMasterPasswordCreation')
self.set_boolean_policy('DisableBuiltinPDFViewer')
self.set_boolean_policy('DisableDeveloperTools')
self.set_boolean_policy('DisableFeedbackCommands')
self.set_boolean_policy('DisableFirefoxScreenshots')
self.set_boolean_policy('DisableFirefoxAccounts')
self.set_boolean_policy('DisableFirefoxStudies')
self.set_boolean_policy('DisableForgetButton')
self.set_boolean_policy('DisableFormHistory')
self.set_boolean_policy('DisablePasswordReveal')
self.set_boolean_policy('DisablePocket')
self.set_boolean_policy('DisablePrivateBrowsing')
self.set_boolean_policy('DisableProfileImport')
self.set_boolean_policy('DisableProfileRefresh')
self.set_boolean_policy('DisableSafeMode')
self.set_boolean_policy('DisableSystemAddonUpdate')
self.set_boolean_policy('DisableTelemetry')
self.set_boolean_policy('DontCheckDefaultBrowser')
self.set_boolean_policy('ExtensionUpdate')
self.set_boolean_policy('HardwareAcceleration')
self.set_boolean_policy('PrimaryPassword')
self.set_boolean_policy('NetworkPrediction')
self.set_boolean_policy('NewTabPage')
self.set_boolean_policy('NoDefaultBookmarks')
self.set_boolean_policy('OfferToSaveLogins')
self.set_boolean_policy('PasswordManagerEnabled')
self.set_boolean_policy('PromptForDownloadLocation')
self.set_boolean_policy('SanitizeOnShutdown')
self.set_boolean_policy('SearchSuggestEnabled')
destfile = os.path.join(self.__firefox_installdir, 'policies.json')
destfile = os.path.join(self.__firefox_installdir1, 'policies.json')
os.makedirs(self.__firefox_installdir, exist_ok=True)
os.makedirs(self.__firefox_installdir1, exist_ok=True)
with open(destfile, 'w') as f:
json.dump(self.policies_json, f)
logging.debug(slogm('Wrote Firefox preferences to {}'.format(destfile)))
destfile = os.path.join(self.__firefox_installdir2, 'policies.json')
os.makedirs(self.__firefox_installdir2, exist_ok=True)
with open(destfile, 'w') as f:
json.dump(self.policies_json, f)
logging.debug(slogm('Wrote Firefox preferences to {}'.format(destfile)))
@@ -136,7 +199,11 @@ class firefox_applier(applier_frontend):
logging.debug(slogm('Found Firefox profile in {}/{}'.format(profiledir, profile)))
def apply(self):
self.machine_apply()
if self.__module_enabled:
logging.debug(slogm('Running Firefox applier for machine'))
self.machine_apply()
else:
logging.debug(slogm('Firefox applier for machine will not be started'))
#if not self._is_machine_name:
# logging.debug('Running user applier for Firefox')
# self.user_apply()

View File

@@ -0,0 +1,65 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
import subprocess
from util.logging import slogm
from .applier_frontend import (
applier_frontend
, check_enabled
)
from .appliers.firewall_rule import FirewallRule
class firewall_applier(applier_frontend):
__module_name = 'FirewallApplier'
__module_experimental = True
__module_enabled = False
__firewall_branch = 'SOFTWARE\\Policies\\Microsoft\\WindowsFirewall\\FirewallRules'
__firewall_switch = 'SOFTWARE\\Policies\\Microsoft\\WindowsFirewall\\DomainProfile\\EnableFirewall'
__firewall_reset_cmd = ['/usr/bin/alterator-net-iptables', 'reset']
def __init__(self, storage):
self.storage = storage
self.firewall_settings = self.storage.filter_hklm_entries('{}%'.format(self.__firewall_branch))
self.firewall_enabled = self.storage.get_hklm_entry(self.__firewall_switch)
self.__module_enabled = check_enabled(
self.storage
, self.__module_name
, self.__module_experimental
)
def run(self):
for setting in self.firewall_settings:
rule = FirewallRule(setting.data)
rule.apply()
def apply(self):
if self.__module_enabled:
logging.debug(slogm('Running Firewall applier for machine'))
if '1' == self.firewall_enabled:
logging.debug(slogm('Firewall is enabled'))
self.run()
else:
logging.debug(slogm('Firewall is disabled, settings will be reset'))
proc = subprocess.Popen(self.__firewall_reset_cmd)
proc.wait()
else:
logging.debug(slogm('Firewall applier will not be started'))

View File

@@ -0,0 +1,84 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from pathlib import Path
from .applier_frontend import (
applier_frontend
, check_enabled
)
from .appliers.folder import Folder
from util.logging import slogm
import logging
class folder_applier(applier_frontend):
__module_name = 'FoldersApplier'
__module_experimental = False
__module_enabled = True
def __init__(self, storage, sid):
self.storage = storage
self.sid = sid
self.folders = self.storage.get_folders(self.sid)
self.__module_enabled = check_enabled(self.storage, self.__module_name, self.__module_enabled)
def apply(self):
if self.__module_enabled:
logging.debug(slogm('Running Folder applier for machine'))
for directory_obj in self.folders:
fld = Folder(directory_obj)
fld.action()
else:
logging.debug(slogm('Folder applier for machine will not be started'))
class folder_applier_user(applier_frontend):
__module_name = 'FoldersApplierUser'
__module_experimental = False
__module_enabled = True
def __init__(self, storage, sid, username):
self.storage = storage
self.sid = sid
self.username = username
self.folders = self.storage.get_folders(self.sid)
self.__module_enabled = check_enabled(
self.storage
, self.__module_name
, self.__module_experimental
)
def run(self):
for directory_obj in self.folders:
fld = Folder(directory_obj, self.username)
fld.act()
def admin_context_apply(self):
if self.__module_enabled:
logging.debug(slogm('Running Folder applier for user in administrator context'))
self.run()
else:
logging.debug(slogm('Folder applier for user in administrator context will not be started'))
def user_context_apply(self):
if self.__module_enabled:
logging.debug(slogm('Running Folder applier for user in user context'))
self.run()
else:
logging.debug(slogm('Folder applier for user administrator context will not be started'))

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,19 +13,25 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from storage import registry_factory
from storage.fs_file_cache import fs_file_cache
from .control_applier import control_applier
from .polkit_applier import polkit_applier
from .polkit_applier import (
polkit_applier
, polkit_applier_user
)
from .systemd_applier import systemd_applier
from .firefox_applier import firefox_applier
from .chromium_applier import chromium_applier
from .cups_applier import cups_applier
from .package_applier import package_applier
from .package_applier import (
package_applier
, package_applier_user
)
from .shortcut_applier import (
shortcut_applier,
shortcut_applier_user
@@ -32,16 +40,26 @@ from .gsettings_applier import (
gsettings_applier,
gsettings_applier_user
)
from .firewall_applier import firewall_applier
from .folder_applier import (
folder_applier
, folder_applier_user
)
from .cifs_applier import cifs_applier_user
from .ntp_applier import ntp_applier
from .envvar_applier import (
envvar_applier
, envvar_applier_user
)
from util.windows import get_sid
from util.users import (
is_root,
get_process_user,
username_match_uid,
with_privileges
)
from util.logging import slogm
from util.logging import log
from util.system import with_privileges
import logging
def determine_username(username=None):
'''
@@ -54,16 +72,30 @@ def determine_username(username=None):
# of process owner.
if not username:
name = get_process_user()
logging.debug(slogm('Username is not specified - will use username of current process'))
logdata = dict({'username': name})
log('D2', logdata)
if not username_match_uid(name):
if not is_root():
raise Exception('Current process UID does not match specified username')
logging.debug(slogm('Username for frontend is set to {}'.format(name)))
logdata = dict({'username': name})
log('D15', logdata)
return name
def apply_user_context(user_appliers):
for applier_name, applier_object in user_appliers.items():
log('D55', {'name': applier_name})
try:
applier_object.user_context_apply()
except Exception as exc:
logdata = dict()
logdata['applier'] = applier_name
logdata['exception'] = str(exc)
log('E20', logdata)
class frontend_manager:
'''
The frontend_manager class decides when and how to run appliers
@@ -76,60 +108,86 @@ class frontend_manager:
self.is_machine = is_machine
self.process_uname = get_process_user()
self.sid = get_sid(self.storage.get_info('domain'), self.username, is_machine)
self.file_cache = fs_file_cache('file_cache')
self.machine_appliers = dict({
'control': control_applier(self.storage),
'polkit': polkit_applier(self.storage),
'systemd': systemd_applier(self.storage),
'firefox': firefox_applier(self.storage, self.sid, self.username),
'chromium': chromium_applier(self.storage, self.sid, self.username),
'shortcuts': shortcut_applier(self.storage),
'gsettings': gsettings_applier(self.storage),
'cups': cups_applier(self.storage),
'package': package_applier(self.storage)
})
self.machine_appliers = dict()
self.machine_appliers['control'] = control_applier(self.storage)
self.machine_appliers['polkit'] = polkit_applier(self.storage)
self.machine_appliers['systemd'] = systemd_applier(self.storage)
self.machine_appliers['firefox'] = firefox_applier(self.storage, self.sid, self.username)
self.machine_appliers['chromium'] = chromium_applier(self.storage, self.sid, self.username)
self.machine_appliers['shortcuts'] = shortcut_applier(self.storage)
self.machine_appliers['gsettings'] = gsettings_applier(self.storage, self.file_cache)
self.machine_appliers['cups'] = cups_applier(self.storage)
self.machine_appliers['firewall'] = firewall_applier(self.storage)
self.machine_appliers['folders'] = folder_applier(self.storage, self.sid)
self.machine_appliers['package'] = package_applier(self.storage)
self.machine_appliers['ntp'] = ntp_applier(self.storage)
self.machine_appliers['envvar'] = envvar_applier(self.storage, self.sid)
# User appliers are expected to work with user-writable
# files and settings, mostly in $HOME.
self.user_appliers = dict({
'shortcuts': shortcut_applier_user(self.storage, self.sid, self.username),
'gsettings': gsettings_applier_user(self.storage, self.sid, self.username)
})
self.user_appliers = dict()
self.user_appliers['shortcuts'] = shortcut_applier_user(self.storage, self.sid, self.username)
self.user_appliers['folders'] = folder_applier_user(self.storage, self.sid, self.username)
self.user_appliers['gsettings'] = gsettings_applier_user(self.storage, self.file_cache, self.sid, self.username)
try:
self.user_appliers['cifs'] = cifs_applier_user(self.storage, self.sid, self.username)
except Exception as exc:
logdata = dict()
logdata['applier_name'] = 'cifs'
logdata['msg'] = str(exc)
log('E25', logdata)
self.user_appliers['package'] = package_applier_user(self.storage, self.sid, self.username)
self.user_appliers['polkit'] = polkit_applier_user(self.storage, self.sid, self.username)
self.user_appliers['envvar'] = envvar_applier_user(self.storage, self.sid, self.username)
def machine_apply(self):
'''
Run global appliers with administrator privileges.
'''
if not is_root():
logging.error('Not sufficient privileges to run machine appliers')
log('E13')
return
logging.debug(slogm('Applying computer part of settings'))
self.machine_appliers['systemd'].apply()
self.machine_appliers['control'].apply()
self.machine_appliers['polkit'].apply()
self.machine_appliers['firefox'].apply()
self.machine_appliers['chromium'].apply()
self.machine_appliers['shortcuts'].apply()
self.machine_appliers['gsettings'].apply()
self.machine_appliers['cups'].apply()
#self.machine_appliers['package'].apply()
log('D16')
for applier_name, applier_object in self.machine_appliers.items():
try:
applier_object.apply()
except Exception as exc:
logdata = dict()
logdata['applier_name'] = applier_name
logdata['msg'] = str(exc)
log('E24', logdata)
def user_apply(self):
'''
Run appliers for users.
'''
if is_root():
logging.debug(slogm('Running user appliers from administrator context'))
self.user_appliers['shortcuts'].admin_context_apply()
self.user_appliers['gsettings'].admin_context_apply()
for applier_name, applier_object in self.user_appliers.items():
try:
applier_object.admin_context_apply()
except Exception as exc:
logdata = dict()
logdata['applier'] = applier_name
logdata['exception'] = str(exc)
log('E19', logdata)
logging.debug(slogm('Running user appliers for user context'))
with_privileges(self.username, self.user_appliers['shortcuts'].user_context_apply)
with_privileges(self.username, self.user_appliers['gsettings'].user_context_apply)
try:
with_privileges(self.username, lambda: apply_user_context(self.user_appliers))
except Exception as exc:
logdata = dict()
logdata['username'] = self.username
logdata['exception'] = str(exc)
log('E30', logdata)
else:
logging.debug(slogm('Running user appliers from user context'))
self.user_appliers['shortcuts'].user_context_apply()
self.user_appliers['gsettings'].user_context_apply()
for applier_name, applier_object in self.user_appliers.items():
try:
applier_object.user_context_apply()
except Exception as exc:
logdata = dict({'applier_name': applier_name, 'message': str(exc)})
log('E11', logdata)
def apply_parameters(self):
'''

View File

@@ -1,9 +1,11 @@
#
# Copyright (C) 2019-2020 BaseALT Ltd.
# GPOA - GPO Applier for Linux
#
# This program is free software; you can redistribute it and/or modify
# Copyright (C) 2019-2021 BaseALT Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,49 +13,136 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
import os
import pwd
import subprocess
from .applier_frontend import applier_frontend
from gi.repository import (
Gio
, GLib
)
from .applier_frontend import (
applier_frontend
, check_enabled
, check_windows_mapping_enabled
)
from .appliers.gsettings import (
system_gsetting,
system_gsettings,
user_gsetting
)
from util.logging import slogm
def uri_fetch(schema, path, value, cache):
'''
Function to fetch and cache uri
'''
retval = value
logdata = dict()
logdata['schema'] = schema
logdata['path'] = path
logdata['src'] = value
try:
retval = cache.get(value)
logdata['dst'] = retval
logging.debug(slogm('Getting cached file for URI: {}'.format(logdata)))
except Exception as exc:
pass
return retval
class gsettings_applier(applier_frontend):
__registry_branch = 'Software\\BaseALT\\Policies\\gsettings'
__module_name = 'GSettingsApplier'
__module_experimental = False
__module_enabled = True
__registry_branch = 'Software\\BaseALT\\Policies\\GSettings\\'
__registry_locks_branch = 'Software\\BaseALT\\Policies\\GSettingsLocks\\'
__wallpaper_entry = 'Software\\BaseALT\\Policies\\GSettings\\org.mate.background.picture-filename'
__global_schema = '/usr/share/glib-2.0/schemas'
__override_priority_file = 'zzz_policy.gschema.override'
__override_old_file = '0_policy.gschema.override'
__windows_settings = dict()
def __init__(self, storage):
def __init__(self, storage, file_cache):
self.storage = storage
self.file_cache = file_cache
gsettings_filter = '{}%'.format(self.__registry_branch)
gsettings_locks_filter = '{}%'.format(self.__registry_locks_branch)
self.gsettings_keys = self.storage.filter_hklm_entries(gsettings_filter)
self.gsettings = list()
self.override_file = os.path.join(self.__global_schema, '0_policy.gschema.override')
self.gsettings_locks = self.storage.filter_hklm_entries(gsettings_locks_filter)
self.override_file = os.path.join(self.__global_schema, self.__override_priority_file)
self.override_old_file = os.path.join(self.__global_schema, self.__override_old_file)
self.gsettings = system_gsettings(self.override_file)
self.locks = dict()
self.dictArr = dict()
self.__module_enabled = check_enabled(
self.storage
, self.__module_name
, self.__module_experimental
)
def update_file_cache(self, data):
try:
self.file_cache.store(data)
except Exception as exc:
logdata = dict()
logdata['exception'] = str(exc)
logging.debug(slogm('Unable to cache specified URI for machine: {}'.format(logdata)))
def uri_fetch_helper(self, schema, path, value):
return uri_fetch(schema, path, value, self.file_cache)
def run(self):
# Compatility cleanup of old settings
if os.path.exists(self.override_old_file):
os.remove(self.override_old_file)
def apply(self):
# Cleanup settings from previous run
if os.path.exists(self.override_file):
logging.debug(slogm('Removing GSettings policy file from previous run'))
os.remove(self.override_file)
# Get all configured gsettings locks
for lock in self.gsettings_locks:
valuename = lock.hive_key.rpartition('\\')[2]
self.locks[valuename] = int(lock.data)
# Calculate all configured gsettings
for setting in self.gsettings_keys:
valuename = setting.hive_key.rpartition('\\')[2]
helper = None
valuename = setting.valuename
rp = valuename.rpartition('.')
schema = rp[0]
path = rp[2]
self.gsettings.append(system_gsetting(schema, path, setting.data))
data = setting.data
if setting.hive_key.lower() == self.__wallpaper_entry.lower():
self.update_file_cache(setting.data)
helper = self.uri_fetch_helper
# Registry branch ends with back slash.
# If keyname starts with same prefix, it would be array
elif setting.keyname.lower().startswith(self.__registry_branch.lower()):
valuenameArr = setting.keyname.rpartition('\\')[2]
if valuenameArr:
valuename = valuenameArr
rpArr = valuename.rpartition('.')
schema = rpArr[0]
path = rpArr[2]
if self.dictArr and path in self.dictArr.keys():
self.dictArr[path].append(setting.data)
self.gsettings.pop()
else:
self.dictArr[path] = [setting.data,]
data = self.dictArr[path]
lock = bool(self.locks[valuename]) if valuename in self.locks else None
self.gsettings.append(schema, path, data, lock, helper)
# Create GSettings policy with highest available priority
for gsetting in self.gsettings:
gsetting.apply()
self.gsettings.apply()
# Recompile GSettings schemas with overrides
try:
@@ -61,31 +150,176 @@ class gsettings_applier(applier_frontend):
except Exception as exc:
logging.debug(slogm('Error recompiling global GSettings schemas'))
class gsettings_applier_user(applier_frontend):
__registry_branch = 'Software\\BaseALT\\Policies\\gsettings'
# Update desktop configuration system backend
try:
proc = subprocess.run(args=['/usr/bin/dconf', "update"], capture_output=True, check=True)
except Exception as exc:
logging.debug(slogm('Error update desktop configuration system backend'))
def __init__(self, storage, sid, username):
def apply(self):
if self.__module_enabled:
logging.debug(slogm('Running GSettings applier for machine'))
self.run()
else:
logging.debug(slogm('GSettings applier for machine will not be started'))
class GSettingsMapping:
def __init__(self, hive_key, gsettings_schema, gsettings_key):
self.hive_key = hive_key
self.gsettings_schema = gsettings_schema
self.gsettings_key = gsettings_key
try:
self.schema_source = Gio.SettingsSchemaSource.get_default()
self.schema = self.schema_source.lookup(self.gsettings_schema, True)
self.gsettings_schema_key = self.schema.get_key(self.gsettings_key)
self.gsettings_type = self.gsettings_schema_key.get_value_type()
except Exception as exc:
logdata = dict()
logdata['hive_key'] = self.hive_key
logdata['gsettings_schema'] = self.gsettings_schema
logdata['gsettings_key'] = self.gsettings_key
logging.warning(slogm('Unable to resolve GSettings parameter {}.{}'.format(self.gsettings_schema, self.gsettings_key)))
def preg2gsettings(self):
'''
Transform PReg key variant into GLib.Variant. This function
performs mapping of PReg type system into GLib type system.
'''
pass
def gsettings2preg(self):
'''
Transform GLib.Variant key type into PReg key type.
'''
pass
class gsettings_applier_user(applier_frontend):
__module_name = 'GSettingsApplierUser'
__module_experimental = False
__module_enabled = True
__registry_branch = 'Software\\BaseALT\\Policies\\GSettings\\'
__wallpaper_entry = 'Software\\BaseALT\\Policies\\GSettings\\org.mate.background.picture-filename'
def __init__(self, storage, file_cache, sid, username):
self.storage = storage
self.file_cache = file_cache
self.sid = sid
self.username = username
gsettings_filter = '{}%'.format(self.__registry_branch)
self.gsettings_keys = self.storage.filter_hkcu_entries(self.sid, gsettings_filter)
self.gsettings = list()
self.__module_enabled = check_enabled(self.storage, self.__module_name, self.__module_enabled)
self.__windows_mapping_enabled = check_windows_mapping_enabled(self.storage)
self.dictArr = dict()
self.__windows_settings = dict()
self.windows_settings = list()
mapping = [
# Disable or enable screen saver
GSettingsMapping(
'Software\\Policies\\Microsoft\\Windows\\Control Panel\\Desktop\\ScreenSaveActive'
, 'org.mate.screensaver'
, 'idle-activation-enabled'
)
# Timeout in seconds for screen saver activation. The value of zero effectively disables screensaver start
, GSettingsMapping(
'Software\\Policies\\Microsoft\\Windows\\Control Panel\\Desktop\\ScreenSaveTimeOut'
, 'org.mate.session'
, 'idle-delay'
)
# Enable or disable password protection for screen saver
, GSettingsMapping(
'Software\\Policies\\Microsoft\\Windows\\Control Panel\\Desktop\\ScreenSaverIsSecure'
, 'org.mate.screensaver'
, 'lock-enabled'
)
# Specify image which will be used as a wallpaper
, GSettingsMapping(
'Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System\\Wallpaper'
, 'org.mate.background'
, 'picture-filename'
)
]
self.windows_settings.extend(mapping)
def user_context_apply(self):
for element in self.windows_settings:
self.__windows_settings[element.hive_key] = element
def windows_mapping_append(self):
for setting_key in self.__windows_settings.keys():
value = self.storage.get_hkcu_entry(self.sid, setting_key)
if value:
logging.debug(slogm('Found GSettings windows mapping {} to {}'.format(setting_key, value.data)))
mapping = self.__windows_settings[setting_key]
try:
self.gsettings.append(user_gsetting(mapping.gsettings_schema, mapping.gsettings_key, value.data))
except Exception as exc:
print(exc)
def uri_fetch_helper(self, schema, path, value):
return uri_fetch(schema, path, value, self.file_cache)
def run(self):
#for setting in self.gsettings_keys:
# valuename = setting.hive_key.rpartition('\\')[2]
# rp = valuename.rpartition('.')
# schema = rp[0]
# path = rp[2]
# self.gsettings.append(user_gsetting(schema, path, setting.data))
# Calculate all mapped gsettings if mapping enabled
if self.__windows_mapping_enabled:
logging.debug(slogm('Mapping Windows policies to GSettings policies'))
self.windows_mapping_append()
else:
logging.debug(slogm('GSettings windows policies mapping not enabled'))
# Calculate all configured gsettings
for setting in self.gsettings_keys:
valuename = setting.hive_key.rpartition('\\')[2]
rp = valuename.rpartition('.')
schema = rp[0]
path = rp[2]
self.gsettings.append(user_gsetting(schema, path, setting.data))
helper = self.uri_fetch_helper if setting.hive_key.lower() == self.__wallpaper_entry.lower() else None
if valuename == setting.data:
valuenameArr = setting.keyname.rpartition('\\')[2]
rpArr = valuenameArr.rpartition('.')
schema = rpArr[0]
path = rpArr[2]
if self.dictArr and path in self.dictArr.keys():
self.dictArr[path].append(setting.data)
self.gsettings.pop()
else:
self.dictArr[path] = [setting.data,]
self.gsettings.append(user_gsetting(schema, path, self.dictArr[path], helper))
continue
self.gsettings.append(user_gsetting(schema, path, setting.data, helper))
# Create GSettings policy with highest available priority
for gsetting in self.gsettings:
logging.debug(slogm('Applying user setting {}.{} to {}'.format(gsetting.schema,
gsetting.path,
gsetting.value)))
gsetting.apply()
def admin_context_apply(self):
'''
Not implemented because there is no point of doing so.
'''
pass
def user_context_apply(self):
if self.__module_enabled:
logging.debug(slogm('Running GSettings applier for user in user context'))
self.run()
else:
logging.debug(slogm('GSettings applier for user in user context will not be started'))
def admin_context_apply(self):
# Cache files on remote locations
try:
entry = self.__wallpaper_entry
filter_result = self.storage.get_hkcu_entry(self.sid, entry)
if filter_result:
self.file_cache.store(filter_result.data)
except Exception as exc:
logdata = dict()
logdata['exception'] = str(exc)
logging.debug(slogm('Unable to cache specified URI for user: {}'.format(logdata)))

View File

@@ -0,0 +1,147 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
import subprocess
from enum import Enum
from .applier_frontend import (
applier_frontend
, check_enabled
)
from util.logging import slogm
class NTPServerType(Enum):
NTP = 'NTP'
class ntp_applier(applier_frontend):
__module_name = 'NTPApplier'
__module_experimental = True
__module_enabled = False
__ntp_branch = 'Software\\Policies\\Microsoft\\W32time\\Parameters'
__ntp_client_branch = 'Software\\Policies\\Microsoft\\W32time\\TimeProviders\\NtpClient'
__ntp_server_branch = 'Software\\Policies\\Microsoft\\W32time\\TimeProviders\\NtpServer'
__ntp_key_address = 'NtpServer'
__ntp_key_type = 'Type'
__ntp_key_client_enabled = 'Enabled'
__ntp_key_server_enabled = 'Enabled'
__chrony_config = '/etc/chrony.conf'
def __init__(self, storage):
self.storage = storage
self.ntp_server_address_key = '{}\\{}'.format(self.__ntp_branch, self.__ntp_key_address)
self.ntp_server_type = '{}\\{}'.format(self.__ntp_branch, self.__ntp_key_type)
self.ntp_client_enabled = '{}\\{}'.format(self.__ntp_client_branch, self.__ntp_key_client_enabled)
self.ntp_server_enabled = '{}\\{}'.format(self.__ntp_server_branch, self.__ntp_key_server_enabled)
self.__module_enabled = check_enabled(
self.storage
, self.__module_name
, self.__module_experimental
)
def _chrony_as_client(self):
command = ['/usr/sbin/control', 'chrony', 'client']
proc = subprocess.Popen(command)
proc.wait()
def _chrony_as_server(self):
command = ['/usr/sbin/control', 'chrony', 'server']
proc = subprocess.Popen(command)
proc.wait()
def _start_chrony_client(self, server=None):
srv = None
if server:
srv = server.data.rpartition(',')[0]
logging.debug(slogm('NTP server is configured to {}'.format(srv)))
start_command = ['/usr/bin/systemctl', 'start', 'chronyd']
chrony_set_server = ['/usr/bin/chronyc', 'add', 'server', srv]
chrony_disconnect_all = ['/usr/bin/chronyc', 'offline']
chrony_connect = ['/usr/bin/chronyc', 'online', srv]
logging.debug(slogm('Starting Chrony daemon'))
proc = subprocess.Popen(start_command)
proc.wait()
if srv:
logging.debug(slogm('Setting reference NTP server to {}'.format(srv)))
proc = subprocess.Popen(chrony_disconnect_all)
proc.wait()
proc = subprocess.Popen(chrony_set_server)
proc.wait()
proc = subprocess.Popen(chrony_connect)
proc.wait()
def _stop_chrony_client(self):
stop_command = ['/usr/bin/systemctl', 'stop', 'chronyd']
logging.debug(slogm('Stopping Chrony daemon'))
proc = subprocess.Popen(stop_command)
proc.wait()
def run(self):
server_type = self.storage.get_hklm_entry(self.ntp_server_type)
server_address = self.storage.get_hklm_entry(self.ntp_server_address_key)
ntp_server_enabled = self.storage.get_hklm_entry(self.ntp_server_enabled)
ntp_client_enabled = self.storage.get_hklm_entry(self.ntp_client_enabled)
if NTPServerType.NTP.value != server_type.data:
logging.warning(slogm('Unsupported NTP server type: {}'.format(server_type)))
else:
logging.debug(slogm('Configuring NTP server...'))
if '1' == ntp_server_enabled.data:
logging.debug(slogm('NTP server is enabled'))
self._start_chrony_client(server_address)
self._chrony_as_server()
elif '0' == ntp_server_enabled.data:
logging.debug(slogm('NTP server is disabled'))
self._chrony_as_client()
else:
logging.debug(slogm('NTP server is not configured'))
if '1' == ntp_client_enabled.data:
logging.debug(slogm('NTP client is enabled'))
self._start_chrony_client()
elif '0' == ntp_client_enabled.data:
logging.debug(slogm('NTP client is disabled'))
self._stop_chrony_client()
else:
logging.debug(slogm('NTP client is not configured'))
def apply(self):
if self.__module_enabled:
logging.debug(slogm('Running NTP applier for machine'))
self.run()
else:
logging.debug(slogm('NTP applier for machine will not be started'))

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,25 +13,88 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
from util.logging import slogm
from util.rpm import (
update
, install_rpm
, remove_rpm
)
from .applier_frontend import applier_frontend
from .appliers.rpm import rpm
from .applier_frontend import (
applier_frontend
, check_enabled
)
class package_applier(applier_frontend):
__module_name = 'PackagesApplier'
__module_experimental = True
__module_enabled = False
__install_key_name = 'Install'
__remove_key_name = 'Remove'
__hklm_branch = 'Software\\BaseALT\\Policies\\Packages'
def __init__(self, storage):
self.storage = storage
install_branch = '{}\\{}%'.format(self.__hklm_branch, self.__install_key_name)
remove_branch = '{}\\{}%'.format(self.__hklm_branch, self.__remove_key_name)
self.install_packages_setting = self.storage.filter_hklm_entries(install_branch)
self.remove_packages_setting = self.storage.filter_hklm_entries(remove_branch)
self.__module_enabled = check_enabled(
self.storage
, self.__module_name
, self.__module_experimental
)
def run(self):
if 0 < self.install_packages_setting.count() or 0 < self.remove_packages_setting.count():
update()
for package in self.install_packages_setting:
try:
install_rpm(package.data)
except Exception as exc:
logging.error(exc)
for package in self.remove_packages_setting:
try:
remove_rpm(package.data)
except Exception as exc:
logging.error(exc)
def apply(self):
pass
if self.__module_enabled:
logging.debug(slogm('Running Package applier for machine'))
self.run()
else:
logging.debug(slogm('Package applier for machine will not be started'))
class package_applier_user(applier_frontend):
def __init__(self):
pass
__module_name = 'PackagesApplierUser'
__module_experimental = True
__module_enabled = False
__install_key_name = 'Install'
__remove_key_name = 'Remove'
__hkcu_branch = 'Software\\BaseALT\\Policies\\Packages'
def __init__(self, storage, sid, username):
self.storage = storage
self.sid = sid
self.username = username
install_branch = '{}\\{}%'.format(self.__hkcu_branch, self.__install_key_name)
remove_branch = '{}\\{}%'.format(self.__hkcu_branch, self.__remove_key_name)
self.install_packages_setting = self.storage.filter_hkcu_entries(self.sid, install_branch)
self.remove_packages_setting = self.storage.filter_hkcu_entries(self.sid, remove_branch)
self.__module_enabled = check_enabled(self.storage, self.__module_name, self.__module_enabled)
def user_context_apply(self):
'''
@@ -37,10 +102,29 @@ class package_applier_user(applier_frontend):
'''
pass
def run(self):
if 0 < self.install_packages_setting.count() or 0 < self.remove_packages_setting.count():
update()
for package in self.install_packages_setting:
try:
install_rpm(package.data)
except Exception as exc:
logging.debug(exc)
for package in self.remove_packages_setting:
try:
remove_rpm(package.data)
except Exception as exc:
logging.debug(exc)
def admin_context_apply(self):
'''
Install software assigned to specified username regardless
which computer he uses to log into system.
'''
pass
if self.__module_enabled:
logging.debug(slogm('Running Package applier for user in administrator context'))
self.run()
else:
logging.debug(slogm('Package applier for user in administrator context will not be started'))

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,20 +13,25 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from .applier_frontend import applier_frontend
from .applier_frontend import (
applier_frontend
, check_enabled
)
from .appliers.polkit import polkit
from util.logging import slogm
import logging
class polkit_applier(applier_frontend):
__module_name = 'PolkitApplier'
__module_experimental = False
__module_enabled = True
__deny_all = 'Software\\Policies\\Microsoft\\Windows\\RemovableStorageDevices\\Deny_All'
__polkit_map = {
__deny_all: ['99-gpoa_disk_permissions', { 'Deny_All': 0 }]
__deny_all: ['49-gpoa_disk_permissions', { 'Deny_All': 0 }]
}
def __init__(self, storage):
@@ -40,11 +47,66 @@ class polkit_applier(applier_frontend):
logging.debug(slogm('Deny_All setting not found'))
self.policies = []
self.policies.append(polkit(template_file, template_vars))
self.__module_enabled = check_enabled(
self.storage
, self.__module_name
, self.__module_experimental
)
def apply(self):
'''
Trigger control facility invocation.
'''
for policy in self.policies:
policy.generate()
if self.__module_enabled:
logging.debug(slogm('Running Polkit applier for machine'))
for policy in self.policies:
policy.generate()
else:
logging.debug(slogm('Polkit applier for machine will not be started'))
class polkit_applier_user(applier_frontend):
__module_name = 'PolkitApplierUser'
__module_experimental = False
__module_enabled = True
__deny_all = 'Software\\Policies\\Microsoft\\Windows\\RemovableStorageDevices\\Deny_All'
__polkit_map = {
__deny_all: ['48-gpoa_disk_permissions_user', { 'Deny_All': 0, 'User': '' }]
}
def __init__(self, storage, sid, username):
self.storage = storage
self.sid = sid
self.username = username
deny_all = storage.filter_hkcu_entries(self.sid, self.__deny_all).first()
# Deny_All hook: initialize defaults
template_file = self.__polkit_map[self.__deny_all][0]
template_vars = self.__polkit_map[self.__deny_all][1]
if deny_all:
logging.debug(slogm('Deny_All setting for user {} found: {}'.format(self.username, deny_all.data)))
self.__polkit_map[self.__deny_all][1]['Deny_All'] = deny_all.data
self.__polkit_map[self.__deny_all][1]['User'] = self.username
else:
logging.debug(slogm('Deny_All setting not found'))
self.policies = []
self.policies.append(polkit(template_file, template_vars, self.username))
self.__module_enabled = check_enabled(
self.storage
, self.__module_name
, self.__module_experimental
)
def user_context_apply(self):
pass
def admin_context_apply(self):
'''
Trigger control facility invocation.
'''
if self.__module_enabled:
logging.debug(slogm('Running Polkit applier for user in administrator context'))
for policy in self.policies:
policy.generate()
else:
logging.debug(slogm('Polkit applier for user in administrator context will not be started'))

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,19 +13,25 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
import subprocess
from .applier_frontend import applier_frontend
from .applier_frontend import (
applier_frontend
, check_enabled
)
from gpt.shortcuts import json2sc
from util.windows import expand_windows_var
from util.logging import slogm
from util.util import (
get_homedir,
homedir_exists
)
def storage_get_shortcuts(storage, sid):
def storage_get_shortcuts(storage, sid, username=None):
'''
Query storage for shortcuts' rows for specified SID.
'''
@@ -32,60 +40,116 @@ def storage_get_shortcuts(storage, sid):
for sc_obj in shortcut_objs:
sc = json2sc(sc_obj.shortcut)
if username:
sc.set_expanded_path(expand_windows_var(sc.path, username))
shortcuts.append(sc)
return shortcuts
def write_shortcut(shortcut, username=None):
def apply_shortcut(shortcut, username=None):
'''
Write the single shortcut file to the disk.
Apply the single shortcut file to the disk.
:username: None means working with machine variables and paths
'''
dest_abspath = expand_windows_var(shortcut.dest, username).replace('\\', '/') + '.desktop'
logging.debug(slogm('Writing shortcut file to {}'.format(dest_abspath)))
shortcut.write_desktop(dest_abspath)
dest_abspath = shortcut.dest
if not dest_abspath.startswith('/') and not dest_abspath.startswith('%'):
dest_abspath = '%HOME%/' + dest_abspath
logging.debug(slogm('Try to expand path for shortcut: {} for {}'.format(dest_abspath, username)))
dest_abspath = expand_windows_var(dest_abspath, username).replace('\\', '/') + '.desktop'
# Check that we're working for user, not on global system level
if username:
# Check that link destination path starts with specification of
# user's home directory
if dest_abspath.startswith(get_homedir(username)):
# Don't try to operate on non-existent directory
if not homedir_exists(username):
logging.warning(slogm('No home directory exists for user {}: will not apply link {}'.format(username, dest_abspath)))
return None
else:
logging.warning(slogm('User\'s shortcut not placed to home directory for {}: bad path {}'.format(username, dest_abspath)))
return None
if '%' in dest_abspath:
logging.debug(slogm('Fail for applying shortcut to file with \'%\': {}'.format(dest_abspath)))
return None
if not dest_abspath.startswith('/'):
logging.debug(slogm('Fail for applying shortcut to not absolute path \'%\': {}'.format(dest_abspath)))
return None
logging.debug(slogm('Applying shortcut file to {} with action {}'.format(dest_abspath, shortcut.action)))
shortcut.apply_desktop(dest_abspath)
class shortcut_applier(applier_frontend):
__module_name = 'ShortcutsApplier'
__module_experimental = False
__module_enabled = True
def __init__(self, storage):
self.storage = storage
self.__module_enabled = check_enabled(
self.storage
, self.__module_name
, self.__module_experimental
)
def apply(self):
def run(self):
shortcuts = storage_get_shortcuts(self.storage, self.storage.get_info('machine_sid'))
if shortcuts:
for sc in shortcuts:
write_shortcut(sc)
apply_shortcut(sc)
if len(shortcuts) > 0:
# According to ArchWiki - this thing is needed to rebuild MIME
# type cache in order file bindings to work. This rebuilds
# databases located in /usr/share/applications and
# /usr/local/share/applications
subprocess.check_call(['/usr/bin/update-desktop-database'])
else:
logging.debug(slogm('No shortcuts to process for {}'.format(self.storage.get_info('machine_sid'))))
# According to ArchWiki - this thing is needed to rebuild MIME
# type cache in order file bindings to work. This rebuilds
# databases located in /usr/share/applications and
# /usr/local/share/applications
subprocess.check_call(['/usr/bin/update-desktop-database'])
def apply(self):
if self.__module_enabled:
logging.debug(slogm('Running Shortcut applier for machine'))
self.run()
else:
logging.debug(slogm('Shortcut applier for machine will not be started'))
class shortcut_applier_user(applier_frontend):
__module_name = 'ShortcutsApplierUser'
__module_experimental = False
__module_enabled = True
def __init__(self, storage, sid, username):
self.storage = storage
self.sid = sid
self.username = username
def user_context_apply(self):
shortcuts = storage_get_shortcuts(self.storage, self.sid)
def run(self, in_usercontext):
shortcuts = storage_get_shortcuts(self.storage, self.sid, self.username)
if shortcuts:
for sc in shortcuts:
if sc.is_usercontext():
write_shortcut(sc, self.username)
if in_usercontext and sc.is_usercontext():
apply_shortcut(sc, self.username)
if not in_usercontext and not sc.is_usercontext():
apply_shortcut(sc, self.username)
else:
logging.debug(slogm('No shortcuts to process for {}'.format(self.sid)))
def user_context_apply(self):
if self.__module_enabled:
logging.debug(slogm('Running Shortcut applier for user in user context'))
self.run(True)
else:
logging.debug(slogm('Shortcut applier for user in user context will not be started'))
def admin_context_apply(self):
shortcuts = storage_get_shortcuts(self.storage, self.sid)
if shortcuts:
for sc in shortcuts:
if not sc.is_usercontext():
write_shortcut(sc, self.username)
if self.__module_enabled:
logging.debug(slogm('Running Shortcut applier for user in administrator context'))
self.run(False)
else:
logging.debug(slogm('No shortcuts to process for {}'.format(self.sid)))
logging.debug(slogm('Shortcut applier for user in administrator context will not be started'))

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,28 +13,35 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from .applier_frontend import applier_frontend
from .applier_frontend import (
applier_frontend
, check_enabled
)
from .appliers.systemd import systemd_unit
from util.logging import slogm
import logging
class systemd_applier(applier_frontend):
__module_name = 'SystemdApplier'
__module_experimental = False
__module_enabled = True
__registry_branch = 'Software\\BaseALT\\Policies\\SystemdUnits'
def __init__(self, storage):
self.storage = storage
self.systemd_unit_settings = self.storage.filter_hklm_entries('Software\\BaseALT\\Policies\\SystemdUnits%')
self.units = []
self.__module_enabled = check_enabled(
self.storage
, self.__module_name
, self.__module_experimental
)
def apply(self):
'''
Trigger control facility invocation.
'''
def run(self):
for setting in self.systemd_unit_settings:
valuename = setting.hive_key.rpartition('\\')[2]
try:
@@ -46,7 +55,20 @@ class systemd_applier(applier_frontend):
except:
logging.error(slogm('Failed applying unit {}'.format(unit.unit_name)))
def apply(self):
'''
Trigger control facility invocation.
'''
if self.__module_enabled:
logging.debug(slogm('Running systemd applier for machine'))
self.run()
else:
logging.debug(slogm('systemd applier for machine will not be started'))
class systemd_applier_user(applier_frontend):
__module_name = 'SystemdApplierUser'
__module_experimental = False
__module_enabled = True
__registry_branch = 'Software\\BaseALT\\Policies\\SystemdUnits'
def __init__(self, storage, sid, username):

104
gpoa/gpoa
View File

@@ -1,10 +1,12 @@
#! /usr/bin/env python3
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -12,20 +14,21 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import argparse
import logging
import os
import signal
import gettext
import locale
from backend import backend_factory
from frontend.frontend_manager import frontend_manager, determine_username
from plugin import plugin_manager
from messages import message_with_code
from util.util import get_machine_name
from util.kerberos import machine_kinit
from util.users import (
is_root,
get_process_user
@@ -33,7 +36,9 @@ from util.users import (
from util.arguments import (
set_loglevel
)
from util.logging import slogm
from util.logging import log
from util.exceptions import geterr
from util.signals import signal_handler
def parse_arguments():
arguments = argparse.ArgumentParser(description='Generate configuration out of parsed policies')
@@ -53,6 +58,9 @@ def parse_arguments():
arguments.add_argument('--noplugins',
action='store_true',
help='Don\'t start plugins')
arguments.add_argument('--list-backends',
action='store_true',
help='Show list of available backends')
arguments.add_argument('--loglevel',
type=int,
default=4,
@@ -60,34 +68,60 @@ def parse_arguments():
return arguments.parse_args()
class gpoa_controller:
__kinit_successful = False
__args = None
def __init__(self):
self.__args = parse_arguments()
self.is_machine = False
if not self.__args.user:
user = get_machine_name()
self.is_machine = True
self.noupdate = self.__args.noupdate
set_loglevel(self.__args.loglevel)
self.__kinit_successful = machine_kinit()
locale.bindtextdomain('gpoa', '/usr/lib/python3/site-packages/gpoa/locale')
gettext.bindtextdomain('gpoa', '/usr/lib/python3/site-packages/gpoa/locale')
gettext.textdomain('gpoa')
if not self.__args.user:
self.username = get_machine_name()
self.is_machine = True
else:
self.username = self.__args.user
uname = get_process_user()
uid = os.getuid()
logging.debug(slogm('The process was started for user {} with UID {}'.format(uname, uid), uid=uid))
logdata = dict()
logdata['username'] = self.username
logdata['is_machine'] = self.is_machine
logdata['process_username'] = uname
logdata['process_uid'] = uid
if self.is_machine:
log('D61', logdata)
else:
log('D1', logdata)
self.username = determine_username(self.username)
if not is_root():
self.username = uname
self.noupdate = True
if self.is_machine:
msgtext = message_with_code('E34')
log('E34', {'username': self.username})
raise Exception(msgtext)
log('D59', {'username': self.username})
else:
self.username = determine_username(self.__args.user)
log('D60', {'username': self.username})
def run(self):
'''
GPOA controller entry point
'''
if self.__args.list_backends:
print('local')
print('samba')
return
self.start_plugins()
self.start_backend()
self.start_frontend()
def start_backend(self):
'''
@@ -98,11 +132,33 @@ class gpoa_controller:
if self.__args.nodomain:
nodomain = True
if not self.__args.noupdate:
if not self.noupdate:
if is_root():
back = backend_factory(dc, self.username, self.is_machine, nodomain)
back = None
try:
back = backend_factory(dc, self.username, self.is_machine, nodomain)
except Exception as exc:
logdata = dict({'msg': str(exc)})
einfo = geterr()
print(einfo)
print(type(einfo))
#logdata.update(einfo)
log('E12', logdata)
if back:
back.retrieve_and_store()
try:
back.retrieve_and_store()
# Start frontend only on successful backend finish
self.start_frontend()
except Exception as exc:
logdata = dict({'message': str(exc)})
# In case we're handling "E3" - it means that
# this is a very specific exception that was
# not handled properly on lower levels of
# code so we're also printing file name and
# other information.
einfo = geterr()
logdata.update(einfo)
log('E3', logdata)
def start_frontend(self):
'''
@@ -112,7 +168,11 @@ class gpoa_controller:
appl = frontend_manager(self.username, self.is_machine)
appl.apply_parameters()
except Exception as exc:
logging.error(slogm('Error occured while running applier: {}'.format(exc)))
logdata = dict({'message': str(exc)})
einfo = geterr()
#print(einfo)
logdata.update(einfo)
log('E4', logdata)
def start_plugins(self):
'''
@@ -127,5 +187,7 @@ def main():
controller.run()
if __name__ == "__main__":
default_handler = signal.getsignal(signal.SIGINT)
signal.signal(signal.SIGINT, signal_handler)
main()

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,7 +13,6 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,9 +13,8 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import json
from base64 import b64decode
@@ -21,24 +22,13 @@ from Crypto.Cipher import AES
from util.xml import get_xml_root
def read_drives(drives_file):
drives = list()
for drive in get_xml_root(drives_file):
drive_obj = drivemap()
props = drive.find('Properties')
drive_obj.set_login(props.get('username'))
drive_obj.set_pass(props.get('cpassword'))
drives.append(drive_obj)
return drives
def decrypt_pass(cpassword):
'''
AES key for cpassword decryption: http://msdn.microsoft.com/en-us/library/2c15cbf0-f086-4c74-8b70-1f2fa45dd4be%28v=PROT.13%29#endNote2
'''
if not cpassword:
return cpassword
key = (
b'\x4e\x99\x06\xe8'
b'\xfc\xb6\x6c\xc9'
@@ -52,23 +42,80 @@ def decrypt_pass(cpassword):
cpass_len = len(cpassword)
padded_pass = (cpassword + "=" * ((4 - cpass_len % 4) % 4))
password = b64decode(padded_pass)
decrypter = AES(key, AES.MODE_CBC, '\x00' * 16)
decrypter = AES.new(key, AES.MODE_CBC, '\x00' * 16)
return decrypter.decrypt(password)
# decrypt() returns byte array which is immutable and we need to
# strip padding, then convert UTF-16LE to UTF-8
binstr = decrypter.decrypt(password)
by = list()
for item in binstr:
if item != 16:
by.append(item)
utf16str = bytes(by).decode('utf-16', 'ignore')
utf8str = utf16str.encode('utf8')
return utf8str.decode()
def read_drives(drives_file):
drives = list()
for drive in get_xml_root(drives_file):
drive_obj = drivemap()
props = drive.find('Properties')
drive_obj.set_login(props.get('username'))
drive_obj.set_pass(decrypt_pass(props.get('cpassword')))
drive_obj.set_dir(props.get('letter'))
drive_obj.set_path(props.get('path'))
drives.append(drive_obj)
return drives
def merge_drives(storage, sid, drive_objects, policy_name):
for drive in drive_objects:
storage.add_drive(sid, drive, policy_name)
def json2drive(json_str):
json_obj = json.loads(json_str)
drive_obj = drivemap()
drive_obj.set_login(json_obj['login'])
drive_obj.set_pass(json_obj['password'])
drive_obj.set_dir(json_obj['dir'])
drive_obj.set_path(json_obj['path'])
return drive_obj
class drivemap:
def __init__(self):
self.login = None
self.password = None
self.dir = None
self.path = None
def set_login(self, username):
self.login = username
if not username:
self.login = ''
def set_pass(self, password):
self.password = password
if not password:
self.password = ''
def set_dir(self, path):
self.dir = path
def set_path(self, path):
self.path = path
def to_json(self):
drive = dict()
drive['login'] = self.login
drive['password'] = self.password
drive['dir'] = self.dir
drive['path'] = self.path
contents = dict()
contents['drive'] = drive

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,23 +13,53 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from util.xml import get_xml_root
from enum import Enum
class FileAction(Enum):
CREATE = 'C'
REPLACE = 'R'
UPDATE = 'U'
DELETE = 'D'
def action_letter2enum(letter):
if letter in ['C', 'R', 'U', 'D']:
if letter == 'C': return FileAction.CREATE
if letter == 'R': return FileAction.REPLACE
if letter == 'U': return FileAction.UPDATE
if letter == 'D': return FileAction.DELETE
return FileAction.CREATE
def read_envvars(envvars_file):
variables = list()
for var in get_xml_root(envvars_file):
var_obj = envvar()
props = var.find('Properties')
name = props.get('name')
value = props.get('value')
var_obj = envvar(name, value)
var_obj.set_action(action_letter2enum(props.get('action', default='C')))
variables.append(var_obj)
return variables
class envvar:
def __init__(self):
pass
def merge_envvars(storage, sid, envvar_objects, policy_name):
for envv in envvar_objects:
storage.add_envvar(sid, envv, policy_name)
class envvar:
def __init__(self, name, value):
self.name = name
self.value = value
self.action = FileAction.CREATE
def set_action(self, action):
self.action = action

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,9 +13,8 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from util.xml import get_xml_root
@@ -27,6 +28,10 @@ def read_files(filesxml):
return files
def merge_files(storage, sid, file_objects, policy_name):
for fileobj in file_objects:
pass
class fileentry:
def __init__(self):
pass

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,23 +13,86 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from enum import Enum
from util.xml import get_xml_root
class FileAction(Enum):
CREATE = 'C'
REPLACE = 'R'
UPDATE = 'U'
DELETE = 'D'
def action_letter2enum(letter):
if letter in ['C', 'R', 'U', 'D']:
if letter == 'C': return FileAction.CREATE
if letter == 'R': return FileAction.REPLACE
if letter == 'U': return FileAction.UPDATE
if letter == 'D': return FileAction.DELETE
return FileAction.CREATE
def action_enum2letter(enumitem):
return enumitem.value
def folder_int2bool(val):
value = val
if type(value) == str:
value = int(value)
if value == 0:
return True
return False
def read_folders(folders_file):
folders = list()
for fld in get_xml_root(folders_file):
fld_obj = folderentry()
props = fld.find('Properties')
fld_obj = folderentry(props.get('path'))
fld_obj.set_action(action_letter2enum(props.get('action', default='C')))
fld_obj.set_delete_folder(folder_int2bool(props.get('deleteFolder', default=1)))
fld_obj.set_delete_sub_folders(folder_int2bool(props.get('deleteSubFolders', default=1)))
fld_obj.set_delete_files(folder_int2bool(props.get('deleteFiles', default=1)))
folders.append(fld_obj)
return folders
class folderentry:
def __init__(self):
pass
def merge_folders(storage, sid, folder_objects, policy_name):
for folder in folder_objects:
storage.add_folder(sid, folder, policy_name)
class folderentry:
def __init__(self, path):
self.path = path
self.action = FileAction.CREATE
self.delete_folder = False
self.delete_sub_folders = False
self.delete_files = False
def set_action(self, action):
self.action = action
def set_delete_folder(self, del_bool):
self.delete_folder = del_bool
def set_delete_sub_folders(self, del_bool):
self.delete_sub_folders = del_bool
def set_delete_files(self, del_bool):
self.delete_files = del_bool

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,32 +13,131 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
import os
from pathlib import Path
from enum import Enum, unique
from samba.gp_parse.gp_pol import GPPolParser
from storage import registry_factory
from .shortcuts import read_shortcuts
from .services import read_services
from .printers import read_printers
from .inifiles import read_inifiles
from .folders import read_folders
from .files import read_files
from .envvars import read_envvars
from .drives import read_drives
from .polfile import (
read_polfile
, merge_polfile
)
from .shortcuts import (
read_shortcuts
, merge_shortcuts
)
from .services import (
read_services
, merge_services
)
from .printers import (
read_printers
, merge_printers
)
from .inifiles import (
read_inifiles
, merge_inifiles
)
from .folders import (
read_folders
, merge_folders
)
from .files import (
read_files
, merge_files
)
from .envvars import (
read_envvars
, merge_envvars
)
from .drives import (
read_drives
, merge_drives
)
from .tasks import (
read_tasks
, merge_tasks
)
import util
import util.preg
from util.paths import (
default_policy_path,
local_policy_path,
cache_dir,
local_policy_cache
)
from util.logging import slogm
from util.logging import log
@unique
class FileType(Enum):
PREG = 'registry.pol'
SHORTCUTS = 'shortcuts.xml'
FOLDERS = 'folders.xml'
FILES = 'files.xml'
DRIVES = 'drives.xml'
SCHEDULEDTASKS = 'scheduledtasks.xml'
ENVIRONMENTVARIABLES = 'environmentvariables.xml'
INIFILES = 'inifiles.xml'
SERVICES = 'services.xml'
PRINTERS = 'printers.xml'
def get_preftype(path_to_file):
fpath = Path(path_to_file)
if fpath.exists():
file_name = fpath.name.lower()
for item in FileType:
if file_name == item.value:
return item
return None
def pref_parsers():
parsers = dict()
parsers[FileType.PREG] = read_polfile
parsers[FileType.SHORTCUTS] = read_shortcuts
parsers[FileType.FOLDERS] = read_folders
parsers[FileType.FILES] = read_files
parsers[FileType.DRIVES] = read_drives
parsers[FileType.SCHEDULEDTASKS] = read_tasks
parsers[FileType.ENVIRONMENTVARIABLES] = read_envvars
parsers[FileType.INIFILES] = read_inifiles
parsers[FileType.SERVICES] = read_services
parsers[FileType.PRINTERS] = read_printers
return parsers
def get_parser(preference_type):
parsers = pref_parsers()
return parsers[preference_type]
def pref_mergers():
mergers = dict()
mergers[FileType.PREG] = merge_polfile
mergers[FileType.SHORTCUTS] = merge_shortcuts
mergers[FileType.FOLDERS] = merge_folders
mergers[FileType.FILES] = merge_files
mergers[FileType.DRIVES] = merge_drives
mergers[FileType.SCHEDULEDTASKS] = merge_tasks
mergers[FileType.ENVIRONMENTVARIABLES] = merge_envvars
mergers[FileType.INIFILES] = merge_inifiles
mergers[FileType.SERVICES] = merge_services
mergers[FileType.PRINTERS] = merge_printers
return mergers
def get_merger(preference_type):
mergers = pref_mergers()
return mergers[preference_type]
class gpt:
__user_policy_mode_key = 'Software\\Policies\\Microsoft\\Windows\\System\\UserPolicyMode'
@@ -45,26 +146,40 @@ class gpt:
self.path = gpt_path
self.sid = sid
self.storage = registry_factory('registry')
self._scan_gpt()
def _scan_gpt(self):
'''
Collect the data from the specified GPT on file system (cached
by Samba).
'''
self.guid = self.path.rpartition('/')[2]
self.name = ''
self.guid = self.path.rpartition('/')[2]
if 'default' == self.guid:
self.guid = 'Local Policy'
self._machine_path = None
self._user_path = None
self._get_machine_user_dirs()
self._machine_path = find_dir(self.path, 'Machine')
self._user_path = find_dir(self.path, 'User')
logging.debug(slogm('Looking for machine part of GPT {}'.format(self.guid)))
self._find_machine()
logging.debug(slogm('Looking for user part of GPT {}'.format(self.guid)))
self._find_user()
self.settings_list = [
'shortcuts'
, 'drives'
, 'environmentvariables'
, 'printers'
, 'folders'
, 'files'
, 'inifiles'
, 'services'
, 'scheduledtasks'
]
self.settings = dict()
self.settings['machine'] = dict()
self.settings['user'] = dict()
self.settings['machine']['regpol'] = find_file(self._machine_path, 'registry.pol')
self.settings['user']['regpol'] = find_file(self._user_path, 'registry.pol')
for setting in self.settings_list:
machine_preffile = find_preffile(self._machine_path, setting)
user_preffile = find_preffile(self._user_path, setting)
mlogdata = dict({'setting': setting, 'prefpath': machine_preffile})
log('D24', mlogdata)
self.settings['machine'][setting] = machine_preffile
ulogdata = dict({'setting': setting, 'prefpath': user_preffile})
log('D23', ulogdata)
self.settings['user'][setting] = user_preffile
def set_name(self, name):
'''
@@ -87,167 +202,92 @@ class gpt:
return upm
def _get_machine_user_dirs(self):
'''
Find full path to Machine and User parts of GPT.
'''
entries = os.listdir(self.path)
for entry in entries:
full_entry_path = os.path.join(self.path, entry)
if os.path.isdir(full_entry_path):
if 'machine' == entry.lower():
self._machine_path = full_entry_path
if 'user' == entry.lower():
self._user_path = full_entry_path
def _find_user(self):
self._user_regpol = self._find_regpol('user')
self._user_shortcuts = self._find_shortcuts('user')
def _find_machine(self):
self._machine_regpol = self._find_regpol('machine')
self._machine_shortcuts = self._find_shortcuts('machine')
def _find_regpol(self, part):
'''
Find Registry.pol files.
'''
search_path = self._machine_path
if 'user' == part:
search_path = self._user_path
if not search_path:
return None
return find_file(search_path, 'registry.pol')
def _find_shortcuts(self, part):
'''
Find Shortcuts.xml files.
'''
search_path = os.path.join(self._machine_path, 'Preferences', 'Shortcuts')
if 'user' == part:
try:
search_path = os.path.join(self._user_path, 'Preferences', 'Shortcuts')
except Exception as exc:
return None
if not search_path:
return None
return find_file(search_path, 'shortcuts.xml')
def _find_envvars(self, part):
'''
Find EnvironmentVariables.xml files.
'''
search_path = os.path.join(self._machine_path, 'Preferences', 'EnvironmentVariables')
if 'user' == part:
search_path = os.path.join(self._user_path, 'Preferences', 'EnvironmentVariables')
if not search_path:
return None
return find_file(search_path, 'environmentvariables.xml')
def _find_drives(self, part):
'''
Find Drives.xml files.
'''
search_path = os.path.join(self._machine_path, 'Preferences', 'Drives')
if 'user' == part:
search_path = os.path.join(self._user_path, 'Preferences', 'Drives')
if not search_path:
return None
return find_file(search_path, 'drives.xml')
def _find_printers(self, part):
'''
Find Printers.xml files.
'''
search_path = os.path.join(self._machine_path, 'Preferences', 'Printers')
if 'user' == part:
search_path = os.path.join(self._user_path, 'Preferences', 'Printers')
if not search_path:
return None
return find_file(search_path, 'printers.xml')
def _merge_shortcuts(self):
shortcuts = list()
if self.sid == self.storage.get_info('machine_sid'):
shortcuts = read_shortcuts(self._machine_shortcuts)
else:
shortcuts = read_shortcuts(self._user_shortcuts)
for sc in shortcuts:
self.storage.add_shortcut(self.sid, sc)
def merge(self):
'''
Merge machine and user (if sid provided) settings to storage.
'''
if self.sid == self.storage.get_info('machine_sid'):
# Merge machine settings to registry if possible
if self._machine_regpol:
logging.debug(slogm('Merging machine settings from {}'.format(self._machine_regpol)))
util.preg.merge_polfile(self._machine_regpol)
if self._user_regpol:
logging.debug(slogm('Merging machine(user) settings from {}'.format(self._machine_regpol)))
util.preg.merge_polfile(self._user_regpol, self.machine_sid)
if self._machine_shortcuts:
logging.debug(slogm('Merging machine shortcuts from {}'.format(self._machine_shortcuts)))
self._merge_shortcuts()
try:
# Merge machine settings to registry if possible
for preference_name, preference_path in self.settings['machine'].items():
if preference_path:
preference_type = get_preftype(preference_path)
logdata = dict({'pref': preference_type.value, 'sid': self.sid})
log('D28', logdata)
preference_parser = get_parser(preference_type)
preference_merger = get_merger(preference_type)
preference_objects = preference_parser(preference_path)
preference_merger(self.storage, self.sid, preference_objects, self.name)
if self.settings['user']['regpol']:
mulogdata = dict({'polfile': self.settings['machine']['regpol']})
log('D35', mulogdata)
util.preg.merge_polfile(self.settings['user']['regpol'], sid=self.sid, policy_name=self.name)
if self.settings['machine']['regpol']:
mlogdata = dict({'polfile': self.settings['machine']['regpol']})
log('D34', mlogdata)
util.preg.merge_polfile(self.settings['machine']['regpol'], policy_name=self.name)
except Exception as exc:
logdata = dict()
logdata['gpt'] = self.name
logdata['msg'] = str(exc)
log('E28', logdata)
else:
# Merge user settings if UserPolicyMode set accordingly
# and user settings (for HKCU) are exist.
policy_mode = upm2str(self.get_policy_mode())
if 'Merge' == policy_mode or 'Not configured' == policy_mode:
if self._user_regpol:
logging.debug(slogm('Merging user settings from {} for {}'.format(self._user_regpol, self.sid)))
util.preg.merge_polfile(self._user_regpol, self.sid)
if self._user_shortcuts:
logging.debug(slogm('Merging user shortcuts from {} for {}'.format(self._user_shortcuts, self.sid)))
self._merge_shortcuts()
try:
for preference_name, preference_path in self.settings['user'].items():
if preference_path:
preference_type = get_preftype(preference_path)
logdata = dict({'pref': preference_type.value, 'sid': self.sid})
log('D29', logdata)
preference_parser = get_parser(preference_type)
preference_merger = get_merger(preference_type)
preference_objects = preference_parser(preference_path)
preference_merger(self.storage, self.sid, preference_objects, self.name)
except Exception as exc:
logdata = dict()
logdata['gpt'] = self.name
logdata['msg'] = str(exc)
log('E29', logdata)
def __str__(self):
template = '''
GUID: {}
Name: {}
For SID: {}
def find_dir(search_path, name):
'''
Attempt for case-insensitive search of directory
Machine part: {}
Machine Registry.pol: {}
Machine Shortcuts.xml: {}
:param search_path: Path to get file list from
:param name: Name of the directory to search for
'''
if not search_path:
return None
User part: {}
User Registry.pol: {}
User Shortcuts.xml: {}
try:
file_list = os.listdir(search_path)
for entry in file_list:
dir_path = os.path.join(search_path, entry)
if os.path.isdir(dir_path) and name.lower() == str(entry).lower():
return dir_path
except Exception as exc:
pass
'''
result = template.format(
self.guid,
self.name,
self.sid,
self._machine_path,
self._machine_regpol,
self._machine_shortcuts,
self._user_path,
self._user_regpol,
self._user_shortcuts,
)
return result
return None
def find_file(search_path, name):
'''
Attempt for case-insensitive file search in directory.
'''
if not search_path:
return None
if not name:
return None
try:
file_list = os.listdir(search_path)
for entry in file_list:
file_path = os.path.join(search_path, entry)
if os.path.isfile(file_path) and name.lower() == entry.lower():
if os.path.isfile(file_path) and name.lower() == str(entry).lower():
return file_path
except Exception as exc:
#logging.error(exc)
@@ -255,11 +295,38 @@ def find_file(search_path, name):
return None
def find_preferences(search_path):
'''
Find 'Preferences' directory
'''
if not search_path:
return None
return find_dir(search_path, 'Preferences')
def find_preffile(search_path, prefname):
'''
Find file with path like Preferences/prefname/prefname.xml
'''
# Look for 'Preferences' directory
prefdir = find_preferences(search_path)
if not prefdir:
return None
# Then search for preference directory
pref_dir = find_dir(prefdir, prefname)
file_name = '{}.xml'.format(prefname)
# And then try to find the corresponding file.
pref_file = find_file(pref_dir, file_name)
return pref_file
def lp2gpt():
'''
Convert local-policy to full-featured GPT.
'''
lppath = os.path.join(default_policy_path(), 'local.xml')
lppath = os.path.join(local_policy_path(), 'Machine/Registry.pol.xml')
# Load settings from XML PolFile
polparser = GPPolParser()
@@ -277,7 +344,7 @@ def get_local_gpt(sid):
'''
Convert default policy to GPT and create object out of it.
'''
logging.debug(slogm('Re-caching Local Policy'))
log('D25')
lp2gpt()
local_policy = gpt(str(local_policy_cache()), sid)
local_policy.set_name('Local Policy')

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,9 +13,8 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from util.xml import get_xml_root
@@ -27,6 +28,10 @@ def read_inifiles(inifiles_file):
return inifiles
def merge_inifiles(storage, sid, inifile_objects, policy_name):
for inifile in inifile_objects:
pass
def inifile():
def __init__(self):
pass

32
gpoa/gpt/polfile.py Normal file
View File

@@ -0,0 +1,32 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from util.preg import (
load_preg
)
def read_polfile(filename):
return load_preg(filename).entries
def merge_polfile(storage, sid, policy_objects, policy_name):
for entry in policy_objects:
if not sid:
storage.add_hklm_entry(entry, policy_name)
else:
storage.add_hkcu_entry(entry, sid, policy_name)

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,9 +13,8 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import json
@@ -40,6 +41,10 @@ def read_printers(printers_file):
return printers
def merge_printers(storage, sid, printer_objects, policy_name):
for device in printer_objects:
storage.add_printer(sid, device, policy_name)
def json2printer(json_str):
'''
Build printer object out of string-serialized JSON.

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,9 +13,8 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from util.xml import get_xml_root
@@ -38,6 +39,10 @@ def read_services(service_file):
return services
def merge_services(storage, sid, service_objects, policy_name):
for srv in service_objects:
pass
class service:
def __init__(self, name):
self.unit = name

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,11 +13,13 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from pathlib import Path
import stat
import logging
from enum import Enum
from xml.etree import ElementTree
from xdg.DesktopEntry import DesktopEntry
@@ -24,48 +28,107 @@ import json
from util.windows import transform_windows_path
from util.xml import get_xml_root
class TargetType(Enum):
FILESYSTEM = 'FILESYSTEM'
URL = 'URL'
def get_ttype(targetstr):
'''
Validation function for targetType property
:targetstr: String representing link type.
:returns: Object of type TargetType.
'''
ttype = TargetType.FILESYSTEM
if targetstr == 'URL':
ttype = TargetType.URL
return ttype
def ttype2str(ttype):
'''
Transform TargetType to string for JSON serialization
:param ttype: TargetType object
'''
result = 'FILESYSTEM'
if ttype == TargetType.URL:
result = 'URL'
return result
def read_shortcuts(shortcuts_file):
'''
Read shortcut objects from GPTs XML file
:shortcuts_file: Location of Shortcuts.xml
'''
shortcuts = list()
for link in get_xml_root(shortcuts_file):
props = link.find('Properties')
# Location of the link itself
dest = props.get('shortcutPath')
# Location where link should follow
path = transform_windows_path(props.get('targetPath'))
# Arguments to executable file
arguments = props.get('arguments')
sc = shortcut(dest, path, arguments, link.get('name'))
# URL or FILESYSTEM
target_type = get_ttype(props.get('targetType'))
sc = shortcut(dest, path, arguments, link.get('name'), props.get('action'), target_type)
sc.set_changed(link.get('changed'))
sc.set_clsid(link.get('clsid'))
sc.set_guid(link.get('uid'))
sc.set_usercontext(link.get('userContext', False))
sc.set_icon(props.get('iconPath'))
shortcuts.append(sc)
return shortcuts
def merge_shortcuts(storage, sid, shortcut_objects, policy_name):
for shortcut in shortcut_objects:
storage.add_shortcut(sid, shortcut, policy_name)
def json2sc(json_str):
'''
Build shortcut out of string-serialized JSON
'''
json_obj = json.loads(json_str)
link_type = get_ttype(json_obj['type'])
sc = shortcut(json_obj['dest'], json_obj['path'], json_obj['arguments'], json_obj['name'])
sc = shortcut(json_obj['dest'], json_obj['path'], json_obj['arguments'], json_obj['name'], json_obj['action'], link_type)
sc.set_changed(json_obj['changed'])
sc.set_clsid(json_obj['clsid'])
sc.set_guid(json_obj['guid'])
sc.set_usercontext(json_obj['is_in_user_context'])
if 'icon' in json_obj:
sc.set_icon(json_obj['icon'])
return sc
class shortcut:
def __init__(self, dest, path, arguments, name=None):
def __init__(self, dest, path, arguments, name=None, action=None, ttype=TargetType.FILESYSTEM):
'''
:param dest: Path to resulting file on file system
:param path: Path where the link should point to
:param arguments: Arguemnts to eecutable file
:param name: Name of the application
:param type: Link type - FILESYSTEM or URL
'''
self.dest = dest
self.path = path
self.expanded_path = None
self.arguments = arguments
self.name = name
self.action = action
self.changed = ''
self.icon = None
self.is_in_user_context = self.set_usercontext()
self.type = ttype
def __str__(self):
result = self.to_json()
@@ -83,6 +146,17 @@ class shortcut:
def set_guid(self, uid):
self.guid = uid
def set_icon(self, icon_name):
self.icon = icon_name
def set_type(self, ttype):
'''
Set type of the hyperlink - FILESYSTEM or URL
:ttype: - object of class TargetType
'''
self.type = ttype
def set_usercontext(self, usercontext=False):
'''
Perform action in user context or not
@@ -94,6 +168,12 @@ class shortcut:
self.is_in_user_context = ctx
def set_expanded_path(self, path):
'''
Adjust shortcut path with expanding windows variables
'''
self.expanded_path = path
def is_usercontext(self):
return self.is_in_user_context
@@ -109,30 +189,88 @@ class shortcut:
content['clsid'] = self.clsid
content['guid'] = self.guid
content['changed'] = self.changed
content['action'] = self.action
content['is_in_user_context'] = self.is_in_user_context
content['type'] = ttype2str(self.type)
if self.icon:
content['icon'] = self.icon
result = self.desktop()
result.content.update(content)
return json.dumps(result.content)
def desktop(self):
def desktop(self, dest=None):
'''
Returns desktop file object which may be written to disk.
'''
self.desktop_file = DesktopEntry()
self.desktop_file.addGroup('Desktop Entry')
self.desktop_file.set('Type', 'Application')
self.desktop_file.set('Version', '1.0')
self.desktop_file.set('Terminal', 'false')
self.desktop_file.set('Exec', '{} {}'.format(self.path, self.arguments))
self.desktop_file.set('Name', self.name)
if dest:
self.desktop_file = DesktopEntry(dest)
else:
self.desktop_file = DesktopEntry()
self.desktop_file.addGroup('Desktop Entry')
self.desktop_file.set('Version', '1.0')
self._update_desktop()
return self.desktop_file
def write_desktop(self, dest):
def _update_desktop(self):
'''
Write .desktop file to disk using path 'dest'
Update desktop file object from internal data.
'''
self.desktop().write(dest)
if self.type == TargetType.URL:
self.desktop_file.set('Type', 'Link')
else:
self.desktop_file.set('Type', 'Application')
self.desktop_file.set('Name', self.name)
desktop_path = self.path
if self.expanded_path:
desktop_path = self.expanded_path
if self.type == TargetType.URL:
self.desktop_file.set('URL', desktop_path)
else:
self.desktop_file.set('Terminal', 'false')
self.desktop_file.set('Exec', '{} {}'.format(desktop_path, self.arguments))
if self.icon:
self.desktop_file.set('Icon', self.icon)
def _write_desktop(self, dest, create_only=False, read_firstly=False):
'''
Write .desktop file to disk using path 'dest'. Please note that
.desktop files must have executable bit set in order to work in
GUI.
'''
sc = Path(dest)
if sc.exists() and create_only:
return
if sc.exists() and read_firstly:
self.desktop(dest).write(dest)
else:
self.desktop().write(dest)
sc.chmod(sc.stat().st_mode | stat.S_IEXEC)
def _remove_desktop(self, dest):
'''
Remove .desktop file fromo disk using path 'dest'.
'''
sc = Path(dest)
if sc.exists():
sc.unlink()
def apply_desktop(self, dest):
'''
Apply .desktop file by action.
'''
if self.action == 'U':
self._write_desktop(dest, read_firstly=True)
elif self.action == 'D':
self._remove_desktop(dest)
elif self.action == 'R':
self._remove_desktop(dest)
self._write_desktop(dest)
elif self.action == 'C':
self._write_desktop(dest, create_only=True)

25
gpoa/gpt/tasks.py Normal file
View File

@@ -0,0 +1,25 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
def read_tasks(filename):
pass
def merge_tasks(storage, sid, task_objects, policy_name):
for task in task_objects:
pass

View File

@@ -1,10 +1,12 @@
#! /usr/bin/env python3
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -12,31 +14,35 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import argparse
import locale
import gettext
import subprocess
import os
import sys
import logging
import pwd
import signal
from util.users import (
is_root
)
from util.arguments import (
process_target
process_target,
set_loglevel,
ExitCodeUpdater
)
from util.dbus import (
is_oddjobd_gpupdate_accessible,
dbus_runner
)
from util.signals import signal_handler
logging.basicConfig(level=logging.DEBUG)
from util.logging import log
#logging.basicConfig(level=logging.DEBUG)
class file_runner:
_gpoa_exe = '/usr/sbin/gpoa'
@@ -80,27 +86,24 @@ def runner_factory(args, target):
if is_root():
# Only root may specify any username to update.
try:
username = pwd.getpwnam(args.user).pw_name
if args.user:
username = pwd.getpwnam(args.user).pw_name
else:
target = 'Computer'
except:
username = None
logstring = (
'Unable to perform gpupdate for non-existent user {},'
' will update machine settings'
)
logging.error(logstring.format(args.user))
logdata = dict({'username': args.user})
log('W1', logdata)
else:
# User may only perform gpupdate for machine (None) or
# itself (os.getusername()).
username = pwd.getpwuid(os.getuid()).pw_name
if args.user != username:
logstring = (
'Unable to perform gpupdate for {} with current'
' permissions, will update current user settings'
)
logging.error(logstring.format(args.user))
logdata = dict({'username': args.user})
log('W2', logdata)
if is_oddjobd_gpupdate_accessible():
logging.debug('Starting gpupdate via D-Bus')
log('D13')
computer_runner = None
user_runner = None
if target == 'All' or target == 'Computer':
@@ -110,10 +113,10 @@ def runner_factory(args, target):
user_runner = dbus_runner(username)
return (computer_runner, user_runner)
else:
logging.warning('oddjobd is inaccessible')
log('W3')
if is_root():
logging.debug('Starting gpupdate by command invocation')
log('D14')
computer_runner = None
user_runner = None
if target == 'All' or target == 'Computer':
@@ -122,21 +125,41 @@ def runner_factory(args, target):
user_runner = file_runner(username)
return (computer_runner, user_runner)
else:
logging.error('Insufficient permissions to run gpupdate')
log('E1')
return None
def main():
args = parse_cli_arguments()
locale.bindtextdomain('gpoa', '/usr/lib/python3/site-packages/gpoa/locale')
gettext.bindtextdomain('gpoa', '/usr/lib/python3/site-packages/gpoa/locale')
gettext.textdomain('gpoa')
set_loglevel(0)
gpo_appliers = runner_factory(args, process_target(args.target))
if gpo_appliers:
if gpo_appliers[0]:
gpo_appliers[0].run()
try:
gpo_appliers[0].run()
except Exception as exc:
logdata = dict({'error': str(exc)})
log('E5')
return int(ExitCodeUpdater.FAIL_GPUPDATE_COMPUTER_NOREPLY)
if gpo_appliers[1]:
gpo_appliers[1].run()
try:
gpo_appliers[1].run()
except Exception as exc:
logdata = dict({'error': str(exc)})
log('E6', logdata)
return int(ExitCodeUpdater.FAIL_GPUPDATE_USER_NOREPLY)
else:
logging.error('gpupdate will not be started')
log('E2')
return int(ExitCodeUpdater.FAIL_NO_RUNNER)
return int(ExitCodeUpdater.EXIT_SUCCESS)
if __name__ == '__main__':
main()
signal.signal(signal.SIGINT, signal_handler)
sys.exit(int(main()))

327
gpoa/gpupdate-setup Executable file
View File

@@ -0,0 +1,327 @@
#! /usr/bin/env python3
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
import argparse
import subprocess
from util.util import (
runcmd
, get_backends
, get_default_policy_name
, get_policy_entries
, get_policy_variants
)
from util.config import GPConfig
from util.paths import get_custom_policy_dir
class Runner:
__control_path = '/usr/sbin/control'
__systemctl_path = '/bin/systemctl'
def __init__(self):
self.arguments = parse_arguments()
def parse_arguments():
'''
Parse CLI arguments.
'''
parser = argparse.ArgumentParser(prog='gpupdate-setup')
subparsers = parser.add_subparsers(dest='action',
metavar='action',
help='Group Policy management actions (default action is status)')
parser_list = subparsers.add_parser('list',
help='List avalable types of local policy')
parser_list = subparsers.add_parser('list-backends',
help='Show list of available backends')
parser_status = subparsers.add_parser('status',
help='Show current Group Policy status')
parser_enable = subparsers.add_parser('enable',
help='Enable Group Policy subsystem')
parser_disable = subparsers.add_parser('disable',
help='Disable Group Policy subsystem')
parser_write = subparsers.add_parser('write',
help='Operate on Group Policies (enable or disable)')
parser_set_backend = subparsers.add_parser('set-backend',
help='Set or change currently active backend')
parser_default = subparsers.add_parser('default-policy',
help='Show name of default policy')
parser_active = subparsers.add_parser('active-policy',
help='Show name of policy enabled')
parser_active_backend = subparsers.add_parser('active-backend',
help='Show currently configured backend')
parser_set_backend.add_argument('backend',
default='samba',
type=str,
nargs='?',
const='backend',
choices=['local', 'samba'],
help='Backend (source of settings) name')
parser_write.add_argument('status',
choices=['enable', 'disable'],
help='Enable or disable Group Policies')
parser_write.add_argument('localpolicy',
default=None,
nargs='?',
help='Name of local policy to enable')
parser_write.add_argument('backend',
default='samba',
type=str,
nargs='?',
const='backend',
choices=['local', 'samba'],
help='Backend (source of settings) name')
parser_enable.add_argument('--local-policy',
default=None,
help='Name of local policy to enable')
parser_enable.add_argument('--backend',
default='samba',
type=str,
choices=['local', 'samba'],
help='Backend (source of settings) name')
return parser.parse_args()
def validate_policy_name(policy_name):
return policy_name in [os.path.basename(d) for d in get_policy_variants()]
def is_unit_enabled(unit_name, unit_global=False):
'''
Check that designated systemd unit is enabled
'''
command = ['/bin/systemctl', 'is-enabled', unit_name]
if unit_global:
command = ['/bin/systemctl', '--global', 'is-enabled', unit_name]
value = runcmd(command)
# If first line of stdout is equal to "enabled" and return code
# is zero then unit is considered enabled.
rc = value[0]
result = []
try:
result = value[1].replace('\n', '')
except IndexError as exc:
return False
if result == 'enabled' and rc == 0:
return True
return False
def get_status():
'''
Check that gpupdate.service and gpupdate-user.service are enabled.
'''
is_gpupdate = is_unit_enabled('gpupdate.service')
is_gpupdate_user = is_unit_enabled('gpupdate-user.service', unit_global=True)
if is_gpupdate and is_gpupdate_user:
return True
return False
def get_active_policy_name():
'''
Show the name of an active Local Policy template
'''
config = GPConfig()
return os.path.basename(config.get_local_policy_template())
def get_active_backend():
config = GPConfig()
return config.get_backend()
def rollback_on_error(command_name):
'''
Disable group policy services in case command returns error code
'''
if 0 != runcmd(command_name)[0]:
disable_gp()
return False
return True
def disable_gp():
'''
Consistently disable group policy services
'''
cmd_set_global_policy = ['/usr/sbin/control', 'system-policy', 'remote']
cmd_set_local_policy = ['/usr/sbin/control', 'system-policy', 'local']
cmd_disable_gpupdate_service = ['/bin/systemctl', 'disable', 'gpupdate.service']
cmd_disable_gpupdate_user_service = ['/bin/systemctl', '--global', 'disable', 'gpupdate-user.service']
cmd_control_system_auth = ['/usr/sbin/control', 'system-auth']
config = GPConfig()
auth_result = 'local'
try:
auth_result = runcmd(cmd_control_system_auth)[1][0]
except Exception as exc:
print(str(exc))
if auth_result != 'local':
runcmd(cmd_set_global_policy)
else:
runcmd(cmd_set_local_policy)
runcmd(cmd_disable_gpupdate_service)
runcmd(cmd_disable_gpupdate_user_service)
config.set_local_policy_template()
config.set_backend()
def enable_gp(policy_name, backend_type):
'''
Consistently enable group policy services
'''
cmd_set_gpupdate_policy = ['/usr/sbin/control', 'system-policy', 'gpupdate']
cmd_gpoa_nodomain = ['/usr/sbin/gpoa', '--nodomain', '--loglevel', '5']
cmd_enable_gpupdate_service = ['/bin/systemctl', 'enable', 'gpupdate.service']
cmd_enable_gpupdate_user_service = ['/bin/systemctl', '--global', 'enable', 'gpupdate-user.service']
config = GPConfig()
custom_policy_dir = get_custom_policy_dir()
if not os.path.isdir(custom_policy_dir):
os.makedirs(custom_policy_dir)
target_policy_name = get_default_policy_name()
if policy_name:
if validate_policy_name(policy_name):
target_policy_name = policy_name
print (target_policy_name)
config.set_local_policy_template(target_policy_name)
config.set_backend(backend_type)
# Enable oddjobd_gpupdate in PAM config
if not rollback_on_error(cmd_set_gpupdate_policy):
return
# Bootstrap the Group Policy engine
if not rollback_on_error(cmd_gpoa_nodomain):
return
# Enable gpupdate.service
if not rollback_on_error(cmd_enable_gpupdate_service):
return
if not is_unit_enabled('gpupdate.service'):
disable_gp()
return
# Enable gpupdate-setup.service for all users
if not rollback_on_error(cmd_enable_gpupdate_user_service):
return
if not is_unit_enabled('gpupdate-user.service', unit_global=True):
disable_gp()
return
def act_list():
'''
Show list of available templates of Local Policy
'''
for entry in get_policy_variants():
print(entry.rpartition('/')[2])
def act_list_backends():
'''
List backends supported by GPOA
'''
backends = get_backends()
for backend in backends:
print(backend)
def act_status():
'''
Check that group policy services are enabled
'''
if get_status():
print('enabled')
else:
print('disabled')
def act_set_backend(backend_name):
config = GPConfig()
config.set_backend(backend_name)
def act_write(status, localpolicy, backend):
'''
Enable or disable group policy services
'''
if status == 'enable' or status == '#t':
enable_gp(localpolicy, backend)
if status == 'disable' or status == '#f':
disable_gp()
def act_enable(localpolicy, backend):
'''
Enable group policy services
'''
enable_gp(localpolicy, backend)
def act_active_policy():
'''
Print active Local Policy template name to stdout
'''
print(get_active_policy_name())
def act_active_backend():
'''
Print currently configured backend.
'''
print(get_active_backend())
def act_default_policy():
'''
Print default Local Policy template name to stdout
'''
print(get_default_policy_name())
def main():
arguments = parse_arguments()
action = dict()
action['list'] = act_list
action['list-backends'] = act_list_backends
action['status'] = act_status
action['set-backend'] = act_set_backend
action['write'] = act_write
action['enable'] = act_enable
action['disable'] = disable_gp
action['active-policy'] = act_active_policy
action['active-backend'] = act_active_backend
action['default-policy'] = act_default_policy
if arguments.action == None:
action['status']()
elif arguments.action == 'enable':
action[arguments.action](arguments.local_policy, arguments.backend)
elif arguments.action == 'write':
action[arguments.action](arguments.status, arguments.localpolicy, arguments.backend)
elif arguments.action == 'set-backend':
action[arguments.action](arguments.backend)
else:
action[arguments.action]()
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,334 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#domain "gpoa"
msgid ""
msgstr ""
"Project-Id-Version: 0.8.0\n"
"Report-Msgid-Bugs-To: samba@lists.altlinux.org\n"
"PO-Revision-Date: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain;charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Language: ru\n"
msgid "Don't start plugins"
msgstr "Не запускать модули"
# Info
msgid "Got GPO list for username"
msgstr "Получен список GPO для пользователя"
msgid "Got GPO"
msgstr "Получен объект групповой политики"
msgid "Unknown info code"
msgstr "Неизвестный код информационного сообщения"
# Error
msgid "Insufficient permissions to run gpupdate"
msgstr "Недостаточно прав для запуска gpupdate"
msgid "gpupdate will not be started"
msgstr "gpupdate не будет запущен"
msgid "Backend execution error"
msgstr "Ошибка бэкэнда"
msgid "Error occurred while running frontend manager"
msgstr "Ошибка фронтенда"
msgid "Error running GPOA for computer"
msgstr "Ошибка запуска GPOA для машины"
msgid "Error running GPOA for user"
msgstr "Ошибка запуска GPOA для пользователя"
msgid "Unable to initialize Samba backend"
msgstr "Невозможно инициализировать бэкэнд Samba"
msgid "Unable to initialize no-domain backend"
msgstr "Невозможно инициализировать бэкэнд-заглушку"
msgid "Error running ADP"
msgstr "Ошибка во время работы ADP"
msgid "Unable to determine DC hostname"
msgstr "Невозможно определить имя контроллера домена"
msgid "Error occured while running applier with user privileges"
msgstr "Ошибка во время работы applier в контексте пользователя"
msgid "Unable to initialize backend"
msgstr "Невозможно инициализировать бэкэнд"
msgid "Not sufficient privileges to run machine appliers"
msgstr "Недостаточно прав для запуска appliers для машины"
msgid "Kerberos ticket check failed"
msgstr "Проверка билета Kerberos закончилась неудачно"
msgid "Unable to retrieve domain name via CLDAP query"
msgstr "Не удалось определить имя домена AD через запрос к LDAP"
msgid "Error getting SID using wbinfo, will use SID from cache"
msgstr "Не удалось определить SID с использованием утилиты wbinfo, будет использоваться фиктивный/кэшированный SID"
msgid "Unable to get GPO list for user from AD DC"
msgstr "Не удалось получить список групповых политик для пользователя от контроллера домена AD"
msgid "Error getting XDG_DESKTOP_DIR"
msgstr "Не удалось получить значение XDG_DESKTOP_DIR"
msgid "Error occured while running user applier in administrator context"
msgstr "Ошибка выполнения applier в контексте администратора"
msgid "Error occured while running user applier in user context (with dropped privileges)"
msgstr "Ошибка работы пользовательского applier в пользовательском контексте (со сбросом привилегий процесса)"
msgid "No reply from oddjobd GPOA runner via D-Bus for current user"
msgstr "Не получен ответ от oddjobd для текущего пользователя"
msgid "No reply from oddjobd GPOA runner via D-Bus for computer"
msgstr "Не получен ответ от oddjobd для компьютера"
msgid "No reply from oddjobd GPOA runner via D-Bus for user"
msgstr "Не получен ответ от oddjobd для пользователя"
msgid "Error occured while running machine applier"
msgstr "Ошибка во время работы applier для машины"
msgid "Error occured while initializing user applier"
msgstr "Ошибка инициализации пользовательского applier"
msgid "Error merging machine GPT"
msgstr "Ошибка слияния машинной групповой политики"
msgid "Error merging user GPT"
msgstr "Ошибка слияния пользовательской групповой политики"
msgid "Error merging machine part of GPT"
msgstr "Ошибка слияния машинной части групповой политики"
msgid "Error merging user part of GPT"
msgstr "Ошибка слияния пользовательской части групповой политики"
msgid "Unknown error code"
msgstr "Неизвестный код ошибки"
# Debug
msgid "The GPOA process was started for user"
msgstr "Произведён запуск GPOA для обновления политик пользователя"
msgid "Username is not specified - will use username of the current process"
msgstr "Имя пользователя не указано - будет использовано имя владельца процесса"
msgid "Initializing plugin manager"
msgstr "Инициализация плагинов"
msgid "ADP plugin initialized"
msgstr "Инициализирован плагин ADP"
msgid "Running ADP plugin"
msgstr "Запущен плагин ADP"
msgid "Starting GPOA for user via D-Bus"
msgstr "Запускается GPOA для пользователя обращением к oddjobd через D-Bus"
msgid "Cache directory determined"
msgstr "Определена директория кэша Samba"
msgid "Initializing local backend without domain"
msgstr "Инициализация бэкэнда-заглушки"
msgid "Initializing Samba backend for domain"
msgstr "Инициализация бэкэнда Samba"
msgid "Group Policy target set for update"
msgstr "Групповые политики будут обновлены для указанной цели"
msgid "Starting GPOA for computer via D-Bus"
msgstr "Запускается GPOA для компьютера обращением к oddjobd через D-Bus"
msgid "Got exit code"
msgstr "Получен код возврата из утилиты"
msgid "Starting GPOA via D-Bus"
msgstr "Запускается GPOA обращением к oddjobd через D-Bus"
msgid "Starting GPOA via command invocation"
msgstr "GPOA запускается с помощью прямого вызова приложения"
msgid "Username for frontend is determined"
msgstr "Определено имя пользователя для фронтенда"
msgid "Applying computer part of settings"
msgstr "Применение настроек для машины"
msgid "Kerberos ticket check succeed"
msgstr "Проверка билета Kerberos прошла успешно"
msgid "Found AD domain via CLDAP query"
msgstr "Имя домена Active Directory успешно определено при запросе к LDAP"
msgid "Setting info"
msgstr "Установка вспомогательной переменной"
msgid "Initializing cache"
msgstr "Инициализация кэша"
msgid "Set operational SID"
msgstr "Установка рабочего SID"
msgid "Got PReg entry"
msgstr "Получен ключ реестра"
msgid "Looking for preference in user part of GPT"
msgstr "Поиск настроек в пользовательской части GPT"
msgid "Looking for preference in machine part of GPT"
msgstr "Поиск настроек в машинной части GPT"
msgid "Re-caching Local Policy"
msgstr "Обновление кэша локальной политики"
msgid "Adding HKCU entry"
msgstr "Слияние ключа в пользовательскую (HKCU) часть реестра"
msgid "Skipping HKLM branch deletion key"
msgstr "Пропускаем специальный ключ удаления ветви реестра HKLM"
msgid "Reading and merging machine preference"
msgstr "Вычитывание и слияние машинных настроек"
msgid "Reading and merging user preference"
msgstr "Вычитывание и слияние пользовательских настроек"
msgid "Found SYSVOL entry"
msgstr "Найден путь SYSVOL"
msgid "Trying to load PReg from .pol file"
msgstr "Пробуем загрузить ключи реестра из .pol файла"
msgid "Finished reading PReg from .pol file"
msgstr "Вычитаны ключи реестра из .pol файла"
msgid "Determined length of PReg file"
msgstr "Определена длина .pol файла"
msgid "Merging machine settings from PReg file"
msgstr "Слияние машинных настроек из .pol файла"
msgid "Merging machine (user part) settings from PReg file"
msgstr "Слияние пользовательской части машинных настроек из .pol файла"
msgid "Loading PReg from XML"
msgstr "Загружаем ключи реестра из XML"
msgid "Setting process permissions"
msgstr "Установка прав процесса"
msgid "Samba DC setting is overriden by user setting"
msgstr "Используется указанный пользователем контроллер домена AD"
msgid "Saving information about drive mapping"
msgstr "Сохранение информации о привязках дисков"
msgid "Saving information about printer"
msgstr "Сохранение информации о принтерах"
msgid "Saving information about link"
msgstr "Сохранение информации о ярлычках"
msgid "Saving information about folder"
msgstr "Сохранение информации о папках"
msgid "No value cached for object"
msgstr "Отсутствует кэшированное значение для объекта"
msgid "Key is already present in cache, will update the value"
msgstr "Ключ уже существует, его значение будет обновлено"
msgid "GPO update started"
msgstr "Начато обновление GPO"
msgid "GPO update finished"
msgstr "Завершено обновление GPO"
msgid "Retrieving list of GPOs to replicate from AD DC"
msgstr "Получение списка GPO для репликации с контроллера домена AD"
msgid "Establishing connection with AD DC"
msgstr "Установка соединения с контроллером домена AD"
msgid "Started GPO replication from AD DC"
msgstr "Начата репликация GPO от контроллера домена AD"
msgid "Finished GPO replication from AD DC"
msgstr "Завершена репликация GPO от контроллера домена AD"
msgid "Skipping HKCU branch deletion key"
msgstr "Пропускаем специальный ключ удаления ветви реестра HKCU"
msgid "Read domain name from configuration file"
msgstr "Имя контроллера домена для репликации прочитано из файла конфигурации"
msgid "Saving information about environment variables"
msgstr "Сохранение информации о переменных окружения"
msgid "Unknown debug code"
msgstr "Неизвестный отладочный код"
# Warning
msgid "Unable to perform gpupdate for non-existent user, will update machine settings"
msgstr "Невозможно запустить gpupdate для несуществующего пользователя, будут обновлены настройки машины"
msgid "Current permissions does not allow to perform gpupdate for designated user. Will update current user settings"
msgstr "Текущий уровень привилегий не позволяет выполнить gpupdate для указанного пользователя. Будут обновлены настройки текущего пользователя."
msgid "oddjobd is inaccessible"
msgstr "oddjobd недоступен"
msgid "No SYSVOL entry assigned to GPO"
msgstr "Объект групповой политики не имеет привязанного пути на SYSVOL"
msgid "ADP package is not installed - plugin will not be initialized"
msgstr "Пакет ADP не установлен, плагин не будет инициализирован"
msgid "Unknown warning code"
msgstr "Неизвестный код предупреждения"
# Fatal
msgid "Unable to refresh GPO list"
msgstr "Невозможно обновить список объектов групповых политик"
msgid "Error getting GPTs for machine"
msgstr "Не удалось получить GPT для машины"
msgid "Error getting GPTs for user"
msgstr "Не удалось получить GPT для пользователя"
msgid "Unknown fatal code"
msgstr "Неизвестный код фатальной ошибки"
# get_message
msgid "Unknown message type, no message assigned"
msgstr "Неизвестный тип сообщения"

187
gpoa/messages/__init__.py Normal file
View File

@@ -0,0 +1,187 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import gettext
def info_code(code):
info_ids = dict()
info_ids[1] = 'Got GPO list for username'
info_ids[2] = 'Got GPO'
return info_ids.get(code, 'Unknown info code')
def error_code(code):
error_ids = dict()
error_ids[1] = 'Insufficient permissions to run gpupdate'
error_ids[2] = 'gpupdate will not be started'
error_ids[3] = 'Backend execution error'
error_ids[4] = 'Error occurred while running frontend manager'
error_ids[5] = 'Error running GPOA for computer'
error_ids[6] = 'Error running GPOA for user'
error_ids[7] = 'Unable to initialize Samba backend'
error_ids[8] = 'Unable to initialize no-domain backend'
error_ids[9] = 'Error running ADP'
error_ids[10] = 'Unable to determine DC hostname'
error_ids[11] = 'Error occured while running applier with user privileges'
error_ids[12] = 'Unable to initialize backend'
error_ids[13] = 'Not sufficient privileges to run machine appliers'
error_ids[14] = 'Kerberos ticket check failed'
error_ids[15] = 'Unable to retrieve domain name via CLDAP query'
error_ids[16] = 'Error getting SID using wbinfo, will use SID from cache'
error_ids[17] = 'Unable to get GPO list for user from AD DC'
error_ids[18] = 'Error getting XDG_DESKTOP_DIR'
error_ids[19] = 'Error occured while running user applier in administrator context'
error_ids[20] = 'Error occured while running user applier in user context (with dropped privileges)'
error_ids[21] = 'No reply from oddjobd GPOA runner via D-Bus for current user'
error_ids[22] = 'No reply from oddjobd GPOA runner via D-Bus for computer'
error_ids[23] = 'No reply from oddjobd GPOA runner via D-Bus for user'
error_ids[24] = 'Error occured while running machine applier'
error_ids[25] = 'Error occured while initializing user applier'
error_ids[26] = 'Error merging machine GPT'
error_ids[27] = 'Error merging user GPT'
error_ids[28] = 'Error merging machine part of GPT'
error_ids[29] = 'Error merging user part of GPT'
error_ids[30] = 'Error occured while running dropped privileges process for user context appliers'
error_ids[31] = 'Error connecting to DBus Session daemon'
error_ids[32] = 'No reply from DBus Session'
error_ids[33] = 'Error occured while running forked process with dropped privileges'
error_ids[34] = 'Error running GPOA directly for computer'
error_ids[35] = 'Error caching URI to file'
error_ids[36] = 'Error getting cached file for URI'
error_ids[37] = 'Error caching file URIs'
error_ids[38] = 'Unable to cache specified URI'
return error_ids.get(code, 'Unknown error code')
def debug_code(code):
debug_ids = dict()
debug_ids[1] = 'The GPOA process was started for user'
debug_ids[2] = 'Username is not specified - will use username of the current process'
debug_ids[3] = 'Initializing plugin manager'
debug_ids[4] = 'ADP plugin initialized'
debug_ids[5] = 'Running ADP plugin'
debug_ids[6] = 'Starting GPOA for user via D-Bus'
debug_ids[7] = 'Cache directory determined'
debug_ids[8] = 'Initializing local backend without domain'
debug_ids[9] = 'Initializing Samba backend for domain'
debug_ids[10] = 'Group Policy target set for update'
debug_ids[11] = 'Starting GPOA for computer via D-Bus'
debug_ids[12] = 'Got exit code'
debug_ids[13] = 'Starting GPOA via D-Bus'
debug_ids[14] = 'Starting GPOA via command invocation'
debug_ids[15] = 'Username for frontend is determined'
debug_ids[16] = 'Applying computer part of settings'
debug_ids[17] = 'Kerberos ticket check succeed'
debug_ids[18] = 'Found AD domain via CLDAP query'
debug_ids[19] = 'Setting info'
debug_ids[20] = 'Initializing cache'
debug_ids[21] = 'Set operational SID'
debug_ids[22] = 'Got PReg entry'
debug_ids[23] = 'Looking for preference in user part of GPT'
debug_ids[24] = 'Looking for preference in machine part of GPT'
debug_ids[25] = 'Re-caching Local Policy'
debug_ids[26] = 'Adding HKCU entry'
debug_ids[27] = 'Skipping HKLM branch deletion key'
debug_ids[28] = 'Reading and merging machine preference'
debug_ids[29] = 'Reading and merging user preference'
debug_ids[30] = 'Found SYSVOL entry'
debug_ids[31] = 'Trying to load PReg from .pol file'
debug_ids[32] = 'Finished reading PReg from .pol file'
debug_ids[33] = 'Determined length of PReg file'
debug_ids[34] = 'Merging machine settings from PReg file'
debug_ids[35] = 'Merging machine (user part) settings from PReg file'
debug_ids[36] = 'Loading PReg from XML'
debug_ids[37] = 'Setting process permissions'
debug_ids[38] = 'Samba DC setting is overriden by user setting'
debug_ids[39] = 'Saving information about drive mapping'
debug_ids[40] = 'Saving information about printer'
debug_ids[41] = 'Saving information about link'
debug_ids[42] = 'Saving information about folder'
debug_ids[43] = 'No value cached for object'
debug_ids[44] = 'Key is already present in cache, will update the value'
debug_ids[45] = 'GPO update started'
debug_ids[46] = 'GPO update finished'
debug_ids[47] = 'Retrieving list of GPOs to replicate from AD DC'
debug_ids[48] = 'Establishing connection with AD DC'
debug_ids[49] = 'Started GPO replication from AD DC'
debug_ids[50] = 'Finished GPO replication from AD DC'
debug_ids[51] = 'Skipping HKCU branch deletion key'
debug_ids[52] = 'Read domain name from configuration file'
debug_ids[53] = 'Saving information about environment variables'
debug_ids[54] = 'Run forked process with droped privileges'
debug_ids[55] = 'Run user context applier with dropped privileges'
debug_ids[56] = 'Kill dbus-daemon and dconf-service in user context'
debug_ids[57] = 'Found connection by org.freedesktop.DBus.GetConnectionUnixProcessID'
debug_ids[58] = 'Connection search return org.freedesktop.DBus.Error.NameHasNoOwner'
debug_ids[59] = 'Running GPOA without GPT update directly for user'
debug_ids[60] = 'Running GPOA by root for user'
debug_ids[61] = 'The GPOA process was started for computer'
debug_ids[62] = 'Path not resolved as UNC URI'
debug_ids[63] = 'Delete HKLM branch key'
debug_ids[64] = 'Delete HKCU branch key'
debug_ids[65] = 'Delete HKLM branch key error'
debug_ids[66] = 'Delete HKCU branch key error'
return debug_ids.get(code, 'Unknown debug code')
def warning_code(code):
warning_ids = dict()
warning_ids[1] = (
'Unable to perform gpupdate for non-existent user, '
'will update machine settings'
)
warning_ids[2] = (
'Current permissions does not allow to perform gpupdate for '
'designated user. Will update current user settings'
)
warning_ids[3] = 'oddjobd is inaccessible'
warning_ids[4] = 'No SYSVOL entry assigned to GPO'
warning_ids[5] = 'ADP package is not installed - plugin will not be initialized'
return warning_ids.get(code, 'Unknown warning code')
def fatal_code(code):
fatal_ids = dict()
fatal_ids[1] = 'Unable to refresh GPO list'
fatal_ids[2] = 'Error getting GPTs for machine'
fatal_ids[3] = 'Error getting GPTs for user'
return fatal_ids.get(code, 'Unknown fatal code')
def get_message(code):
retstr = 'Unknown message type, no message assigned'
if code.startswith('E'):
retstr = error_code(int(code[1:]))
if code.startswith('I'):
retstr = info_code(int(code[1:]))
if code.startswith('D'):
retstr = debug_code(int(code[1:]))
if code.startswith('W'):
retstr = warning_code(int(code[1:]))
if code.startswith('F'):
retstr = fatal_code(int(code[1:]))
return retstr
def message_with_code(code):
retstr = '[' + code[0:1] + code[1:].rjust(5, '0') + ']| ' + gettext.gettext(get_message(code))
return retstr

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,9 +13,8 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from .plugin_manager import plugin_manager

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,9 +13,8 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
import subprocess
@@ -21,19 +22,20 @@ import subprocess
from util.rpm import is_rpm_installed
from .exceptions import PluginInitError
from util.logging import slogm
from messages import message_with_code
class adp:
def __init__(self):
if not is_rpm_installed('adp'):
raise PluginInitError('adp is not installed - plugin cannot be initialized')
logging.info(slogm('ADP plugin initialized'))
raise PluginInitError(message_with_code('W5'))
logging.info(slogm(message_with_code('D4')))
def run(self):
try:
logging.info('Running ADP plugin')
logging.info(slogm(message_with_code('D5')))
subprocess.call(['/usr/bin/adp', 'fetch'])
subprocess.call(['/usr/bin/adp', 'apply'])
except Exception as exc:
logging.error(slogm('Error running ADP'))
logging.error(slogm(message_with_code('E9')))
raise exc

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,9 +13,8 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class PluginInitError(Exception):
def __init__(self, message):

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,9 +13,8 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from abc import ABC

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,9 +13,8 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
@@ -22,15 +23,16 @@ from .roles import roles
from .exceptions import PluginInitError
from .plugin import plugin
from util.logging import slogm
from messages import message_with_code
class plugin_manager:
def __init__(self):
self.plugins = dict()
logging.info(slogm('Starting plugin manager'))
logging.debug(slogm(message_with_code('D3')))
try:
self.plugins['adp'] = adp()
except PluginInitError as exc:
logging.error(slogm(exc))
logging.warning(slogm(str(exc)))
def run(self):
self.plugins.get('adp', plugin('adp')).run()

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,9 +13,8 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from util.roles import fill_roles

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,9 +13,8 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from .sqlite_registry import sqlite_registry
from .sqlite_cache import sqlite_cache
@@ -21,6 +22,6 @@ from .sqlite_cache import sqlite_cache
def cache_factory(cache_name):
return sqlite_cache(cache_name)
def registry_factory(registry_name):
return sqlite_registry(registry_name)
def registry_factory(registry_name='registry', registry_dir=None):
return sqlite_registry(registry_name, registry_dir)

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,9 +13,8 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from abc import ABC

View File

@@ -0,0 +1,97 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2021 BaseALT Ltd. <org@basealt.ru>
# Copyright (C) 2021 Igor Chudov <nir@nir.org.ru>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import os.path
from pathlib import Path
import smbc
from util.logging import log
from util.paths import file_cache_dir, UNCPath
from util.exceptions import NotUNCPathError
class fs_file_cache:
__read_blocksize = 4096
def __init__(self, cache_name):
self.cache_name = cache_name
self.storage_uri = file_cache_dir()
logdata = dict({'cache_file': self.storage_uri})
log('D20', logdata)
self.samba_context = smbc.Context(use_kerberos=1)
#, debug=10)
def store(self, uri):
destdir = uri
try:
uri_path = UNCPath(uri)
file_name = os.path.basename(uri_path.get_path())
file_path = os.path.dirname(uri_path.get_path())
destdir = Path('{}/{}/{}'.format(self.storage_uri,
uri_path.get_domain(),
file_path))
except Exception as exc:
logdata = dict({'exception': str(exc)})
log('E38', logdata)
raise exc
if not destdir.exists():
destdir.mkdir(parents=True, exist_ok=True)
destfile = Path('{}/{}/{}'.format(self.storage_uri,
uri_path.get_domain(),
uri_path.get_path()))
with open(destfile, 'wb') as df:
df.truncate()
df.flush()
try:
file_handler = self.samba_context.open(str(uri_path), os.O_RDONLY)
while True:
data = file_handler.read(self.__read_blocksize)
if not data:
break
df.write(data)
df.flush()
except Exception as exc:
logdata = dict({'exception': str(exc)})
log('E35', logdata)
raise exc
def get(self, uri):
destfile = uri
try:
uri_path = UNCPath(uri)
file_name = os.path.basename(uri_path.get_path())
file_path = os.path.dirname(uri_path.get_path())
destfile = Path('{}/{}/{}'.format(self.storage_uri,
uri_path.get_domain(),
uri_path.get_path()))
except NotUNCPathError as exc:
logdata = dict({'path': str(exc)})
log('D62', logdata)
except Exception as exc:
logdata = dict({'exception': str(exc)})
log('E36', logdata)
raise exc
return str(destfile)

View File

@@ -0,0 +1,176 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class samba_preg(object):
'''
Object mapping representing HKLM entry (registry key without SID)
'''
def __init__(self, preg_obj, policy_name):
self.policy_name = policy_name
self.keyname = preg_obj.keyname
self.valuename = preg_obj.valuename
self.hive_key = '{}\\{}'.format(self.keyname, self.valuename)
self.type = preg_obj.type
self.data = preg_obj.data
def update_fields(self):
fields = dict()
fields['policy_name'] = self.policy_name
fields['type'] = self.type
fields['data'] = self.data
return fields
class samba_hkcu_preg(object):
'''
Object mapping representing HKCU entry (registry key with SID)
'''
def __init__(self, sid, preg_obj, policy_name):
self.sid = sid
self.policy_name = policy_name
self.keyname = preg_obj.keyname
self.valuename = preg_obj.valuename
self.hive_key = '{}\\{}'.format(self.keyname, self.valuename)
self.type = preg_obj.type
self.data = preg_obj.data
def update_fields(self):
fields = dict()
fields['policy_name'] = self.policy_name
fields['type'] = self.type
fields['data'] = self.data
return fields
class ad_shortcut(object):
'''
Object mapping representing Windows shortcut.
'''
def __init__(self, sid, sc, policy_name):
self.sid = sid
self.policy_name = policy_name
self.path = sc.dest
self.shortcut = sc.to_json()
def update_fields(self):
fields = dict()
fields['policy_name'] = self.policy_name
fields['path'] = self.path
fields['shortcut'] = self.shortcut
return fields
class info_entry(object):
def __init__(self, name, value):
self.name = name
self.value = value
def update_fields(self):
fields = dict()
fields['value'] = self.value
return fields
class printer_entry(object):
'''
Object mapping representing Windows printer of some type.
'''
def __init__(self, sid, pobj, policy_name):
self.sid = sid
self.policy_name = policy_name
self.name = pobj.name
self.printer = pobj.to_json()
def update_fields(self):
fields = dict()
fields['policy_name'] = self.policy_name
fields['name'] = self.name
fields['printer'] = self.printer.to_json()
return fields
class drive_entry(object):
'''
Object mapping representing Samba share bound to drive letter
'''
def __init__(self, sid, dobj, policy_name):
self.sid = sid
self.policy_name = policy_name
self.login = dobj.login
self.password = dobj.password
self.dir = dobj.dir
self.path = dobj.path
def update_fields(self):
fields = dict()
fields['policy_name'] = self.policy_name
fields['login'] = self.login
fields['password'] = self.password
fields['dir'] = self.dir
fields['path'] = self.path
return fields
class folder_entry(object):
'''
Object mapping representing file system directory
'''
def __init__(self, sid, fobj, policy_name):
self.sid = sid
self.policy_name = policy_name
self.path = fobj.path
self.action = fobj.action.value
self.delete_folder = str(fobj.delete_folder)
self.delete_sub_folders = str(fobj.delete_sub_folders)
self.delete_files = str(fobj.delete_files)
def update_fields(self):
'''
Return list of fields to update
'''
fields = dict()
fields['policy_name'] = self.policy_name
fields['action'] = self.action
fields['delete_folder'] = self.delete_folder
fields['delete_sub_folders'] = self.delete_sub_folders
fields['delete_files'] = self.delete_files
return fields
class envvar_entry(object):
'''
Object mapping representing environment variables
'''
def __init__(self, sid, evobj, policy_name):
self.sid = sid
self.policy_name = policy_name
self.name = evobj.name
self.value = evobj.value
self.action = evobj.action.value
def update_fields(self):
'''
Return list of fields to update
'''
fields = dict()
fields['policy_name'] = self.policy_name
fields['action'] = self.action
fields['value'] = self.value
return fields

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,9 +13,8 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from abc import ABC

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,13 +13,11 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from .cache import cache
import logging
import os
from sqlalchemy import (
@@ -33,7 +33,7 @@ from sqlalchemy.orm import (
sessionmaker
)
from util.logging import slogm
from util.logging import log
from util.paths import cache_dir
def mapping_factory(mapper_suffix):
@@ -52,7 +52,8 @@ class sqlite_cache(cache):
self.cache_name = cache_name
self.mapper_obj = mapping_factory(self.cache_name)
self.storage_uri = os.path.join('sqlite:///{}/{}.sqlite'.format(cache_dir(), self.cache_name))
logging.debug(slogm('Initializing cache {}'.format(self.storage_uri)))
logdata = dict({'cache_file': self.storage_uri})
log('D20', logdata)
self.db_cnt = create_engine(self.storage_uri, echo=False)
self.__metadata = MetaData(self.db_cnt)
self.cache_table = Table(
@@ -79,7 +80,9 @@ class sqlite_cache(cache):
def get_default(self, obj_id, default_value):
result = self.get(obj_id)
if result == None:
logging.debug(slogm('No value cached for {}'.format(obj_id)))
logdata = dict()
logdata['object'] = obj_id
log('D43', logdata)
self.store(obj_id, default_value)
return str(default_value)
return result.value
@@ -88,9 +91,11 @@ class sqlite_cache(cache):
try:
self.db_session.add(obj)
self.db_session.commit()
except:
except Exception as exc:
self.db_session.rollback()
logging.error(slogm('Error inserting value into cache, will update the value'))
logdata = dict()
logdata['msg'] = str(exc)
log('D44', logdata)
self.db_session.query(self.mapper_obj).filter(self.mapper_obj.str_id == obj.str_id).update({ 'value': obj.value })
self.db_session.commit()

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,11 +13,9 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
import os
from sqlalchemy import (
@@ -32,56 +32,27 @@ from sqlalchemy.orm import (
sessionmaker
)
from util.logging import slogm
from util.logging import log
from util.paths import cache_dir
from .registry import registry
class samba_preg(object):
'''
Object mapping representing HKLM entry (registry key without SID)
'''
def __init__(self, preg_obj):
self.hive_key = '{}\\{}'.format(preg_obj.keyname, preg_obj.valuename)
self.type = preg_obj.type
self.data = preg_obj.data
class samba_hkcu_preg(object):
'''
Object mapping representing HKCU entry (registry key with SID)
'''
def __init__(self, sid, preg_obj):
self.sid = sid
self.hive_key = '{}\\{}'.format(preg_obj.keyname, preg_obj.valuename)
self.type = preg_obj.type
self.data = preg_obj.data
class ad_shortcut(object):
'''
Object mapping representing Windows shortcut.
'''
def __init__(self, sid, sc):
self.sid = sid
self.path = sc.dest
self.shortcut = sc.to_json()
class info_entry(object):
def __init__(self, name, value):
self.name = name
self.value = value
class printer_entry(object):
'''
Object mapping representing Windows printer of some type.
'''
def __init__(self, sid, pobj):
self.sid = sid
self.name = pobj.name
self.printer = pobj.to_json()
from .record_types import (
samba_preg
, samba_hkcu_preg
, ad_shortcut
, info_entry
, printer_entry
, drive_entry
, folder_entry
, envvar_entry
)
class sqlite_registry(registry):
def __init__(self, db_name):
def __init__(self, db_name, registry_cache_dir=None):
self.db_name = db_name
self.db_path = os.path.join('sqlite:///{}/{}.sqlite'.format(cache_dir(), self.db_name))
cdir = registry_cache_dir
if cdir == None:
cdir = cache_dir()
self.db_path = os.path.join('sqlite:///{}/{}.sqlite'.format(cdir, self.db_name))
self.db_cnt = create_engine(self.db_path, echo=False)
self.__metadata = MetaData(self.db_cnt)
self.__info = Table(
@@ -92,40 +63,85 @@ class sqlite_registry(registry):
Column('value', String(65536))
)
self.__hklm = Table(
'HKLM',
self.__metadata,
Column('id', Integer, primary_key=True),
Column('hive_key', String(65536), unique=True),
Column('type', Integer),
Column('data', String)
'HKLM'
, self.__metadata
, Column('id', Integer, primary_key=True)
, Column('hive_key', String(65536, collation='NOCASE'),
unique=True)
, Column('keyname', String(collation='NOCASE'))
, Column('valuename', String(collation='NOCASE'))
, Column('policy_name', String)
, Column('type', Integer)
, Column('data', String)
)
self.__hkcu = Table(
'HKCU',
self.__metadata,
Column('id', Integer, primary_key=True),
Column('sid', String),
Column('hive_key', String(65536)),
Column('type', Integer),
Column('data', String),
UniqueConstraint('sid', 'hive_key')
'HKCU'
, self.__metadata
, Column('id', Integer, primary_key=True)
, Column('sid', String)
, Column('hive_key', String(65536, collation='NOCASE'))
, Column('keyname', String(collation='NOCASE'))
, Column('valuename', String(collation='NOCASE'))
, Column('policy_name', String)
, Column('type', Integer)
, Column('data', String)
, UniqueConstraint('sid', 'hive_key')
)
self.__shortcuts = Table(
'Shortcuts',
self.__metadata,
Column('id', Integer, primary_key=True),
Column('sid', String),
Column('path', String),
Column('shortcut', String),
UniqueConstraint('sid', 'path')
'Shortcuts'
, self.__metadata
, Column('id', Integer, primary_key=True)
, Column('sid', String)
, Column('path', String)
, Column('policy_name', String)
, Column('shortcut', String)
, UniqueConstraint('sid', 'path')
)
self.__printers = Table(
'Printers',
self.__metadata,
Column('id', Integer, primary_key=True),
Column('sid', String),
Column('name', String),
Column('printer', String),
UniqueConstraint('sid', 'name')
'Printers'
, self.__metadata
, Column('id', Integer, primary_key=True)
, Column('sid', String)
, Column('name', String)
, Column('policy_name', String)
, Column('printer', String)
, UniqueConstraint('sid', 'name')
)
self.__drives = Table(
'Drives'
, self.__metadata
, Column('id', Integer, primary_key=True)
, Column('sid', String)
, Column('login', String)
, Column('password', String)
, Column('dir', String)
, Column('policy_name', String)
, Column('path', String)
, UniqueConstraint('sid', 'dir')
)
self.__folders = Table(
'Folders'
, self.__metadata
, Column('id', Integer, primary_key=True)
, Column('sid', String)
, Column('path', String)
, Column('policy_name', String)
, Column('action', String)
, Column('delete_folder', String)
, Column('delete_sub_folders', String)
, Column('delete_files', String)
, UniqueConstraint('sid', 'path')
)
self.__envvars = Table(
'Envvars'
, self.__metadata
, Column('id', Integer, primary_key=True)
, Column('sid', String)
, Column('name', String)
, Column('policy_name', String)
, Column('action', String)
, Column('value', String)
, UniqueConstraint('sid', 'name')
)
self.__metadata.create_all(self.db_cnt)
Session = sessionmaker(bind=self.db_cnt)
@@ -136,6 +152,9 @@ class sqlite_registry(registry):
mapper(samba_hkcu_preg, self.__hkcu)
mapper(ad_shortcut, self.__shortcuts)
mapper(printer_entry, self.__printers)
mapper(drive_entry, self.__drives)
mapper(folder_entry, self.__folders)
mapper(envvar_entry, self.__envvars)
except:
pass
#logging.error('Error creating mapper')
@@ -152,127 +171,243 @@ class sqlite_registry(registry):
try:
self._add(row)
except:
update_obj = dict({ 'value': row.value })
(self
.db_session.query(info_entry)
.filter(info_entry.name == row.name)
.update(update_obj))
.update(row.update_fields()))
self.db_session.commit()
def _hklm_upsert(self, row):
try:
self._add(row)
except:
update_obj = dict({'type': row.type, 'data': row.data })
(self
.db_session
.query(samba_preg)
.filter(samba_preg.hive_key == row.hive_key)
.update(update_obj))
.update(row.update_fields()))
self.db_session.commit()
def _hkcu_upsert(self, row):
try:
self._add(row)
except:
update_obj = dict({'type': row.type, 'data': row.data })
except Exception as exc:
(self
.db_session
.query(samba_preg)
.query(samba_hkcu_preg)
.filter(samba_hkcu_preg.sid == row.sid)
.filter(samba_hkcu_preg.hive_key == row.hive_key)
.update(update_obj))
.update(row.update_fields()))
self.db_session.commit()
def _shortcut_upsert(self, row):
try:
self._add(row)
except:
update_obj = dict({ 'shortcut': row.shortcut })
(self
.db_session
.query(ad_shortcut)
.filter(ad_shortcut.sid == row.sid)
.filter(ad_shortcut.path == row.path)
.update(update_obj))
.update(row.update_fields()))
self.db_session.commit()
def _printer_upsert(self, row):
try:
self._add(row)
except:
update_obj = dict({ 'printer': row.printer })
(self
.db_session
.query(printer_entry)
.filter(printer_entry.sid == row.sid)
.filter(printer_entry.name == row.name)
.update(update_obj))
.update(row.update_fields()))
self.db_session.commit()
def _drive_upsert(self, row):
try:
self._add(row)
except:
(self
.db_session
.query(drive_entry)
.filter(drive_entry.sid == row.sid)
.filter(drive_entry.dir == row.dir)
.update(row.update_fields()))
self.db_session.commit()
def set_info(self, name, value):
ientry = info_entry(name, value)
logging.debug(slogm('Setting info {}:{}'.format(name, value)))
logdata = dict()
logdata['varname'] = name
logdata['value'] = value
log('D19', logdata)
self._info_upsert(ientry)
def add_hklm_entry(self, preg_entry):
def _delete_hklm_keyname(self, keyname):
'''
Delete PReg hive_key from HKEY_LOCAL_MACHINE
'''
logdata = dict({'keyname': keyname})
try:
(self
.db_session
.query(samba_preg)
.filter(samba_preg.keyname == keyname)
.delete(synchronize_session=False))
self.db_session.commit()
log('D65', logdata)
except Exception as exc:
log('D63', logdata)
def add_hklm_entry(self, preg_entry, policy_name):
'''
Write PReg entry to HKEY_LOCAL_MACHINE
'''
pentry = samba_preg(preg_entry)
self._hklm_upsert(pentry)
pentry = samba_preg(preg_entry, policy_name)
if not pentry.valuename.startswith('**'):
self._hklm_upsert(pentry)
else:
logdata = dict({'key': pentry.hive_key})
if pentry.valuename.lower() == '**delvals.':
self._delete_hklm_keyname(pentry.keyname)
else:
log('D27', logdata)
def add_hkcu_entry(self, preg_entry, sid):
def _delete_hkcu_keyname(self, keyname, sid):
'''
Delete PReg hive_key from HKEY_CURRENT_USER
'''
logdata = dict({'sid': sid, 'keyname': keyname})
try:
(self
.db_session
.query(samba_hkcu_preg)
.filter(samba_hkcu_preg.sid == sid)
.filter(samba_hkcu_preg.keyname == keyname)
.delete(synchronize_session=False))
self.db_session.commit()
log('D66', logdata)
except:
log('D64', logdata)
def add_hkcu_entry(self, preg_entry, sid, policy_name):
'''
Write PReg entry to HKEY_CURRENT_USER
'''
hkcu_pentry = samba_hkcu_preg(sid, preg_entry)
logging.debug(slogm('Adding HKCU entry for {}'.format(sid)))
self._hkcu_upsert(hkcu_pentry)
hkcu_pentry = samba_hkcu_preg(sid, preg_entry, policy_name)
logdata = dict({'sid': sid, 'policy': policy_name, 'key': hkcu_pentry.hive_key})
if not hkcu_pentry.valuename.startswith('**'):
log('D26', logdata)
self._hkcu_upsert(hkcu_pentry)
else:
if hkcu_pentry.valuename.lower() == '**delvals.':
self._delete_hkcu_keyname(hkcu_pentry.keyname, sid)
else:
log('D51', logdata)
def add_shortcut(self, sid, sc_obj):
def add_shortcut(self, sid, sc_obj, policy_name):
'''
Store shortcut information in the database
'''
sc_entry = ad_shortcut(sid, sc_obj)
logging.debug(slogm('Saving info about {} link for {}'.format(sc_entry.path, sid)))
sc_entry = ad_shortcut(sid, sc_obj, policy_name)
logdata = dict()
logdata['link'] = sc_entry.path
logdata['sid'] = sid
log('D41', logdata)
self._shortcut_upsert(sc_entry)
def add_printer(self, sid, pobj):
def add_printer(self, sid, pobj, policy_name):
'''
Store printer configuration in the database
'''
prn_entry = printer_entry(sid, pobj)
logging.debug(slogm('Saving info about printer {} for {}'.format(prn_entry.name, sid)))
prn_entry = printer_entry(sid, pobj, policy_name)
logdata = dict()
logdata['printer'] = prn_entry.name
logdata['sid'] = sid
log('D40', logdata)
self._printer_upsert(prn_entry)
def get_shortcuts(self, sid):
def add_drive(self, sid, dobj, policy_name):
drv_entry = drive_entry(sid, dobj, policy_name)
logdata = dict()
logdata['uri'] = drv_entry.path
logdata['sid'] = sid
log('D39', logdata)
self._drive_upsert(drv_entry)
def add_folder(self, sid, fobj, policy_name):
fld_entry = folder_entry(sid, fobj, policy_name)
logdata = dict()
logdata['folder'] = fld_entry.path
logdata['sid'] = sid
log('D42', logdata)
try:
self._add(fld_entry)
except Exception as exc:
(self
._filter_sid_obj(folder_entry, sid)
.filter(folder_entry.path == fld_entry.path)
.update(fld_entry.update_fields()))
self.db_session.commit()
def add_envvar(self, sid, evobj, policy_name):
ev_entry = envvar_entry(sid, evobj, policy_name)
logdata = dict()
logdata['envvar'] = ev_entry.name
logdata['sid'] = sid
log('D53', logdata)
try:
self._add(ev_entry)
except Exception as exc:
(self
._filter_sid_obj(envvar_entry, sid)
.filter(envvar_entry.name == ev_entry.name)
.update(ev_entry.update_fields()))
self.db_session.commit()
def _filter_sid_obj(self, row_object, sid):
res = (self
.db_session
.query(ad_shortcut)
.filter(ad_shortcut.sid == sid)
.query(row_object)
.filter(row_object.sid == sid))
return res
def _filter_sid_list(self, row_object, sid):
res = (self
.db_session
.query(row_object)
.filter(row_object.sid == sid)
.order_by(row_object.id)
.all())
return res
def get_shortcuts(self, sid):
return self._filter_sid_list(ad_shortcut, sid)
def get_printers(self, sid):
res = (self
.db_session
.query(printer_entry)
.filter(printer_entry.sid == sid)
.all())
return res
return self._filter_sid_list(printer_entry, sid)
def get_drives(self, sid):
return self._filter_sid_list(drive_entry, sid)
def get_folders(self, sid):
return self._filter_sid_list(folder_entry, sid)
def get_envvars(self, sid):
return self._filter_sid_list(envvar_entry, sid)
def get_hkcu_entry(self, sid, hive_key):
res = (self
.db_session
.query(samba_preg)
.query(samba_hkcu_preg)
.filter(samba_hkcu_preg.sid == sid)
.filter(samba_hkcu_preg.hive_key == hive_key)
.first())
# Try to get the value from machine SID as a default if no option is set.
if not res:
machine_sid = self.get_info('machine_sid')
res = self.db_session.query(samba_preg).filter(samba_hkcu_preg.sid == machine_sid).filter(samba_hkcu_preg.hive_key == hive_key).first()
res = self.db_session.query(samba_hkcu_preg).filter(samba_hkcu_preg.sid == machine_sid).filter(samba_hkcu_preg.hive_key == hive_key).first()
return res
def filter_hkcu_entries(self, sid, startswith):
@@ -307,31 +442,16 @@ class sqlite_registry(registry):
return res
def wipe_user(self, sid):
self.wipe_hkcu(sid)
self.wipe_shortcuts(sid)
self.wipe_printers(sid)
self._wipe_sid(samba_hkcu_preg, sid)
self._wipe_sid(ad_shortcut, sid)
self._wipe_sid(printer_entry, sid)
self._wipe_sid(drive_entry, sid)
def wipe_shortcuts(self, sid):
def _wipe_sid(self, row_object, sid):
(self
.db_session
.query(ad_shortcut)
.filter(ad_shortcut.sid == sid)
.delete())
self.db_session.commit()
def wipe_printers(self, sid):
(self
.db_session
.query(printer_entry)
.filter(printer_entry.sid == sid)
.delete())
self.db_session.commit()
def wipe_hkcu(self, sid):
(self
.db_session
.query(samba_hkcu_preg)
.filter(samba_hkcu_preg.sid == sid)
.query(row_object)
.filter(row_object.sid == sid)
.delete())
self.db_session.commit()

View File

@@ -0,0 +1,29 @@
{#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#}
{% if Deny_All == '1' %}
polkit.addRule(function (action, subject) {
if ((action.id == "org.freedesktop.udisks2.filesystem-mount" ||
action.id == "org.freedesktop.udisks2.filesystem-mount-system" ||
action.id == "org.freedesktop.udisks2.filesystem-mount-other-seat") &&
subject.user == "{{User}}" ) {
return polkit.Result.NO;
}
});
{% endif %}

View File

@@ -0,0 +1,28 @@
{#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#}
{% if Deny_All == '1' %}
polkit.addRule(function (action, subject) {
if (action.id == "org.freedesktop.udisks2.filesystem-mount" ||
action.id == "org.freedesktop.udisks2.filesystem-mount-system" ||
action.id == "org.freedesktop.udisks2.filesystem-mount-other-seat") {
return polkit.Result.NO;
}
});
{% endif %}

View File

@@ -1,9 +0,0 @@
{% if Deny_All == '1' %}
polkit.addRule(function (action, subject) {
if (action.id == "org.freedesktop.udisks2.filesystem-mount" ||
action.id == "org.freedesktop.udisks2.filesystem-mount-system" ||
action.id == "org.freedesktop.udisks2.filesystem-mount-other-seat") {
return polkit.Result.NO;
}
});
{% endif %}

View File

@@ -0,0 +1,20 @@
{#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#}
{{ home_dir }}/net {{ mount_file }} -t 120

View File

@@ -0,0 +1,25 @@
{#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#}
{% if login %}
username={{ login }}
{% endif %}
{% if password %}
password={{ password }}
{% endif %}

View File

@@ -0,0 +1,21 @@
{#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#}
{%- for drv in drives %}
{{ drv.dir }} -fstype=cifs,cruid=$USER,sec=krb5,noperm :{{ drv.path }}
{% endfor %}

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,7 +13,6 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

8
gpoa/test/files/share.desktop Executable file
View File

@@ -0,0 +1,8 @@
[Desktop Entry]
Type=Link
Version=1.0
Name=Docs
GenericName=Link to CIFS disk
Comment=Link to Samba share
URL=smb://10.0.0.0/

View File

@@ -0,0 +1,18 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

View File

@@ -0,0 +1,18 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

Binary file not shown.

View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<PolFile num_entries="1" signature="PReg" version="1">
<Entry type="4" type_name="REG_DWORD">
<Key>Software\BaseALT\Policies\Control</Key>
<ValueName>sshd-gssapi-auth</ValueName>
<Value>1</Value>
</Entry>
</PolFile>

Binary file not shown.

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<PolFile num_entries="1" signature="PReg" version="1">
<Entry type="1" type_name="REG_SZ">
<Key>Software\BaseALT\Policies\Control</Key>
<ValueName>dvd-ram-control</ValueName>
<Value>restricted</Value>
</Entry>
</PolFile>

View File

@@ -0,0 +1,74 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import unittest
from util.preg import load_preg
from frontend.appliers.control import control
class ControlTestCase(unittest.TestCase):
'''
Semi-integrational tests for control facility
'''
def test_control_with_int(self):
'''
Test procedure for control framework invocation with integer
value. The type of data loaded from PReg must be 'int' but
we're storing all values as strings inside the database. So,
for the test to be correct - we transform the value to string
first.
'''
preg_file = 'test/frontend/appliers/data/control_int.pol'
preg_data = load_preg(preg_file)
for entry in preg_data.entries:
control_name = entry.valuename
control_value = str(entry.data)
test_control = control(control_name, int(control_value))
test_control.set_control_status()
def test_control_int_out_of_range(self):
'''
Test procedure for control framework invocation with incorrect
integer value (out of range). The type of data loaded from PReg
must be 'int' but we're storing all values as strings inside the
database. So, for the test to be correct - we transform the
value to string first.
'''
control_name = 'sshd-gssapi-auth'
control_value = '50'
test_control = control(control_name, int(control_value))
test_control.set_control_status()
def test_control_with_str(self):
'''
Test procedure for control framework invocation with string
value. The type of data loaded from PReg must be 'str'.
'''
preg_file = 'test/frontend/appliers/data/control_string.pol'
preg_data = load_preg(preg_file)
for entry in preg_data.entries:
control_name = entry.valuename
control_value = entry.data
test_control = control(control_name, str(control_value))
test_control.set_control_status()

View File

@@ -0,0 +1,39 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import unittest
from frontend.appliers.rpm import rpm
class PackageTestCase(unittest.TestCase):
'''
Semi-integrational tests for packages installation/removing
'''
def test_package_not_exist(self):
packages_for_install = 'dummy1 dummy2'
packages_for_remove = 'dummy3'
test_rpm = rpm(packages_for_install, packages_for_remove)
test_rpm.apply()
def test_install_remove_same_package(self):
packages_for_install = 'gotop'
packages_for_remove = 'gotop'
test_rpm = rpm(packages_for_install, packages_for_remove)
test_rpm.apply()

View File

@@ -0,0 +1,3 @@
<?xml version="1.0" encoding="utf-8"?>
<Printers clsid="{1F577D12-3D1B-471e-A1B7-060317597B9C}"><PortPrinter clsid="{C3A739D2-4A44-401e-9F9D-88E5E77DFB3E}" name="10.64.128.250" status="10.64.128.250" image="0" changed="2020-01-23 11:48:07" uid="{88D998C2-9875-4278-A607-EC828839EFCE}" userContext="1" bypassErrors="1"><Properties lprQueue="" snmpCommunity="public" protocol="PROTOCOL_RAWTCP_TYPE" portNumber="9100" doubleSpool="0" snmpEnabled="0" snmpDevIndex="1" ipAddress="10.64.128.250" action="C" location="" localName="printer" comment="" default="1" skipLocal="0" useDNS="0" path="\\prnt" deleteAll="0"/><Filters><FilterGroup bool="AND" not="0" name="DOMAIN\Domain Users" sid="S-1-5-21-3359553909-270469630-9462315-513" userContext="1" primaryGroup="0" localGroup="0"/></Filters></PortPrinter>
</Printers>

View File

@@ -1,9 +1,11 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software; you can redistribute it and/or modify
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -11,7 +13,6 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

Binary file not shown.

View File

@@ -0,0 +1,3 @@
<?xml version="1.0" encoding="utf-8"?>
<ScheduledTasks clsid="{CC63F200-7309-4ba0-B154-A71CD118DBCC}"><TaskV2 clsid="{D8896631-B747-47a7-84A6-C155337F3BC8}" name="mytask" image="2" changed="2020-01-24 13:06:25" uid="{0DBF3CAA-3DCF-4AAA-A52F-82B010B35380}"><Properties action="U" name="mytask" runAs="%LogonDomain%\%LogonUser%" logonType="InteractiveToken"><Task version="1.3"><RegistrationInfo><Author>DOMAIN\samba</Author><Description></Description></RegistrationInfo><Principals><Principal id="Author"><UserId>%LogonDomain%\%LogonUser%</UserId><LogonType>InteractiveToken</LogonType><RunLevel>HighestAvailable</RunLevel></Principal></Principals><Settings><IdleSettings><Duration>PT10M</Duration><WaitTimeout>PT1H</WaitTimeout><StopOnIdleEnd>true</StopOnIdleEnd><RestartOnIdle>false</RestartOnIdle></IdleSettings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>true</StopIfGoingOnBatteries><AllowHardTerminate>true</AllowHardTerminate><AllowStartOnDemand>true</AllowStartOnDemand><Enabled>true</Enabled><Hidden>false</Hidden><ExecutionTimeLimit>P3D</ExecutionTimeLimit><Priority>7</Priority></Settings><Triggers><CalendarTrigger><StartBoundary>2020-01-24T14:59:48</StartBoundary><Enabled>true</Enabled><ScheduleByDay><DaysInterval>1</DaysInterval></ScheduleByDay></CalendarTrigger></Triggers><Actions><Exec><Command>C:\Program Files (x86)\Google\Chrome\Application\chrome.exe</Command></Exec></Actions></Task></Properties></TaskV2>
</ScheduledTasks>

View File

@@ -0,0 +1,3 @@
<?xml version="1.0" encoding="utf-8"?>
<Shortcuts clsid="{872ECB34-B2EC-401b-A585-D32574AA90EE}"><Shortcut clsid="{4F2F7C55-2790-433e-8127-0739D1CFA327}" name="Documents" status="Far" image="1" removePolicy="1" userContext="0" bypassErrors="0" changed="2019-12-11 16:53:37" uid="{3C6978C0-F9F6-4B8B-822C-2846327A1C45}"><Properties pidl="" targetType="URL" action="R" comment="Far 32-bit" shortcutKey="0" startIn="" arguments="%HOME%" iconIndex="13" targetPath="smb://10.0.0.0/" iconPath="%SystemRoot%\system32\SHELL32.dll" window="MIN" shortcutPath="%DesktopDir%\Docs"/></Shortcut>
</Shortcuts>

View File

@@ -0,0 +1,42 @@
#
# GPOA - GPO Applier for Linux
#
# Copyright (C) 2019-2020 BaseALT Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import unittest
import unittest.mock
import os
import util.paths
import json
class GptDrivesTestCase(unittest.TestCase):
@unittest.mock.patch('util.paths.cache_dir')
def test_drive_reader(self, cdir_mock):
'''
Test functionality to read objects from Shortcuts.xml
'''
cdir_mock.return_value = '/var/cache/gpupdate'
import gpt.drives
testdata_path = '{}/test/gpt/data/Drives.xml'.format(os.getcwd())
drvs = gpt.drives.read_drives(testdata_path)
json_obj = json.loads(drvs[0].to_json())
self.assertIsNotNone(json_obj['drive'])

Some files were not shown because too many files have changed in this diff Show More