Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions docs/https.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
1 change: 1 addition & 0 deletions include/dnd_tls.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
18 changes: 17 additions & 1 deletion scripts/ci_https.py
Original file line number Diff line number Diff line change
Expand Up @@ -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;i<seed.Length;i++)if(seed[i]!=0)return 1;
var pipeTask=TlsStream.ConnectAsync("localhost",$PORT,default);Wait(pipeTask);
using(var pipe=pipeTask.GetAwaiter().GetResult()){
var masks=new byte[256];pipe.FillRandom(masks,0,masks.Length);bool any=false;for(int i=0;i<masks.Length;i++)any|=masks[i]!=0;if(!any)return 31;
var request=Dolphin.Text.Encoding.ASCII.GetBytes("GET /pipe HTTP/1.1\\r\\nHost: localhost\\r\\nConnection: close\\r\\n\\r\\n");
int sent=0;for(int step=0;step<2000000&&sent<request.Length;step++){int n=pipe.TryWrite(request,sent,request.Length-sent);if(n<0)continue;if(n==0)return 23;sent+=n;}
if(sent!=request.Length)return 24;
var received=new byte[128];int total=0;bool eof=false;
for(int step=0;step<2000000&&!eof;step++){int n=pipe.TryRead(received,total,received.Length-total);if(n<0)continue;if(n==0){eof=true;break;}total+=n;if(total==received.Length)return 25;}
if(!eof||total<2||received[total-2]!=(byte)'O'||received[total-1]!=(byte)'K')return 26;
try{pipe.TryRead(received,-1,1);return 27;}catch(ArgumentOutOfRangeException){}
pipe.Dispose();try{pipe.TryWrite(request,0,1);return 28;}catch(ObjectDisposedException){}
}
try{Wait(TlsStream.ConnectAsync("wrong.example",$PORT,default));return 29;}catch(IOException){}
var noPipe=new System.Threading.CancellationTokenSource();noPipe.Cancel();try{TlsStream.ConnectAsync("localhost",$PORT,noPipe.Token);return 30;}catch(OperationCanceledException){}

using(var client=new HttpClient()){
client.DefaultRequestHeaders.Add("authorization","test-secret");
foreach(string path in new[]{"/final","/relative","/network","/cross","/chunked"}){var task=client.GetStringAsync($URL+path);Wait(task);if(task.GetAwaiter().GetResult()!="OK")return 2;}
Expand Down Expand Up @@ -63,7 +78,7 @@ class Program {
TlsConfiguration.Reset();
NetworkRuntime.Stop();return 0;
}catch(Exception e){Console.WriteLine(e.Message);return 99;}}
}''').substitute(CA=json.dumps(roots),ENTROPY=','.join(map(str,entropy)),LOCAL_ENTROPY=','.join(map(str,local_entropy)),UTC=str(utc),LOCAL=str(utc+2*86400),URL=json.dumps(url),WRONG=json.dumps(wrong))
}''').substitute(CA=json.dumps(roots),ENTROPY=','.join(map(str,entropy)),LOCAL_ENTROPY=','.join(map(str,local_entropy)),UTC=str(utc),LOCAL=str(utc+2*86400),URL=json.dumps(url),WRONG=json.dumps(wrong),PORT=str(__import__('urllib.parse',fromlist=['urlsplit']).urlsplit(url).port))

def main():
run('dotnet','build','tools/DolphinDotNet.Compiler','-c','Release')
Expand Down Expand Up @@ -117,6 +132,7 @@ def peer(connection,index):
elif path==b'/chunked':reply=b'HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n1\r\nO\r\n1\r\nK\r\n0\r\n\r\n'
else:reply=b'HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK'
for byte in reply:stream.sendall(bytes([byte]))
if path==b'/pipe':stream.unwrap()
except (ssl.SSLError,ConnectionError,TimeoutError,OSError):pass
def serve(listener,index):
while True:
Expand Down
11 changes: 11 additions & 0 deletions source/tls.c
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,16 @@ int dnd_tls_handshake(int token){
if(mbedtls_ssl_get_verify_result(&sessions[i].ssl)!=0)return failure(-2);
sessions[i].ready=1;return 0;
}
int dnd_net_tls_random(int token,DndArray *output,int offset,int count){
int i=find(token);
if(i<0||!sessions[i].ready||!configured||!output||output->elements_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);
Expand All @@ -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;}
Expand Down
1 change: 1 addition & 0 deletions src/DolphinDotNet.Core/Dolphin/Network/NativeNetwork.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
109 changes: 109 additions & 0 deletions src/DolphinDotNet.Core/Dolphin/Network/TlsStream.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace Dolphin.Network;

/// <summary>A certificate-validated TLS connection with caller-owned nonblocking I/O buffers.</summary>
/// <remarks>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.</remarks>
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<TlsStream> 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;
}

/// <summary>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.</summary>
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<TlsStream> Completion = new TaskCompletionSource<TlsStream>();
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); }
}
}
1 change: 1 addition & 0 deletions tools/DolphinDotNet.Compiler/NativeStorageBindings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
Loading