-
Notifications
You must be signed in to change notification settings - Fork 7
/
winpmem.cpp
1121 lines (878 loc) · 30.4 KB
/
winpmem.cpp
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2012-2014 Michael Cohen <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#define _WIN32_WINNT 0x0501
/********************************************************************
This is a single binary memory imager for Windows.
Supported systems:
- Windows XPSP2 to Windows 8 inclusive, both 32 bit and 64 bit.
*********************************************************************/
#ifdef _WIN32
#define _USE_32BIT_TIME_T 1
#elif _WIN64
#define _USE_64BIT_TIME_T 1
#endif
#include "winpmem.h"
#include <time.h>
#include <winioctl.h>
#include <algorithm>
/* Create the corrent WinPmem object. Currently this selects between
32/64 bit implementations.
*/
using namespace std;
WinPmem *WinPmemFactory() {
SYSTEM_INFO sys_info;
ZeroMemory(&sys_info, sizeof(sys_info));
GetNativeSystemInfo(&sys_info);
switch(sys_info.wProcessorArchitecture) {
case PROCESSOR_ARCHITECTURE_AMD64:
return new WinPmem64();
case PROCESSOR_ARCHITECTURE_INTEL:
return new WinPmem32();
default:
return NULL;
}
};
__int64 WinPmem::pad(__int64 length) {
__int64 count = 1;
__int64 start = 0;
ZeroMemory(buffer_, buffer_size_);
while (start < length) {
DWORD to_write = (DWORD) min(buffer_size_, (const size_t &) (length - start));
DWORD bytes_written;
if (!WriteFile(out_fd_, buffer_,
to_write, &bytes_written, NULL) ||
bytes_written != to_write) {
LogLastError((TCHAR *) TEXT("Failed to write padding"));
goto error;
}
out_offset += bytes_written;
start += bytes_written;
Log(TEXT("."));
if (!(count % 60)) {
Log(TEXT("\n0x%08llX "), start);
}
count++;
};
return 1;
error:
return 0;
};
__int64 WinPmem::copy_memory(unsigned __int64 start, unsigned __int64 end) {
LARGE_INTEGER large_start;
__int64 count = 0;
if (start > max_physical_memory_) {
return 0;
};
// Clamp the region to the top of physical memory.
if (end > max_physical_memory_) {
end = max_physical_memory_;
};
while (start < end) {
DWORD to_write = (DWORD) min((long long unsigned int)buffer_size_, (end - start));
DWORD bytes_read = 0;
DWORD bytes_written = 0;
large_start.QuadPart = start;
if (0xFFFFFFFF == SetFilePointerEx(
fd_, large_start, NULL, FILE_BEGIN)) {
LogError((TCHAR *) TEXT("Failed to seek in the pmem device.\n"));
goto error;
};
if (!ReadFile(fd_, buffer_, to_write, &bytes_read, NULL) ||
bytes_read != to_write) {
LogError((TCHAR *) TEXT("Failed to Read memory.\n"));
goto error;
}
if (!WriteFile(out_fd_, buffer_, bytes_read,
&bytes_written, NULL) ||
bytes_written != bytes_read) {
LogLastError((TCHAR *) TEXT("Failed to write image file"));
goto error;
}
out_offset += bytes_written;
if ((count % 50) == 0) {
Log(TEXT("\n%02lld%% 0x%08llX "), (start * 100) / max_physical_memory_,
start);
}
Log(TEXT("."));
start += to_write;
count++;
};
Log(TEXT("\n"));
return 1;
error:
return 0;
};
// Turn on write support in the driver.
__int64 WinPmem::set_write_enabled(void) {
uint32 mode;
DWORD size;
if (!DeviceIoControl(fd_, PMEM_WRITE_ENABLE, &mode, 4, NULL, 0,
&size, NULL)) {
LogError((TCHAR *) TEXT("Failed to set write mode. Maybe these drivers do ")
TEXT("not support this mode?\n"));
return -1;
};
Log(TEXT("Write mode enabled! Hope you know what you are doing.\n"));
return 1;
};
void WinPmem::print_mode_(unsigned __int32 mode) {
switch (mode) {
case PMEM_MODE_IOSPACE:
Log(TEXT("MMMapIoSpace"));
break;
case PMEM_MODE_PHYSICAL:
Log(TEXT("\\\\.\\PhysicalMemory"));
break;
case PMEM_MODE_PTE:
Log(TEXT("PTE Remapping"));
break;
case PMEM_MODE_PTE_PCI:
Log(TEXT("PTE Remapping with PCI introspection"));
break;
default:
Log(TEXT("Unknown"));
};
};
// Display information about the memory geometry.
void WinPmem::print_memory_info() {
struct PmemMemoryInfo info;
__int64 i;
DWORD size;
// Get the memory ranges.
if (!DeviceIoControl(fd_, PMEM_INFO_IOCTRL, NULL, 0, (char *) &info,
sizeof(info), &size, NULL)) {
LogError((TCHAR *) TEXT("Failed to get memory geometry,"));
goto error;
}
Log(TEXT("CR3: 0x%010llX\n %d memory ranges:\n"), info.CR3.QuadPart,
info.NumberOfRuns);
for (i = 0; i < info.NumberOfRuns.QuadPart; i++) {
Log(TEXT("Start 0x%08llX - Length 0x%08llX\n"), info.Run[i].start,
info.Run[i].length);
max_physical_memory_ = (unsigned long long int) (info.Run[i].start + info.Run[i].length);
};
// When using the pci introspection we dont know the maximum physical memory,
// we therefore make a guess based on the total ram in the system.
Log(TEXT("Acquitision mode "));
print_mode_(mode_);
Log(TEXT("\n"));
if (mode_ == PMEM_MODE_PTE_PCI) {
ULONGLONG installed_memory = 0;
MEMORYSTATUSEX statusx;
statusx.dwLength = sizeof(statusx);
if (GlobalMemoryStatusEx(&statusx)) {
max_physical_memory_ = statusx.ullTotalPhys * 3 / 2;
Log(TEXT("Max physical memory guessed at 0x%08llX\n"),
max_physical_memory_);
} else {
Log(TEXT("Unable to guess max physical memory. Just Ctrl-C when ")
TEXT("done.\n"));
};
};
Log(TEXT("\n"));
error:
return;
};
__int64 WinPmem::set_acquisition_mode(unsigned __int32 mode) {
DWORD size;
if (mode == PMEM_MODE_AUTO) {
mode = default_mode_;
}
// Set the acquisition mode.
if (!DeviceIoControl(fd_, PMEM_CTRL_IOCTRL, &mode, 4, NULL, 0,
&size, NULL)) {
Log(TEXT("Failed to set acquisition mode %lu "), mode);
LogLastError((TCHAR *) TEXT(""));
print_mode_(mode);
Log(TEXT("\n"));
return -1;
};
mode_ = mode;
return 1;
};
__int64 WinPmem::create_output_file(TCHAR *output_filename) {
__int64 status = 1;
// The special file name of - means we should use stdout.
if (!_tcscmp(output_filename, TEXT("-"))) {
out_fd_ = GetStdHandle(STD_OUTPUT_HANDLE);
suppress_output = TRUE;
status = 1;
goto exit;
}
// Create the output file.
out_fd_ = CreateFile(output_filename,
GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (out_fd_ == INVALID_HANDLE_VALUE) {
LogError((TCHAR *) TEXT("Unable to create output file."));
status = -1;
goto exit;
};
exit:
return status;
}
__int64 WinPmem::write_coredump() {
// Somewhere to store the info from the driver;
struct PmemMemoryInfo info;
DWORD size;
__int64 i;
__int64 status = -1;
if (out_fd_ == INVALID_HANDLE_VALUE) {
LogError((TCHAR *) TEXT("Must open an output file first."));
goto exit;
};
RtlZeroMemory(&info, sizeof(info));
// Get the memory ranges.
if (!DeviceIoControl(fd_, PMEM_INFO_IOCTRL, NULL, 0, (char *) &info,
sizeof(info), &size, NULL)) {
LogError((TCHAR *) TEXT("Failed to get memory geometry,"));
status = -1;
goto exit;
};
Log(TEXT("Will write an elf coredump.\n"));
print_memory_info();
if (!write_coredump_header_(&info)) {
goto exit;
};
for (i = 0; i < info.NumberOfRuns.QuadPart; i++) {
copy_memory((unsigned long long int) info.Run[i].start,
(unsigned long long int) (info.Run[i].start + info.Run[i].length));
};
// Remember where we wrote the last metadata header.
last_header_offset_ = out_offset;
if (!WriteFile(out_fd_, metadata_, metadata_len_, &metadata_len_, NULL)) {
LogError((TCHAR *) TEXT("Can not write metadata.\n"));
}
out_offset += metadata_len_;
if (pagefile_path_) {
write_page_file();
};
exit:
CloseHandle(out_fd_);
out_fd_ = INVALID_HANDLE_VALUE;
return status;
};
void WinPmem::CreateChildProcess(TCHAR *command, HANDLE stdout_wr) {
PROCESS_INFORMATION piProcInfo;
STARTUPINFO siStartInfo;
BOOL bSuccess = FALSE;
// Set up members of the PROCESS_INFORMATION structure.
ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION));
// Set up members of the STARTUPINFO structure.
// This structure specifies the STDIN and STDOUT handles for redirection.
ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
siStartInfo.cb = sizeof(STARTUPINFO);
siStartInfo.hStdInput = NULL;
siStartInfo.hStdOutput = stdout_wr;
siStartInfo.hStdError = stdout_wr;
siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
Log(TEXT("Launching %s\n"), command);
// Create the child process.
bSuccess = CreateProcess(NULL,
command, // command line
NULL, // process security attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
0, // creation flags
NULL, // use parent's environment
NULL, // use parent's current directory
&siStartInfo, // STARTUPINFO pointer
&piProcInfo); // receives PROCESS_INFORMATION
// If an error occurs, exit the application.
if (!bSuccess) {
LogLastError((TCHAR *) TEXT("Unable to launch process."));
return;
}
// Close handles to the child process and its primary thread.
// Some applications might keep these handles to monitor the status
// of the child process, for example.
CloseHandle(piProcInfo.hProcess);
CloseHandle(piProcInfo.hThread);
CloseHandle(stdout_wr);
}
// Copy the pagefile to the current place in the output file.
void WinPmem::write_page_file() {
unsigned __int64 pagefile_offset = out_offset;
int count = 0;
int total_mb_read = 0;
TCHAR path[MAX_PATH + 1];
TCHAR filename[MAX_PATH + 1] = {0};
TCHAR *command_line;
SECURITY_ATTRIBUTES saAttr;
HANDLE stdout_rd = NULL;
HANDLE stdout_wr = NULL;
if (!GetTempPath(MAX_PATH, path)) {
LogError((TCHAR *) TEXT("Unable to determine temporary path."));
goto error;
}
// filename is now the random path.
GetTempFileName(path, TEXT("fls"), 0, filename);
Log(TEXT("Extracting fcat to %s\n"), filename);
if (extract_file_(WINPMEM_FCAT_EXECUTABLE, filename) < 0) {
goto error;
};
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
// Create a pipe for the child process's STDOUT.
if (!CreatePipe(&stdout_rd, &stdout_wr, &saAttr, 0)) {
LogLastError((TCHAR *) TEXT("StdoutRd CreatePipe"));
goto error;
};
// Ensure the read handle to the pipe for STDOUT is not inherited.
SetHandleInformation(stdout_rd, HANDLE_FLAG_INHERIT, 0);
command_line = aswprintf(TEXT("%s %s \\\\.\\%s"), filename,
&pagefile_path_[3],
pagefile_path_);
CreateChildProcess(command_line, stdout_wr);
Log(TEXT("Preparing to read pagefile.\n"));
while (1) {
DWORD bytes_read = buffer_size_;
DWORD bytes_written = 0;
if (!ReadFile(stdout_rd, buffer_, bytes_read, &bytes_read, NULL)) {
break;
};
count += bytes_read;
if (count > 1024 * 1024) {
count -= 1024 * 1024;
if (total_mb_read % 50 == 0) {
Log(TEXT("\n% 5dMb "), total_mb_read);
};
total_mb_read += 1;
Log(TEXT("."));
};
if (!WriteFile(out_fd_, buffer_, bytes_read, &bytes_written, NULL) ||
bytes_written != bytes_read) {
LogLastError((TCHAR *) TEXT("Failed to write image file"));
goto error;
};
out_offset += bytes_written;
};
error:
Log(TEXT("\n"));
// Write another metadata header.
{
char *metadata = asprintf("# PMEM\n"
"---\n"
"PreviousHeader: %#llx\n"
"PagefileOffset: %#llx\n"
"PagefileSize: %#llx\n"
"...\n",
last_header_offset_,
pagefile_offset,
out_offset - pagefile_offset
);
if (metadata) {
DWORD metadata_len = strlen(metadata);
DWORD bytes_written = 0;
if (!WriteFile(out_fd_, metadata, metadata_len, &bytes_written, NULL) ||
bytes_written != metadata_len) {
LogLastError((TCHAR *) TEXT("Failed to write image file"));
};
out_offset += bytes_written;
free(metadata);
};
};
if (filename) DeleteFile(filename);
return;
};
__int64 WinPmem::write_raw_image() {
// Somewhere to store the info from the driver;
struct PmemMemoryInfo info;
DWORD size;
__int64 i;
__int64 status = -1;
__int64 offset = 0;
if (out_fd_ == INVALID_HANDLE_VALUE) {
LogError((TCHAR *) TEXT("Must open an output file first."));
goto exit;
};
RtlZeroMemory(&info, sizeof(info));
// Get the memory ranges.
if (!DeviceIoControl(fd_, PMEM_INFO_IOCTRL, NULL, 0, (char *) &info,
sizeof(info), &size, NULL)) {
LogError((TCHAR *) TEXT("Failed to get memory geometry,"));
status = -1;
goto exit;
};
Log(TEXT("Will generate a RAW image\n"));
print_memory_info();
for (i = 0; i < info.NumberOfRuns.QuadPart; i++) {
if (info.Run[i].start > offset) {
Log(TEXT("Padding from 0x%08llX to 0x%08llX\n"), offset, info.Run[i].start);
if (!pad(info.Run[i].start - offset)) {
goto exit;
}
};
copy_memory((unsigned long long int) info.Run[i].start,
(unsigned long long int) (info.Run[i].start + info.Run[i].length));
offset = info.Run[i].start + info.Run[i].length;
};
// All is well.
status = 1;
exit:
CloseHandle(out_fd_);
out_fd_ = INVALID_HANDLE_VALUE;
return status;
};
WinPmem::WinPmem() :
fd_(INVALID_HANDLE_VALUE),
buffer_size_(1024 * 1024),
buffer_(NULL),
suppress_output(FALSE),
service_name((TCHAR *) PMEM_SERVICE_NAME),
max_physical_memory_(0),
mode_(PMEM_MODE_AUTO),
default_mode_(PMEM_MODE_AUTO),
metadata_(NULL),
metadata_len_(0),
driver_filename_(NULL),
driver_is_tempfile_(false),
out_offset(0),
pagefile_path_(NULL) {
buffer_ = new char[buffer_size_];
_tcscpy(last_error, TEXT(""));
}
WinPmem::~WinPmem() {
if (fd_ != INVALID_HANDLE_VALUE) {
CloseHandle(fd_);
};
if (buffer_) {
delete[] buffer_;
}
if (driver_filename_ && driver_is_tempfile_) {
free(driver_filename_);
}
}
void WinPmem::LogError(TCHAR *message) {
_tcsncpy(last_error, message, sizeof(last_error));
if (suppress_output) return;
wprintf(L"%s", message);
};
void WinPmem::Log(const TCHAR *message, ...) {
if (suppress_output) return;
va_list ap;
va_start(ap, message);
__mingw_vprintf(message, ap);
va_end(ap);
};
void WinPmem::LogLastError(TCHAR *message) {
TCHAR *buffer;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &buffer,
0, NULL);
Log(TEXT("%s"), message);
Log(TEXT(": %s\n"), buffer);
};
__int64 WinPmem::extract_file_(__int64 resource_id, TCHAR *filename) {
// Locate the driver resource in the .EXE file.
HRSRC hRes = FindResource(NULL, MAKEINTRESOURCE(resource_id), TEXT("FILE"));
DWORD size;
HANDLE out_fd;
VOID *lpResLock;
HGLOBAL hResLoad;
if (hRes == NULL) {
LogError((TCHAR *) TEXT("Could not locate driver resource."));
goto error;
}
hResLoad = LoadResource(NULL, hRes);
if (hResLoad == NULL) {
LogError((TCHAR *) TEXT("Could not load driver resource."));
goto error;
}
lpResLock = LockResource(hResLoad);
if (lpResLock == NULL) {
LogError((TCHAR *) TEXT("Could not lock driver resource."));
goto error;
}
size = SizeofResource(NULL, hRes);
// Now open the filename and write the driver image on it.
out_fd = CreateFile(filename, GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (out_fd == INVALID_HANDLE_VALUE) {
LogError((TCHAR *) TEXT("Can not create temporary file."));
goto error_resource;
};
if (!WriteFile(out_fd, lpResLock, size, &size, NULL)) {
LogError((TCHAR *) TEXT("Can not write to temporary file."));
goto error_file;
}
CloseHandle(out_fd);
return 1;
error_file:
CloseHandle(out_fd);
error_resource:
error:
return -1;
};
void WinPmem::set_driver_filename(TCHAR *driver_filename) {
DWORD res;
if (driver_filename_) {
free(driver_filename_);
driver_filename_ = NULL;
};
if (driver_filename) {
driver_filename_ = (TCHAR *) malloc(MAX_PATH * sizeof(TCHAR));
if (driver_filename_) {
res = GetFullPathName(driver_filename, MAX_PATH,
driver_filename_, NULL);
};
};
}
void WinPmem::set_pagefile_path(TCHAR *path) {
DWORD res;
if (pagefile_path_) {
free(pagefile_path_);
pagefile_path_ = NULL;
};
if (path) {
pagefile_path_ = (TCHAR *) malloc(MAX_PATH * sizeof(TCHAR));
if (pagefile_path_) {
res = GetFullPathName(path, MAX_PATH,
pagefile_path_, NULL);
};
// Split at the drive letter. C:\pagefile.sys
pagefile_path_[2] = 0;
};
};
__int64 WinPmem::install_driver() {
SC_HANDLE scm, service;
__int64 status = -1;
// Try to load the driver from the resource section.
if (extract_driver() < 0)
goto error;
uninstall_driver();
scm = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);
if (!scm) {
LogError((TCHAR *) TEXT("Can not open SCM. Are you administrator?\n"));
goto error;
}
service = CreateService(scm,
service_name,
service_name,
SERVICE_ALL_ACCESS,
SERVICE_KERNEL_DRIVER,
SERVICE_DEMAND_START,
SERVICE_ERROR_NORMAL,
driver_filename_,
NULL,
NULL,
NULL,
NULL,
NULL);
if (GetLastError() == ERROR_SERVICE_EXISTS) {
service = OpenService(scm, service_name, SERVICE_ALL_ACCESS);
}
if (!service) {
goto error;
};
if (!StartService(service, 0, NULL)) {
if (GetLastError() != ERROR_SERVICE_ALREADY_RUNNING) {
LogError((TCHAR *) TEXT("Error: StartService(), Cannot start the driver.\n"));
goto service_error;
}
}
Log(TEXT("Loaded Driver %s.\n"), driver_filename_);
fd_ = CreateFile(TEXT("\\\\.\\") TEXT(PMEM_DEVICE_NAME),
// Write is needed for IOCTL.
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (fd_ == INVALID_HANDLE_VALUE) {
LogError((TCHAR *) TEXT("Can not open raw device."));
status = -1;
};
status = 1;
service_error:
CloseServiceHandle(service);
CloseServiceHandle(scm);
error:
// Only remove the driver file if it was a temporary file.
if (driver_is_tempfile_) {
Log(TEXT("Deleting %s\n"), driver_filename_);
DeleteFile(driver_filename_);
};
return status;
}
__int64 WinPmem::uninstall_driver() {
SC_HANDLE scm, service;
SERVICE_STATUS ServiceStatus;
scm = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);
if (!scm) return 0;
service = OpenService(scm, service_name, SERVICE_ALL_ACCESS);
if (service) {
ControlService(service, SERVICE_CONTROL_STOP, &ServiceStatus);
};
DeleteService(service);
CloseServiceHandle(service);
Log(TEXT("Driver Unloaded.\n"));
return 1;
CloseServiceHandle(scm);
return 0;
}
/* Create a YAML file describing the image encoded into a null terminated
string. Caller will own the memory.
*/
char *store_metadata_(struct PmemMemoryInfo *info) {
SYSTEM_INFO sys_info;
struct tm *newtime;
#ifdef _WIN32
__time32_t aclock;
#elif _WIN64
__time64_t aclock;
#endif
char *time_buffer = NULL;
char *arch = NULL;
#ifdef _WIN32
_time32(&aclock); // Get time in seconds.
newtime = _gmtime32(&aclock); // Convert time to struct tm form.
#elif _WIN64
_time64(&aclock); // Get time in seconds.
newtime = _gmtime64(&aclock); // Convert time to struct tm form.
#endif
// Print local time as a string.
time_buffer = asctime(newtime);
// Get basic architecture information (Note that we always write ELF64 core
// dumps - even on 32 bit platforms).
ZeroMemory(&sys_info, sizeof(sys_info));
GetNativeSystemInfo(&sys_info);
switch (sys_info.wProcessorArchitecture) {
case PROCESSOR_ARCHITECTURE_AMD64:
arch = (char *) "AMD64";
break;
case PROCESSOR_ARCHITECTURE_INTEL:
arch = (char *) "I386";
break;
default:
arch = (char *) "Unknown";
}
return asprintf(// A YAML File describing metadata about this image.
"# PMEM\n"
"---\n" // The start of the YAML file.
"acquisition_tool: 'WinPMEM " PMEM_VERSION "'\n"
"acquisition_timestamp: %s\n"
"CR3: %#llx\n"
"NtBuildNumber: %#llx\n"
"NtBuildNumberAddr: %#llx\n"
"KernBase: %#llx\n"
"Arch: %s\n"
"...\n", // This is the end of a YAML file.
time_buffer,
info->CR3.QuadPart,
info->NtBuildNumber.QuadPart,
info->NtBuildNumberAddr.QuadPart,
info->KernBase.QuadPart,
arch
);
};
// WinPmem64 - A 64 bit implementation of the imager.
__int64 WinPmem::write_coredump_header_(struct PmemMemoryInfo *info) {
Elf64_Ehdr header;
DWORD header_size;
Elf64_Phdr pheader;
uint64 file_offset;
int i;
if (!metadata_) {
metadata_ = store_metadata_(info);
if (!metadata_) goto error;
metadata_len_ = strlen(metadata_);
};
// Where we start writing data.
file_offset = (uint64) (
sizeof(Elf64_Ehdr) +
// One Phdr for each run and one for the metadata.
(info->NumberOfRuns.QuadPart + 1) * sizeof(Elf64_Phdr));
// All values that are unset will be zero
RtlZeroMemory(&header, sizeof(Elf64_Ehdr));
// We create a 64 bit core dump file with one section
// for each physical memory segment.
header.ident[0] = ELFMAG0;
header.ident[1] = ELFMAG1;
header.ident[2] = ELFMAG2;
header.ident[3] = ELFMAG3;
header.ident[4] = ELFCLASS64;
header.ident[5] = ELFDATA2LSB;
header.ident[6] = EV_CURRENT;
header.type = ET_CORE;
header.machine = EM_X86_64;
header.version = EV_CURRENT;
header.phoff = sizeof(Elf64_Ehdr);
header.ehsize = sizeof(Elf64_Ehdr);
header.phentsize = sizeof(Elf64_Phdr);
// One more header for the metadata.
header.phnum = (Elf64_Half) ((uint32) info->NumberOfRuns.QuadPart + 1);
header.shentsize = sizeof(Elf64_Shdr);
header.shnum = 0;
header_size = sizeof(header);
if (!WriteFile(out_fd_, &header, header_size, &header_size, NULL)) {
LogLastError((TCHAR *) TEXT("Failed to write header"));
goto error;
};
out_offset += header_size;
for (i = 0; i < info->NumberOfRuns.QuadPart; i++) {
PHYSICAL_MEMORY_RANGE range = info->Run[i];
RtlZeroMemory(&pheader, sizeof(Elf64_Phdr));
pheader.type = PT_LOAD;
pheader.paddr = (Elf64_Addr) range.start;
pheader.memsz = (Elf64_Xword) range.length;
pheader.align = PAGE_SIZE;
pheader.flags = PF_R;
pheader.off = file_offset;
pheader.filesz = (Elf64_Xword) range.length;
// Move the file offset by the size of this run.
file_offset += range.length;
header_size = sizeof(pheader);
if (!WriteFile(out_fd_, &pheader, header_size, &header_size, NULL)) {
LogLastError((TCHAR *) TEXT("Failed to write header"));
goto error;
};
out_offset += header_size;
};
// Add a header for the metadata so it can be easily found in the file.
RtlZeroMemory(&pheader, sizeof(Elf64_Phdr));
pheader.type = PT_PMEM_METADATA;
// The metadata section will be written at the end of the
pheader.off = file_offset;
pheader.filesz = metadata_len_;
header_size = sizeof(pheader);
if (!WriteFile(out_fd_, &pheader, header_size, &header_size, NULL)) {
LogLastError((TCHAR *) TEXT("Failed to write header"));
goto error;
};
out_offset += header_size;
return 1;
error:
return 0;
};
__int64 WinPmem::extract_driver(TCHAR *driver_filename) {
set_driver_filename(driver_filename);
return extract_driver();
};
__int64 WinPmem64::extract_driver() {
// 64 bit drivers use PTE acquisition by default.
default_mode_ = PMEM_MODE_PTE;
if (!driver_filename_) {
TCHAR path[MAX_PATH + 1];
TCHAR filename[MAX_PATH + 1];
// Gets the temp path env string (no guarantee it's a valid path).
if (!GetTempPath(MAX_PATH, path)) {
LogError((TCHAR *) TEXT("Unable to determine temporary path."));
goto error;
}
GetTempFileName(path, service_name, 0, filename);
set_driver_filename(filename);
driver_is_tempfile_ = true;