def License_verify_invalid(): """Tests that License.verify raises exception for invalid signatures""" with assert_exception(License.InvalidSignatureException): License.issue(certificate(), key(), license_data = LicenseData( '2014-01-01T00:00:00', '2014-01-01T00:00:01')).verify(other_certificate())
def License_verify_valid(): """Tests that License.verify does not raise exception for valid certificate""" License.issue(certificate(), key(), license_data = LicenseData( '2014-01-01T00:00:00', '2014-01-01T00:00:01')).verify(certificate())
def License_verify_invalid(): """Tests that License.verify raises exception for invalid signatures""" with assert_exception(License.InvalidSignatureException): License.issue(certificate(), key(), license_data=LicenseData('2014-01-01T00:00:00', '2014-01-01T00:00:01')).verify( other_certificate())
def License_verify_valid(): """Tests that License.verify does not raise exception for valid certificate""" License.issue(certificate(), key(), license_data=LicenseData('2014-01-01T00:00:00', '2014-01-01T00:00:01')).verify( certificate())
def test_verify_valid(self): """Tests that License.verify does not raise exception for valid certificate""" License.issue(CERTIFICATE, key(), license_data=LicenseData( '2014-01-01T00:00:00', '2014-01-01T00:00:01')).verify(CERTIFICATE)
def test_verify_invalid(self): """Tests that License.verify raises exception for invalid signatures""" with self.assertRaises(License.InvalidSignatureException): License.issue(CERTIFICATE, key(), license_data=LicenseData( '2014-01-01T00:00:00', '2014-01-01T00:00:01')).verify(OTHER_CERTIFICATE)
def License_store(): """Tests that a license can be loaded from the stored data""" f = io.BytesIO() License.issue(certificate(), key(), license_data = LicenseData( '2014-01-01T00:00:00', '2014-01-01T00:00:01')).store(f, b'valid password') License.load(io.BytesIO(f.getvalue()), b'valid password')
def test_verify_invalid(self): """Tests that License.verify raises exception for invalid signatures""" with self.assertRaises(License.InvalidSignatureException): License.issue( CERTIFICATE, key(), license_data=LicenseData( '2014-01-01T00:00:00', '2014-01-01T00:00:01')).verify(OTHER_CERTIFICATE)
def test_verify_valid(self): """Tests that License.verify does not raise exception for valid certificate""" License.issue( CERTIFICATE, key(), license_data=LicenseData( '2014-01-01T00:00:00', '2014-01-01T00:00:01')).verify(CERTIFICATE)
def License_store(): """Tests that a license can be loaded from the stored data""" f = io.BytesIO() License.issue(certificate(), key(), license_data=LicenseData('2014-01-01T00:00:00', '2014-01-01T00:00:01')).store( f, b'valid password') License.load(io.BytesIO(f.getvalue()), b'valid password')
def test_store(self): """Tests that a license can be loaded from the stored data""" f = io.BytesIO() License.issue(CERTIFICATE, key(), license_data=LicenseData('2014-01-01T00:00:00', '2014-01-01T00:00:01')).store( f, b'valid password') License.load(io.BytesIO(f.getvalue()), b'valid password')
def test_store(self): """Tests that a license can be loaded from the stored data""" f = io.BytesIO() License.issue( CERTIFICATE, key(), license_data=LicenseData( '2014-01-01T00:00:00', '2014-01-01T00:00:01')).store(f, b'valid password') License.load(io.BytesIO(f.getvalue()), b'valid password')
def test_issue_invalid_license_data(self): """Tests that License.issue with invalid license_data fails""" with self.assertRaises(ValueError): License.issue( CERTIFICATE, key(), license_data=None) with self.assertRaises(ValueError): License.issue( CERTIFICATE, key(), license_data=LicenseData( '2014-01-01T00:00:00', '2014-01-01T00:00:01'), not_before='2014-01-01T00:00:00') with self.assertRaises(ValueError): License.issue( CERTIFICATE, key(), license_data=LicenseData( '2014-01-01T00:00:00', '2014-01-01T00:00:01'), issuer='CN=must not be passed') with self.assertRaises(ValueError): License.issue( CERTIFICATE, key(), not_before='2014-01-01T00:00:00')
def test_signature_algorithm_valid_non_default_signature_algo(self): """Tests License() for valid, non-default signature_algorithm""" License(to_document( serialize(LicenseData('2014-01-01T00:00:00', '2014-01-01T00:00:01'))), '<signature>', signature_algorithm='HELLOwithWORLD')
def IssueLicense(self, key_folder, licence_input, password='******', licence_file='license.key', validate_days=365): with open(os.path.join(key_folder, 'certificate.pem'), 'rb') as f: certificate = f.read() # Load the private key with open(os.path.join(key_folder, 'key.pem'), 'rb') as f: key = serialization.load_pem_private_key( f.read(), password=str.encode(password, encoding='UTF-8'), backend=backends.default_backend()) # Issue the license license = License.issue( certificate, key, license_data=LicenseData( datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S'), (datetime.datetime.now() + datetime.timedelta( days=validate_days)).strftime('%Y-%m-%dT%H:%M:%S'))) # Store the license with open(licence_file, 'wb') as f: license.store(f, str.encode(licence_input, encoding='UTF-8'))
def test_issue_valid(self): """Tests that the signature is correctly constructed""" # Generated with command below: ''' python -c 'import tests.license_test; \ open("key.pem", "w").write(tests.license_test.KEY)' python -c 'import sys, truepy; sys.stdout.write( \ truepy._bean.to_document( \ truepy._bean.serialize( \ truepy.LicenseData( \ not_before = "2014-01-01T00:00:00", \ not_after = "2014-01-01T00:00:01"))))' \ | openssl sha -sign key.pem -sha1 \ | base64 ''' expected = ( 'BwaJUYJTcY22EiC5x/qZQVMKGeIxAwTiIejRjrch2Q/uVoUrB1ptKRn1ffGgYs5zc' 'agsj+7YTi8bB8nim+W+ANy93WttNrgz5hl2k75D4hGmR3EGV+f45l91RYMdTHukuK' 'ZkA+agc/At5ByHC8Qaw4+4Jdz2e0XJMJaR3aEAYIJ/5NDVKSHD2OjpGDLEc70Qwdo' 'rUU10B4X2URasRKHuRZTv9jVz2t4Mgk4wrJHiT/gw6sHbR1U7u7PbbnbQ8Xx/c37U' 'L54jy9ZqM+j7yEhEXqPGW5rXvj0IQmYrODLdyVzNMUa/ReC66oERy2JZA0aaFyY8l' 'Fr5V1yC1xT4r6yMnw==') self.assertEqual( expected, License.issue( CERTIFICATE, key(), license_data=LicenseData('2014-01-01T00:00:00', '2014-01-01T00:00:01')).signature)
def test_issue_valid(self): """Tests that the signature is correctly constructed""" # Generated with command below: ''' python -c 'import tests.license_test; \ open("key.pem", "w").write(tests.license_test.KEY)' python -c 'import sys, truepy; sys.stdout.write( \ truepy._bean.to_document( \ truepy._bean.serialize( \ truepy.LicenseData( \ not_before = "2014-01-01T00:00:00", \ not_after = "2014-01-01T00:00:01"))))' \ | openssl sha -sign key.pem -sha1 \ | base64 ''' expected = ( 'BwaJUYJTcY22EiC5x/qZQVMKGeIxAwTiIejRjrch2Q/uVoUrB1ptKRn1ffGgYs5zc' 'agsj+7YTi8bB8nim+W+ANy93WttNrgz5hl2k75D4hGmR3EGV+f45l91RYMdTHukuK' 'ZkA+agc/At5ByHC8Qaw4+4Jdz2e0XJMJaR3aEAYIJ/5NDVKSHD2OjpGDLEc70Qwdo' 'rUU10B4X2URasRKHuRZTv9jVz2t4Mgk4wrJHiT/gw6sHbR1U7u7PbbnbQ8Xx/c37U' 'L54jy9ZqM+j7yEhEXqPGW5rXvj0IQmYrODLdyVzNMUa/ReC66oERy2JZA0aaFyY8l' 'Fr5V1yC1xT4r6yMnw==') self.assertEqual( expected, License.issue( CERTIFICATE, key(), license_data=LicenseData( '2014-01-01T00:00:00', '2014-01-01T00:00:01')).signature)
def License_signature_algorithm0(): """Tests License() for invalid signature_algorithm""" with assert_exception(ValueError): License(to_document( serialize(LicenseData('2014-01-01T00:00:00', '2014-01-01T00:00:01'))), '<signature>', signature_algorithm='invalid')
def License_signature_encoding0(): """Tests License() for invalid signature_encoding""" with assert_exception(ValueError): License(to_document( serialize(LicenseData('2014-01-01T00:00:00', '2014-01-01T00:00:01'))), '<signature>', signature_encoding='UTF-8/Base64')
def test_encoded_valid(self): """Tests that License() with valid encoded data has correct encoded value""" License( to_document( serialize( LicenseData('2014-01-01T00:00:00', '2014-01-01T00:00:01'))), '<signature>')
def test_signature_algorithm_invalid(self): """Tests License() for invalid signature_algorithm""" with self.assertRaises(ValueError): License(to_document( serialize( LicenseData('2014-01-01T00:00:00', '2014-01-01T00:00:01'))), '<signature>', signature_algorithm='invalid')
def test_signature_encoding_invalid(self): """Tests License() for invalid signature_encoding""" with self.assertRaises(ValueError): License(to_document( serialize( LicenseData('2014-01-01T00:00:00', '2014-01-01T00:00:01'))), '<signature>', signature_encoding='UTF-8/Base64')
def lget_license(sock): ''' get license data from the server which is connecting sock ''' lengthb = lrecv(sock, 1024) length = unpack('i', lengthb)[0] lsend(sock, b'ack') lic = lrecv(sock, length) # create local license file and check it temp = tempfile.TemporaryFile() temp.write(lic) temp.seek(0) return License.load(temp, PSK)
def VerifyLicense(self, certificate_path, licence_input, licence_file='license.key'): with open(certificate_path, 'rb') as f: certificate = f.read() # Load the license try: with open(licence_file, 'rb') as f: license = License.load( f, str.encode(licence_input, encoding='UTF-8')) license.verify(certificate) return True except truepy.License.InvalidPasswordException: return False
def License_issue_invalid_license_data(): """Tests that License.issue with invalid license_data fails""" with assert_exception(ValueError): License.issue(certificate(), key(), license_data=None) with assert_exception(ValueError): License.issue(certificate(), key(), license_data=LicenseData('2014-01-01T00:00:00', '2014-01-01T00:00:01'), not_before='2014-01-01T00:00:00') with assert_exception(ValueError): License.issue(certificate(), key(), license_data=LicenseData('2014-01-01T00:00:00', '2014-01-01T00:00:01'), issuer='CN=must not be passed') with assert_exception(ValueError): License.issue(certificate(), key(), not_before='2014-01-01T00:00:00')
def test_issue_invalid_license_data(self): """Tests that License.issue with invalid license_data fails""" with self.assertRaises(ValueError): License.issue(CERTIFICATE, key(), license_data=None) with self.assertRaises(ValueError): License.issue(CERTIFICATE, key(), license_data=LicenseData('2014-01-01T00:00:00', '2014-01-01T00:00:01'), not_before='2014-01-01T00:00:00') with self.assertRaises(ValueError): License.issue(CERTIFICATE, key(), license_data=LicenseData('2014-01-01T00:00:00', '2014-01-01T00:00:01'), issuer='CN=must not be passed') with self.assertRaises(ValueError): License.issue(CERTIFICATE, key(), not_before='2014-01-01T00:00:00')
def License_issue_invalid_license_data(): """Tests that License.issue with invalid license_data fails""" with assert_exception(ValueError): License.issue(certificate(), key(), license_data = None) with assert_exception(ValueError): License.issue(certificate(), key(), license_data = LicenseData( '2014-01-01T00:00:00', '2014-01-01T00:00:01'), not_before = '2014-01-01T00:00:00') with assert_exception(ValueError): License.issue(certificate(), key(), license_data = LicenseData( '2014-01-01T00:00:00', '2014-01-01T00:00:01'), issuer = 'CN=must not be passed') with assert_exception(ValueError): License.issue(certificate(), key(), not_before = '2014-01-01T00:00:00')
def _keyIsValid(self) -> bool: try: path = os.path.join( Resources.getPath( self._application.ResourceTypes.Certificates), "license_cert.pem") with open(path, 'rb') as f: certificate = f.read() key = BytesIO(bytes.fromhex(self.licenseKey)) lic = License.load(key, b'StereotechSTESlicerProFeatures') lic.verify(certificate) return True except License.InvalidSignatureException: Logger.log("w", "License key is wrong!") return False except FileNotFoundError: Logger.log("w", "Certificate not found!") return False except Exception as e: Logger.log("w", "License error: %s", str(e)) return False
def load_license(self, license_file): ''' load the license file and check validation of it. ''' self.logger.info('Loading %s ...', license_file) # open license file try: fid = open(license_file, 'rb') except IOError as ioe: self.logger.error('I/O error: %s: %s', ioe.strerror, license_file) sys.exit(-1) # import license file try: self.lic = License.load(fid, self.psk) except License.InvalidSignatureException: exc = sys.exc_info() self.logger.critical('truepy: %s', str(exc[1])) sys.exit(-1) fid.close() self.license_file = license_file self.extra = eval(self.lic.data.extra, {'null': None}) self.feats = self.extra['features'] # dump licenseData self._dump_data() # checking host ID if self._check_serverid(): self.logger.error( 'run \'%s\' on valid server has the following host IDs: %s', self.prog, repr(self.extra['serverids'])) sys.exit(-1) # load the license file as row data to pass to clients. size = os.path.getsize(license_file) with open(license_file, 'rb') as fid: self.rowsize = size self.rowlic = fid.read(size)
def show(license_file, issuer_certificate, license_file_password, **args): """show [license file] Verifies the signature of a license file and shows information about it. You must specify the issuer certificate as --issuer-certificate on the command line, and the license file password as --license-file-password. """ with open(license_file, 'rb') as f: try: license = License.load(f, license_file_password) except Exception as e: raise RuntimeError('Failed to load license file: %s', e) try: license.verify(issuer_certificate) except Exception as e: raise RuntimeError('Failed to verify license: %s', e) print('License information') print('\tissued by:\t"%s"' % str(license.data.issuer)) print('\tissued to:\t"%s"' % str(license.data.holder)) print('\tvalid from:\t%s' % str(license.data.not_before)) print('\tvalid to:\t%s' % str(license.data.not_after)) print('\tsubject:\t%s' % ( '"%s"' % license.data.subject if license.data.subject else '<none>')) print('\tconsumer_type:\t%s' % ( '"%s"' % license.data.consumer_type if license.data.consumer_type else '<none>')) print('\tinformation:\t%s' % ( '"%s"' % license.data.info if license.data.info else '<none>')) print('\textra data:\t%s' % ( '"%s"' % license.data.extra if license.data.extra else '<none>'))
def test_load_invalid_password(self): """Tests that License.load fails for invalid license data""" with self.assertRaises(License.InvalidPasswordException): License.load(license(), b'invalid password')
def License_encoded0(): """Tests that License() with invalid encoded data raises ValueError""" with assert_exception(ValueError): License('<invalid/>', '<signature>')
def test_load(self): """Tests that License.load succeeds with valid license data""" License.load(license(), b'valid password')
def License_load_invalid_data(): """Tests that License.load fails for invalid license data""" with assert_exception(License.InvalidPasswordException): License.load(io.BytesIO(b'hello world!!!!!'), b'password')
def test_load_invalid_data(self): """Tests that License.load fails for invalid license data""" with self.assertRaises(License.InvalidPasswordException): License.load(io.BytesIO(b'hello world!!!!!'), b'password')
def License_load_invalid_password(): """Tests that License.load fails for invalid license data""" with assert_exception(License.InvalidPasswordException): License.load(license(), b'invalid password')
def test_encoded_invalid(self): """Tests that License() with invalid encoded data raises ValueError""" with self.assertRaises(ValueError): License('<invalid/>', '<signature>')
def issue(license_file, license_description, issuer_certificate, issuer_key, license_file_password, **args): """issue [license file] [digest] [license description] Issues a new license and shows information about it. You must specify the issuer certificate and key as --issuer-certificate/key on the command line, and the license file password as --license-file-password. [digest] The environment digest file. [license description] must be one command line argument on the form not_before=2014-01-01T00:00:00,not_after=2016-01-01T00:00:00,... containing license data fields. - The license of the subject of the request, possible arguments are: node - Authorization Number of nodes, default 10000 not_before - The timestamp when this license starts to be valid. not_after - The timestamp when this license ceases to be valid. This must be strictly after `not_before`. issued - The timestamp when this license was issued. This defaults to not_before. issuer - The issuer of this certificate. If not specified, UNKNOWN_NAME will be used. holder - The holder of this certificate. If not specified, UNKNOWN_NAME will be used. subject - Free-form string data to associate with the license. This value will be stringified. consumer_type - Free-form string data to associate with the license. This value will be stringified. info - Free-form string data to associate with the license. This value will be stringified. extra - Any type of data to store in the license. If this is not a string, it will be JSON serialised. """ try: license_data_parameters = dict( (p.strip() for p in i.split('=', 1)) for i in license_description.split(',')) except Exception as e: raise RuntimeError( 'Invalid license data description (%s): %s', license_description, e) extra = {'node': license_data_parameters.pop('node', 10000), 'digests': args.get('digest'), 'other_extra': license_data_parameters.get('extra')} license_data_parameters['extra'] = extra try: license_data = LicenseData(**license_data_parameters) except TypeError as e: raise RuntimeError( 'Incomplete license data description (%s): %s', license_description, e) license = License.issue(issuer_certificate, issuer_key, license_data=license_data) with open(license_file, 'wb') as f: license.store(f, license_file_password) show(license_file, issuer_certificate, license_file_password)