aboutsummaryrefslogtreecommitdiff
path: root/zenserver/testing/launch.cpp
blob: f315ec1b46c6374af9d459e55e11ae89e90ee2a0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
// Copyright Epic Games, Inc. All Rights Reserved.

#include "launch.h"

#if ZEN_WITH_COMPUTE_SERVICES

#	include <zencore/compactbinary.h>
#	include <zencore/compactbinarybuilder.h>
#	include <zencore/filesystem.h>
#	include <zencore/fmtutils.h>
#	include <zencore/iobuffer.h>
#	include <zencore/iohash.h>
#	include <zencore/logging.h>
#	include <zencore/windows.h>
#	include <zenstore/cas.h>

ZEN_THIRD_PARTY_INCLUDES_START
#	include <AccCtrl.h>
#	include <AclAPI.h>
#	include <UserEnv.h>
#	include <atlbase.h>
#	include <sddl.h>
ZEN_THIRD_PARTY_INCLUDES_END
#	pragma comment(lib, "UserEnv.lib")

#	include <filesystem>
#	include <span>

using namespace std::literals;

namespace zen {

struct BasicJob
{
public:
	BasicJob() = default;
	~BasicJob();

	void SetWorkingDirectory(const std::filesystem::path& WorkingDirectory) { m_WorkingDirectory = WorkingDirectory; }
	bool SpawnJob(std::filesystem::path ExePath, std::wstring CommandLine);
	bool Wait(uint32_t TimeoutMs = ~0);
	int	 ExitCode();

private:
	std::filesystem::path m_WorkingDirectory;
	int					  m_ProcessId = 0;
	CHandle				  m_ProcessHandle;
};

BasicJob::~BasicJob()
{
	Wait();
}

bool
BasicJob::SpawnJob(std::filesystem::path ExePath, std::wstring CommandLine)
{
	STARTUPINFOEX		StartupInfo = {sizeof(STARTUPINFOEX)};
	PROCESS_INFORMATION ProcessInfo{};

	std::wstring ExePathNative	  = ExePath.native();
	std::wstring WorkingDirNative = m_WorkingDirectory.native();

	BOOL Created = ::CreateProcess(ExePathNative.data() /* ApplicationName */,
								   CommandLine.data() /* Command Line */,
								   nullptr /* Process Attributes */,
								   nullptr /* Security Attributes */,
								   FALSE /* InheritHandles */,
								   0 /* Flags */,
								   nullptr /* Environment */,
								   WorkingDirNative.data() /* Current Directory */,
								   (LPSTARTUPINFO)&StartupInfo,
								   &ProcessInfo);

	if (!Created)
	{
		throw std::system_error(::GetLastError(), std::system_category(), fmt::format("Failed to create process '{}'", ExePath).c_str());
	}

	m_ProcessId = ProcessInfo.dwProcessId;
	m_ProcessHandle.Attach(ProcessInfo.hProcess);
	::CloseHandle(ProcessInfo.hThread);

	ZEN_INFO("Created process {}", m_ProcessId);

	return true;
}

bool
BasicJob::Wait(uint32_t TimeoutMs)
{
	if (!m_ProcessHandle)
	{
		return true;
	}

	DWORD WaitResult = WaitForSingleObject(m_ProcessHandle, TimeoutMs);

	if (WaitResult == WAIT_TIMEOUT)
	{
		return false;
	}

	if (WaitResult == WAIT_OBJECT_0)
	{
		return true;
	}

	throw std::runtime_error("Failed wait on process handle");
}

int
BasicJob::ExitCode()
{
	DWORD Ec	  = 0;
	BOOL  Success = GetExitCodeProcess(m_ProcessHandle, &Ec);

	if (!Success)
	{
		ZEN_WARN("failed getting exit code");
	}

	if (Ec == STILL_ACTIVE)
	{
		ZEN_WARN("getting exit code but process is STILL_ACTIVE");
	}

	return gsl::narrow_cast<int>(Ec);
}

////////////////////////////////////////////////////////////////////////////////

struct SandboxedJob
{
	SandboxedJob()	= default;
	~SandboxedJob() = default;

	void SetWorkingDirectory(const std::filesystem::path& WorkingDirectory) { m_WorkingDirectory = WorkingDirectory; }
	void Initialize(std::string_view AppContainerId);
	bool SpawnJob(std::filesystem::path ExePath);
	void AddWhitelistFile(const std::filesystem::path& FilePath) { m_WhitelistFiles.push_back(FilePath); }

private:
	bool GrantNamedObjectAccess(PWSTR Name, SE_OBJECT_TYPE Type, ACCESS_MASK AccessMask, bool Recursive);

	std::filesystem::path			   m_WorkingDirectory;
	std::vector<std::filesystem::path> m_WhitelistFiles;
	std::vector<std::wstring>		   m_WhitelistRegistryKeys;
	PSID							   m_AppContainerSid = nullptr;
	bool							   m_IsInitialized	 = false;
};

bool
SandboxedJob::GrantNamedObjectAccess(PWSTR ObjectName, SE_OBJECT_TYPE ObjectType, ACCESS_MASK AccessMask, bool Recursive)
{
	DWORD Status;
	PACL  NewAcl = nullptr;

	DWORD grfInhericance = 0;

	if (Recursive)
	{
		grfInhericance = OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE;
	}

	EXPLICIT_ACCESS Access{.grfAccessPermissions = AccessMask,
						   .grfAccessMode		 = GRANT_ACCESS,
						   .grfInheritance		 = grfInhericance,
						   .Trustee				 = {.pMultipleTrustee		  = nullptr,
										.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE,
										.TrusteeForm			  = TRUSTEE_IS_SID,
										.TrusteeType			  = TRUSTEE_IS_GROUP,
										.ptstrName				  = (PWSTR)m_AppContainerSid}};

	PACL OldAcl = nullptr;

	Status = GetNamedSecurityInfo(ObjectName /* ObjectName */,
								  ObjectType /* ObjectType */,
								  DACL_SECURITY_INFORMATION /* SecurityInfo */,
								  nullptr /* ppsidOwner */,
								  nullptr /* ppsidGroup */,
								  &OldAcl /* ppDacl */,
								  nullptr /* ppSacl */,
								  nullptr /* ppSecurityDescriptor */);
	if (Status != ERROR_SUCCESS)
		return false;

	Status = SetEntriesInAcl(1 /* CountOfExplicitEntries */, &Access /* pListOfExplicitEntries */, OldAcl, &NewAcl);
	if (Status != ERROR_SUCCESS)
		return false;

	Status = SetNamedSecurityInfo(ObjectName /* ObjectName */,
								  ObjectType /* ObjectType */,
								  DACL_SECURITY_INFORMATION /*SecurityInfo */,
								  nullptr /* psidOwner */,
								  nullptr /* psidGroup */,
								  NewAcl /* pDacl */,
								  nullptr /* pSacl */);
	if (NewAcl)
		::LocalFree(NewAcl);

	return Status == ERROR_SUCCESS;
}

void
SandboxedJob::Initialize(std::string_view AppContainerId)
{
	if (m_IsInitialized)
	{
		return;
	}

	std::wstring ContainerName = zen::Utf8ToWide(AppContainerId);

	HRESULT hRes = ::CreateAppContainerProfile(ContainerName.c_str(),
											   ContainerName.c_str() /* Display Name */,
											   ContainerName.c_str() /* Description */,
											   nullptr /* Capabilities */,
											   0 /* Capability Count */,
											   &m_AppContainerSid);

	if (FAILED(hRes))
	{
		hRes = ::DeriveAppContainerSidFromAppContainerName(ContainerName.c_str(), &m_AppContainerSid);

		if (FAILED(hRes))
		{
			ZEN_ERROR("Failed creating app container SID");
		}
	}

	// Debugging context

	PWSTR Str = nullptr;
	::ConvertSidToStringSid(m_AppContainerSid, &Str);

	ZEN_INFO("AppContainer SID : '{}'", WideToUtf8(Str));

	PWSTR Path = nullptr;
	if (SUCCEEDED(::GetAppContainerFolderPath(Str, &Path)))
	{
		ZEN_INFO("AppContainer folder: '{}'", WideToUtf8(Path));

		::CoTaskMemFree(Path);
	}
	::LocalFree(Str);

	m_IsInitialized = true;
}

bool
SandboxedJob::SpawnJob(std::filesystem::path ExePath)
{
	// Build process attributes

	SECURITY_CAPABILITIES Sc = {0};
	Sc.AppContainerSid		 = m_AppContainerSid;

	STARTUPINFOEX		StartupInfo = {sizeof(STARTUPINFOEX)};
	PROCESS_INFORMATION ProcessInfo{};
	SIZE_T				Size = 0;

	::InitializeProcThreadAttributeList(nullptr, 1, 0, &Size);

	auto AttrBuffer				= std::make_unique<uint8_t[]>(Size);
	StartupInfo.lpAttributeList = reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(AttrBuffer.get());

	if (!::InitializeProcThreadAttributeList(StartupInfo.lpAttributeList, 1, 0, &Size))
	{
		return false;
	}

	if (!::UpdateProcThreadAttribute(StartupInfo.lpAttributeList,
									 0,
									 PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES,
									 &Sc,
									 sizeof Sc,
									 nullptr,
									 nullptr))
	{
		return false;
	}

	// Set up security for files/folders/registry

	for (const std::filesystem::path& File : m_WhitelistFiles)
	{
		std::wstring NativeFileName = File.native();
		GrantNamedObjectAccess(NativeFileName.data(), SE_FILE_OBJECT, FILE_ALL_ACCESS, true);
	}

	for (std::wstring& RegKey : m_WhitelistRegistryKeys)
	{
		GrantNamedObjectAccess(RegKey.data(), SE_REGISTRY_WOW64_32KEY, KEY_ALL_ACCESS, true);
	}

	std::wstring ExePathNative	  = ExePath.native();
	std::wstring WorkingDirNative = m_WorkingDirectory.native();

	BOOL Created = ::CreateProcess(nullptr /* ApplicationName */,
								   ExePathNative.data() /* Command line */,
								   nullptr /* Process Attributes */,
								   nullptr /* Security Attributes */,
								   FALSE /* InheritHandles */,
								   EXTENDED_STARTUPINFO_PRESENT | CREATE_NEW_CONSOLE /* Flags */,
								   nullptr /* Environment */,
								   WorkingDirNative.data() /* Current Directory */,
								   (LPSTARTUPINFO)&StartupInfo,
								   &ProcessInfo);

	DeleteProcThreadAttributeList(StartupInfo.lpAttributeList);

	if (!Created)
	{
		return false;
	}

	ZEN_INFO("Created process {}", ProcessInfo.dwProcessId);

	return true;
}

////////////////////////////////////////////////////////////////////////////////

HttpLaunchService::HttpLaunchService(CasStore& Store, const std::filesystem::path& SandboxBaseDir)
: m_Log(logging::Get("exec"))
, m_CasStore(Store)
, m_SandboxPath(SandboxBaseDir)
{
	m_Router.AddPattern("job", "([[:digit:]]+)");

	m_Router.RegisterRoute(
		"jobs/{job}",
		[this](HttpRouterRequest& Req) {
			HttpServerRequest& HttpReq = Req.ServerRequest();

			switch (HttpReq.RequestVerb())
			{
				case HttpVerb::kGet:
					break;

				case HttpVerb::kPost:
					break;

				default:
					break;
			}
		},
		HttpVerb::kGet | HttpVerb::kPost);

	// Experimental

#	if 0
	m_Router.RegisterRoute(
		"jobs/sandbox",
		[this](HttpRouterRequest& Req) {
			HttpServerRequest& HttpReq = Req.ServerRequest();

			switch (HttpReq.RequestVerb())
			{
				case HttpVerb::kGet:
					break;

				case HttpVerb::kPost:
					{
						SandboxedJob Job;
						Job.Initialize("zen_test");
						Job.SetWorkingDirectory("c:\\temp\\sandbox1");
						Job.AddWhitelistFile("c:\\temp\\sandbox1");
						Job.SpawnJob("c:\\windows\\system32\\cmd.exe");
					}
					break;

				default:
					break;
			}
		},
		HttpVerb::kGet | HttpVerb::kPost);
#	endif

	m_Router.RegisterRoute(
		"jobs/prep",
		[this](HttpRouterRequest& Req) {
			HttpServerRequest& HttpReq = Req.ServerRequest();

			switch (HttpReq.RequestVerb())
			{
				case HttpVerb::kPost:
					{
						// This operation takes the proposed job spec and identifies which
						// chunks are not present on this server. This list is then returned in
						// the "need" list in the response

						IoBuffer Payload	   = HttpReq.ReadPayload();
						CbObject RequestObject = LoadCompactBinaryObject(Payload);

						std::vector<IoHash> NeedList;

						for (auto Entry : RequestObject["files"sv])
						{
							CbObjectView Ob = Entry.AsObjectView();

							const IoHash FileHash = Ob["hash"sv].AsHash();

							if (!m_CasStore.FindChunk(FileHash))
							{
								ZEN_DEBUG("NEED: {} {} {}", FileHash, Ob["file"sv].AsString(), Ob["size"sv].AsUInt64());

								NeedList.push_back(FileHash);
							}
						}

						CbObjectWriter Cbo;
						Cbo.BeginArray("need");

						for (const IoHash& Hash : NeedList)
						{
							Cbo << Hash;
						}

						Cbo.EndArray();
						CbObject Response = Cbo.Save();

						return HttpReq.WriteResponse(HttpResponseCode::OK, Response);
					}
					break;

				default:
					break;
			}
		},
		HttpVerb::kPost);

	m_Router.RegisterRoute(
		"jobs",
		[this](HttpRouterRequest& Req) {
			HttpServerRequest& HttpReq = Req.ServerRequest();

			switch (HttpReq.RequestVerb())
			{
				case HttpVerb::kGet:
					break;

				case HttpVerb::kPost:
					{
						IoBuffer Payload	   = HttpReq.ReadPayload();
						CbObject RequestObject = LoadCompactBinaryObject(Payload);

						bool AllOk = true;

						std::vector<IoHash> NeedList;

						std::filesystem::path SandboxDir{CreateNewSandbox()};

						ZEN_DEBUG("setting up job in sandbox '{}'", SandboxDir);

						zen::DeleteDirectories(SandboxDir);
						zen::CreateDirectories(SandboxDir);

						for (auto Entry : RequestObject["files"sv])
						{
							CbObjectView Ob = Entry.AsObjectView();

							std::string_view FileName = Ob["file"sv].AsString();
							const IoHash	 FileHash = Ob["hash"sv].AsHash();
							uint64_t		 FileSize = Ob["size"sv].AsUInt64();

							if (IoBuffer Chunk = m_CasStore.FindChunk(FileHash); !Chunk)
							{
								ZEN_DEBUG("MISSING: {} {} {}", FileHash, FileName, FileSize);
								AllOk = false;

								NeedList.push_back(FileHash);
							}
							else
							{
								std::filesystem::path FullPath = SandboxDir / FileName;

								const IoBuffer* Chunks[] = {&Chunk};

								zen::WriteFile(FullPath, Chunks, 1);
							}
						}

						if (!AllOk)
						{
							// TODO: Could report all the missing pieces in the response here
							return HttpReq.WriteResponse(HttpResponseCode::NotFound);
						}

						std::string Executable8{RequestObject["cmd"].AsString()};
						std::string Args8{RequestObject["args"].AsString()};

						std::wstring Executable = Utf8ToWide(Executable8);
						std::wstring Args		= Utf8ToWide(Args8);

						ZEN_DEBUG("spawning job in sandbox '{}': '{}' '{}'", SandboxDir, Executable8, Args8);

						std::filesystem::path ExeName = SandboxDir / Executable;

						BasicJob Job;
						Job.SetWorkingDirectory(SandboxDir);
						Job.SpawnJob(ExeName, Args);
						Job.Wait();

						CbObjectWriter Response;

						Response << "exitcode" << Job.ExitCode();

						return HttpReq.WriteResponse(HttpResponseCode::OK, Response.Save());
					}
					break;

				default:
					break;
			}
		},
		HttpVerb::kGet | HttpVerb::kPost);
}

HttpLaunchService::~HttpLaunchService()
{
}

const char*
HttpLaunchService::BaseUri() const
{
	return "/exec/";
}

void
HttpLaunchService::HandleRequest(HttpServerRequest& Request)
{
	if (m_Router.HandleRequest(Request) == false)
	{
		ZEN_WARN("No route found for {0}", Request.RelativeUri());
	}
}

std::filesystem::path
HttpLaunchService::CreateNewSandbox()
{
	std::string			  UniqueId = std::to_string(++m_SandboxCount);
	std::filesystem::path Path	   = m_SandboxPath / UniqueId;
	zen::CreateDirectories(Path);
	return Path;
}

}  // namespace zen

#endif	// ZEN_WITH_COMPUTE_SERVICES