Postquantum-feldman-vss

Latest version: v0.8.0b3

Safety actively analyzes 722674 Python packages for vulnerabilities to keep your Python projects secure.

Scan your dependencies

0.8.0b3

What's Changed
* Update snyk/actions digest to cdb7600 by renovate in https://github.com/DavidOsipov/PostQuantum-Feldman-VSS/pull/21


**Full Changelog**: https://github.com/DavidOsipov/PostQuantum-Feldman-VSS/compare/v0.8.0b2...v0.8.0b3

0.8.0b2

This release focuses on enhanced security, memory management, and code clarity for the Post-Quantum Feldman VSS library.

**Major Highlights:**

* **Enhanced Memory Management:** Implemented a `MemoryMonitor` class and integrated memory safety checks throughout the code to prevent excessive memory allocation and potential denial-of-service vulnerabilities. This drastically improves the library's robustness, especially when dealing with large threshold values and bit lengths.
* **Improved Error Handling and Forensics:** Enhanced exception handling throughout the codebase with more detailed forensic data included in exceptions for debugging/auditing purposes. Added `get_forensic_data` to errors for better debugging. Sanitized errors are used by default to prevent information leakage.
* **Enhanced Security:** Further hardened constant-time operations, Byzantine fault tolerance, and memory safety. Enhanced comments and documentation for security-sensitive areas of the code.

**Detailed Changes:**

* **Core Security Enhancements:**
* **`constant_time_compare`:** Added input validation for `gmpy2.mpz` types.
* **`secure_redundant_execution`:** Added a deterministically selected result to prevent timing side-channels, and added a more robust approach for gathering results in `concurrent.futures.ThreadPoolExecutor`.
* **`_find_secure_pivot`:** Updated with constant-time update to minimum value and added more secure swaps. Added improved error check- ensure we're not returning a row with a zero pivot.
* **`_compute_combined_randomizer`** Added type hints for function parameter.
* **`_process_echo_consistency`:** Added input validation and more comprehensive Byzantine evidence collection.
* **`_detect_byzantine_behavior`:** Added more explicit checks for malformed commitments and safer element access. Now explicitly requires passing the zero commitment check.
* **``_generate_invalidity_evidence`:** Added additional evidence about consistency checks.
* **`secure_exp`:** Optimization: For safe primes p=2q+1, reduce modulo q instead of p-1. Check memory safety before proceeding.
* **`create_polynomial_proof`:** Removed the use of `id()` for commitment keys and replaced it with the use of a secure cryptographic hashing algorithm to generate commitment keys, significantly improving the uniqueness and security of the keys.

* **Memory Management:**
* **`MemoryMonitor` Class:** Added a `MemoryMonitor` class to track allocated memory and prevent exceeding limits.
* **`check_allocation`, `allocate`, `release`, `get_usage_stats`:** Implemented methods for memory tracking and management.
* **`check_memory_safety`:** Added comprehensive memory safety checks throughout the code.
* **`estimate_mpz_size`:** Added a function to estimate memory usage of `gmpy2.mpz` numbers.
* Integrated memory safety checks within `CyclicGroup.exp`, `CyclicGroup.efficient_multi_exp`, `FeldmanVSS._evaluate_polynomial`, and `FeldmanVSS._secure_matrix_solve`.

* **Error Handling & Forensic Data:**
* **Custom Exception Classes:** Enhanced `SecurityError`, `SerializationError`, `VerificationError`, and `ParameterError` with fields like `detailed_info`, `severity`, `timestamp`, `data_format`, `checksum_info`, `parameter_name`, `parameter_value`, and `expected_type` for more comprehensive error reporting. Added `get_forensic_data` to errors for better debugging.
* **Detailed Error Messages:** Added forensic data collection for debugging/auditing purposes.
* **Sanitized Errors:** Sanitized errors are used by default to prevent information leakage.
* **Enhanced Input Validation:** Added additional input validation and logging to various methods.
* **Corrected potential errors:** Fixed a potential error that might occur if the input was undefined

* **Code Quality & Clarity:**
* **Type Hinting:** Added type hints throughout the code for improved readability and maintainability.
* **Docstring Improvements:** Enhanced docstrings for better clarity and consistency.
* **Removed Unnecessary Code:** Removed code to free up memory in a class, as it is automatically handled by garbage collector.
* **Function Renaming:** Renamed memory_safe_mpz_mul to check_memory_safety for more clarity.

* **Bug Fixes:**
* Fixed an error with the input type of a function.

* **Dependency Updates:**
* Updated `requires-python` version.
* Updated `dependencies` version.

* **Documentation:**
* Updated the documentation to accurately reflect the current codebase.
* Enhanced docstrings throughout the code for better clarity and consistency.
* Updated System Requirements section.
* Added PyPi link.

**Breaking Changes:**

* Some exceptions now inherit from the custom classes (`SecurityError`, `SerializationError`, `VerificationError`, `ParameterError`) to provide additional diagnostic information. This *should* be backwards compatible in most cases, but code that specifically catches `Exception` may need to be updated.

**Security Notes:**

* This release addresses potential denial-of-service vulnerabilities related to excessive memory allocation.
* This release adds a deterministically selected result to prevent timing side-channels.
* This release adds a challenge consistency check to help detect malicious tampering.
* As a reminder, this library still has timing side-channel and fault injection vulnerabilities that cannot be adequately addressed in pure Python. These issues require implementation in a lower-level language like Rust to fix properly.

**Upgrade Notes:**

* It is highly recommended to upgrade to this version for improved security and stability.
* Pay special attention to the "Breaking Changes" section if your code relies on catching specific exception types.

**Future Work:**

* Further hardening of constant-time operations.
* More comprehensive testing and auditing.
* Fixing issues with Type Hints by creating custom stubs

0.7.6beta

Changed

- **Major Refactor and Enhancements:** This version introduces significant internal changes and improvements, building upon version 0.7.5b0. While the public API remains largely compatible, many functions have been optimized, rewritten, or enhanced for security and performance.
- **Enhanced Security:**
- Improved fault injection countermeasures in `secure_redundant_execution`. Increased redundancy from 3 to 5 executions, added random execution ordering, and introduced small random delays to decorrelate execution timing. Used more robust constant-time comparisons for all result permutations.
- `hash_to_group` now uses strict rejection sampling *without* fallback to modular reduction, eliminating a potential (though minor) bias. Increased the number of attempts and added domain separation to improve the success rate of rejection sampling.
- Enhanced domain separation in `_enhanced_encode_for_hash` with type tagging and length prefixing to prevent collision attacks.
- Improved validation during deserialization of commitments and proofs, including stricter checks on data types, structures, and cryptographic parameters (primality, generator validity, range checks).
- Added more comprehensive Byzantine fault tolerance in `_refresh_shares_additive`, including an echo broadcast mechanism for consistency verification, adaptive quorum-based detection of Byzantine parties, and enhanced collusion detection.
- Introduced `_detect_byzantine_behavior` for more thorough detection of malicious behavior, including inconsistent shares, invalid commitments, and equivocation.
- Added cryptographic proof generation for invalid shares (`_create_invalidity_proof`) and for correct share refreshing (`_generate_refresh_consistency_proof`).
- Improved collusion detection using network analysis algorithms (`_enhanced_collusion_detection`).
- Added secure constant-time summation of shares (`_secure_sum_shares`) to prevent timing attacks during share refreshing.
- Implemented a more secure randomized pivot selection strategy in `_find_secure_pivot` to prevent timing-based side-channel attacks during Gaussian elimination.
- Added better handling of extra entropy during commitment creation and verification
- Added more detailed diagnostics to error messages.
- Improved sanitization of error messages.
- Added handling for potential failures during random shuffle and delay.
- **Performance Optimizations:**
- Optimized `batch_verify_shares` with caching of intermediate values and batch processing for improved performance with large batches.
- Optimized `_refresh_shares_additive` for better performance in asynchronous environments, reduced communication complexity, and more efficient verification.
- Improved parallelism in `_process_verification_batches`.
- Optimized `efficient_multi_exp` with adaptive window sizing and selective precomputation.
- Pre-compute powers of generator with multi-level windows.
- Dynamic window sizing based on prime size.
- **API Changes (Minor):**
- Added optional `sanitize_error_func`, `function_name`, and `context` parameters to `secure_redundant_execution` for better error handling and context.
- Added optional `original_commitments` and `participant_ids` parameters to `refresh_shares`.
- Renamed `create_commitments_and_proof` to `create_commitments_with_proof` for clarity.
- The `_find_secure_pivot` function's output is now deterministic with respect to its inputs, even though it uses randomness internally. This improves testability.
- **Bug Fixes:**
- Fixed potential `TypeError` in `constant_time_compare` when comparing mixed types. Now uses a consistent conversion approach.
- Fixed various potential issues in deserialization methods by adding stricter type and structure checks.
- Fixed potential error in `_secure_matrix_solve` by using gmpy2.invert for modular inversion.
- **Code Quality:**
- Improved type hints and documentation throughout the code.
- Added more comprehensive input validation and error handling.
- Used `gmpy2.mpz` consistently for all integer arithmetic to ensure consistent handling and prevent potential type-related issues.
- Improved logging and warning messages.

0.7.5beta

This release focuses on enhancing security, improving performance, and refining the API for better usability and robustness. It addresses several potential vulnerabilities and incorporates feedback from the alpha testing phase.

**Key Changes and Improvements:**

Security Enhancements

* **`hash_to_group` Bias Mitigation:**
* Increased the maximum attempts for rejection sampling in `hash_to_group` from 100 to 1000. This significantly reduces the already slight statistical bias introduced by the fallback modular reduction, making it even more negligible.

* **Enhanced Domain Separation in Hashing:**
* Replaced length-prefixed encoding in `_enhanced_encode_for_hash` with a more robust scheme that includes type tagging. This scheme explicitly encodes the type of each input (bytes, string, int/mpz) *before* its length, providing stronger domain separation. This prevents a wider range of potential collision attacks.

* **Deserialization Validation Improvements:**
* `deserialize_commitments` and `deserialize_commitments_with_proof` now include significantly more rigorous validation checks:
* **Generator Validation:** Verifies that the deserialized generator is within the valid range (1 < generator < prime - 1) and that it's a valid generator for the given prime. For safe primes, it checks `g^q != 1 mod p`, where `q = (p-1)/2`.
* **Commitment and Randomizer Range Checks:** Ensures all deserialized commitment and randomizer values are within the expected range [0, prime-1].
* **Commitment Structure Validation:** Confirms each commitment has the correct structure: `(commitment, randomizer)` or `(commitment, randomizer, extra_entropy)`.
* **Proof Structure Validation (for `deserialize_commitments_with_proof`):** Adds comprehensive checks for the presence and correct types of all required fields within the deserialized proof structure (`blinding_commitments`, `challenge`, `responses`, `commitment_randomizers`, `blinding_randomizers`, `timestamp`). Also verifies the consistency of lengths between the different proof components.
* **Timestamp Validation (for `deserialize_commitments_with_proof`):** Checks that the timestamp within the proof is not in the future (allowing for a small clock skew) and is not excessively old (warning if older than 90 days).

* **Byzantine Fault Tolerance in Share Refreshing:**
* The `_refresh_shares_additive` method (implementing Chen & Lindell's Protocol 5) has received several improvements to its Byzantine fault tolerance:
* **Adaptive Quorum-Based Byzantine Detection:** Consistency checks during share refreshing now use an adaptive quorum. The required consistency ratio for accepting a party's shares increases dynamically based on the number of participants and the detected threat level. This makes it harder for colluding adversaries to disrupt the refresh process.
* **Enhanced Evidence Collection:** The `_detect_byzantine_behavior` function now collects more detailed evidence when Byzantine behavior is detected, including information about inconsistent shares, invalid commitments, and equivocation (sending different values to different participants).
* **Improved Collusion Detection:** The `_enhanced_collusion_detection` function uses a more sophisticated graph analysis approach to identify potential collusion patterns. It considers both the number of invalid shares and the overlap in the participants targeted by those invalid shares.
* **Echo Consistency Protocol:** The `_process_echo_consistency` function has been significantly enhanced to provide stronger detection of equivocation. It uses cryptographically secure fingerprints of shared values to ensure consistent information among participants.

* **Constant-Time Operations:**
* The `_secure_matrix_solve` function now uses `gmpy2.invert()` instead of `powmod()` for modular inversion during Gaussian elimination. `gmpy2.invert()` is designed for constant-time modular inversion, offering better protection against timing side-channels.
* The `verify_dual_commitments` function now incorporates `constant_time_compare` to check the validity of commitment proofs. This ensures constant-time verification, preventing potential leakage of information about the secret values.

Performance Optimizations

* **Dynamic Window Sizing in `CyclicGroup`:**
* The `_precompute_powers` method in the `CyclicGroup` class now uses a more sophisticated dynamic window sizing strategy for precomputation. This adaptive logic considers the size of the prime and adjusts the small window size accordingly, leading to better performance across a wider range of prime sizes.

* **Verification Batch Size Calculation:**
* The `_calculate_optimal_batch_size` function now takes into account the number of available CPU cores (using `multiprocessing.cpu_count()`) to determine the optimal batch size for verification. This improves parallelism and reduces verification time, especially for large numbers of shares.

API and Usability Refinements

* **Clearer Error Messages and Warnings:** Many error messages and warnings have been improved to provide more specific and informative diagnostics.
* **Type Hinting and Documentation:** The code has been thoroughly reviewed and updated with comprehensive type hints and docstrings, improving readability and maintainability.
* **Consistent Use of `gmpy2`:** The code now consistently uses `gmpy2.mpz` for all integer arithmetic within the `CyclicGroup` and `FeldmanVSS` classes, ensuring consistent behavior and leveraging `gmpy2`'s performance optimizations.

Bug Fixes

* Fixed several minor inconsistencies and potential edge-case issues in serialization and deserialization methods.
* Addressed potential type errors in various functions by adding more robust input validation.

Potential Vulnerabilities (Acknowledged but Not Fully Addressed)

* **Timing Side-Channels (Partially Addressed):** Significant progress has been made in mitigating timing side-channels (e.g., `gmpy2.invert()`, `constant_time_compare` in `verify_dual_commitments`). However, a core concern remains: functions like `constant_time_compare`, `_secure_matrix_solve`, and `_find_secure_pivot` are implemented in pure Python. The Python interpreter and underlying hardware can still introduce timing variations. Full mitigation requires implementation in a lower-level language or using a well-vetted cryptographic library.

* **`secure_redundant_execution` Assumptions:** The `secure_redundant_execution` function still relies on the assumption that the provided function is deterministic and has no side effects.

* **Bias in `hash_to_group`:** Although reduced significantly, the `hash_to_group` function uses a fallback mechanism that can introduce a slight statistical bias. While negligible for large primes, this remains a theoretical weakness.

Note

This is a beta release. While extensive testing has been performed, there may still be undiscovered issues. It is recommended to thoroughly test this version in your environment before deploying it in a production setting.

0.7.4alpha

**Major Security and Performance Enhancements:**

* **Robust Post-Quantum Security:**
* Improved `hash_to_group` in `CyclicGroup` to ensure uniform distribution for primes of *any* size, eliminating potential bias in commitment generation. This is critical for provable post-quantum security.
* `_enhanced_encode_for_hash` now uses *fixed-length* byte representations for integers, guaranteeing deterministic hashing across all platforms and Python implementations. This prevents subtle inconsistencies and potential vulnerabilities.
* `_compute_hash_commitment_single` (and thus `_compute_hash_commitment`) now use the deterministic integer encoding, ensuring consistent commitment values.
* `_find_secure_pivot` implements a significantly more robust and constant-time pivot selection strategy during Gaussian elimination, mitigating timing side-channel attacks.
* `deserialize_commitments` now validates that the deserialized prime is a safe prime if `safe_prime` is enabled in the config.
* Extensive input validation added throughout the codebase to prevent incorrect usage and potential vulnerabilities.

* **Improved Byzantine Fault Tolerance (BFT) in Share Refreshing:**
* `refresh_shares_additive` now implements *adaptive quorum-based Byzantine detection*. The required consistency ratio dynamically adjusts based on the number of participants and observed inconsistencies.
* Shares from identified Byzantine parties are *explicitly excluded* from the share refresh process, preventing them from corrupting the secret.
* More comprehensive evidence collection for Byzantine behavior, including consistency ratios.
* Verification Proofs were added to the method.

* **Performance Optimizations:**
* `CyclicGroup` now uses a `SafeLRUCache` (Least Recently Used cache) with a configurable `capacity` (defaulting to 128) for storing exponentiation results. This provides:
* Bounded memory usage (prevents unbounded growth).
* Automatic eviction of least recently used entries.
* A cleaner and more standard caching interface.
* `_find_secure_pivot` generates random bytes in a single block for improved efficiency.

* **Correctness and Consistency:**
* `create_enhanced_commitments` now includes `extra_entropy` in the returned commitment tuples, ensuring that it's available for verification.
* `_verify_share_hash_based_single` now correctly uses the `extra_entropy` during verification.
* `serialize_commitments` and `deserialize_commitments` now correctly handle the `extra_entropy` for low-entropy secrets, ensuring round-trip consistency.
* The number of tries in `_find_generator` was significantly increased.

* **Code Quality and Maintainability:**
* Widespread addition of input validation to public and private methods.
* Improved comments and clearer logic in many methods.

0.7.0alpha

Initial release

© 2025 Safety CLI Cybersecurity Inc. All Rights Reserved.