Files
Alphaeus Mote 5eb4edf900 feat(screen): Being Viewed banner in the signed-in user's session, with Stop
- New src/Agent.Banner (ExecuteR-Banner.exe): a WinForms tool window at the
  top centre, always on top, never activated, draggable, per-monitor DPI,
  light/dark/high contrast, embedded icon (assets/icons/banner.ico: the
  product tile with an eye). "Being Viewed by <operator> · View Only|Control"
  and Stop, one row per session. Hardens DLL search first thing; talks only
  to a pipe owned by SYSTEM and served from session 0, at Identification.
- Agent: ScreenBanner follows the open sessions and the console and decides
  (ScreenBannerPolicy) when the banner runs: policy off, Windows PE, nothing
  open, nobody signed in -> never; console switch, sign-out, another user ->
  end (and launch for whoever is there); a banner that went away -> end,
  retry after 30 s. WindowsScreenBannerLauncher starts it with
  WTSQueryUserToken (the filtered token, never SYSTEM), the user's
  environment, winsta0\default, no inherited handles, image-load
  mitigations, a kill-on-close job, from the protected agent folder.
- IPC (ScreenBannerProtocol, ScreenBannerConnection): a per-launch nonce pipe
  created first (first instance, one instance, SYSTEM owner, SYSTEM full +
  the user's SID read/write, network denied); the client must be the
  launched PID in its session (GetNamedPipeClientProcessId /
  GetNamedPipeClientSessionId). Service -> banner: display data only.
  Banner -> service: exactly "stop <id>", 64-byte lines, honoured only for a
  session it shows in its console session; anything else ends it.
- Stop: the agent sends a final StoppedAtDevice state and ends the streams,
  and refuses a reconnect of that session (status "stopped"). The server ends
  the session with its own reason "Stopped by the user at the device." and
  audits it as ended. The open request now carries the operator's display
  name for the banner.
- RemoteViewBanner (default off) is read like the other Remote View policy
  values and reported in the inventory policy (on only where the banner can
  run).
- Tests: protocol (only a valid stop of a shown session, garbage, overlong
  and non-UTF-8 lines, wrong client PID or session refused), launcher
  decisions, the banner manager with a fake launcher, the agent's display
  data and stop path, the pipe ACL, the protected-folder check, the
  server's handling and audit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 14:44:59 -05:00

805 lines
33 KiB
C#
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.IO.Pipelines;
using System.IO.Pipes;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text;
using Agent.Screen;
using Microsoft.Extensions.Logging.Abstractions;
using Shared.Contracts.Messages;
using Shared.Contracts.Models;
using Xunit;
namespace Agent.Tests;
/// <summary>Two in-memory streams joined back to back: what one end writes, the other reads.</summary>
internal sealed class DuplexStream(Stream reading, Stream writing) : Stream
{
public static (DuplexStream Service, DuplexStream Banner) Pair()
{
var toBanner = new Pipe();
var toService = new Pipe();
return (
new DuplexStream(toService.Reader.AsStream(), toBanner.Writer.AsStream()),
new DuplexStream(toBanner.Reader.AsStream(), toService.Writer.AsStream()));
}
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => true;
public override long Length => throw new NotSupportedException();
public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
public override void Flush() => writing.Flush();
public override Task FlushAsync(CancellationToken cancellationToken) => writing.FlushAsync(cancellationToken);
public override int Read(byte[] buffer, int offset, int count) => reading.Read(buffer, offset, count);
public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default) => reading.ReadAsync(buffer, cancellationToken);
public override void Write(byte[] buffer, int offset, int count) => writing.Write(buffer, offset, count);
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default) => writing.WriteAsync(buffer, cancellationToken);
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
protected override void Dispose(bool disposing)
{
if (disposing)
{
reading.Dispose();
writing.Dispose();
}
base.Dispose(disposing);
}
}
/// <summary>The service's end of a banner pipe, with whatever client the test says connected.</summary>
internal sealed class FakeBannerPipe(int? clientProcess, int? clientSession) : IScreenBannerPipe
{
private readonly (DuplexStream Service, DuplexStream Banner) ends = DuplexStream.Pair();
public bool Connects { get; init; } = true;
public bool Disposed { get; private set; }
public Stream Stream => ends.Service;
/// <summary>The banner's end.</summary>
public Stream Banner => ends.Banner;
public int? ClientProcessId => clientProcess;
public int? ClientSessionId => clientSession;
public Task WaitForConnectionAsync(CancellationToken cancellationToken)
=> Connects ? Task.CompletedTask : Task.Delay(Timeout.Infinite, cancellationToken);
public ValueTask DisposeAsync()
{
Disposed = true;
ends.Service.Dispose();
ends.Banner.Dispose();
return ValueTask.CompletedTask;
}
/// <summary>The banner reads the service's next line.</summary>
public async Task<IReadOnlyList<ScreenBannerItem>> NextShowAsync(ScreenBannerLineReader reader)
{
var line = await reader.ReadLineAsync(CancellationToken.None).WaitAsync(TimeSpan.FromSeconds(10));
Assert.True(ScreenBannerProtocol.TryParseShow(line, out var items), $"Not a display line: {line}");
return items;
}
/// <summary>The banner sends a raw line.</summary>
public async Task SendAsync(string line)
{
await Banner.WriteAsync(Encoding.UTF8.GetBytes(line + "\n"));
await Banner.FlushAsync();
}
}
/// <summary>Starts nothing: hands out fake banners and remembers each launch.</summary>
internal sealed class FakeBannerLauncher : IScreenBannerLauncher
{
private int nextProcess = 4000;
public List<(int Session, string PipeName, FakeBannerInstance Instance)> Launched { get; } = [];
/// <summary>Who the kernel says connects (null: the process launched, in its session).</summary>
public Func<int, int, (int? Process, int? Session)>? Client { get; set; }
public bool Fails { get; set; }
public IScreenBannerInstance Launch(int session, string pipeName)
{
if (Fails)
{
throw new InvalidOperationException("Nobody is signed in.");
}
var process = Interlocked.Increment(ref nextProcess);
var (clientProcess, clientSession) = Client?.Invoke(process, session) ?? (process, session);
var instance = new FakeBannerInstance(process, session, new FakeBannerPipe(clientProcess, clientSession));
lock (Launched)
{
Launched.Add((session, pipeName, instance));
}
return instance;
}
}
internal sealed class FakeBannerInstance(int processId, int sessionId, FakeBannerPipe pipe) : IScreenBannerInstance
{
private readonly TaskCompletionSource<int> exited = new(TaskCreationOptions.RunContinuationsAsynchronously);
public int ProcessId => processId;
public int SessionId => sessionId;
public IScreenBannerPipe Pipe => pipe;
public FakeBannerPipe FakePipe => pipe;
public Task<int> Exited => exited.Task;
public bool Killed { get; private set; }
public void Kill()
{
Killed = true;
exited.TrySetResult(1);
}
/// <summary>The banner exits by itself (the user ended it in Task Manager).</summary>
public void Exit() => exited.TrySetResult(0);
public async ValueTask DisposeAsync()
{
Kill();
await pipe.DisposeAsync();
}
}
/// <summary>Records what <see cref="ScreenSessions"/> tells the banner.</summary>
internal sealed class RecordingBannerSink : IScreenBannerSink
{
private readonly List<IReadOnlyList<ScreenBannerEntry>> shown = [];
public IReadOnlyList<ScreenBannerEntry> Last
{
get
{
lock (shown)
{
return shown.Count == 0 ? [] : shown[^1];
}
}
}
public void Show(IReadOnlyList<ScreenBannerEntry> entries)
{
lock (shown)
{
shown.Add(entries);
}
}
}
public class ScreenBannerProtocolTests
{
private static readonly Guid Id = Guid.Parse("6f1c2a4e-9b3d-4e57-8a21-c0d4e5f6a7b8");
[Fact]
public void OnlyAStopLineIsAStop()
{
Assert.True(ScreenBannerProtocol.TryParseStop(ScreenBannerProtocol.StopLine(Id), out var parsed));
Assert.Equal(Id, parsed);
Assert.Equal("stop 6f1c2a4e-9b3d-4e57-8a21-c0d4e5f6a7b8", ScreenBannerProtocol.StopLine(Id));
string?[] garbage =
[
null,
"",
"stop",
"stop ",
"STOP 6f1c2a4e-9b3d-4e57-8a21-c0d4e5f6a7b8",
"stop 6F1C2A4E-9B3D-4E57-8A21-C0D4E5F6A7B8",
" stop 6f1c2a4e-9b3d-4e57-8a21-c0d4e5f6a7b8",
"stop 6f1c2a4e-9b3d-4e57-8a21-c0d4e5f6a7b8 ",
"stop 6f1c2a4e-9b3d-4e57-8a21-c0d4e5f6a7b8",
"stop {6f1c2a4e-9b3d-4e57-8a21-c0d4e5f6a7b8}",
"stop 6f1c2a4e9b3d4e578a21c0d4e5f6a7b8",
"stop 6f1c2a4e-9b3d-4e57-8a21-c0d4e5f6a7b8 extra",
"stop 00000000-0000-0000-0000-000000000000",
"stop 6f1c2a4e-9b3d-4e57-8a21-c0d4e5f6a7bz",
"end 6f1c2a4e-9b3d-4e57-8a21-c0d4e5f6a7b8",
"{\"type\":\"stop\",\"sessionId\":\"6f1c2a4e-9b3d-4e57-8a21-c0d4e5f6a7b8\"}",
"run calc.exe",
];
foreach (var line in garbage)
{
Assert.False(ScreenBannerProtocol.TryParseStop(line, out _), $"Accepted: {line}");
}
}
[Fact]
public void PipeNamesAreThePrefixAndANonce()
{
Assert.True(ScreenBannerProtocol.IsPipeName(ScreenBannerProtocol.PipeName(new string('a', 16) + "0123456789abcdef")));
Assert.False(ScreenBannerProtocol.IsPipeName("ExecuteR-Banner-"));
Assert.False(ScreenBannerProtocol.IsPipeName("ExecuteR-Banner-0123456789ABCDEF0123456789abcdef"));
Assert.False(ScreenBannerProtocol.IsPipeName("Other-0123456789abcdef0123456789abcdef"));
Assert.False(ScreenBannerProtocol.IsPipeName(@"ExecuteR-Banner-0123456789abcdef0123456789abcde\"));
Assert.False(ScreenBannerProtocol.IsPipeName(null));
}
[Fact]
public void TheDisplayLineCarriesTheSessionTheOperatorAndTheMode()
{
var line = ScreenBannerProtocol.ShowLine([new(Id, "Ann Smith", ViewOnly: false), new(Guid.Empty, "Bob", ViewOnly: true)]);
Assert.Contains("\"sessionId\":\"6f1c2a4e-9b3d-4e57-8a21-c0d4e5f6a7b8\"", line);
Assert.Contains("\"mode\":\"control\"", line);
Assert.Contains("\"mode\":\"view-only\"", line);
Assert.True(ScreenBannerProtocol.TryParseShow(line, out var items));
Assert.Equal([new ScreenBannerItem(Id, "Ann Smith", false), new ScreenBannerItem(Guid.Empty, "Bob", true)], items);
Assert.True(ScreenBannerProtocol.TryParseShow(ScreenBannerProtocol.ShowLine([]), out var none));
Assert.Empty(none);
}
[Fact]
public void AMalformedDisplayLineIsRefused()
{
string[] bad =
[
"",
"[]",
"{}",
"{\"sessions\":{}}",
"{\"sessions\":[{\"sessionId\":\"x\",\"operator\":\"a\",\"mode\":\"control\"}]}",
"{\"sessions\":[{\"sessionId\":\"6f1c2a4e-9b3d-4e57-8a21-c0d4e5f6a7b8\",\"operator\":\"a\",\"mode\":\"admin\"}]}",
"{\"sessions\":[{\"sessionId\":\"6f1c2a4e-9b3d-4e57-8a21-c0d4e5f6a7b8\",\"mode\":\"control\"}]}",
"{\"sessions\":[1,2,3,4,5]}",
"not json",
"{\"sessions\":[" + string.Join(',', Enumerable.Repeat("{\"sessionId\":\"6f1c2a4e-9b3d-4e57-8a21-c0d4e5f6a7b8\",\"operator\":\"a\",\"mode\":\"control\"}", 5)) + "]}",
];
foreach (var line in bad)
{
Assert.False(ScreenBannerProtocol.TryParseShow(line, out _), $"Accepted: {line}");
}
}
[Fact]
public void OperatorNamesAreCleanedForDisplay()
{
// Bidirectional overrides and control characters could make the banner read otherwise.
Assert.Equal("Ann evil", ScreenBannerProtocol.CleanOperator("Ann‮ evil\r\n\t"));
Assert.Equal("An administrator", ScreenBannerProtocol.CleanOperator(" ​ "));
Assert.Equal("An administrator", ScreenBannerProtocol.CleanOperator(null));
var longName = ScreenBannerProtocol.CleanOperator(new string('x', 500));
Assert.Equal(ScreenBannerProtocol.MaxOperatorLength + 1, longName.Length);
Assert.EndsWith("…", longName);
}
[Fact]
public async Task TheLineReaderStopsAtItsLimit()
{
var reader = new ScreenBannerLineReader(new MemoryStream(Encoding.UTF8.GetBytes("one\r\ntwo\n")), 16);
Assert.Equal("one", await reader.ReadLineAsync(CancellationToken.None));
Assert.Equal("two", await reader.ReadLineAsync(CancellationToken.None));
Assert.Null(await reader.ReadLineAsync(CancellationToken.None));
var flood = new ScreenBannerLineReader(new MemoryStream(Encoding.UTF8.GetBytes(new string('x', 100_000))), ScreenBannerProtocol.MaxBannerLineBytes);
await Assert.ThrowsAsync<InvalidDataException>(() => flood.ReadLineAsync(CancellationToken.None));
var longLine = new ScreenBannerLineReader(new MemoryStream(Encoding.UTF8.GetBytes(new string('x', 65) + "\n")), ScreenBannerProtocol.MaxBannerLineBytes);
await Assert.ThrowsAsync<InvalidDataException>(() => longLine.ReadLineAsync(CancellationToken.None));
var notUtf8 = new ScreenBannerLineReader(new MemoryStream([0x73, 0xFF, 0xFE, 0x0A]), 16);
await Assert.ThrowsAsync<InvalidDataException>(() => notUtf8.ReadLineAsync(CancellationToken.None));
}
}
public class ScreenBannerConnectionTests
{
private static readonly Guid Shown = Guid.NewGuid();
[Theory]
[InlineData(4321, 2, "wrong process")]
[InlineData(1234, 3, "wrong session")]
[InlineData(null, 2, "no process id")]
[InlineData(1234, null, "no session id")]
public async Task AClientThatIsNotTheLaunchedProcessIsRefused(int? process, int? session, string because)
{
var pipe = new FakeBannerPipe(process, session);
var connection = await ScreenBannerConnection.AcceptAsync(pipe, processId: 1234, session: 2, TimeSpan.FromSeconds(5), NullLogger.Instance, CancellationToken.None);
Assert.True(connection is null, because);
Assert.True(pipe.Disposed);
}
[Fact]
public async Task NoClientInTimeIsRefused()
{
var pipe = new FakeBannerPipe(1234, 2) { Connects = false };
Assert.Null(await ScreenBannerConnection.AcceptAsync(pipe, 1234, 2, TimeSpan.FromMilliseconds(100), NullLogger.Instance, CancellationToken.None));
Assert.True(pipe.Disposed);
}
private static async Task<(ScreenBannerConnection Connection, FakeBannerPipe Pipe, ScreenBannerLineReader Banner)> ConnectedAsync()
{
var pipe = new FakeBannerPipe(1234, 2);
var connection = await ScreenBannerConnection.AcceptAsync(pipe, 1234, 2, TimeSpan.FromSeconds(5), NullLogger.Instance, CancellationToken.None);
Assert.NotNull(connection);
var banner = new ScreenBannerLineReader(pipe.Banner, ScreenBannerProtocol.MaxServiceLineBytes);
await connection.SendAsync([new ScreenBannerItem(Shown, "Ann", ViewOnly: true)], CancellationToken.None);
Assert.Equal([new ScreenBannerItem(Shown, "Ann", true)], await pipe.NextShowAsync(banner));
return (connection, pipe, banner);
}
[Fact]
public async Task OnlyAStopForAShownSessionIsPassedOn()
{
var (connection, pipe, _) = await ConnectedAsync();
var stopped = new List<Guid>();
var reading = connection.ReadAsync(id => { lock (stopped) { stopped.Add(id); } return true; }, CancellationToken.None);
await pipe.SendAsync(ScreenBannerProtocol.StopLine(Guid.NewGuid()));
await pipe.SendAsync(ScreenBannerProtocol.StopLine(Shown));
await ScreenHostTestKit.WaitUntilAsync(() => { lock (stopped) { return stopped.Count > 0; } });
Assert.Equal([Shown], stopped);
Assert.False(reading.IsCompleted);
await pipe.Banner.DisposeAsync();
Assert.Equal("The banner closed its pipe.", await reading.WaitAsync(TimeSpan.FromSeconds(10)));
}
[Theory]
[InlineData("hello")]
[InlineData("stop all")]
[InlineData("{\"sessions\":[]}")]
public async Task GarbageEndsTheBanner_AndStopsNothing(string line)
{
var (connection, pipe, _) = await ConnectedAsync();
var stopped = 0;
var reading = connection.ReadAsync(_ => { Interlocked.Increment(ref stopped); return true; }, CancellationToken.None);
await pipe.SendAsync(line);
await pipe.SendAsync(ScreenBannerProtocol.StopLine(Shown));
Assert.Equal("The banner broke the protocol.", await reading.WaitAsync(TimeSpan.FromSeconds(10)));
Assert.Equal(0, stopped);
}
[Fact]
public async Task AnOverlongLineEndsTheBanner()
{
var (connection, pipe, _) = await ConnectedAsync();
var stopped = 0;
var reading = connection.ReadAsync(_ => { Interlocked.Increment(ref stopped); return true; }, CancellationToken.None);
await pipe.SendAsync(ScreenBannerProtocol.StopLine(Shown) + new string(' ', 200));
Assert.Equal("The banner broke the protocol.", await reading.WaitAsync(TimeSpan.FromSeconds(10)));
Assert.Equal(0, stopped);
}
[Fact]
public async Task AStopForASessionNoLongerShownIsIgnored()
{
var (connection, pipe, banner) = await ConnectedAsync();
var stopped = 0;
var reading = connection.ReadAsync(_ => { Interlocked.Increment(ref stopped); return true; }, CancellationToken.None);
await connection.SendAsync([], CancellationToken.None);
Assert.Empty(await pipe.NextShowAsync(banner));
await pipe.SendAsync(ScreenBannerProtocol.StopLine(Shown));
await Task.Delay(200);
Assert.Equal(0, stopped);
Assert.False(reading.IsCompleted);
await connection.DisposeAsync();
}
}
public class ScreenBannerPolicyTests
{
private static ScreenBannerDecision Decide(
bool enabled = true, bool winPe = false, int? console = 2, string? user = @"CONTOSO\ann", bool anyToShow = true, ScreenBannerRunning? running = null)
=> ScreenBannerPolicy.Decide(enabled, winPe, console, user, anyToShow, running);
private static readonly ScreenBannerRunning Running = new(2, @"CONTOSO\ann", Gone: false);
[Fact]
public void ASessionOpenWithSomeoneSignedInLaunches()
=> Assert.Equal(ScreenBannerAction.Launch, Decide().Action);
[Fact]
public void PolicyOffNeverLaunches_AndEndsOneRunning()
{
Assert.Equal(ScreenBannerAction.None, Decide(enabled: false).Action);
Assert.Equal(ScreenBannerAction.End, Decide(enabled: false, running: Running).Action);
}
[Fact]
public void WindowsPeNeverLaunches()
{
Assert.Equal(ScreenBannerAction.None, Decide(winPe: true).Action);
Assert.Equal(ScreenBannerAction.End, Decide(winPe: true, running: Running).Action);
}
[Fact]
public void NobodySignedInNeverLaunches()
{
Assert.Equal(ScreenBannerAction.None, Decide(user: null).Action);
Assert.Equal(ScreenBannerAction.None, Decide(user: "").Action);
Assert.Equal(ScreenBannerAction.None, Decide(console: null, user: null).Action);
Assert.Equal(ScreenBannerAction.End, Decide(user: null, running: Running).Action);
}
[Fact]
public void NothingToShowNeverLaunches_AndEndsOneRunning()
{
Assert.Equal(ScreenBannerAction.None, Decide(anyToShow: false).Action);
Assert.Equal(ScreenBannerAction.End, Decide(anyToShow: false, running: Running).Action);
}
[Fact]
public void AConsoleSwitchOrAnotherUserEndsTheRunningOne()
{
Assert.Equal(ScreenBannerAction.End, Decide(console: 3, running: Running).Action);
Assert.Equal(ScreenBannerAction.End, Decide(console: null, running: Running).Action);
Assert.Equal(ScreenBannerAction.End, Decide(user: @"CONTOSO\bob", running: Running).Action);
Assert.Equal(ScreenBannerAction.Keep, Decide(user: @"contoso\ANN", running: Running).Action);
}
[Fact]
public void ABannerThatWentAwayEnds()
=> Assert.Equal(ScreenBannerAction.End, Decide(running: Running with { Gone = true }).Action);
}
public class ScreenBannerTests
{
private static readonly Guid Session = Guid.NewGuid();
private sealed class Harness
{
public FakeDesktop Desktop { get; } = new() { Session = 2, User = @"CONTOSO\ann" };
public FakeBannerLauncher Launcher { get; } = new();
public bool Enabled { get; set; } = true;
public List<(Guid Session, int? Console)> Stopped { get; } = [];
public ScreenBanner Banner { get; }
public Harness(bool winPe = false)
{
Banner = new ScreenBanner(Launcher, Desktop, () => Enabled, winPe, (id, console) =>
{
lock (Stopped)
{
Stopped.Add((id, console));
}
return true;
}, NullLogger.Instance);
}
public FakeBannerInstance Last => Launcher.Launched[^1].Instance;
}
private static ScreenBannerEntry Entry(int? console = 2, bool viewOnly = false, string name = "Ann Smith")
=> new(Session, name, viewOnly, console);
[Fact]
public async Task AnOpenSessionStartsTheBanner_WithTheDisplayData()
{
var harness = new Harness();
harness.Banner.Show([Entry(viewOnly: true)]);
await harness.Banner.ReconcileAsync(CancellationToken.None);
var (session, pipeName, instance) = Assert.Single(harness.Launcher.Launched);
Assert.Equal(2, session);
Assert.True(ScreenBannerProtocol.IsPipeName(pipeName));
var reader = new ScreenBannerLineReader(instance.FakePipe.Banner, ScreenBannerProtocol.MaxServiceLineBytes);
Assert.Equal([new ScreenBannerItem(Session, "Ann Smith", true)], await instance.FakePipe.NextShowAsync(reader));
await harness.Banner.DisposeAsync();
Assert.True(instance.Killed);
}
[Fact]
public async Task EveryLaunchHasItsOwnPipeNonce()
{
var harness = new Harness();
harness.Banner.Show([Entry()]);
await harness.Banner.ReconcileAsync(CancellationToken.None);
harness.Desktop.Session = 5;
harness.Banner.Show([Entry(console: 5)]);
await harness.Banner.ReconcileAsync(CancellationToken.None);
Assert.Equal(2, harness.Launcher.Launched.Count);
Assert.NotEqual(harness.Launcher.Launched[0].PipeName, harness.Launcher.Launched[1].PipeName);
await harness.Banner.DisposeAsync();
}
[Fact]
public async Task PolicyOff_WindowsPe_OrNobodySignedIn_NeverLaunch()
{
var off = new Harness { Enabled = false };
off.Banner.Show([Entry()]);
await off.Banner.ReconcileAsync(CancellationToken.None);
Assert.Empty(off.Launcher.Launched);
var winPe = new Harness(winPe: true);
winPe.Banner.Show([Entry()]);
await winPe.Banner.ReconcileAsync(CancellationToken.None);
Assert.Empty(winPe.Launcher.Launched);
var nobody = new Harness();
nobody.Desktop.User = null;
nobody.Banner.Show([Entry()]);
await nobody.Banner.ReconcileAsync(CancellationToken.None);
Assert.Empty(nobody.Launcher.Launched);
var nothing = new Harness();
await nothing.Banner.ReconcileAsync(CancellationToken.None);
Assert.Empty(nothing.Launcher.Launched);
}
[Fact]
public async Task ASessionInAnotherConsoleSessionIsNotShown()
{
var harness = new Harness();
harness.Banner.Show([Entry(console: 7)]);
await harness.Banner.ReconcileAsync(CancellationToken.None);
Assert.Empty(harness.Launcher.Launched);
}
[Fact]
public async Task AConsoleSwitchEndsTheBanner_AndANewUserGetsTheirOwn()
{
var harness = new Harness();
harness.Banner.Show([Entry()]);
await harness.Banner.ReconcileAsync(CancellationToken.None);
var first = harness.Last;
// Fast user switch: bob is at the console now, in session 3; the Remote View follows.
harness.Desktop.Session = 3;
harness.Desktop.User = @"CONTOSO\bob";
harness.Banner.Show([Entry(console: 3)]);
await harness.Banner.ReconcileAsync(CancellationToken.None);
Assert.True(first.Killed);
Assert.Equal(2, harness.Launcher.Launched.Count);
Assert.Equal(3, harness.Last.SessionId);
Assert.False(harness.Last.Killed);
await harness.Banner.DisposeAsync();
}
[Fact]
public async Task SigningOutEndsTheBanner()
{
var harness = new Harness();
harness.Banner.Show([Entry()]);
await harness.Banner.ReconcileAsync(CancellationToken.None);
harness.Desktop.User = null;
await harness.Banner.ReconcileAsync(CancellationToken.None);
Assert.True(harness.Last.Killed);
Assert.Null(harness.Banner.RunningProcessId);
Assert.Single(harness.Launcher.Launched);
}
[Fact]
public async Task TheSessionEndingEndsTheBanner()
{
var harness = new Harness();
harness.Banner.Show([Entry()]);
await harness.Banner.ReconcileAsync(CancellationToken.None);
harness.Banner.Show([]);
await harness.Banner.ReconcileAsync(CancellationToken.None);
Assert.True(harness.Last.Killed);
}
[Fact]
public async Task ABannerThatIsNotTheLaunchedProcessIsKilled()
{
var harness = new Harness();
harness.Launcher.Client = (process, session) => (process + 1, session);
harness.Banner.Show([Entry()]);
await harness.Banner.ReconcileAsync(CancellationToken.None);
Assert.True(harness.Last.Killed);
Assert.Null(harness.Banner.RunningProcessId);
// And it is not retried straight away.
await harness.Banner.ReconcileAsync(CancellationToken.None);
Assert.Single(harness.Launcher.Launched);
}
[Fact]
public async Task ALaunchThatFailsIsNotRetriedStraightAway()
{
var harness = new Harness();
harness.Launcher.Fails = true;
harness.Banner.Show([Entry()]);
await harness.Banner.ReconcileAsync(CancellationToken.None);
harness.Launcher.Fails = false;
await harness.Banner.ReconcileAsync(CancellationToken.None);
Assert.Empty(harness.Launcher.Launched);
}
[Fact]
public async Task StopFromTheBannerStopsThatSession_InItsConsoleSession()
{
var harness = new Harness();
harness.Banner.Show([Entry()]);
await harness.Banner.ReconcileAsync(CancellationToken.None);
var pipe = harness.Last.FakePipe;
var reader = new ScreenBannerLineReader(pipe.Banner, ScreenBannerProtocol.MaxServiceLineBytes);
await pipe.NextShowAsync(reader);
await pipe.SendAsync(ScreenBannerProtocol.StopLine(Guid.NewGuid()));
await pipe.SendAsync(ScreenBannerProtocol.StopLine(Session));
await ScreenHostTestKit.WaitUntilAsync(() => { lock (harness.Stopped) { return harness.Stopped.Count > 0; } });
Assert.Equal([(Session, (int?)2)], harness.Stopped);
await harness.Banner.DisposeAsync();
}
[Fact]
public async Task GarbageFromTheBannerEndsIt()
{
var harness = new Harness();
harness.Banner.Show([Entry()]);
await harness.Banner.ReconcileAsync(CancellationToken.None);
var instance = harness.Last;
await instance.FakePipe.SendAsync("rm -rf");
await ScreenHostTestKit.WaitUntilAsync(() =>
{
harness.Banner.ReconcileAsync(CancellationToken.None).GetAwaiter().GetResult();
return instance.Killed;
});
Assert.Empty(harness.Stopped);
Assert.Single(harness.Launcher.Launched);
}
}
public class WindowsScreenBannerPipeSecurityTests
{
[Fact]
public void ThePipeIsOwnedBySystem_AndOpenOnlyToSystemAndTheOneUser()
{
var user = new SecurityIdentifier("S-1-5-21-1111111111-2222222222-3333333333-1001");
var system = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null);
var security = WindowsScreenBannerLauncher.PipeSecurityFor(user);
Assert.Equal(system, security.GetOwner(typeof(SecurityIdentifier)));
Assert.True(security.AreAccessRulesProtected);
var rules = security.GetAccessRules(true, true, typeof(SecurityIdentifier)).Cast<PipeAccessRule>().ToList();
Assert.Equal(3, rules.Count);
Assert.Contains(rules, r => r.IdentityReference.Equals(system)
&& r.AccessControlType == AccessControlType.Allow
&& r.PipeAccessRights.HasFlag(PipeAccessRights.FullControl));
var mine = Assert.Single(rules, r => r.IdentityReference.Equals(user));
Assert.Equal(AccessControlType.Allow, mine.AccessControlType);
Assert.True(mine.PipeAccessRights.HasFlag(PipeAccessRights.ReadWrite));
// The user cannot make a second instance of the pipe, nor change who may open it.
Assert.False(mine.PipeAccessRights.HasFlag(PipeAccessRights.CreateNewInstance));
Assert.False(mine.PipeAccessRights.HasFlag(PipeAccessRights.ChangePermissions));
Assert.False(mine.PipeAccessRights.HasFlag(PipeAccessRights.TakeOwnership));
Assert.Contains(rules, r => r.IdentityReference.Equals(new SecurityIdentifier(WellKnownSidType.NetworkSid, null))
&& r.AccessControlType == AccessControlType.Deny);
}
[Fact]
public void TheLauncherRefusesANameThatIsNotABannerPipe()
=> Assert.Throws<ArgumentException>(() => new WindowsScreenBannerLauncher(@"C:\nowhere\ExecuteR-Banner.exe").Launch(1, @"..\..\pipe\evil"));
[Fact]
public void TheBannerOnlyRunsFromAProtectedFolder()
{
var folder = Directory.CreateTempSubdirectory("banner-");
try
{
Assert.Equal((null, "The banner is not installed."), ScreenHost.LocateBanner(folder.FullName));
// A temp folder is the user's own: a banner there would run as the next user signed in.
File.WriteAllText(Path.Combine(folder.FullName, Shared.Infrastructure.Constants.Branding.BannerExecutableName), "");
var security = folder.GetAccessControl();
security.AddAccessRule(new FileSystemAccessRule(
new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.Modify,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
folder.SetAccessControl(security);
var (path, problem) = ScreenHost.LocateBanner(folder.FullName);
Assert.Null(path);
Assert.StartsWith("The banner is not protected", problem);
}
finally
{
folder.Delete(recursive: true);
}
}
}
public class ScreenSessionBannerTests
{
private static ScreenSessions Sessions(FakeDesktop desktop, RecordingBannerSink sink, Func<int?>? console = null)
{
var sessions = new ScreenSessions(
ScreenHostTestKit.Host(ScreenHostTestKit.FakeHost(), new RecordingLauncher(console), desktop),
() => true,
() => ScreenSessionPolicy.Default with { Banner = true },
NullLogger.Instance)
{
Banner = sink,
};
return sessions;
}
[Fact]
public async Task TheBannerGetsTheOperatorsDisplayName_TheMode_AndTheSession()
{
var sink = new RecordingBannerSink();
var desktop = new FakeDesktop { Session = 2 };
await using var sessions = Sessions(desktop, sink, () => 2);
var request = new ScreenOpenRequest(Guid.NewGuid(), Guid.NewGuid(), ViewOnly: true, Monitor: -1, Operator: "ann@contoso.example", OperatorName: "Ann Smith");
var server = new ScreenHostTestKit.Server(sessions, request.StreamId);
Assert.Equal(ScreenOpenStatuses.Ok, (await sessions.OpenAsync(request, server.Publish, CancellationToken.None)).Status);
Assert.Equal([new ScreenBannerEntry(request.SessionId, "Ann Smith", true, 2)], sink.Last);
sessions.Close(request.SessionId, "Closed from the console.");
Assert.Empty(sink.Last);
await ScreenHostTestKit.WaitUntilAsync(() => sessions.ActiveStreams == 0);
}
[Fact]
public async Task WithoutADisplayNameTheBannerNamesTheOperator()
{
var sink = new RecordingBannerSink();
await using var sessions = Sessions(new FakeDesktop(), sink);
var request = new ScreenOpenRequest(Guid.NewGuid(), Guid.NewGuid(), ViewOnly: false, Monitor: -1, Operator: "bob");
var server = new ScreenHostTestKit.Server(sessions, request.StreamId);
Assert.Equal(ScreenOpenStatuses.Ok, (await sessions.OpenAsync(request, server.Publish, CancellationToken.None)).Status);
Assert.Equal([new ScreenBannerEntry(request.SessionId, "bob", false, null)], sink.Last);
sessions.Close(request.SessionId, "done");
await ScreenHostTestKit.WaitUntilAsync(() => sessions.ActiveStreams == 0);
}
[Fact]
public async Task StopAtTheDeviceEndsTheSessionForGood_AndTellsTheServer()
{
var sink = new RecordingBannerSink();
var desktop = new FakeDesktop { Session = 2 };
await using var sessions = Sessions(desktop, sink, () => 2);
var request = new ScreenOpenRequest(Guid.NewGuid(), Guid.NewGuid(), false, -1, "bob");
var server = new ScreenHostTestKit.Server(sessions, request.StreamId);
Assert.Equal(ScreenOpenStatuses.Ok, (await sessions.OpenAsync(request, server.Publish, CancellationToken.None)).Status);
var receiving = server.ReceiveAsync(CancellationToken.None);
// Only for a session open in the banner's own console session.
Assert.False(sessions.StopAtDevice(request.SessionId, consoleSession: 3));
Assert.False(sessions.StopAtDevice(Guid.NewGuid(), consoleSession: 2));
Assert.True(sessions.StopAtDevice(request.SessionId, consoleSession: 2));
Assert.Equal(ScreenEndReasons.StoppedAtDevice, await receiving.WaitAsync(TimeSpan.FromSeconds(20)));
var final = Assert.Single(server.States, s => s.StoppedAtDevice == true);
Assert.Equal(ScreenSessionState.Closed, final.State);
Assert.Empty(sink.Last);
await ScreenHostTestKit.WaitUntilAsync(() => sessions.ActiveStreams == 0);
// A reconnect of the same session is refused without asking again.
var again = request with { StreamId = Guid.NewGuid() };
var reply = await sessions.OpenAsync(again, new ScreenHostTestKit.Server(sessions, again.StreamId).Publish, CancellationToken.None);
Assert.Equal(ScreenOpenStatuses.Stopped, reply.Status);
Assert.Equal(ScreenEndReasons.StoppedAtDevice, reply.Message);
Assert.Equal(0, sessions.ActiveStreams);
}
}