GithubHelp home page GithubHelp logo

crypt_r's Introduction

crypt_r --- Function to check Unix passwords

Originally by: Steven D. Majewski <[email protected]>

The crypt_r module is a renamed copy of the crypt module as it was present in Python 3.12 before it was removed.

See PEP 594 for details of the removal.

Unlike crypt, this library always exposes the crypt_r(3) function, not crypt(3).

Note that crypt_r is not part of any standard. This library is tested with the crypt_r implementation in Fedora Linux (libxcrypt, as of 2024), and should work with compatible implementations of crypt_r (such as libcrypt.so from older glibc).

Note that the improvements in crypt_r over crypt are in memory management and thread safety, not security/cryptography.

It is easy to use crypt_r in an insecure way. Notably: All hashing methods except METHOD_CRYPT (the original Unix algorithm from the 1970s) are optional platform-specific extensions. This library does not expose modern hashing methods like libxcrypt's yescrypt. The last wrapper update is from 2017. No future development is planned.

To use this module, you can either import crypt_r explicitly or use the old crypt name for backward compatibility. However, on Python older than 3.13, the crypt module from the standard library will usually take precedence on sys.path.

Here follows the original documentation for the removed crypt module, updated to refer to it as crypt_r:


This module implements an interface to the crypt_r(3) routine, which is a one-way hash function based upon a modified DES algorithm; see the Unix man page for further details. Possible uses include storing hashed passwords so you can check passwords without storing the actual password, or attempting to crack Unix passwords with a dictionary.

Notice that the behavior of this module depends on the actual implementation of the crypt_r(3) routine in the running system. Therefore, any extensions available on the current implementation will also be available on this module.

Hashing Methods

New in Python 3.3.

The crypt_r module defines the list of hashing methods (not all methods are available on all platforms):

METHOD_SHA512
A Modular Crypt Format method with 16 character salt and 86 character hash based on the SHA-512 hash function. This is the strongest method.
METHOD_SHA256
Another Modular Crypt Format method with 16 character salt and 43 character hash based on the SHA-256 hash function.
METHOD_BLOWFISH

Another Modular Crypt Format method with 22 character salt and 31 character hash based on the Blowfish cipher.

New in Python 3.7.

METHOD_MD5
Another Modular Crypt Format method with 8 character salt and 22 character hash based on the MD5 hash function.
METHOD_CRYPT
The traditional method with a 2 character salt and 13 characters of hash. This is the weakest method.

Module Attributes

New in Python 3.3.

methods
A list of available password hashing algorithms, as crypt_r.METHOD_* objects. This list is sorted from strongest to weakest.

Module Functions

The crypt_r module defines the following functions:

crypt(word, salt=None)

word will usually be a user's password as typed at a prompt or in a graphical interface. The optional salt is either a string as returned from mksalt(), one of the crypt_r.METHOD_* values (though not all may be available on all platforms), or a full encrypted password including salt, as returned by this function. If salt is not provided, the strongest method available in methods will be used.

Checking a password is usually done by passing the plain-text password as word and the full results of a previous crypt call, which should be the same as the results of this call.

salt (either a random 2 or 16 character string, possibly prefixed with $digit$ to indicate the method) which will be used to perturb the encryption algorithm. The characters in salt must be in the set [./a-zA-Z0-9], with the exception of Modular Crypt Format which prefixes a $digit$.

Returns the hashed password as a string, which will be composed of characters from the same alphabet as the salt.

Since a few crypt_r(3) extensions allow different values, with different sizes in the salt, it is recommended to use the full crypted password as salt when checking for a password.

Changed in Python 3.3: Accept crypt_r.METHOD_* values in addition to strings for salt.

mksalt(method=None, *, rounds=None)

Return a randomly generated salt of the specified method. If no method is given, the strongest method available in methods is used.

The return value is a string suitable for passing as the salt argument to crypt .

rounds specifies the number of rounds for METHOD_SHA256, METHOD_SHA512 and METHOD_BLOWFISH. For METHOD_SHA256 and METHOD_SHA512 it must be an integer between 1000 and 999_999_999, the default is 5000. For METHOD_BLOWFISH it must be a power of two between 16 (24) and 2_147_483_648 (231), the default is 4096 (212).

New in Python 3.3.

Changed in Python 3.7: Added the rounds parameter.

Examples

A simple example illustrating typical use (a constant-time comparison operation is needed to limit exposure to timing attacks. hmac.compare_digest() is suitable for this purpose):

import pwd
import crypt_r
import getpass
from hmac import compare_digest as compare_hash

def login():
    username = input('Python login: ')
    cryptedpasswd = pwd.getpwnam(username)[1]
    if cryptedpasswd:
        if cryptedpasswd == 'x' or cryptedpasswd == '*':
            raise ValueError('no support for shadow passwords')
        cleartext = getpass.getpass()
        return compare_hash(crypt_r.crypt(cleartext, cryptedpasswd), cryptedpasswd)
    else:
        return True

To generate a hash of a password using the strongest available method and check it against the original:

import crypt_r
from hmac import compare_digest as compare_hash

hashed = crypt_r.crypt(plaintext)
if not compare_hash(hashed, crypt_r.crypt(plaintext, hashed)):
    raise ValueError("hashed version doesn't validate against original")

Changelog

3.13.1

  • Fix build with -Werror=incompatible-pointer-types

3.13.0

  • Initial fork from CPython 3.12.3
  • Always uses the crypt_r(3) function, never crypt(3)
  • Renamed the Python modules to crypt_r and _crypt_r

For historical changes when this module was included in Python, please refer to the Python 3.12 Changelog.

crypt_r's People

Contributors

anthonybaxter avatar benjaminp avatar birkenfeld avatar bitdancer avatar brettcannon avatar cam-gerlach avatar ericsnowcurrently avatar ezio-melotti avatar felixxm avatar freddrake avatar gvanrossum avatar hrnciar avatar hroncok avatar larryhastings avatar loewis avatar mdickinson avatar merwok avatar mhammond avatar ncoghlan avatar nnorwitz avatar pitrou avatar serhiy-storchaka avatar shireenrao avatar terryjreedy avatar tim-one avatar tiran avatar vadmium avatar vstinner avatar warsaw avatar yhg1s avatar

Stargazers

 avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Forkers

hroncok hrnciar

crypt_r's Issues

Harmful renaming?

I'm a lost at the renaming, couldn't you have keep it with the same previous name, ie crypt?

I had hoped that installing passlib 1.7.4 + crypt_r with Python 3.13 would work out of the box.

However passlib (which does not seem to be updated soon) does from crypt import crypt ... ,
so a key point is that the package name (not its publication name, I'm fine with crypt_r)
must be crypt and the provided function must be crypt for this to work.

There should not be any issue with Python 3.13 because there is no crypt, it was removed, that's the point.

There should not be any issue with prior versions because there is a crypt there and it is the same as this one,
so declaring a dependency conditional on the version would be enough. The new crypt_r module should declare
that it requires Python 3.13 or above.

What am I missing?

Add a changelog

We should add a changelog (to REDAME?). It should say what changes since the fork from CPython and link to CPython 3.12.3 changelog for previous changes.

Could not install crypt_r on Mac

Could not install crypt_r on Mac.

% pip install crypt-r

Collecting crypt-r
Using cached crypt_r-3.13.1.tar.gz (20 kB)
Installing build dependencies ... done
Getting requirements to build wheel ... done
Preparing metadata (pyproject.toml) ... done
Building wheels for collected packages: crypt-r
Building wheel for crypt-r (pyproject.toml) ... error
error: subprocess-exited-with-error

× Building wheel for crypt-r (pyproject.toml) did not run successfully.
│ exit code: 1
╰─> [26 lines of output]
running bdist_wheel
running build
running build_py
creating build
creating build/lib.macosx-10.9-x86_64-cpython-311
copying src/crypt_r.py -> build/lib.macosx-10.9-x86_64-cpython-311
copying src/crypt.py -> build/lib.macosx-10.9-x86_64-cpython-311
running egg_info
writing src/crypt_r.egg-info/PKG-INFO
writing dependency_links to src/crypt_r.egg-info/dependency_links.txt
writing top-level names to src/crypt_r.egg-info/top_level.txt
reading manifest file 'src/crypt_r.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
warning: no files found matching '*.h' under directory 'src'
adding license file 'LICENSE'
writing manifest file 'src/crypt_r.egg-info/SOURCES.txt'
running build_ext
building '_crypt_r' extension
creating build/temp.macosx-10.9-x86_64-cpython-311
creating build/temp.macosx-10.9-x86_64-cpython-311/src
clang -DNDEBUG -fwrapv -O2 -Wall -fPIC -O2 -isystem /<...>/include -fPIC -O2 -isystem /Users/serg/opt/anaconda3/envs/tokenizer/include -I/Users/<...>/include/python3.11 -c src/_crypt_r.c -o build/temp.macosx-10.9-x86_64-cpython-311/src/_crypt_r.o
src/_crypt_r.c:9:10: fatal error: 'crypt.h' file not found
#include <crypt.h>
^~~~~~~~~
1 error generated.
error: command '/usr/bin/clang' failed with exit code 1
[end of output]

note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for crypt-r
Failed to build crypt-r
ERROR: Could not build wheels for crypt-r, which is required to install pyproject.toml-based projects

Add Python package metadata

We should add some metadata to pyproject.toml.

  • minimal Python version
  • license
  • classifiers
  • link(s) this repository
  • ...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.