python-nss is a Python binding for NSS (Network Security Services) and NSPR (Netscape Portable Runtime). NSS provides cryptography services supporting SSL, TLS, PKI, PKIX, X509, PKCS*, etc. NSS is an alternative to OpenSSL and used extensively by major software projects. NSS is FIPS-140 certified.
NSS is built upon NSPR because NSPR provides an abstraction of common operating system services, particularly in the areas of networking and process management. Python also provides an abstraction of common operating system services but because NSS and NSPR are tightly bound python-nss exposes elements of NSPR.
For information on NSS and NSPR, see the following:
NSS and NSPR are C language API's which python-nss "wraps" and exposes to Python programs. The design of python-nss follows these basic guiding principles:
- Be a thin layer with almost a one-to-one mapping of NSS/NSPR calls to python methods and functions. Programmers already familiar with NSS/NSPR will be quite comfortable with python-nss.
- Be "Pythonic". The term Pythonic means to follow accepted Python paradigms and idoms in the Python language and libraries. Thus when deciding if the NSS/NSPR API should be rigidly followed or a more Pythonic API provided the Pythonic implementation wins because Python programmers do not want to write C programs in Python, rather they want their Python code to feel like Python code with the richness of full Python.
- Identifer names follow the preferred Python style instead of the style in the NSS/NSPR C header files.
- Classes are camel-case. Class names always begin with a upper case letter and are then followed by a mix of lower and upper case letters, a upper case letter is used to separate words. Acronyms always appear as a contiguous string of upper case letters.
- Method, function and property names are always lower case with words seperated by underscores.
- Constants are all upper case with words seperated by underscores, they match the NSS/NSPR C API.
- Every module, class, function, and method has associated documentation and is exposed via the standard Python methodology. This documentation is available via the numerous Python documentation extraction tools. Also see the generated HTML documentation provided with each release. The current release's documentation can be found here.
- NSS/NSPR structs are exposed as Python objects.
- NSS/NSPR functions which operate on a NSS/NSPR object (i.e. struct) become methods of that object.
- NSS/NSPR objects which are collections support the Python iteration protocol. In other words they can be iterated over, indexed by position, or used as slices.
- NSS/NSPR objects whose collection elements can be referenced by name support associative indexing.
- NSS/NSPR objects which have "get" and "set" API function calls are exposed as Python properties.
- All NSS/NSPR Python objects can print their current value by evaluting the Python object in a string context or by using the Python str() function.
- Support threading. The Python Global Interpreter Lock (GIL) is released prior to calling NSS/NSPR C functions and reaquired after the NSS/NSPR C function returns. This allows other Python threads to execute during the time a NSS/NSPR function is progress in another thread. Also, any "global" values which are set in python-nss are actually thread-local. Examples of this are the various callbacks which can be set and their parameters. Thus each thread gets it own set of callbacks.
- Many methods/functions provide sane default (keyword) parameters freeing the Python programmer from having to specify all parameters yet allowing them to be overriden when necessary.
- Error codes are never returned from methods/functions. python-nss follows the existing Python exception mechanism. Any error reported by NSS/NSPR is converted into a Python exception and raised. The exact error code, error description, and often contextual error information will be present in the exception object.
- Enumerated constants used in the NSS/NSPR API's are available in the Python module under the exact same name as they appear in the C header files of NSS/NSPR.
- Convenience functions are provided to translate between the numeric value of an enumerated constant and it's string representation and visa versa.
- python-nss internally supports UTF-8. Strings may be Python str objects or Python unicode objects. If a Python unicode object is passed to a NSS/NSPR function it will be encoded as UTF-8 first before being passed to NSS/NSPR.
- python-nss tries to be flexible when generating a print representation of complex objects. For simplicity you can receive a block of formatted text but if you need more control, such as when building GUI elments you can access a list of "lines", each line is paired with an indentation level value. The (indent, text) pairs allow you to insert the item into a GUI tree structure or simply change the indentation formatting.
- Deprecated elements of the python-nss API are marked with Python deprecation warnings as well as being documented in the nss module documentation. As of Python 2.7 deprecation warnings are no longer reported by default. It is suggested Python developers using python-nss periodically run their code with deprecation warnings enabled. Depercated elements will persist for a least two releases before being removed from the API entirely.
Red Hat utilizes both NSS and Python in many of it's projects, however it was not previously possible to call NSS directly from Python. To solve this problem Red Hat generously funded the initial development of python-nss as well as it's continued maintenance. Red Hat following it's open source philosophy has contributed the source to the Mozilla security project. Red Hat welcomes all interested contributors who would like to contribute the the python-nss project as part of an open source community. The initial release of python-nss occurred in September 2008 with it's inclusion in the Fedora distribution. The source code to python-nss was first imported into the Mozilla CVS repository on June 9th 2009. python-nss is currently available in:
The principal developer of python-nss is John Dennis firstname.lastname@example.org. Additional contributors are:
The python-nss binding is still young despite having been utilized in several major software projects. Thus it's major version number is still at zero. This is primarily so the developers can make changes to the API as experiece grows with it. For example it is already known there are some naming inconsistencies. Elments of the API are probably not ideally partitioned into proper namespaces via Python modules. Some functionality and interface have already been deprecated due to lessons learned. Thus at some point in the future when it is felt the API has solidified and been further proven in the field a 1.0 release will be made. At that point in time existing users of the python-nss API will need to some elements of their code. A migration script will be provided to assist them.
python-nss is available under the Mozilla Public License, the GNU General Public License, and the GNU Lesser General Public License. For information on downloading python-nss releases as tar files, see Source Download.
python-nss API documentation
The python-nss API documentation for the current release can be viewed at python-nss API documentation.
The API documentation is generated from the python-nss source code and compiled modules. You can build it yourself via
./setup.py build_doc. Most distributions include the python-nss API documentation in the python-nss packaging. Consult your distribution for more information.
The doc/examples directory contains numerous examples of python-nss programs and libraries you may wish to consult. They illustrate suggested usage and best practice.
In addition the test directory contains unit tests that also illustrate python-nss usage, however unlike the examples the unit tests are geared towards testing rather than expository illustration.
The doc directory contains other files you may wish to review.
How to Report a Bug
python-nss bugs are currently being tracked in the Red Hat bugzilla system for Fedora. You can enter a bug report here.
Source Download Area
Source downloads are maintained here. Links to download URL for a specific release can be found in the Release Information section.
Mozilla Source Code Management (SCM) Information
On March 21, 2013 the NSS project switched from using CVS as it's source code manager (SCM) to Mercurial, also known as
hg. All prior CVS information (including release tags) were imported into the new Mercurial repositories, as such there is no need to utilize the deprecated CVS repositories, use Mercurial instead.
To check out python-nss source code from Mercurial do this:
hg clone https://hg.mozilla.org/projects/python-nss
The SCM tags for various python-nss releases can be found in the Release Information.
You may want to review the Getting Mozilla Source Code Using Mercurial documentation for more information with working with Mercurial.
The old deprecated CVS documentation can be found here: Getting Mozilla Source Code Using CVS.
The old deprecated python-nss CVS source code location is
Release 0.14.1 contains only modifications to tests and examples, otherwise functionally it is the same as release 0.14.0
Fix bug in ssl_example.py and test_client_server.py where complete data was not read from socket. The Beast CVE fix in NSS causes only one octet to be sent in the first socket packet and then the remaining data is sent normally, this is known as 1/n-1 record splitting. The example and test SSL code sent short messages and then did a sock.recv(1024). We had always received the entire message in one sock.recv() call because it was so short. But sock.recv() does not guarantee how much data will be received, thus this was a coding mistake. The solution is straight forward, use newlines as a record separator and call sock.readline() instead of sock.recv(). sock.readline() calls sock.recv() internally until a complete line is read or the socket is closed.
Rewrite setup_certs.py, it was written like an expect script reacting to prompts read from a pseudo terminal but it was fragile and would hang on some systems. New version uses temporary password file and writes hardcoded responses to the stdin of certuil and modutil.
setup_certs now creates a new sql sytle NSS database (sql:pki)
All tests and examples now load the sql:pki database. Command line arg and variable changed from dbdir to db_name to reflect the database specification is no longer just a directory.
All command line process in test and examples now uses modern argparse module instead of deprecated getopt and optparse. Some command line args were tweaked.
The primary enhancements in this version is support of certifcate validation, OCSP support, and support for the certificate "Authority Information Access" extension.
Enhanced certifcate validation including CA certs can be done via Certificate.verify() or Certificate.is_ca_cert(). When cert validation fails you can now obtain diagnostic information as to why the cert failed to validate. This is encapsulated in the CertVerifyLog class which is a iterable collection of CertVerifyLogNode objects. Most people will probablby just print the string representation of the returned CertVerifyLog object. Cert validation logging is handled by the Certificate.verify() method. Support has also been added for the various key usage and cert type entities which feature prominently during cert validation.
Certificate() constructor signature changed from
Certificate(data, certdb=cert_get_default_certdb(), perm=False, nickname=None)
This change was necessary because all certs should be added to the NSS temporary database when they are loaded, but earlier code failed to to that. It's is not likely that an previous code was failing to pass initialization data or the der_is_signed flag so this change should be backwards compatible.
Fix bug #922247, PKCS12Decoder.database_import() method. Importing into a NSS database would sometimes fail or segfault.
Error codes and descriptions were updated from upstream NSPR & NSS.
The password callback did not allow for breaking out of a password prompting loop, now if None is returned from the password callback the password prompting is terminated.
nss.nss_shutdown_context now called from InitContext destructor, this assures the context is shutdown even if the programmer forgot to. It's still best to explicitly shut it down, this is just failsafe.
Support was added for shutdown callbacks.
cert_dump.py extended to print NS_CERT_TYPE_EXTENSION
cert_usage_flags, nss_init_flags now support optional repr_kind parameter
- The following classes were added:
- error.CertVerifyError (exception)
- The following class methods were added:
- The following class properties were added:
- The following module functions were added:
- The following files were added:
- The following constants were added:
- Reimplement exception handling
- NSPRError is now derived from StandardException instead of EnvironmentError. It was never correct to derive from EnvironmentError but was difficult to implement a new subclassed exception with it's own attributes, using EnvironmentError had been expedient.
- NSPRError now derived from StandardException, provides:
- errno (numeric error code)
- strerror (error description associated with error code)
- error_message (optional detailed message)
- error_code (alias for errno)
- error_desc (alias for strerror)
- CertVerifyError derived from NSPRError, extends with:
- usages (bitmask of returned usages)
- log (CertVerifyLog object)
Expose error lookup to sibling modules
Use macros for bitmask_to_list functions to reduce code duplication and centralize logic.
Add repr_kind parameter to cert_trust_flags_str()
Add support for repr_kind AsEnumName to bitstring table lookup.
Add cert_type_bitstr_to_tuple() lookup function
Add PRTimeConvert(), used to convert Python time values to PRTime, centralizes conversion logic, reduces duplication
Add UTF8OrNoneConvert to better handle unicode parameters which are optional.
Add Certificate_summary_format_lines() utility to generate concise certificate identification info for output.
Certificate_new_from_CERTCertificate now takes add_reference parameter to properly reference count certs, should fix shutdown busy problems.
Add print_traceback(), print_cert() debugging support.
- Fix NSS SECITEM_CompareItem bug via workaround.
- Fix incorrect format strings in PyArg_ParseTuple* for:
- Fix bug when decoding certificate BasicConstraints extension
- Fix hang in setup_certs.
- For NSS >= 3.13 support CERTDB_TERMINAL_RECORD
- You can now query for a specific certificate extension Certficate.get_extension()
- The PublicKey formatting (i.e. format_lines) was augmented to format DSA keys (formerly it only recognized RSA keys).
- Allow lables and values to be justified when printing objects
The following classes were added
The following class methods were added
The following module functions were added
The following internal utilities were added
The following class constructors were modified to accept intialization parameters
- KEYPQGParams (DSA generation parameters)
The following were deprecated
- nss.nss.make_line_pairs (replaced by nss.nss.make_line_fmt_tuples)
make_line_pairs() has been replaced by make_line_fmt_tuples() because 2-valued tuples were not sufficently general. It is expected very few programs will have used this function, it's mostly used internally but provided as a support utility.
- Major new enhancement is additon of PKCS12 support and AlgorithmID's.
- setup.py build enhancements
- Now searches for the NSS and NSPR header files rather than hardcoding their location. This makes building friendlier on other systems (i.e. debian)
- Now takes optional command line arguments, -d or --debug will turn on debug options during the build.
- Fix reference counting bug in PK11_password_callback() which contributed to NSS not being able to shutdown due to resources still in use.
- Add UTF-8 support to ssl.config_server_session_id_cache()
- Added unit tests for cipher, digest, client_server.
- All unittests now run, added test/run_tests to invoke full test suite.
- Fix bug in test/setup_certs.py, hardcoded full path to libnssckbi.so was causing failures on 64-bit systems, just use the libnssckbi.so basename, modutil will find it on the standard search path.
- doc/examples/cert_dump.py uses new AlgorithmID class to dump Signature Algorithm
- doc/examples/ssl_example.py now can cleanly shutdown NSS.
- Exception error messages now include PR error text if available.
The following classes were replaced
- SignatureAlgorithm replaced by new class AlgorithmID
The following classes were added
The following class methods were added
The following class properties were added
The following module functions were added
The following constants were added
The following files were added
- test/test_cipher.py (replaces cipher_test.py)
- test/test_digest.py (replaces digest_test.py)
- Add AddrInfo class to support IPv6 address resolution. Supports iteration over it's set of NetworkAddress objects and provides hostname, canonical_name object properties.
- Add PR_AI_* constants.
- NetworkAddress constructor and NetworkAddress.set_from_string() added optional family parameter. This is necessary for utilizing PR_GetAddrInfoByName().
- NetworkAddress initialized via a string paramter are now initalized via PR_GetAddrInfoByName using family.
- Add NetworkAddress.address property to return the address sans the port as a string. NetworkAddress.str() includes the port. For IPv6 the a hex string must be enclosed in brackets if a port is appended to it, the bracketed hex address with appended with a port is unappropriate in some circumstances, hence the new address property to permit either the address string with a port or without a port.
- Fix the implementation of the NetworkAddress.family property, it was returning bogus data due to wrong native data size.
- HostEntry objects now support iteration and indexing of their NetworkAddress members.
- Add io.addr_family_name() function to return string representation of PR_AF_* constants.
- Modify example and test code to utilize AddrInfo instead of deprecated NetworkAddress functionality. Add address family command argument to ssl_example.
- Fix pty import statement in test/setup_certs.py
- NetworkAddress initialized via a string paramter is now deprecated. AddrInfo should be used instead.
- NetworkAddress.set_from_string is now deprecated. AddrInfo should be used instead.
- NetworkAddress.hostentry is deprecated. It was a bad idea, NetworkAddress objects can support both IPv4 and IPv6, but a HostEntry object can only support IPv4. Plus the implementation depdended on being able to perform a reverse DNS lookup which is not always possible.
- HostEntry.get_network_addresses() and HostEntry.get_network_address() are now deprecated. In addition their port parameter is now no longer respected. HostEntry objects now support iteration and indexing of their NetworkAddress and that should be used to access their NetworkAddress objects instead.
- Utilize PR_NetAddrFamily() access macro instead of explict access.
- Add PRNetAddr_port() utility to hide host vs. network byte order requirements when accessing the port inside a PRNetAddr and simplify accessing the IPv4 vs. IPv6 port variants.
- Replace the use of PR_InitializeNetAddr() with PR_SetNetAddr(), the later properly handles IPv6, the former did not.
- Rename NetworkAddress.addr to NetworkAddress.pr_netaddr for naming consistency.
- Update HostEntry documentation to indicate it's deprecated status.
- Remove redundant implementation of NetworkAddress_new_from_PRNetAddr from py_ssl.c and properly import the implementation from py_nspr_io.c.
- The following other non-IPv6 fixes were also made because they were discovered while doing the IPv6 work:
- Move definition of TYPE_READY to py_nspr_common.h so it can be shared. Update all modules to utilize it.
- Replace incorrect use of free() with PyMem_Free for string data returned by Python's utf-8 encoder.
- Add header dependency information to setup.py so modules will be rebuilt when header files change.
- Add utility tuple_str() to convert a tuple to a string representation by calling str() on each object in the tuple. Tuple.str() in CPython only calls repr() on each member.
- HostEntry objects now store their aliases and NetworkAddress's in internal tuples.
The following classes were added:
The following module functions were added:
The following constants were added:
The following file was added:
- Correct definciencies in auth_certificate_callback found in several of the example files and documentation. If you've copied that code you should merge those changes in.
- Unicode objects now accepted as well as str objects for interfaces expecting a string.
- Sockets were enhanced thusly:
- Threads will now yield during blocking IO.
- Socket.makefile() reimplemented
- file object methods that had been missing (readlines(), sendall(), and iteration) were implemented
- makefile now just returns the same
- Socket object but increments an "open" ref count. Thus a Socket object behaves like a file object and must be closed once for each makefile() call before it's actually closed.
- Sockets now support the iter protocol
- Added methods:
- Apply patches from Miloslav Trmač <email@example.com> for ref counting and threading support. Thanks Miloslav!
- Review all ref counting, numerous ref counting fixes
- Implement cyclic garbage collection support by adding object traversal and clear methods
- Identify static variables, move to thread local storage
- Remove python-nss specific httplib.py, no longer needed python-nss now compatible with standard library
- Rewrite httplib_example.py to use standard library and illustrate ssl, non-ssl, connection class, http class usage
The following classes were added:
The following module functions were added:
The following class methods and properties were added:
Note: it's a method if the name is suffixed with (), a propety otherwise
The following module functions were removed:
Note: use nss.nss.oid_tag() instead
The following files were added:
- SecItem's now support indexing and slicing on their data
- Clean up parsing and parameter validation of variable arg functions
The following were added:
- SecItem.type SecItem.len
- add support for symmetric encryption/decryption
- more support for digests (hashes)
The following classes added:
The following methods and functions added:
The following files added:
- fix Red Hat bug #510343 client_auth_data_callback seg faults if False is returned from callback
- restore ssl.nss_init and ssl.nss_shutdown but make them deprecated
- add __version__ string to nss module
- add binding for NSS_NoDB_Init(), Red Hat bug #509002
- move nss_init and nss_shutdown from ssl module to nss module
- import to Mozilla CVS, tweak directory layout
- apply patch from Red Hat bug #472805, (Miloslav Trmač)
- Don't allow closing a socket twice, that causes crashes.
- Fix return value creation in SSLSocket.get_security_status
- Convert licensing to MPL tri-license
The following were added: