blackmamba.framework.security

Security.framework wrapper.

Shared classes and constants

Base classes for keychain items (passwords)

These classes do provide shared implementation of methods like delete, etc.

Generic password specifics

Internet password specifics

Errors

Base class for all errors is KeychainError. If you’d like to catch all security errors, just do:

except KeychainError:
    pass

Pythonista compatibility

Compatibility layer for Pythonista keychain module. Signature for all these functions matches Pythonista ones.

These functions will not be enhanced to support prompt, authentication_ui unless Ole adds them to the Pythonista itself.

Example how to use it as a keychain drop in replacement:

import blackmamba.framework.security as keychain
keychain.set_password('service', 'account', 'password')

Low level wrappers

All these wrappers operates with kSec* keys. These keys are not listed in the documentation just to make it shorter.

You shouldn’t use these low level wrappers unless you really need them. Stick with GenericPassword or InternetPassword.

Examples

Store generic password:

gp = GenericPassword('service', 'account')
gp.set_password('password')

Update generic password attributes:

gp = GenericPassword('service', 'account')
gp.comment = 'Great password'
gp.description = 'Demo purposes, nothing elseeeee'
gp.save()

Get generic password attributes:

gp = GenericPassword('service', 'account')
attrs = gp.get_attributes()
print(attrs.creation_date)

Protect password with user presence:

gp = GenericPassword('service', 'account')
gp.access_control = AccessControl(
    Accessibility.WHEN_PASSCODE_SET_THIS_DEVICE_ONLY,
    AuthenticationPolicy.TOUCH_ID_ANY | AuthenticationPolicy.OR | AuthenticationPolicy.DEVICE_PASSCODE
)
gp.set_password('password')

Get protected password:

gp = GenericPassword('service', 'account')
try:
    password = gp.get_password(
        prompt='Your finger!'
    )
    print(password)
except KeychainUserCanceledError:
    print('User did tap on Cancel, no password')
except KeychainAuthFailedError:
    print('Authentication failed, no password')

Disable authentication UI for protected items:

gp = GenericPassword('service', 'account')
try:
    password = gp.get_password(
        prompt='Your finger!',
        authentication_ui=AuthenticationUI.FAIL
    )
    print(password)
except KeychainInteractionNotAllowedError:
    print('Item is protected, authentication UI disabled, no password')

Skip protected items:

gp = GenericPassword('service', 'account')
try:
    password = gp.get_password(
        prompt='Your finger!',
        authentication_ui=AuthenticationUI.SKIP
    )
    print(password)
except KeychainItemNotFoundError:
    print('Authentication UI disabled, protected items skipped, no password')

Query for generic passwords:

try:
    for x in GenericPassword.query_items():
        print(f'{x.creation_date} {x.service} {x.account}')
except KeychainItemNotFoundError:
    print('No generic password items')
except KeychainUserCanceledError:
    print('Some items are protected, but user cancels authentication')
except KeychainAuthFailedError:
    print('Some items are protected, but authentication failed')

Limit to specific service:

GenericPassword.query_items(service='service')

Skip protected items:

GenericPassword.query_items(authentication_ui=AuthenticationUI.SKIP)

Internet password:

ip = InternetPassword('zrzka', server='https://github.com/',
                      protocol=Protocol.HTTPS, authentication_type=AuthenticationType.HTML_FORM)
ip.set_password('password')

Query internet passwords:

for x in InternetPassword.query_items(server='https://github.com/'):
    print(f'{x.creation_date} {x.account} {x.protocol} {x.authentication_type}')
class blackmamba.framework.security.AccessControl(protection: blackmamba.framework.security.Accessibility, flags: blackmamba.framework.security.AuthenticationPolicy)[source]

Allows you to combine accessibility and authentication policy.

Parameters:
flags

Authentication policy flags.

protection

Keychain item protection.

value

SecAccessControl object wrapped in ObjCInstance.

Raises:KeychainError – Failed to create SecAccessControl object.
class blackmamba.framework.security.Accessibility[source]

Indicates when a keychain item is accessible.

You should choose the most restrictive option that meets your app’s needs so that the system can protect that item to the greatest extent possible.

Default value is WHEN_UNLOCKED.

  • ALWAYS - The data in the keychain item can always be accessed regardless of whether the device is locked.

    This is not recommended for application use. Items with this attribute migrate to a new device when using encrypted backups.

  • ALWAYS_THIS_DEVICE_ONLY - The data in the keychain item can always be accessed regardless of whether the device is locked.

    This is not recommended for application use. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present.

  • WHEN_PASSCODE_SET_THIS_DEVICE_ONLY - The data in the keychain can only be accessed when the device is unlocked.

    Only available if a passcode is set on the device.

    This is recommended for items that only need to be accessible while the application is in the foreground. Items with this attribute never migrate to a new device. After a backup is restored to a new device, these items are missing. No items can be stored in this class on devices without a passcode. Disabling the device passcode causes all items in this class to be deleted.

  • AFTER_FIRST_UNLOCK - The data in the keychain item cannot be accessed after a restart until the device has been unlocked once by the user.

    After the first unlock, the data remains accessible until the next restart. This is recommended for items that need to be accessed by background applications. Items with this attribute migrate to a new device when using encrypted backups.

  • AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY - The data in the keychain item cannot be accessed after a restart until the device has been unlocked once by the user.

    After the first unlock, the data remains accessible until the next restart. This is recommended for items that need to be accessed by background applications. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present.

  • WHEN_UNLOCKED - The data in the keychain item can be accessed only while the device is unlocked by the user.

    This is recommended for items that need to be accessible only while the application is in the foreground. Items with this attribute migrate to a new device when using encrypted backups.

    This is the default value for keychain items added without explicitly setting an accessibility constant.

  • WHEN_UNLOCKED_THIS_DEVICE_ONLY - The data in the keychain item can be accessed only while the device is unlocked by the user.

    This is recommended for items that need to be accessible only while the application is in the foreground. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present.

class blackmamba.framework.security.AuthenticationPolicy[source]

Protection class to be used for the item.

  • USER_PRESENCE - Constraint to access an item with either Touch ID or passcode.

    Touch ID does not have to be available or enrolled. The item is still accessible by Touch ID even if fingers are added or removed.

  • TOUCH_ID_ANY - Constraint to access an item with Touch ID for any enrolled fingers.

    Touch ID must be available and enrolled with at least one finger. The item is still accessible by Touch ID if fingers are added or removed.

  • TOUCH_ID_CURRENT_SET - Constraint to access an item with Touch ID for currently enrolled fingers.

    Touch ID must be available and enrolled with at least one finger. The item is invalidated if fingers are added or removed.

  • DEVICE_PASSCODE - Constraint to access an item with a passcode.

  • OR - Logical disjunction operation, such that when specifying more than one constraint, at least one must be satisfied.

  • AND - Logical conjunction operation, such that when specifying more than one constraint, all of them must be satisfied.

  • APPLICATION_PASSWORD - Option to use an application-provided password for data encryption key generation.

    This may be specified in addition to any constraints.

class blackmamba.framework.security.AuthenticationType[source]

Indicates the item’s authentication scheme.

  • NTLM - Windows NT LAN Manager authentication.
  • MSN - Microsoft Network default authentication.
  • DPA - Distributed Password authentication.
  • RPA - Remote Password authentication.
  • HTTP_BASIC - HTTP Basic authentication.
  • HTTP_DIGEST - HTTP Digest Access authentication.
  • HTML_FORM - HTML form based authentication.
  • DEFAULT - The default authentication type.
class blackmamba.framework.security.AuthenticationUI[source]

Indicates whether the user may be prompted for authentication.

A default value of ALLOW is assumed when this key is not present.

  • ALLOW - A value that indicates user authentication is allowed.

    The user may be prompted for authentication. This is the default value.

  • FAIL - A value that indicates user authentication is disallowed.

    When you specify this value, if user authentication is needed, the KeychainInteractionNotAllowedError is raised.

  • SKIP - A value that indicates items requiring user authentication should be skipped.

    Silently skip any items that require user authentication.

class blackmamba.framework.security.GenericPassword(service: str, account: str)[source]

Generic password wrapper.

Parameters:
  • service (str) – Service.
  • account (str) – Account.
service

str – Service.

account

str – Account.

generic

bytes – Custom data (not password).

get_attributes(*, prompt: str = None, authentication_ui: blackmamba.framework.security.AuthenticationUI = <AuthenticationUI.ALLOW: 'kSecUseAuthenticationUIAllow'>) → blackmamba.framework.security.GenericPasswordAttributes[source]

Fetch item attributes.

Warning

Never call on the main thread. UI can be locked up if the item is protected.

Parameters:
  • prompt (str, optional) – Authentication prompt.
  • authentication_ui (AuthenticationUI) – Indicates whether the user may be prompted for authentication.
Returns:

GenericPasswordAttributes – Attributes.

Raises:
get_password(*, prompt: str = None, authentication_ui: blackmamba.framework.security.AuthenticationUI = <AuthenticationUI.ALLOW: 'kSecUseAuthenticationUIAllow'>) → str[source]

Fetch item password.

Warning

Never call on the main thread. UI can be locked up if the item is protected.

Parameters:
  • prompt (str, optional) – Authentication prompt.
  • authentication_ui (AuthenticationUI) – Indicates whether the user may be prompted for authentication.
Returns:

str – Password.

Raises:
classmethod query_items(service: str = None, *, prompt: str = None, authentication_ui: blackmamba.framework.security.AuthenticationUI = <AuthenticationUI.ALLOW: 'kSecUseAuthenticationUIAllow'>) → typing.List[blackmamba.framework.security.GenericPasswordAttributes][source]

Search for generic password items.

Warning

Never call on the main thread. UI can be locked up if the item is protected.

Parameters:
  • service (str, optional) – Limit search to specific service.
  • prompt (str, optional) – Authentication prompt.
  • authentication_ui (AuthenticationUI) – Indicates whether the user may be prompted for authentication.
Returns:

List[GenericPasswordAttributes] – List of attributes.

Raises:
set_password(password: str, *, prompt: str = None, authentication_ui: blackmamba.framework.security.AuthenticationUI = <AuthenticationUI.ALLOW: 'kSecUseAuthenticationUIAllow'>)[source]

Set item password.

Warning

Never call on the main thread. UI can be locked up if the item is protected.

Parameters:
  • password (str) – Password to set.
  • prompt (str, optional) – Authentication prompt.
  • authentication_ui (AuthenticationUI) – Indicates whether the user may be prompted for authentication.
Raises:
class blackmamba.framework.security.GenericPasswordAttributes(attrs)[source]

Generic password attributes.

Note

Do not instantiate this class on your own. You have to use GenericPassword.get_attributes or GenericPassword.query_items.

See also

SecItemAttributes for inherited attributes.

item_class

ItemClass – Always ItemClass.GENERIC_PASSWORD.

service

str – Service.

account

str – Account.

generic

bytes – Custom data (not password).

class blackmamba.framework.security.InternetPassword(account: str, security_domain: str = None, server: str = None, protocol: blackmamba.framework.security.Protocol = None, authentication_type: blackmamba.framework.security.AuthenticationType = None, port: int = None)[source]

Internet password wrapper.

Parameters:
  • account (str) – Account.
  • security_domain (str) – Security domain.
  • server (str) – Server.
  • protocol (Protocol) – Protocol.
  • authentication_type (AuthenticationType) – Authentication type.
  • port (int) – Port.
account

str – Account.

security_domain

str – Security domain.

server

str – Server.

protocol

Protocol – Protocol.

authentication_type

AuthenticationType – Authentication type.

port

int – Port.

get_attributes(*, prompt: str = None, authentication_ui: blackmamba.framework.security.AuthenticationUI = <AuthenticationUI.ALLOW: 'kSecUseAuthenticationUIAllow'>) → blackmamba.framework.security.InternetPasswordAttributes[source]

Fetch item attributes.

Warning

Never call on the main thread. UI can be locked up if the item is protected.

Parameters:
  • prompt (str, optional) – Authentication prompt.
  • authentication_ui (AuthenticationUI) – Indicates whether the user may be prompted for authentication.
Returns:

InternetPasswordAttributes – Attributes.

Raises:
get_password(*, prompt: str = None, authentication_ui: blackmamba.framework.security.AuthenticationUI = <AuthenticationUI.ALLOW: 'kSecUseAuthenticationUIAllow'>) → str[source]

Fetch item password.

Warning

Never call on the main thread. UI can be locked up if the item is protected.

Parameters:
  • prompt (str, optional) – Authentication prompt.
  • authentication_ui (AuthenticationUI) – Indicates whether the user may be prompted for authentication.
Returns:

str – Password.

Raises:
classmethod query_items(account: str = None, security_domain: str = None, server: str = None, protocol: blackmamba.framework.security.Protocol = None, authentication_type: blackmamba.framework.security.AuthenticationType = None, port: int = None, *, prompt: str = None, authentication_ui: blackmamba.framework.security.AuthenticationUI = <AuthenticationUI.ALLOW: 'kSecUseAuthenticationUIAllow'>) → typing.List[blackmamba.framework.security.InternetPasswordAttributes][source]

Search for internet password items.

Warning

Never call on the main thread. UI can be locked up if the item is protected.

Parameters:
  • account (str) – Account.
  • security_domain (str) – Security domain.
  • server (str) – Server.
  • protocol (Protocol) – Protocol.
  • authentication_type (AuthenticationType) – Authentication type.
  • port (int) – Port.
  • prompt (str, optional) – Authentication prompt.
  • authentication_ui (AuthenticationUI) – Indicates whether the user may be prompted for authentication.
Returns:

List[InternetPasswordAttributes] – List of attributes.

Raises:
set_password(password, *, prompt: str = None, authentication_ui: blackmamba.framework.security.AuthenticationUI = <AuthenticationUI.ALLOW: 'kSecUseAuthenticationUIAllow'>)[source]

Set item password.

Warning

Never call on the main thread. UI can be locked up if the item is protected.

Parameters:
  • password (str) – Password to set.
  • prompt (str, optional) – Authentication prompt.
  • authentication_ui (AuthenticationUI) – Indicates whether the user may be prompted for authentication.
Raises:
class blackmamba.framework.security.InternetPasswordAttributes(attrs)[source]

Internet password attributes.

Note

Do not instantiate this class on your own. You have to use InternetPassword.get_attributes or InternetPassword.query_items.

See also

SecItemAttributes for inherited attributes.

item_class

ItemClass – Always ItemClass.INTERNET_PASSWORD.

account

str – Account.

security_domain

str – Security domain.

server

str – Server.

protocol

Protocol – Protocol.

authentication_type

AuthenticationType – Authentication type.

port

int – Port.

class blackmamba.framework.security.ItemClass[source]

Keychain item class.

  • GENERIC_PASSWORD - The value that indicates a generic password item.
  • INTERNET_PASSWORD - The value that indicates an Internet password item.
exception blackmamba.framework.security.KeychainAuthFailedError(*args, status: int = None)[source]

Authentication failed.

exception blackmamba.framework.security.KeychainDuplicateItemError(*args, status: int = None)[source]

Keychain item already exists.

exception blackmamba.framework.security.KeychainError(*args, status: int = None)[source]

Base class for all security module errors.

Parameters:
  • *args – Passed to super class
  • status (int, optional) – OSStatus error if applicable or None
status

int, optionalOSStatus error code or None

exception blackmamba.framework.security.KeychainInteractionNotAllowedError(*args, status: int = None)[source]

User interaction is not allowed.

exception blackmamba.framework.security.KeychainItemNotFoundError(*args, status: int = None)[source]

Keychain item does not exist.

exception blackmamba.framework.security.KeychainParamError(*args, status: int = None)[source]

Invalid parameters.

exception blackmamba.framework.security.KeychainUnhandledError(*args, status: int = None)[source]

Generic keychain error.

exception blackmamba.framework.security.KeychainUserCanceledError(*args, status: int = None)[source]

User cancels authentication.

class blackmamba.framework.security.Protocol[source]

Indicates the item’s protocol.

Items of class ItemClass.INTERNET_PASSWORD have this attribute.

  • FTP - FTP protocol.
  • FTP_ACCOUNT - A client side FTP account.
  • HTTP - HTTP protocol.
  • IRC - IRC protocol.
  • NNTP - NNTP protocol.
  • POP3 - POP3 protocol.
  • SMTP - SMTP protocol.
  • SOCKS - SOCKS protocol.
  • IMAP - IMAP protocol.
  • LDAP - LDAP protocol.
  • APPLETALK - AFP over AppleTalk.
  • AFTP - AFP over TCP.
  • TELNET - Telnet protocol.
  • SSH - SSH protocol.
  • FTPS - FTP over TLS/SSL.
  • HTTPS - HTTP over TLS/SSL.
  • HTTP_PROXY - HTTP proxy.
  • HTTPS_PROXY - HTTPS proxy.
  • FTP_PROXY - FTP proxy.
  • SMB - SMB protocol.
  • RTSP - RTSP protocol.
  • RTSP_PROXY - RTSP proxy.
  • DAAP - DAAP protocol.
  • EPPC - Remote Apple Events.
  • IPP - IPP protocol.
  • NNTPS - NNTP over TLS/SSL.
  • LDAPS - LDAP over TLS/SSL.
  • TELNETS - Telnet over TLS/SSL.
  • IMAPS - IMAP over TLS/SSL.
  • IRCS - IRC over TLS/SSL.
  • POP3S - POP3 over TLS/SSL.
class blackmamba.framework.security.SecItem(**kwargs)[source]

Base class for all keychain items.

Parameters:**kwargs – Keyword arguments where keys are matching attribute names and types.
accessibility

Accessibility – Indicates when a keychain item is accessible.

access_control

AccessControl – Indicates access control settings for the item.

description

str – Item description

label

str – Item label

comment

str – Item comment

is_invisible

bool – Indicates the item’s visibility.

is_negative

bool – Indicates whether the item has a valid password.

add(*, data: bytes = None, prompt: str = None, authentication_ui: blackmamba.framework.security.AuthenticationUI = <AuthenticationUI.ALLOW: 'kSecUseAuthenticationUIAllow'>)[source]

Add item to the keychain.

Warning

Never call on the main thread. UI can be locked up if the item is protected.

Parameters:
  • data (bytes, optional) – Item data.
  • prompt (str, optional) – Authentication prompt.
  • authentication_ui (AuthenticationUI) – Indicates whether the user may be prompted for authentication.
Raises:
delete()[source]

Delete keychain item.

Raises:
get_data(*, prompt: str = None, authentication_ui: blackmamba.framework.security.AuthenticationUI = <AuthenticationUI.ALLOW: 'kSecUseAuthenticationUIAllow'>) → bytes[source]

Get keychain item data.

Warning

Never call on the main thread. UI can be locked up if the item is protected.

Parameters:
  • prompt (str, optional) – Authentication prompt.
  • authentication_ui (AuthenticationUI) – Indicates whether the user may be prompted for authentication.
Raises:
item_class

ItemClass – Keychain item class.

save(*, data: bytes = None, prompt: str = None, authentication_ui: blackmamba.framework.security.AuthenticationUI = <AuthenticationUI.ALLOW: 'kSecUseAuthenticationUIAllow'>)[source]

Save keychain item.

Convenience method wrapping add and update methods. Use this method if you’d like to store keychain item and you don’t care if it exists or not. It’s handled automatically for you.

Warning

Never call on the main thread. UI can be locked up if the item is protected.

Parameters:
  • data (bytes, optional) – Item data.
  • prompt (str, optional) – Authentication prompt.
  • authentication_ui (AuthenticationUI) – Indicates whether the user may be prompted for authentication.
Raises:
update(*, data: bytes = None, prompt: str = None, authentication_ui: blackmamba.framework.security.AuthenticationUI = <AuthenticationUI.ALLOW: 'kSecUseAuthenticationUIAllow'>)[source]

Update keychain item.

Warning

Never call on the main thread. UI can be locked up if the item is protected.

Parameters:
  • data (bytes, optional) – Item data.
  • prompt (str, optional) – Authentication prompt.
  • authentication_ui (AuthenticationUI) – Indicates whether the user may be prompted for authentication.
Raises:
class blackmamba.framework.security.SecItemAttributes(attrs)[source]

Base class for all keychain item attributes.

Note

Do not instantiate this class on your own. You have to use SecItem subclass get_attributes instance method or query_items class method.

modification_date

datetime.datetime – Modification date.

creation_date

datetime.datetime – Creation date.

description

str – Item description.

label

str – Item label.

comment

str – Item comment.

is_invisible

bool – Indicates the item’s visibility.

is_negative

bool – Indicates whether the item has a valid password.

blackmamba.framework.security.delete_password(service, account)[source]

Delete the password for the given service/account from the keychain.

blackmamba.framework.security.get_password(service, account)[source]

Get the password for the given service/account that was previously stored in the keychain.

blackmamba.framework.security.get_services()[source]

Return a list of all services and accounts that are stored in the keychain (each item is a 2-tuple).

blackmamba.framework.security.reset_keychain() → NoneType[source]

Delete all data from the keychain (including the master password) after showing a confirmation dialog.

Raises:NotImplementedError – Always raised, not implemented and never will be.
blackmamba.framework.security.sec_item_add(attributes: dict) → None[source]

SecItemAdd wrapper.

Parameters:

attributes – Keychain item attributes.

Raises:
blackmamba.framework.security.sec_item_copy_matching(query_attributes: dict) → <MagicMock name='mock.ObjCInstance' id='140335229180056'>[source]

SecItemCopyMatching wrapper.

Parameters:

query_attributes – Keychain item attributes.

Returns:

ObjCInstance which can be hold NSDictionary or NSData.

Raises:
blackmamba.framework.security.sec_item_copy_matching_attributes(query_attributes: dict) → dict[source]

SecItemCopy wrapper.

Calls sec_item_copy_matching and forces attributes retrieval.

Parameters:

query_attributes – Keychain item attributes.

Raises:
blackmamba.framework.security.sec_item_copy_matching_data(query_attributes: dict) → bytes[source]

SecItemCopy wrapper.

Calls sec_item_copy_matching and forces data retrieval.

Parameters:

query_attributes – Keychain item attributes.

Raises:
blackmamba.framework.security.sec_item_delete(query_attributes: dict) → None[source]

SecItemDelete wrapper.

Parameters:

query_attributes – Keychain item attributes

Raises:
blackmamba.framework.security.sec_item_update(query_attributes: dict, attributes_to_update: dict) → None[source]

SecItemUpdate wrapper.

Parameters:
  • query_attributes – Item query attributes.
  • attributes_to_update – Attributes that should be updated.
Raises:
blackmamba.framework.security.set_password(service, account, password)[source]

Save a password for the given service and account in the keychain.