File: secretutils.py

package info (click to toggle)
python-oslo.utils 10.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 1,104 kB
  • sloc: python: 7,832; makefile: 21; sh: 2
file content (71 lines) | stat: -rw-r--r-- 2,216 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

"""
Secret utilities.

.. versionadded:: 3.5
"""

import ctypes
import ctypes.util
import secrets
import string as _string
from typing import Any, cast


_crypt: Any
if ctypes.util.find_library("crypt"):
    _libcrypt = ctypes.CDLL(ctypes.util.find_library("crypt"), use_errno=True)
    _crypt = _libcrypt.crypt
    _crypt.argtypes = (ctypes.c_char_p, ctypes.c_char_p)
    _crypt.restype = ctypes.c_char_p
else:
    _crypt = None


def crypt_mksalt(method: str) -> str:
    """Make salt to encrypt password string

    This is provided as a replacement of crypt.mksalt method because crypt
    module was removed in Python 3.13.

    .. versionadded:: 8.0
    """
    # NOTE(tkajinam): The mksalt method in crypto module used to support MD5
    # and DES. However these are considered unsafe so we do not support these
    # to engourage more secure methods.
    methods = {'SHA-512': '$6$', 'SHA-256': '$5$'}
    if method not in methods:
        raise ValueError(f'Unsupported method: {method}')

    salt_set = _string.ascii_letters + _string.digits + './'
    return ''.join(
        [methods[method]] + [secrets.choice(salt_set) for c in range(16)]
    )


def crypt_password(key: str, salt: str) -> str:
    """Encrtpt password string and generate the value in /etc/shadow format

    This is provided as a replacement of crypt.crypt method because crypt
    module was removed in Python 3.13.

    .. versionadded:: 8.0
    """
    if _crypt is None:
        raise RuntimeError('libcrypt is not available')
    return cast(
        bytes, _crypt(key.encode('utf-8'), salt.encode('utf-8'))
    ).decode('utf-8')