-
Notifications
You must be signed in to change notification settings - Fork 75
Add certificate parsing to webserver plugins #1415
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
Merged
Merged
Changes from 7 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
b382f4c
Add certificate parsing to webserver plugins
JSCU-CNI 28fb58a
Merge branch 'main' into webserver-certs
JSCU-CNI 6e7d693
implement review feedback
JSCU-CNI edf2548
rename (untested) ual field to prevent field type conflict
JSCU-CNI 734b5aa
Merge branch 'main' into webserver-certs
JSCU-CNI 97ca4ae
guard asn1 import
JSCU-CNI eea5d3d
Merge branch 'main' into webserver-certs
JSCU-CNI 1f9b66a
workaround for serial_number varint field
JSCU-CNI 7cc0f56
Merge branch 'main' into webserver-certs
Schamper d3ed9cd
Merge branch 'main' into webserver-certs
Schamper 82f9193
Fix paths on Windows
Schamper File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import base64 | ||
| import binascii | ||
| import hashlib | ||
| from pathlib import Path | ||
|
|
||
| from flow.record import RecordDescriptor | ||
|
|
||
| try: | ||
| from asn1crypto import pem, x509 | ||
|
|
||
| HAS_ASN1 = True | ||
|
|
||
| except ImportError: | ||
| HAS_ASN1 = False | ||
|
|
||
|
|
||
| COMMON_CERTIFICATE_FIELDS = [ | ||
| ("digest", "fingerprint"), | ||
| ("varint", "serial_number"), | ||
| ("datetime", "not_valid_before"), | ||
| ("datetime", "not_valid_after"), | ||
| ("string", "issuer_dn"), | ||
| ("string", "subject_dn"), | ||
| ("bytes", "pem"), | ||
| ] | ||
|
|
||
| CertificateRecord = RecordDescriptor( | ||
| "certificate", | ||
| [ | ||
| *COMMON_CERTIFICATE_FIELDS, | ||
| ], | ||
| ) | ||
|
|
||
| # Translation layer for asn1crypto names to RFC4514 names. | ||
| # References: https://github.com/wbond/asn1crypto/blob/master/asn1crypto/x509.py @ NameType | ||
| # References: https://github.com/pyca/cryptography/blob/main/src/cryptography/x509/name.py | ||
| NAMEOID_TO_NAME = { | ||
| "common_name": "CN", # 2.5.4.3 | ||
| "country_name": "C", # 2.5.4.6 | ||
| "locality_name": "L", # 2.5.4.7 | ||
| "state_or_province_name": "ST", # 2.5.4.8 | ||
| "street_address": "STREET", # 2.5.4.9 | ||
| "organization_name": "O", # 2.5.4.10 | ||
| "organizational_unit_name": "OU", # 2.5.4.11 | ||
| "domain_component": "DC", # 0.9.2342.192.00300.100.1.25 | ||
| "user_id": "UID", # 0.9.2342.192.00300.100.1.1 | ||
| } | ||
|
|
||
|
|
||
| def compute_pem_fingerprints(pem: str | bytes) -> tuple[str, str, str]: | ||
| """Compute the MD5, SHA-1 and SHA-256 fingerprint hash of a x509 certificate PEM.""" | ||
|
|
||
| if pem is None: | ||
| raise ValueError("No PEM provided") | ||
|
|
||
| if isinstance(pem, bytes): | ||
| pem = pem.decode() | ||
|
|
||
| elif not isinstance(pem, str): | ||
| raise TypeError("Provided PEM is not str or bytes") | ||
|
|
||
| stripped_pem = pem.strip().removeprefix("-----BEGIN CERTIFICATE-----").removesuffix("-----END CERTIFICATE-----") | ||
|
|
||
| try: | ||
| der = base64.b64decode(stripped_pem) | ||
| except binascii.Error as e: | ||
| raise ValueError(f"Unable to parse PEM: {e!s}") from e | ||
|
|
||
| md5 = hashlib.md5(der).hexdigest() | ||
| sha1 = hashlib.sha1(der).hexdigest() | ||
| sha256 = hashlib.sha256(der).hexdigest() | ||
|
|
||
| return md5, sha1, sha256 | ||
|
|
||
|
|
||
| def parse_x509(file: str | bytes | Path) -> CertificateRecord: | ||
| """Parses a PEM file. Returns a CertificateREcord. Does not parse a public key embedded in a x509 certificate.""" | ||
|
|
||
| if isinstance(file, str): | ||
| content = file.encode() | ||
|
|
||
| elif isinstance(file, bytes): | ||
| content = file | ||
|
|
||
| elif isinstance(file, Path) or hasattr(file, "read_bytes"): | ||
| content = file.read_bytes() | ||
|
|
||
| else: | ||
| raise TypeError("Parameter file is not of type str, bytes or Path") | ||
|
|
||
| if not HAS_ASN1: | ||
| raise ValueError("Missing asn1crypto dependency") | ||
|
|
||
| md5, _, _ = compute_pem_fingerprints(content.decode()) | ||
| _, _, der = pem.unarmor(content) | ||
| crt = x509.Certificate.load(der) | ||
|
|
||
| issuer = [] | ||
| for key, value in crt.issuer.native.items(): | ||
| issuer.append(f"{NAMEOID_TO_NAME.get(key, key)}={value}") | ||
|
|
||
| subject = [] | ||
| for key, value in crt.subject.native.items(): | ||
| subject.append(f"{NAMEOID_TO_NAME.get(key, key)}={value}") | ||
|
|
||
| return CertificateRecord( | ||
| not_valid_before=crt.not_valid_before, | ||
| not_valid_after=crt.not_valid_after, | ||
| issuer_dn=",".join(issuer), | ||
| subject_dn=",".join(subject), | ||
| fingerprint=(md5, crt.sha1.hex(), crt.sha256.hex()), | ||
| serial_number=crt.serial_number, | ||
| pem=crt.dump(), | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@yunzheng what are your thoughts on this pattern?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nothing wrong with this pattern. Other options could've been using a webserver metadata RecordDescriptor in combination with GroupedRecord, or using extend_record. But it seems there are already other Webserver-like RecordDescriptors defined so I think this is fine.
It will however, overwrite the
_source,_generatedand_versionfields. But depending if that's an issue or not, can be fixed by usingcert._asdict(exclude=["_source", "_generated", "_version"]).