PyASN1 programmer's manual
written by Ilya Etingof, 2011-2012
Free and open-source pyasn1 library makes it easier for programmers and network engineers to develop, debug and experiment with ASN.1-based protocols using Python programming language as a tool.
Abstract Syntax Notation One (ASN.1) is a set of ITU standards concered with provisioning instrumentation for developing data exchange protocols in a robust, clear and interoperabable way for various IT systems and applications. Most of the efforts are targeting the following areas:
This tutorial and algorithms, implemented by pyasn1 library, are largely based on the information read in the book ASN.1 - Communication between heterogeneous systems by Olivier Dubuisson. Another relevant resource is A Layman's Guide to a Subset of ASN.1, BER, and DER by Burton S. Kaliski. It's advised to refer to these books for more in-depth knowledge on the subject of ASN.1.
As of this writing, pyasn1 library implements most of standard ASN.1 data structures in a rather detailed and feature-rich manner. Another highly important capability of the library is its data serialization facilities. The last component of the standard - ASN.1 compiler is planned for implementation in the future.The pyasn1 library was designed to follow the pre-1995 ASN.1 specification (also known as X.208). Later, post 1995, revision (X.680) introduced significant changes most of which have not yet been supported by pyasn1.
Table of contents
1. Data model for ASN.1 types
All ASN.1 types could be categorized into two groups: scalar (also called simple or primitive) and constructed. The first group is populated by well-known types like Integer or String. Members of constructed group hold other types (simple or constructed) as their inner components, thus they are semantically close to a programming language records or lists.
In pyasn1, all ASN.1 types and values are implemented as Python objects. The same pyasn1 object can represent either ASN.1 type and/or value depending of the presense of value initializer on object instantiation. We will further refer to these as pyasn1 type object versus pyasn1 value object.
Primitive ASN.1 types are implemented as immutable scalar objects. There values could be used just like corresponding native Python values (integers, strings/bytes etc) and freely mixed with them in expressions.
It would be an error to perform an operation on a pyasn1 type object as it holds no value to deal with:
1.1 Scalar types
In the sub-sections that follow we will explain pyasn1 mapping to those primitive ASN.1 types. Both, ASN.1 notation and corresponding pyasn1 syntax will be given in each case.
1.1.1 Boolean type
This is the simplest type those values could be either True or False.
And here's pyasn1 version of it:
1.1.2 Null type
The NULL type is sometimes used to express the absense of any information.
We will explain the CHOICE type later in this paper, meanwhile the NULL type:
1.1.3 Integer type
ASN.1 defines the values of Integer type as negative or positive of whatever length. This definition plays nicely with Python as the latter places no limit on Integers. However, some ASN.1 implementations may impose certain limits of integer value ranges. Keep that in mind when designing new data structures.
A rather strigntforward mapping into pyasn1:
ASN.1 allows to assign human-friendly names to particular values of an INTEGER type.
The Temperature type expressed in pyasn1:
These values labels have no effect on Integer type operations, any value still could be assigned to a type (information on value constraints will follow further in this paper).
1.1.4 Enumerated type
ASN.1 Enumerated type differs from an Integer type in a number of ways. Most important is that its instance can only hold a value that belongs to a set of values specified on type declaration.
When constructing Enumerated type we will use two pyasn1 features: values labels (as mentioned above) and value constraint (will be described in more details later on).
Particular integer values associated with Enumerated value states have no meaning. They should not be used as such or in any kind of math operation. Those integer values are only used by codecs to transfer state from one entity to another.
1.1.5 Real type
Values of the Real type are a three-component tuple of mantissa, base and exponent. All three are integers.
Corresponding pyasn1 objects can be initialized with either a three-component tuple or a Python float. Infinite values could be expressed in a way, compatible with Python float type.
If a Real object is initialized from a Python float or yielded by a math operation, the base is set to decimal 10 (what affects encoding).
1.1.6 Bit string type
ASN.1 BIT STRING type holds opaque binary data of an arbitrarily length. A BIT STRING value could be initialized by either a binary (base 2) or hex (base 16) value.
The pyasn1 BitString objects can initialize from native ASN.1 notation (base 2 or base 16 strings) or from a Python tuple of binary components.
Another BIT STRING initialization method supported by ASN.1 notation is to specify only 1-th bits along with their human-friendly label and bit offset relative to the beginning of the bit string. With this method, all not explicitly mentioned bits are doomed to be zeros.
To express this in pyasn1, we will employ the named values feature (as with Enumeration type).
The BitString objects mimic the properties of Python tuple type in part of immutable sequence object protocol support.
1.1.7 OctetString type
The OCTET STRING type is a confusing subject. According to ASN.1 specification, this type is similar to BIT STRING, the major difference is that the former operates in 8-bit chunks of data. What is important to note, is that OCTET STRING was NOT designed to handle text strings - the standard provides many other types specialized for text content. For that reason, ASN.1 forbids to initialize OCTET STRING values with "quoted text strings", only binary or hex initializers, similar to BIT STRING ones, are allowed.
However, ASN.1 users (e.g. protocols designers) seem to ignore the original purpose of the OCTET STRING type - they used it for handling all kinds of data, including text strings.
In pyasn1, we have taken a liberal approach and allowed both BIT STRING style and quoted text initializers for the OctetString objects. To avoid possible collisions, quoted text is the default initialization syntax.
Most frequent usage of the OctetString class is to instantiate it with a text string.
OctetString objects support the immutable sequence object protocol. In other words, they behave like Python 3 bytes (or Python 2 strings).
When running pyasn1 on Python 3, it's better to use the bytes objects for OctetString instantiation, as it's more reliable and efficient.
Additionally, OctetString's can also be instantiated with a sequence of 8-bit integers (ASCII codes).
It is sometimes convenient to express OctetString instances as 8-bit characters (Python 3 bytes or Python 2 strings) or 8-bit integers.
1.1.8 ObjectIdentifier type
Values of the OBJECT IDENTIFIER type are sequences of integers that could be used to identify virtually anything in the world. Various ASN.1-based protocols employ OBJECT IDENTIFIERs for their own identification needs.
One of the natural ways to map OBJECT IDENTIFIER type into a Python one is to use Python tuples of integers. So this approach is taken by pyasn1.
A more human-friendly "dotted" notation is also supported.
Symbolic names of the arcs of object identifier, sometimes present in ASN.1 specifications, are not preserved and used in pyasn1 objects.
The ObjectIdentifier objects mimic the properties of Python tuple type in part of immutable sequence object protocol support.
1.1.9 Character string types
ASN.1 standard introduces a diverse set of text-specific types. All of them were designed to handle various types of characters. Some of these types seem be obsolete nowdays, as their target technologies are gone. Another issue to be aware of is that raw OCTET STRING type is sometimes used in practice by ASN.1 users instead of specialized character string types, despite explicit prohibition imposed by ASN.1 specification.
The two types are specific to ASN.1 are NumericString and PrintableString.
Their pyasn1 implementations are:
The following types came to ASN.1 from ISO standards on character sets.
The last three types are relatively recent addition to the family of character string types: UniversalString, BMPString, UTF8String.
In pyasn1, all character type objects behave like Python strings. None of them is currently constrained in terms of valid alphabet so it's up to the data source to keep an eye on data validation for these types.
1.1.10 Useful types
There are three so-called useful types defined in the standard: ObjectDescriptor, GeneralizedTime, UTCTime. They all are subtypes of GraphicString or VisibleString types therefore useful types are character string types.
It's advised by the ASN.1 standard to have an instance of ObjectDescriptor type holding a human-readable description of corresponding instance of OBJECT IDENTIFIER type. There are no formal linkage between these instances and provision for ObjectDescriptor uniqueness in the standard.
GeneralizedTime and UTCTime types are designed to hold a human-readable timestamp in a universal and unambiguous form. The former provides more flexibility in notation while the latter is more strict but has Y2K issues.
Despite their intended use, these types possess no special, time-related, handling in pyasn1. They are just printable strings.
In order to continue with the Constructed ASN.1 types, we will first have to introduce the concept of tagging (and its pyasn1 implementation), as some of the Constructed types rely upon the tagging feature.
When a value is coming into an ASN.1-based system (received from a network or read from some storage), the receiving entity has to determine the type of the value to interpret and verify it accordingly.
Historically, the first data serialization protocol introduced in ASN.1 was BER (Basic Encoding Rules). According to BER, any serialized value is packed into a triplet of (Type, Length, Value) where Type is a code that identifies the value (which is called tag in ASN.1), length is the number of bytes occupied by the value in its serialized form and value is ASN.1 value in a form suitable for serial transmission or storage.
For that reason almost every ASN.1 type has a tag (which is actually a BER type) associated with it by default.
An ASN.1 tag could be viewed as a tuple of three numbers: (Class, Format, Number). While Number identifies a tag, Class component is used to create scopes for Numbers. Four scopes are currently defined: UNIVERSAL, context-specific, APPLICATION and PRIVATE. The Format component is actually a one-bit flag - zero for tags associated with scalar types, and one for constructed types (will be discussed later on).
In pyasn1, tags are implemented as immutable, tuple-like objects:
Default tag, associated with any ASN.1 type, could be extended or replaced to make new type distinguishable from its ancestor. The standard provides two modes of tag mangling - IMPLICIT and EXPLICIT.
EXPLICIT mode works by appending new tag to the existing ones thus creating an ordered set of tags. This set will be considered as a whole for type identification and encoding purposes. Important property of EXPLICIT tagging mode is that it preserves base type information in encoding what makes it possible to completely recover type information from encoding.
When tagging in IMPLICIT mode, the outermost existing tag is dropped and replaced with a new one.
To model both modes of tagging, a specialized container TagSet object (holding zero, one or more Tag objects) is used in pyasn1.
As a side note: the "base tag" concept (accessible through the getBaseTag() method) is specific to pyasn1 -- the base tag is used to identify the original ASN.1 type of an object in question. Base tag is never occurs in encoding and is mostly used internally by pyasn1 for choosing type-specific data processing algorithms. The "effective tag" is the one that always appears in encoding and is used on tagSets comparation.
Any two TagSet objects could be compared to see if one is a derivative of the other. Figuring this out is also useful in cases when a type-specific data processing algorithms are to be chosen.
We will complete this discussion on tagging with a real-world example. The following ASN.1 tagged type:
could be expressed in pyasn1 like this:
Referring to the above code, the tagSet class attribute is a property of any pyasn1 type object that assigns default tagSet to a pyasn1 value object. This default tagSet specification can be ignored and effectively replaced by some other tagSet value passed on object instantiation.
It's important to understand that the tag set property of pyasn1 type/value object can never be modifed in place. In other words, a pyasn1 type/value object can never change its tags. The only way is to create a new pyasn1 type/value object and associate different tag set with it.
1.3 Constructed types
Besides scalar types, ASN.1 specifies so-called constructed ones - these are capable of holding one or more values of other types, both scalar and constructed.
In pyasn1 implementation, constructed ASN.1 types behave like Python sequences, and also support additional component addressing methods, specific to particular constructed type.
1.3.1 Sequence and Set types
The Sequence and Set types have many similar properties:
However, Sequence type guarantees the ordering of Sequence value components to match their declaration order. By contrast, components of the Set type can be ordered to best suite application's needs.
Up to this moment, the only method we used for creating new pyasn1 types is Python sub-classing. With this method, a new, named Python class is created what mimics type derivation in ASN.1 grammar. However, ASN.1 also allows for defining anonymous subtypes (room and house components in the example above). To support anonymous subtyping in pyasn1, a cloning operation on an existing pyasn1 type object can be invoked what creates a new instance of original object with possibly modified properties.
All pyasn1 constructed type classes have a class attribute componentType that represent default type specification. Its value is a NamedTypes object.
The NamedTypes class instance holds a sequence of NameType, OptionalNamedType or DefaultedNamedType objects which, in turn, refer to pyasn1 type objects that represent inner SEQUENCE components specification.
Finally, invocation of a subtype() method of pyasn1 type objects in the code above returns an implicitly tagged copy of original object.
Once a SEQUENCE or SET type is decleared with pyasn1, it can be instantiated and initialized (continuing the above code):
Inner components of pyasn1 Sequence/Set objects could be accessed using the following methods:
The Set type share all the properties of Sequence type, and additionally support by-tag component addressing (as all Set components have distinct types).
1.3.2 SequenceOf and SetOf types
Both, SequenceOf and SetOf types resemble an unlimited size list of components. All the components must be of the same type.
SequenceOf and SetOf types are expressed by the very similar pyasn1 type objects. Their components can only be addressed by position and they both have a property of automatic resize.
To specify inner component type, the componentType class attribute should refer to another pyasn1 type object.
Any scalar or constructed pyasn1 type object can serve as an inner component. Missing components are prohibited in SequenceOf/SetOf value objects.
1.3.3 Choice type
Values of ASN.1 CHOICE type can contain only a single value of a type from a list of possible alternatives. Alternatives must be ASN.1 types with distinct tags for the whole structure to remain unambiguous. Unlike most other types, CHOICE is an untagged one, e.g. it has no base tag of its own.
In pyasn1 implementation, Choice object behaves like Set but accepts only a single inner component at a time. It also offers a few additional methods specific to its behaviour.
Since there could be only a single inner component value in the pyasn1 Choice value object, either of the following methods could be used for fetching it (continuing previous code):
1.3.4 Any type
The ASN.1 ANY type is a kind of wildcard or placeholder that matches any other type without knowing it in advance. Like CHOICE type, ANY has no base tag.
The ANY type is frequently used in specifications, where exact type is not yet agreed upon between communicating parties or the number of possible alternatives of a type is infinite. Sometimes an auxiliary selector is kept around to help parties indicate the kind of ANY payload in effect ("code" in the example above).
Values of the ANY type contain serialized ASN.1 value(s) in form of an octet string. Therefore pyasn1 Any value object share the properties of pyasn1 OctetString object.
Receiving application is supposed to explicitly deserialize the content of Any value object, possibly using auxiliary selector for figuring out its ASN.1 type to pick appropriate decoder.
There will be some more talk and code snippets covering Any type in the codecs chapters that follow.
1.4 Subtype constraints
Most ASN.1 types can correspond to an infinite set of values. To adapt to particular application's data model and needs, ASN.1 provides a mechanism for limiting the infinite set to values, that make sense in particular case.
Imposing value constraints on an ASN.1 type can also be seen as creating a subtype from its base type.
In pyasn1, constraints take shape of immutable objects capable of evaluating given value against constraint-specific requirements. Constraint object is a property of pyasn1 type. Like TagSet property, associated with every pyasn1 type, constraints can never be modified in place. The only way to modify pyasn1 type constraint is to associate new constraint object to a new pyasn1 type object.
A handful of different flavors of constraints are defined in ASN.1. We will discuss them one by one in the following chapters and also explain how to combine and apply them to types.
1.4.1 Single value constraint
This kind of constraint allows for limiting type to a finite, specified set of values.
Its pyasn1 implementation would look like:
As can be seen in the snippet above, if a value violates the constraint, an exception will be thrown. A constrainted pyasn1 type object holds a reference to a constraint object (or their combination, as will be explained later) and calls it for value verification.
Constrained pyasn1 value object can never hold a violating value.
1.4.2 Value range constraint
A pair of values, compliant to a type to be constrained, denote low and upper bounds of allowed range of values of a type.
And in pyasn1 terms:
Value range constraint usually applies numeric types.
1.4.3 Size constraint
It is sometimes convenient to set or limit the allowed size of a data item to be sent from one application to another to manage bandwidth and memory consumption issues. Size constraint specifies the lower and upper bounds of the size of a valid value.
Express the same grammar in pyasn1:
Size constraint can be applied to potentially massive values - bit or octet strings, SEQUENCE OF/SET OF values.
1.4.4 Alphabet constraint
The permitted alphabet constraint is similar to Single value constraint but constraint applies to individual characters of a value.
And in pyasn1:
Current implementation does not handle ranges of characters in constraint (FROM "A".."Z" syntax), one has to list the whole set in a range.
1.4.5 Constraint combinations
Up to this moment, we used a single constraint per ASN.1 type. The standard, however, allows for combining multiple individual constraints into intersections, unions and exclusions.
In pyasn1 data model, all of these methods of constraint combinations are implemented as constraint-like objects holding individual constraint (or combination) objects. Like terminal constraint objects, combination objects are capable to perform value verification at its set of enclosed constraints according to the logic of particular combination.
Constraints intersection verification succeeds only if a value is compliant to each constraint in a set. To begin with, the following specification will constitute a valid telephone number:
Constraint intersection object serves the logic above:
Union of constraints works by making sure that a value is compliant to any of the constraint in a set. For instance:
It's important to note, that a value must fully comply to any single constraint in a set. In the specification above, a value of all small or all capital letters is compliant, but a mix of small&capitals is not. Here's its pyasn1 analogue:
Finally, the exclusion constraint simply negates the logic of value verification at a constraint. In the following example, any integer value is allowed in a type but not zero.
In pyasn1 the above definition would read:
The depth of such a constraints tree, built with constraint combination objects at its nodes, has not explicit limit. Value verification is performed in a recursive manner till a definite solution is found.
1.5 Types relationships
In the course of data processing in an application, it is sometimes convenient to figure out the type relationships between pyasn1 type or value objects. Formally, two things influence pyasn1 types relationship: tag set and subtype constraints. One pyasn1 type is considered to be a derivative of another if their TagSet and Constraint objects are a derivation of one another.
The following example illustrates the concept (we use the same tagset but different constraints for simplicity):
As can be seen in the above code snippet, there are two methods of any pyasn1 type/value object that test types for their relationship: isSameTypeWith() and isSuperTypeOf(). The former is self-descriptive while the latter yields true if the argument appears to be a pyasn1 object which has tagset and constraints derived from those of the object being called.
In ASN.1 context, codec is a program that transforms between concrete data structures and a stream of octets, suitable for transmission over the wire. This serialized form of data is sometimes called substrate or essence.
In pyasn1 implementation, substrate takes shape of Python 3 bytes or Python 2 string objects.
One of the properties of a codec is its ability to cope with incomplete data and/or substrate what implies codec to be stateful. In other words, when decoder runs out of substrate and data item being recovered is still incomplete, stateful codec would suspend and complete data item recovery whenever the rest of substrate becomes available. Similarly, stateful encoder would encode data items in multiple steps waiting for source data to arrive. Codec restartability is especially important when application deals with large volumes of data and/or runs on low RAM. For an interesting discussion on codecs options and design choices, refer to Apache ASN.1 project .
As of this writing, codecs implemented in pyasn1 are all stateless, mostly to keep the code simple.
Encoder is used for transforming pyasn1 value objects into substrate. Only pyasn1 value objects could be serialized, attempts to process pyasn1 type objects will cause encoder failure.
The following code will create a pyasn1 Integer object and serialize it with BER encoder:
BER standard also defines a so-called indefinite length encoding form which makes large data items processing more memory efficient. It is mostly useful when encoder does not have the whole value all at once and the length of the value can not be determined at the beginning of encoding.
Constructed encoding is another feature of BER closely related to the indefinite length form. In essence, a large scalar value (such as ASN.1 character BitString type) could be chopped into smaller chunks by encoder and transmitted incrementally to limit memory consumption. Unlike indefinite length case, the length of the whole value must be known in advance when using constructed, definite length encoding form.
Since pyasn1 codecs are not restartable, pyasn1 encoder may only encode data item all at once. However, even in this case, generating indefinite length encoding may help a low-memory receiver, running a restartable decoder, to process a large data item.
The defMode encoder parameter disables definite length encoding mode, while the optional maxChunkSize parameter specifies desired substrate chunk size that influences memory requirements at the decoder's end.
To use CER or DER encoders one needs to explicitly import and call them - the APIs are all compatible.
In the process of decoding, pyasn1 value objects are created and linked to each other, based on the information containted in the substrate. Thus, the original pyasn1 value object(s) are recovered.
Commenting on the code snippet above, pyasn1 decoder accepts substrate as an argument and returns a tuple of pyasn1 value object (possibly a top-level one in case of constructed object) and unprocessed part of input substrate.
All pyasn1 decoders can handle both definite and indefinite length encoding modes automatically, explicit switching into one mode to another is not required.
Speaking of BER/CER/DER encoding, in many situations substrate may not contain all necessary information needed for complete and accurate ASN.1 values recovery. The most obvious cases include implicitly tagged ASN.1 types and constrained types.
As discussed earlier in this handbook, when an ASN.1 type is implicitly tagged, previous outermost tag is lost and never appears in substrate. If it is the base tag that gets lost, decoder is unable to pick type-specific value decoder at its table of built-in types, and therefore recover the value part, based only on the information contained in substrate. The approach taken by pyasn1 decoder is to use a prototype pyasn1 type object (or a set of them) to guide the decoding process by matching [possibly incomplete] tags recovered from substrate with those found in prototype pyasn1 type objects (also called pyasn1 specification object further in this paper).
Decoder would neither modify pyasn1 specification object nor use its current values (if it's a pyasn1 value object), but rather use it as a hint for choosing proper decoder and as a pattern for creating new objects:
Notice in the example above, that an attempt to run decoder without passing pyasn1 specification object fails because recovered tag does not belong to any of the built-in types.
Another important feature of guided decoder operation is the use of values constraints possibly present in pyasn1 specification object. To explain this, we will decode a random integer object into generic Integer and the constrained one.
Similarily to encoders, to use CER or DER decoders application has to explicitly import and call them - all APIs are compatible.
2.2.1 Decoding untagged types
It has already been mentioned, that ASN.1 has two "special case" types: CHOICE and ANY. They are different from other types in part of tagging - unless these two are additionally tagged, neither of them will have their own tag. Therefore these types become invisible in substrate and can not be recovered without passing pyasn1 specification object to decoder.
To explain the issue, we will first prepare a Choice object to deal with:
Let's now encode this Choice object and then decode its substrate with and without pyasn1 specification object:
First thing to notice in the listing above is that the substrate produced for our Choice value object is equivalent to the substrate for an OctetString object initialized to the same value. In other words, any information about the Choice component is absent in encoding.
Sure enough, that kind of substrate will decode into an OctetString object, unless original Choice type object is passed to decoder to guide the decoding process.
Similarily untagged ANY type behaves differently on decoding phase - when decoder bumps into an Any object in pyasn1 specification, it stops decoding and puts all the substrate into a new Any value object in form of an octet string. Concerned application could then re-run decoder with an additional, more exact pyasn1 specification object to recover the contents of Any object.
As it was mentioned elsewhere in this paper, Any type allows for incomplete or changing ASN.1 specification to be handled gracefully by decoder and applications.
To illustrate the working of Any type, we'll have to make the stage by encoding a pyasn1 object and then putting its substrate into an any object.
As with Choice type encoding, there is no traces of Any type in substrate. Obviously, the substrate we are dealing with, will decode into the inner [Integer] component, unless pyasn1 specification is given to guide the decoder. Continuing previous code:
Both CHOICE and ANY types are widely used in practice. Reader is welcome to take a look at ASN.1 specifications of X.509 applications for more information.
2.2.2 Ignoring unknown types
When dealing with a loosely specified ASN.1 structure, the receiving end may not be aware of some types present in the substrate. It may be convenient then to turn decoder into a recovery mode. Whilst there, decoder will not bail out when hit an unknown tag but rather treat it as an Any type.
It's also possible to configure a custom decoder, to handle unknown tags found in substrate. This can be done by means of defaultRawDecoder attribute holding a reference to type decoder object. Refer to the source for API details.
3. Feedback and getting help
Although pyasn1 software is almost a decade old and used in many production environments, it still may have bugs and non-implemented pieces. Anyone who happens to run into such defect is welcome to complain to pyasn1 mailing list or better yet fix the issue and send me the patch.
Typically, pyasn1 is used for building arbitrary protocol support into various applications. This involves manual translation of ASN.1 data structures into their pyasn1 implementations. To save time and effort, data structures for some of the popular protocols are pre-programmed and kept for further re-use in form of the pyasn1-modules package. For instance, many structures for PKI (X.509, PKCS#*, CRMF, OCSP), LDAP and SNMP are present. Applications authors are advised to import and use relevant modules from that package whenever needed protocol structures are already there. New protocol modules contributions are welcome.