def modversion(package): # will need updating once we hit 8.20 :( for i in range(20, 3, -1): if pkgconfig.installed(package, '>= 8.' + str(i)): # be careful micro version is always set to 0 return '8.' + str(i) + '.0' return '8.2.0'
def install_data(temp_dir: str, root_dir: str, prefix_dir: str): chdir_to_source_root() print('Checking dependencies') if not pkgconfig.installed('systemd', '>= 240'): print( 'Systemd is not installed on this system. Please make systemd available to continue.' ) sys.exit(4) print('Generating manual pages') manpage_files = make_manpages(temp_dir) print('Installing data') inst = Installer(root_dir, prefix_dir) sd_tmpfiles_dir = pkgconfig.variables('systemd')['tmpfilesdir'] sd_system_unit_dir = pkgconfig.variables('systemd')['systemdsystemunitdir'] man_dir = os.path.join('share', 'man', 'man1') inst.install('data/tmpfiles.d/debspawn.conf', sd_tmpfiles_dir) inst.install('data/services/debspawn-clear-caches.timer', sd_system_unit_dir) inst.install('data/services/debspawn-clear-caches.service', sd_system_unit_dir, replace_vars=True) for mf in manpage_files: inst.install(mf, man_dir)
def check_lib(name, version): lib_installed = pkgconfig.exists(name) if not lib_installed: raise RuntimeError("lib{0} not installed".format(name)) lib_min = pkgconfig.installed(name, version) if not lib_min: raise RuntimeError("requires lib{0} {1} ".format(name, version)) return pkgconfig.parse(name)
def test_version(): assertions = { '3.2.1': True, '==3.2.1': True, '==3.2.2': False, '> 2.2': True, '> 3.4': False, '<= 3.3.5': True, '< 2.3': False } for version, val in assertions.items(): nt.assert_true(pkgconfig.installed(PACKAGE_NAME, version) == val)
def test_import_key_double_fail(self, cryptography_key): key, key_public_pem = cryptography_key key_path = f"/ext/key_{random_uid()}" imported = self.fapi.import_object(path=key_path, import_data=key_public_pem) assert imported is True assert key_path in self.fapi.list() # assert imported is False # TODO bug: tpm2-tss #2028, fixed in master if pkgconfig.installed("tss2-fapi", ">=3.1.0"): with pytest.raises(TSS2_Exception): self.fapi.import_object(path=key_path, import_data=key_public_pem) else: self.fapi.import_object(path=key_path, import_data=key_public_pem)
def test_version(): assertions = { '3.2.1': True, '==3.2.1': True, '==3.2.2': False, '> 2.2': True, '> 3.4': False, '<= 3.3.5': True, '< 2.3': False } for version, val in assertions.items(): nt.assert_true(pkgconfig.installed(PACKAGE_NAME, version) == val)
def find_eigen(hint=None): r''' Try to find the Eigen library. If successful the include directory is returned. ''' # search with pkgconfig # --------------------- try: import pkgconfig if pkgconfig.installed('eigen3', '>3.0.0'): return pkgconfig.parse('eigen3')['include_dirs'][0] except: pass # manual search # ------------- search_dirs = [] if hint is None else hint search_dirs += [ "/usr/local/include/eigen3", "/usr/local/homebrew/include/eigen3", "/opt/local/var/macports/software/eigen3", "/opt/local/include/eigen3", "/usr/include/eigen3", "/usr/include/local", "/usr/include", ] for d in search_dirs: path = os.path.join(d, "Eigen", "Dense") if os.path.exists(path): vf = os.path.join(d, "Eigen", "src", "Core", "util", "Macros.h") if not os.path.exists(vf): continue src = open(vf, "r").read() v1 = re.findall("#define EIGEN_WORLD_VERSION (.+)", src) v2 = re.findall("#define EIGEN_MAJOR_VERSION (.+)", src) v3 = re.findall("#define EIGEN_MINOR_VERSION (.+)", src) if not len(v1) or not len(v2) or not len(v3): continue v = "{0}.{1}.{2}".format(v1[0], v2[0], v3[0]) print("Found Eigen version {0} in: {1}".format(v, d)) return d return None
def test_import_policy_double_fail(self): policy = """ { "description":"Description of this policy", "policy":[{"type": "POLICYAUTHVALUE"}] } """ policy_path = f"/policy/policy_{random_uid()}" imported = self.fapi.import_object(path=policy_path, import_data=policy) assert imported is True assert policy_path in self.fapi.list() # assert imported is False # TODO bug: tpm2-tss #2028, fixed in master if pkgconfig.installed("tss2-fapi", ">=3.1.0"): with pytest.raises(TSS2_Exception): self.fapi.import_object(path=policy_path, import_data=policy) else: self.fapi.import_object(path=policy_path, import_data=policy)
def lib_ext_kwargs(pc, prefix_env_var, lib_name, lib_pkg_name, pc_version, lib_subdir='lib'): system_prefix = os.environ.get(prefix_env_var) if system_prefix: print( f"Detected and preferring {lib_pkg_name} [via {prefix_env_var}]" ) return dict(include_dirs=[os.path.join(system_prefix, 'include')], library_dirs=[os.path.join(system_prefix, lib_subdir)], libraries=[lib_name]) if pc and pc.installed(lib_pkg_name, pc_version): print(f"Detected and preferring {lib_pkg_name} [via pkg-config]") return pc.parse(lib_pkg_name) raise Exception( f"Could not find {lib_name} lib/headers, please set {prefix_env_var} " f"or ensure {lib_pkg_name}.pc is in PKG_CONFIG_PATH.")
# # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, see <http://www.gnu.org/licenses/>. import pkgconfig from setuptools import setup, Extension macros = [] if pkgconfig.installed("blkid", ">= 2.36"): macros.append(("HAVE_BLKID2360", "1")) with open("README.md", "r") as f: long_description = f.read() def main(): setup( name="pylibblkid", version="0.2", description="Python interface for the libblkid C library", long_description=long_description, long_description_content_type="text/markdown", author="Vojtech Trefny", author_email="*****@*****.**",
def test_openssl(version, expected): assert pkgconfig.installed('fake-openssl', version) == expected
from configparser import ConfigParser import pkgconfig import os config = ConfigParser() config.add_section('directories') config.set('directories', 'basedirlist', os.environ['SAGE_LOCAL']) config.add_section('libs') config.set('libs', 'system_freetype', 'True') if pkgconfig.installed('qhull', '>= 7.2.0'): config.set('libs', 'system_qhull', 'True') # lto is problematic if we mix libraries from the OS with our own libraries, # which are not necessarily compiled with the same gcc version # https://trac.sagemath.org/ticket/27754 config.set('libs', 'enable_lto', 'False') ##################################################################### # Sage code -- all this code just sets the graphical_backend variable. # If True, that means we try to build GUI's; otherwise, we definitely # will not even try, even if we could. See trac #5301. ##################################################################### print( "NOTE: Set SAGE_MATPLOTLIB_GUI to anything but 'no' to try to build the Matplotlib GUI." ) graphical_backend = 'False' if os.environ.get('SAGE_MATPLOTLIB_GUI', 'no').lower() != 'no': graphical_backend = 'auto'
# SPDX-FileCopyrightText: 2020 The cython-iscsi Authors # # SPDX-License-Identifier: LGPL-2.1-or-later import pkgconfig import setuptools_scm # noqa: F401 # Ensure it's present. from Cython.Build import cythonize from setuptools import Extension, setup if not pkgconfig.installed("libiscsi", ">=1.13"): raise Exception( "libiscsi 1.13 not found, make sure you installed libiscsi-dev package, or equivalent" ) libiscsi_pkg = pkgconfig.parse("libiscsi") setup(ext_modules=cythonize( Extension(name="iscsi", sources=["src/iscsi.pyx"], **libiscsi_pkg)), )
import pkgconfig from Cython.Build import cythonize from setuptools import Extension, setup dep = "avro-c" dep_version = ">=1.8.0" if not pkgconfig.installed(dep, dep_version): raise Exception(f"{dep}{dep_version} not found") avroc_pkg = pkgconfig.parse(dep) extensions = cythonize( [Extension("*", sources=["src/avroc/*.pyx"], **avroc_pkg)], language_level="3") setup(ext_modules=extensions)
return "1.0.7" if "PKG_CONFIG_PATH" not in os.environ: os.environ["PKG_CONFIG_PATH"] = "" pkg_config_path = os.environ["PKG_CONFIG_PATH"].split(":") # todo add miniconda folder if "/usr/local/lib/pkgconfig" not in pkg_config_path: os.environ["PKG_CONFIG_PATH"] += ":/usr/local/lib/pkgconfig" if not pkgconfig.exists("libsemigroups"): raise ImportError("cannot locate libsemigroups library") elif pkgconfig.installed("libsemigroups", "< " + minimum_libsemigroups_version()): # the following lines require pkgconfig v1.5.0 which is very recent, # and hence not on conda at time of writing. # raise ImportError( # "libsemigroups version {0} is required, found {1}".format( # minimum_libsemigroups_version(), libsemigroups_version() # )) raise ImportError("libsemigroups version {0} is required".format( minimum_libsemigroups_version())) def libsemigroups_version(): # the try-except is require pkgconfig v1.5.0 which is very recent, and # hence not on conda at time of writing. try: return pkgconfig.modversion("libsemigroups")
def test_version(version, expected): assert pkgconfig.installed(PACKAGE_NAME, version) == expected
def test_dld_pkg(version, expected): assert pkgconfig.installed('fake-dld-pkg', version) == expected
# flake8: noqa import pkgconfig from cffi import FFI # we must have the vips package to be able to do anything if not pkgconfig.exists('vips'): raise Exception('unable to find pkg-config package "vips"') if pkgconfig.installed('vips', '< 8.2'): raise Exception( 'pkg-config "vips" is too old -- need libvips 8.2 or later') ffibuilder = FFI() ffibuilder.set_source("_libvips", r""" #include <vips/vips.h> """, **pkgconfig.parse('vips')) # this is awful, why doesn't pkgconfig let us get the modversion? major = 8 minor = 2 micro = 0 if pkgconfig.installed('vips', '>= 8.7'): minor = 7 elif pkgconfig.installed('vips', '>= 8.6'): minor = 6 elif pkgconfig.installed('vips', '>= 8.5'): minor = 5 elif pkgconfig.installed('vips', '>= 8.4'): minor = 4
kwargs = dict(libraries=[library]) header_file = sys.argv[1] module_name = sys.argv[2] with open(header_file) as f: cdefs = f.read() else: import subprocess try: import pkgconfig if not pkgconfig.exists(library): raise ModuleNotFoundError("Unable to find pkg-config package 'dftd4'") if pkgconfig.installed(library, "< 3.0"): raise Exception( "Installed 'dftd4' version is too old, 3.0 or newer is required" ) kwargs = pkgconfig.parse(library) cflags = pkgconfig.cflags(library).split() except ModuleNotFoundError: kwargs = dict(libraries=[library]) cflags = [] if prefix_var in os.environ: prefix = os.environ[prefix_var] kwargs.update( include_dirs=[os.path.join(prefix, "include")], library_dirs=[os.path.join(prefix, "lib")],
def run(self): # noqa: C901 if force_bundled_libcapnp: need_build = True elif force_system_libcapnp: need_build = False else: # Try to use capnp executable to find include and lib path capnp_executable = shutil.which("capnp") if capnp_executable: capnp_dir = os.path.dirname(capnp_executable) self.include_dirs += [os.path.join(capnp_dir, "..", "include")] self.library_dirs += [os.path.join(capnp_dir, "..", "lib{}".format(8 * struct.calcsize("P")))] self.library_dirs += [os.path.join(capnp_dir, "..", "lib")] # Look for capnproto using pkg-config (and minimum version) try: if pkgconfig.installed('capnp', '>= 0.8.0'): need_build = False else: need_build = True except EnvironmentError: # pkg-config not available in path need_build = True if need_build: print( "*WARNING* no libcapnp detected or rebuild forced. " "Attempting to build it from source now. " "If you have C++ Cap'n Proto installed, it may be out of date or is not being detected. " "This may take a while..." ) bundle_dir = os.path.join(_this_dir, "bundled") if not os.path.exists(bundle_dir): os.mkdir(bundle_dir) build_dir = os.path.join(_this_dir, "build{}".format(8 * struct.calcsize("P"))) if not os.path.exists(build_dir): os.mkdir(build_dir) # Check if we've already built capnproto capnp_bin = os.path.join(build_dir, 'bin', 'capnp') if os.name == 'nt': capnp_bin = os.path.join(build_dir, 'bin', 'capnp.exe') if not os.path.exists(capnp_bin): # Not built, fetch and build fetch_libcapnp(bundle_dir, libcapnp_url) build_libcapnp(bundle_dir, build_dir) else: print("capnproto already built at {}".format(build_dir)) self.include_dirs += [os.path.join(build_dir, 'include')] self.library_dirs += [os.path.join(build_dir, 'lib{}'.format(8 * struct.calcsize("P")))] self.library_dirs += [os.path.join(build_dir, 'lib')] # Copy .capnp files from source src_glob = glob.glob(os.path.join(build_dir, 'include', 'capnp', '*.capnp')) dst_dir = os.path.join(self.build_lib, "capnp") for file in src_glob: print("copying {} -> {}".format(file, dst_dir)) shutil.copy(file, dst_dir) return build_ext_c.run(self)
the directory where your system's numpy inclde files can be found is autogenerated, but I sort of made up the method. I'm sure there's a better way and this has only been tested on my system. Created by Benjamin Fields on 2009-09-04. Copyright (c) 2009 Goldsmith University of London. All rights reserved. """ from distutils.core import setup, Extension from numpy import __path__ as numpyBase from os.path import join import pkgconfig import sys if not pkgconfig.installed('audioDB', '0.0'): print 'libaudioDB not found' sys.exit(1) adblibs = pkgconfig.parse('audioDB') module1 = Extension('_pyadb', define_macros=[('MAJOR_VERSION', '0'), ('MINOR_VERSION', '2')], include_dirs=list(adblibs['include_dirs']) + [join(numpyBase[0], 'core/include')], libraries=list(adblibs['libraries']), library_dirs=list(adblibs['library_dirs']), sources=['pyadbmodule.c']) setup(
def test_dld_pkg(version, expected): assert pkgconfig.installed('fake-dld-pkg', version) == expected
LZ4_REQUIRED_VERSION = '>= 1.7.5' PY3C_REQUIRED_VERSION = '>= 1.0' # Check to see if we have a lz4 and py3c libraries installed on the system, and # of suitable versions, and use if so. If not, we'll use the bundled libraries. liblz4_found = False py3c_found = False liblz4_pkgconfig = True try: import pkgconfig except ImportError: # pkgconfig is not installed. It will be installed by setup_requires. pass else: try: liblz4_found = pkgconfig.installed('liblz4', LZ4_REQUIRED_VERSION) if liblz4_found: liblz4_pkgconfig = True py3c_found = pkgconfig.installed('py3c', PY3C_REQUIRED_VERSION) except EnvironmentError: # Windows, no pkg-config present pass if not liblz4_found: lz4_dir = os.environ.get('LZ4_DIR', None) if lz4_dir: liblz4_found = True liblz4_include_dir = os.path.join(lz4_dir, "include") liblz4_library_dir = os.path.join(lz4_dir, "lib") # Set up the extension modules. If a system wide lz4 library is found, and is
def test_version(version, expected): assert pkgconfig.installed(PACKAGE_NAME, version) == expected
# flake8: noqa import pkgconfig from cffi import FFI # we must have the vips package to be able to do anything if not pkgconfig.exists('vips'): raise Exception('unable to find pkg-config package "vips"') if pkgconfig.installed('vips', '< 8.2'): raise Exception( 'pkg-config "vips" is too old -- need libvips 8.2 or later') ffibuilder = FFI() ffibuilder.set_source("_libvips", r""" #include <vips/vips.h> """, **pkgconfig.parse('vips')) # pkgconfig 1.5+ has modversion ... otherwise, use a small shim try: from pkgconfig import modversion except ImportError: def modversion(package): # will need updating once we hit 8.20 :( for i in range(20, 3, -1): if pkgconfig.installed(package, '>= 8.' + str(i)): # be careful micro version is always set to 0 return '8.' + str(i) + '.0' return '8.2.0'
class TestFapi: @pytest.fixture def esys(self): # TODO ESAPI should accept either a cdata obj or a dedicated TCTI class, not TctiLdr! tcti = SimpleNamespace() tcti.ctx = self.fapi.tcti with ESAPI(tcti=tcti) as esys: yield esys @pytest.fixture def cryptography_key(self): key = ec.generate_private_key(ec.SECP256R1(), backend=default_backend()) key_public_pem = (key.public_key().public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo, ).decode()) return key, key_public_pem @pytest.fixture def sign_key(self): profile_name = self.fapi.config.profile_name key_path = f"/{profile_name}/HS/SRK/key_{random_uid()}" self.fapi.create_key(path=key_path, type="sign, exportable") yield key_path self.fapi.delete(path=key_path) @pytest.fixture def decrypt_key(self): profile_name = self.fapi.config.profile_name key_path = f"/{profile_name}/HS/SRK/key_{random_uid()}" self.fapi.create_key(path=key_path, type="decrypt, restricted, noda") yield key_path self.fapi.delete(path=key_path) @pytest.fixture def seal(self): profile_name = self.fapi.config.profile_name seal_path = f"/{profile_name}/HS/SRK/seal_{random_uid()}" seal_data = random_uid().encode() self.fapi.create_seal(path=seal_path, data=seal_data) yield seal_path, seal_data self.fapi.delete(path=seal_path) @pytest.fixture def ext_key(self, cryptography_key): key, key_public_pem = cryptography_key key_path = f"/ext/key_{random_uid()}" self.fapi.import_object(path=key_path, import_data=key_public_pem) yield key_path, key self.fapi.delete(path=key_path) @pytest.fixture def nv_ordinary(self): nv_path = f"/nv/Owner/nv_{random_uid()}" # TODO Owner should be case insensitive (fix upstream)? self.fapi.create_nv(path=nv_path, size=10) yield nv_path self.fapi.delete(path=nv_path) @pytest.fixture def nv_increment(self): nv_path = f"/nv/Owner/nv_{random_uid()}" self.fapi.create_nv(path=nv_path, size=10, type="counter") yield nv_path self.fapi.delete(path=nv_path) @pytest.fixture def nv_pcr(self): nv_path = f"/nv/Owner/nv_{random_uid()}" self.fapi.create_nv(path=nv_path, size=32, type="pcr") yield nv_path self.fapi.delete(path=nv_path) @pytest.fixture def nv_bitfield(self): nv_path = f"/nv/Owner/nv_{random_uid()}" self.fapi.create_nv(path=nv_path, size=32, type="bitfield") yield nv_path self.fapi.delete(path=nv_path) def test_provision_ok(self): provisioned = self.fapi.provision() assert provisioned is False def test_provision_fail(self): with pytest.raises(TSS2_Exception): self.fapi.provision(is_provisioned_ok=False) # TODO provision second (RSA) profile def test_get_random(self): random_bytes = self.fapi.get_random(42) assert type(random_bytes) == bytes assert len(random_bytes) == 42 def test_get_random_zero(self): random_bytes = self.fapi.get_random(0) assert type(random_bytes) == bytes assert len(random_bytes) == 0 def test_get_random_large(self): with pytest.raises(OverflowError): self.fapi.get_random(0xFFFFFFFFFFFFFFFF + 1) def test_get_random_negative(self): with pytest.raises(OverflowError): self.fapi.get_random(-1) def test_get_info(self): info = self.fapi.get_info() assert type(info) is str json.loads(info) assert "capabilities" in info def test_list(self): profile_name = self.fapi.config.profile_name path_list = self.fapi.list() assert type(path_list) is list assert len(path_list) > 0 assert type(path_list[0]) is str assert f"/{profile_name}/HS" in path_list def test_list_search_path(self): profile_name = self.fapi.config.profile_name search_path = f"/{profile_name}/HE" path_list = self.fapi.list(search_path) assert type(path_list) is list assert len(path_list) > 0 assert type(path_list[0]) is str assert all(path.startswith(search_path) for path in path_list) def test_list_bad_search_path(self): with pytest.raises(TSS2_Exception): self.fapi.list("/nonexistent") def test_create_key(self): profile_name = self.fapi.config.profile_name key_path = f"/{profile_name}/HS/key_{random_uid()}" created = self.fapi.create_key(path=key_path) assert created is True assert key_path in self.fapi.list() def test_create_key_double_ok(self): profile_name = self.fapi.config.profile_name key_path = f"/{profile_name}/HS/key_{random_uid()}" created = self.fapi.create_key(path=key_path) assert created is True assert key_path in self.fapi.list() created = self.fapi.create_key(path=key_path, exists_ok=True) assert created is False def test_create_key_double_fail(self): profile_name = self.fapi.config.profile_name key_path = f"/{profile_name}/HS/key_{random_uid()}" created = self.fapi.create_key(path=key_path) assert created is True assert key_path in self.fapi.list() with pytest.raises(TSS2_Exception): self.fapi.create_key(path=key_path) def test_get_tpm_blobs(self, sign_key): tpm_2b_public, tpm_2b_private, policy = self.fapi.get_tpm_blobs( path=sign_key) assert tpm_2b_public.size == 0x56 assert tpm_2b_public.publicArea.type == lib.TPM2_ALG_ECC assert tpm_2b_public.publicArea.nameAlg == lib.TPM2_ALG_SHA256 assert (tpm_2b_public.publicArea.objectAttributes == lib.TPMA_OBJECT_SIGN_ENCRYPT | lib.TPMA_OBJECT_USERWITHAUTH | lib.TPMA_OBJECT_SENSITIVEDATAORIGIN) assert tpm_2b_public.publicArea.authPolicy.size == 0 assert (tpm_2b_public.publicArea.parameters.eccDetail.symmetric. algorithm == lib.TPM2_ALG_NULL) assert (tpm_2b_public.publicArea.parameters.eccDetail.scheme.scheme == lib.TPM2_ALG_NULL) assert (tpm_2b_public.publicArea.parameters.eccDetail.curveID == lib.TPM2_ECC_NIST_P256) assert (tpm_2b_public.publicArea.parameters.eccDetail.kdf.scheme == lib.TPM2_ALG_NULL) assert tpm_2b_private.size == 0x7E assert policy == "" def test_get_esys_blob_contextload(self, esys, sign_key): blob_data, blob_type = self.fapi.get_esys_blob(path=sign_key) assert blob_type == lib.FAPI_ESYSBLOB_CONTEXTLOAD esys_handle = esys.load_blob(blob_data, blob_type) esys.ReadPublic(esys_handle) esys.FlushContext(esys_handle) def test_get_esys_blob_deserialize(self, esys, nv_ordinary): blob_data, blob_type = self.fapi.get_esys_blob(path=nv_ordinary) assert blob_type == lib.FAPI_ESYSBLOB_DESERIALIZE esys_handle = esys.load_blob(blob_data, blob_type) esys.NV_ReadPublic(esys_handle) def test_sign(self, sign_key): # create signature message = b"Hello World" digest = hashes.Hash(hashes.SHA256(), backend=default_backend()) digest.update(message) digest = digest.finalize() signature, key_public_pem, cert_pem = self.fapi.sign(path=sign_key, digest=digest) assert type(signature) == bytes assert type(key_public_pem) == bytes assert type(cert_pem) == bytes # verify via fapi self.fapi.verify_signature(sign_key, digest, signature) # verify via openssl public_key = serialization.load_pem_public_key( key_public_pem, backend=default_backend()) public_key.verify(signature, message, ec.ECDSA(hashes.SHA256())) def test_verify(self, ext_key): # create signature externally key_path, key = ext_key message = b"Hello World" signature = key.sign(message, ec.ECDSA(hashes.SHA256())) # verify signature via fapi self.fapi.verify_signature(key_path, sha256(message), signature) def test_verify_fail(self, ext_key): key_path, key = ext_key with pytest.raises(TSS2_Exception): self.fapi.verify_signature(key_path, digest=b"A" * 32, signature=b"bad signature") # TODO test encrypt with RSA profile. Needs to be provisioned separately. @pytest.mark.skipif(pkgconfig.installed("tss2-fapi", "<3.1.0"), reason="tpm2-tss bug, see #2028") def test_import_key_double_ok(self, cryptography_key): key, key_public_pem = cryptography_key key_path = f"/ext/key_{random_uid()}" imported = self.fapi.import_object(path=key_path, import_data=key_public_pem) assert imported is True assert key_path in self.fapi.list() imported = self.fapi.import_object(path=key_path, import_data=key_public_pem, exists_ok=True) assert imported is False @pytest.mark.skipif(pkgconfig.installed("tss2-fapi", "<3.1.0"), reason="tpm2-tss bug, see #2028") def test_import_key_double_fail(self, cryptography_key): key, key_public_pem = cryptography_key key_path = f"/ext/key_{random_uid()}" imported = self.fapi.import_object(path=key_path, import_data=key_public_pem) assert imported is True assert key_path in self.fapi.list() with pytest.raises(TSS2_Exception): self.fapi.import_object(path=key_path, import_data=key_public_pem) @pytest.mark.skipif(pkgconfig.installed("tss2-fapi", "<3.1.0"), reason="tpm2-tss bug, see #2028") def test_import_policy_double_ok(self): policy = """ { "description":"Description of this policy", "policy":[{"type": "POLICYAUTHVALUE"}] } """ policy_path = f"/policy/policy_{random_uid()}" imported = self.fapi.import_object(path=policy_path, import_data=policy) assert imported is True assert policy_path in self.fapi.list() imported = self.fapi.import_object(path=policy_path, import_data=policy, exists_ok=True) assert imported is False @pytest.mark.skipif(pkgconfig.installed("tss2-fapi", "<3.1.0"), reason="tpm2-tss bug, see #2028") def test_import_policy_double_fail(self): policy = """ { "description":"Description of this policy", "policy":[{"type": "POLICYAUTHVALUE"}] } """ policy_path = f"/policy/policy_{random_uid()}" imported = self.fapi.import_object(path=policy_path, import_data=policy) assert imported is True assert policy_path in self.fapi.list() with pytest.raises(TSS2_Exception): self.fapi.import_object(path=policy_path, import_data=policy) def test_import_exported_key(self, sign_key): exported_data = self.fapi.export_key(path=sign_key) profile_name = self.fapi.config.profile_name new_path = f"/{profile_name}/HS/SRK/key_{random_uid()}" self.fapi.import_object(path=new_path, import_data=exported_data) def test_export_imported_policy(self): policy = """ { "description":"Description of this policy", "policy":[{"type": "POLICYAUTHVALUE"}] } """ policy_path = f"/policy/policy_{random_uid()}" self.fapi.import_object(path=policy_path, import_data=policy) exported_policy = self.fapi.export_policy(path=policy_path) assert type(exported_policy) == str assert "Description of this policy" in exported_policy def test_create_seal(self): profile_name = self.fapi.config.profile_name seal_path = f"/{profile_name}/HS/SRK/seal_{random_uid()}" seal_data = "Hello World" created = self.fapi.create_seal(path=seal_path, data=seal_data) assert created is True assert seal_path in self.fapi.list() def test_create_seal_double_ok(self): profile_name = self.fapi.config.profile_name seal_path = f"/{profile_name}/HS/SRK/seal_{random_uid()}" seal_data = "Hello World" created = self.fapi.create_seal(path=seal_path, data=seal_data) assert created is True assert seal_path in self.fapi.list() created = self.fapi.create_seal(path=seal_path, data=seal_data, exists_ok=True) assert created is False def test_create_seal_double_fail(self): profile_name = self.fapi.config.profile_name seal_path = f"/{profile_name}/HS/SRK/seal_{random_uid()}" seal_data = "Hello World" created = self.fapi.create_seal(path=seal_path, data=seal_data) assert created is True assert seal_path in self.fapi.list() with pytest.raises(TSS2_Exception): self.fapi.create_seal(path=seal_path, data=seal_data) def test_unseal(self, seal): seal_path, seal_data = seal unseal_data = self.fapi.unseal(path=seal_path) assert type(unseal_data) is bytes assert seal_data == unseal_data def test_quote_verify(self, sign_key): info, signature, pcr_log, certificate = self.fapi.quote(path=sign_key, pcrs=[7, 9]) info_json = json.loads(info) assert info_json["attest"]["type"] == "ATTEST_QUOTE" assert type(signature) is bytes pcr_log_json = json.loads(pcr_log) assert pcr_log_json == [] assert certificate == "" # TODO verify via openssl # exported_data = self.fapi.export_key(path=sign_key) # sign_key_public_pem = json.loads(exported_data)["pem_ext_public"].encode() # public_key = serialization.load_pem_public_key(sign_key_public_pem) # message = b"TODO" # public_key.verify(signature, message, ec.ECDSA(hashes.SHA256())) # signature via fapi self.fapi.verify_quote(path=sign_key, signature=signature, quote_info=info) def test_export_key(self, sign_key): exported_data = self.fapi.export_key(path=sign_key) assert type(exported_data) is str json.loads(exported_data) def test_delete_key(self): profile_name = self.fapi.config.profile_name key_path = f"/{profile_name}/HS/key_{random_uid()}" self.fapi.create_key(path=key_path) assert key_path in self.fapi.list() self.fapi.delete(path=key_path) assert key_path not in self.fapi.list() def test_set_get_description(self, sign_key): description = "Nobody expects the Spanish Inquisition!" self.fapi.set_description(path=sign_key, description=description) returned_description = self.fapi.get_description(path=sign_key) assert description == returned_description def test_get_empty_description(self, sign_key): description = self.fapi.get_description(path=sign_key) assert description == "" def test_set_get_app_data(self, sign_key): app_data = b"\x00\xDE\xCA\xFB\xAD\x00" self.fapi.set_app_data(path=sign_key, app_data=app_data) returned_app_data = self.fapi.get_app_data(path=sign_key) assert app_data == returned_app_data def test_get_no_app_data(self, sign_key): app_data = self.fapi.get_app_data(path=sign_key) assert app_data is None def test_set_get_certificate(self, sign_key): certificate = "<PEM-encoded certificate (but FAPI does not really check)>" self.fapi.set_certificate(path=sign_key, certificate=certificate) returned_certificate = self.fapi.get_certificate(path=sign_key) assert certificate == returned_certificate def test_get_empty_certificate(self, sign_key): certificate = self.fapi.get_certificate(path=sign_key) assert certificate == "" def test_get_empty_platform_certificates_ok(self): certificates = self.fapi.get_platform_certificates(no_cert_ok=True) assert certificates is b"" def test_get_empty_platform_certificates_fail(self): with pytest.raises(TSS2_Exception): self.fapi.get_platform_certificates() def test_pcr_read(self): value, log = self.fapi.pcr_read(7) assert value == b"\0" * 32 assert log == "[\n]" def test_pcr_extend_read(self): index = 16 value_old, _ = self.fapi.pcr_read(index) data = b"\x11" * 100 log = '{"test":"myfile"}' self.fapi.pcr_extend(index, data, log) returned_value, returned_log = self.fapi.pcr_read(index) assert returned_value == sha256(value_old + sha256(data)) assert '"test":"myfile"' in returned_log def test_nv_write_read(self, nv_ordinary): data = b"ABCDEFGHIJ" # 10 bytes as defined in fixture self.fapi.nv_write(nv_ordinary, data) returned_data, log = self.fapi.nv_read(nv_ordinary) assert returned_data == data assert log == "" def test_nv_increment(self, nv_increment): self.fapi.nv_increment(nv_increment) returned_data, log = self.fapi.nv_read(nv_increment) assert returned_data == b"\x00\x00\x00\x00\x00\x00\x00\x01" assert log == "" def test_nv_pcr(self, nv_pcr): value_old = b"\x00" * 32 data = b"\x11" * 100 log = '{"test":"myfile"}' self.fapi.nv_extend(nv_pcr, data, log) returned_value, returned_log = self.fapi.nv_read(nv_pcr) assert returned_value == sha256(value_old + data) assert '"test":"myfile"' in returned_log def test_nv_set_bits(self, nv_bitfield): value_old = b"\x00" * 32 bitfield = 0x0000DECAFBAD0000 self.fapi.nv_set_bits(nv_bitfield, bitfield) returned_value, returned_log = self.fapi.nv_read(nv_bitfield) assert returned_value == bitfield.to_bytes(8, byteorder="big") assert returned_log == "" def test_set_auth_callback(self, sign_key): def callback(path, descr, user_data): print( f"Callback: path={path}, descr={descr}, user_data={user_data}") return user_data profile_name = self.fapi.config.profile_name key_path = f"/{profile_name}/HS/SRK/key_{random_uid()}" self.fapi.create_key(path=key_path, auth_value=b"123456") self.fapi.set_auth_callback(callback, user_data=b"123456") self.fapi.sign(key_path, b"\x11" * 32) self.fapi.change_auth(path=key_path, auth_value=b"ABCDEF") self.fapi.set_auth_callback(callback, user_data=b"ABCDEF") self.fapi.sign(key_path, b"\x22" * 32) def test_unset_auth_callback(self, sign_key): def callback(path, descr, user_data): print( f"Callback: path={path}, descr={descr}, user_data={user_data}") return user_data profile_name = self.fapi.config.profile_name key_path = f"/{profile_name}/HS/SRK/key_{random_uid()}" self.fapi.create_key(path=key_path, auth_value=b"123456") self.fapi.set_auth_callback(callback, user_data=b"123456") self.fapi.sign(key_path, b"\x11" * 32) self.fapi.change_auth(path=key_path, auth_value=None) self.fapi.set_auth_callback(callback=None) self.fapi.sign(key_path, b"\x22" * 32) @pytest.mark.skipif(pkgconfig.installed("tss2-fapi", "<3.1.0"), reason="tpm2-tss bug, see #2084") def test_write_authorize_nv(self, esys): # write CommandCode policy for sign key into nv index nv_path = f"/nv/Owner/nv_policy_{random_uid()}" policy = """ { "description": "", "policy": [ { "type": "CommandCode", "code": "sign" } ] }""" policy_auth_nv_path = f"/policy/policy_{random_uid()}" self.fapi.import_object(path=policy_auth_nv_path, import_data=policy) self.fapi.create_nv(path=nv_path, size=34) self.fapi.write_authorize_nv(nv_path, policy_auth_nv_path) # create key with AuthorizeNV policy (which ties the above policy, stored in the nv index, to the key) policy_auth_nv = f""" {{ "description":"Description pol_authorize_nv", "policy":[ {{ "type": "AuthorizeNV", "nvPath": "{nv_path}", }} ] }} """ policy_path = f"/policy/policy_{random_uid()}" self.fapi.import_object(path=policy_path, import_data=policy_auth_nv) profile_name = self.fapi.config.profile_name key_path = f"/{profile_name}/HS/SRK/key_{random_uid()}" self.fapi.create_key(path=key_path, type="sign", policy_path=policy_path) # use key for signing: success self.fapi.sign(path=key_path, digest=b"\x11" * 32) # use key for quoting: fail with pytest.raises(TSS2_Exception): self.fapi.quote(path=key_path, pcrs=[7, 9]) @pytest.mark.skipif(pkgconfig.installed("tss2-fapi", "<3.1.0"), reason="tpm2-tss bug, see #2084") def test_authorize_policy(self, sign_key): # create policy Authorize, which is satisfied via a signature by sign_key policy_authorize_path = f"/policy/policy_{random_uid()}" policy_authorize = f""" {{ "description": "Description pol_authorize", "policy": [ {{ "type": "Authorize", "policyRef": [1, 2, 3, 4, 5], "keyPath": "{sign_key}", }} ] }} """ self.fapi.import_object(path=policy_authorize_path, import_data=policy_authorize) # create policy CommandCode policy = """ { "description": "", "policy": [ { "type": "CommandCode", "code": "sign" } ] }""" policy_path = f"/policy/policy_{random_uid()}" self.fapi.import_object(path=policy_path, import_data=policy) # create key which can only be used if policy Authorize is satisfied profile_name = self.fapi.config.profile_name key_path = f"/{profile_name}/HS/SRK/key_{random_uid()}" self.fapi.create_key(path=key_path, type="sign", policy_path=policy_authorize_path) # try to use key without satisfying policy Authorize: fail with pytest.raises(TSS2_Exception): self.fapi.sign(path=key_path, digest=b"\x11" * 32) # specify underlying policy CommandCode and use key: success self.fapi.authorize_policy( policy_path=policy_path, key_path=sign_key, policy_ref=b"\x01\x02\x03\x04\x05", ) self.fapi.sign(path=key_path, digest=b"\x11" * 32) # specify underlying policy CommandCode and use key: fail because policy CommandCode is not satisfied self.fapi.authorize_policy( policy_path=policy_path, key_path=sign_key, policy_ref=b"\x01\x02\x03\x04\x05", ) with pytest.raises(TSS2_Exception): self.fapi.quote(path=key_path, pcrs=[7, 9]) @pytest.mark.skipif(pkgconfig.installed("tss2-fapi", "<3.1.0"), reason="tpm2-tss bug, see #2080") def test_policy_signed(self, cryptography_key): # create external signing key used by the signing authority external to the TPM sign_key, sign_key_public_pem = cryptography_key # create policy Signed, which is satisfied via a signature by sign_key policy = f""" {{ "description": "Description pol_signed", "policy": [ {{ "type": "PolicySigned", "publicKeyHint": "Test key hint", "keyPEM": "{sign_key_public_pem}", }} ] }} """ policy_path = f"/policy/policy_{random_uid()}" self.fapi.import_object(path=policy_path, import_data=policy) # create key which can only be used if policy Signed is satisfied profile_name = self.fapi.config.profile_name key_path = f"/{profile_name}/HS/SRK/key_{random_uid()}" self.fapi.create_key(path=key_path, type="sign", policy_path=policy_path) # try to use key without satisfying policy Signed: fail with pytest.raises(TSS2_Exception): self.fapi.sign(path=key_path, digest=b"\x11" * 32) def sign_callback( path, description, public_key, public_key_hint, hash_alg, data_to_sign, user_data, ): assert key_path.endswith(path) assert description == "PolicySigned" assert public_key == sign_key_public_pem assert public_key_hint == "Test key hint" assert hash_alg == lib.TPM2_ALG_SHA256 assert user_data == b"123456" # signing authority signs external to TPM (via openssl) to authorize usage of key (policy Signed) return sign_key.sign(data_to_sign, ec.ECDSA(hashes.SHA256())) # set signing callback, will be called if policy Signed is to be satisfied self.fapi.set_sign_callback(callback=sign_callback, user_data=b"123456") # use key for signing: success self.fapi.sign(path=key_path, digest=b"\x11" * 32) def test_policy_branched(self): pcr_index = 15 pcr_data = b"ABCDEF" pcr_digest = b"\x00" * 32 pcr_digest = sha256(pcr_digest + sha256(pcr_data)) # create policy Signed, which is satisfied via a signature by sign_key policy = f""" {{ "description": "Read, Password for write", "policy": [ {{ "type": "PolicyOR", "branches": [ {{ "name": "Read", "description": "des", "policy": [ {{ "type": "CommandCode", "code": "NV_READ" }} ] }}, {{ "name": "Write", "description": "dgf", "policy": [ {{ "type": "CommandCode", "code": "NV_WRITE" }}, {{ "type": "PolicyPCR", "pcrs":[ {{ "pcr": {pcr_index}, "hashAlg": "TPM2_ALG_SHA256", "digest": "{binascii.hexlify(pcr_digest).decode()}" }} ] }} ] }} ] }} ] }} """ print(policy) policy_path = f"/policy/policy_{random_uid()}" self.fapi.import_object(path=policy_path, import_data=policy) # create key which can only be used if policy Signed is satisfied nv_path = f"/nv/Owner/nv_{random_uid()}" self.fapi.create_nv(path=nv_path, size=11, policy_path=policy_path) def branch_callback(path, description, branch_names, user_data): assert path == nv_path assert description == "PolicyOR" assert branch_names == ["Read", "Write"] assert user_data == b"123456" return policy_coice(branch_names) # set branch callback, will be called if the nv index is accessed self.fapi.set_branch_callback(callback=branch_callback, user_data=b"123456") # at first, we will choose the 'Write' branch policy_coice = lambda options: options.index("Write") # write to nv index: fail with pytest.raises(TSS2_Exception): self.fapi.nv_write(path=nv_path, data="Hello World") # satisfy policy PCR (and thus policy OR) self.fapi.pcr_extend(index=pcr_index, data=pcr_data) # write to nv index: success self.fapi.nv_write(path=nv_path, data="Hello World") # extend PCR so policy PCR cannot be satisfied anymore self.fapi.pcr_extend(index=pcr_index, data="nobody expects the spanish inquisition!") # secondly, we will choose the 'Read' branch policy_coice = lambda options: options.index("Read") # use the 'Read' branch (satisfied via policy CommandCode) nv_data, _ = self.fapi.nv_read(nv_path) assert nv_data == b"Hello World" policy_coice = None # thirdly, we set different branch callback function (here lambda) and read again self.fapi.set_branch_callback( callback=lambda _path, _description, branch_names, _user_data: branch_names.index("Read")) nv_data, _ = self.fapi.nv_read(nv_path) assert nv_data == b"Hello World" # clean up self.fapi.delete(path=nv_path) @pytest.mark.skipif(pkgconfig.installed("tss2-fapi", "<3.1.0"), reason="tpm2-tss bug, see #2089") def test_policy_action(self): # create policy Action, which is satisfied via the callback policy = f""" {{ "description":"The description", "policy":[ {{ "type": "POLICYACTION", "action": "myaction" }} ] }} """ policy_path = f"/policy/policy_{random_uid()}" self.fapi.import_object(path=policy_path, import_data=policy) # create key which can only be used if policy Action is satisfied profile_name = self.fapi.config.profile_name key_path = f"/{profile_name}/HS/SRK/key_{random_uid()}" self.fapi.create_key(path=key_path, type="sign", policy_path=policy_path) # try to use key without satisfying policy Action: fail with pytest.raises(TSS2_Exception): self.fapi.sign(path=key_path, digest=b"\x11" * 32) def policy_action_callback_error(path, action, user_data) -> None: assert f"/{path}" == key_path assert action == "myaction" assert user_data == b"123456" raise ValueError("Policy Action: Invalid action.") # set policy Action callback, will be called if policy Action is to be satisfied self.fapi.set_policy_action_callback( callback=policy_action_callback_error, user_data=b"123456") # try to use key with policy Action that raises an exception: fail with pytest.raises(TSS2_Exception): self.fapi.sign(path=key_path, digest=b"\x11" * 32) # set policy Action callback to lambda, returning success self.fapi.set_policy_action_callback(callback=lambda *_: None) # use key for signing: success self.fapi.sign(path=key_path, digest=b"\x11" * 32)
# flake8: noqa import pkgconfig from cffi import FFI # we must have the vips package to be able to do anything if not pkgconfig.exists('vips'): raise Exception('unable to find pkg-config package "vips"') if pkgconfig.installed('vips', '< 8.2'): raise Exception( 'pkg-config "vips" is too old -- need libvips 8.2 or later') ffibuilder = FFI() ffibuilder.set_source("_libvips", r""" #include <vips/vips.h> """, **pkgconfig.parse('vips')) features = { # in API mode 'api': True, # at_least_libvips(8, 4): '8.4+': pkgconfig.installed('vips', '>= 8.4'), # at_least_libvips(8, 5): '8.5+': pkgconfig.installed('vips', '>= 8.5'), # at_least_libvips(8, 6): '8.6+': pkgconfig.installed('vips', '>= 8.6'), } from pyvips import decls
import os import pkgconfig __LIBSEMIGROUPS_VERSION = "1.0.7" if "PKG_CONFIG_PATH" not in os.environ: os.environ["PKG_CONFIG_PATH"] = "" pkg_config_path = os.environ["PKG_CONFIG_PATH"].split(":") if "/usr/local/lib/pkgconfig" not in pkg_config_path: os.environ["PKG_CONFIG_PATH"] += ":/usr/local/lib/pkgconfig" if not pkgconfig.exists("libsemigroups"): raise ImportError("cannot locate libsemigroups library") elif pkgconfig.installed("libsemigroups", "< " + __LIBSEMIGROUPS_VERSION): raise ImportError( "libsemigroups version {0} is required, found {1}".format( __LIBSEMIGROUPS_VERSION, pkgconfig.modversion("libsemigroups"))) import cppyy import sys cppyy.gbl path = os.environ["PATH"].split(":") for d in path: if d.find("include") != -1: try: cppyy.add_include_path(d) except:
def test_openssl(version, expected): assert pkgconfig.installed('fake-openssl', version) == expected
import os import sys import subprocess import pkgconfig import numpy from setuptools import setup, Extension VERSION = '1.1.0' if not pkgconfig.installed('pygobject-3.0', '>=3.2.2') and \ not pkgconfig.installed('pygobject-2.0', '>=2.28'): sys.exit("You must install pygobject-2.0 or pygobject-3.0") if not pkgconfig.installed('ufo', '>=0.4.0'): sys.exit("You must install ufo>=0.4.0") def listify(d): return {k: list(v) for k, v in d.items()} build_flags = listify(pkgconfig.parse('pygobject-3.0 ufo')) build_flags['include_dirs'].append(numpy.get_include()) build_flags['extra_compile_args'] = ['-std=c99'] setup( name='ufo', version=VERSION, author='Matthias Vogelgesang', author_email='*****@*****.**',
import os import sys import subprocess import pkgconfig import numpy from setuptools import setup, Extension VERSION = '1.1.0' if not pkgconfig.installed('pygobject-3.0', '>=3.2.2') and \ not pkgconfig.installed('pygobject-2.0', '>=2.28'): sys.exit("You must install pygobject-2.0 or pygobject-3.0") if not pkgconfig.installed('ufo', '>=0.4.0'): sys.exit("You must install ufo>=0.4.0") def listify(d): return {k: list(v) for k, v in d.items()} build_flags = listify(pkgconfig.parse('pygobject-3.0 ufo')) build_flags['include_dirs'].append(numpy.get_include()) build_flags['extra_compile_args'] = ['-std=c99'] setup( name='ufo', version=VERSION, author='Matthias Vogelgesang',
# Write result with open(outfile, "w") as f: f.write( textwrap.dedent(""" /* * SPDX-License-Identifier: BSD-2 * This file was automatically generated. Do not modify ! */ """)) f.write(common) f.write(types) f.write(tcti) f.write(tcti_ldr) f.write(sapi) f.write(esapi) if build_fapi: f.write(fapi) f.write(rcdecode) f.write(mu) if __name__ == "__main__": if len(sys.argv) != 3: print("Usage: {0} <tss2-header-dir> <output-file>".format(sys.argv[0])) exit(1) build_fapi = pkgconfig.installed("tss2-fapi", ">=3.0.0") prepare(sys.argv[1], sys.argv[2], build_fapi=build_fapi)