Commit d152be11 authored by jan.koester's avatar jan.koester
Browse files

needs testing

parent c1f73b94
Loading
Loading
Loading
Loading
+215 −12
Changes for src/crypto/x509.cpp: 215 added lines, 12 removed lines.
Original line number Diff line number Diff line
@@ -50,25 +50,98 @@ bool netplus::x509cert::loadFromFile(const std::string& filePath) {
    return true;
}

size_t netplus::x509cert::parseTLV(const uint8_t* data, size_t size, uint8_t& tag, std::vector<uint8_t>& value) {
std::string netplus::x509cert::decodeOID(const std::vector<uint8_t>& data) {
    if (data.empty()) return "";

    std::stringstream ss;

    // Rule 1: The first byte contains the first two components
    uint8_t first = data[0];
    ss << (int)(first / 40) << "." << (int)(first % 40);

    // Rule 2: Subsequent bytes
    size_t i = 1;
    while (i < data.size()) {
        uint32_t value = 0;
        uint8_t byte;

        // Handle Base-128 variable length encoding
        do {
            if (i >= data.size()) break;
            byte = data[i++];
            // Shift existing value 7 bits and add the new 7 bits
            value = (value << 7) | (byte & 0x7F);
        } while (byte & 0x80); // Keep going if bit 8 is set

        ss << "." << value;
    }

    return ss.str();
}

size_t netplus::x509cert::parseInternal(const uint8_t* data, size_t size, ASN1Node& outNode) {
    if (size < 2) return 0;

    tag = data[0];
    size_t length = data[1];
    size_t headerSize = 2;
    size_t cursor = 0;
    outNode.tag = data[cursor++];

    // Handle "Long Form" length (if length byte has bit 8 set)
    if (length & 0x80) {
        int numOctets = length & 0x7F;
    // 1. Parse Length
    size_t length = data[cursor++];
    if (length & 0x80) { // Long form
        int octets = length & 0x7F;
        length = 0;
        for (int i = 0; i < numOctets; ++i) {
            length = (length << 8) | data[2 + i];
        for (int i = 0; i < octets; ++i) {
            length = (length << 8) | data[cursor++];
        }
        headerSize += numOctets;
    }

    value.assign(data + headerSize, data + headerSize + length);
    return headerSize + length;
    // Safety check: ensure we don't read past the buffer
    if (cursor + length > size) return 0;

    // 2. Extract Data
    outNode.data.assign(data + cursor, data + cursor + length);

    // 3. Recursive Step: If it's a "Constructed" type (Sequence, Set, etc.)
    // Bit 6 of the tag indicates if it's constructed (0x20)
    if (outNode.tag & 0x20) {
        size_t subCursor = 0;
        while (subCursor < length) {
            ASN1Node child;
            size_t bytesRead = parseInternal(outNode.data.data() + subCursor, length - subCursor, child);
            if (bytesRead == 0) break;
            outNode.children.push_back(child);
            subCursor += bytesRead;
        }
    }

    return cursor + length;
}

std::tm netplus::x509cert::parseUTCTime(const std::vector<uint8_t>& data) {
    std::string timeStr(data.begin(), data.end());
    std::tm t = {};

    // Format: YYMMDDHHMMSSZ (13 bytes)
    if (timeStr.length() >= 12) {
        int year = std::stoi(timeStr.substr(0, 2));
        // Adjust year based on RFC 5280 rules
        year += (year < 50) ? 100 : 0; // 100 is offset from 1900 (so 2024 is 124)

        t.tm_year = year;
        t.tm_mon  = std::stoi(timeStr.substr(2, 2)) - 1; // 0-indexed
        t.tm_mday = std::stoi(timeStr.substr(4, 2));
        t.tm_hour = std::stoi(timeStr.substr(6, 2));
        t.tm_min  = std::stoi(timeStr.substr(8, 2));
        t.tm_sec  = std::stoi(timeStr.substr(10, 2));
    }
    return t;
}

bool netplus::x509cert::isExpired(const std::tm& notAfter) {
    std::time_t now = std::time(nullptr);
    std::time_t expiry = std::mktime(const_cast<std::tm*>(&notAfter));

    return std::difftime(now, expiry) > 0;
}

std::string netplus::x509cert::bytesToHex(const std::vector<uint8_t>& bytes) {
@@ -78,3 +151,133 @@ std::string netplus::x509cert::bytesToHex(const std::vector<uint8_t>& bytes) {
    }
    return ss.str();
}

void netplus::x509cert::bytesToBigInt(const std::vector<uint8_t>& bytes, netplus::rsa::bigInt& out) {
    // Initialize out to 0
    out.fromString("0");

    netplus::rsa::bigInt base256;
    base256.fromString("256");

    netplus::rsa::bigInt tempAdd;
    netplus::rsa::bigInt tempMul;

    for (uint8_t b : bytes) {
        // out = (out * 256) + byte
        netplus::rsa::multiply(out, base256, tempMul);

        tempAdd.fromString(std::to_string((int)b));
        netplus::rsa::add(tempMul, tempAdd, out);
    }
}

bool netplus::x509cert::extractPublicKey(netplus::rsa& outRsa) {
    // 1. Root -> TBSCertificate (child 0)
    if (root.children.empty()) return false;
    auto& tbs = root.children[0];

    // 2. TBSCertificate -> SubjectPublicKeyInfo (child 6)
    if (tbs.children.size() < 7) return false;
    auto& pubKeyInfo = tbs.children[6];

    // 3. Find the BitString (Tag 0x03)
    for (auto& node : pubKeyInfo.children) {
        if (node.tag == 0x03) {
            // RSA Public Key is a nested Sequence inside the BitString
            // Skip the first byte (unused bits, usually 0)
            ASN1Node rsaKeyPackage;
            if (parseInternal(node.data.data() + 1, node.data.size() - 1, rsaKeyPackage)) {

                if (rsaKeyPackage.children.size() >= 2) {
                    netplus::rsa::bigInt n, e;

                    // Modulus (strip leading 00 if present)
                    auto mBytes = rsaKeyPackage.children[0].data;
                    if (mBytes.size() > 1 && mBytes[0] == 0x00) {
                        mBytes.erase(mBytes.begin());
                    }

                    bytesToBigInt(mBytes, n);
                    bytesToBigInt(rsaKeyPackage.children[1].data, e);

                    // IMPORTANT: You need a way to set these in your RSA class
                    // E.g., outRsa.setPublicKey(n, e);
                    return true;
                }
            }
        }
    }
    return false;
}

std::string netplus::x509cert::getSubjectCN() {
    // 1. Navigate to TBSCertificate (child 0) -> Subject (child 5)
    if (root.children.empty() || root.children[0].children.size() < 6) {
        return "";
    }

    auto& subject = root.children[0].children[5];

    // 2. Iterate through the RDN Sets
    for (auto& rdnSet : subject.children) {
        // Each RDN is usually a Sequence inside the Set
        for (auto& attrSeq : rdnSet.children) {
            if (attrSeq.children.size() < 2) continue;

            // First child is the OID
            std::string oid = decodeOID(attrSeq.children[0].data);

            // "2.5.4.3" is the OID for Common Name (CN)
            if (oid == "2.5.4.3") {
                // Second child is the value (UTF8String, PrintableString, etc.)
                auto& valueNode = attrSeq.children[1];
                return std::string(valueNode.data.begin(), valueNode.data.end());
            }
        }
    }

    return ""; // CN not found
}

std::vector<std::string> netplus::x509cert::getSubjectAltNames() {
    std::vector<std::string> dnsNames;

    // 1. Extensions are the last element (usually index 7 or 8) in TBSCertificate
    // They are prefixed with the tag 0xA3
    auto& tbs = root.children[0];
    ASN1Node* extensionsNode = nullptr;

    for (auto& child : tbs.children) {
        if (child.tag == 0xA3) {
            extensionsNode = &child.children[0]; // The Sequence inside the wrapper
            break;
        }
    }

    if (!extensionsNode) return dnsNames;

    // 2. Iterate through extensions to find OID 2.5.29.17
    for (auto& ext : extensionsNode->children) {
        if (ext.children.empty()) continue;

        std::string oid = decodeOID(ext.children[0].data);
        if (oid == "2.5.29.17") {
            // The 2nd or 3rd child is an Octet String containing the actual SAN Sequence
            // We must parse that Octet String's data as DER
            for (auto& valNode : ext.children) {
                if (valNode.tag == 0x04) { // Octet String
                    ASN1Node sanSequence;
                    if (parseInternal(valNode.data.data(), valNode.data.size(), sanSequence)) {
                        for (auto& name : sanSequence.children) {
                            // 0x82 is the context-specific tag for 'dNSName'
                            if (name.tag == 0x82) {
                                dnsNames.push_back(std::string(name.data.begin(), name.data.end()));
                            }
                        }
                    }
                }
            }
        }
    }
    return dnsNames;
}
+25 −5
Changes for src/crypto/x509.h: 25 added lines, 5 removed lines.
Original line number Diff line number Diff line
@@ -28,8 +28,18 @@
#include <string>
#include <vector>
#include <cstdint>
#include<chrono>

#include "rsa.h"

namespace netplus {

    struct ASN1Node {
        uint8_t tag;
        std::vector<uint8_t> data;
        std::vector<ASN1Node> children;
    };

    class x509cert {
    public:
        x509cert();
@@ -37,19 +47,29 @@ namespace netplus {
        // Load binary DER data
        bool loadFromFile(const std::string& filePath);

        // Simple getters for parsed data
        std::string getSerialNumber() const { return serialNumber; }
        std::string getIssuer() const { return issuer; }
        std::string getSubject() const { return subject; }
        std::string getSubjectCN();
        bool isExpired(const std::tm& notAfter);
        bool extractPublicKey(netplus::rsa& outRsa);
        std::vector<std::string> getSubjectAltNames();

    private:

        struct CertificateValidity {
            std::tm notBefore;
            std::tm notAfter;
        };

        std::vector<uint8_t> derData;
        std::string serialNumber;
        std::string issuer;
        std::string subject;

        // Internal ASN.1 parsing helpers
        size_t parseTLV(const uint8_t* data, size_t size, uint8_t& tag, std::vector<uint8_t>& value);
        ASN1Node root;
        size_t parseInternal(const uint8_t* data, size_t size, ASN1Node& outNode);
        std::tm parseUTCTime(const std::vector<uint8_t>& data);
        std::string decodeOID(const std::vector<uint8_t>& data);
        std::string bytesToHex(const std::vector<uint8_t>& bytes);
        void bytesToBigInt(const std::vector<uint8_t>& bytes, netplus::rsa::bigInt& out);
    };
};
+45 −4
Changes for test/x509.cpp: 45 added lines, 4 removed lines.
Original line number Diff line number Diff line
@@ -25,12 +25,53 @@

#include <iostream>

#include <iostream>
#include <vector>
#include "crypto//x509.h"

int main() {
    try {
        std::cout << "\nAll tests passed successfully!\n";
    } catch (const std::exception& e) {
        std::cerr << "\nTest failed with error: " << e.what() << std::endl;
    // 1. Initialize the Certificate Parser
    netplus::x509cert cert;

    // Most certificates from web servers are in .der (binary) format
    if (!cert.loadFromFile("server_cert.der")) {
        std::cerr << "Error: Could not load or parse the DER file." << std::endl;
        return 1;
    }

    // 2. Prepare your RSA Engine
    netplus::rsa rsaEngine;

    // 3. Extract the Public Key (N and E) into the RSA Engine
    // This uses the bytesToBigInt logic we built to fill rsaEngine.n and rsaEngine.e
    if (cert.extractPublicKey(rsaEngine)) {
        std::cout << "Successfully extracted RSA Public Key." << std::endl;
    } else {
        std::cerr << "Failed to extract RSA Public Key components." << std::endl;
    }

    // 4. Extract Identity Metadata (SAN and CN)
    std::cout << "\n--- Certificate Identity ---" << std::endl;

    std::vector<std::string> domains = cert.getSubjectAltNames();
    if (domains.empty()) {
        // Fallback to Common Name if SAN is empty
        std::cout << "Subject (CN): " << cert.getSubjectCN() << std::endl;
    } else {
        std::cout << "Authorized Domains (SAN):" << std::endl;
        for (const auto& domain : domains) {
            std::cout << "  - " << domain << std::endl;
        }
    }

    // 5. Practical Test: Encrypt a small message with the parsed key
    std::cout << "\n--- RSA Engine Test ---" << std::endl;
    netplus::rsa::bigInt message;
    message.fromString("42"); // Simple secret

    netplus::rsa::bigInt ciphertext = rsaEngine.encrypt(message);
    std::cout << "Test encryption of '42' complete." << std::endl;
    std::cout << "Ciphertext: " << ciphertext.toString().substr(0, 32) << "..." << std::endl;

    return 0;
}