def generate_sym_key(): """ This Function generate Symmetric key and nonce data """ ## Initialize NSS Database opens temporary database and the internal PKCS #112 module nss.nss_init_nodb() ## Mechanism to be used for symmetric key mechanism = nss.CKM_DES_CBC_PAD # From the Soft token that we initialized get slot to generate symmetric key slot = nss.get_best_slot(mechanism) # Generate a symmetric key on the pk11 slot, The sym_key is of type PK11SymKey sym_key = slot.key_gen(mechanism, None, slot.get_best_key_length(mechanism)) # Generate Nonce iv_length = nss.get_iv_length(mechanism) if iv_length > 0: # Generate Nonce iv_data = nss.generate_random(iv_length) # Pass this random data to NSS SecItem iv_si = nss.SecItem(iv_data) # Use the Data passed to SecItem for initialization Vector iv_param = nss.param_from_iv(mechanism, iv_si) # Random data is converted to hex pki_nonce = nss.data_to_hex(data=iv_data, separator=":") #print "generated %d bytes initialization vector: %s" % (iv_length, pki_nonce) # Create a Symmetric key Context using the Symmetric key, nonce The context should be # used for encrypt as well as decrypt encoding_ctx = nss.create_context_by_sym_key(mechanism, nss.CKA_ENCRYPT, sym_key, iv_param) decoding_ctx = nss.create_context_by_sym_key(mechanism, nss.CKA_DECRYPT, sym_key, iv_param) #return the symmetric key, nonce data, encoding context and decoding context to encrypt and # decrypt return sym_key, pki_nonce, encoding_ctx, decoding_ctx
def load_certificate(data, datatype=PEM, dbdir=None): """ Given a base64-encoded certificate, with or without the header/footer, return a request object. Returns a nss.Certificate type """ if type(data) in (tuple, list): data = data[0] if (datatype == PEM): data = strip_header(data) data = base64.b64decode(data) if not nss.nss_is_initialized(): if dbdir is None: if 'in_tree' in api.env: if api.env.in_tree: dbdir = api.env.dot_ipa + os.sep + 'alias' else: dbdir = "/etc/httpd/alias" nss.nss_init(dbdir) else: nss.nss_init_nodb() else: nss.nss_init(dbdir) return nss.Certificate(buffer(data))
def __init__(self, host, port=None, strict=None): six.moves.http_client.HTTPConnection.__init__(self, host, port, strict) logging.debug('%s init %s', self.__class__.__name__, host) if not nss.nss_is_initialized(): nss.nss_init_nodb() self.sock = None
def getKeyFromPassphrase(self, keylen): pdialog = self.xml.get_widget("passphraseDialog") phraseEntry = self.xml.get_widget("passphraseEntry") phraseEntry.set_text('') pdialog.show() button = pdialog.run() pdialog.hide() if button != gtk.RESPONSE_OK and button != 0: return None phrase = phraseEntry.get_text() try: import nss.nss as nss nss.nss_init_nodb() shasum = nss.data_to_hex(nss.sha1_digest(phrase)) except: import hashlib shasum = hashlib.sha1(phrase).hexdigest() if len(shasum) > keylen: shasum = shasum[:keylen] return shasum
def test_full(self): nss.nss_init_nodb() try: doc = PSKCDocument(os.path.join(basename, "full.xml")) assert [(t.id, t.options) for t in doc.getKeyPackages()] == [ ( u"KID1", { "ipatokenotpkey": u"GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", "ipatokennotafter": u"20060531000000Z", "ipatokennotbefore": u"20060501000000Z", "ipatokenserial": u"SerialNo-IssueNo", "ipatokentotpclockoffset": 60000, "ipatokenotpalgorithm": u"sha1", "ipatokenvendor": u"iana.dummy", "description": u"FriendlyName", "ipatokentotptimestep": 200, "ipatokenhotpcounter": 0, "ipatokenmodel": u"Model", "ipatokenotpdigits": 8, "type": u"hotp", }, ) ] finally: nss.nss_shutdown()
def setUp(self): self.conn = None self.ldapuri = 'ldap://%s' % ipautil.format_netloc(api.env.host) self.ccache = '/tmp/krb5cc_%d' % os.getuid() nss.nss_init_nodb() self.dn = DN(('krbprincipalname','ldap/%s@%s' % (api.env.host, api.env.realm)), ('cn','services'),('cn','accounts'),api.env.basedn)
def setup(self): nss.nss_init_nodb() if ipautil.file_exists("test0.csr"): self.testdir="./" elif ipautil.file_exists("ipatests/test_pkcs10/test0.csr"): self.testdir= "./ipatests/test_pkcs10/" else: raise nose.SkipTest("Unable to find test update files")
def test_invalid(self): nss.nss_init_nodb() try: PSKCDocument(os.path.join(basename, "pskc-invalid.xml")) except ValueError: # File is invalid. pass else: assert False finally: nss.nss_shutdown()
def test_figure8(self): nss.nss_init_nodb() try: PSKCDocument(os.path.join(basename, "pskc-figure8.xml")) except NotImplementedError: # X.509 is not supported. pass else: assert False finally: nss.nss_shutdown()
def test_mini(self): nss.nss_init_nodb() try: doc = PSKCDocument(os.path.join(basename, "pskc-mini.xml")) [(t.id, t.options) for t in doc.getKeyPackages()] except ValidationError: # Unsupported token type. pass else: assert False finally: nss.nss_shutdown()
def setup(self): self.conn = None self.ldapuri = "ldap://%s" % ipautil.format_netloc(api.env.host) self.ccache = paths.TMP_KRB5CC % os.getuid() nss.nss_init_nodb() self.dn = DN( ("krbprincipalname", "ldap/%s@%s" % (api.env.host, api.env.realm)), ("cn", "services"), ("cn", "accounts"), api.env.basedn, )
def main(): global options parser = argparse.ArgumentParser(description='Password Based Encryption Example') parser.add_argument('-q', '--quiet', action='store_true', help='stiffle chatty output') # === NSS Database Group === group = parser.add_argument_group('PBKDF2', 'Specify the PBKDF2 parameters') group.add_argument('--pbe-alg', help='password based encryption algorithm') group.add_argument('--cipher-alg', help='cipher algorithm') group.add_argument('--prf-alg', help='pseudo-random function algorithm') group.add_argument('-l', '--key-length', help='number of octets in derived key') group.add_argument('-s', '--salt', help='salt as a string, if none then use random data') group = parser.add_argument_group('Encryption', 'Specify the encryption parameters') group.add_argument('-p', '--password', help='PBE password') group.add_argument('-t', '--plain-text', help='string to encrypt') parser.set_defaults(pbe_alg = 'SEC_OID_PKCS5_PBKDF2', cipher_alg = 'SEC_OID_AES_256_CBC', prf_alg = 'SEC_OID_HMAC_SHA1', iterations = 100, key_length = 0, salt = None, password = '******', plain_text = 'Black holes are where God divided by zero - Steven Wright', ) options = parser.parse_args() # Initialize NSS. nss.nss_init_nodb() do_pbkdf2()
def main(): global options parser = argparse.ArgumentParser( description='Password Based Encryption Example') parser.add_argument('-q', '--quiet', action='store_true', help='stiffle chatty output') # === NSS Database Group === group = parser.add_argument_group('PBKDF2', 'Specify the PBKDF2 parameters') group.add_argument('--pbe-alg', help='password based encryption algorithm') group.add_argument('--cipher-alg', help='cipher algorithm') group.add_argument('--prf-alg', help='pseudo-random function algorithm') group.add_argument('-l', '--key-length', help='number of octets in derived key') group.add_argument('-s', '--salt', help='salt as a string, if none then use random data') group = parser.add_argument_group('Encryption', 'Specify the encryption parameters') group.add_argument('-p', '--password', help='PBE password') group.add_argument('-t', '--plain-text', help='string to encrypt') parser.set_defaults( pbe_alg='SEC_OID_PKCS5_PBKDF2', cipher_alg='SEC_OID_AES_256_CBC', prf_alg='SEC_OID_HMAC_SHA1', iterations=100, key_length=0, salt=None, password='******', plain_text='Black holes are where God divided by zero - Steven Wright', ) options = parser.parse_args() # Initialize NSS. nss.nss_init_nodb() do_pbkdf2()
def test_figure7(self): nss.nss_init_nodb() try: doc = PSKCDocument(os.path.join(basename, "pskc-figure7.xml")) assert doc.keyname == 'My Password 1' doc.setKey('qwerty') assert [(t.id, t.options) for t in doc.getKeyPackages()] == \ [(u'123456', { 'ipatokenotpkey': u'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ', 'ipatokenvendor': u'TokenVendorAcme', 'ipatokenserial': u'987654321', 'ipatokenotpdigits': 8, 'type': u'hotp'})] finally: nss.nss_shutdown()
def load_certificate_request(csr, datatype=PEM): """ Given a base64-encoded certificate request, with or without the header/footer, return a request object. """ if datatype == PEM: csr = strip_header(csr) csr = base64.b64decode(csr) # A fail-safe so we can always read a CSR. python-nss/NSS will segfault # otherwise if not nss.nss_is_initialized(): nss.nss_init_nodb() return nss.CertificateRequest(csr)
def test_figure6(self): nss.nss_init_nodb() try: doc = PSKCDocument(os.path.join(basename, "pskc-figure6.xml")) assert doc.keyname == 'Pre-shared-key' doc.setKey('12345678901234567890123456789012'.decode('hex')) assert [(t.id, t.options) for t in doc.getKeyPackages()] == \ [(u'12345678', { 'ipatokenotpkey': u'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ', 'ipatokenvendor': u'Manufacturer', 'ipatokenserial': u'987654321', 'ipatokenhotpcounter': 0, 'ipatokenotpdigits': 8, 'type': u'hotp'})] finally: nss.nss_shutdown()
def verify_sym_key(archived_key, archived_iv, algorithm, plain_text): """ This function verifies whether archived key is usable, Actually verifying this is senseless, reason any random data can be used for encryption, but still just for the heck of it. """ # Initialize NSS nss.nss_init_nodb() # Decode the base64 string to binary key = base64.decodestring(archived_data) # Currently we are assuming the mechanism to AES # Will need to add other mechanisms later, but # this is just an example. mechanism = nss.CKM_AES_CBC_PAD # Get the best pkcs11 slot slot = nss.get_best_slot(mechanism) # convert the binary to hex with separtor as : pki_key = nss.data_to_hex(data=key,separator=":") # create a nssSecItem object out of it. key_si = nss.SecItem(nss.read_hex(pki_key)) # Import the key to the slot sym_key = nss.import_sym_key(slot, mechanism, nss.PK11_OriginUnwrap, nss.CKA_ENCRYPT, key_si) # Same for the nonce data iv = base64.decodestring(archived_iv) iv_data = nss.data_to_hex(data=iv,separator=":") iv_si = nss.SecItem(nss.read_hex(iv_data)) iv_param = nss.param_from_iv(mechanism, iv_si) encoding_ctx = nss.create_context_by_sym_key(mechanism, nss.CKA_ENCRYPT,sym_key, iv_param) decoding_ctx = nss.create_context_by_sym_key(mechanism, nss.CKA_DECRYPT,sym_key, iv_param) cipher_text = encoding_ctx.cipher_op(plain_text) cipher_text += encoding_ctx.digest_final() print cipher_text decoded_text = decoding_ctx.cipher_op(cipher_text) decoded_text += decoding_ctx.digest_final() print decoded_text
def initialize_nss_database(dbdir=None): """ Initializes NSS database, if not initialized yet. Uses a proper database directory (.ipa/alias or HTTPD_ALIAS_DIR), depending on the value of api.env.in_tree. """ if not nss.nss_is_initialized(): if dbdir is None: if 'in_tree' in api.env: if api.env.in_tree: dbdir = api.env.dot_ipa + os.sep + 'alias' else: dbdir = paths.HTTPD_ALIAS_DIR nss.nss_init(dbdir) else: nss.nss_init_nodb() else: nss.nss_init(dbdir)
def test_figure7(self): nss.nss_init_nodb() try: doc = PSKCDocument(os.path.join(basename, "pskc-figure7.xml")) assert doc.keyname == "My Password 1" doc.setKey("qwerty") assert [(t.id, t.options) for t in doc.getKeyPackages()] == [ ( u"123456", { "ipatokenotpkey": u"GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", "ipatokenvendor": u"TokenVendorAcme", "ipatokenserial": u"987654321", "ipatokenotpdigits": 8, "type": u"hotp", }, ) ] finally: nss.nss_shutdown()
def test_figure6(self): nss.nss_init_nodb() try: doc = PSKCDocument(os.path.join(basename, "pskc-figure6.xml")) assert doc.keyname == "Pre-shared-key" doc.setKey("12345678901234567890123456789012".decode("hex")) assert [(t.id, t.options) for t in doc.getKeyPackages()] == [ ( u"12345678", { "ipatokenotpkey": u"GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", "ipatokenvendor": u"Manufacturer", "ipatokenserial": u"987654321", "ipatokenhotpcounter": 0, "ipatokenotpdigits": 8, "type": u"hotp", }, ) ] finally: nss.nss_shutdown()
def test_full(self): nss.nss_init_nodb() try: doc = PSKCDocument(os.path.join(basename, "full.xml")) assert [(t.id, t.options) for t in doc.getKeyPackages()] == \ [(u'KID1', { 'ipatokenotpkey': u'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ', 'ipatokennotafter': u'20060531000000Z', 'ipatokennotbefore': u'20060501000000Z', 'ipatokenserial': u'SerialNo-IssueNo', 'ipatokentotpclockoffset': 60000, 'ipatokenotpalgorithm': u'sha1', 'ipatokenvendor': u'iana.dummy', 'description': u'FriendlyName', 'ipatokentotptimestep': 200, 'ipatokenhotpcounter': 0, 'ipatokenmodel': u'Model', 'ipatokenotpdigits': 8, 'type': u'hotp', })] finally: nss.nss_shutdown()
def test_shutdown_callback(self): int_value = 43 str_value = u"foobar" count = 0 dict_value = {'count': count} def shutdown_callback(nss_data, i, s, d): self.assertEqual(isinstance(nss_data, dict), True) self.assertEqual(isinstance(i, int), True) self.assertEqual(i, int_value) self.assertEqual(isinstance(s, six.string_types), True) self.assertEqual(s, str_value) self.assertEqual(isinstance(d, dict), True) self.assertEqual(d, dict_value) d['count'] += 1 return True nss.nss_init_nodb() nss.set_shutdown_callback(shutdown_callback, int_value, str_value, dict_value) nss.nss_shutdown() self.assertEqual(dict_value['count'], count + 1) # Callback should not be invoked again after shutdown nss.nss_init_nodb() nss.nss_shutdown() self.assertEqual(dict_value['count'], count + 1) # Callback should not be invoked if cleared nss.nss_init_nodb() nss.set_shutdown_callback(shutdown_callback, int_value, str_value, dict_value) nss.set_shutdown_callback(None) nss.nss_shutdown() self.assertEqual(dict_value['count'], count + 1)
def setUp(self): nss.nss_init_nodb() self.encoding_ctx, self.decoding_ctx = setup_contexts(mechanism, key, iv)
def __init__(self, host, port=None, strict=None): httplib.HTTPConnection.__init__(self, host, port, strict) logging.debug('%s init %s', self.__class__.__name__, host) if not nss.nss_is_initialized(): nss.nss_init_nodb() self.sock = None
def setUp(self): nss.nss_init_nodb() self.csr_der = nss.SecItem(pem, ascii=True) self.csr = nss.CertificateRequest(self.csr_der)
def execute(self, argv): try: opts, _ = getopt.gnu_getopt(argv, 'i:v', ['instance=', 'verbose', 'help']) except getopt.GetoptError as e: print('ERROR: ' + str(e)) self.usage() sys.exit(1) instance_name = 'pki-tomcat' for o, a in opts: if o in ('-i', '--instance'): instance_name = a elif o in ('-v', '--verbose'): self.set_verbose(True) elif o == '--help': self.usage() sys.exit() else: print('ERROR: unknown option ' + o) self.usage() sys.exit(1) nss.nss_init_nodb() instance = pki.server.PKIInstance(instance_name) if not instance.is_valid(): print("ERROR: Invalid instance %s." % instance_name) sys.exit(1) instance.load() subsystem = instance.get_subsystem('ca') if not subsystem: print('ERROR: No CA subsystem in instance %s.' % instance_name) sys.exit(1) base_dn = subsystem.config['internaldb.basedn'] conn = subsystem.open_database() try: repo_dn = 'ou=certificateRepository,ou=ca,%s' % base_dn if self.verbose: print( 'Searching certificates records with missing issuerName in %s' % repo_dn) entries = conn.ldap.search_s( repo_dn, ldap.SCOPE_ONELEVEL, '(&(objectclass=certificaterecord)(|(!(issuername=*))(issuername=)))', None) for entry in entries: self.add_issuer_name(conn, entry) finally: conn.close() self.print_message('Upgrade complete')
def setUp(self): nss.nss_init_nodb() self.encoding_ctx, self.decoding_ctx = setup_contexts( mechanism, key, iv)
def setup(self): nss.nss_init_nodb() self.testdir = os.path.abspath(os.path.dirname(__file__)) if not ipautil.file_exists(os.path.join(self.testdir, "test0.csr")): raise nose.SkipTest("Unable to find test update files")
def setUp(self): nss.nss_init_nodb()
return csr def load_certificate_request(csr, datatype=PEM): """ Given a base64-encoded certificate request, with or without the header/footer, return a request object. """ if datatype == PEM: csr = strip_header(csr) csr = base64.b64decode(csr) # A fail-safe so we can always read a CSR. python-nss/NSS will segfault # otherwise if not nss.nss_is_initialized(): nss.nss_init_nodb() return nss.CertificateRequest(csr) if __name__ == '__main__': nss.nss_init_nodb() # Read PEM request from stdin and print out its components csrlines = sys.stdin.readlines() csr = ''.join(csrlines) print load_certificate_request(csr) print get_subject(csr) print get_subjectaltname(csr) print get_friendlyname(csr)
def main(cls, argv): nss.nss_init_nodb() try: super(OTPTokenImport, cls).main(argv) finally: nss.nss_shutdown()
class _ExtKeyUsageSyntax(univ.SequenceOf): componentType = univ.ObjectIdentifier() def encode_ext_key_usage(ext_key_usage): eku = _ExtKeyUsageSyntax() for i, oid in enumerate(ext_key_usage): eku[i] = univ.ObjectIdentifier(oid) eku = encoder.encode(eku) return _encode_extension('2.5.29.37', EKU_ANY not in ext_key_usage, eku) if __name__ == '__main__': # this can be run with: # python ipalib/x509.py < /etc/ipa/ca.crt from ipalib import api api.bootstrap() api.finalize() nss.nss_init_nodb() # Read PEM certs from stdin and print out its components certlines = sys.stdin.readlines() cert = ''.join(certlines) nsscert = load_certificate(cert) print(nsscert)
def new_generate_random(self): nss.nss_init_nodb() rndnoise = hashlib.sha256(nss.generate_random(50)).hexdigest() return rndnoise
def execute(self, argv): try: opts, _ = getopt.gnu_getopt( argv, 'i:v', ['instance=', 'verbose', 'help']) except getopt.GetoptError as e: print('ERROR: ' + str(e)) self.usage() sys.exit(1) instance_name = 'pki-tomcat' for o, a in opts: if o in ('-i', '--instance'): instance_name = a elif o in ('-v', '--verbose'): self.set_verbose(True) elif o == '--help': self.usage() sys.exit() else: print('ERROR: unknown option ' + o) self.usage() sys.exit(1) nss.nss_init_nodb() instance = pki.server.PKIInstance(instance_name) if not instance.is_valid(): print("ERROR: Invalid instance %s." % instance_name) sys.exit(1) instance.load() subsystem = instance.get_subsystem('ca') if not subsystem: print('ERROR: No CA subsystem in instance %s.' % instance_name) sys.exit(1) base_dn = subsystem.config['internaldb.basedn'] conn = subsystem.open_database() try: repo_dn = 'ou=certificateRepository,ou=ca,%s' % base_dn if self.verbose: print('Searching certificates records with missing issuerName in %s' % repo_dn) entries = conn.ldap.search_s( repo_dn, ldap.SCOPE_ONELEVEL, '(&(objectclass=certificaterecord)(|(!(issuername=*))(issuername=)))', None) for entry in entries: self.add_issuer_name(conn, entry) finally: conn.close() self.print_message('Upgrade complete')