diff --git a/docs/https.md b/docs/https.md index 39976cb7..2fdd2ada 100644 --- a/docs/https.md +++ b/docs/https.md @@ -116,3 +116,30 @@ LTO, and passed DOL section validation. Physical GameCube/BBA interoperability, provisioning and full-scene performance remain separate hardware acceptance checks. Host TLS success does not prove the quality of an application's entropy/time inputs or real-console compatibility. + +## Nonblocking TLS streams + +`Dolphin.Network.TlsStream.ConnectAsync(hostname, port, cancellationToken)` opens +an authenticated TLS connection using the same explicit trust roots, fresh +entropy, clock checks and HTTP/1.1 ALPN as HTTPS. It owns and closes its socket. +It does not expose the socket or allow certificate validation to be bypassed. +Connection setup uses the runtime's normal cancellation and deadline handling. + +`TryRead(buffer, offset, count)` and `TryWrite(buffer, offset, count)` use +caller-owned arrays, allocate no task/result per poll and return `-1` when the +operation would block. Reads return zero at EOF; writes can accept a shorter +range. Retry a would-block write with the identical, unmodified range. Dispose +closes the connection and subsequent I/O fails. Reads, writes and the native +TLS step still need application frame/time budgets. Applications supply HTTP +upgrade/WebSocket framing or another HTTP/1.1 application protocol themselves. + +The HTTPS native/AOT fixtures exercise the stream's fragmented response, short +I/O, EOF, cancellation, disposal and hostname-validation failure in addition +to the shared TLS provider's trust and certificate-time acceptance tests. + +`TlsStream.FillRandom(buffer, offset, count)` fills at most 256 caller-owned +bytes from the already seeded TLS cryptographic DRBG. Use it for upgrade nonces +and unpredictable WebSocket masks; pool small draws. The existing bounded DRBG +reseed interval still applies. Exhaustion fails closed: dispose connections, +collect fresh platform entropy and reconfigure before reconnecting. This API +never manufactures replacement entropy or changes certificate validation. diff --git a/include/dnd_tls.h b/include/dnd_tls.h index d74fde48..31428d44 100644 --- a/include/dnd_tls.h +++ b/include/dnd_tls.h @@ -7,6 +7,7 @@ int dnd_net_tls_configure(DndArray *roots,DndArray *seed,int64_t unix_seconds); int dnd_net_tls_configure_local_clock(DndArray *roots,DndArray *seed,int64_t local_unix_seconds); int dnd_net_tls_reset(void); +int dnd_net_tls_random(int token,DndArray *output,int offset,int count); int dnd_net_tls_start(int token,DndString *host); int dnd_net_tls_handshake(int token); int dnd_net_tls_error(void); diff --git a/scripts/ci_https.py b/scripts/ci_https.py index 991857f5..0e886f58 100644 --- a/scripts/ci_https.py +++ b/scripts/ci_https.py @@ -31,6 +31,21 @@ class Program { Wait(NetworkRuntime.StartAsync(new NetworkOptions{DnsServers=new[]{Dolphin.Network.IPAddress.Loopback},DnsPort=15353},default)); var ca=Dolphin.Text.Encoding.ASCII.GetBytes($CA);var seed=new byte[]{$ENTROPY};TlsConfiguration.Initialize(ca,seed,$UTC); for(int i=0;ielements_are_references|| + output->element_size!=1||offset<0||count<0||count>256|| + (unsigned)offset>output->length||(unsigned)count>output->length-(unsigned)offset)return failure(-2); + if(!count)return 0; + int r=mbedtls_ctr_drbg_random(&random_state,output->data+offset,(size_t)count); + if(r){mbedtls_platform_zeroize(output->data+offset,(size_t)count);return failure(r);} + return 0; +} int dnd_tls_read(int token,void *buffer,int count){ int i=find(token);if(i<0||!sessions[i].ready)return failure(-3);if(!count)return 0; int r=mbedtls_ssl_read(&sessions[i].ssl,buffer,(size_t)count); @@ -160,6 +170,7 @@ int dnd_net_tls_configure_local_clock(DndArray *a,DndArray *b,int64_t t){(void)a int dnd_net_tls_reset(void){return 0;} int dnd_tls_begin(int t,int f,const char *h){(void)t;(void)f;(void)h;return -2;} int dnd_tls_handshake(int t){(void)t;return -2;} +int dnd_net_tls_random(int t,DndArray *b,int o,int n){(void)t;(void)b;(void)o;(void)n;return -2;} int dnd_tls_read(int t,void *b,int n){(void)t;(void)b;(void)n;return -2;} int dnd_tls_write(int t,const void *b,int n){(void)t;(void)b;(void)n;return -2;} void dnd_tls_close(int t){(void)t;} diff --git a/src/DolphinDotNet.Core/Dolphin/Network/NativeNetwork.cs b/src/DolphinDotNet.Core/Dolphin/Network/NativeNetwork.cs index d467b6de..58ce9b15 100644 --- a/src/DolphinDotNet.Core/Dolphin/Network/NativeNetwork.cs +++ b/src/DolphinDotNet.Core/Dolphin/Network/NativeNetwork.cs @@ -7,6 +7,7 @@ internal static class NativeNetwork internal static int TlsConfigureLocalClock(byte[] roots,byte[] entropy,long localUnixSeconds)=>throw Unsupported(); internal static int TlsReset()=>throw Unsupported(); internal static int TlsStart(int handle,string hostname)=>throw Unsupported(); + internal static int TlsRandom(int handle,byte[] buffer,int offset,int count)=>throw Unsupported(); internal static int TlsHandshake(int handle)=>throw Unsupported(); internal static int NetStart(int ip,int mask,int gateway,int dhcp)=>throw Unsupported(); internal static int NetStatus()=>throw Unsupported(); diff --git a/src/DolphinDotNet.Core/Dolphin/Network/TlsStream.cs b/src/DolphinDotNet.Core/Dolphin/Network/TlsStream.cs new file mode 100644 index 00000000..081181fe --- /dev/null +++ b/src/DolphinDotNet.Core/Dolphin/Network/TlsStream.cs @@ -0,0 +1,109 @@ +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace Dolphin.Network; + +/// A certificate-validated TLS connection with caller-owned nonblocking I/O buffers. +/// Uses the configured trust, entropy and clock and negotiates HTTP/1.1. +/// Retry a would-block write with the same unmodified buffer range. This class +/// does not add HTTP, WebSocket framing or application authentication. +public sealed class TlsStream : IDisposable +{ + private readonly TcpClient client; + private readonly int[] endpoint = new int[2]; + private bool disposed; + + private TlsStream(TcpClient client) { this.client = client; } + + public static Task ConnectAsync(string hostname, int port, CancellationToken cancellationToken) + { + NetworkRuntime.RequireReady(); + if (hostname == null) throw new ArgumentNullException("hostname"); + if (hostname.Length == 0 || hostname.Length > 253 || port < 1 || port > 65535) + throw new ArgumentException("Invalid TLS endpoint."); + cancellationToken.ThrowIfCancellationRequested(); + var client = new TcpClient(); + try + { + var work = new ConnectWork(client, hostname, port, cancellationToken); + NetworkRuntime.Add(work); + return work.Completion.Task; + } + catch { client.Dispose(); throw; } + } + + // -1 means would block, zero means EOF. No Task or result allocation per poll. + public int TryRead(byte[] buffer, int offset, int count) + { + Check(); Socket.Validate(buffer, offset, count); + if (count == 0) return 0; + int read = NativeNetwork.NetRead(client.Client.Handle, buffer, offset, count, endpoint); + NetworkRuntime.Check(read); return read; + } + + // A positive result can be a short write. -1 leaves the buffer owned by the caller. + public int TryWrite(byte[] buffer, int offset, int count) + { + Check(); Socket.Validate(buffer, offset, count); + if (count == 0) return 0; + int written = NativeNetwork.NetWrite(client.Client.Handle, buffer, offset, count, 0, 0); + NetworkRuntime.Check(written); return written; + } + + /// Fill up to 256 bytes from the configured cryptographic DRBG, + /// for protocol nonces and client WebSocket masks. Pool small draws to stay + /// inside the provider's bounded entropy interval. Exhaustion fails closed + /// and requires fresh configuration after all TLS streams are closed. + public void FillRandom(byte[] buffer, int offset, int count) + { + Check(); Socket.Validate(buffer, offset, count); + if (count > 256) throw new ArgumentOutOfRangeException("count"); + if (NativeNetwork.TlsRandom(client.Client.Handle, buffer, offset, count) < 0) + throw new IOException("TLS random state requires fresh entropy."); + } + + private void Check() + { + if (disposed) throw new ObjectDisposedException("TlsStream"); + client.Client.Check(); + } + + public void Dispose() + { + if (disposed) return; + disposed = true; client.Dispose(); + } + + private sealed class ConnectWork : Operation + { + private readonly TcpClient client; + private readonly string hostname; + private readonly int port; + private readonly CancellationToken cancellation; + private Task? connecting; + private bool startedTls; + internal readonly TaskCompletionSource Completion = new TaskCompletionSource(); + internal ConnectWork(TcpClient client, string hostname, int port, CancellationToken cancellation) : base(cancellation) + { this.client = client; this.hostname = hostname; this.port = port; this.cancellation = cancellation; } + + protected override bool Step() + { + if (connecting == null) { connecting = client.ConnectAsync(hostname, port, cancellation); return false; } + if (!connecting.IsCompleted) return false; + connecting.GetAwaiter().GetResult(); + if (!startedTls) + { + if (NativeNetwork.TlsStart(client.Client.Handle, hostname) < 0) + throw new IOException("TLS is unavailable or not securely configured."); + startedTls = true; + } + int result = NativeNetwork.TlsHandshake(client.Client.Handle); + if (result == -1) return false; + if (result < 0) throw new IOException("TLS handshake or certificate verification failed."); + Completion.SetResult(new TlsStream(client)); return true; + } + protected override void Fail(Exception error) { client.Dispose(); Completion.SetException(error); } + } +} diff --git a/tools/DolphinDotNet.Compiler/NativeStorageBindings.cs b/tools/DolphinDotNet.Compiler/NativeStorageBindings.cs index e905b5f4..47121492 100644 --- a/tools/DolphinDotNet.Compiler/NativeStorageBindings.cs +++ b/tools/DolphinDotNet.Compiler/NativeStorageBindings.cs @@ -225,6 +225,7 @@ internal static class NativeStorageBindings ["TlsConfigureLocalClock"]=("dnd_net_tls_configure_local_clock","aal",false), ["Fill"]=("dnd_platform_entropy_fill_array","ai",false), ["TlsReset"]=("dnd_net_tls_reset","",false), + ["TlsRandom"]=("dnd_net_tls_random","iaii",false), ["TlsStart"]=("dnd_net_tls_start","is",false),["TlsHandshake"]=("dnd_net_tls_handshake","i",false), ["NetStart"]=("dnd_net_start","iiii",false),["NetStatus"]=("dnd_net_status","",false),["NetTime"]=("dnd_net_time","",false),["NetError"]=("dnd_net_error","",false), ["NetOpen"]=("dnd_net_open","i",false),["NetBind"]=("dnd_net_bind","iii",false),["NetListen"]=("dnd_net_listen","ii",false),["NetAccept"]=("dnd_net_accept","ia",false),