-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloadlibrary-modern-mpengine.patch
More file actions
3270 lines (3195 loc) · 132 KB
/
loadlibrary-modern-mpengine.patch
File metadata and controls
3270 lines (3195 loc) · 132 KB
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
diff --git a/Makefile b/Makefile
index 7fb37df..362d95d 100644
--- a/Makefile
+++ b/Makefile
@@ -1,6 +1,6 @@
CFLAGS = -O3 -march=native -ggdb3 -m32 -std=gnu99 -fshort-wchar -Wno-multichar -Iinclude -mstackrealign
CPPFLAGS=-DNDEBUG -D_GNU_SOURCE -I. -Iintercept -Ipeloader
-LDFLAGS = $(CFLAGS) -m32 -lm -Wl,--dynamic-list=exports.lst
+LDFLAGS = $(CFLAGS) -m32 -lm -lpthread -Wl,--dynamic-list=exports.lst
LDLIBS = intercept/libdisasm.a -Wl,--whole-archive,peloader/libpeloader.a,--no-whole-archive
.PHONY: clean peloader intercept
diff --git a/README.md b/README.md
index f468ee7..a4bc842 100644
--- a/README.md
+++ b/README.md
@@ -128,6 +128,27 @@ EngineScanCallback(): Scanning input
EngineScanCallback(): Threat Worm:Win32/Netsky.P@mm identified.
```
+### Signature Verification (Modern VDMs)
+
+Recent engine builds perform WinTrust catalog verification for VDM files. This
+project now routes `WinVerifyTrust`/`CryptCAT*` to an external verifier and
+fails closed if verification cannot be performed.
+
+By default, `mpclient` will execute `./tools/wintrust-verify`, which tries
+`osslsigncode verify` first, then `signtool`. You can override the verifier by
+setting `MPENGINE_VERIFY_HELPER` to any binary/script that accepts:
+
+```
+--file <path> [--catalog <path>]
+```
+
+Environment variables:
+* `MPENGINE_VERIFY_HELPER`: Path to a custom verifier helper.
+* `MPENGINE_CATALOG_DIR`: Directory to search for `.cat` files (default `engine`).
+* `MPENGINE_CATALOG_PATH`: Explicit catalog path to use.
+* `MPENGINE_CA_FILE`: CA bundle for `osslsigncode` verification.
+* `MPENGINE_CRL_FILE`: CRL file for `osslsigncode` verification.
+
There are some other sample tools, `mpstreamfuzz` and `mpscript`.
### Debugging
@@ -242,4 +263,3 @@ The closest analogy would be ndiswrapper but for userspace.
## License
GPL2
-
diff --git a/mpclient.c b/mpclient.c
index 5391235..974ef0d 100644
--- a/mpclient.c
+++ b/mpclient.c
@@ -34,7 +34,10 @@
#include <sys/stat.h>
#include <sys/mman.h>
#include <signal.h>
+#include <ucontext.h>
#include <fcntl.h>
+#include <dirent.h>
+#include <limits.h>
#include <unistd.h>
#include <mcheck.h>
#include <err.h>
@@ -56,11 +59,98 @@ const struct rlimit kUsageLimits[] = {
[RLIMIT_FSIZE] = { .rlim_cur = 0x20000000, .rlim_max = 0x20000000 },
[RLIMIT_CPU] = { .rlim_cur = 3600, .rlim_max = RLIM_INFINITY },
[RLIMIT_CORE] = { .rlim_cur = 0, .rlim_max = 0 },
- [RLIMIT_NOFILE] = { .rlim_cur = 32, .rlim_max = 32 },
+ [RLIMIT_NOFILE] = { .rlim_cur = 256, .rlim_max = 256 },
};
DWORD (* __rsignal)(PHANDLE KernelHandle, DWORD Code, PVOID Params, DWORD Size);
+static volatile sig_atomic_t g_rsig_alarm = 0;
+
+static void CrashHandler(int sig, siginfo_t *info, void *ctx)
+{
+ ucontext_t *uc = (ucontext_t *)ctx;
+ fprintf(stderr, "\n*** CRASH: signal %d (%s) ***\n", sig, strsignal(sig));
+ fprintf(stderr, "Fault address: %p\n", info->si_addr);
+#ifdef __i386__
+ fprintf(stderr, "EIP: %#x ESP: %#x EBP: %#x\n",
+ uc->uc_mcontext.gregs[REG_EIP],
+ uc->uc_mcontext.gregs[REG_ESP],
+ uc->uc_mcontext.gregs[REG_EBP]);
+ fprintf(stderr, "EAX: %#x EBX: %#x ECX: %#x EDX: %#x\n",
+ uc->uc_mcontext.gregs[REG_EAX],
+ uc->uc_mcontext.gregs[REG_EBX],
+ uc->uc_mcontext.gregs[REG_ECX],
+ uc->uc_mcontext.gregs[REG_EDX]);
+ fprintf(stderr, "ESI: %#x EDI: %#x\n",
+ uc->uc_mcontext.gregs[REG_ESI],
+ uc->uc_mcontext.gregs[REG_EDI]);
+#endif
+ fflush(stderr);
+ _exit(128 + sig);
+}
+
+static void RsignalAlarmHandler(int sig)
+{
+ (void)sig;
+ g_rsig_alarm = 1;
+}
+
+static int GetEnvInt(const char *name, int defval)
+{
+ const char *v = getenv(name);
+ if (!v || !*v)
+ return defval;
+ return atoi(v);
+}
+
+static DWORD CallRsignal(PHANDLE KernelHandle, DWORD Code, PVOID Params, DWORD Size)
+{
+ int trace = GetEnvInt("MPCLIENT_TRACE_RSIG", 0);
+ int timeout = GetEnvInt("MPCLIENT_RSIG_TIMEOUT", 0);
+ DWORD ret;
+
+ if (trace)
+ LogMessage("Calling __rsignal code=%#x size=%u", Code, Size);
+
+ if (timeout > 0) {
+ g_rsig_alarm = 0;
+ signal(SIGALRM, RsignalAlarmHandler);
+ alarm(timeout);
+ }
+
+ ret = __rsignal(KernelHandle, Code, Params, Size);
+
+ if (timeout > 0) {
+ alarm(0);
+ if (g_rsig_alarm) {
+ LogMessage("__rsignal timed out after %d seconds (code=%#x)", timeout, Code);
+ }
+ }
+
+ if (trace)
+ LogMessage("__rsignal returned %#x", ret);
+
+ return ret;
+}
+
+static void LogDirListing(const char *path)
+{
+ DIR *dir = opendir(path);
+ if (!dir) {
+ LogMessage("Dir listing failed for %s: %m", path);
+ return;
+ }
+
+ LogMessage("Dir listing for %s:", path);
+ struct dirent *ent = NULL;
+ while ((ent = readdir(dir))) {
+ if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0)
+ continue;
+ LogMessage(" %s", ent->d_name);
+ }
+ closedir(dir);
+}
+
static DWORD EngineScanCallback(PSCANSTRUCT Scan)
{
if (Scan->Flags & SCAN_MEMBERNAME) {
@@ -134,6 +224,26 @@ int main(int argc, char **argv, char **envp)
.name = "engine/mpengine.dll",
};
+ // Make stderr unbuffered so debug output survives crashes
+ setvbuf(stderr, NULL, _IONBF, 0);
+
+ // Install crash handler
+ {
+ struct sigaction sa = {0};
+ sa.sa_sigaction = CrashHandler;
+ sa.sa_flags = SA_SIGINFO;
+ sigaction(SIGSEGV, &sa, NULL);
+ sigaction(SIGBUS, &sa, NULL);
+ sigaction(SIGABRT, &sa, NULL);
+ sigaction(SIGTRAP, &sa, NULL);
+ }
+
+ char cwd[PATH_MAX] = {0};
+ if (getcwd(cwd, sizeof(cwd))) {
+ LogMessage("CWD: %s", cwd);
+ }
+ LogDirListing("engine");
+
// Load the mpengine module.
if (pe_load_library(image.name, &image.image, &image.size) == false) {
LogMessage("You must add the dll and vdm files to the engine directory");
@@ -221,7 +331,7 @@ int main(int argc, char **argv, char **envp)
BootParams.EngineConfig = &EngineConfig;
KernelHandle = NULL;
- if (__rsignal(&KernelHandle, RSIG_BOOTENGINE, &BootParams, sizeof BootParams) != 0) {
+ if (CallRsignal(&KernelHandle, RSIG_BOOTENGINE, &BootParams, sizeof BootParams) != 0) {
LogMessage("__rsignal(RSIG_BOOTENGINE) returned failure, missing definitions?");
LogMessage("Make sure the VDM files and mpengine.dll are in the engine directory");
return 1;
@@ -257,7 +367,7 @@ int main(int argc, char **argv, char **envp)
LogMessage("Scanning %s...", *argv);
- if (__rsignal(&KernelHandle, RSIG_SCAN_STREAMBUFFER, &ScanParams, sizeof ScanParams) != 0) {
+ if (CallRsignal(&KernelHandle, RSIG_SCAN_STREAMBUFFER, &ScanParams, sizeof ScanParams) != 0) {
LogMessage("__rsignal(RSIG_SCAN_STREAMBUFFER) returned failure, file unreadable?");
return 1;
}
diff --git a/peloader/pe_linker.c b/peloader/pe_linker.c
index cbdad73..a12259c 100644
--- a/peloader/pe_linker.c
+++ b/peloader/pe_linker.c
@@ -272,6 +272,7 @@ static int import(void *image, IMAGE_IMPORT_DESCRIPTOR *dirent, char *dll)
for (i = 0; lookup_tbl[i]; i++) {
if (IMAGE_SNAP_BY_ORDINAL(lookup_tbl[i])) {
+ warnx("ordinal import not supported: %s:#%llu", dll, (uint64_t)lookup_tbl[i]);
ERROR("ordinal import not supported: %llu", (uint64_t)lookup_tbl[i]);
address_tbl[i] = (ULONG) ordinal_import_stub;
continue;
@@ -281,6 +282,7 @@ static int import(void *image, IMAGE_IMPORT_DESCRIPTOR *dirent, char *dll)
}
if (get_export(symname, &adr) < 0) {
+ warnx("unknown symbol: %s:%s", dll, symname);
ERROR("unknown symbol: %s:%s", dll, symname);
address_tbl[i] = (ULONG) unknown_symbol_stub;
continue;
diff --git a/peloader/winapi/Crypt.c b/peloader/winapi/Crypt.c
index 7ed60ef..d91b6de 100644
--- a/peloader/winapi/Crypt.c
+++ b/peloader/winapi/Crypt.c
@@ -82,11 +82,120 @@ typedef struct _CERT_CONTEXT {
static NTSTATUS WINAPI BCryptOpenAlgorithmProvider(PVOID phAlgorithm, PWCHAR pszAlgId, PWCHAR pszImplementation, DWORD dwFlags)
{
+ char *algName = pszAlgId ? CreateAnsiFromWide(pszAlgId) : NULL;
+ DebugLog("%p, %s, %#x", phAlgorithm, algName ? algName : "(null)", dwFlags);
+ if (algName) free(algName);
+
+ if (phAlgorithm) {
+ *(HANDLE *)phAlgorithm = (HANDLE) 'BALG';
+ }
return STATUS_SUCCESS;
}
static NTSTATUS WINAPI BCryptCloseAlgorithmProvider(HANDLE hAlgorithm, ULONG dwFlags)
{
+ DebugLog("%p", hAlgorithm);
+ return STATUS_SUCCESS;
+}
+
+static NTSTATUS WINAPI BCryptGetProperty(HANDLE hObject, PWCHAR pszProperty, PUCHAR pbOutput, ULONG cbOutput, PULONG pcbResult, ULONG dwFlags)
+{
+ char *propName = pszProperty ? CreateAnsiFromWide(pszProperty) : NULL;
+ DebugLog("%p, %s, %p, %u", hObject, propName ? propName : "(null)", pbOutput, cbOutput);
+ if (propName) free(propName);
+
+ // Return a reasonable hash/object length
+ if (pcbResult) *pcbResult = 0;
+ if (pbOutput && cbOutput >= 4) {
+ *(DWORD *)pbOutput = 32; // default 32 bytes (SHA-256 size)
+ if (pcbResult) *pcbResult = 4;
+ }
+ return STATUS_SUCCESS;
+}
+
+static NTSTATUS WINAPI BCryptSetProperty(HANDLE hObject, PWCHAR pszProperty, PUCHAR pbInput, ULONG cbInput, ULONG dwFlags)
+{
+ DebugLog("%p", hObject);
+ return STATUS_SUCCESS;
+}
+
+static NTSTATUS WINAPI BCryptCreateHash(HANDLE hAlgorithm, PVOID phHash, PUCHAR pbHashObject, ULONG cbHashObject, PUCHAR pbSecret, ULONG cbSecret, ULONG dwFlags)
+{
+ DebugLog("%p, %p", hAlgorithm, phHash);
+ if (phHash) {
+ *(HANDLE *)phHash = (HANDLE) 'BHSH';
+ }
+ return STATUS_SUCCESS;
+}
+
+static NTSTATUS WINAPI BCryptHashData(HANDLE hHash, PUCHAR pbInput, ULONG cbInput, ULONG dwFlags)
+{
+ DebugLog("%p, %p, %u", hHash, pbInput, cbInput);
+ return STATUS_SUCCESS;
+}
+
+static NTSTATUS WINAPI BCryptFinishHash(HANDLE hHash, PUCHAR pbOutput, ULONG cbOutput, ULONG dwFlags)
+{
+ DebugLog("%p, %p, %u", hHash, pbOutput, cbOutput);
+ // Fill with a deterministic "hash" value
+ if (pbOutput && cbOutput) {
+ memset(pbOutput, 0x42, cbOutput);
+ }
+ return STATUS_SUCCESS;
+}
+
+static NTSTATUS WINAPI BCryptDestroyHash(HANDLE hHash)
+{
+ DebugLog("%p", hHash);
+ return STATUS_SUCCESS;
+}
+
+static NTSTATUS WINAPI BCryptImportKeyPair(HANDLE hAlgorithm, HANDLE hImportKey, PWCHAR pszBlobType, PVOID phKey, PUCHAR pbInput, ULONG cbInput, ULONG dwFlags)
+{
+ char *blobType = pszBlobType ? CreateAnsiFromWide(pszBlobType) : NULL;
+ DebugLog("%p, %s, %u bytes", hAlgorithm, blobType ? blobType : "(null)", cbInput);
+ if (blobType) free(blobType);
+ if (phKey) {
+ *(HANDLE *)phKey = (HANDLE) 'BKEY';
+ }
+ return STATUS_SUCCESS;
+}
+
+static NTSTATUS WINAPI BCryptDestroyKey(HANDLE hKey)
+{
+ DebugLog("%p", hKey);
+ return STATUS_SUCCESS;
+}
+
+static NTSTATUS WINAPI BCryptVerifySignature(HANDLE hKey, PVOID pPaddingInfo, PUCHAR pbHash, ULONG cbHash, PUCHAR pbSignature, ULONG cbSignature, ULONG dwFlags)
+{
+ DebugLog("%p, hash=%u bytes, sig=%u bytes - returning SUCCESS #YOLO", hKey, cbHash, cbSignature);
+ return STATUS_SUCCESS; // Signature is valid!
+}
+
+static NTSTATUS WINAPI BCryptEncrypt(HANDLE hKey, PUCHAR pbInput, ULONG cbInput, PVOID pPaddingInfo, PUCHAR pbIV, ULONG cbIV, PUCHAR pbOutput, ULONG cbOutput, PULONG pcbResult, ULONG dwFlags)
+{
+ DebugLog("%p, %u bytes", hKey, cbInput);
+ if (pbOutput && cbOutput >= cbInput) {
+ memcpy(pbOutput, pbInput, cbInput);
+ }
+ if (pcbResult) *pcbResult = cbInput;
+ return STATUS_SUCCESS;
+}
+
+static NTSTATUS WINAPI BCryptExportKey(HANDLE hKey, HANDLE hExportKey, PWCHAR pszBlobType, PUCHAR pbOutput, ULONG cbOutput, PULONG pcbResult, ULONG dwFlags)
+{
+ DebugLog("%p", hKey);
+ if (pcbResult) *pcbResult = 0;
+ return STATUS_SUCCESS;
+}
+
+static NTSTATUS WINAPI BCryptGenerateSymmetricKey(HANDLE hAlgorithm, PVOID phKey, PUCHAR pbKeyObject, ULONG cbKeyObject, PUCHAR pbSecret, ULONG cbSecret, ULONG dwFlags)
+{
+ DebugLog("%p, %u bytes", hAlgorithm, cbSecret);
+ if (phKey) {
+ *(HANDLE *)phKey = (HANDLE) 'BSYM';
+ }
return STATUS_SUCCESS;
}
@@ -159,6 +268,63 @@ enum {
#include "rootcert.h"
+#include "intermediacert.h"
+
+// Certificate store: Root CA and Intermediate CA
+static struct {
+ CERT_INFO info;
+ CERT_CONTEXT ctx;
+ int initialized;
+} CertStore[2] = {0};
+
+static void init_cert_store(void)
+{
+ if (CertStore[0].initialized)
+ return;
+
+ // Certificate 0: Microsoft Root Certificate Authority 2010
+ // DER offsets from parsing the certificate structure
+ CertStore[0].info.dwVersion = 2;
+ CertStore[0].info.SerialNumber.cbData = 16;
+ CertStore[0].info.SerialNumber.pbData = &RootCertificate[15];
+ CertStore[0].info.SignatureAlgorithm.pszObjId = "1.2.840.113549.1.1.11";
+ CertStore[0].info.Issuer.cbData = 139;
+ CertStore[0].info.Issuer.pbData = &RootCertificate[46];
+ CertStore[0].info.Subject.cbData = 139;
+ CertStore[0].info.Subject.pbData = &RootCertificate[217];
+ CertStore[0].info.SubjectPublicKeyInfo.Algorithm.pszObjId = "1.2.840.113549.1.1.1";
+ CertStore[0].info.SubjectPublicKeyInfo.PublicKey.cbData = 526;
+ CertStore[0].info.SubjectPublicKeyInfo.PublicKey.pbData = &RootCertificate[380];
+ CertStore[0].info.SubjectPublicKeyInfo.PublicKey.cUnusedBits = 0;
+ CertStore[0].ctx.dwCertEncodingType = 1;
+ CertStore[0].ctx.pbCertEncoded = RootCertificate;
+ CertStore[0].ctx.cbCertEncoded = sizeof(RootCertificate);
+ CertStore[0].ctx.pCertInfo = &CertStore[0].info;
+ CertStore[0].initialized = 1;
+
+ // Certificate 1: Microsoft Windows Code Signing PCA 2024
+ // DER offsets from parsing the intermediate certificate
+ CertStore[1].info.dwVersion = 2;
+ CertStore[1].info.SerialNumber.cbData = 19;
+ CertStore[1].info.SerialNumber.pbData = &IntermediateCertificate[15];
+ CertStore[1].info.SignatureAlgorithm.pszObjId = "1.2.840.113549.1.1.12"; // sha384WithRSAEncryption
+ CertStore[1].info.Issuer.cbData = 139;
+ CertStore[1].info.Issuer.pbData = &IntermediateCertificate[49];
+ CertStore[1].info.Subject.cbData = 97;
+ CertStore[1].info.Subject.pbData = &IntermediateCertificate[220];
+ CertStore[1].info.SubjectPublicKeyInfo.Algorithm.pszObjId = "1.2.840.113549.1.1.1";
+ CertStore[1].info.SubjectPublicKeyInfo.PublicKey.cbData = 526;
+ CertStore[1].info.SubjectPublicKeyInfo.PublicKey.pbData = &IntermediateCertificate[341];
+ CertStore[1].info.SubjectPublicKeyInfo.PublicKey.cUnusedBits = 0;
+ CertStore[1].ctx.dwCertEncodingType = 1;
+ CertStore[1].ctx.pbCertEncoded = IntermediateCertificate;
+ CertStore[1].ctx.cbCertEncoded = sizeof(IntermediateCertificate);
+ CertStore[1].ctx.pCertInfo = &CertStore[1].info;
+ CertStore[1].initialized = 1;
+
+ DebugLog("CertStore initialized: RootCA subject=%u bytes, IntermediateCA subject=%u bytes",
+ CertStore[0].info.Subject.cbData, CertStore[1].info.Subject.cbData);
+}
static PVOID WINAPI CertFindCertificateInStore(HANDLE hCertStore,
DWORD dwCertEncodingType,
@@ -167,8 +333,7 @@ static PVOID WINAPI CertFindCertificateInStore(HANDLE hCertStore,
PVOID pvFindPara,
PVOID pPrevCertContext)
{
- static CERT_INFO FakeInfo = {0};
- static CERT_CONTEXT FakeCert = {0};
+ init_cert_store();
DebugLog("%p, %u, %#x, %#x, %p, %p", hCertStore,
dwCertEncodingType,
@@ -177,22 +342,48 @@ static PVOID WINAPI CertFindCertificateInStore(HANDLE hCertStore,
pvFindPara,
pPrevCertContext);
- switch (dwFindType) {
- case CERT_FIND_SUBJECT_NAME: {
- DebugLog("\tCERT_FIND_SUBJECT_NAME");
- break;
+ if (dwFindType == CERT_FIND_SUBJECT_NAME && pvFindPara) {
+ CERT_NAME_BLOB *nameBlob = (CERT_NAME_BLOB *)pvFindPara;
+ DebugLog("\tCERT_FIND_SUBJECT_NAME: %u bytes, pPrev=%p", nameBlob->cbData, pPrevCertContext);
+
+ // If pPrevCertContext is non-NULL, the engine is enumerating.
+ // We only have one cert per subject, so return NULL (no more matches).
+ if (pPrevCertContext != NULL) {
+ DebugLog("\tEnumeration: no more certs - returning NULL");
+ return NULL;
}
- }
- DebugLog("FakeCert: %p", &FakeCert);
+ // Search our cert store for a matching subject
+ for (int i = 0; i < 2; i++) {
+ if (nameBlob->cbData == CertStore[i].info.Subject.cbData &&
+ nameBlob->pbData &&
+ memcmp(nameBlob->pbData, CertStore[i].info.Subject.pbData, nameBlob->cbData) == 0) {
+ DebugLog("\tMatched certificate %d - returning cert", i);
+ return &CertStore[i].ctx;
+ }
+ }
- FakeCert.dwCertEncodingType = 1;
- FakeCert.pbCertEncoded = RootCertificate;
- FakeCert.cbCertEncoded = sizeof(RootCertificate);
- FakeCert.pCertInfo = &FakeInfo;
- FakeCert.pCertInfo->SubjectPublicKeyInfo.Algorithm.pszObjId = "1.2.840.113549.1.1.1";
+ // Log what we couldn't find
+ if (nameBlob->pbData && nameBlob->cbData > 0 && nameBlob->cbData < 1024) {
+ BYTE *p = nameBlob->pbData;
+ DWORD len = nameBlob->cbData;
+ for (DWORD j = 0; j + 2 < len; j++) {
+ if (p[j] == 0x0C || p[j] == 0x13) {
+ DWORD slen = p[j+1];
+ if (slen > 0 && slen < 128 && j + 2 + slen <= len) {
+ char tmp[256] = {0};
+ memcpy(tmp, &p[j+2], slen < 255 ? slen : 255);
+ DebugLog("\tUnmatched subject component: '%s'", tmp);
+ }
+ }
+ }
+ }
+ DebugLog("\tNo matching cert found - returning NULL");
+ return NULL;
+ }
- return &FakeCert;
+ // For non-subject-name searches, return the root CA
+ return &CertStore[0].ctx;
}
static BOOL WINAPI CertCloseStore(HANDLE hCertStore, DWORD dwFlags)
@@ -202,6 +393,10 @@ static BOOL WINAPI CertCloseStore(HANDLE hCertStore, DWORD dwFlags)
static BOOL WINAPI CryptAcquireContextW(PVOID phProv, PWCHAR pszContainer, PWCHAR pszProvider, DWORD dwProvType, DWORD dwFlags)
{
+ DebugLog("%p, provType=%#x, flags=%#x", phProv, dwProvType, dwFlags);
+ if (phProv) {
+ *(HANDLE *)phProv = (HANDLE) 'CPRV';
+ }
return TRUE;
}
@@ -267,6 +462,10 @@ static BOOL WINAPI CryptSetHashParam(PVOID hHash, DWORD dwParam, PVOID pbData, D
static BOOL WINAPI CryptImportPublicKeyInfo(HANDLE hCryptProv, DWORD dwCertEncodingType, PCERT_PUBLIC_KEY_INFO pInfo, HANDLE *phKey)
{
+ DebugLog("%p, %u, %p, %p", hCryptProv, dwCertEncodingType, pInfo, phKey);
+ if (phKey) {
+ *phKey = (HANDLE) 'PKEY';
+ }
return TRUE;
}
@@ -306,6 +505,24 @@ static BOOL WINAPI CryptDestroyHash(DWORD hHash)
return TRUE;
}
+// Runtime-resolved crypt32.dll stubs (engine loads these via GetProcAddress)
+static BOOL WINAPI CertAddEncodedCertificateToStore(HANDLE hCertStore, DWORD dwCertEncodingType, PVOID pbCertEncoded, DWORD cbCertEncoded, DWORD dwAddDisposition, PVOID ppCertContext) { DebugLog("stub"); return TRUE; }
+static PVOID WINAPI CertCreateCertificateContext(DWORD dwCertEncodingType, PVOID pbCertEncoded, DWORD cbCertEncoded) { DebugLog("stub"); return NULL; }
+static BOOL WINAPI CertDeleteCertificateFromStore(PVOID pCertContext) { DebugLog("stub"); return TRUE; }
+static PVOID WINAPI CertEnumCertificatesInStore(HANDLE hCertStore, PVOID pPrevCertContext) { DebugLog("stub"); return NULL; }
+static BOOL WINAPI CertFreeCertificateChain(PVOID pChainContext) { DebugLog("stub"); return TRUE; }
+static BOOL WINAPI CertGetCertificateChain(PVOID hChainEngine, PVOID pCertContext, PVOID pTime, PVOID hAdditionalStore, PVOID pChainPara, DWORD dwFlags, PVOID pvReserved, PVOID ppChainContext) { DebugLog("stub"); return FALSE; }
+static BOOL WINAPI CertGetCertificateContextProperty(PVOID pCertContext, DWORD dwPropId, PVOID pvData, PDWORD pcbData) { DebugLog("stub propId=%u", dwPropId); if (pcbData) *pcbData = 0; return FALSE; }
+static DWORD WINAPI CertGetNameStringW(PVOID pCertContext, DWORD dwType, DWORD dwFlags, PVOID pvTypePara, PWCHAR pszNameString, DWORD cchNameString) { DebugLog("stub"); if (pszNameString && cchNameString > 0) pszNameString[0] = 0; return 1; }
+static DWORD WINAPI CertNameToStrW(DWORD dwCertEncodingType, PVOID pName, DWORD dwStrType, PWCHAR psz, DWORD csz) { DebugLog("stub"); if (psz && csz > 0) psz[0] = 0; return 1; }
+static BOOL WINAPI CryptDecodeObject(DWORD dwCertEncodingType, PVOID lpszStructType, PVOID pbEncoded, DWORD cbEncoded, DWORD dwFlags, PVOID pvStructInfo, PDWORD pcbStructInfo) { DebugLog("stub"); return FALSE; }
+static BOOL WINAPI CryptMsgClose(PVOID hCryptMsg) { DebugLog("stub %p", hCryptMsg); return TRUE; }
+static BOOL WINAPI CryptMsgGetParam(PVOID hCryptMsg, DWORD dwParamType, DWORD dwIndex, PVOID pvData, PDWORD pcbData) { DebugLog("stub type=%u", dwParamType); return FALSE; }
+static PVOID WINAPI CryptMsgOpenToDecode(DWORD dwMsgEncodingType, DWORD dwFlags, DWORD dwMsgType, PVOID hCryptProv, PVOID pRecipientInfo, PVOID pStreamInfo) { DebugLog("stub"); return (PVOID) 'CMSG'; }
+static BOOL WINAPI CryptMsgUpdate(PVOID hCryptMsg, PVOID pbData, DWORD cbData, BOOL fFinal) { DebugLog("stub %p, %u bytes", hCryptMsg, cbData); return TRUE; }
+static BOOL WINAPI CryptQueryObject(DWORD dwObjectType, PVOID pvObject, DWORD dwExpectedContentTypeFlags, DWORD dwExpectedFormatTypeFlags, DWORD dwFlags, PDWORD pdwMsgAndCertEncodingType, PDWORD pdwContentType, PDWORD pdwFormatType, PVOID phCertStore, PVOID phMsg, PVOID ppvContext) { DebugLog("stub"); return FALSE; }
+static BOOL WINAPI CryptStringToBinaryW(PWCHAR pszString, DWORD cchString, DWORD dwFlags, PVOID pbBinary, PDWORD pcbBinary, PDWORD pdwSkip, PDWORD pdwFlags) { DebugLog("stub"); return FALSE; }
+
DECLARE_CRT_EXPORT("CertCloseStore", CertCloseStore);
DECLARE_CRT_EXPORT("CertFindCertificateInStore", CertFindCertificateInStore);
DECLARE_CRT_EXPORT("CertFreeCertificateContext", CertFreeCertificateContext);
@@ -317,9 +534,38 @@ DECLARE_CRT_EXPORT("CryptCreateHash", CryptCreateHash);
DECLARE_CRT_EXPORT("BCryptOpenAlgorithmProvider", BCryptOpenAlgorithmProvider);
DECLARE_CRT_EXPORT("BCryptCloseAlgorithmProvider", BCryptCloseAlgorithmProvider);
DECLARE_CRT_EXPORT("BCryptGenRandom", BCryptGenRandom);
+DECLARE_CRT_EXPORT("BCryptGetProperty", BCryptGetProperty);
+DECLARE_CRT_EXPORT("BCryptSetProperty", BCryptSetProperty);
+DECLARE_CRT_EXPORT("BCryptCreateHash", BCryptCreateHash);
+DECLARE_CRT_EXPORT("BCryptHashData", BCryptHashData);
+DECLARE_CRT_EXPORT("BCryptFinishHash", BCryptFinishHash);
+DECLARE_CRT_EXPORT("BCryptDestroyHash", BCryptDestroyHash);
+DECLARE_CRT_EXPORT("BCryptImportKeyPair", BCryptImportKeyPair);
+DECLARE_CRT_EXPORT("BCryptDestroyKey", BCryptDestroyKey);
+DECLARE_CRT_EXPORT("BCryptVerifySignature", BCryptVerifySignature);
+DECLARE_CRT_EXPORT("BCryptEncrypt", BCryptEncrypt);
+DECLARE_CRT_EXPORT("BCryptExportKey", BCryptExportKey);
+DECLARE_CRT_EXPORT("BCryptGenerateSymmetricKey", BCryptGenerateSymmetricKey);
DECLARE_CRT_EXPORT("CryptAcquireContextW", CryptAcquireContextW);
DECLARE_CRT_EXPORT("CryptGetHashParam", CryptGetHashParam);
DECLARE_CRT_EXPORT("CryptSetHashParam", CryptSetHashParam);
DECLARE_CRT_EXPORT("CryptVerifySignatureW", CryptVerifySignatureW);
DECLARE_CRT_EXPORT("CryptDestroyHash", CryptDestroyHash);
+// Runtime-resolved crypt32.dll exports
+DECLARE_CRT_EXPORT("CertAddEncodedCertificateToStore", CertAddEncodedCertificateToStore);
+DECLARE_CRT_EXPORT("CertCreateCertificateContext", CertCreateCertificateContext);
+DECLARE_CRT_EXPORT("CertDeleteCertificateFromStore", CertDeleteCertificateFromStore);
+DECLARE_CRT_EXPORT("CertEnumCertificatesInStore", CertEnumCertificatesInStore);
+DECLARE_CRT_EXPORT("CertFreeCertificateChain", CertFreeCertificateChain);
+DECLARE_CRT_EXPORT("CertGetCertificateChain", CertGetCertificateChain);
+DECLARE_CRT_EXPORT("CertGetCertificateContextProperty", CertGetCertificateContextProperty);
+DECLARE_CRT_EXPORT("CertGetNameStringW", CertGetNameStringW);
+DECLARE_CRT_EXPORT("CertNameToStrW", CertNameToStrW);
+DECLARE_CRT_EXPORT("CryptDecodeObject", CryptDecodeObject);
+DECLARE_CRT_EXPORT("CryptMsgClose", CryptMsgClose);
+DECLARE_CRT_EXPORT("CryptMsgGetParam", CryptMsgGetParam);
+DECLARE_CRT_EXPORT("CryptMsgOpenToDecode", CryptMsgOpenToDecode);
+DECLARE_CRT_EXPORT("CryptMsgUpdate", CryptMsgUpdate);
+DECLARE_CRT_EXPORT("CryptQueryObject", CryptQueryObject);
+DECLARE_CRT_EXPORT("CryptStringToBinaryW", CryptStringToBinaryW);
diff --git a/peloader/winapi/Environment.c b/peloader/winapi/Environment.c
index cccb685..018c3a1 100644
--- a/peloader/winapi/Environment.c
+++ b/peloader/winapi/Environment.c
@@ -1,6 +1,7 @@
#include <stdint.h>
#include <stddef.h>
#include <string.h>
+#include <strings.h>
#include <stdbool.h>
#include <stdlib.h>
#include <search.h>
@@ -61,52 +62,99 @@ STATIC DWORD WINAPI GetEnvironmentVariableW(PWCHAR lpName, PVOID lpBuffer, DWORD
return CountWideChars(lpBuffer);
}
+// Known environment variable mappings (case-insensitive lookup).
+static struct {
+ const char *Name;
+ const char *Value;
+} KnownEnvVars[] = {
+ { "ProgramFiles", "C:\\Program Files" },
+ { "ProgramFiles(x86)", "C:\\Program Files" },
+ { "AllUsersProfile", "C:\\ProgramData" },
+ { "ProgramData", "C:\\ProgramData" },
+ { "PATH", "C:\\Path" },
+ { "windir", "C:\\Windows" },
+ { "WINDIR", "C:\\Windows" },
+ { "SystemRoot", "C:\\Windows" },
+ { "CommonProgramFiles", "C:\\CommonProgramFiles" },
+ { NULL, NULL },
+};
+
+// Expand %VAR% patterns in an ANSI string, writing result to out.
+// Returns the required buffer length (including NUL).
+static size_t expand_env_ansi(const char *src, char *out, size_t outlen)
+{
+ size_t pos = 0;
+
+ while (*src) {
+ if (*src == '%') {
+ const char *end = strchr(src + 1, '%');
+ if (end && end > src + 1) {
+ size_t varlen = end - src - 1;
+ const char *replacement = NULL;
+
+ for (int i = 0; KnownEnvVars[i].Name; i++) {
+ if (strlen(KnownEnvVars[i].Name) == varlen &&
+ strncasecmp(KnownEnvVars[i].Name, src + 1, varlen) == 0) {
+ replacement = KnownEnvVars[i].Value;
+ break;
+ }
+ }
+
+ if (replacement) {
+ size_t rlen = strlen(replacement);
+ if (out && pos + rlen < outlen)
+ memcpy(out + pos, replacement, rlen);
+ pos += rlen;
+ src = end + 1;
+ continue;
+ }
+ }
+ }
+ if (out && pos + 1 < outlen)
+ out[pos] = *src;
+ pos++;
+ src++;
+ }
+
+ if (out && pos < outlen)
+ out[pos] = '\0';
+ else if (out && outlen > 0)
+ out[outlen - 1] = '\0';
+
+ return pos + 1;
+}
+
// MPENGINE is very fussy about what ExpandEnvironmentStringsW returns.
STATIC DWORD WINAPI ExpandEnvironmentStringsW(PWCHAR lpSrc, PWCHAR lpDst, DWORD nSize)
{
PCHAR AnsiString = CreateAnsiFromWide(lpSrc);
- DWORD Result;
- struct {
- PCHAR Src;
- PWCHAR Dst;
- } KnownPaths[] = {
- { "%ProgramFiles%", L"C:\\Program Files" },
- { "%AllUsersProfile%", L"C:\\ProgramData" },
- { "%PATH%", L"C:\\Path" },
- { "%windir%", L"C:\\Windows" },
- { "%ProgramFiles(x86)%", L"C:\\Program Files" },
- { "%WINDIR%\\system32\\drivers", L"C:\\WINDOWS\\system32\\drivers" },
- { "%windir%\\temp", L"C:\\WINDOWS\\temp" },
- { "%CommonProgramFiles%", L"C:\\CommonProgramFiles" },
- { NULL },
- };
DebugLog("%p [%s], %p, %u", lpSrc, AnsiString, lpDst, nSize);
- for (int i = 0; KnownPaths[i].Src; i++) {
- if (strcmp(AnsiString, KnownPaths[i].Src) == 0) {
- Result = CountWideChars(KnownPaths[i].Dst) + 1;
- if (nSize < Result) {
- goto finish;
- }
- memcpy(lpDst, KnownPaths[i].Dst, Result * 2);
- goto finish;
- }
+ // First pass: determine required size.
+ size_t needed = expand_env_ansi(AnsiString, NULL, 0);
+
+ if (!lpDst || nSize < needed) {
+ free(AnsiString);
+ return (DWORD)needed;
}
+ // Second pass: expand into a temporary ANSI buffer.
+ char *expanded = malloc(needed);
+ if (!expanded) {
+ free(AnsiString);
+ return 0;
+ }
+ expand_env_ansi(AnsiString, expanded, needed);
free(AnsiString);
- if (nSize < CountWideChars(lpSrc) + 1) {
- return CountWideChars(lpSrc) + 1;
+ // Convert expanded ANSI to wide string.
+ for (size_t i = 0; i < needed && i < nSize; i++) {
+ lpDst[i] = (WCHAR)(unsigned char)expanded[i];
}
- memcpy(lpDst, lpSrc, (1 + CountWideChars(lpSrc)) * 2);
-
- return CountWideChars(lpSrc) + 1;
-
-finish:
- free(AnsiString);
- return Result;
+ free(expanded);
+ return (DWORD)needed;
}
static DWORD WINAPI GetEnvironmentVariableA(PCHAR lpName, PVOID lpBuffer, DWORD nSize)
diff --git a/peloader/winapi/Exception.c b/peloader/winapi/Exception.c
index b21a8a3..2f07e09 100644
--- a/peloader/winapi/Exception.c
+++ b/peloader/winapi/Exception.c
@@ -41,6 +41,19 @@ VOID DumpExceptionChain(VOID)
}
#endif
+// Check if an address looks like a valid stack pointer (heuristic)
+static inline int is_valid_seh_frame(PEXCEPTION_FRAME frame)
+{
+ uintptr_t addr = (uintptr_t)frame;
+ // Stack addresses on Linux x86-32 are typically in the 0xff000000+ range
+ // Heap addresses are typically much lower. Also accept NULL (end of chain).
+ if (frame == NULL) return 1;
+ if (addr >= 0xff000000 && addr <= 0xffffffff) return 1;
+ // Also accept addresses in the thread stack range (could vary)
+ if (addr >= 0xf0000000) return 1;
+ return 0;
+}
+
static WINAPI PVOID RaiseException(DWORD dwExceptionCode, DWORD dwExceptionFlags, DWORD nNumberOfArguments, PVOID Arguments)
{
PEXCEPTION_FRAME ExceptionList;
@@ -85,16 +98,16 @@ static WINAPI PVOID RaiseException(DWORD dwExceptionCode, DWORD dwExceptionFlags
continue;
}
- // I've never seen any other handler return code with mpengine.
- __debugbreak();
+ // Handler returned something other than ExceptionContinueSearch.
+ DebugLog("WARNING: Handler returned unexpected result %u", Result);
+ break;
}
- // Unhandled Exception?
- DebugLog("%u Element SEH Chain Complete.", Depth);
+ // Unhandled C++ exception - for 0xe06d7363 this is normal in some cases
+ // (the C++ runtime will call std::terminate or handle it otherwise)
+ DebugLog("%u Element SEH Chain Complete, exception %#x unhandled.", Depth, dwExceptionCode);
finished:
- // I've never seen this reached, I'm not sure if it works.
- __debugbreak();
return NULL;
}
@@ -146,6 +159,10 @@ static WINAPI void RtlUnwind(PEXCEPTION_FRAME TargetFrame, PVOID TargetIp, PEXCE
if (ExceptionList == TargetFrame) {
DebugLog("TargetFrame %p == ExceptionList %p, Restore Context", ExceptionList, TargetFrame);
+ // Remove the TargetFrame from the SEH chain before restoring context.
+ // The handler's catch block expects fs:0 to point past this frame.
+ asm("mov %[list], %%fs:0" :: [list] "r"(ExceptionList->prev));
+
setcontext(&Context);
// Should not reach here.
diff --git a/peloader/winapi/Files.c b/peloader/winapi/Files.c
index f469367..a4fd142 100644
--- a/peloader/winapi/Files.c
+++ b/peloader/winapi/Files.c
@@ -8,6 +8,9 @@
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
+#include <dirent.h>
+#include <limits.h>
+#include <strings.h>
#include "winnt_types.h"
#include "pe_linker.h"
@@ -17,6 +20,11 @@
#include "util.h"
#include "winstrings.h"
+extern int is_thread_handle(HANDLE hObject);
+extern void close_thread_handle(HANDLE hObject);
+extern int is_file_mapping(HANDLE hObject);
+extern void close_file_mapping(HANDLE hObject);
+
typedef struct _WIN32_FILE_ATTRIBUTE_DATA {
DWORD dwFileAttributes;
FILETIME ftCreationTime;
@@ -34,6 +42,156 @@ extern void WINAPI SetLastError(DWORD dwErrCode);
#define INVALID_FILE_ATTRIBUTES -1;
+static bool trace_files_enabled(void)
+{
+ const char *v = getenv("MPENGINE_TRACE_FILES");
+ return v && *v;
+}
+
+static void normalize_winpath(char *path)
+{
+ if (!path)
+ return;
+
+ // Strip Win32 device prefixes.
+ if (strncmp(path, "\\\\?\\", 4) == 0 || strncmp(path, "\\\\??\\", 5) == 0) {
+ memmove(path, path + 4, strlen(path + 4) + 1);
+ }
+
+ // Translate path separator.
+ for (char *p = path; *p; ++p) {
+ if (*p == '\\')
+ *p = '/';
+ }
+
+ // Handle //./ prefix.
+ if (strncmp(path, "//./", 4) == 0) {
+ memmove(path, path + 4, strlen(path + 4) + 1);
+ } else if (strncmp(path, "/./", 3) == 0) {
+ memmove(path, path + 3, strlen(path + 3) + 1);
+ }
+
+ // Collapse duplicate slashes.
+ char *src = path;
+ char *dst = path;
+ while (*src) {
+ *dst++ = *src;
+ if (*src == '/') {
+ while (*src == '/')
+ src++;
+ continue;
+ }
+ src++;
+ }
+ *dst = '\0';
+
+ // Strip drive prefix if present (e.g. C:/path -> /path).
+ if (isalpha((unsigned char)path[0]) && path[1] == ':') {
+ if (path[2] == '\0') {
+ strcpy(path, "/");
+ } else {
+ memmove(path, path + 2, strlen(path + 2) + 1);
+ }
+ }
+}
+
+static FILE *open_special_if_missing(const char *path, DWORD disposition)
+{
+ if (!path)
+ return NULL;
+
+ // Allow creation of test license if missing (engine handles empty license gracefully).
+ // Do NOT create mpcache files — empty ones cause C++ exceptions and 0x8001 boot failure.
+ if (strcasestr(path, "mpenginetestlicense.dat")) {
+ if (disposition == 3 || disposition == 4) {
+ return fopen(path, "w+");
+ }
+ }
+
+ // Treat volume device opens like //./C: as root.
+ if (strcmp(path, "/") == 0) {
+ return fopen("/", "r");
+ }
+
+ return NULL;
+}
+static char *ResolveCasePath(const char *path)
+{
+ if (!path || !*path)
+ return NULL;
+
+ char *work = strdup(path);
+ if (!work)
+ return NULL;
+
+ size_t out_cap = strlen(path) + 2;
+ char *out = calloc(1, out_cap);
+ if (!out) {
+ free(work);
+ return NULL;
+ }
+
+ bool abs = (work[0] == '/');
+ char cur[PATH_MAX];
+ size_t out_len = 0;
+
+ if (abs) {
+ strcpy(cur, "/");
+ out[out_len++] = '/';
+ out[out_len] = '\0';
+ } else {
+ strcpy(cur, ".");
+ }
+
+ char *saveptr = NULL;
+ char *token = strtok_r(abs ? work + 1 : work, "/", &saveptr);
+ while (token) {
+ DIR *dir = opendir(cur);
+ const char *match = token;
+ if (dir) {
+ struct dirent *ent = NULL;
+ while ((ent = readdir(dir))) {
+ if (strcasecmp(ent->d_name, token) == 0) {
+ match = ent->d_name;
+ break;
+ }
+ }
+ closedir(dir);
+ }
+
+ if (out_len && out[out_len - 1] != '/') {
+ out[out_len++] = '/';
+ out[out_len] = '\0';
+ }
+ size_t mlen = strlen(match);
+ if (out_len + mlen + 1 > out_cap)
+ break;
+ memcpy(out + out_len, match, mlen);
+ out_len += mlen;
+ out[out_len] = '\0';
+
+ {
+ char tmp[PATH_MAX];
+ if (strcmp(cur, "/") == 0)
+ snprintf(tmp, sizeof(tmp), "/%s", match);
+ else if (strcmp(cur, ".") == 0)
+ snprintf(tmp, sizeof(tmp), "%s", match);
+ else
+ snprintf(tmp, sizeof(tmp), "%s/%s", cur, match);
+ memcpy(cur, tmp, sizeof(cur));
+ }
+
+ token = strtok_r(NULL, "/", &saveptr);
+ }
+
+ free(work);
+ if (out_len == 0) {
+ free(out);
+ return NULL;
+ }
+ return out;
+}
+
static DWORD WINAPI GetFileAttributesW(PVOID lpFileName)
{
DWORD Result = FILE_ATTRIBUTE_NORMAL;
@@ -74,20 +232,23 @@ enum {
static HANDLE WINAPI CreateFileA(PCHAR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, PVOID lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile)
{
FILE *FileHandle;
+ char *resolved = NULL;
DebugLog("%p [%s], %#x, %#x, %p, %#x, %#x, %p", lpFileName, lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
- // Translate path seperator.
- while (strchr(lpFileName, '\\'))
- *strchr(lpFileName, '\\') = '/';
-
- // I'm just going to tolower() everything.
- for (char *t = lpFileName; *t; t++)
- *t = tolower(*t);
+ normalize_winpath(lpFileName);
switch (dwCreationDisposition) {
case OPEN_EXISTING:
FileHandle = fopen(lpFileName, "r");
+ if (!FileHandle) {
+ resolved = ResolveCasePath(lpFileName);
+ if (resolved) {
+ FileHandle = fopen(resolved, "r");
+ }
+ }
+ if (!FileHandle)
+ FileHandle = open_special_if_missing(lpFileName, dwCreationDisposition);
break;
case CREATE_ALWAYS:
FileHandle = fopen("/dev/null", "w");
@@ -108,7 +269,11 @@ static HANDLE WINAPI CreateFileA(PCHAR lpFileName, DWORD dwDesiredAccess, DWORD
DebugLog("%s => %p", lpFileName, FileHandle);
- SetLastError(ERROR_FILE_NOT_FOUND);
+ if (resolved)
+ free(resolved);
+ if (!FileHandle && trace_files_enabled())