Skip to content
SecureKhan
Go back

PKI & Certificates for Pentesters: How Digital Trust Works

PKI & Certificates for Pentesters

TL;DR: PKI is the trust infrastructure that makes HTTPS work. Certificates prove identity using cryptographic signatures. Misconfigurations and attacks against PKI can lead to MITM, impersonation, and data theft.


Table of Contents

Open Table of Contents

Quick Reference

Essential Commands

CommandPurposeExample
openssl s_clientConnect and view certopenssl s_client -connect host:443
openssl x509Parse certificateopenssl x509 -in cert.pem -text
openssl verifyVerify cert chainopenssl verify -CAfile ca.pem cert.pem
openssl reqCreate CSRopenssl req -new -key key.pem -out csr.pem
certutil (Windows)Certificate operationscertutil -dump cert.pem

Certificate Validation Checks

CheckWhat It VerifiesFailure =
Chain of TrustSigned by trusted CAUntrusted certificate
ExpirationNot Before/After datesExpired/not yet valid
HostnameCN or SAN matchesWrong certificate
RevocationCRL or OCSP statusCertificate revoked
Key UsageAllowed operationsInvalid use
SignatureCryptographic validityTampered certificate

Common Certificate Ports

PortProtocolCertificate Use
443HTTPSWeb server authentication
636LDAPSLDAP over TLS
993IMAPSEmail over TLS
995POP3SEmail over TLS
8443HTTPS-altAlternative web
3389RDPRemote desktop (optional)

Why PKI Matters for Pentesters

Security Impact

PKI provides three critical security properties:

PropertyHow PKI Provides ItAttack If Broken
AuthenticationCertificates prove identityImpersonation
ConfidentialityPublic key encryptionEavesdropping
IntegrityDigital signaturesData tampering

Real-World PKI Breaches

IncidentWhat HappenedImpact
DigiNotar (2011)CA compromise, fake certsIranian surveillance
Comodo (2011)RA breach, fake certsGoogle, Yahoo impersonation
Symantec (2017)Improper validationBrowsers distrust
Let’s Encrypt (2020)Bug in issuance3M certs revoked
Kazakhstan (2020)Govt-mandated root CANational MITM capability

What Pentesters Test

  1. Certificate validation - Does client properly verify?
  2. Trust boundaries - Are internal CAs trusted externally?
  3. Expired/weak certs - Old or misconfigured certificates
  4. Pinning bypass - Can we intercept pinned connections?
  5. Private key exposure - Keys in source code, backups
  6. CT monitoring - Are all issued certs visible?

How PKI Works

TL;DR: PKI uses asymmetric cryptography and trusted third parties (CAs) to establish identity without prior relationship.

The Trust Problem

Without PKI:
┌─────────┐         "I'm really bank.com"         ┌─────────┐
│  User   │ ◄────────────────────────────────────►│ Attacker│
│         │         How do you verify?            │         │
└─────────┘                                       └─────────┘

With PKI:
┌─────────┐                                       ┌─────────┐
│  User   │◄──────── Certificate ─────────────────│ Server  │
│         │    Signed by DigiCert CA              │         │
└────┬────┘                                       └─────────┘

     │  Verifies signature using
     │  DigiCert public key
     │  (already trusted in browser)

┌─────────────────────────────────────────────────────────────┐
│  "This certificate is valid and signed by a trusted CA"    │
│  "The server is really bank.com"                           │
└─────────────────────────────────────────────────────────────┘

PKI Components

ComponentRoleExample
Certificate Authority (CA)Issues and signs certificatesDigiCert, Let’s Encrypt
Registration Authority (RA)Verifies identity before issuancePart of CA
CertificateBinds identity to public keyX.509 certificate
Certificate RevocationInvalidates compromised certsCRL, OCSP
Trust StorePre-trusted root CA certificatesBrowser/OS trust store

PKI Operation Flow

1. Server generates key pair
   ┌──────────┐
   │ Server   │ ──► Private Key (keep secret!)
   │          │ ──► Public Key
   └──────────┘

2. Server creates Certificate Signing Request (CSR)
   ┌──────────┐     CSR contains:
   │ Server   │ ──► - Public Key
   │          │     - Organization info
   └──────────┘     - Domain name

3. CA verifies and issues certificate
   ┌──────────┐         ┌──────────┐
   │ Server   │ ──CSR──►│    CA    │
   │          │◄─Cert───│          │
   └──────────┘         └──────────┘

4. Server uses certificate
   ┌──────────┐         ┌──────────┐
   │ Client   │◄─Cert───│  Server  │
   │          │         │          │
   └──────────┘         └──────────┘

       ▼ Validates against trusted CAs

Certificate Authority Hierarchy

TL;DR: CAs are organized in a hierarchy. Root CAs sign intermediate CAs, which sign end-entity certificates.

CA Chain Structure

┌───────────────────────────────────────────────────────────────┐
│                        ROOT CA                                 │
│                   (Self-signed, offline)                       │
│                                                                │
│   Subject: CN=DigiCert Global Root G2                         │
│   Issuer:  CN=DigiCert Global Root G2 (same = self-signed)    │
│   Validity: 25 years                                          │
│                                                                │
│   Location: Browser/OS trust store                            │
└───────────────────────────┬───────────────────────────────────┘
                            │ Signs

┌───────────────────────────────────────────────────────────────┐
│                    INTERMEDIATE CA                             │
│               (Signed by Root, online)                         │
│                                                                │
│   Subject: CN=DigiCert SHA2 Extended Validation Server CA     │
│   Issuer:  CN=DigiCert Global Root G2                         │
│   Validity: 10 years                                          │
│                                                                │
│   Location: Sent by server in TLS handshake                   │
└───────────────────────────┬───────────────────────────────────┘
                            │ Signs

┌───────────────────────────────────────────────────────────────┐
│                    END-ENTITY CERT                             │
│              (The actual server certificate)                   │
│                                                                │
│   Subject: CN=www.example.com                                 │
│   Issuer:  CN=DigiCert SHA2 Extended Validation Server CA     │
│   Validity: 1-2 years                                         │
│                                                                │
│   Location: Server                                            │
└───────────────────────────────────────────────────────────────┘

Why Intermediate CAs?

ReasonExplanation
SecurityRoot stays offline, reducing compromise risk
ContainmentCompromise of intermediate limits damage
FlexibilityDifferent intermediates for different purposes
RevocationCan revoke intermediate without affecting root

Chain Validation

Client receives certificate chain:
[End-Entity] ← [Intermediate] ← [Root in trust store]

Validation:
1. End-Entity signed by Intermediate? ✓
2. Intermediate signed by Root? ✓
3. Root in trust store? ✓
4. All dates valid? ✓
5. Hostname matches? ✓
6. Not revoked? ✓

Result: TRUSTED

X.509 Certificates Explained

TL;DR: X.509 is the standard format for digital certificates. Understanding the fields helps you identify misconfigurations.

Certificate Structure

┌─────────────────────────────────────────────────────────────────┐
│                    X.509 Certificate                            │
├─────────────────────────────────────────────────────────────────┤
│ Version: 3 (0x2)                                                │
│                                                                 │
│ Serial Number: 0a:bc:de:12:34:56:78:90                         │
│                                                                 │
│ Signature Algorithm: sha256WithRSAEncryption                    │
│                                                                 │
│ Issuer: C=US, O=DigiCert Inc, CN=DigiCert SHA2 CA              │
│                                                                 │
│ Validity:                                                       │
│     Not Before: Jan  1 00:00:00 2024 GMT                       │
│     Not After:  Dec 31 23:59:59 2025 GMT                       │
│                                                                 │
│ Subject: C=US, ST=CA, L=SF, O=Example Inc, CN=www.example.com  │
│                                                                 │
│ Subject Public Key Info:                                        │
│     Public Key Algorithm: rsaEncryption                         │
│     RSA Public Key: (2048 bit)                                  │
│         Modulus: 00:ab:cd:ef...                                 │
│         Exponent: 65537 (0x10001)                               │
│                                                                 │
│ X509v3 Extensions:                                              │
│     Basic Constraints: CA:FALSE                                 │
│     Key Usage: Digital Signature, Key Encipherment              │
│     Extended Key Usage: TLS Web Server Authentication           │
│     Subject Alternative Name:                                   │
│         DNS:www.example.com                                     │
│         DNS:example.com                                         │
│         DNS:*.example.com                                       │
│     Authority Key Identifier: ...                               │
│     Subject Key Identifier: ...                                 │
│     CRL Distribution Points: http://crl.digicert.com/...        │
│     Authority Information Access:                               │
│         OCSP: http://ocsp.digicert.com                          │
│         CA Issuers: http://cacerts.digicert.com/...             │
│                                                                 │
│ Signature Algorithm: sha256WithRSAEncryption                    │
│ Signature: 12:34:56:78:ab:cd:ef...                              │
└─────────────────────────────────────────────────────────────────┘

Key Fields Explained

FieldPurposePentester Interest
Serial NumberUnique identifierIdentify specific cert
IssuerWho signed itVerify trusted CA
SubjectWho it belongs toVerify correct entity
ValidityNot Before/AfterCheck expiration
Public KeySubject’s public keyCheck key strength
SANSubject Alternative NamesAll valid hostnames
Key UsageAllowed operationsCertificate misuse
Basic ConstraintsCA:TRUE/FALSEFake CA detection
CRL/OCSPRevocation check URLsVerify not revoked

Subject Alternative Name (SAN)

Modern certificates use SAN for hostname validation:

Subject Alternative Name:
    DNS:example.com
    DNS:www.example.com
    DNS:*.example.com          <- Wildcard
    DNS:mail.example.com
    IP Address:93.184.216.34   <- IP can be in SAN

Important: CN (Common Name) is deprecated for hostname. SAN is required.


Certificate Validation Process

TL;DR: Clients validate certificates through a series of checks. Failures should reject the connection (but often don’t).

Validation Steps

┌─────────────────────────────────────────────────────────────────┐
│                  Certificate Validation                          │
└─────────────────────────────────────────────────────────────────┘

          ┌───────────────────┴───────────────────┐
          ▼                                       ▼
┌──────────────────┐                   ┌──────────────────┐
│ 1. Chain Valid?  │                   │ 4. Hostname OK?  │
│                  │                   │                  │
│ - Signatures OK  │                   │ - CN or SAN      │
│ - Chain complete │                   │   matches URL    │
│ - Root trusted   │                   └────────┬─────────┘
└────────┬─────────┘                            │
         │                                      │
         ▼                                      ▼
┌──────────────────┐                   ┌──────────────────┐
│ 2. Dates Valid?  │                   │ 5. Not Revoked?  │
│                  │                   │                  │
│ - Not Before     │                   │ - Check CRL      │
│ - Not After      │                   │ - Check OCSP     │
└────────┬─────────┘                   └────────┬─────────┘
         │                                      │
         ▼                                      ▼
┌──────────────────┐                   ┌──────────────────┐
│ 3. Key Usage OK? │                   │ 6. Constraints?  │
│                  │                   │                  │
│ - digitalSign    │                   │ - CA:FALSE for   │
│ - keyEncipherment│                   │   end-entity     │
└────────┬─────────┘                   └────────┬─────────┘
         │                                      │
         └──────────────┬───────────────────────┘

              ┌──────────────────┐
              │   All Passed?    │
              ├──────────────────┤
              │ YES → TRUSTED    │
              │ NO  → REJECT     │
              └──────────────────┘

Common Validation Failures

FailureError MessageCause
Chain incompleteUnable to verifyMissing intermediate
Untrusted rootSelf-signed certNot in trust store
ExpiredCertificate has expiredPast Not After date
Not yet validCertificate not yet validBefore Not Before
Hostname mismatchHostname doesn’t matchWrong cert or typo
RevokedCertificate revokedOn CRL or OCSP revoked
Weak signatureInsecure algorithmMD5 or SHA1 signature

Certificate Types

By Validation Level

TypeValidationVisual IndicatorUse Case
DV (Domain Validated)Domain ownership onlyPadlockBlogs, small sites
OV (Organization Validated)Organization verifiedPadlockBusiness sites
EV (Extended Validation)Extensive verificationPadlock (was green bar)Banking, e-commerce

By Scope

TypeCoversExample
Single DomainOne specific domainwww.example.com
Multi-Domain (SAN)Multiple specific domainswww.example.com, api.example.com
WildcardOne level of subdomains*.example.com
Multi-Domain WildcardMultiple wildcards*.example.com, *.example.org

Wildcard Certificate Rules

Certificate: *.example.com

✓ Matches: www.example.com
✓ Matches: api.example.com
✓ Matches: mail.example.com
✗ Doesn't match: example.com (no subdomain)
✗ Doesn't match: sub.www.example.com (multi-level)
✗ Doesn't match: www.example.org (different domain)

By Purpose

TypeKey UsagePurpose
Server AuthTLS Web Server AuthenticationHTTPS servers
Client AuthTLS Web Client AuthenticationClient certificates
Code SigningCode SigningSoftware signatures
Email (S/MIME)Email ProtectionEncrypted email
CA CertificateCertificate Sign, CRL SignIssuing certs

Certificate Formats

Common Formats

FormatExtensionEncodingContains
PEM.pem, .crt, .cerBase64Cert and/or key
DER.der, .cerBinaryCert only
PKCS#7.p7b, .p7cBase64/BinaryCert chain (no key)
PKCS#12.pfx, .p12BinaryCert + private key
JKS.jksBinaryJava keystore

PEM Format

-----BEGIN CERTIFICATE-----
MIIDXTCCAkWgAwIBAgIJAJC1HiIAZAiUMA0Gcx...
... base64 encoded data ...
Rw0NJsU9WRvYvN3MgBLjmgj/AAAAAA==
-----END CERTIFICATE-----

Format Conversion

Conversion Commands
# PEM to DER
openssl x509 -in cert.pem -outform DER -out cert.der

# DER to PEM
openssl x509 -in cert.der -inform DER -outform PEM -out cert.pem

# PEM cert + key to PKCS#12
openssl pkcs12 -export -out cert.pfx -inkey key.pem -in cert.pem -certfile ca.pem

# PKCS#12 to PEM
openssl pkcs12 -in cert.pfx -out cert.pem -nodes

# Extract private key from PKCS#12
openssl pkcs12 -in cert.pfx -nocerts -out key.pem

# Extract certificate from PKCS#12
openssl pkcs12 -in cert.pfx -clcerts -nokeys -out cert.pem

# View PKCS#7 certificates
openssl pkcs7 -in chain.p7b -print_certs

Common Misconfigurations

Testing Checklist

Misconfiguration Matrix

MisconfigurationRiskImpact
Self-signed certHighMITM if client accepts
Expired certMediumUser warnings, MITM if bypassed
Missing intermediateMediumValidation failure
Weak key (<2048 bit)HighFactorization attacks
SHA1 signatureMediumCollision attacks
Wildcard overuseMediumLarger attack surface
Missing revocationLowCan’t revoke if compromised
Wrong hostnameMediumCert for wrong domain
AttackDetectDefend
Self-signed MITMCheck issuerReject self-signed
Expired cert exploitationMonitor expiryAuto-renewal (Let’s Encrypt)
Chain validation bypassTest with curl —cacertSend complete chain
Weak key factoringCheck key sizeUse 2048+ bit keys
Testing Commands
# === Check Certificate Details ===

# View certificate
echo | openssl s_client -connect example.com:443 2>/dev/null | \
    openssl x509 -text -noout

# Check expiration
echo | openssl s_client -connect example.com:443 2>/dev/null | \
    openssl x509 -noout -dates

# Check subject and SANs
echo | openssl s_client -connect example.com:443 2>/dev/null | \
    openssl x509 -noout -subject -ext subjectAltName

# Check key size
echo | openssl s_client -connect example.com:443 2>/dev/null | \
    openssl x509 -noout -text | grep "Public-Key"

# Check signature algorithm
echo | openssl s_client -connect example.com:443 2>/dev/null | \
    openssl x509 -noout -text | grep "Signature Algorithm"

# === Check Certificate Chain ===

# View full chain
openssl s_client -connect example.com:443 -showcerts

# Verify chain
openssl s_client -connect example.com:443 -verify 5

# === Check Revocation ===

# Get OCSP URL
echo | openssl s_client -connect example.com:443 2>/dev/null | \
    openssl x509 -noout -ocsp_uri

# Check OCSP status
openssl s_client -connect example.com:443 -status 2>/dev/null | \
    grep -A 20 "OCSP Response"

Certificate Attacks

1. Self-Signed Certificate MITM

If application accepts self-signed certificates, trivial MITM is possible.

Normal:
[Client] ◄──── Valid Cert (CA signed) ────► [Server]

Attack:
[Client] ◄── Self-Signed Cert ── [Attacker] ◄── Valid Cert ── [Server]

              └── If client accepts, attacker decrypts all traffic
AttackDetectDefend
Present self-signed certCheck issuer is trusted CAReject self-signed
Use attacker CAVerify CA in trust storeCertificate pinning
Exploit validation bypassLog cert warningsProper validation
Attack Commands
# Generate self-signed certificate
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes \
    -subj "/CN=www.target.com"

# Test if server accepts self-signed (as client)
curl -k https://api.target.com  # -k ignores cert errors

# MITM with mitmproxy
mitmproxy --cert cert.pem

2. Null Byte Injection

Older implementations vulnerable to null bytes in CN/SAN.

Certificate CN: www.target.com\0.attacker.com

Vulnerable parser sees: www.target.com
CA validates: www.target.com\0.attacker.com (owned by attacker)
AttackDetectDefend
Null byte in subjectScan for \x00 in certsModern SSL libraries
Bypass hostname checkLog unusual certificatesReject null bytes

3. Certificate Confusion

Using certificate for wrong purpose.

Attack: Use code-signing cert for TLS server
        Use email cert for server auth
        Use CA cert for end-entity

If key usage not checked, impersonation possible.
AttackDetectDefend
Wrong key usageCheck certificate purposeVerify Extended Key Usage
CA cert as server certCheck Basic ConstraintsReject CA:TRUE for servers

4. Private Key Theft

Stolen private keys allow complete impersonation.

Common Exposure Points:

AttackDetectDefend
Extract from source codeScan repos for keysNever commit keys
Memory extractionMonitor for HeartbleedPatch vulnerabilities
Backup theftAudit backup securityEncrypt backups
Detection Commands
# Search for private keys in directory
grep -r "BEGIN RSA PRIVATE KEY" /path/to/search
grep -r "BEGIN PRIVATE KEY" /path/to/search
grep -r "BEGIN EC PRIVATE KEY" /path/to/search

# Search git history
git log -p | grep -A 5 "BEGIN.*PRIVATE KEY"

# Using truffleHog
trufflehog git https://github.com/target/repo

# Using gitleaks
gitleaks detect --source=/path/to/repo

5. CA Compromise

If CA is compromised, all issued certificates are suspect.

Historical CA Compromises:

AttackDetectDefend
Issue fake certsCertificate TransparencyMonitor CT logs
Modify CA systemsAudit CA operationsMulti-party controls
Social engineering CAVerify cert ownershipUse CAA records

6. OCSP Stapling Issues

If OCSP is not checked or stapled, revoked certs may be accepted.

Without OCSP Stapling:
[Client] ──── Check revocation ────► [OCSP Server]

                    May be blocked        │
                    or slow               │

[Client] ◄──── "Still valid" or timeout ──┘

With OCSP Stapling:
[Server] ◄── Fresh OCSP response ── [OCSP Server]

    └── Includes OCSP response in TLS handshake

[Client] ◄── Certificate + OCSP staple ── [Server]
AttackDetectDefend
Use revoked certCheck OCSP statusOCSP Must-Staple
Block OCSP checksMonitor OCSP failuresHard-fail on OCSP error
Testing Commands
# Check OCSP stapling
openssl s_client -connect example.com:443 -status 2>/dev/null | \
    grep -A 100 "OCSP Response"

# If empty, no stapling
# If present, check "Cert Status: good"

# Manual OCSP check
# 1. Get certificate
echo | openssl s_client -connect example.com:443 2>/dev/null | \
    openssl x509 -outform PEM > cert.pem

# 2. Get OCSP URL
openssl x509 -in cert.pem -noout -ocsp_uri

# 3. Query OCSP
openssl ocsp -issuer chain.pem -cert cert.pem \
    -url http://ocsp.digicert.com -resp_text

Certificate Pinning

TL;DR: Pinning hardcodes expected certificate/key in client, preventing MITM even with fake CA-signed certs.

How Pinning Works

Without Pinning:
[Client] trusts any CA-signed cert

     ├── DigiCert CA? ✓ Trust
     ├── Let's Encrypt CA? ✓ Trust
     └── Attacker's fake CA? ✓ Trust (if in trust store)

With Pinning:
[Client] only trusts specific cert/key

     ├── Expected certificate? ✓ Trust
     ├── Different valid cert? ✗ Reject
     └── Attacker's cert? ✗ Reject

Pinning Types

TypeWhat’s PinnedFlexibility
Certificate PinEntire certificateMust update pin on renewal
Public Key PinSubject Public Key InfoSurvives cert renewal
CA PinIntermediate/Root CAOnly that CA can issue

Pinning Implementations

PlatformMethod
iOSInfo.plist, URLSession
AndroidNetwork Security Config
WebPublic-Key-Pins header (deprecated)
OkHttpCertificatePinner
.NETServicePointManager

Bypassing Certificate Pinning

For authorized testing, pinning bypass is often needed.

TechniqueToolPlatform
Frida hooksobjection, frida-scriptsiOS, Android
Xposed modulesSSLUnpinningAndroid
Proxy CA installBurp, mitmproxyAll
Binary patchingapktool, HopperiOS, Android
Debug builds-Development
Bypass Commands
# === Android ===

# Using Frida + objection
objection -g com.target.app explore
> android sslpinning disable

# Using Frida script
frida -U -f com.target.app -l universal-ssl-bypass.js

# Modify APK (network_security_config.xml)
apktool d app.apk
# Edit res/xml/network_security_config.xml
# Add: <certificates src="user"/>
apktool b app -o app-modified.apk
jarsigner -keystore debug.keystore app-modified.apk androiddebugkey

# === iOS ===

# Using objection
objection -g com.target.app explore
> ios sslpinning disable

# Using SSL Kill Switch 2 (jailbroken)
# Install via Cydia

# === General ===

# Install proxy CA
# 1. Export Burp CA
# 2. Install on device
# 3. Trust CA in settings

Certificate Transparency

TL;DR: CT logs publicly record all issued certificates, allowing detection of misissued or malicious certs.

How CT Works

Certificate Issuance:
┌──────────┐         ┌─────────┐         ┌──────────┐
│  CA      │ ──────► │ CT Log  │ ──────► │ SCT      │
│          │  Submit │ Server  │  Return  │ (proof)  │
└──────────┘         └─────────┘         └──────────┘

                          │ Public,
                          │ Append-only

                     ┌─────────┐
                     │ Monitor │ ◄── You can watch for
                     │         │     certs issued for
                     └─────────┘     your domains

TLS Handshake:
[Server] ── Certificate + SCT ──► [Client]


                              Verify SCT is valid
                              (cert was logged)

Using CT for Reconnaissance

CT logs reveal all certificates for a domain:

# Find subdomains via CT logs
curl -s "https://crt.sh/?q=%25.example.com&output=json" | \
    jq -r '.[].name_value' | sort -u

# Using certspotter
curl -s "https://api.certspotter.com/v1/issuances?domain=example.com" | \
    jq -r '.[].dns_names[]' | sort -u

# Useful for:
# - Subdomain enumeration
# - Identifying internal domains
# - Finding staging/dev environments

Monitoring Your Domains

ServiceURLUse
crt.shcrt.shManual search
Cert Spottersslmate.com/certspotterFree monitoring
Facebook CTdevelopers.facebook.com/tools/ctMonitoring
Google Transparencytransparencyreport.google.com/https/certificatesSearch

Testing Certificates

Comprehensive Testing Workflow

1. Retrieve Certificate


2. Check Basic Info
   - Subject, Issuer
   - Validity dates
   - Key size


3. Verify Chain
   - Complete chain?
   - Trusted root?


4. Check Extensions
   - SAN matches hostname?
   - Key usage correct?
   - Basic constraints?


5. Check Revocation
   - OCSP status?
   - CRL status?
   - Stapling enabled?


6. Test Known Issues
   - Weak algorithms?
   - Short key?
   - Expired?

Testing Checklist

CheckCommandPass Criteria
Expirationopenssl x509 -noout -datesFuture date
Key sizeopenssl x509 -text | grep "Public-Key"≥2048 bit RSA
Signatureopenssl x509 -text | grep "Signature Algorithm"SHA256+
Chainopenssl s_client -verify 5Verify return:0
Hostnameopenssl s_client -verify_hostnameOK
OCSPopenssl s_client -statusCert Status: good
Complete Testing Script
#!/bin/bash
# Certificate Testing Script

TARGET=${1:-"example.com"}
PORT=${2:-443}

echo "=== Certificate Test for $TARGET:$PORT ==="

# Get certificate
echo | openssl s_client -connect $TARGET:$PORT -servername $TARGET 2>/dev/null > /tmp/cert_test.txt

# Extract cert
openssl x509 -in /tmp/cert_test.txt -outform PEM > /tmp/cert.pem 2>/dev/null

echo ""
echo "=== Subject ==="
openssl x509 -in /tmp/cert.pem -noout -subject

echo ""
echo "=== Issuer ==="
openssl x509 -in /tmp/cert.pem -noout -issuer

echo ""
echo "=== Validity ==="
openssl x509 -in /tmp/cert.pem -noout -dates

echo ""
echo "=== Key Size ==="
openssl x509 -in /tmp/cert.pem -noout -text | grep "Public-Key:"

echo ""
echo "=== Signature Algorithm ==="
openssl x509 -in /tmp/cert.pem -noout -text | grep "Signature Algorithm" | head -1

echo ""
echo "=== Subject Alternative Names ==="
openssl x509 -in /tmp/cert.pem -noout -ext subjectAltName

echo ""
echo "=== Chain Verification ==="
openssl s_client -connect $TARGET:$PORT -servername $TARGET -verify 5 2>&1 | grep "Verify"

echo ""
echo "=== OCSP Stapling ==="
openssl s_client -connect $TARGET:$PORT -servername $TARGET -status 2>&1 | grep -A 5 "OCSP Response"

# Cleanup
rm -f /tmp/cert_test.txt /tmp/cert.pem

Tools Reference

Command Line

ToolPurposeInstall
opensslAll certificate operationsBuilt-in
testssl.shComprehensive TLS testinggit clone
sslscanQuick certificate scanapt install sslscan
sslyzePython SSL scannerpip install sslyze
certutil (Windows)Windows certificate toolBuilt-in

Online Tools

ToolURLUse
SSL Labsssllabs.com/ssltestFull analysis
crt.shcrt.shCT log search
Cert Spottersslmate.com/certspotterMonitoring
Hardenizehardenize.comSecurity posture

Mobile Testing

ToolPlatformPurpose
objectioniOS/AndroidPinning bypass
FridaiOS/AndroidDynamic instrumentation
apktoolAndroidAPK modification
SSL Kill SwitchiOS (jailbreak)Pinning bypass

Practice Labs

Beginner

ResourceFocus
TryHackMe - PKICertificate basics
HackTheBox AcademyTLS/PKI fundamentals
PortSwigger AcademyCertificate issues

Intermediate

ResourceFocus
PentesterLabCertificate attacks
DVWA with HTTPSTesting methodology
Own CA setupUnderstanding PKI

Create Your Own CA (Lab)

# 1. Create Root CA
openssl genrsa -out rootCA.key 4096
openssl req -x509 -new -key rootCA.key -days 3650 -out rootCA.crt \
    -subj "/CN=My Test Root CA"

# 2. Create Server Key
openssl genrsa -out server.key 2048

# 3. Create CSR
openssl req -new -key server.key -out server.csr \
    -subj "/CN=test.local"

# 4. Create Extension File
cat > server.ext << EOF
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, keyEncipherment
subjectAltName = DNS:test.local, DNS:*.test.local
EOF

# 5. Sign Certificate
openssl x509 -req -in server.csr -CA rootCA.crt -CAkey rootCA.key \
    -CAcreateserial -out server.crt -days 365 -extfile server.ext

# 6. Verify
openssl verify -CAfile rootCA.crt server.crt

Glossary

TermDefinition
CACertificate Authority - issues certificates
CertificateDigital document binding identity to public key
ChainSequence of certificates from end-entity to root
CRLCertificate Revocation List
CSRCertificate Signing Request
CTCertificate Transparency
DERBinary certificate encoding
DV/OV/EVDomain/Organization/Extended Validation
Intermediate CACA signed by root, signs end-entity
OCSPOnline Certificate Status Protocol
PEMBase64 certificate encoding
PKCSPublic Key Cryptography Standards
PinningHardcoding expected certificate/key
Root CATop of trust hierarchy, self-signed
SANSubject Alternative Name
SCTSigned Certificate Timestamp (CT proof)
Trust StoreCollection of trusted root CAs
X.509Certificate format standard

What’s Next?

Now that you understand PKI and certificates:

TopicDescriptionLink
TLS/SSL HandshakeHow certificates are usedTLS Deep Dive
How Email WorksCertificates in email securityComing Soon
Authentication FlowsCertificates in authAuth Flows Guide
Web App PentestingTesting HTTPS applicationsWeb App Pentesting Guide

Summary

PKI and certificates are fundamental to secure communications:

  1. Trust Hierarchy - Root → Intermediate → End-entity
  2. Validation - Chain, dates, hostname, revocation, key usage
  3. Common Issues - Self-signed, expired, weak keys, missing chain
  4. Attacks - MITM with fake certs, private key theft, CA compromise
  5. Pinning - Prevents MITM even with valid fake certs
  6. CT - Public logging enables monitoring and recon

Pentester Takeaways:


Found this guide helpful? Check out the other posts in the SecureKhan penetration testing series.


Share this post on:

Previous Post
Web Application Pentesting: The Complete Beginner's Guide
Next Post
Encoding vs Encryption vs Hashing: A Pentester's Guide