Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor!: use RSA directly, drop PGPy #1

Merged
merged 8 commits into from
Dec 30, 2024
Merged

refactor!: use RSA directly, drop PGPy #1

merged 8 commits into from
Dec 30, 2024

Conversation

JarbasAl
Copy link
Member

@JarbasAl JarbasAl commented Dec 30, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new GitHub Actions workflow for automating stable releases.
    • Added a workflow to automate the addition of labels to pull requests.
    • Enhanced the HandShake class with RSA encryption and signatures.
  • Bug Fixes

    • Updated various example scripts to display secret keys in hexadecimal format for improved readability.
  • Refactor

    • Replaced PGP-based cryptographic operations with RSA-based encryption and signatures.
    • Removed version bumping and management scripts.
  • Dependency Changes

    • Removed PGPy library.
    • Added pycryptodomex library.

Copy link

coderabbitai bot commented Dec 30, 2024

Warning

Rate limit exceeded

@JarbasAl has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 23 minutes and 53 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 1eeda01 and 11498db.

📒 Files selected for processing (2)
  • poorman_handshake/asymmetric/__init__.py (1 hunks)
  • poorman_handshake/asymmetric/utils.py (1 hunks)

Walkthrough

This pull request introduces significant changes to the poorman_handshake library, including the removal of various GitHub Actions workflows related to version management and publishing. The project transitions from PGP-based cryptography to RSA-based cryptography, with updates to utility functions and example scripts. Additionally, new workflows for automating label addition and stable releases are added, while several version management scripts are deleted.

Changes

File/Path Change Summary
.github/workflows/publish_alpha.yml Deleted workflow file for publishing alpha releases to PyPI.
.github/workflows/dev2master.yml Deleted workflow file for promoting code from dev to master.
.github/workflows/publish_build.yml Deleted workflow file for publishing build releases to PyPI.
.github/workflows/publish_major.yml Deleted workflow file for publishing major releases to PyPI.
.github/workflows/publish_minor.yml Deleted workflow file for publishing minor releases to PyPI.
.github/workflows/conventional-label.yaml Added new workflow for automating label addition to pull requests.
.github/workflows/publish_stable.yml Added new workflow for automating the release of stable versions.
.github/workflows/release_workflow.yml Added new workflow for automating the release process on pull request merges.
examples/*_handshake.py Updated success message printing to use bob.secret.hex() for hexadecimal representation.
examples/key_handling.py Deleted file with private key export functionality.
poorman_handshake/asymmetric/__init__.py Significant updates to HandShake class with RSA encryption, signatures, and new methods.
poorman_handshake/asymmetric/utils.py Replaced PGP-based key management with RSA-focused cryptographic functions.
poorman_handshake/symmetric/utils.py Updated generate_iv and hashing mechanisms to use Cryptodome modules.
requirements.txt Removed PGPy dependency, added pycryptodomex.
scripts/bump_*.py Deleted various version management scripts.

Sequence Diagram

sequenceDiagram
    participant Alice
    participant Bob
    participant RSA_Util

    Alice->>RSA_Util: Generate Key Pair
    Bob->>RSA_Util: Generate Key Pair
    Alice->>Bob: Generate Handshake (Encrypt Secret)
    Bob->>RSA_Util: Verify Handshake
    Bob->>Bob: Decrypt Shared Secret
    Bob-->>Alice: Confirm Handshake
Loading

Poem

🐰 A Cryptographic Hop! 🔐

RSA keys dance with might,
PGP fades into the night,
Secrets hex'd with rabbit glee,
Encryption's new melody!

Cryptographic carrots, yum! 🥕


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (9)
poorman_handshake/symmetric/utils.py (1)

5-7: Docstring mismatch for generate_iv.
The docstring states “Generate a random string of letters and digits,” but the implementation returns random bytes. Consider updating the docstring to reflect the actual return type and usage.

 def generate_iv(key_length=8):
-    """Generate a random string of letters and digits """
+    """Generate random bytes of specified length"""
     return get_random_bytes(key_length)
poorman_handshake/asymmetric/utils.py (3)

9-26: Potential file I/O error handling in export_RSA_key.
Currently, if the file path is invalid or unwritable, the function will raise an exception. Consider adding try-except or clarifying in docstrings that an I/O exception may occur.


28-40: Encourage error handling for file not found in load_RSA_key.
Similar to export_RSA_key, you may want to add a brief note on possible I/O exceptions when the file does not exist or is unreadable.


121-147: verify_RSA: Balanced approach to signature verification.
The logic for adjusting signature_size depending on the form of public_key is clean. Consider clarifying the docstring around possible ValueError or TypeError.

poorman_handshake/asymmetric/__init__.py (5)

54-62: export_private_key: Delegates to utilities properly.
Implementation is consistent. Could consider clarifying docstrings about overwriting existing files.


65-75: pubkey property returns PEM string.
Looks great. Suggest raising an exception or returning an empty string if self.private_key is missing. Current code returns None in that scenario.


114-133: verify method: Good separation of signature from ciphertext.
Implementation is clean. As a future improvement, consider returning an error message or raising an exception if verification fails.


134-145: receive_and_verify: Good orchestrator method.
Calls verify first, then receive_handshake. Consider returning the handshake result or success/failure for better clarity in external usage.


152-161: HalfHandShake.receive_handshake: Decrypts without XOR.
This approach replaces self.secret directly, in contrast to the parent class’s XOR usage. The difference in design seems intentional but might create confusion. Document each approach’s difference explicitly.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9853a58 and d155cd3.

📒 Files selected for processing (18)
  • .github/workflows/publish_alpha.yml (1 hunks)
  • examples/half_handshake.py (1 hunks)
  • examples/key_handling.py (0 hunks)
  • examples/simple_handshake.py (1 hunks)
  • examples/simple_mitm.py (1 hunks)
  • examples/static_handshake.py (1 hunks)
  • examples/static_mitm.py (1 hunks)
  • examples/tofu_handshake.py (1 hunks)
  • examples/tofu_mitm.py (1 hunks)
  • poorman_handshake/asymmetric/__init__.py (1 hunks)
  • poorman_handshake/asymmetric/utils.py (1 hunks)
  • poorman_handshake/symmetric/utils.py (2 hunks)
  • requirements.txt (1 hunks)
  • scripts/bump_alpha.py (0 hunks)
  • scripts/bump_build.py (0 hunks)
  • scripts/bump_major.py (0 hunks)
  • scripts/bump_minor.py (0 hunks)
  • scripts/remove_alpha.py (0 hunks)
💤 Files with no reviewable changes (6)
  • examples/key_handling.py
  • scripts/bump_alpha.py
  • scripts/remove_alpha.py
  • scripts/bump_build.py
  • scripts/bump_major.py
  • scripts/bump_minor.py
✅ Files skipped from review due to trivial changes (3)
  • requirements.txt
  • .github/workflows/publish_alpha.yml
  • examples/simple_mitm.py
🔇 Additional comments (19)
poorman_handshake/symmetric/utils.py (2)

1-2: Use consistent imports for Cryptodome.
Looks good. The transition from hashlib to Cryptodome.Hash and usage of get_random_bytes is consistent with the new RSA-based design.


18-18: Verify usage of SHA256.new.
Using SHA256.new(iv + text.encode("utf-8")) is appropriate, but confirm that all upstream calls handle the resulting digest properly and that the code does not rely on the old hashlib approach.

poorman_handshake/asymmetric/utils.py (6)

1-7: Imports alignment and library usage.
The chosen Cryptodome modules and typing utilities look properly imported. This sets up the RSA-based workflow correctly.


42-56: Key size configurability in create_RSA_key.
Providing a default key size of 2048 is good. For specialized use cases (e.g., heavier security or performance constraints), users can pass a different size. This function looks clean.


58-77: encrypt_RSA: Potential large message handling caution.
RSA encryption has inherent limits on input size (must be smaller than key size minus padding overhead). Consider clarifying that large messages should be encrypted with a symmetric key instead, or docstring clarification.


79-98: decrypt_RSA: Good direct counterpart to encrypt_RSA.
Implementation is straightforward and consistent with the PKCS1_OAEP usage. No major concerns.


100-119: sign_RSA: Good use of PSS.
The usage of PSS for digital signatures is a recommended secure practice. Implementation is sound.


149-157: Demonstration block.
The example usage of RSA generation, encryption, decryption, and signing flows nicely. It might be helpful to print or log each step for educational purposes in the demonstration.

poorman_handshake/asymmetric/__init__.py (5)

28-35: Constructor handles new key creation or loading well.
Using isfile(path) is a sensible check. If the path does not exist, a fresh key is generated. Ensure that any I/O and file permission errors are surfaced or handled.


45-51: load_private: Good delegation to load_RSA_key.
Straightforward approach. No concerns beyond potential file I/O issues.


76-91: generate_handshake: Creates and signs handshake.
Encryption + signing is an excellent approach. Ensure the caller has loaded the correct public key into self.target_key if pub is not provided.


92-100: load_public: Simple public key import.
Implementation is correct. Could also add error handling or docstring notes if the key is invalid.


101-113: receive_handshake: XOR usage highlight.
You’re XORing the newly decrypted secret with self.secret. Confirm that this “combined secret” design is intentional, as it changes each handshake step. If the code intended to replace self.secret, remove the XOR.

examples/simple_handshake.py (1)

28-28: Hex-encoding secrets.
Printing bob.secret.hex() improves clarity and ensures raw binary data won’t break terminals. This looks good.

examples/half_handshake.py (1)

26-26: Printing alice.secret in hex.
Consistent with other examples. This is a helpful change for readability and debugging.

examples/static_handshake.py (1)

29-29: **Using .hex() for consistent secret output **
Printing the secret in hexadecimal format improves readability and consistency with other examples.

examples/static_mitm.py (1)

29-29: **Hexadecimal display standardizes secret representation **
Converting the secret to hex ensures a uniform output convention across the codebase.

examples/tofu_handshake.py (1)

41-41: **Aligning secret output format with .hex() usage **
This minor change is consistent with the broader approach of printing secrets in a standardized hexadecimal form.

examples/tofu_mitm.py (1)

42-42: **Hexadecimal format maintains consistency and readability **
Using .hex() here complements the rest of the updated handshake examples, ensuring uniform secret output.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🧹 Nitpick comments (3)
.github/workflows/conventional-label.yaml (1)

10-10: Consider these minor improvements:

  1. Pin to a specific SHA for better reproducibility
  2. Add a newline at the end of file

Apply this diff:

-      - uses: bcoe/conventional-release-labels@v1
+      - uses: bcoe/[email protected]  # or specific SHA
+
🧰 Tools
🪛 yamllint (1.35.1)

[error] 10-10: no new line character at the end of file

(new-line-at-end-of-file)

.github/workflows/release_workflow.yml (1)

1-108: Well-structured release automation workflow with room for improvement.

The workflow effectively handles the complete release process from alpha to stable versions. The job dependencies and conditions are properly set up, ensuring a sequential and controlled release process.

Consider these architectural improvements:

  1. Add status checks before PyPI publishing
  2. Include automated changelog generation
  3. Add automated version validation
  4. Consider implementing rollback procedures

Would you like me to provide implementation details for any of these improvements?

🧰 Tools
🪛 actionlint (1.7.4)

26-26: the runner of "actions/checkout@v2" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)


42-42: the runner of "actions/checkout@v2" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)


47-47: the runner of "actions/setup-python@v1" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)


54-54: workflow command "set-output" was deprecated. use echo "{name}={value}" >> $GITHUB_OUTPUT instead: https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions

(deprecated-commands)


71-71: the runner of "actions/checkout@v3" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)


76-76: the runner of "actions/setup-python@v2" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)


82-82: shellcheck reported issue in this script: SC2086:info:2:28: Double quote to prevent globbing and word splitting

(shellcheck)


94-94: shellcheck reported issue in this script: SC2034:warning:2:1: BRANCH_NAME appears unused. Verify use (or export if used externally)

(shellcheck)

.github/workflows/publish_stable.yml (1)

1-58: Consider adding explicit permissions.

For enhanced security, consider adding explicit permissions to limit the workflow's scope:

Add this configuration at the workflow level:

name: Stable Release
on:
  push:
    branches: [master]
  workflow_dispatch:

+permissions:
+  contents: write    # for checkout and pushing changes
+  packages: write   # for publishing packages
+  pull-requests: read # for reading PR information
🧰 Tools
🪛 actionlint (1.7.4)

22-22: the runner of "actions/checkout@v2" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)


27-27: the runner of "actions/setup-python@v1" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)


34-34: workflow command "set-output" was deprecated. use echo "{name}={value}" >> $GITHUB_OUTPUT instead: https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions

(deprecated-commands)


50-50: the runner of "actions/checkout@v2" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)

🪛 yamllint (1.35.1)

[error] 58-58: no new line character at the end of file

(new-line-at-end-of-file)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d155cd3 and f59bebc.

📒 Files selected for processing (8)
  • .github/workflows/conventional-label.yaml (1 hunks)
  • .github/workflows/dev2master.yml (0 hunks)
  • .github/workflows/publish_alpha.yml (0 hunks)
  • .github/workflows/publish_build.yml (0 hunks)
  • .github/workflows/publish_major.yml (0 hunks)
  • .github/workflows/publish_minor.yml (0 hunks)
  • .github/workflows/publish_stable.yml (1 hunks)
  • .github/workflows/release_workflow.yml (1 hunks)
💤 Files with no reviewable changes (5)
  • .github/workflows/publish_build.yml
  • .github/workflows/publish_alpha.yml
  • .github/workflows/dev2master.yml
  • .github/workflows/publish_minor.yml
  • .github/workflows/publish_major.yml
🧰 Additional context used
🪛 yamllint (1.35.1)
.github/workflows/conventional-label.yaml

[error] 10-10: no new line character at the end of file

(new-line-at-end-of-file)

.github/workflows/publish_stable.yml

[error] 58-58: no new line character at the end of file

(new-line-at-end-of-file)

🪛 actionlint (1.7.4)
.github/workflows/release_workflow.yml

26-26: the runner of "actions/checkout@v2" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)


42-42: the runner of "actions/checkout@v2" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)


47-47: the runner of "actions/setup-python@v1" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)


54-54: workflow command "set-output" was deprecated. use echo "{name}={value}" >> $GITHUB_OUTPUT instead: https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions

(deprecated-commands)


71-71: the runner of "actions/checkout@v3" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)


76-76: the runner of "actions/setup-python@v2" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)


82-82: shellcheck reported issue in this script: SC2086:info:2:28: Double quote to prevent globbing and word splitting

(shellcheck)


94-94: shellcheck reported issue in this script: SC2034:warning:2:1: BRANCH_NAME appears unused. Verify use (or export if used externally)

(shellcheck)

.github/workflows/publish_stable.yml

22-22: the runner of "actions/checkout@v2" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)


27-27: the runner of "actions/setup-python@v1" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)


34-34: workflow command "set-output" was deprecated. use echo "{name}={value}" >> $GITHUB_OUTPUT instead: https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions

(deprecated-commands)


50-50: the runner of "actions/checkout@v2" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)

🔇 Additional comments (4)
.github/workflows/conventional-label.yaml (2)

1-10: LGTM! The workflow configuration is secure and well-structured.

The workflow is correctly configured to automatically label PRs using conventional commit standards. The use of pull_request_target is appropriate here as the workflow only uses a trusted action for labeling.

🧰 Tools
🪛 yamllint (1.35.1)

[error] 10-10: no new line character at the end of file

(new-line-at-end-of-file)


3-4: Verify the event trigger configuration.

The workflow uses pull_request_target which runs with repository token access. While this is safe for the current usage (only labeling), ensure that any future modifications to this workflow maintain security best practices.

Run this script to check for other workflows using pull_request_target:

✅ Verification successful

Let me check the actual implementation of the workflow to ensure it's following security best practices.


pull_request_target usage is secure in this workflow

The workflow is correctly configured and follows security best practices:

  • It's the only workflow using pull_request_target in the repository
  • It exclusively uses a trusted third-party action (bcoe/conventional-release-labels@v1) for labeling
  • The workflow doesn't checkout any code from the pull request
  • No repository contents are processed directly, eliminating the risk of executing untrusted code
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for other workflows using pull_request_target to ensure consistent security practices

# Search for pull_request_target in workflow files
echo "Checking other workflows using pull_request_target:"
rg -l "pull_request_target" .github/workflows/

Length of output: 201


Script:

#!/bin/bash
# Check the implementation details of the conventional-label workflow
cat .github/workflows/conventional-label.yaml

Length of output: 266

.github/workflows/release_workflow.yml (1)

1-7: LGTM! Well-structured workflow trigger configuration.

The workflow trigger is properly configured to run only when PRs are closed (merged) to the dev branch.

.github/workflows/publish_stable.yml (1)

1-6: LGTM: Workflow triggers are appropriately configured.

The workflow triggers are well-configured for stable releases, allowing both automated (push to master) and manual (workflow_dispatch) execution.

.github/workflows/release_workflow.yml Show resolved Hide resolved
.github/workflows/release_workflow.yml Show resolved Hide resolved
.github/workflows/release_workflow.yml Show resolved Hide resolved
.github/workflows/release_workflow.yml Show resolved Hide resolved
.github/workflows/publish_stable.yml Show resolved Hide resolved
.github/workflows/publish_stable.yml Show resolved Hide resolved
.github/workflows/publish_stable.yml Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f59bebc and b338291.

📒 Files selected for processing (1)
  • poorman_handshake/asymmetric/__init__.py (1 hunks)
🔇 Additional comments (1)
poorman_handshake/asymmetric/__init__.py (1)

95-99: Verify the cryptographic protocol implementation.

The handshake protocol implementation has potential security considerations:

  1. The shared secret generation uses a secure random number generator (good!)
  2. However, the protocol might be vulnerable to replay attacks as it lacks a timestamp or nonce
  3. The signature is concatenated with the ciphertext without a clear delimiter

Consider enhancing the protocol security by:

  1. Adding a nonce or timestamp
  2. Using a standardized format (like ASN.1) for message structure
  3. Implementing perfect forward secrecy

poorman_handshake/asymmetric/__init__.py Show resolved Hide resolved
poorman_handshake/asymmetric/__init__.py Outdated Show resolved Hide resolved
poorman_handshake/asymmetric/__init__.py Outdated Show resolved Hide resolved
poorman_handshake/asymmetric/__init__.py Outdated Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
poorman_handshake/asymmetric/__init__.py (2)

31-38: Validate RSA key size against security standards

The default key size of 2048 bits meets minimum security requirements, but consider:

  1. Adding validation to prevent keys smaller than 2048 bits
  2. Documenting that 4096 bits is recommended for long-term security
 def __init__(self, path: str = None, key_size: int = 2048):
+    if key_size < 2048:
+        raise ValueError("RSA key size must be at least 2048 bits for security")
     self.private_key = None

53-54: Use exception chaining for better error tracking

When re-raising exceptions, use exception chaining to preserve the original traceback.

-                except Exception as e:
-                    raise ValueError(f"Failed to handle invalid key file: {e}")
+                except Exception as e:
+                    raise ValueError(f"Failed to handle invalid key file") from e
🧰 Tools
🪛 Ruff (0.8.2)

54-54: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b338291 and 1eeda01.

📒 Files selected for processing (2)
  • poorman_handshake/asymmetric/__init__.py (1 hunks)
  • requirements.txt (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • requirements.txt
🧰 Additional context used
🪛 Ruff (0.8.2)
poorman_handshake/asymmetric/__init__.py

54-54: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

🔇 Additional comments (2)
poorman_handshake/asymmetric/__init__.py (2)

126-130: Review the secret combination logic

The XOR operation for combining secrets might not provide the best security properties:

  1. XOR is sensitive to bit flips
  2. If an attacker obtains one secret, they can influence the final combined secret

Consider using a more robust key derivation function:

-self.secret = bytes(a ^ b for a, b in zip(self.secret, decrypted))
+from cryptography.hazmat.primitives import hashes
+from cryptography.hazmat.primitives.kdf.hkdf import HKDF
+self.secret = HKDF(
+    algorithm=hashes.SHA256(),
+    length=32,
+    salt=None,
+    info=b"handshake-key",
+).derive(self.secret + decrypted)

166-168: Document security implications of HalfHandShake

The HalfHandShake class skips the secret combination step, which has security implications:

  1. The docstring should explicitly warn about the reduced security properties
  2. Consider adding a warning when this class is instantiated
 class HalfHandShake(HandShake):
     """
     A simpler handshake implementation where the shared secret is directly decrypted.
+
+    Warning:
+        This implementation provides weaker security guarantees compared to the full HandShake:
+        - No perfect forward secrecy
+        - Vulnerable to replay attacks
+        - Should only be used in specific scenarios where these trade-offs are acceptable
     """
+
+    def __init__(self, *args, **kwargs):
+        import warnings
+        warnings.warn(
+            "HalfHandShake provides reduced security. "
+            "Use the full HandShake implementation unless you have specific requirements.",
+            category=SecurityWarning
+        )
+        super().__init__(*args, **kwargs)

poorman_handshake/asymmetric/__init__.py Show resolved Hide resolved
@JarbasAl JarbasAl merged commit 0355094 into dev Dec 30, 2024
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant