python4cpm 1.1.7__py3-none-any.whl → 1.1.9__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
python4cpm/accounts.py CHANGED
@@ -1,5 +1,5 @@
1
1
  from python4cpm.envhandler import EnvHandler, Props
2
- from python4cpm.secret import Secret
2
+ from python4cpm.secrets import Password, NewPassword
3
3
 
4
4
 
5
5
  class BaseAccount(EnvHandler):
@@ -11,7 +11,7 @@ class BaseAccount(EnvHandler):
11
11
  password: str | None
12
12
  ) -> None:
13
13
  self._username = username
14
- self._password = Secret.from_env_var(password)
14
+ self._password = Password.from_env_var(password)
15
15
 
16
16
  @classmethod
17
17
  def get(cls) -> object | None:
@@ -25,7 +25,7 @@ class BaseAccount(EnvHandler):
25
25
  return self._username
26
26
 
27
27
  @property
28
- def password(self) -> Secret:
28
+ def password(self) -> Password:
29
29
  return self._password
30
30
 
31
31
 
@@ -62,7 +62,7 @@ class TargetAccount(BaseAccount):
62
62
  self._object_name = object_name
63
63
  self._address = address
64
64
  self._port = port
65
- self._new_password = Secret.from_env_var(new_password)
65
+ self._new_password = NewPassword.from_env_var(new_password)
66
66
 
67
67
  @property
68
68
  def policy_id(self) -> str | None:
@@ -85,7 +85,7 @@ class TargetAccount(BaseAccount):
85
85
  return self._port
86
86
 
87
87
  @property
88
- def new_password(self) -> Secret:
88
+ def new_password(self) -> NewPassword:
89
89
  return self._new_password
90
90
 
91
91
 
python4cpm/devhelper.py CHANGED
@@ -5,6 +5,14 @@ import os
5
5
 
6
6
 
7
7
  class DevHelper:
8
+ @staticmethod
9
+ def _get_secret_value(value: str | None) -> str | None:
10
+ if not value:
11
+ return None
12
+ if Crypto.ENABLED:
13
+ return Crypto.encrypt(value)
14
+ return value
15
+
8
16
  @classmethod
9
17
  def set(
10
18
  cls,
@@ -23,11 +31,10 @@ class DevHelper:
23
31
  reconcile_password: str | None = None,
24
32
  target_new_password: str | None = None
25
33
  ) -> None:
26
- if Crypto.ENABLED:
27
- target_password = Crypto.encrypt(target_password)
28
- logon_password = Crypto.encrypt(logon_password)
29
- reconcile_password = Crypto.encrypt(reconcile_password)
30
- target_new_password = Crypto.encrypt(target_new_password)
34
+ target_password = cls._get_secret_value(target_password)
35
+ logon_password = cls._get_secret_value(logon_password)
36
+ reconcile_password = cls._get_secret_value(reconcile_password)
37
+ target_new_password = cls._get_secret_value(target_new_password)
31
38
  keys = (
32
39
  Args.get_key(Args.PROPS.action),
33
40
  Args.get_key(Args.PROPS.logging_level),
@@ -62,4 +69,6 @@ class DevHelper:
62
69
  )
63
70
  for i, key in enumerate(keys):
64
71
  if values[i] is not None:
65
- os.environ.update({key: values[i]})
72
+ os.environ[key] = values[i]
73
+ else:
74
+ os.environ.pop(key, None)
@@ -0,0 +1,27 @@
1
+ from python4cpm.loggerhandler import LoggerHandler
2
+ import atexit
3
+ import sys
4
+
5
+
6
+ class ExitHandler:
7
+ _ERROR_MESSAGE = "No close signal called"
8
+ _closed = False
9
+
10
+ @classmethod
11
+ def reset(cls) -> None:
12
+ cls._closed = False
13
+
14
+ @classmethod
15
+ def set_closed(cls) -> None:
16
+ cls._closed = True
17
+
18
+ @classmethod
19
+ def on_exit(cls) -> None:
20
+ if cls._closed is False:
21
+ for logger in LoggerHandler.get_all_loggers():
22
+ logger.error(cls._ERROR_MESSAGE)
23
+ sys.stderr.write(cls._ERROR_MESSAGE)
24
+ sys.stderr.flush()
25
+
26
+
27
+ atexit.register(ExitHandler.on_exit)
@@ -3,7 +3,7 @@ import logging
3
3
  from logging.handlers import RotatingFileHandler
4
4
 
5
5
 
6
- class Logger:
6
+ class LoggerHandler:
7
7
  _LOGS_DIR = os.path.join("Logs", "ThirdParty")
8
8
  _LOGGING_LEVELS = {
9
9
  "critical": logging.CRITICAL,
@@ -13,6 +13,7 @@ class Logger:
13
13
  "debug": logging.DEBUG
14
14
  }
15
15
  _DEFAULT_LEVEL = "error"
16
+ _all_loggers = []
16
17
 
17
18
  @classmethod
18
19
  def get_logger(
@@ -42,4 +43,9 @@ class Logger:
42
43
  formatter = logging.Formatter(fmt=fmt, datefmt=datefmt)
43
44
  handler.setFormatter(formatter)
44
45
  logger.addHandler(handler)
46
+ cls._all_loggers.append(logger)
45
47
  return logger
48
+
49
+ @classmethod
50
+ def get_all_loggers(cls):
51
+ return cls._all_loggers
python4cpm/python4cpm.py CHANGED
@@ -1,10 +1,10 @@
1
1
  import sys
2
- import atexit
3
2
  import logging
4
- from python4cpm.secret import Secret
3
+ from python4cpm.secrets import Secret
5
4
  from python4cpm.args import Args
6
- from python4cpm.logger import Logger
5
+ from python4cpm.loggerhandler import LoggerHandler
7
6
  from python4cpm.accounts import TargetAccount, LogonAccount, ReconcileAccount
7
+ from python4cpm.exithandler import ExitHandler
8
8
 
9
9
 
10
10
  class Python4CPM:
@@ -36,8 +36,6 @@ class Python4CPM:
36
36
  self._log_obj(self._target_account)
37
37
  self._log_obj(self._logon_account)
38
38
  self._log_obj(self._reconcile_account)
39
- self._closed = False
40
- atexit.register(self._on_exit)
41
39
 
42
40
  @property
43
41
  def args(self) -> Args:
@@ -66,7 +64,7 @@ class Python4CPM:
66
64
  self._target_account.object_name
67
65
  )
68
66
  name = "-".join(name_parts)
69
- return Logger.get_logger(name, self._args.logging_level)
67
+ return LoggerHandler.get_logger(name, self._args.logging_level)
70
68
 
71
69
  def _verify_action(self) -> None:
72
70
  if self._args.action not in self._VALID_ACTIONS:
@@ -91,17 +89,10 @@ class Python4CPM:
91
89
  else:
92
90
  code = self._FAILED_UNRECOVERABLE_CODE
93
91
  self._logger.error(f"Closing with code {code}")
94
- self._closed = True
92
+ ExitHandler.set_closed()
95
93
  sys.exit(code)
96
94
 
97
95
  def close_success(self) -> None:
98
96
  self._logger.debug(f"Closing with code {self._SUCCESS_CODE}")
99
- self._closed = True
97
+ ExitHandler.set_closed()
100
98
  sys.exit(self._SUCCESS_CODE)
101
-
102
- def _on_exit(self):
103
- if self._closed is False:
104
- message = "No close signal called"
105
- self._logger.error(message)
106
- sys.stderr.write(message)
107
- sys.stderr.flush()
@@ -3,7 +3,7 @@ from python4cpm.crypto import Crypto
3
3
 
4
4
  class Secret:
5
5
  def __init__(self, secret: str) -> None:
6
- self._secret = secret
6
+ self._value = secret
7
7
 
8
8
  @classmethod
9
9
  def from_env_var(cls, secret: str | None) -> object | None:
@@ -18,5 +18,13 @@ class Secret:
18
18
 
19
19
  def get(self) -> str:
20
20
  if Crypto.ENABLED:
21
- return Crypto.decrypt(self._secret)
22
- return self._secret
21
+ return Crypto.decrypt(self._value)
22
+ return self._value
23
+
24
+
25
+ class Password(Secret):
26
+ pass
27
+
28
+
29
+ class NewPassword(Secret):
30
+ pass
@@ -0,0 +1,330 @@
1
+ Metadata-Version: 2.4
2
+ Name: python4cpm
3
+ Version: 1.1.9
4
+ Summary: Python for CPM
5
+ Author-email: Gonzalo Atienza Rela <gonatienza@gmail.com>
6
+ License-Expression: MIT
7
+ Requires-Python: >=3.11
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Dynamic: license-file
11
+
12
+ # Python4CPM
13
+
14
+ A simple and secure way of using python scripts with Idira/CyberArk CPM/SRS password rotations.
15
+
16
+ ## How it works
17
+
18
+ This module leverages the [Credential Management .NET SDK](https://docs.cyberark.com/privilege-cloud-standard/latest/en/content/pasimp/plug-in-netinvoker.htm) from CyberArk to securely offload a password rotation logic into Python.
19
+
20
+ All objects are collected from the SDK and sent as environment context to be picked up by the `python4cpm` module during the subprocess execution of python. All secrets of such environment are protected and encrypted by [Data Protection API (DPAPI)](https://learn.microsoft.com/en-us/dotnet/standard/security/how-to-use-data-protection), until they are explicitely retrieved in your python script runtime, invoking the `Secret.get()` method. Finally, python controls the termination signal sent back to the SDK, which is consequently used as the return code to CPM/SRS. Such as a successful or failed (recoverable or not) result of the requested action.
21
+
22
+ This platform allows you to duplicate it multiple times, simply changing its settings (from Privilege Cloud/PVWA) to point to different venvs and/or python scripts.
23
+
24
+ ## Installation
25
+
26
+ ### Preparing Python
27
+
28
+ 1. Install Python 3.11 or later along CPM or the SRS Connector Management Agent.
29
+ - **Python must be installed for all users**. Follow the custom install steps from the installation wizard to check the checkbox.
30
+ 2. Create a venv in the server, by running `py -m venv c:\venv`. If desired, use a custom location and adjust any future references.
31
+ 3. Install `python4cpm` in your venv:
32
+ - If your CPM/SRS can connect to the internet, install with `c:\venv\Scripts\pip.exe install python4cpm`.
33
+ - If your CPM/SRS cannot connect to the internet:
34
+ - Download the latest `python4cpm-*.whl` file from the [pypi project files](https://pypi.org/project/python4cpm/#files).
35
+ - Copy the file to the server into a temporary directory called `python4cpm-wheel`.
36
+ - From the parent directory of `python4cpm-wheel` run `c:\venv\Scripts\pip.exe install --no-index --find-links=.\python4cpm-wheel python4cpm`.
37
+
38
+
39
+ ### Importing the platform
40
+
41
+ #### If you are using CPM (SaaS or Self-Hosted):
42
+ 1. Download the latest [Credential Management .NET SDK](https://community.cyberark.com/marketplace/s/#a3550000000EkA0AAK-a3950000000jjoOAAQ) and place its content in the bin folder of CPM (`C:\Program Files (x86)\CyberArk\Password Manager\bin`). The files for this may already be present.
43
+ 2. Download the `python4cpm-platform-*.zip` asset from the latest [release](https://github.com/gonatienza/python4cpm/releases).
44
+ 3. Import the platform zip file into Privilege Cloud/PVWA `(Administration -> Platform Management -> Import platform)`.
45
+ 4. Craft your python script and place it within a folder in CPM (e.g., `C:\python4cpm-scripts`).
46
+ 5. Duplicate the imported platform in Privilege Cloud/PVWA `(Administration -> Platform Management -> Application -> Python for CPM)` and name it after your application (e.g., My App).
47
+ 6. Edit the duplicated platform and specify the path of your script, under `Target Account Platform -> Automatic Platform Management -> Additional Policy Settings -> Parameters -> PythonScriptPath -> Value` (e.g., `C:\python4cpm-scripts\myapp.py`).
48
+ 7. Also update `Target Account Platform -> Automatic Platform Management -> Additional Policy Settings -> Parameters -> PythonExePath -> Value` with the custom path for the venv's `python.exe` file (e.g., `c:\venv\Scripts\python.exe`).
49
+ 8. If you want to change the logging level, update `Target Account Platform -> Automatic Platform Management -> Additional Policy Settings -> Parameters -> PythonLoggingLevel -> Value` to `critical`, `error`, `warning`, `info` or `debug`.
50
+ 9. For new applications repeat steps from 4 to 8.
51
+
52
+ #### If you are using SRS (SaaS only):
53
+ 1. Download the `python4cpm-platform-*.zip` asset from the latest [release](https://github.com/gonatienza/python4cpm/releases).
54
+ 2. Import the platform zip file into Privilege Cloud `(Administration -> Platform Management -> Import platform)`.
55
+ 3. Craft your python script and place it within a folder in the Cloud Connector (where the SRS Management Agent runs) (e.g., `C:\python4cpm-scripts`).
56
+ 4. Duplicate the imported platform in Privilege Cloud/PVWA `(Administration -> Platform Management -> Application -> Python for CPM)` and name it after your application (e.g., My App).
57
+ 5. Edit the duplicated platform and specify the path of your script, under `Plugin Settings -> Additional Parameters -> PythonScriptPath` (e.g., `C:\python4cpm-scripts\myapp.py`).
58
+ 6. Also update `Plugin Settings -> Additional Parameters -> PythonExePath` with the custom path for the venv's `python.exe` file (e.g., `c:\venv\Scripts\python.exe`).
59
+ 7. If you want to change the logging level, update `Plugin Settings -> Additional Parameters -> PythonLoggingLevel -> Value` to `critical`, `error`, `warning`, `info` or `debug`.
60
+ 8. For new applications repeat steps from 3 to 7.
61
+
62
+ ### Platform defaults
63
+
64
+ **Automatic verification and change are enabled by default.** Only assign accounts to a duplicated platform that has `PythonExePath` and `PythonScriptPath` set. The imported platform ships with the placeholder `ReplaceWithAbsolutePath`, which fails with `8900` without starting Python. Adjust these defaults to match your application:
65
+
66
+ | Setting | Default | Meaning |
67
+ | --- | --- | --- |
68
+ | `PerformPeriodicChange` | `Yes` | Rotate automatically |
69
+ | `ExpirationPeriod` | `90` | Days before a password expires |
70
+ | `VFPerformPeriodicVerification` | `Yes` | Verify automatically |
71
+ | `Interval` | `1440` | Minutes |
72
+ | `Timeout` | `120` | Seconds |
73
+ | `MaximumRetries` | `5` | Retries |
74
+ | `MinDelayBetweenRetries` | `90` | Minutes between retries |
75
+ | `UnrecoverableErrors` | `8900` | Return codes treated as unrecoverable |
76
+ | `RCAutomaticReconcileWhenUnsynched` | `Yes` | Reconcile when unsynched |
77
+ | `PasswordLength`, `MinUpperCase`, `MinLowerCase`, `MinDigit`, `MinSpecial` | `12`, `2`, `2`, `1`, `1` | Rules for generating `new_password` |
78
+ | `PasswordForbiddenChars` | Empty | Characters the new password must not contain |
79
+
80
+ The new password is generated for you, so **make the password rules match the target system's policy**. Your script only applies it.
81
+
82
+ Accounts require `Username` and `Address`, and `Port` is optional. Link a `LogonAccount` and a `ReconcileAccount` if your script needs them.
83
+
84
+ ## Python Script
85
+
86
+ ```python
87
+ from python4cpm import Python4CPMHandler
88
+
89
+
90
+ class CredManager(Python4CPMHandler):
91
+ """
92
+ Properties:
93
+ target_account (TargetAccount): Account being managed.
94
+ .username (str): Account username.
95
+ .address (str): Target address.
96
+ .port (str | None): Target port.
97
+ .policy_id (str): Platform ID.
98
+ .safe_name (str): Safe name.
99
+ .object_name (str): Account name in the vault.
100
+ .password (Secret | None): Current password. Call .get() to retrieve value as many times as needed.
101
+ .new_password (Secret | None): Replacement password. Call .get() to retrieve value as many times as needed.
102
+
103
+ logon_account (LogonAccount | None): Linked Logon Account.
104
+ .username (str): Account username.
105
+ .password (Secret | None): Logon password. Call .get() to retrieve value.
106
+
107
+ reconcile_account (ReconcileAccount | None): Linked Reconcile Account.
108
+ .username (str): Account username.
109
+ .password (Secret | None): Reconcile password. Call .get() to retrieve value.
110
+
111
+ args (Args): Execution arguments.
112
+ .action (str): Requested action.
113
+ .logging_level (str | None): Value of PythonLoggingLevel.
114
+
115
+ logger (logging.Logger): Logger instance.
116
+
117
+ Methods:
118
+ close_success(): Signal successful completion and terminate.
119
+ close_fail(): Signal failed completion and terminate.
120
+ """
121
+
122
+
123
+ def verify(self):
124
+ """
125
+ REQUIRED METHOD
126
+ """
127
+ # TODO: use account objects for your logic
128
+ self.close_success()
129
+
130
+ def logon(self):
131
+ """
132
+ REQUIRED METHOD
133
+ """
134
+ # TODO: use account objects for your logic
135
+ self.close_success()
136
+
137
+ def change(self):
138
+ """
139
+ REQUIRED METHOD
140
+ """
141
+ # TODO: use account objects for your logic
142
+ self.close_success()
143
+
144
+ def prereconcile(self):
145
+ """
146
+ REQUIRED METHOD
147
+ """
148
+ # TODO: use account objects for your logic
149
+ self.close_success()
150
+
151
+ def reconcile(self):
152
+ """
153
+ REQUIRED METHOD
154
+ """
155
+ # TODO: use account objects for your logic
156
+ self.close_success()
157
+
158
+
159
+ if __name__ == "__main__":
160
+ CredManager().run() # initializes the class and calls the action that was requested from CPM/SRS.
161
+ ```
162
+ (*) More realistic examples can be found [here](https://github.com/gonatienza/python4cpm/blob/main/examples).
163
+
164
+ When doing `verify`, `change` or `reconcile` from Privilege Cloud/PVWA:
165
+ 1. Verify -> the script will be executed once running the `verify()` method.
166
+ 2. Change -> the script will be executed twice: first `logon()`, then `change()`.
167
+ 3. Reconcile -> the script will be executed twice: first `prereconcile()`, then `reconcile()`.
168
+ 4. When calling `verify()`, `logon()` or `prereconcile()`: `target_account.new_password` will always return `None`.
169
+ 5. If a logon account is not linked, `logon_account` will return `None`.
170
+ 6. If a reconcile account is not linked, `reconcile_account` will return `None`.
171
+ 7. **Always** use the `close_success` or `close_fail` methods to signal the proper termination for all actions.
172
+ - `close_fail` takes the optional argument of `unrecoverable` as a bool flag (by default set to `False`). It signals CPM whether the error you encountered cannot be solved through the rotation logic or requires manual intervention. E.g., a regular rotation fails (which is still recoverable) and when called for a reconciliation process it fails too (at this point the error encountered is not recoverable).
173
+ - If any action is not terminated with a termination method, CPM/SRS will see this as a `close_fail(unrecoverable=True)`. This happens regardless of whether it was terminated by an exception or no exception was raised. **If you rotate a credential successfully and do not close with success, you will have a rotated credential that will be lost and not saved into the vault**.
174
+ 8. The python `Logger` places its logs in the `Logs/ThirdParty` directory.
175
+
176
+ ### Writing a rotation script
177
+
178
+ #### What each method should do
179
+
180
+ | Method | Action | `new_password` | What to do |
181
+ | --- | --- | --- | --- |
182
+ | `verify()` | `verifypass` | `None` | Authenticate with `target_account`. |
183
+ | `logon()` | `logon` | `None` | Prepare for `change()`. It can just call `close_success()`. |
184
+ | `change()` | `changepass` | Set | Authenticate, then set `target_account.new_password` on the target. |
185
+ | `prereconcile()` | `prereconcilepass` | `None` | Authenticate with `reconcile_account`. |
186
+ | `reconcile()` | `reconcilepass` | Set | Authenticate with `reconcile_account`, then set `target_account.new_password` on `target_account.username`. |
187
+
188
+ Use `reconcile_account` for `prereconcile()` and `reconcile()`, because `target_account.password` is not expected to work when reconciling.
189
+
190
+ #### Return codes
191
+
192
+ | Script result | Python exit code | Returned to CPM/SRS |
193
+ | --- | --- | --- |
194
+ | `close_success()` | `10` | `0` (success) |
195
+ | `close_fail()` | `81` | `8100` (recoverable) |
196
+ | `close_fail(unrecoverable=True)` | `89` | `8900` (unrecoverable) |
197
+ | Unhandled exception | `1` | `8900` (unrecoverable) |
198
+ | No close method called | `0` | `8900` (unrecoverable) |
199
+ | Any other exit code | That code | `8900` (unrecoverable) |
200
+ | `PythonExePath` or `PythonScriptPath` not found | Python is not started | `8900` (unrecoverable) |
201
+
202
+ #### Rules for your script
203
+
204
+ - **Every method runs in a new python process.** Nothing in memory is shared between `logon()` and `change()`, or between `prereconcile()` and `reconcile()`.
205
+ - **Implement all five methods.** A missing method raises a `TypeError` when the class is created, which returns `8900`.
206
+ - **If you override `__init__`, call `super().__init__()` first.**
207
+ - **Check for `None`.** Empty values are not sent, so these can all be `None`: `port`, any `password`, and `new_password`. A linked account can have a username and no password. `.get()` on `None` raises an `AttributeError`.
208
+ - **`address` is the raw value from the account.** Build URLs yourself, and pick a default for when `port` is `None`.
209
+ - **Change the password last.** Close with `close_success()` straight after the target accepts it, and do nothing that can fail in between.
210
+ - **Close methods raise `SystemExit`.** They are safe inside `try/except Exception`, and code after them does not run, except `finally` blocks. A bare `except:` or `except BaseException:` catches them, and that action then returns `8900`.
211
+ - **Set a timeout on every network call.** The plugin waits for python with no time limit of its own, so keep each action under the platform's `Timeout`.
212
+ - **Use `self.logger`, not `print`.** Standard output is not captured. Standard error is written to the plugin log when an action fails.
213
+ - **Never log the result of `.get()`.** Logging a `Secret` itself is safe and shows `[ENCRYPTED]`. Keep secrets out of exception messages too, as tracebacks reach the plugin log.
214
+ - **Use absolute paths.** The working directory is inherited from the CPM/SRS process, not taken from your script's folder.
215
+ - **Keep TLS verification on in production.** The `simpleauthcredmanager.py` example turns it off.
216
+
217
+ Common failures can be handled like this:
218
+
219
+ ```python
220
+ def verify(self):
221
+ try:
222
+ self._login(self.target_account)
223
+ except Exception as e:
224
+ self.logger.error(f"{type(e).__name__}: {e}")
225
+ self.close_fail()
226
+ self.close_success()
227
+ ```
228
+
229
+ Use `close_fail()` for what a later attempt could fix, like a timeout or a rejected password. Use `close_fail(unrecoverable=True)` for what needs manual intervention.
230
+
231
+ #### Logs
232
+
233
+ All logs are in `Logs/ThirdParty`, relative to the working directory.
234
+
235
+ | File | Content |
236
+ | --- | --- |
237
+ | `python4cpm.loggerhandler_<level>_<PolicyID>-<SafeName>-<ObjectName>.log` | `self.logger` output. Rotates at 1 MB and keeps one backup. |
238
+ | `<PolicyID>-<SafeName>-<FolderName>-<ObjectName>.Log` | The last error, with its error code. |
239
+ | `Debug_<PolicyID>-<SafeName>-<FolderName>-<ObjectName>_CANetPluginInvoker_<date>.log` | Plugin trace, written with `Debug=Yes` in a manual run, including paths, values and standard error. |
240
+
241
+ The default level is `error`, so `self.logger.info()` and `self.logger.debug()` write nothing until you change `PythonLoggingLevel`. An unknown level falls back to `error`, and `critical` is the quietest. Logging cannot be turned off.
242
+
243
+ #### Troubleshooting
244
+
245
+ | Log message | Cause |
246
+ | --- | --- |
247
+ | `PythonExePath: '...' not found` or `PythonScriptPath: '...' not found` | Wrong path, or the account is still on the imported platform. |
248
+ | `Python closed with exit code: 0` and `No close signal called` | A method ended without a close method. |
249
+ | `Python closed with exit code: 1` | Unhandled exception. The traceback follows in `StdErr Output`. |
250
+ | `Python closed with failed recoverable` | The script called `close_fail()`. |
251
+ | `Python closed with failed unrecoverable` | The script called `close_fail(unrecoverable=True)`. |
252
+ | `can't open file '...\ C:\...'` | A manual `.ini` file has spaces around `=`. |
253
+
254
+
255
+ ### Installing dependencies in python venv
256
+
257
+ As with any python venv, you can install dependencies in your venv.
258
+ 1. If your CPM can connect to the internet:
259
+ - You can use regular pip install commands (e.g., `c:\venv\Scripts\pip.exe install requests`).
260
+ 2. If your CPM cannot connect to the internet:
261
+ - You can download packages for an offline install. More info [here](https://pip.pypa.io/en/stable/cli/pip_download/).
262
+
263
+
264
+ ## Dev Helper:
265
+
266
+ For dev purposes, `DevHelper` is a companion helper to test your scripts without CPM/SRS. It simplifies the instantiation of the `Python4CPM` or `Python4CPMHandler` objects by simulating how the plugin creates the environment context for the python module.
267
+
268
+ **Note**: As CPM and the SRS management agent run in Windows, the plugin was built to encrypt secrets using DPAPI (a windows only library). For dev purposes in Linux/Mac dev workstations, those secrets put in the environment context by `DevHelper` will be in plaintext. In windows dev workstations, `DevHelper` encrypts the secrets as the .NET plugin does. This is informational only, **the module will use its encryption/decryption capabilities automatically based on the platform** it is running on and you do not have to do anything specific to enable it.
269
+
270
+ ### Example:
271
+
272
+ #### Set your arguments and secrets:
273
+
274
+ ```python
275
+ from python4cpm import DevHelper, Python4CPM, Python4CPMHandler
276
+
277
+ DevHelper.set(
278
+ action=Python4CPM.ACTION_CHANGE, # use actions from Python4CPM.ACTION_*
279
+ logging_level="debug",
280
+ target_policy_id="DevHelper", # name of platform
281
+ target_safe_name="Safename", # name of safe
282
+ target_object_name="Objectname", # name of account
283
+ target_username="jdoe",
284
+ target_address="myapp.corp.local",
285
+ target_port="8443",
286
+ logon_username="ldoe",
287
+ reconcile_username="rdoe",
288
+ target_password="", # str value of target password (required by most scripts)
289
+ logon_password="", # str value of logon password (leave out if not linked)
290
+ reconcile_password="", # str value of reconcile password (leave out if not linked)
291
+ target_new_password="" # str value of new password (only for change and reconcile)
292
+ )
293
+
294
+ class CredManager(Python4CPMHandler):
295
+ def verify(self):
296
+ # TODO: Add your logic here
297
+ self.close_success()
298
+
299
+ def logon(self):
300
+ # TODO: Add your logic here
301
+ self.close_success()
302
+
303
+ def change(self):
304
+ # TODO: Add your logic here
305
+ self.close_success()
306
+
307
+ def prereconcile(self):
308
+ # TODO: Add your logic here
309
+ self.close_success()
310
+
311
+ def reconcile(self):
312
+ # TODO: Add your logic here
313
+ self.close_success()
314
+
315
+ CredManager().run()
316
+ ```
317
+
318
+ #### Remember when using `DevHelper`:
319
+
320
+ - `target_policy_id`, `target_safe_name` and `target_object_name` are required. The log file name is built from them.
321
+ - A password left out or set to `""` becomes `None`, as in production. Leave out `target_new_password` when testing `verify()`, `logon()` or `prereconcile()`.
322
+ - Each `DevHelper.set()` call replaces the previous one, so anything left out is cleared.
323
+ - Each run tests one `action`, so set it to test each of the five methods.
324
+ - Exit code `10` means success, and `81` or `89` mean the script called `close_fail()`. Anything else returns `8900` in production.
325
+ - **Your script runs for real.** `change()` and `reconcile()` change the password on the target, so use a test account.
326
+
327
+ #### Remember for your final script:
328
+
329
+ - Remove the import of `DevHelper`.
330
+ - Remove the `DevHelper.set()` call.
@@ -0,0 +1,16 @@
1
+ python4cpm/__init__.py,sha256=GQvsXZY2escF3zucv3d68s2ydqHSIYi5tnNDCkhTjcM,302
2
+ python4cpm/accounts.py,sha256=MSRcHotQ_ITGCy02nNVkZyfxbBP31OIcH9PbRS9aUbo,2231
3
+ python4cpm/args.py,sha256=PQDDlMakP-YsDLd3HdwIZtxVpIM4m4aHl2GuRj9kHpI,504
4
+ python4cpm/crypto.py,sha256=FufZdKcm36-HYnSYrBGdADPVk2YmRPl0WDVZ29FfUU0,2337
5
+ python4cpm/devhelper.py,sha256=pU90ErFMbPWTmNHSKPqC2PTSF74zF5sNNalMrAaOW-Q,2860
6
+ python4cpm/envhandler.py,sha256=mNDOaYVemmxKREXyOf7IuQdFDXrvZ7f_7sNaqWV7TsI,678
7
+ python4cpm/exithandler.py,sha256=en_Xy8cnRk5w6xOuQgkxipLSyRWrB3AEZfhoc9T1Cvg,623
8
+ python4cpm/loggerhandler.py,sha256=OrFayXn2VENO2bm0hNmlrBH_Bc_ew8WYxSICuFPr91g,1610
9
+ python4cpm/python4cpm.py,sha256=FD9HMWwN_MIhHTVvN4aj-q7Yr0nmpav3UMSNgRDjvK4,3228
10
+ python4cpm/python4cpmhandler.py,sha256=SXKsnFAwUp8cHEhv2TygpNpptUkN3bVQZt1i-3TWql4,935
11
+ python4cpm/secrets.py,sha256=ijY2t4gSuVZyfDSiGNSqjjNjIhSL4K4yhKrPF-DrGOs,606
12
+ python4cpm-1.1.9.dist-info/licenses/LICENSE,sha256=vF2wZA3GchZjH5lUmhonEwd4snuBc6o0ytpZNxVFyCw,1077
13
+ python4cpm-1.1.9.dist-info/METADATA,sha256=EUi2prlUIfVNj5veDoz66CBszZE-tcf37feeSWAnLs8,19336
14
+ python4cpm-1.1.9.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
15
+ python4cpm-1.1.9.dist-info/top_level.txt,sha256=EhbshwpANmL0wYXaET8_6V9ZENtSwIyAd-kM3jGhUlE,11
16
+ python4cpm-1.1.9.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (82.0.1)
2
+ Generator: setuptools (84.2.1)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,215 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: python4cpm
3
- Version: 1.1.7
4
- Summary: Python for CPM
5
- Author-email: Gonzalo Atienza Rela <gonatienza@gmail.com>
6
- License-Expression: MIT
7
- Requires-Python: >=3.10
8
- Description-Content-Type: text/markdown
9
- License-File: LICENSE
10
- Dynamic: license-file
11
-
12
- # Python4CPM
13
-
14
- A simple and secure way of using python scripts with CyberArk CPM/SRS password rotations.
15
-
16
- ## How it works
17
-
18
- This module leverages the [Credential Management .NET SDK](https://docs.cyberark.com/privilege-cloud-standard/latest/en/content/pasimp/plug-in-netinvoker.htm) from CyberArk to securely offload a password rotation logic into Python.
19
-
20
- All objects are collected from the SDK and sent as environment context to be picked up by the `python4cpm` module during the subprocess execution of python. All secrets of such environment are protected and encrypted by [Data Protection API (DPAPI)](https://learn.microsoft.com/en-us/dotnet/standard/security/how-to-use-data-protection), until they are explicitely retrieved in your python script runtime, invoking the `Secret.get()` method. Finally, python controls the termination signal sent back to the SDK, which is consequently used as the return code to CPM/SRS. Such as a successful or failed (recoverable or not) result of the requested action.
21
-
22
- This platform allows you to duplicate it multiple times, simply changing its settings (from Privilege Cloud/PVWA) to point to different venvs and/or python scripts.
23
-
24
- ## Installation
25
-
26
- ### Preparing Python
27
-
28
- 1. Install Python along CPM or the SRS Connector Management Agent.
29
- - **Python must be installed for all users**. Follow the custom install steps from the installation wizard to check the checkbox.
30
- 3. Create a venv in the server, by running `py -m venv c:\venv`. If desired, use a custom location and adjust any future references.
31
- 4. Install `python4cpm` in your venv:
32
- - If your CPM can connect to the internet, install with `c:\venv\Scripts\pip.exe install python4cpm`.
33
- - If your CPM cannot connect to the internet:
34
- - Download the latest `python4cpm-*.whl` file from the [pypi project files](https://pypi.org/project/python4cpm/#files).
35
- - Copy the file to the server into a temporary directory called `python4cpm-wheel`.
36
- - From the parent directory of `python4cpm-wheel` run `c:\venv\Scripts\pip.exe install --no-index --find-links=.\python4cpm-wheel python4cpm`.
37
-
38
-
39
- ### Importing the platform
40
-
41
- #### If you are using CPM (SaaS or Self-Hosted):
42
- 1. Download the latest [Credential Management .NET SDK](https://community.cyberark.com/marketplace/s/#a3550000000EkA0AAK-a3950000000jjoOAAQ) and place its content in the bin folder of CPM (`C:\Program Files (x86)\CyberArk\Password Manager\bin`). The files for this may already be present.
43
- 2. Download the `python4cpm-platform-*.zip` asset from the latest [release](https://github.com/gonatienza/python4cpm/releases).
44
- 3. Import the platform zip file into Privilege Cloud/PVWA `(Administration -> Platform Management -> Import platform)`.
45
- 4. Craft your python script and place it within a folder in CPM (e.g., `C:\python4cpm-scripts`).
46
- 5. Duplicate the imported platform in Privilege Cloud/PVWA `(Administration -> Platform Management -> Application -> Python for CPM)` and name it after your application (e.g., My App).
47
- 6. Edit the duplicated platform and specify the path of your script, under `Target Account Platform -> Automatic Platform Management -> Additional Policy Settings -> Parameters -> PythonScriptPath -> Value` (e.g., `C:\python4cpm-scripts\myapp.py`).
48
- 7. Also update `Target Account Platform -> Automatic Platform Management -> Additional Policy Settings -> Parameters -> PythonExePath -> Value` with the custom path for the venv's `python.exe` file (e.g., `c:\venv\Scripts\python.exe`).
49
- 8. If you want to disable logging, update `Target Account Platform -> Automatic Platform Management -> Additional Policy Settings -> Parameters -> PythonLogging -> Value` to `no`.
50
- 9. If you want to change the logging level to `debug`, update `Target Account Platform -> Automatic Platform Management -> Additional Policy Settings -> Parameters -> PythonLoggingLevel -> Value` to `debug`.
51
- 10. For new applications repeat steps from 4 to 9.
52
-
53
- #### If you are using SRS (SaaS only):
54
- 1. Download the `python4cpm-platform-*.zip` asset from the latest [release](https://github.com/gonatienza/python4cpm/releases).
55
- 2. Import the platform zip file into Privilege Cloud `(Administration -> Platform Management -> Import platform)`.
56
- 3. Craft your python script and place it within a folder in the Cloud Connector (where the SRS Management Agent runs) (e.g., `C:\python4cpm-scripts`).
57
- 4. Duplicate the imported platform in Privilege Cloud/PVWA `(Administration -> Platform Management -> Application -> Python for CPM)` and name it after your application (e.g., My App).
58
- 5. Edit the duplicated platform and specify the path of your script, under `Plugin Settings -> Additional Parameters -> PythonScriptPath` (e.g., `C:\python4cpm-scripts\myapp.py`).
59
- 6. Also update `Plugin Settings -> Additional Parameters -> PythonExePath` with the custom path for the venv's `python.exe` file (e.g., `c:\venv\Scripts\python.exe`).
60
- 7. If you want to disable logging, update `Plugin Settings -> Additional Parameters -> PythonLogging` to `no`.
61
- 8. If you want to change the logging level to `debug`, update `Plugin Settings -> Additional Parameters -> PythonLoggingLevel -> Value` to `debug`.
62
- 9. For new applications repeat steps from 3 to 8.
63
-
64
- ## Python Script
65
-
66
- ```python
67
- from python4cpm import Python4CPMHandler
68
-
69
-
70
- class CredManager(Python4CPMHandler):
71
- """
72
- Properties:
73
- target_account (TargetAccount): Account being managed.
74
- .username (str): Account username.
75
- .address (str): Target address.
76
- .port (str): Target port.
77
- .password (Secret): Current password. Call .get() to retrieve value.
78
- .new_password (Secret): Replacement password. Call .get() to retrieve value.
79
-
80
- logon_account (LogonAccount): Linked Logon Account.
81
- .username (str): Account username.
82
- .password (Secret): Logon password. Call .get() to retrieve value.
83
-
84
- reconcile_account (ReconcileAccount): Linked Reconcile Account.
85
- .username (str): Account username.
86
- .password (Secret): Reconcile password. Call .get() to retrieve value.
87
-
88
- logger (logging.Logger): Logger instance.
89
-
90
- Methods:
91
- close_success(): Signal successful completion and terminate.
92
- close_fail(): Signal failed completion and terminate.
93
- """
94
-
95
-
96
- def verify(self):
97
- """
98
- REQUIRED METHOD
99
- """
100
- # TODO: use account objects for your logic
101
- self.close_success()
102
-
103
- def logon(self):
104
- """
105
- REQUIRED METHOD
106
- """
107
- # TODO: use account objects for your logic
108
- self.close_success()
109
-
110
- def change(self):
111
- """
112
- REQUIRED METHOD
113
- """
114
- # TODO: use account objects for your logic
115
- self.close_success()
116
-
117
- def prereconcile(self):
118
- """
119
- REQUIRED METHOD
120
- """
121
- # TODO: use account objects for your logic
122
- self.close_success()
123
-
124
- def reconcile(self):
125
- """
126
- REQUIRED METHOD
127
- """
128
- # TODO: use account objects for your logic
129
- self.close_success()
130
-
131
-
132
- if __name__ == "__main__":
133
- CredManager().run() # initializes the class and calls the action that was requested from CPM/SRS.
134
- ```
135
- (*) More realistic examples can be found [here](https://github.com/gonatienza/python4cpm/blob/main/examples).
136
-
137
- When doing `verify`, `change` or `reconcile` from Privilege Cloud/PVWA:
138
- 1. Verify -> the script will be executed once running the `verify()` method.
139
- 2. Change -> the script will be executed twice: first `logon()`, then `change()`.
140
- 3. Reconcile -> the script will be executed twice: first `prereconcile()`, then `reconcile()`.
141
- 4. When calling `verify()`, `logon()` or `prereconcile()`: `target_account.new_password` will always return `None`.
142
- 5. If a logon account is not linked, `logon_account` will return `None`.
143
- 6. If a reconcile account is not linked, `reconcile_account` will return `None`.
144
- 7. Always use the `close_success` or `close_fail` methods to signal the proper termination for all actions.
145
- - If any action is not terminated with a termination method, CPM/SRS will see this as a `close_fail(unrecoverable=True)`, even if no exceptions are raised.
146
- 8. The python `Logger` places its logs in the `Logs/ThirdParty` directory.
147
-
148
-
149
- ### Installing dependencies in python venv
150
-
151
- As with any python venv, you can install dependencies in your venv.
152
- 1. If your CPM can connect to the internet:
153
- - You can use regular pip install commands (e.g., `c:\venv\Scripts\pip.exe install requests`).
154
- 2. If your CPM cannot connect to the internet:
155
- - You can download packages for an offline install. More info [here](https://pip.pypa.io/en/stable/cli/pip_download/).
156
-
157
-
158
- ## Dev Helper:
159
-
160
- For dev purposes, `DevHelper` is a companion helper to test your scripts without CPM/SRS. It simplifies the instantiation of the `Python4CPM` or `Python4CPMHandler` objects by simulating how the plugin creates the environment context for the python module.
161
-
162
- **Note**: As CPM and the SRS management agent run in Windows, the plugin was built to encrypt secrets using DPAPI (a windows only library). For dev purposes in Linux/Mac dev workstations, those secrets put in the environment context by `DevHelper` will be in plaintext. In windows dev workstations, `DevHelper` encrypts the secrets as the .NET plugin does. This is informational only, **the module will use its encryption/decryption capabilities automatically based on the platform** it is running on and you do not have to do anything specific to enable it.
163
-
164
- ### Example:
165
-
166
- #### Set your arguments and secrets:
167
-
168
- ```python
169
- from python4cpm import DevHelper, Python4CPM, Python4CPMHandler
170
-
171
- DevHelper.set(
172
- action=Python4CPM.ACTION_CHANGE, # use actions from Python4CPM.ACTION_*
173
- logging_level="debug",
174
- target_policy_id="DevHelper", # name of platform
175
- target_safe_name="Safename", # name of safe
176
- target_object_name="Objectname", # name of account
177
- target_username="jdoe",
178
- target_address="myapp.corp.local",
179
- target_port="8443",
180
- logon_username="ldoe",
181
- reconcile_username="rdoe",
182
- target_password="", # str value of target password
183
- logon_password="", # str value of logon password
184
- reconcile_password="", # str value of reconcile password
185
- target_new_password="" # str value of new password
186
- )
187
-
188
- class CredManager(Python4CPMHandler):
189
- def verify(self):
190
- # TODO: Add your logic here
191
- self.close_success()
192
-
193
- def logon(self):
194
- # TODO: Add your logic here
195
- self.close_success()
196
-
197
- def change(self):
198
- # TODO: Add your logic here
199
- self.close_success()
200
-
201
- def prereconcile(self):
202
- # TODO: Add your logic here
203
- self.close_success()
204
-
205
- def reconcile(self):
206
- # TODO: Add your logic here
207
- self.close_success()
208
-
209
- CredManager().run()
210
- ```
211
-
212
- #### Remember for your final script:
213
-
214
- - Remove the import of `DevHelper`.
215
- - Remove the `DevHelper.set()` call.
@@ -1,15 +0,0 @@
1
- python4cpm/__init__.py,sha256=GQvsXZY2escF3zucv3d68s2ydqHSIYi5tnNDCkhTjcM,302
2
- python4cpm/accounts.py,sha256=tzLr6kFeHD6jDF-dZXjp2FeoABFsWn2hp4bO5uYN2Zg,2201
3
- python4cpm/args.py,sha256=PQDDlMakP-YsDLd3HdwIZtxVpIM4m4aHl2GuRj9kHpI,504
4
- python4cpm/crypto.py,sha256=FufZdKcm36-HYnSYrBGdADPVk2YmRPl0WDVZ29FfUU0,2337
5
- python4cpm/devhelper.py,sha256=iv5zHSMyMNMdksGkkTh_8c_ObocJfQormQ4S3nZzo0Y,2609
6
- python4cpm/envhandler.py,sha256=mNDOaYVemmxKREXyOf7IuQdFDXrvZ7f_7sNaqWV7TsI,678
7
- python4cpm/logger.py,sha256=66lkgsGsSyXJLeMfn8zq6DinTPJWRfFyMBiUYySM2Ec,1461
8
- python4cpm/python4cpm.py,sha256=hkVKd_pEiCA7VPPSUgGFxJ_9sWb3p4GB-EJ034HLxfA,3446
9
- python4cpm/python4cpmhandler.py,sha256=SXKsnFAwUp8cHEhv2TygpNpptUkN3bVQZt1i-3TWql4,935
10
- python4cpm/secret.py,sha256=H3TUjhVN9uPPtr3BUaENEPG1odc3SJXj-u7wD-bCz58,536
11
- python4cpm-1.1.7.dist-info/licenses/LICENSE,sha256=vF2wZA3GchZjH5lUmhonEwd4snuBc6o0ytpZNxVFyCw,1077
12
- python4cpm-1.1.7.dist-info/METADATA,sha256=Kh0gEBT3OepZHxMrTGjQY9llpEprDnLAHBPP7_V4bFI,11193
13
- python4cpm-1.1.7.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
14
- python4cpm-1.1.7.dist-info/top_level.txt,sha256=EhbshwpANmL0wYXaET8_6V9ZENtSwIyAd-kM3jGhUlE,11
15
- python4cpm-1.1.7.dist-info/RECORD,,