pyndn.security.v2 package

Submodules

pyndn.security.v2.certificate_cache_v2 module

This module defines the CertificateCacheV2 class which holds other user’s verified certificates in security v2 format CertificateV2. A certificate is removed no later than its NotAfter time, or maxLifetime after it has been added to the cache.

class pyndn.security.v2.certificate_cache_v2.CertificateCacheV2(maxLifetimeMilliseconds=None)[source]

Bases: object

Create a CertificateCacheV2.

Parameters:maxLifetimeMilliseconds (float) – (optional) The maximum time that certificates can live inside the cache, in milliseconds. If omitted use getDefaultLifetime()
clear()[source]

Clear all certificates from the cache.

deleteCertificate(certificateName)[source]

Remove the certificate whose name equals the given name. If no such certificate is in the cache, do nothing.

Parameters:certificateName (Name) – The name of the certificate.
find(certificatePrefixOrInterest)[source]

Find the certificate by the given key name or interest.

Parameters:certificatePrefixOrInterest (Name or Interest) – If a Name, it is the certificate prefix for searching for the certificate. If an Interest, it is the input interest object.
Returns:The found certificate which matches the interest, or None if not found. You must not modify the returned object. If you need to modify it, then make a copy.
Note:If searching by Interest, the ChildSelector is not supported.
static getDefaultLifetime()[source]

Get the default maximum lifetime (1 hour).

Returns:The lifetime in milliseconds.
Return type:float
insert(certificate)[source]

Insert the certificate into the cache. The inserted certificate will be removed no later than its NotAfter time, or maxLifetimeMilliseconds given to the constructor.

Parameters:certificate (CertificateV2) – The certificate object, which is copied.

pyndn.security.v2.certificate_container_interface module

This module defines the CertificateContainerInterface class.

class pyndn.security.v2.certificate_container_interface.CertificateContainerInterface[source]

Bases: object

add(certificate)[source]

Add the certificate to the container.

Parameters:certificate (CertificateV2) – The certificate to add, which is copied.
remove(certificateName)[source]

Remove the certificate with the given name. If the name does not exist, do nothing.

Parameters:certificateName (Name) – The name of the certificate.

pyndn.security.v2.certificate_fetcher module

This module defines the CertificateFetcher class which is an abstract base class which provides an interface used by the validator to fetch missing certificates.

class pyndn.security.v2.certificate_fetcher.CertificateFetcher[source]

Bases: object

fetch(certificateRequest, state, continueValidation)[source]

Asynchronously fetch a certificate. setCertificateStorage must have been called first. If the requested certificate exists in the storage, then this method will immediately call continueValidation with the certificate. If certificate is not available, then the implementation-specific doFetch will be called to asynchronously fetch the certificate. The successfully-retrieved certificate will be automatically added to the unverified cache of the certificate storage. When the requested certificate is retrieved, continueValidation is called. Otherwise, the fetcher implementation calls state.failed() with the appropriate error code and diagnostic message.

Parameters:
  • certificateRequest (CertificateRequest) – The the request with the Interest for fetching the certificate.
  • state (ValidationState) – The validation state.
  • continueValidation (function object) – After fetching, this calls continueValidation(certificate, state) where certificate is the fetched certificate and state is the ValidationState.
setCertificateStorage(certificateStorage)[source]

Assign the certificate storage used to check for known certificates and to cache unverified ones.

Parameters:certificateStorage (CertificateStorage) – The certificate storage object which must be valid for the lifetime of this CertificateFetcher.

pyndn.security.v2.certificate_fetcher_from_network module

This module defines the CertificateFetcherFromNetwork class which extends CertificateFetcher to fetch missing certificates from the network.

class pyndn.security.v2.certificate_fetcher_from_network.CertificateFetcherFromNetwork(face)[source]

Bases: pyndn.security.v2.certificate_fetcher.CertificateFetcher

pyndn.security.v2.certificate_fetcher_offline module

This module defines the CertificateFetcherOffline class which extends CertificateFetcher to implement a fetcher that does not fetch certificates (always offline).

class pyndn.security.v2.certificate_fetcher_offline.CertificateFetcherOffline[source]

Bases: pyndn.security.v2.certificate_fetcher.CertificateFetcher

pyndn.security.v2.certificate_request module

This module defines the CertificateRequest class which represents a request for a certificate, associated with the number of retries left. The _interest and _nRetriesLeft fields are public so that you can modify them. _interest is the Interest for the requested Data packet or Certificate, and _nRetriesLeft is the number of remaining retries after a timeout or NACK.

class pyndn.security.v2.certificate_request.CertificateRequest(interest)[source]

Bases: object

Create a CertificateRequest with an optional Interest.

Parameters:interest (Interest) – (optional) If supplied, create a CertificateRequest with a copy of the interest and 3 retries left. Of omitted, create a CertificateRequest with a default Interest object and 0 retries left.

pyndn.security.v2.certificate_storage module

This module defines the CertificateStorage class which stores trusted anchors and has a verified certificate cache, and an unverified certificate cache.

class pyndn.security.v2.certificate_storage.CertificateStorage[source]

Bases: object

cacheUnverifiedCertificate(certificate)[source]

Cache the unverified certificate for a period of time (5 minutes).

Parameters:certificate (CertificateV2) – The certificate packet, which is copied.
cacheVerifiedCertificate(certificate)[source]

Cache the verified certificate a period of time (1 hour).

Parameters:certificate (CertificateV2) – The certificate object, which is copied.
findTrustedCertificate(interestForCertificate)[source]

Find a trusted certificate in the trust anchor container or in the verified cache.

Parameters:interestForCertificate (Interest) – The Interest for the certificate.
Returns:The found certificate, or None if not found.
Return type:CertificateV2
getTrustAnchors()[source]

Get the trust anchor container.

Returns:The trust anchor container.
Return type:TrustAnchorContainer
getUnverifiedCertificateCache()[source]

Get the unverified certificate cache.

Returns:The unverified certificate cache.
Return type:CertificateCacheV2
getVerifiedCertificateCache()[source]

Get the verified certificate cache.

Returns:The verified certificate cache.
Return type:CertificateCacheV2
isCertificateKnown(certificatePrefix)[source]

Check if the certificate with the given name prefix exists in the verified cache, the unverified cache, or in the set of trust anchors.

Parameters:certificatePrefix (Name) – The certificate name prefix.
Returns:True if the certificate is known.
Return type:bool
loadAnchor(groupId, certificateOrPath, refreshPeriod=None, isDirectory=False)[source]

There are two forms of loadAnchor: loadAnchor(groupId, certificate) - Load a static trust anchor. Static trust anchors are permanently associated with the validator and never expire. loadAnchor(groupId, path, refreshPeriod, isDirectory) - Load dynamic trust anchors. Dynamic trust anchors are associated with the validator for as long as the underlying trust anchor file (or set of files) exists.

Parameters:
  • groupId (str) – The certificate group id.
  • certificate (CertificateV2) – The certificate to load as a trust anchor, which is copied.
  • path (str) – The path to load the trust anchors.
  • refreshPeriod (float) – The refresh time in milliseconds for the anchors under path. This must be positive. The relevant trust anchors will only be updated when find is called.
  • isDirectory (bool) – (optional) If True, then path is a directory. If False or omitted, it is a single file.
resetAnchors()[source]

Remove any previously loaded static or dynamic trust anchors.

resetVerifiedCertificates()[source]

Remove any cached verified certificates.

pyndn.security.v2.certificate_v2 module

This module defines the CertificateV2 class which represents a certificate following the certificate format naming convention.

Overview of the NDN certificate format:

CertificateV2 ::= DATA-TLV TLV-LENGTH
Name (= /<NameSpace>/KEY/[KeyId]/[IssuerId]/[Version]) MetaInfo (.ContentType = KEY) Content (= X509PublicKeyContent) SignatureInfo (= CertificateV2SignatureInfo) SignatureValue
X509PublicKeyContent ::= CONTENT-TLV TLV-LENGTH
BYTE+ (= public key bits in PKCS#8 format)
CertificateV2SignatureInfo ::= SIGNATURE-INFO-TYPE TLV-LENGTH
SignatureType KeyLocator ValidityPeriod … optional critical or non-critical extension blocks …

An example of NDN certificate name:

/edu/ucla/cs/yingdi/KEY/%03%CD…%F1/%9F%D3…%B7/%FD%d2…%8E _________________/ ___________/ ___________/___________/
Certificate Namespace Key Id Issuer Id Version
(Identity)
__________________________________/
Key Name

Notes:

  • Key Id is an opaque name component to identify the instance of the public key for the certificate namespace. The value of Key ID is controlled by the namespace owner. The library includes helpers for generating key IDs using an 8-byte random number, SHA-256 digest of the public key, timestamp, and the specified numerical identifiers.
  • Issuer Id is sn opaque name component to identify the issuer of the certificate. The value is controlled by the issuer. The library includes helpers to set issuer the ID to an 8-byte random number, SHA-256 digest of the issuer’s public key, and the specified numerical identifiers.
  • Key Name is a logical name of the key used for management purposes. the
    Key Name includes the certificate namespace, keyword KEY, and KeyId components.

See https://github.com/named-data/ndn-cxx/blob/master/docs/specs/certificate-format.rst

class pyndn.security.v2.certificate_v2.CertificateV2(data=None)[source]

Bases: pyndn.data.Data

Create a CertificateV2 from the content in the Data packet (if not omitted).

Parameters:data (Data) – (optional) The data packet with the content to copy. If omitted, create a CertificateV2 with content type KEY and default or unspecified values.
exception Error(message)[source]

Bases: exceptions.Exception

Create a CertificateV2.Error to report an error for not complying with the certificate format.

Parameters:message (str) – The error message.
ISSUER_ID_OFFSET = -2
KEY_COMPONENT = <pyndn.name.Component object>
KEY_COMPONENT_OFFSET = -4
KEY_ID_OFFSET = -3
MIN_CERT_NAME_LENGTH = 4
MIN_KEY_NAME_LENGTH = 2
VERSION_OFFSET = -1
static extractIdentityFromCertName(certificateName)[source]

Extract the identity namespace from certificateName.

Parameters:certificateName (Name) – The name of the certificate.
Returns:The identity namespace as a new Name.
Return type:Name
static extractKeyNameFromCertName(certificateName)[source]

Extract key name from certificateName.

Parameters:certificateName (Name) – The name of the certificate.
Returns:The key name as a new Name.
Return type:Name
getIdentity()[source]

Get the identity name from the certificate name.

Returns:The identity name as a new Name.
Return type:Name
getIssuerId()[source]

Get the issuer ID component from the certificate name.

Returns:The issuer ID component.
Return type:Name.Component
getKeyId()[source]

Get the key ID component from the certificate name.

Returns:The key ID name component.
Return type:Name.Component
getKeyName()[source]

Get key name from the certificate name.

Returns:The key name as a new Name.
Return type:Name
getPublicKey()[source]

Get the public key DER encoding.

Returns:The DER encoding Blob.
Return type:Blob
Raises:CertificateV2.Error – If the public key is not set.
getValidityPeriod()[source]

Get the certificate validity period from the SignatureInfo.

Returns:The ValidityPeriod object.
Return type:ValidityPeriod
Raises:ValueError – If the SignatureInfo doesn’t have a ValidityPeriod.
isValid(time=None)[source]

Check if the time falls within the validity period.

Parameters:time (float) – (optional) The time to check as milliseconds since Jan 1, 1970 UTC. If omitted, use the current time.
Returns:True if the beginning of the validity period is less than or equal to time and time is less than or equal to the end of the validity period.
Return type:bool
Raises:ValueError – If the SignatureInfo doesn’t have a ValidityPeriod.
static isValidName(certificateName)[source]

Check if certificateName follows the naming convention for a certificate.

Parameters:certificateName (Name) – The name of the certificate.
Returns:True if certificateName follows the naming convention.
Return type:bool
wireDecode(buf, wireFormat=None)[source]

Override to call the base class wireDecode then check the certificate format.

Parameters:
  • input (A Blob or an array type with int elements) – The array with the bytes to decode. If input is not a Blob, then copy the bytes to save the defaultWireEncoding (otherwise take another pointer to the same Blob).
  • wireFormat (A subclass of WireFormat) – (optional) A WireFormat object used to decode this Data object. If omitted, use WireFormat.getDefaultWireFormat().

pyndn.security.v2.data_validation_state module

This modules defines the DataValidationState class which extends ValidationState to hold the validation state for a Data packet.

class pyndn.security.v2.data_validation_state.DataValidationState(data, successCallback, failureCallback)[source]

Bases: pyndn.security.v2.validation_state.ValidationState

Create a DataValidationState for the Data packet. The caller must ensure that the state instance is valid until the validation finishes (i.e., until validateCertificateChain() and validateOriginalPacket() have been called).

Parameters:
  • data (Data) – The Date packet being validated, which is copied.
  • successCallback (function object) – This calls successCallback(data) to report a successful Data validation.
  • failureCallback (function object) – This calls failureCallback(data, error) to report a failed Data validation, where error is a ValidationError.
fail(error)[source]

Call the failure callback.

Parameters:error (ValidationError) –
getOriginalData()[source]

Get the original Data packet being validated which was given to the constructor.

Returns:The original Data packet.
Return type:Data

pyndn.security.v2.dynamic_trust_anchor_group module

This module defines the DynamicTrustAnchorGroup class which extends TrustAnchorGroup to implement a dynamic trust anchor group.

class pyndn.security.v2.dynamic_trust_anchor_group.DynamicTrustAnchorGroup(certificateContainer, id, path, refreshPeriod, isDirectory)[source]

Bases: pyndn.security.v2.trust_anchor_group.TrustAnchorGroup

Create a DynamicTrustAnchorGroup to use an existing container.

Parameters:
  • certificateContainer (CertificateContainer) – The existing certificate container which implements the CertificateContainer interface.
  • id (str) – The group ID.
  • path (str) – The file path for trust anchor(s), which could be a directory or a file. If it is a directory, all the certificates in the directory will be loaded.
  • refreshPeriod (float) – The refresh time in milliseconds for the anchors under path. This must be positive.
  • isDirectory (bool) – If True, then path is a directory. If False, it is a single file.
Raises:

ValueError If refreshPeriod is not positive.

refresh()[source]

Request a certificate refresh.

pyndn.security.v2.interest_validation_state module

This modules defines the DataValidationState class which extends ValidationState to hold the validation state for a Data packet.

class pyndn.security.v2.interest_validation_state.InterestValidationState(interest, successCallback, failureCallback)[source]

Bases: pyndn.security.v2.validation_state.ValidationState

Create a InterestValidationState for the Interest packet. The caller must ensure that the state instance is valid until the validation finishes (i.e., until validateCertificateChain() and validateOriginalPacket() have been called).

Parameters:
  • interest (Interest) – The Date packet being validated, which is copied.
  • successCallback (function object) – This calls successCallback(interest) to report a successful Interest validation.
  • failureCallback (function object) – This calls failureCallback(interest, error) to report a failed Interest validation, where error is a ValidationError.
addSuccessCallback(successCallback)[source]
Parameters:successCallback (function object) – This calls successCallback(interest).
fail(error)[source]

Call the failure callback.

Parameters:error (ValidationError) –
getOriginalInterest()[source]

Get the original Interest packet being validated which was given to the constructor.

Returns:The original Interest packet.
Return type:Interest

pyndn.security.v2.static_trust_anchor_group module

This module defines the StaticTrustAnchorGroup class which extends TrustAnchorGroup to implement a static trust anchor group.

class pyndn.security.v2.static_trust_anchor_group.StaticTrustAnchorGroup(certificateContainer, id)[source]

Bases: pyndn.security.v2.trust_anchor_group.TrustAnchorGroup

Create a StaticTrustAnchorGroup to use an existing container.

Parameters:
  • certificateContainer (CertificateContainer) – The existing certificate container which implements the CertificateContainer interface.
  • id (str) – The group ID.
add(certificate)[source]

Load the static anchor certificate. If a certificate with the name is already added, do nothing.

Parameters:certificate (CertificateV2) – The certificate to add, which is copied.
remove(certificateName)[source]

Remove the static anchor with the certificate name.

Parameters:certificateName (Name) – The certificate name.

pyndn.security.v2.trust_anchor_container module

This module defines the TrustAnchorContainer class which represents a container for trust anchors.

There are two kinds of anchors: static anchors that are permanent for the lifetime of the container, and dynamic anchors that are periodically updated.

Trust anchors are organized in groups. Each group has a unique group id. The same anchor certificate (same name without considering the implicit digest) can be inserted into multiple groups, but no more than once into each.

Dynamic groups are created using the appropriate TrustAnchorContainer.insert method. Once created, the dynamic anchor group cannot be updated.

The returned pointer to Certificate from find methods is only guaranteed to be valid until the next invocation of find and may be invalidated afterwards.

class pyndn.security.v2.trust_anchor_container.TrustAnchorContainer[source]

Bases: object

Create an empty TrustAnchorContainer.

exception Error(message)[source]

Bases: exceptions.Exception

Create a TrustAnchorContainer.Error.

Parameters:message (str) – The error message.
clear()[source]

Remove all static and dynamic anchors.

find(keyNameOrInterest)[source]

There are two forms of find: find(keyName) - Search for a certificate across all groups (longest prefix match). find(interest) - Find a certificate for the given interest. Note: Interests with implicit digest are not supported.

Parameters:
  • keyName (Name) – The key name prefix for searching for the certificate.
  • interest (Interest}) – The input interest packet.
Returns:

The found certificate, or None if not found.

Return type:

CertificateV2

getGroup(groupId)[source]

Get the trust anchor group for the groupId.

Parameters:groupId (str) – The group ID.
Returns:The trust anchor group.
Return type:TrustAnchorGroup
Raises:TrustAnchorContainer.Error if the groupId does not exist.
insert(groupId, certificateOrPath, refreshPeriod=None, isDirectory=False)[source]

There are two forms of insert: insert(groupId, certificate) - Insert a static trust anchor. If the certificate (having the same name without considering implicit digest) already exists in the group with groupId, then do nothing. insert(groupId, path, refreshPeriod, isDirectory) - Insert dynamic trust anchors from the path.

Parameters:
  • groupId (str) – The certificate group id.
  • certificate (CertificateV2) – The certificate to insert, which is copied.
  • path (str) – The path to load the trust anchors.
  • refreshPeriod (float) – The refresh time in milliseconds for the anchors under path. This must be positive. The relevant trust anchors will only be updated when find is called.
  • isDirectory (bool) – (optional) If True, then path is a directory. If False or omitted, it is a single file.
Raises:

TrustAnchorContainer.Error If inserting a static trust anchor and groupId is for a dynamic anchor group , or if inserting a dynamic trust anchor and a group with groupId already exists.

Raises:

ValueError If refreshPeriod is not positive.

size()[source]

Get the number of trust anchors across all groups.

Returns:The number of trust anchors.
Return type:int

pyndn.security.v2.trust_anchor_group module

This module defines the TrustAnchorGroup class which represents a group of trust anchors which implement the CertificateContainer interface.

class pyndn.security.v2.trust_anchor_group.TrustAnchorGroup(certificateContainer, id)[source]

Bases: object

Create a TrustAnchorGroup to use an existing container.

Parameters:
  • certificateContainer (CertificateContainer) – The existing certificate container which implements the CertificateContainer interface.
  • id (str) – The group ID.
getId()[source]

Get the group id given to the constructor.

Returns:The group id.
Return type:str
static readCertificate(filePath)[source]

Read a base-64-encoded certificate from a file.

Parameters:filePath (str) – The certificate file path.
Returns:The decoded certificate, or None if there is an error.
Return type:CertificateV2
refresh()[source]

Request a certificate refresh. The base method does nothing.

size()[source]

Get the number of certificates in the group.

Returns:The number of certificates.
Return type:int

pyndn.security.v2.validation_error module

This module defines the ValidationError class which holds an error code and an optional detailed error message.

class pyndn.security.v2.validation_error.ValidationError(code, info='')[source]

Bases: object

Create a new ValidationError for the given code.

Parameters:
  • code (int) – The code which is one of the standard error codes such as ValidationError.INVALID_SIGNATURE, or a custom code if greater than or equal to ValidationError.USER_MIN .
  • info (str) – {optinal) The error message. If omitted, use an empty string.
CANNOT_RETRIEVE_CERTIFICATE = 3
EXCEEDED_DEPTH_LIMIT = 7
EXPIRED_CERTIFICATE = 4
IMPLEMENTATION_ERROR = 255
INVALID_KEY_LOCATOR = 8
INVALID_SIGNATURE = 1
LOOP_DETECTED = 5
MALFORMED_CERTIFICATE = 6
NO_ERROR = 0
NO_SIGNATURE = 2
POLICY_ERROR = 9
USER_MIN = 256
getCode()[source]

Get the error code given to the constructor.

Returns:The error code which is one of the standard error codes such as ValidationError.INVALID_SIGNATURE, or a custom code if greater than or equal to ValidationError.USER_MIN.
Return type:int
getInfo()[source]

Get the error message given to the constructor.

Returns:The error message, or “” if none.
Return type:str
toString()[source]

Get a string representation of this ValidationError.

Returns:The string representation.
Return type:str

pyndn.security.v2.validation_policy module

This module defines the ValidationPolicy class which is an abstract base class that implements a validation policy for Data and Interest packets.

class pyndn.security.v2.validation_policy.ValidationPolicy[source]

Bases: object

checkCertificatePolicy(certificate, state, continueValidation)[source]

Check the certificate against the policy. This base class implementation just calls checkPolicy(certificate, …). Your derived class may override. Depending on implementation of the policy, this check can be done synchronously or asynchronously. See the checkPolicy(Data) documentation for the semantics.

Parameters:
  • certificate (CertificateV2) – The certificate to check.
  • state (ValidationState) – The ValidationState of this validation.
  • continueValidation (function object) – The policy should call continueValidation() as described above.
checkPolicy(dataOrInterest, state, continueValidation)[source]

Check the Data or Interest packet against the policy. Your derived class must implement this. Depending on the implementation of the policy, this check can be done synchronously or asynchronously. The semantics of checkPolicy are as follows: If the packet violates the policy, then the policy should call state.fail() with an appropriate error code and error description. If the packet conforms to the policy and no further key retrievals are necessary, then the policy should call continueValidation(None, state). If the packet conforms to the policy and a key needs to be fetched, then the policy should call continueValidation({appropriate-key-request-instance}, state).

Parameters:
  • dataOrInterest (Data or Interest) – The Data or Interest packet to check.
  • state (ValidationState) – The ValidationState of this validation.
  • continueValidation (function object) – The policy should call continueValidation() as described above.
getInnerPolicy()[source]

Get the inner policy. If the inner policy was not set, the behavior is undefined.

Returns:The inner policy.
Return type:ValidationPolicy
static getKeyLocatorName(dataOrInterest, state)[source]

Extract the KeyLocator Name from a Data or signed Interest packet. The SignatureInfo in the packet must contain a KeyLocator of type KEYNAME. Otherwise, state.fail is invoked with INVALID_KEY_LOCATOR.

Parameters:
  • dataOrInterest (Data or Interest) – The Data or Interest packet with the KeyLocator.
  • state (ValidationState) – On error, this calls state.fail and returns an empty Name.
Returns:

The KeyLocator name, or an empty Name for failure.

Return type:

Name

hasInnerPolicy()[source]

Check if the inner policy is set.

Returns:True if the inner policy is set.
Return type:bool
setInnerPolicy(innerPolicy)[source]

Set the inner policy. Multiple assignments of the inner policy will create a “chain” of linked policies. The inner policy from the latest invocation of setInnerPolicy will be at the bottom of the policy list. For example, the sequence self.setInnerPolicy(policy1) and self.setInnerPolicy(policy2), will result in self._innerPolicy == policy1, self._innerPolicy_._innerPolicy == policy2’, and `self._innerPolicy._innerPolicy._innerPolicy == None.

Parameters:innerPolicy (ValidationPolicy) –
Raises:ValueError if the innerPolicy is None.
setValidator(validator)[source]

Set the validator to which this policy is associated. This replaces any previous validator.

Parameters:validator (Validator) – The validator.

pyndn.security.v2.validation_policy_accept_all module

This module defines the ValidationPolicyAcceptAll class which extends ValidationPolicy to implement a validator policy that accepts any signature of a Data or Interest packet.

class pyndn.security.v2.validation_policy_accept_all.ValidationPolicyAcceptAll[source]

Bases: pyndn.security.v2.validation_policy.ValidationPolicy

checkPolicy(dataOrInterest, state, continueValidation)[source]
Parameters:

pyndn.security.v2.validation_policy_command_interest module

This module defines the ValidationPolicyCommandInterest class which extends ValidationPolicy as a policy for stop-and-wait command Interests. See: https://redmine.named-data.net/projects/ndn-cxx/wiki/CommandInterest

This policy checks the timestamp field of a stop-and-wait command Interest. Signed Interest validation and Data validation requests are delegated to an inner policy.

class pyndn.security.v2.validation_policy_command_interest.ValidationPolicyCommandInterest(innerPolicy, options=None)[source]

Bases: pyndn.security.v2.validation_policy.ValidationPolicy

Create a ValidationPolicyCommandInterest.

Parameters:
  • innerPolicy (ValidationPolicy) – a ValidationPolicy for signed Interest signature validation and Data validation. This must not be None.
  • options (ValidationPolicyCommandInterest.Options) – (optional) The stop-and-wait command Interest validation options. If omitted, use a default Options().
Raises:

ValueError if innerPolicy is None.

class LastTimestampRecord(keyName, timestamp, lastRefreshed)[source]

Bases: object

Parameters:
  • keyName (Name) –
  • timestamp (float) –
  • lastRefreshed (float) –
class Options(gracePeriodOrOptions=None, maxRecords=None, recordLifetime=None)[source]

Bases: object

Create a ValidationPolicyCommandInterest.Options with the values.

Parameters:
  • gracePeriodOrOptions (float or ValidationPolicyCommandInterest.Options) – (optional) The tolerance of the initial timestamp in milliseconds. (However, if this is another ValidationPolicyCommandInterest.Options, then copy values from it.) If omitted, use a grace period of 2 minutes. A stop-and-wait command Interest is considered “initial” if the validator has not recorded the last timestamp from the same public key, or when such knowledge has been erased. For an initial command Interest, its timestamp is compared to the current system clock, and the command Interest is rejected if the absolute difference is greater than the grace interval. The grace period should be positive. Setting this option to 0 or negative causes the validator to require exactly the same timestamp as the system clock, which most likely rejects all command Interests.
  • maxRecords (int) – (optional) The maximum number of distinct public keys of which to record the last timestamp. If omitted, use 1000. The validator records the last timestamps for every public key. For a subsequent command Interest using the same public key, its timestamp is compared to the last timestamp from that public key, and the command Interest is rejected if its timestamp is less than or equal to the recorded timestamp. This option limits the number of distinct public keys being tracked. If the limit is exceeded, then the oldest record is deleted. Setting max records to -1 allows tracking unlimited public keys. Setting max records to 0 disables using last timestamp records and causes every command Interest to be processed as initial.
  • recordLifetime (float) – (optional) The maximum lifetime of a last timestamp record in milliseconds. If omitted, use 1 hour. A last timestamp record expires and can be deleted if it has not been refreshed within the record lifetime. Setting the record lifetime to 0 or negative makes last timestamp records expire immediately and causes every command Interest to be processed as initial.
checkPolicy(dataOrInterest, state, continueValidation)[source]
Parameters:

pyndn.security.v2.validation_policy_config module

This module defines the ValidationPolicyConfig class which implements a validator which can be set up via a configuration file. For command Interest validation, this policy must be combined with ValidationPolicyCommandInterest in order to guard against replay attacks. Note: This policy does not support inner policies (a sole policy or a terminal inner policy). See https://named-data.net/doc/ndn-cxx/current/tutorials/security-validator-config.html

class pyndn.security.v2.validation_policy_config.ValidationPolicyConfig[source]

Bases: pyndn.security.v2.validation_policy.ValidationPolicy

checkPolicy(dataOrInterest, state, continueValidation)[source]
Parameters:
load(filePathOrInputOrConfigSection, inputName=None)[source]

There are three forms of load: load(filePath) - Load the configuration from the given config file. load(input, inputName) - Load the configuration from the given input string. load(configSection, inputName) - Load the configuration from the given configSection. Each of these forms of load replaces any existing configuration.

Parameters:
  • filePath (str) – The The path of the config file.
  • input (str) – The contents of the configuration rules, with lines separated by NL or CR/NL.
  • configSection (BoostInfoTree) – The configuration section loaded from the config file. It should have one “validator” section.
  • inputName (str) – Used for log messages, etc.

pyndn.security.v2.validation_policy_from_pib module

This module defines the ValidationPolicyFromPib class which extends ValidationPolicy to implement a validator policy that validates a packet using the default certificate of the key in the PIB that is named by the packet’s KeyLocator.

class pyndn.security.v2.validation_policy_from_pib.ValidationPolicyFromPib(pib)[source]

Bases: pyndn.security.v2.validation_policy.ValidationPolicy

Create a ValidationPolicyFromPib to use the given PIB.

Parameters:pib (Pib) – The PIB with certificates.
checkPolicy(dataOrInterest, state, continueValidation)[source]
Parameters:

pyndn.security.v2.validation_policy_simple_hierarchy module

This module defines the ValidationPolicySimpleHierarchy class which extends ValidationPolicy to implement a Validation policy for a simple hierarchical trust model.

class pyndn.security.v2.validation_policy_simple_hierarchy.ValidationPolicySimpleHierarchy[source]

Bases: pyndn.security.v2.validation_policy.ValidationPolicy

checkPolicy(dataOrInterest, state, continueValidation)[source]
Parameters:

pyndn.security.v2.validation_state module

This module defines the ValidationState class which is an abstract base class for DataValidationState and InterestValidationState.

One instance of the validation state is kept for the validation of the whole certificate chain.

The state collects the certificate chain that adheres to the selected validation policy to validate data or interest packets. Certificate, data, and interest packet signatures are verified only after the validator determines that the chain terminates with a trusted certificate (a trusted anchor or a previously validated certificate). This model allows filtering out invalid certificate chains without incurring (costly) cryptographic signature verification overhead and mitigates some forms of denial-of-service attacks.

A validation policy and/or key fetcher may add custom information associated with the validation state using tags.

class pyndn.security.v2.validation_state.ValidationState[source]

Bases: object

addCertificate(certificate)[source]

Add the certificate to the top of the certificate chain. If the certificate chain is empty, then the certificate should be the signer of the original packet. If the certificate chain is not empty, then the certificate should be the signer of the front of the certificate chain. Note: This function does not verify the signature bits.

Parameters:certificate (CertificateV2) – The certificate to add, which is copied.
fail(error)[source]

Call the failure callback.

Parameters:error (ValidationError) –
getDepth()[source]

Get the depth of the certificate chain.

Returns:The depth of the certificate chain.
Return type:int
hasOutcome()[source]

Check if validation failed or success has been called.

Returns:True if validation failed or success has been called.
Return type:bool
hasSeenCertificateName(certificateName)[source]

Check if certificateName has been previously seen, and record the supplied name.

Parameters:certificateName (Name) – The certificate name, which is copied.
Returns:True if certificateName has been previously seen.
Return type:bool
isOutcomeFailed()[source]

Check if validation failed has been called.

Returns:True if validation failed has been called, False if no validation callbacks have been called or validation success was called.
Return type:bool
isOutcomeSuccess()[source]

Check if validation success has been called.

Returns:True if validation success has been called, False if no validation callbacks have been called or validation failed was called.
Return type:bool
setOutcome(outcome)[source]

Set the outcome to the given value, and set _hasOutcome True.

Parameters:outcome (bool) – The outcome.
Raises:RuntimeError If this ValidationState already has an outcome.

pyndn.security.v2.validator module

This module defines the Validator class which provides an interface for validating data and interest packets.

Every time a validation process is initiated, it creates a ValidationState that exists until the validation finishes with either success or failure. This state serves several purposes: to record the Interest or Data packet being validated, to record the failure callback, to record certificates in the certification chain for the Interest or Data packet being validated, to record the names of the requested certificates in order to detect loops in the certificate chain, and to keep track of the validation chain size (also known as the validation “depth”).

During validation, the policy and/or key fetcher can augment the validation state with policy- and fetcher-specific information using tags.

A Validator has a trust anchor cache to save static and dynamic trust anchors, a verified certificate cache for saving certificates that are already verified, and an unverified certificate cache for saving pre-fetched but not yet verified certificates.

class pyndn.security.v2.validator.Validator(policy, certificateFetcher=None)[source]

Bases: pyndn.security.v2.certificate_storage.CertificateStorage

Create a Validator with the policy and fetcher.

Parameters:
  • policy (ValidationPolicy) – The validation policy to be associated with this validator.
  • certificateFetcher (CertificateFetcher) – (optional) The certificate fetcher implementation. If omitted, use a CertificateFetcherOffline (assuming that the validation policy doesn’t need to fetch certificates).
getFetcher()[source]

Get the CertificateFetcher given to (or created in) the constructor.

Returns:The CertificateFetcher.
Return type:CertificateFetcher
getMaxDepth()[source]

Get the maximum depth of the certificate chain.

Returns:The maximum depth.
Return type:int
getPolicy()[source]

Get the ValidationPolicy given to the constructor.

Returns:The ValidationPolicy.
Return type:ValidationPolicy
setMaxDepth(maxDepth)[source]

Set the maximum depth of the certificate chain.

Parameters:maxDepth (int) – The maximum depth.
validate(dataOrInterest, successCallback, failureCallback)[source]

Asynchronously validate the Data or Interest packet.

Parameters:
  • dataOrInterest (Data or Interest) – The Data or Interest packet to validate, which is copied.
  • successCallback (function object) – On validation success, this calls successCallback(dataOrInterest).
  • failureCallback (function object) – On validation failure, this calls failureCallback(dataOrInterest, error) where error is a ValidationError.

Module contents