Skip to content

passlib.apache - Apache Password Files

This module provides utilities for reading and writing Apache's htpasswd and htdigest files, through the use of two helper classes.

Warning

Changed in 1.6: The api for this module was updated to be more flexible, and to have less ambiguous method names. The old method and keyword names are deprecated, and will be removed in Passlib 1.8.

Warning

Changed in 1.7: These classes will now preserve blank lines and "#" comments when updating htpasswd files; previous releases would throw a parse error.

Warning

Changed in 1.8: A number of methods deprecated since 1.6, have been removed.

Htpasswd Files

The HtpasswdFile class allows managing of htpasswd files. A quick summary of its usage:

from passlib.apache import HtpasswdFile

# when creating a new file, set to new=True, add entries, and save.
ht = HtpasswdFile("test.htpasswd", new=True)
ht.set_password("someuser", "really secret password")
ht.save()

# loading an existing file to update a password
ht = HtpasswdFile("test.htpasswd")
ht.set_password("someuser", "new secret password")
ht.save()

# examining file, verifying user's password
ht = HtpasswdFile("test.htpasswd")
print(ht.users())
# > ["someuser"]
print(ht.check_password("someuser", "wrong password"))
# > False
print(ht.check_password("someuser", "new secret password"))
# > True

# making in-memory changes and exporting to string
ht = HtpasswdFile()
ht.set_password("someuser", "mypass")
ht.set_password("someuser", "anotherpass")
s = ht.to_string()
print(s)
# > someuser:$apr1$T4f7D9ly$EobZDROnHblCNPCtrgh5i/
# > anotheruser:$apr1$vBdPWvh1$GrhfbyGvN/7HalW5cS9XB1

Warning

HtpasswdFile currently defaults to using apr_md5_crypt, as this is the only htpasswd hash guaranteed to be portable across operating systems. However, for security reasons Passlib 1.7 will default to using the strongest algorithm available on the host platform (e.g. bcrypt or sha256_crypt). Applications that are relying on the old behavior should specify HtpasswdFile(default_scheme="portable") (new in Passlib 1.6.3).

HtpasswdFile

HtpasswdFile(
    path=None,
    default_scheme=None,
    context=htpasswd_context,
    **kwds,
)

class for reading & writing Htpasswd files.

The class constructor accepts the following arguments:

Parameters:

  • path (filepath, default: None ) –

    Specifies path to htpasswd file, use to implicitly load from and save to.

    This class has two modes of operation:

    1. It can be "bound" to a local file by passing a path to the class constructor. In this case it will load the contents of the file when created, and the :meth:load and :meth:save methods will automatically load from and save to that file if they are called without arguments.

    2. Alternately, it can exist as an independant object, in which case :meth:load and :meth:save will require an explicit path to be provided whenever they are called. As well, autosave behavior will not be available.

    This feature is new in Passlib 1.6, and is the default if no path value is provided to the constructor.

    This is also exposed as a readonly instance attribute.

  • new (bool) –

    Normally, if path is specified, :class:HtpasswdFile will immediately load the contents of the file. However, when creating a new htpasswd file, applications can set new=True so that the existing file (if any) will not be loaded.

    .. versionadded:: 1.6 This feature was previously enabled by setting autoload=False. That alias was removed in Passlib 1.8

  • autosave (bool) –

    Normally, any changes made to an :class:HtpasswdFile instance will not be saved until :meth:save is explicitly called. However, if autosave=True is specified, any changes made will be saved to disk immediately (assuming path has been set).

    This is also exposed as a writeable instance attribute.

  • encoding (str) –

    Optionally specify character encoding used to read/write file and hash passwords. Defaults to utf-8, though latin-1 is the only other commonly encountered encoding.

    This is also exposed as a readonly instance attribute.

  • default_scheme (str, default: None ) –

    Optionally specify default scheme to use when encoding new passwords.

    This can be any of the schemes with builtin Apache support, OR natively supported by the host OS's :func:crypt.crypt function.

    • Builtin schemes include "bcrypt" (apache 2.4+), "apr_md5_crypt"`, and"des_crypt"``.

    • Schemes commonly supported by Unix hosts include "bcrypt", "sha256_crypt", and "des_crypt".

    In order to not have to sort out what you should use, passlib offers a number of aliases, that will resolve to the most appropriate scheme based on your needs:

    • "portable", "portable_apache_24" -- pick scheme that's portable across hosts running apache >= 2.4. This will be the default as of Passlib 2.0.

    • "portable_apache_22" -- pick scheme that's portable across hosts running apache >= 2.4. This is the default up to Passlib 1.9.

    • "host", "host_apache_24" -- pick strongest scheme supported by apache >= 2.4 and/or host OS.

    • "host_apache_22" -- pick strongest scheme supported by apache >= 2.2 and/or host OS.

    .. versionadded:: 1.6 This keyword was previously named default. That alias was removed in Passlib 1.8.

    .. versionchanged:: 1.6.3

    Added support for ``"bcrypt"``, ``"sha256_crypt"``, and ``"portable"`` alias.
    

    .. versionchanged:: 1.7

    Added apache 2.4 semantics, and additional aliases.
    
  • context (:class:`~passlib.context.CryptContext`, default: htpasswd_context ) –

    :class:!CryptContext instance used to create and verify the hashes found in the htpasswd file. The default value is a pre-built context which supports all of the hashes officially allowed in an htpasswd file.

    This is also exposed as a readonly instance attribute.
    
    .. warning::
    
        This option may be used to add support for non-standard hash
        formats to an htpasswd file. However, the resulting file
        will probably not be usable by another application,
        and particularly not by Apache.
    

    Loading & Saving

    .. automethod:: load .. automethod:: load_if_changed .. automethod:: load_string .. automethod:: save .. automethod:: to_string

    Inspection

    .. automethod:: users .. automethod:: check_password .. automethod:: get_hash

    Modification

    .. automethod:: set_password .. automethod:: delete

    Alternate Constructors

    .. automethod:: from_string

    Attributes

    .. attribute:: path

    Path to local file that will be used as the default
    for all :meth:`load` and :meth:`save` operations.
    May be written to, initialized by the *path* constructor keyword.
    

    .. attribute:: autosave

    Writeable flag indicating whether changes will be automatically
    written to *path*.
    

    Errors

Raises:

  • ValueError –

    All of the methods in this class will raise a :exc:ValueError if any user name contains a forbidden character (one of :\r\n\t\x00), or is longer than 255 characters.

mtime property

mtime: float

modify time when last loaded (if bound to a local file)

users

users() -> list[bytes | str]

Return list of all users in database

set_password

set_password(user, password)

Set password for user; adds user if needed.

Returns:

  • –
    • True if existing user was updated.
      • False if user account was added.

    .. versionchanged:: 1.6 This method was previously called update, it was renamed to prevent ambiguity with the dictionary method. The old alias was removed in Passlib 1.8.

get_hash

get_hash(user)

Return hash stored for user, or None if user not found.

.. versionchanged:: 1.6 This method was previously named find, it was renamed for clarity. The old name was removed in Passlib 1.8.

set_hash

set_hash(user, hash)

semi-private helper which allows writing a hash directly; adds user if needed.

.. warning:: does not (currently) do any validation of the hash string

.. versionadded:: 1.7

delete

delete(user)

Delete user's entry.

Returns:

  • –
    • True if user deleted.
    • False if user not found.

check_password

check_password(user, password)

Verify password for specified user. If algorithm marked as deprecated by CryptContext, will automatically be re-hashed.

Returns:

  • –
    • None if user not found.
      • False if user found, but password does not match.
      • True if user found and password matches.

    .. versionchanged:: 1.6 This method was previously called verify, it was renamed to prevent ambiguity with the :class:!CryptContext method. The old alias was removed in Passlib 1.8.

from_string classmethod

from_string(data: str | bytes, **kwargs: Any) -> Self

create new object from raw string.

Parameters:

  • data (str | bytes) –

    database to load, as single string.

  • \*\*kwds –

    all other keywords are the same as in the class constructor

from_path classmethod

from_path(path: PathLike, **kwds: Any) -> Self

create new object from file, without binding object to file.

Parameters:

  • path (str) –

    local filepath to load from

  • \*\*kwds –

    all other keywords are the same as in the class constructor

load_if_changed

load_if_changed() -> bool

Reload from self.path only if file has changed since last load

load

load(path: PathLike | None = None) -> bool

Load state from local file. If no path is specified, attempts to load from self.path.

Parameters:

  • path (str, default: None ) –

    local file to load from

load_string

load_string(data: str | bytes) -> None

Load state from unicode or bytes string, replacing current state

save

save(path: PathLike | None = None) -> None

Save current state to file. If no path is specified, attempts to save to self.path.

to_string

to_string() -> bytes

Export current state as a string of bytes

Htdigest Files

The HtdigestFile class allows management of htdigest files in a similar fashion to HtpasswdFile.

HtdigestFile

HtdigestFile(path=None, default_realm=None, **kwds)

class for reading & writing Htdigest files.

The class constructor accepts the following arguments:

Parameters:

  • path (filepath, default: None ) –

    Specifies path to htdigest file, use to implicitly load from and save to.

    This class has two modes of operation:

    1. It can be "bound" to a local file by passing a path to the class constructor. In this case it will load the contents of the file when created, and the :meth:load and :meth:save methods will automatically load from and save to that file if they are called without arguments.

    2. Alternately, it can exist as an independant object, in which case :meth:load and :meth:save will require an explicit path to be provided whenever they are called. As well, autosave behavior will not be available.

    This feature is new in Passlib 1.6, and is the default if no path value is provided to the constructor.

    This is also exposed as a readonly instance attribute.

  • default_realm (str, default: None ) –

    If default_realm is set, all the :class:HtdigestFile methods that require a realm will use this value if one is not provided explicitly. If unset, they will raise an error stating that an explicit realm is required.

    This is also exposed as a writeable instance attribute.

    .. versionadded:: 1.6

  • new (bool) –

    Normally, if path is specified, :class:HtdigestFile will immediately load the contents of the file. However, when creating a new htpasswd file, applications can set new=True so that the existing file (if any) will not be loaded.

    .. versionadded:: 1.6 This feature was previously enabled by setting autoload=False. That alias was removed in Passlib 1.8

  • autosave (bool) –

    Normally, any changes made to an :class:HtdigestFile instance will not be saved until :meth:save is explicitly called. However, if autosave=True is specified, any changes made will be saved to disk immediately (assuming path has been set).

    This is also exposed as a writeable instance attribute.

  • encoding (str) –

    Optionally specify character encoding used to read/write file and hash passwords. Defaults to utf-8, though latin-1 is the only other commonly encountered encoding.

    This is also exposed as a readonly instance attribute.
    

    Loading & Saving

    .. automethod:: load .. automethod:: load_if_changed .. automethod:: load_string .. automethod:: save .. automethod:: to_string

    Inspection

    .. automethod:: realms .. automethod:: users .. automethod:: check_password(user[, realm], password) .. automethod:: get_hash

    Modification

    .. automethod:: set_password(user[, realm], password) .. automethod:: delete .. automethod:: delete_realm

    Alternate Constructors

    .. automethod:: from_string

    Attributes

    .. attribute:: default_realm

    The default realm that will be used if one is not provided
    to methods that require it. By default this is ``None``,
    in which case an explicit realm must be provided for every
    method call. Can be written to.
    

    .. attribute:: path

    Path to local file that will be used as the default
    for all :meth:`load` and :meth:`save` operations.
    May be written to, initialized by the *path* constructor keyword.
    

    .. attribute:: autosave

    Writeable flag indicating whether changes will be automatically
    written to *path*.
    

    Errors

Raises:

  • ValueError –

    All of the methods in this class will raise a :exc:ValueError if any user name or realm contains a forbidden character (one of :\r\n\t\x00), or is longer than 255 characters.

mtime property

mtime: float

modify time when last loaded (if bound to a local file)

realms

realms()

Return list of all realms in database

users

users(realm=None)

Return list of all users in specified realm.

  • uses self.default_realm if no realm explicitly provided.
  • returns empty list if realm not found.

set_password

set_password(user, realm=None, password=_UNSET)

Set password for user; adds user & realm if needed.

If self.default_realm has been set, this may be called with the syntax set_password(user, password), otherwise it must be called with all three arguments: set_password(user, realm, password).

Returns:

  • –
    • True if existing user was updated
    • False if user account added.

get_hash

get_hash(user, realm=None)

Return :class:~passlib.hash.htdigest hash stored for user.

  • uses self.default_realm if no realm explicitly provided.
  • returns None if user or realm not found.

.. versionchanged:: 1.6 This method was previously named find, it was renamed for clarity. The old name is was removed Passlib 1.8.

set_hash

set_hash(user, realm=None, hash=_UNSET)

semi-private helper which allows writing a hash directly; adds user & realm if needed.

If self.default_realm has been set, this may be called with the syntax set_hash(user, hash), otherwise it must be called with all three arguments: set_hash(user, realm, hash).

.. warning:: does not (currently) do any validation of the hash string

.. versionadded:: 1.7

delete

delete(user, realm=None)

Delete user's entry for specified realm.

if realm is not specified, uses self.default_realm.

Returns:

  • –
    • True if user deleted,
    • False if user not found in realm.

delete_realm

delete_realm(realm)

Delete all users for specified realm.

if realm is not specified, uses self.default_realm.

Returns:

  • –

    number of users deleted (0 if realm not found)

check_password

check_password(user, realm=None, password=_UNSET)

Verify password for specified user + realm.

If self.default_realm has been set, this may be called with the syntax check_password(user, password), otherwise it must be called with all three arguments: check_password(user, realm, password).

Returns:

  • –
    • None if user or realm not found.
      • False if user found, but password does not match.
      • True if user found and password matches.

    .. versionchanged:: 1.6 This method was previously called verify, it was renamed to prevent ambiguity with the :class:!CryptContext method. The old alias was removed in Passlib 1.8.

from_string classmethod

from_string(data: str | bytes, **kwargs: Any) -> Self

create new object from raw string.

Parameters:

  • data (str | bytes) –

    database to load, as single string.

  • \*\*kwds –

    all other keywords are the same as in the class constructor

from_path classmethod

from_path(path: PathLike, **kwds: Any) -> Self

create new object from file, without binding object to file.

Parameters:

  • path (str) –

    local filepath to load from

  • \*\*kwds –

    all other keywords are the same as in the class constructor

load_if_changed

load_if_changed() -> bool

Reload from self.path only if file has changed since last load

load

load(path: PathLike | None = None) -> bool

Load state from local file. If no path is specified, attempts to load from self.path.

Parameters:

  • path (str, default: None ) –

    local file to load from

load_string

load_string(data: str | bytes) -> None

Load state from unicode or bytes string, replacing current state

save

save(path: PathLike | None = None) -> None

Save current state to file. If no path is specified, attempts to save to self.path.

to_string

to_string() -> bytes

Export current state as a string of bytes

References