enclave 是第二個經 Hyper-V 隔離的微型虛擬機器,由 Azure 容器執行個體 中的父層serverless sandbox從客體內部啟動並管理。 父系沙箱使用 aci.hostbridge.peersandbox.v1.PeerSandboxServicegRPC 服務,透過 vsock (AF_VSOCK、主機CID 2、連接埠5090),使用 sandboxctlCLI (或任何由 peersandbox.proto 產生的 gRPC 用戶端),與主機的 gRPC 服務通訊。 enclave 擁有自己的核心、CPU 與記憶體配置,沒有 IP 位址,也沒有對外網際網路存取能力,且只能由其父沙盒透過 vsock 存取。
使用隔離區將代理工作中最敏感的部分(例如處理秘密或評估不受信任輸入的程式碼)與代理程式其他部分隔離。
在本教學中,你會建立一個父沙箱,並為 enclave(properties.peerSandboxProfile)保留 CPU 與記憶體預算,在父沙箱內設定 sandboxctl CLI,啟動一個無網路的 enclave 微型虛擬機,確認該 enclave 是否在一個沒有網路存取的獨立微型虛擬機中運行,然後透過 vsock 將埠轉發到該 enclave 中的服務,並確認超出剩餘預算的 enclave 是否被拒絕。
在這個教學中,你會學到如何:
- 建立具有 enclave 預算(
peerSandboxProfile)的父沙箱 - 在父沙箱中從
sandboxctl建置或安裝peersandbox.proto - 從父環境內部啟動一個 enclave 微型虛擬機,並檢查剩餘預算
- 確認該 enclave 運行於獨立的微型虛擬機中,且無法存取網際網路
- 將連接埠從父沙箱轉送至該 enclave 中的 vsock 服務
- 確認超出剩餘預算的 enclave 請求是否被拒絕
Prerequisites
Azure 訂用帳戶。 如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶。
已使用
az login登入的 Azure CLI(2.60 版或更新版本),或其他可向 Azure Resource Manager 傳送已驗證 REST 要求的工具。在您的訂用帳戶中註冊的
Microsoft.ContainerInstance資源提供者。az provider register --namespace Microsoft.ContainerInstance --wait已將 貢獻者、Azure Deployment Stack Owner 和 儲存體 Blob 資料參與者 角色指派給您訂閱中 Compute Sandbox Groups 服務主體,以便該服務能在您的訂閱中佈建受控資源群組和快照儲存體帳戶。 要指派角色,您需要有權限在訂閱上建立角色指派,例如 擁有者 或 使用者存取管理員 角色:
subscriptionId=$(az account show --query id --output tsv) spObjectId=$(az ad sp show --id 1eeacc2b-ec4a-4b1e-977a-2b5fef2131c6 --query id --output tsv 2>/dev/null || \ az ad sp create --id 1eeacc2b-ec4a-4b1e-977a-2b5fef2131c6 --query id --output tsv) for role in "Contributor" "Azure Deployment Stack Owner" "Storage Blob Data Contributor"; do az role assignment create --assignee-object-id $spObjectId --assignee-principal-type ServicePrincipal \ --role "$role" --scope /subscriptions/$subscriptionId done角色指派可能需要最多 15 分鐘才能生效。
在您的訂閱中為 Azure 容器執行個體 中無伺服器沙盒配置的配額:
在 Azure 入口網站開啟新的支援請求(問題類型設為服務與訂閱限制(配額),配額類型設為 容器執行個體),選擇您的訂閱,然後前往「附加詳細資料」標籤。
選擇輸入詳細資料以開啟配額詳細資料窗格,選擇您的位置,為配額類型選擇 AIAgentsGroups - StandardCores (Preview),並填寫網路類型、容器類型、總 AIAgentsGroups 群組限制及 總 AIAgentsGroups 核心限制:
提交支援申請。 在您的配額申請獲核准後,請重新註冊
Microsoft.ContainerInstance資源提供者(az provider register --namespace Microsoft.ContainerInstance --wait),以便您的訂閱能接收新啟用的功能。
在建立 AI 代理群組和沙箱後(請參閱 快速入門:建立您的第一個無伺服器沙箱)後,若要連接正在執行中的沙箱,請使用由沙箱閘道 protobuf 檔案
sandboxgateway.proto產生的 gRPC 用戶端。 需要 gRPC 用戶端,因為沙箱閘道會公開一個 gRPC 服務(aci.sandboxgateway.SandboxGatewayService),用於沙盒內的操作,例如等待準備就緒、執行指令、傳輸檔案及讀取日誌。 若要使用本文件中的跨平台範例 C# CLI(支援 Linux、macOS 和 Windows),請安裝 .NET 8 SDK,並編譯 CLI。Note
如果你透過 Azure Kubernetes Service (AKS) 排程和管理無伺服器沙盒,則不需要 gRPC 用戶端。
- AI 代理程式群組,以及
{endpoint}和{accessToken},這兩者來自connect動作。 要建立一個,請完成 快速入門:建立您的第一個無伺服器沙盒。
建立帶有 enclave 預算的父沙箱
若要允許沙箱啟動 enclaves,請在建立父沙箱時設定 properties.peerSandboxProfile 。 您必須同時提供 cpu (1–64 個完整核心)與 memoryInGB (1–256 整 GB)。 這些值會保留該父沙箱中所有隔離區共享的 CPU 與記憶體總預算。
enclave 預算在建立後即無法變更。 你不能將 peerSandboxProfile 與 confidentialComputeProperties 資源界限結合使用,也不能將其與 min 和 max 資源界限結合使用,而且你無法儲存具有 enclave 預算的沙盒快照。
建立一個名為 parent1 的父沙盒,父沙盒為 1 個 CPU 核心和 1 GiB 記憶體,並設定 2 個 CPU 核心與 4 GB 記憶體的 enclave 預算:
PUT {endpoint}/sandboxes/parent1?api-version=2026-08-01-preview
Authorization: Bearer {accessToken}
Content-Type: application/json
{
"location": "centralus",
"properties": {
"image": "mcr.microsoft.com/mirror/docker/library/python:3.9-slim-bookworm",
"guestOs": "linux",
"architecture": "amd64",
"resources": {
"cpu": 1,
"memory": 1
},
"peerSandboxProfile": {
"cpu": 2,
"memoryInGB": 4
}
}
}
等到properties.provisioningState為Succeeded。 接著從回應中複製 properties.connectionString,並等待來賓系統準備就緒(WaitForReady)。 透過使用 範例 C# CLI:
dotnet run -- -cs "<parent1-connection-string>" wait
在父沙箱中設定 sandboxctl
在父沙箱內部,客體內的 sandboxctl 工具透過 vsock(5090,連接埠 aci.hostbridge.peersandbox.v1.PeerSandboxService)與主機上的 CID 2 通訊,以管理 enclaves(peer create、peer stop、peer start、peer list、peer get、peer delete 和 peer exec)及 vsock 埠轉送(forward create、forward list 和 forward delete)。
若要在 parent1 中使用 sandboxctl,你可以將 /usr/local/bin/sandboxctl 和 socat 包含在你的父沙盒映像中,或是建置 sandboxctl,將其上傳到 Azure Blob 儲存體,然後將其下載到 parent1:
依照
sandboxctl建立自包含的linux-x64二進位檔。 您可以在 Linux、macOS 或 Windows 上執行此建置;發佈的二進位檔會建立於bin/Release/net8.0/linux-x64/publish/sandboxctl。將已發佈
sandboxctl的二進位檔上傳至 Azure Blob 儲存體 容器,並產生一個短命的唯讀 SAS URL($sandboxctlSasUrl)。storageAccount="aisandboxstore$RANDOM" storageContainer="tools" az storage account create --resource-group myResourceGroup --name $storageAccount --location centralus --sku Standard_LRS az storage container create --account-name $storageAccount --name $storageContainer --auth-mode key az storage blob upload --account-name $storageAccount --container-name $storageContainer \ --name sandboxctl --file bin/Release/net8.0/linux-x64/publish/sandboxctl --overwrite --auth-mode key expiry=$(date -u -d "+1 hour" '+%Y-%m-%dT%H:%MZ' 2>/dev/null || date -u -v+1H '+%Y-%m-%dT%H:%MZ') sandboxctlSasUrl=$(az storage blob generate-sas --account-name $storageAccount --container-name $storageContainer \ --name sandboxctl --permissions r --expiry $expiry --https-only --full-uri --auth-mode key --output tsv) echo $sandboxctlSasUrl在
socat內,安裝sandboxctl並將/usr/local/bin/sandboxctl下載到$sandboxctlSasUrl(將<sandboxctl-blob-sas-url>替換為前一步驟的DownloadFromBlobstore輸出,或使用parent1):dotnet run -- -cs "<parent1-connection-string>" exec /bin/sh -c ' export DEBIAN_FRONTEND=noninteractive apt-get update -qq && apt-get install -y -qq --no-install-recommends curl socat ca-certificates curl -fsSL -o /usr/local/bin/sandboxctl "<sandboxctl-blob-sas-url>" chmod +x /usr/local/bin/sandboxctl'
從 parent 內部啟動一個 enclave 並檢查預算
從
p1(ExecSandbox)內部啟動一個名為parent1的 enclave,使用 1 個 CPU 核心和 2 GB 記憶體(--cpu 0和--memory-gb 0為預設值,會配置所有剩餘預算)。sandboxctl peer create等到飛地到達running狀態。 請使用範例 C# CLI:dotnet run -- -cs "<parent1-connection-string>" exec /usr/local/bin/sandboxctl peer create p1 --image mcr.microsoft.com/mirror/docker/library/python:3.9-slim-bookworm --cpu 1 --memory-gb 2 --timeout 300Name: p1 State: running Image: mcr.microsoft.com/mirror/docker/library/python:3.9-slim-bookworm Cores: 1 Memory (GB): 2 VM id: <vm-guid>在
parent1中列出飛地及剩餘的飛地預算:dotnet run -- -cs "<parent1-connection-string>" exec /usr/local/bin/sandboxctl peer listNAME STATE IMAGE CORES MEMORY(GB) DISK(GB) VM ID p1 running mcr.microsoft.com/mirror/docker/library/python:3.9-slim-bookworm 1 2 10 <vm-guid> Budget: cores 1/2, memory 2/4 GB
驗證 micro VM 隔離且無網路存取
比較核心程序
boot_id、CPU 數量與記憶體,比較對象為parent1和p1:dotnet run -- -cs "<parent1-connection-string>" exec /bin/sh -c ' probe="echo boot_id=\$(cut -c1-8 /proc/sys/kernel/random/boot_id) cpus=\$(nproc) memory_mb=\$(( \$(sed -n \"s/^MemTotal: *\\([0-9]*\\).*/\\1/p\" /proc/meminfo) / 1024 ))" echo "parent: $(sh -c "$probe")" echo "enclave: $(/usr/local/bin/sandboxctl peer exec p1 -- sh -c "$probe")"'父節點與 enclave 報告不同的
boot_id值與獨立的記憶體總數,這證實它p1運行在自己的微型虛擬機中,並擁有自己的 Linux 核心。parent: boot_id=4a91c8e2 cpus=1 memory_mb=972 enclave: boot_id=9f03b21d cpus=1 memory_mb=1984確認
p1沒有對外網際網路存取:dotnet run -- -cs "<parent1-connection-string>" exec /usr/local/bin/sandboxctl peer exec p1 -- /usr/local/bin/python3 -c ' import urllib.request try: urllib.request.urlopen("http://www.bing.com", timeout=5) print("RESULT=REACHABLE") except Exception as e: print("RESULT=BLOCKED (%s)" % getattr(e, "reason", e))'由於該 enclave 沒有外部網路介面,出站請求會立即失敗。
RESULT=BLOCKED ([Errno -3] Temporary failure in name resolution)
將連接埠從父端轉寄到 Enclave 內的服務
由於 enclave 沒有網路介面,父系沙箱與 enclave 僅透過 vsock 連接埠轉送 (sandboxctl forward create) 進行通訊。
在
p1中,啟動一個背景 Python 服務,監聽 vsock 埠8080(socket.AF_VSOCK),並回覆:"hello from the enclave micro VM\n"dotnet run -- -cs "<parent1-connection-string>" exec /usr/local/bin/sandboxctl peer exec p1 -- /bin/sh -c ' cat << "EOF" > /tmp/svc.py import socket s = socket.socket(socket.AF_VSOCK, socket.SOCK_STREAM) s.bind((socket.VMADDR_CID_ANY, 8080)) s.listen(5) open("/tmp/svc.ready", "w").close() while True: c, _ = s.accept() try: c.recv(1024) c.sendall(b"hello from the enclave micro VM\n") finally: c.close() EOF setsid /usr/local/bin/python3 /tmp/svc.py >/tmp/svc.log 2>&1 < /dev/null &'在
parent1中,開啟一個連接埠轉送到p1中的8080連接埠,並透過主機 vsock 中繼(CID 2)在回傳的listenPort上傳送要求:dotnet run -- -cs "<parent1-connection-string>" exec /bin/sh -c ' /usr/local/bin/sandboxctl --output json forward create --peer p1 --target-port 8080 > /tmp/fwd.json port=$(sed -n "s/.*\"listenPort\": *\([0-9]*\).*/\1/p" /tmp/fwd.json | head -1) echo "forward: parent -> host vsock port $port -> enclave p1 port 8080" reply=$( (printf "ping\n"; sleep 1) | socat -t 1 - VSOCK-CONNECT:2:$port ) echo "reply: $reply"'forward: parent -> host vsock port 40000 -> enclave p1 port 8080 reply: hello from the enclave micro VM
驗證飛地預算強制執行
parent1 在其 enclave 預算(Budget: cores 1/2, memory 2/4 GB)中僅剩一個 CPU 核心與 2 GB 記憶體。 嘗試建立第二個 enclave (p2),請求兩個 CPU 核心和 4 GB 記憶體:
dotnet run -- -cs "<parent1-connection-string>" exec /usr/local/bin/sandboxctl peer create p2 --image mcr.microsoft.com/mirror/docker/library/python:3.9-slim-bookworm --cpu 2 --memory-gb 4 --timeout 60
主機拒絕了這個請求,因為這超出了剩餘的 enclave 預算。
error: ResourceExhausted: peer budget exceeded
清理資源
刪除父沙盒。 當您刪除父沙箱時,會自動刪除其所有的 enclave 與埠轉發:
DELETE {endpoint}/sandboxes/parent1?api-version=2026-08-01-preview
Authorization: Bearer {accessToken}
如果你不打算做其他教學,請刪除 AI agents 群組和資源群組。
從 peersandbox.proto 建置 sandboxctl
你可以從 peersandbox.proto 以任何語言產生 gRPC 用戶端,並透過未加密的 HTTP/2(AF_VSOCK = 40)連線,在 Linux vsock(CID = 2,host 5090,port aci.hostbridge.peersandbox.v1.PeerSandboxService)上連線到 h2c。
使用 sandboxctl 在 C# 中建置自包含的 Linux 二進位檔:
建立一個新的專案資料夾(
SandboxCtl),將peersandbox.proto定義另存為peersandbox.proto,然後建立SandboxCtl.csproj。<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net8.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> <AssemblyName>sandboxctl</AssemblyName> <InvariantGlobalization>true</InvariantGlobalization> </PropertyGroup> <ItemGroup> <PackageReference Include="Google.Protobuf" Version="3.28.3" /> <PackageReference Include="Grpc.Net.Client" Version="2.66.0" /> <PackageReference Include="Grpc.Tools" Version="2.67.0" PrivateAssets="All" /> </ItemGroup> <ItemGroup> <Protobuf Include="peersandbox.proto" GrpcServices="Client" /> </ItemGroup> </Project>請以以下實作取代
Program.cs,該實作會透過CID 2(5090,連接埠AF_VSOCK)連線至主機,並實作peer(create、list、delete、exec、start、get、stop)和forward(create、list、delete)。using System.Runtime.InteropServices; using ACI.HostBridge.Api.PeerSandbox.V1; using Google.Protobuf; using Grpc.Core; using Grpc.Net.Client; AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); bool jsonOutput = false; uint vsockPort = 5090; var rest = new List<string>(); for (int i = 0; i < args.Length; i++) { if (args[i] == "--output" && i + 1 < args.Length) { jsonOutput = args[++i] == "json"; } else if (args[i] == "--port" && i + 1 < args.Length) { vsockPort = uint.Parse(args[++i]); } else { rest.Add(args[i]); } } if (rest.Count < 2) { Console.Error.WriteLine("Usage: sandboxctl [--output text|json] <peer|forward> <subcommand> [options]"); return 1; } var handler = new SocketsHttpHandler { ConnectCallback = (_, ct) => VsockStream.ConnectAsync(vsockPort, ct), EnableMultipleHttp2Connections = true, }; using var channel = GrpcChannel.ForAddress("http://localhost", new GrpcChannelOptions { HttpHandler = handler }); var client = new PeerSandboxService.PeerSandboxServiceClient(channel); try { if (rest[0] == "peer") { switch (rest[1]) { case "create": string name = rest[2], image = ""; int cpu = 0, memGb = 0, timeout = 300; bool noWait = false; for (int i = 3; i < rest.Count; i++) { if (rest[i] == "--image") image = rest[++i]; else if (rest[i] == "--cpu") cpu = int.Parse(rest[++i]); else if (rest[i] == "--memory-gb") memGb = int.Parse(rest[++i]); else if (rest[i] == "--timeout") timeout = int.Parse(rest[++i]); else if (rest[i] == "--no-wait") noWait = true; } var peer = (await client.CreatePeerAsync(new CreatePeerRequest { Name = name, Image = image, Cores = cpu, MemoryInGb = memGb })).Peer; DateTime deadline = DateTime.UtcNow.AddSeconds(timeout); while (!noWait && peer.State != "running" && peer.State != "failed") { if (DateTime.UtcNow >= deadline) { Console.Error.WriteLine($"error: timed out waiting for peer {name}"); return 1; } await Task.Delay(1000); peer = (await client.GetPeerAsync(new GetPeerRequest { Name = name }, deadline: deadline)).Peer; } PrintPeer(peer, jsonOutput); return peer.State == "failed" ? 1 : 0; case "list": var listResp = await client.ListPeersAsync(new ListPeersRequest()); if (jsonOutput) { Console.WriteLine(JsonFormatter.Default.Format(listResp)); return 0; } if (listResp.Peers.Count == 0) Console.WriteLine("No peers."); else { Console.WriteLine("NAME\tSTATE\tIMAGE\tCORES\tMEMORY(GB)\tDISK(GB)\tVM ID"); foreach (var p in listResp.Peers) Console.WriteLine($"{p.Name}\t{p.State}\t{p.Image}\t{p.Cores}\t{p.MemoryInGb}\t{p.DiskInGb}\t{p.VmId}"); } if (listResp.Budget is { } b) Console.WriteLine($"Budget: cores {b.UsedCores}/{b.Cores}, memory {b.UsedMemoryInGb}/{b.MemoryInGb} GB"); return 0; case "get": PrintPeer((await client.GetPeerAsync(new GetPeerRequest { Name = rest[2] })).Peer, jsonOutput); return 0; case "start": PrintPeer((await client.StartPeerAsync(new StartPeerRequest { Name = rest[2] })).Peer, jsonOutput); return 0; case "stop": PrintPeer((await client.StopPeerAsync(new StopPeerRequest { Name = rest[2] })).Peer, jsonOutput); return 0; case "delete": await client.DeletePeerAsync(new DeletePeerRequest { Name = rest[2] }); Console.WriteLine($"Deleted {rest[2]}."); return 0; case "exec": string execPeer = rest[2]; int sep = rest.IndexOf("--", 3); var cmdTokens = sep >= 0 ? rest.Skip(sep + 1).ToArray() : rest.Skip(3).ToArray(); var execReq = new ExecPeerRequest { Name = execPeer, Command = cmdTokens[0] }; execReq.Args.AddRange(cmdTokens.Skip(1)); var execResp = await client.ExecPeerAsync(execReq); Console.Out.Write(execResp.Stdout); Console.Error.Write(execResp.Stderr); return execResp.TimedOut ? 124 : execResp.ExitCode; } } else if (rest[0] == "forward") { switch (rest[1]) { case "create": string targetPeer = ""; bool toParent = false; uint targetPort = 0, listenPort = 0; for (int i = 2; i < rest.Count; i++) { if (rest[i] == "--peer") targetPeer = rest[++i]; else if (rest[i] == "--parent") toParent = true; else if (rest[i] == "--target-port") targetPort = uint.Parse(rest[++i]); else if (rest[i] == "--listen-port") listenPort = uint.Parse(rest[++i]); } var fwdResp = await client.CreateForwardAsync(new CreateForwardRequest { Peer = targetPeer, ToParent = toParent, TargetPort = targetPort, ListenPort = listenPort, }); if (jsonOutput) { Console.WriteLine(JsonFormatter.Default.Format(fwdResp)); return 0; } Console.WriteLine($"Forward id: {fwdResp.Forward.Id}\nListen port: {fwdResp.Forward.ListenPort}\nTarget: peer {fwdResp.Forward.Peer}, port {fwdResp.Forward.TargetPort}"); return 0; case "list": var fwds = await client.ListForwardsAsync(new ListForwardsRequest()); if (jsonOutput) { Console.WriteLine(JsonFormatter.Default.Format(fwds)); return 0; } foreach (var f in fwds.Forwards) Console.WriteLine($"{f.Id}\t{f.ListenPort}\t{f.Peer}\t{f.TargetPort}"); return 0; case "delete": await client.DeleteForwardAsync(new DeleteForwardRequest { Id = rest[2] }); Console.WriteLine($"Deleted {rest[2]}."); return 0; } } } catch (RpcException ex) { Console.Error.WriteLine($"error: {ex.StatusCode}: {ex.Status.Detail}"); return 1; } return 1; static void PrintPeer(PeerInfo p, bool json) { if (json) { Console.WriteLine(JsonFormatter.Default.Format(new GetPeerResponse { Peer = p })); return; } Console.WriteLine($"Name: {p.Name}\nState: {p.State}\nImage: {p.Image}\nCores: {p.Cores}\nMemory (GB): {p.MemoryInGb}\nVM id: {p.VmId}"); } internal sealed class VsockStream : Stream { private const int AF_VSOCK = 40, SOCK_STREAM = 1, EINTR = 4; private const uint VMADDR_CID_HOST = 2; private int _fd; private VsockStream(int fd) => _fd = fd; public static ValueTask<Stream> ConnectAsync(uint port, CancellationToken ct) => new(Task.Run<Stream>(() => { int fd = socket(AF_VSOCK, SOCK_STREAM, 0); if (fd < 0) throw new IOException($"vsock socket() failed (errno {Marshal.GetLastPInvokeError()})."); var addr = new SockAddrVm { svm_family = AF_VSOCK, svm_port = port, svm_cid = VMADDR_CID_HOST, svm_zero = new byte[4] }; int size = Marshal.SizeOf<SockAddrVm>(); nint ptr = Marshal.AllocHGlobal(size); try { Marshal.StructureToPtr(addr, ptr, false); if (connect(fd, ptr, (uint)size) < 0) { int e = Marshal.GetLastPInvokeError(); close(fd); throw new IOException($"vsock connect failed (errno {e})."); } } finally { Marshal.FreeHGlobal(ptr); } return new VsockStream(fd); }, ct)); public override bool CanRead => _fd >= 0; public override bool CanWrite => _fd >= 0; public override bool CanSeek => false; public override long Length => throw new NotSupportedException(); public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } public override void Flush() { } public override long Seek(long o, SeekOrigin s) => throw new NotSupportedException(); public override void SetLength(long v) => throw new NotSupportedException(); public override int Read(byte[] b, int o, int c) => ReadAsync(b, o, c, CancellationToken.None).GetAwaiter().GetResult(); public override void Write(byte[] b, int o, int c) => WriteAsync(b, o, c, CancellationToken.None).GetAwaiter().GetResult(); public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken ct) => Task.Run(() => { byte[] target = offset == 0 ? buffer : new byte[count]; while (true) { int r = recv(_fd, target, count, 0); if (r > 0) { if (offset != 0) Array.Copy(target, 0, buffer, offset, r); return r; } if (r == 0 || Marshal.GetLastPInvokeError() != EINTR) return 0; } }, ct); public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken ct) => Task.Run(() => { int sentTotal = 0; while (sentTotal < count) { byte[] chunk = new byte[count - sentTotal]; Array.Copy(buffer, offset + sentTotal, chunk, 0, chunk.Length); int s = send(_fd, chunk, chunk.Length, 0); if (s > 0) { sentTotal += s; continue; } if (Marshal.GetLastPInvokeError() != EINTR) throw new IOException("vsock send failed."); } }, ct); protected override void Dispose(bool disposing) { int fd = Interlocked.Exchange(ref _fd, -1); if (fd >= 0) close(fd); base.Dispose(disposing); } [StructLayout(LayoutKind.Sequential)] private struct SockAddrVm { public ushort svm_family, svm_reserved1; public uint svm_port, svm_cid; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] public byte[] svm_zero; } [DllImport("libc", SetLastError = true)] private static extern int socket(int domain, int type, int protocol); [DllImport("libc", SetLastError = true)] private static extern int connect(int sockfd, nint addr, uint addrlen); [DllImport("libc", SetLastError = true)] private static extern int recv(int sockfd, byte[] buf, int len, int flags); [DllImport("libc", SetLastError = true)] private static extern int send(int sockfd, byte[] buf, int len, int flags); [DllImport("libc", SetLastError = true)] private static extern int close(int fd); }以自包含的單檔案 Linux 執行檔發佈
sandboxctl(父沙箱內不需要 .NET 執行環境):dotnet publish -c Release -r linux-x64 --self-contained true -p:PublishSingleFile=true -p:EnableCompressionInSingleFile=true已發佈的二進位檔建立於
bin/Release/net8.0/linux-x64/publish/sandboxctl。
Enclave protobuf 定義 (peersandbox.proto)
將以下 protobuf 定義儲存為 peersandbox.proto:
syntax = "proto3";
option csharp_namespace = "ACI.HostBridge.Api.PeerSandbox.V1";
package aci.hostbridge.peersandbox.v1;
// Enclave (peer sandbox) management and parent<->enclave port forwarding, served by the host
// on vsock port 5090 (CID 2). The caller is identified by its VM ID.
service PeerSandboxService {
rpc CreatePeer(CreatePeerRequest) returns (CreatePeerResponse);
rpc GetPeer(GetPeerRequest) returns (GetPeerResponse);
rpc ListPeers(ListPeersRequest) returns (ListPeersResponse);
rpc StartPeer(StartPeerRequest) returns (StartPeerResponse);
rpc StopPeer(StopPeerRequest) returns (StopPeerResponse);
rpc DeletePeer(DeletePeerRequest) returns (DeletePeerResponse);
// Runs one command in the enclave. Output is returned when it exits.
rpc ExecPeer(ExecPeerRequest) returns (ExecPeerResponse);
// Interactive TTY shell in the enclave. The first message must be `start`.
rpc ShellPeer(stream ShellPeerRequest) returns (stream ShellPeerResponse);
rpc CreateForward(CreateForwardRequest) returns (CreateForwardResponse);
rpc ListForwards(ListForwardsRequest) returns (ListForwardsResponse);
rpc DeleteForward(DeleteForwardRequest) returns (DeleteForwardResponse);
}
message PeerInfo {
string name = 1;
// Current state, for example "creating", "running", "stopped", "failed", "deleting".
string state = 2;
string target_state = 3;
string image = 4;
int32 cores = 5;
int32 memory_in_gb = 6;
int32 disk_in_gb = 7;
// Hyper-V VM id of the running enclave. Empty when it is not running.
string vm_id = 8;
string failure_message = 9;
}
message PeerBudget {
int32 cores = 1;
int32 memory_in_gb = 2;
int32 used_cores = 3;
int32 used_memory_in_gb = 4;
}
message CreatePeerRequest {
// Short name, [a-z0-9]([a-z0-9-]*[a-z0-9])?, at most 32 characters.
string name = 1;
// Image reference pulled by the host, for example "myregistry.azurecr.io/app:1".
string image = 2;
// 0 means all remaining CPU in the parent budget.
int32 cores = 3;
// 0 means all remaining memory in the parent budget.
int32 memory_in_gb = 4;
// The enclave always gets the parent's disk size.
reserved 5;
reserved "disk_in_gb";
}
message CreatePeerResponse {
PeerInfo peer = 1;
}
message GetPeerRequest {
string name = 1;
}
message GetPeerResponse {
PeerInfo peer = 1;
}
message ListPeersRequest {
}
message ListPeersResponse {
repeated PeerInfo peers = 1;
PeerBudget budget = 2;
}
message StartPeerRequest {
string name = 1;
}
message StartPeerResponse {
PeerInfo peer = 1;
}
message StopPeerRequest {
string name = 1;
}
message StopPeerResponse {
PeerInfo peer = 1;
}
message DeletePeerRequest {
string name = 1;
}
message DeletePeerResponse {
}
message ExecPeerRequest {
string name = 1;
string command = 2;
repeated string args = 3;
string working_directory = 4;
map<string, string> environment = 5;
// 0 means the host default. The host clamps it to its maximum.
int32 timeout_seconds = 6;
}
message ExecPeerResponse {
int32 exit_code = 1;
string stdout = 2;
string stderr = 3;
bool timed_out = 4;
}
message ShellPeerRequest {
oneof request {
ShellStart start = 1;
// Raw terminal input. Keep each chunk at most 16 KiB.
bytes input = 2;
ShellWindowSize window_size = 3;
// Signal name, for example "SIGINT".
string signal = 4;
}
}
message ShellStart {
string name = 1;
// Empty means "/bin/sh".
string shell = 2;
map<string, string> environment = 3;
string working_directory = 4;
int32 rows = 5;
int32 cols = 6;
}
message ShellWindowSize {
int32 rows = 1;
int32 cols = 2;
}
message ShellPeerResponse {
oneof response {
ShellOutput output = 1;
ShellExited exited = 2;
string error = 3;
}
}
message ShellOutput {
enum Stream {
STDOUT = 0;
STDERR = 1;
}
Stream stream = 1;
bytes data = 2;
}
message ShellExited {
int32 exit_code = 1;
}
message ForwardInfo {
string id = 1;
string source_vm_id = 2;
string target_vm_id = 3;
// hvsock/vsock port the source (the caller) connects to on the host (CID 2).
uint32 listen_port = 4;
// Port the relay connects to in the target VM.
uint32 target_port = 5;
// Target enclave name, or empty when the target is the caller's parent.
string peer = 6;
}
message CreateForwardRequest {
// Parent callers: the target enclave name. Must be empty for enclave callers.
string peer = 1;
// Enclave callers: true to forward to the parent. Must be false for parent callers.
bool to_parent = 2;
uint32 target_port = 3;
// 0 means the relay picks a free port.
uint32 listen_port = 4;
}
message CreateForwardResponse {
ForwardInfo forward = 1;
}
message ListForwardsRequest {
}
message ListForwardsResponse {
// Only forwards whose source is the caller.
repeated ForwardInfo forwards = 1;
}
message DeleteForwardRequest {
string id = 1;
}
message DeleteForwardResponse {
}