Home / Docs / TLS 1.2/1.3 Stack
kernel/net/tls/), backed by an equally from-scratch crypto library (kernel/crypto/: AES, SHA-256/512, RSA, ECDSA P-256/P-384, Ed25519, ChaCha20, HMAC, CSPRNG). It supports real certificate-chain verification against a bundled Mozilla CA set, and negotiates TLS 1.2 ECDHE-RSA-AES-GCM or TLS 1.3 AES-GCM/ChaCha20 cipher suites depending on what the server offers. This document is kept for its options-analysis reasoning, not as a description of what shipped.SSL/TLS Implementation Plan for MayteraOS
Document Information
- Version: 1.0
- Date: January 2026
- Author: MayteraOS Development Team
- Status: Planning Phase
1. Executive Summary
This document outlines the implementation plan for adding SSL/TLS support to MayteraOS. The goal is to enable secure HTTPS connections for the existing wget functionality and future networked applications. Given the bare-metal nature of MayteraOS with its 64-bit UEFI C kernel, careful consideration must be given to memory constraints, the absence of floating-point operations (SSE disabled), and the lack of standard library dependencies.
2. Options Analysis
2.1 Option A: BearSSL
Overview: BearSSL is a lightweight SSL/TLS implementation designed for constrained environments. It emphasizes correctness, security, and minimal footprint.
Pros:
- No dynamic memory allocation at runtime (memory is pre-allocated by the caller)
- Extremely small footprint: ~20KB code, ~25KB RAM for minimal configuration
- All cryptographic operations are constant-time by default (side-channel resistant)
- No dependencies on external libraries
- Immune to memory leaks and memory-based DoS attacks
- Well-suited for bare-metal environments
Cons:
- No TLS 1.3 support (TLS 1.2 only)
- No DTLS support
- Limited documentation compared to alternatives
- Smaller community and slower feature development
- Full certificate validation for TLS 1.3 would require dynamic allocation (breaking BearSSL's core design)
Memory Requirements:
- Minimal: ~20KB code + 25KB RAM
- ESP8266 reference: 34.5KB Flash, 6.7KB RAM (minimal config)
- Full validation: 48.3KB Flash, 9.4KB RAM
- Per-connection buffers: ~22KB (reducible with MFLN)
- Secondary stack: ~6KB for temporary variables
Source: BearSSL Official Site
2.2 Option B: mbedTLS (formerly PolarSSL)
Overview: mbedTLS is a widely-used, well-documented SSL/TLS library maintained by ARM. It's designed for embedded systems but has broader applicability.
Pros:
- Excellent documentation and active community
- Highly configurable through compile-time options
- Supports TLS 1.2 and TLS 1.3
- Supports DTLS 1.2 and DTLS 1.3
- Modular design allows selective feature inclusion
- Used extensively in production embedded systems
- Good test coverage with NIST test vectors
Cons:
- Uses dynamic memory allocation by default
- Larger default footprint: ~32-35KB RAM with default config
- Default 16KB frame buffers (32KB for TX+RX) per TLS standard
- Requires more configuration effort to minimize footprint
- Certificate chain verification requires CA chain in RAM
Memory Requirements:
- Default: ~32-35KB RAM per connection
- mbedtls_ssl_setup allocates ~23KB per connection
- Configurable via MBEDTLS_SSL_MAX_CONTENT_LEN (minimum 2KB with MFLN)
- Code size varies by configuration (typically 50-150KB)
- Can be reduced significantly with careful config (MBEDTLS_AES_FEWER_TABLES saves 6KB)
Source: mbedTLS Documentation
2.3 Option C: wolfSSL
Overview: wolfSSL (formerly CyaSSL) is a lightweight, portable SSL/TLS library designed for embedded systems, IoT, and RTOS environments.
Pros:
- Supports TLS 1.3, TLS 1.2, DTLS 1.3, DTLS 1.2
- Excellent embedded OS support with comprehensive porting guide
- Smallest TLS 1.3 implementation available (~24KB on Arduino Nano 33 IoT)
- Commercial support available
- Active development with regular updates
- Hardware crypto acceleration support
- No external dependencies required
- Well-documented porting process
Cons:
- Uses dynamic memory allocation by default
- Dual licensing (GPLv2 or commercial)
- Some advanced features require commercial license
- Slightly more complex API than BearSSL
Memory Requirements:
- Typical: 20-100KB depending on configuration
- Minimal TLS stack: <24KB (demonstrated on Arduino Nano 33 IoT with 32KB RAM)
- Highly configurable to minimize footprint
Source: wolfSSL Porting Guide
2.4 Recommendation: wolfSSL
Selected Option: wolfSSL
Justification:
- TLS 1.3 Support: wolfSSL is the only option providing full TLS 1.3 support with a small footprint. TLS 1.3 offers significant security improvements and faster handshakes (1-RTT vs 2-RTT).
- Proven Embedded Track Record: wolfSSL has been successfully ported to numerous bare-metal and RTOS environments, with detailed porting documentation.
- Memory Efficiency: Can achieve <24KB footprint while supporting modern TLS versions.
- Porting Infrastructure: Provides clear abstraction points for:
- Custom memory allocators
- Filesystem operations
- Threading/mutex (or single-threaded mode)
- Custom I/O callbacks
- Random number generation
- License Compatibility: GPLv2 is acceptable for MayteraOS's open-source nature.
- Active Maintenance: Regular security updates and bug fixes.
- ChaCha20-Poly1305 Support: Provides hardware-independent cipher suite that performs well in pure software implementation, important since MayteraOS runs on various x86 hardware with varying AES-NI support.
3. Requirements Analysis
3.1 Cryptographic Primitives Needed
3.1.1 Symmetric Encryption (Required for TLS 1.3)
| Algorithm | Purpose | Priority | Notes |
|---|---|---|---|
| AES-128-GCM | AEAD cipher | Mandatory | TLS 1.3 requires this cipher suite |
| AES-256-GCM | AEAD cipher | Recommended | Stronger security option |
| ChaCha20-Poly1305 | AEAD cipher | Recommended | Better for software-only implementation |
Implementation Notes:
- ChaCha20-Poly1305 uses only add-rotate-xor operations (no table lookups)
- Inherently constant-time, avoiding cache-timing side channels
- 3x faster than AES-GCM in pure software on platforms without AES-NI
- AES-GCM requires careful implementation to avoid timing attacks
3.1.2 Hash Functions
| Algorithm | Purpose | Priority |
|---|---|---|
| SHA-256 | TLS PRF, HMAC, certificate hashing | Mandatory |
| SHA-384 | TLS PRF for AES-256-GCM | Recommended |
| SHA-512 | Certificate signatures | Optional |
3.1.3 Asymmetric Cryptography
| Algorithm | Purpose | Priority | Key Sizes |
|---|---|---|---|
| RSA | Certificate signatures, key exchange | Mandatory | 2048, 4096 bits |
| ECDSA | Certificate signatures | Recommended | P-256, P-384 |
| ECDHE | Key exchange | Mandatory | P-256, P-384, X25519 |
| Ed25519 | Certificate signatures | Optional | 256 bits |
TLS 1.3 Key Exchange Requirements:
- ECDHE is mandatory (ephemeral key exchange)
- X25519 (Curve25519) is highly recommended
- RSA key exchange removed in TLS 1.3
3.1.4 Message Authentication
| Algorithm | Purpose | Priority |
|---|---|---|
| HMAC-SHA256 | Key derivation, integrity | Mandatory |
| Poly1305 | AEAD authentication | Recommended |
| GCM (GMAC) | AEAD authentication | Mandatory |
3.2 Random Number Generation
Critical Requirement: Cryptographic security depends entirely on high-quality random numbers.
3.2.1 Hardware Sources (x86-64)
RDRAND Instruction:
- Available on Intel (Ivy Bridge+) and AMD (Bulldozer+)
- Provides cryptographically secure random numbers
- Compliant with NIST SP 800-90A, FIPS 140-2, ANSI X9.82
- Uses AES-based CTR_DRBG internally
- Fast: can generate random data at high rates
RDSEED Instruction:
- Available on Intel (Broadwell+) and AMD (Zen+)
- Provides true hardware entropy
- Use for seeding other PRNGs
- Slower but higher quality entropy
Detection via CPUID:
// Check RDRAND: CPUID.01H:ECX bit 30
// Check RDSEED: CPUID.07H:EBX bit 18
3.2.2 Software Fallback
If hardware RNG not available:
- Seed from multiple entropy sources:
- Timer tick variations
- Interrupt timing jitter
- Mouse/keyboard event timing
- Network packet arrival times
- Use a well-seeded CSPRNG (ChaCha20 or AES-CTR-DRBG)
3.2.3 Recommended Implementation
// Priority order for random generation:
// 1. RDSEED (if available) - for initial seeding
// 2. RDRAND (if available) - for runtime generation
// 3. Software CSPRNG seeded from entropy pool
typedef struct {
int has_rdrand;
int has_rdseed;
uint8_t entropy_pool[64];
uint32_t pool_index;
} rng_state_t;
int crypto_random_init(rng_state_t *state);
int crypto_random_bytes(rng_state_t *state, uint8_t *output, size_t len);
3.3 Certificate Handling
3.3.1 X.509 Certificate Support
Required Features:
- Parse DER-encoded certificates
- Parse PEM-encoded certificates (base64 decode + DER parse)
- Verify certificate signatures (RSA-SHA256, ECDSA-SHA256)
- Check certificate validity dates
- Verify certificate chain up to trusted root
Certificate Storage:
- Root CA certificates must be compiled into kernel or loaded from filesystem
- Estimate: 20-50 popular root CAs = 50-150KB of certificate data
- Consider: compressed storage, lazy loading, or curated subset
3.3.2 Certificate Validation Requirements
- Signature Verification: Verify issuer's signature on certificate
- Chain Building: Build chain from server cert to trusted root
- Validity Period: Check notBefore and notAfter dates
- Basic Constraints: Check CA flag for intermediates
- Key Usage: Verify certificate purpose
- Common Name/SAN: Verify hostname matches certificate
3.4 Memory Requirements Summary
| Component | Minimum | Recommended |
|---|---|---|
| wolfSSL code | 50KB | 80KB |
| Crypto primitives | 20KB | 40KB |
| Per-connection state | 15KB | 25KB |
| Send/receive buffers | 8KB | 16KB |
| Certificate storage | 50KB | 100KB |
| Total per connection | ~95KB | ~165KB |
Current MayteraOS Heap:
- Initial: 16MB
- Maximum: 256MB
- Available: More than sufficient for TLS
4. Implementation Phases
Phase 1: Core Cryptographic Primitives (Weeks 1-4)
4.1.1 Objectives
- Implement or port essential crypto algorithms
- Establish secure random number generation
- Create testing framework for crypto operations
4.1.2 Tasks
Week 1: Random Number Generation
kernel/crypto/
├── rng.h # RNG API
├── rng.c # RDRAND/RDSEED + fallback CSPRNG
├── cpuid.h # CPU feature detection
└── cpuid.c # CPUID wrapper functions
- [ ] Implement CPUID feature detection for RDRAND/RDSEED
- [ ] Implement RDRAND wrapper with retry logic
- [ ] Implement RDSEED wrapper for seeding
- [ ] Implement software CSPRNG fallback (ChaCha20-based)
- [ ] Create entropy mixing function
- [ ] Test on hardware with/without RDRAND
Week 2: Hash Functions
kernel/crypto/
├── sha256.h # SHA-256 API
├── sha256.c # SHA-256 implementation
├── sha384.h # SHA-384 API
├── sha384.c # SHA-384 implementation
├── hmac.h # HMAC API
└── hmac.c # HMAC implementation
- [ ] Port or implement SHA-256
- [ ] Port or implement SHA-384
- [ ] Implement HMAC wrapper
- [ ] Verify with NIST test vectors
- [ ] Optimize for x86-64 (consider SIMD later)
Week 3: Symmetric Encryption
kernel/crypto/
├── chacha20.h # ChaCha20 API
├── chacha20.c # ChaCha20 stream cipher
├── poly1305.h # Poly1305 API
├── poly1305.c # Poly1305 MAC
├── chacha20poly1305.h # AEAD API
├── chacha20poly1305.c # ChaCha20-Poly1305 AEAD
├── aes.h # AES API
├── aes.c # AES implementation
├── gcm.h # GCM mode API
└── gcm.c # AES-GCM AEAD
- [ ] Implement ChaCha20 (quarter-round based)
- [ ] Implement Poly1305 MAC
- [ ] Combine into ChaCha20-Poly1305 AEAD
- [ ] Implement AES (constant-time, no table lookups if possible)
- [ ] Implement GCM mode
- [ ] Verify with RFC test vectors
Week 4: Asymmetric Cryptography Foundation
kernel/crypto/
├── bignum.h # Big integer API
├── bignum.c # Big integer operations
├── ecc.h # ECC API
├── ecc.c # Elliptic curve operations
├── x25519.h # X25519 API
└── x25519.c # X25519 key exchange
- [ ] Port wolfSSL big number library or implement basic operations
- [ ] Implement modular exponentiation for RSA
- [ ] Implement X25519 scalar multiplication
- [ ] Implement P-256 curve operations (if time permits)
4.1.3 Deliverables
- Standalone crypto library:
kernel/crypto/ - Test suite:
kernel/crypto/test/ - Documentation of API and usage
Phase 2: TLS 1.2/1.3 Handshake (Weeks 5-8)
4.2.1 Objectives
- Port wolfSSL core to MayteraOS
- Implement TLS handshake state machine
- Support both TLS 1.2 and TLS 1.3
4.2.2 Tasks
Week 5: wolfSSL Porting Foundation
kernel/tls/
├── wolfssl_config.h # wolfSSL user_settings.h equivalent
├── wolfssl_port.c # MayteraOS-specific porting layer
├── tls_memory.c # Custom memory allocator wrapper
└── tls_io.c # Custom I/O callbacks
- [ ] Create wolfSSL configuration header (user_settings.h)
- [ ] Disable unnecessary features (filesystem, threading for now)
- [ ] Implement memory allocation wrappers (kmalloc/kfree)
- [ ] Implement I/O callbacks using TCP stack
- [ ] Implement time functions for certificate validation
wolfSSL Configuration (user_settings.h):
#define WOLFSSL_USER_SETTINGS
#define SINGLE_THREADED
#define NO_FILESYSTEM
#define NO_WRITEV
#define WOLFSSL_NO_SOCK
#define WOLFCRYPT_ONLY // First, verify crypto works
#define NO_DEV_RANDOM // We provide custom RNG
#define CUSTOM_RAND_GENERATE_SEED
#define CUSTOM_RAND_GENERATE_BLOCK
#define SIZEOF_LONG 8
#define SIZEOF_LONG_LONG 8
#define WOLFSSL_SMALL_STACK
#define NO_INLINE // Reduce code size initially
#define TFM_TIMING_RESISTANT
#define ECC_TIMING_RESISTANT
#define WC_RSA_BLINDING
Week 6: TLS Record Layer
- [ ] Integrate wolfSSL source files
- [ ] Implement TLS record parsing/formatting
- [ ] Implement record encryption/decryption
- [ ] Handle record fragmentation
Week 7: TLS Handshake - Client
- [ ] Implement ClientHello generation
- [ ] Parse ServerHello
- [ ] Implement key exchange (ECDHE)
- [ ] Implement Finished message handling
- [ ] TLS 1.2 handshake complete
Week 8: TLS 1.3 Handshake
- [ ] Implement TLS 1.3 message format changes
- [ ] Implement 1-RTT handshake
- [ ] Handle encrypted extensions
- [ ] Support 0-RTT (optional, lower priority)
4.2.3 Deliverables
- Working TLS 1.2 client handshake
- Working TLS 1.3 client handshake
- Handshake test against known servers
Phase 3: Certificate Validation (Weeks 9-11)
4.3.1 Objectives
- Parse and validate X.509 certificates
- Build certificate chains
- Implement hostname verification
4.3.2 Tasks
Week 9: Certificate Parsing
kernel/tls/
├── x509.h # X.509 API
├── x509.c # X.509 parsing
├── asn1.h # ASN.1/DER parsing
├── asn1.c # ASN.1/DER implementation
├── pem.h # PEM encoding
└── pem.c # PEM decode/encode
- [ ] Implement ASN.1/DER parser
- [ ] Implement base64 decode for PEM
- [ ] Parse X.509 certificate structure
- [ ] Extract public key, validity, extensions
Week 10: Certificate Chain Validation
- [ ] Implement signature verification
- [ ] Build certificate chain
- [ ] Verify chain to trusted root
- [ ] Check validity dates (requires RTC)
- [ ] Verify basic constraints
Week 11: Root CA Store and Hostname Verification
kernel/tls/
├── ca_bundle.h # Compiled-in root CAs
├── ca_bundle.c # Root CA certificates (DER format)
└── hostname.c # Hostname verification
- [ ] Curate minimal root CA bundle (20-30 most common CAs)
- [ ] Implement hostname verification (CN and SAN)
- [ ] Handle wildcard certificates
- [ ] Test against major websites
4.3.3 Deliverables
- Working certificate validation
- Root CA bundle
- Full chain verification
Phase 4: TCP Stack Integration (Weeks 12-14)
4.4.1 Objectives
- Create TLS socket abstraction
- Integrate with existing TCP stack
- Enable HTTPS in wget
4.4.2 Tasks
Week 12: TLS Socket Layer
kernel/net/
├── tls.h # TLS socket API
├── tls.c # TLS socket implementation
└── tls_internal.h # Internal structures
TLS Socket API:
// Create TLS context
tls_ctx_t *tls_ctx_new(void);
void tls_ctx_free(tls_ctx_t *ctx);
// Load CA certificates
int tls_ctx_load_ca(tls_ctx_t *ctx, const uint8_t *ca_data, size_t len);
// Create TLS connection over TCP socket
tls_conn_t *tls_connect(tls_ctx_t *ctx, int tcp_sock, const char *hostname);
// Send/receive encrypted data
int tls_send(tls_conn_t *conn, const void *data, size_t len);
int tls_recv(tls_conn_t *conn, void *buf, size_t len);
// Close connection
int tls_close(tls_conn_t *conn);
// Get error information
int tls_get_error(tls_conn_t *conn);
const char *tls_error_string(int error);
- [ ] Implement TLS context management
- [ ] Implement TLS connection establishment
- [ ] Wire up to wolfSSL I/O callbacks
- [ ] Implement blocking send/receive
Week 13: HTTPS Integration
kernel/net/
├── wget.c # Modified for HTTPS support
└── wget.h # Updated API
- [ ] Modify wget to detect https:// URLs
- [ ] Create TLS connection for HTTPS
- [ ] Handle mixed HTTP/HTTPS transparently
- [ ] Test basic HTTPS fetches
Week 14: Testing and Hardening
- [ ] Test against major HTTPS sites
- [ ] Handle connection errors gracefully
- [ ] Implement session resumption (optional)
- [ ] Performance optimization
- [ ] Memory leak testing
4.4.3 Deliverables
- TLS socket library
- HTTPS-capable wget
- Integration tests
5. Challenges and Mitigations
5.1 No Floating Point (SSE Disabled)
Challenge: Some cryptographic implementations use floating-point for performance optimizations.
Impact:
- Cannot use SIMD-optimized crypto implementations directly
- Some libraries assume floating-point availability
Mitigations:
- Use integer-only implementations (ChaCha20 is inherently integer-based)
- Configure wolfSSL with
WOLFSSL_GENERAL_ALIGNMENTand avoid FP paths - For AES-GCM, use bitsliced or table-based implementations
- Verify no FP instructions in compiled crypto code
wolfSSL Config:
#define NO_WOLFSSL_MEMORY // Don't use wolfSSL memory wrapper
#define WC_NO_ASYNC_THREADING
#define WOLFSSL_SP_NO_FLOAT // Disable SP float optimizations
5.2 Memory Constraints
Challenge: TLS requires significant memory for buffers and state.
Impact:
- Each TLS connection needs 15-25KB of state
- Receive buffers can be up to 16KB per TLS standard
- Certificate chains can be large
Mitigations:
- Limit concurrent TLS connections (e.g., max 4-8)
- Use Maximum Fragment Length Negotiation (MFLN) to reduce buffer sizes
- Process certificates incrementally if possible
- Free connection state promptly after use
- Consider static allocation for predictable memory usage
Buffer Optimization:
// Reduce TLS buffer size (requires server support)
#define WOLFSSL_MAX_MTU 1500
#define MAX_RECORD_SIZE 2048 // Reduced from 16KB default
5.3 Secure Random Number Generation
Challenge: Cryptographic security depends entirely on unpredictable random numbers.
Impact:
- Weak random = completely broken security
- Hardware RNG may not be available on all systems
Mitigations:
- Primary: Use RDRAND/RDSEED when available
- Secondary: Maintain entropy pool from multiple sources
- Fallback: Well-seeded software CSPRNG (ChaCha20-based)
- Verification: Test randomness quality at boot
Entropy Sources for Pool:
- Timer tick counter (TSC)
- Interrupt timing variations
- Mouse/keyboard event timing (when available)
- Network packet arrival times
- Mix with RDRAND if available
Implementation:
// crypto/rng.c
static int collect_entropy(uint8_t *buf, size_t len) {
uint64_t tsc = read_tsc();
mix_entropy(buf, &tsc, sizeof(tsc));
if (has_rdrand) {
uint64_t rdrand_val;
if (rdrand64(&rdrand_val)) {
mix_entropy(buf, &rdrand_val, sizeof(rdrand_val));
}
}
// Add interrupt timing jitter
mix_entropy(buf, &timer_ticks, sizeof(timer_ticks));
return 0;
}
5.4 Time for Certificate Validation
Challenge: Certificate validation requires accurate current time.
Impact:
- Invalid time = cannot verify certificate dates
- May reject valid certificates or accept expired ones
Mitigations:
- Primary: Use RTC if available (CMOS RTC on x86)
- Secondary: Get time via NTP after network is up
- Fallback: Allow user to set time manually
- Option: Skip date validation with security warning (development mode)
Current State: MayteraOS has timer_ticks but needs RTC integration for wall-clock time.
5.5 No Standard C Library
Challenge: TLS libraries expect standard C library functions.
Impact:
- Missing string functions (already have most)
- Missing memory functions (already have)
- Missing time functions
Mitigations:
- Map wolfSSL requirements to MayteraOS equivalents:
malloc/free->kmalloc/kfreememcpy/memset-> already implementedstrlen/strcmp-> already implemented
- Implement missing functions as needed
- Use wolfSSL's
XMALLOC,XFREE,XMEMCPYmacros for mapping
5.6 Code Size
Challenge: TLS implementation adds significant code size.
Impact:
- Larger kernel image
- Longer boot time
- More memory pressure
Mitigations:
- Configure wolfSSL for minimal feature set initially
- Use compile-time options to exclude unused algorithms
- Consider putting TLS code in separate loadable module (future)
- Use
-Osoptimization for crypto code
Minimal Configuration Targets:
- TLS 1.3 only (simpler, smaller code path)
- Single cipher suite: TLS_CHACHA20_POLY1305_SHA256
- Single curve: X25519
- RSA-2048 minimum for certificate verification
6. Integration Points with Existing TCP Stack
6.1 Current TCP Stack Architecture
File: kernel/net/tcp.c
Key Structures:
typedef struct {
int active;
tcp_state_t state;
uint16_t local_port;
uint32_t remote_ip;
uint16_t remote_port;
// ... sequence numbers, buffers, etc.
uint8_t recv_buffer[TCP_RECV_BUFFER_SIZE]; // 4KB
uint8_t send_buffer[TCP_SEND_BUFFER_SIZE]; // 4KB
} tcp_conn_t;
Existing API:
int tcp_socket(void);
int tcp_connect(int sock, uint32_t remote_ip, uint16_t remote_port);
int tcp_send(int sock, const void *data, uint16_t length);
int tcp_recv(int sock, void *buffer, uint16_t length);
int tcp_close(int sock);
tcp_state_t tcp_get_state(int sock);
int tcp_is_connected(int sock);
6.2 TLS Integration Strategy
Approach: Layer TLS on top of existing TCP, using TCP as transport.
+------------------+
| Application | (wget, IRC client, etc.)
+------------------+
|
+------------------+
| TLS Layer | (NEW: encryption/decryption, handshake)
+------------------+
|
+------------------+
| TCP Layer | (EXISTING: reliable transport)
+------------------+
|
+------------------+
| IP Layer | (EXISTING: routing)
+------------------+
6.3 TLS I/O Callbacks
wolfSSL Integration:
// Custom send callback
static int tls_send_callback(WOLFSSL* ssl, char* buf, int sz, void* ctx) {
tls_conn_t *conn = (tls_conn_t *)ctx;
int sent = tcp_send(conn->tcp_sock, buf, sz);
if (sent < 0) {
if (sent == TCP_ERR_WOULD_BLOCK) {
return WOLFSSL_CBIO_ERR_WANT_WRITE;
}
return WOLFSSL_CBIO_ERR_GENERAL;
}
return sent;
}
// Custom receive callback
static int tls_recv_callback(WOLFSSL* ssl, char* buf, int sz, void* ctx) {
tls_conn_t *conn = (tls_conn_t *)ctx;
int received = tcp_recv(conn->tcp_sock, buf, sz);
if (received == 0) {
return WOLFSSL_CBIO_ERR_WANT_READ;
}
if (received < 0) {
return WOLFSSL_CBIO_ERR_GENERAL;
}
return received;
}
6.4 Connection Flow
HTTPS Connection Sequence:
1. Application calls tls_connect(ctx, "example.com", 443)
2. TLS layer:
a. tcp_socket() - create TCP socket
b. tcp_connect(sock, ip, 443) - establish TCP connection
c. Wait for TCP_STATE_ESTABLISHED
d. wolfSSL_connect() - perform TLS handshake
- Sends ClientHello via tls_send_callback -> tcp_send
- Receives ServerHello via tls_recv_callback -> tcp_recv
- Completes handshake
e. Return TLS connection handle
3. Application calls tls_send(conn, "GET / HTTP/1.1\r\n...")
- TLS layer encrypts data
- Sends via tcp_send()
4. Application calls tls_recv(conn, buffer, size)
- Receives via tcp_recv()
- TLS layer decrypts data
- Returns plaintext
6.5 Modifications to Existing Code
Changes to tcp.h:
// No changes required - TLS uses existing API
Changes to wget.c:
// Add HTTPS support
int wget_execute(const char *url, const char *save_path) {
// ... existing code ...
// Detect HTTPS
int use_tls = (strncmp(url, "https://", 8) == 0);
if (use_tls) {
// Create TLS context
tls_ctx_t *tls_ctx = tls_ctx_new();
tls_ctx_load_ca_bundle(tls_ctx);
// Connect with TLS
tls_conn_t *tls_conn = tls_connect(tls_ctx, sock, host);
if (!tls_conn) {
// Handle error
}
// Use TLS send/recv
tls_send(tls_conn, request, req_len);
tls_recv(tls_conn, buffer, size);
tls_close(tls_conn);
tls_ctx_free(tls_ctx);
} else {
// Existing HTTP code path
tcp_send(sock, request, req_len);
tcp_recv(sock, buffer, size);
}
}
6.6 New Files Required
kernel/
├── crypto/
│ ├── rng.h
│ ├── rng.c
│ ├── sha256.h
│ ├── sha256.c
│ ├── chacha20.h
│ ├── chacha20.c
│ ├── poly1305.h
│ ├── poly1305.c
│ └── ...
├── tls/
│ ├── wolfssl/ # wolfSSL source (vendored)
│ ├── wolfssl_config.h # MayteraOS configuration
│ ├── wolfssl_port.c # Porting layer
│ ├── tls.h # Public API
│ ├── tls.c # Implementation
│ ├── ca_bundle.h # Root certificates
│ └── ca_bundle.c
└── net/
├── tcp.c # Existing (unchanged)
├── tcp.h # Existing (unchanged)
├── wget.c # Modified for HTTPS
└── wget.h # Modified for HTTPS
7. Testing Strategy
7.1 Crypto Primitives Testing
Test Framework:
// crypto/test/test_crypto.c
void test_sha256(void);
void test_chacha20(void);
void test_chacha20poly1305(void);
void test_aes_gcm(void);
void test_x25519(void);
void test_rng(void);
Test Vectors:
- SHA-256: NIST FIPS 180-4 test vectors
- ChaCha20-Poly1305: RFC 8439 test vectors
- AES-GCM: NIST SP 800-38D test vectors
- X25519: RFC 7748 test vectors
7.2 TLS Testing
Internal Testing:
- Handshake state machine unit tests
- Record layer encryption/decryption tests
- Certificate parsing tests
Integration Testing:
- Fetch a small file over HTTPS from a test server on the local network
- Fetch a page over HTTPS from a public site (e.g. example.com)
7.3 Compatibility Testing
Test Servers:
- Local OpenSSL server
- Local nginx with TLS 1.3
- Public websites (once DNS implemented)
8. Timeline Summary
| Phase | Duration | Deliverable |
|---|---|---|
| Phase 1: Crypto Primitives | Weeks 1-4 | Working crypto library |
| Phase 2: TLS Handshake | Weeks 5-8 | TLS 1.2/1.3 client |
| Phase 3: Certificate Validation | Weeks 9-11 | Full certificate chain validation |
| Phase 4: TCP Integration | Weeks 12-14 | HTTPS-capable wget |
Total Estimated Time: 14 weeks
9. Dependencies and Prerequisites
9.1 Required Before Starting
- RTC Driver: Implement CMOS RTC reading for certificate date validation
- Memory Review: Ensure heap can handle TLS memory requirements
- TCP Stability: Verify TCP stack handles larger data transfers reliably
9.2 Nice to Have
- DNS Client: Currently using IP addresses; DNS would improve usability
- NTP Client: For accurate time synchronization
- Persistent Storage: For session resumption, cached certificates
10. References
Documentation
- BearSSL Official Site
- mbedTLS Documentation
- wolfSSL Porting Guide
- Intel DRNG Implementation Guide
- OSDev Random Number Generator
RFCs
- RFC 8446: TLS 1.3
- RFC 5246: TLS 1.2
- RFC 8439: ChaCha20 and Poly1305
- RFC 7748: Elliptic Curves (X25519, X448)
Test Vectors
- NIST Cryptographic Algorithm Validation Program (CAVP)
- RFC test vectors for each algorithm
Appendix A: wolfSSL Minimal Configuration
// user_settings.h for MayteraOS
#ifndef _USER_SETTINGS_H_
#define _USER_SETTINGS_H_
// System configuration
#define SINGLE_THREADED
#define NO_FILESYSTEM
#define NO_WRITEV
#define WOLFSSL_NO_SOCK
#define NO_WOLFSSL_DIR
#define NO_WOLFSSL_SERVER // Client only initially
// Memory configuration
#define XMALLOC(s, h, t) kmalloc(s)
#define XFREE(p, h, t) kfree(p)
#define XREALLOC(p, n, h, t) krealloc(p, n)
// Data types
#define SIZEOF_LONG 8
#define SIZEOF_LONG_LONG 8
// Security features
#define TFM_TIMING_RESISTANT
#define ECC_TIMING_RESISTANT
#define WC_RSA_BLINDING
#define WOLFSSL_SP_NO_FLOAT
// Random number generation
#define NO_DEV_RANDOM
#define CUSTOM_RAND_GENERATE_SEED custom_rand_seed
#define CUSTOM_RAND_GENERATE_BLOCK custom_rand_block
// TLS configuration
#define WOLFSSL_TLS13
#define HAVE_TLS_EXTENSIONS
#define HAVE_SUPPORTED_CURVES
#define HAVE_EXTENDED_MASTER
// Cipher suites
#define HAVE_CHACHA
#define HAVE_POLY1305
#define HAVE_AESGCM
#define HAVE_AESCCM
// Key exchange
#define HAVE_ECC
#define HAVE_CURVE25519
#define FP_ECC
#define CURVE25519_SMALL
// Certificate support
#define HAVE_RSA
#define WC_RSA_PSS
#define WOLFSSL_SHA384
#define WOLFSSL_SHA512
// Size optimizations
#define WOLFSSL_SMALL_STACK
#define NO_SESSION_CACHE
#define ALT_ECC_SIZE
#define RSA_LOW_MEM
// Disable unused features
#define NO_DSA
#define NO_DH
#define NO_HC128
#define NO_RABBIT
#define NO_RC4
#define NO_MD4
#define NO_MD5
#define NO_DES3
#define NO_PSK
#define NO_PWDBASED
#define NO_OLD_TLS
#endif // _USER_SETTINGS_H_
Appendix B: Estimated Code Size
| Component | Estimated Size |
|---|---|
| SHA-256 | 2-3KB |
| SHA-384/512 | 3-4KB |
| ChaCha20 | 2KB |
| Poly1305 | 2KB |
| AES | 5-8KB |
| GCM | 3-4KB |
| RSA | 10-15KB |
| ECC/X25519 | 15-20KB |
| X.509 parsing | 10-15KB |
| TLS state machine | 20-30KB |
| wolfSSL core | 30-40KB |
| Total | ~100-140KB |
Appendix C: Glossary
| Term | Definition |
|---|---|
| AEAD | Authenticated Encryption with Associated Data |
| AES-GCM | AES in Galois/Counter Mode |
| ChaCha20-Poly1305 | Stream cipher with MAC |
| CSPRNG | Cryptographically Secure Pseudo-Random Number Generator |
| DER | Distinguished Encoding Rules (binary certificate format) |
| ECDHE | Elliptic Curve Diffie-Hellman Ephemeral |
| MFLN | Maximum Fragment Length Negotiation |
| PEM | Privacy Enhanced Mail (base64 certificate format) |
| RDRAND | Intel random number instruction |
| RDSEED | Intel entropy instruction |
| TLS | Transport Layer Security |
| X.509 | Certificate standard |
| X25519 | Elliptic curve for key exchange |