{Role} Secure _create_self_signed_cert
#21719
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Context
When creating a self-signed certificate in commands such as
az ad sp create-for-rbacoraz ad app credential reset:temp_fileand use its name forcreds_file.cert_fileandkey_file.cert_fileandkey_fileare read back and combined intocreds_file.creds_fileto0o600(rw-------).This procedure exposes problems:
Problem 1:
temp_fileis not deletedAccording to https://docs.python.org/3/library/tempfile.html#tempfile.mkstemp:
At least, the temp file made by
mkstempis empty with permission0o600, so it doesn't leak any credential. It's just it will be left as trash.Solution: Use
NamedTemporaryFilewhich automatically deletes the temp file.Problem 2:
cert_fileandkey_fileare not deletedThe "write to file and read it back" logic was introduced by #2457. The reason behind it is unknown. At least, they are secure with permission
0o600, so no one else can read them:Solution: Only keep certificate and key values in memory as variables. Do not write them to files.
Problem 3: Time gap between
creds_file'sopenandchmodThere is a time gap between
creds_file'sopenandchmod, during which its permission is0o755(rwxr-xr-x) meaning other users can read its content.Solution: Create
creds_filewith the right mode, instead of changing it later. ADAL-based Azure CLI uses this approach for creatingaccessTokens.json:azure-cli/src/azure-cli-core/azure/cli/core/_profile.py
Lines 1100 to 1101 in 14cc787
msal-extensionsmade the same change in AzureAD/microsoft-authentication-extensions-for-python#107.References