Repository navigation
Expand file tree
/
Copy pathP2PIdentityStore.cpp
More file actions
2082 lines (1834 loc) · 85.1 KB
/
Copy pathP2PIdentityStore.cpp
File metadata and controls
2082 lines (1834 loc) · 85.1 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
// Copyright © 2026 Khrustal & Mann
// MELBOURNE, VICTORIA, AUSTRALIA, 3000
//
// 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.
//
//
// P2PIdentityStore.cpp - implementation of the identity storage layer.
// See P2PIdentityStore.h for the format and the threat boundary.
//
// One TU for both platforms, unlike the p2pcng primitives (CNG vs OpenSSL
// backends in separate files): the container format, the atomic-write dance,
// the text parsing and every validation rule here are platform-independent,
// and duplicating them into two files would be duplicating exactly the parts
// that must not drift apart. Only three things differ per platform - protect,
// unprotect, and how a file is created with restrictive permissions - and each
// is isolated below.
//
// Deliberately does NOT include stdafx.h. It needs no MFC and no Platform
// shim, which is what lets the Linux crypto_kat target compile it standalone
// next to the OpenSSL backend TU. The vcxproj marks it PrecompiledHeader
// NotUsing for the same reason.
//
#ifdef _WIN32
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
# include <wincrypt.h>
# include <dpapi.h>
# include <sddl.h>
# pragma comment(lib, "crypt32.lib") // CryptProtectData / CryptUnprotectData
# pragma comment(lib, "advapi32.lib") // ConvertStringSecurityDescriptorToSecurityDescriptorW
#else
# include <fcntl.h>
# include <unistd.h>
# include <sys/stat.h>
# include <sys/types.h>
# include <cerrno>
#endif
#include "P2PIdentityStore.h"
#include <string>
#include <vector>
#include <cstring>
#include <cstdio>
#include <ctime>
#include <mutex> // the external protector's registration
#ifndef _WIN32
#include <fcntl.h> // AT_FDCWD
#include <sys/syscall.h> // SYS_renameat2 (WriteWholeFile, exclusive, no hard links)
#include <unistd.h>
#endif
namespace p2pcng
{
namespace
{
// -------------------------------------------------------------------
// Container constants
// -------------------------------------------------------------------
// Which of the two P-256 keys a container holds. Both blobs are 96 bytes of
// X||Y||d, so nothing about the payload distinguishes them - the container
// has to, or a renamed file silently crosses a signing key with an agreement
// key. See the header.
enum KeyKind { KindIdentity = 0, KindAgreement = 1 };
const unsigned char kMagic[8] = { 'P','2','P','I','D','K','Y', 0x1A };
const unsigned char kMagicAgree[8] = { 'P','2','P','A','G','K','Y', 0x1A };
const unsigned int kVersion = 1;
const size_t kMaxPayload = 64u * 1024u; // a DPAPI blob over 96
// bytes is ~300; this is
// slack, not a budget
const size_t kMaxTextFile = 4u * 1024u * 1024u;
const size_t kMaxLine = 4096;
const unsigned char *MagicOf ( KeyKind eKind )
{
return eKind == KindAgreement ? kMagicAgree : kMagic;
}
#ifdef _WIN32
// DPAPI optional entropy. Binds the blob to this application. NOT a secret -
// see the header. Byte values are fixed here so a future build cannot
// silently change them and orphan every deployed identity file.
//
// Windows-only: POSIX protects the file with its mode, not with a blob, so
// off Windows these are dead weight and gcc rightly says so.
//
// The capital C is LOAD-BEARING, and is why the paragraph above is not just
// a wish. a9bc335's rename sweep recased both of these, which is precisely
// the silent change it warns of: entropy is an input to CryptUnprotectData,
// so every identity file written before that commit would have been
// undecryptable afterwards. StoreSelfTest cannot see it - it writes and
// reads inside one run, with whatever value it finds. These two strings are
// an on-disk format constant that happens to read like a product name. If
// the spelling must ever change, it changes with a new .v2 suffix and a
// read path that still accepts .v1, not on its own.
const char kEntropy[] = "TargetCore.identity.v1";
const char kEntropyAgree[] = "TargetCore.agreement.v1";
// Returns the entropy bytes and, through pcb, their length. Separate values
// per kind so the DPAPI layer refuses the swap too, not only the header.
const char *EntropyOf ( KeyKind eKind, size_t *pcb )
{
if ( eKind == KindAgreement )
{
*pcb = sizeof(kEntropyAgree) - 1;
return kEntropyAgree;
}
*pcb = sizeof(kEntropy) - 1;
return kEntropy;
}
#endif
// -------------------------------------------------------------------
// Small helpers
// -------------------------------------------------------------------
void ZeroMem ( void *pMem, size_t cbMem )
{
// Not SecureZeroMemory: this TU compiles on Linux too. A volatile
// pointer is the portable form the optimiser may not elide.
volatile unsigned char *p = (volatile unsigned char *)pMem;
while ( cbMem-- ) *p++ = 0;
}
void ZeroVec ( std::vector<unsigned char> &v )
{
if ( !v.empty() ) ZeroMem ( &v[0], v.size() );
}
void PutU16 ( unsigned char *p, unsigned int v )
{
p[0] = (unsigned char)( v & 0xFF );
p[1] = (unsigned char)( (v >> 8) & 0xFF );
}
unsigned int GetU16 ( const unsigned char *p )
{
return (unsigned int)p[0] | ( (unsigned int)p[1] << 8 );
}
void PutU32 ( unsigned char *p, unsigned long v )
{
p[0] = (unsigned char)( v & 0xFF );
p[1] = (unsigned char)( (v >> 8) & 0xFF );
p[2] = (unsigned char)( (v >> 16) & 0xFF );
p[3] = (unsigned char)( (v >> 24) & 0xFF );
}
unsigned long GetU32 ( const unsigned char *p )
{
return (unsigned long)p[0] | ( (unsigned long)p[1] << 8 ) |
( (unsigned long)p[2] << 16 ) | ( (unsigned long)p[3] << 24 );
}
bool HexEncode ( const unsigned char *pIn, size_t cbIn, std::string &sOut )
{
static const char *pszDigits = "0123456789abcdef";
if ( !pIn ) return false;
sOut.clear();
sOut.reserve ( cbIn * 2 );
for ( size_t i = 0; i < cbIn; i++ )
{
sOut.push_back ( pszDigits[ pIn[i] >> 4 ] );
sOut.push_back ( pszDigits[ pIn[i] & 0x0F] );
}
return true;
}
int HexNibble ( char c )
{
if ( c >= '0' && c <= '9' ) return c - '0';
if ( c >= 'a' && c <= 'f' ) return c - 'a' + 10;
if ( c >= 'A' && c <= 'F' ) return c - 'A' + 10;
return -1;
}
// Exactly cbOut bytes from exactly cbOut*2 hex chars. A short or long token
// is a format error, never a partial decode.
bool HexDecodeExact ( const char *pszHex, size_t cchHex,
unsigned char *pOut, size_t cbOut )
{
if ( !pszHex || !pOut || cchHex != cbOut * 2 ) return false;
for ( size_t i = 0; i < cbOut; i++ )
{
int hi = HexNibble ( pszHex[i * 2] );
int lo = HexNibble ( pszHex[i * 2 + 1] );
if ( hi < 0 || lo < 0 ) return false;
pOut[i] = (unsigned char)( ( hi << 4 ) | lo );
}
return true;
}
bool IsSpace ( char c )
{ return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\v' || c == '\f'; }
// Epoch seconds, decimal, non-negative, no sign and no leading '+'. Written
// by AppendRevocationList and read back by LoadRevocationList.
//
// Decimal rather than ISO-8601 deliberately: an ISO parser needs a
// timegm/_mkgmtime split across the two platforms and a decision about what
// a missing 'Z' means, all to validate a field that is never compared to a
// clock (P2PIdentityStore.h, "revocation is absolute"). The readable form of
// the date is written into the same line's comment instead, which is where
// the fingerprint already goes.
bool ParseEpoch ( const char *psz, size_t cch, long long *pllOut )
{
if ( !psz || !pllOut || cch == 0 || cch > 19 ) return false;
long long ll = 0;
for ( size_t i = 0; i < cch; i++ )
{
if ( psz[i] < '0' || psz[i] > '9' ) return false;
ll = ll * 10 + ( psz[i] - '0' );
}
*pllOut = ll;
return true;
}
// -------------------------------------------------------------------
// Platform: file I/O
//
// bSecret selects the private-key treatment: a restrictive ACL / mode
// 0600 on write, and a refusal to read a group- or world-accessible file
// on POSIX.
// -------------------------------------------------------------------
#ifdef _WIN32
bool Widen ( const char *pszUtf8, std::wstring &wOut )
{
if ( !pszUtf8 || !*pszUtf8 ) return false;
int n = MultiByteToWideChar ( CP_UTF8, MB_ERR_INVALID_CHARS, pszUtf8, -1,
nullptr, 0 );
if ( n <= 1 ) return false; // n counts the NUL
wOut.assign ( (size_t)n, L'\0' ); // room for the NUL...
if ( MultiByteToWideChar ( CP_UTF8, MB_ERR_INVALID_CHARS, pszUtf8, -1,
&wOut[0], n ) != n )
return false;
wOut.resize ( (size_t)n - 1 ); // ...which std::wstring keeps
return true; // for itself
}
IdResult ReadWholeFile ( const char *pszPathUtf8, std::vector<unsigned char> &vOut,
bool /*bSecret*/, size_t cbMax )
{
std::wstring wPath;
if ( !Widen ( pszPathUtf8, wPath ) ) return IdErrArgs;
HANDLE hFile = CreateFileW ( wPath.c_str(), GENERIC_READ, FILE_SHARE_READ,
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
nullptr );
if ( hFile == INVALID_HANDLE_VALUE )
{
DWORD dwErr = GetLastError();
return ( dwErr == ERROR_FILE_NOT_FOUND || dwErr == ERROR_PATH_NOT_FOUND )
? IdErrNotFound : IdErrIo;
}
// No POSIX-style mode check here: on Windows the file's protection is
// the DACL written at creation (below) plus DPAPI, and a DACL is not
// reducible to a mode word worth testing.
LARGE_INTEGER liSize;
if ( !GetFileSizeEx ( hFile, &liSize ) )
{
CloseHandle ( hFile );
return IdErrIo;
}
if ( liSize.QuadPart < 0 || (unsigned long long)liSize.QuadPart > cbMax )
{
CloseHandle ( hFile );
return IdErrFormat;
}
vOut.assign ( (size_t)liSize.QuadPart, 0 );
size_t cbDone = 0;
bool bOk = true;
while ( cbDone < vOut.size() )
{
DWORD cbRead = 0;
DWORD cbWant = (DWORD)( vOut.size() - cbDone );
if ( !ReadFile ( hFile, &vOut[cbDone], cbWant, &cbRead, nullptr ) ||
cbRead == 0 )
{ bOk = false; break; }
cbDone += cbRead;
}
CloseHandle ( hFile );
if ( !bOk ) { ZeroVec ( vOut ); vOut.clear(); return IdErrIo; }
return IdOk;
}
// Creates the temp file with an explicit DACL when bSecret: SYSTEM,
// Administrators and the owner, protected from inheritance. This is the
// Windows counterpart of 0600, and it matters MORE here than on POSIX
// precisely because machine-scope DPAPI does not restrict local readers -
// the ACL is what keeps an ordinary local account away from the blob.
IdResult WriteWholeFile ( const char *pszPathUtf8, const unsigned char *pData,
size_t cbData, bool bSecret, bool bExclusive )
{
std::wstring wPath;
if ( !Widen ( pszPathUtf8, wPath ) ) return IdErrArgs;
wchar_t szSuffix[32];
swprintf ( szSuffix, 32, L".%lu.tmp", (unsigned long)GetCurrentProcessId() );
std::wstring wTemp = wPath + szSuffix;
SECURITY_ATTRIBUTES sa;
PSECURITY_DESCRIPTOR pSD = nullptr;
LPSECURITY_ATTRIBUTES pSA = nullptr;
if ( bSecret )
{
// D:P DACL, protected (no inherited ACEs)
// (A;;FA;;;SY) LocalSystem - full
// (A;;FA;;;BA) Administrators - full (they can take ownership
// regardless; denying is theatre)
// (A;;FA;;;OW) Owner Rights - full, so the creating account
// can still read its own key
if ( !ConvertStringSecurityDescriptorToSecurityDescriptorW (
L"D:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;FA;;;OW)",
SDDL_REVISION_1, &pSD, nullptr ) )
return IdErrIo; // fail closed: no ACL, no key file
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = pSD;
sa.bInheritHandle = FALSE;
pSA = &sa;
}
// CREATE_NEW, not CREATE_ALWAYS: a security descriptor passed to
// CreateFile is applied only when the file is actually created, so
// reusing a stale temp file would silently inherit the directory's ACL.
DeleteFileW ( wTemp.c_str() );
HANDLE hFile = CreateFileW ( wTemp.c_str(), GENERIC_WRITE, 0, pSA,
CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr );
if ( pSD ) LocalFree ( pSD );
if ( hFile == INVALID_HANDLE_VALUE ) return IdErrIo;
bool bOk = true;
size_t cbDone = 0;
while ( cbDone < cbData )
{
DWORD cbWrote = 0;
DWORD cbWant = (DWORD)( cbData - cbDone );
if ( !WriteFile ( hFile, pData + cbDone, cbWant, &cbWrote, nullptr ) ||
cbWrote == 0 )
{ bOk = false; break; }
cbDone += cbWrote;
}
if ( bOk ) bOk = ( FlushFileBuffers ( hFile ) != FALSE );
CloseHandle ( hFile );
if ( !bOk )
{
DeleteFileW ( wTemp.c_str() );
return IdErrIo;
}
// Without MOVEFILE_REPLACE_EXISTING the move IS the exclusive create,
// and it is atomic - there is no check-then-act window for a second
// process to slip through.
DWORD dwFlags = MOVEFILE_WRITE_THROUGH |
( bExclusive ? 0 : MOVEFILE_REPLACE_EXISTING );
if ( !MoveFileExW ( wTemp.c_str(), wPath.c_str(), dwFlags ) )
{
DWORD dwErr = GetLastError();
DeleteFileW ( wTemp.c_str() );
if ( bExclusive &&
( dwErr == ERROR_ALREADY_EXISTS || dwErr == ERROR_FILE_EXISTS ) )
return IdErrExists;
return IdErrIo;
}
return IdOk;
}
bool FileExists ( const char *pszPathUtf8 )
{
std::wstring wPath;
if ( !Widen ( pszPathUtf8, wPath ) ) return false;
return GetFileAttributesW ( wPath.c_str() ) != INVALID_FILE_ATTRIBUTES;
}
void DeleteOneFile ( const char *pszPathUtf8 )
{
std::wstring wPath;
if ( Widen ( pszPathUtf8, wPath ) ) DeleteFileW ( wPath.c_str() );
}
#else // ---- POSIX ----------------------------------------------------
IdResult ReadWholeFile ( const char *pszPathUtf8, std::vector<unsigned char> &vOut,
bool bSecret, size_t cbMax )
{
if ( !pszPathUtf8 || !*pszPathUtf8 ) return IdErrArgs;
int fd = ::open ( pszPathUtf8, O_RDONLY | O_CLOEXEC );
if ( fd < 0 )
return ( errno == ENOENT || errno == ENOTDIR ) ? IdErrNotFound : IdErrIo;
struct stat st;
if ( ::fstat ( fd, &st ) != 0 ) { ::close ( fd ); return IdErrIo; }
// ssh's rule, and for ssh's reason: a private key readable by the group
// or the world is not a private key, and tolerating it once means
// tolerating it forever.
if ( bSecret && ( st.st_mode & ( S_IRWXG | S_IRWXO ) ) != 0 )
{
::close ( fd );
return IdErrPerms;
}
if ( !S_ISREG ( st.st_mode ) ) { ::close ( fd ); return IdErrFormat; }
if ( (unsigned long long)st.st_size > cbMax )
{ ::close ( fd ); return IdErrFormat; }
vOut.assign ( (size_t)st.st_size, 0 );
size_t cbDone = 0;
bool bOk = true;
while ( cbDone < vOut.size() )
{
ssize_t n = ::read ( fd, &vOut[cbDone], vOut.size() - cbDone );
if ( n < 0 ) { if ( errno == EINTR ) continue; bOk = false; break; }
if ( n == 0 ) { bOk = false; break; }
cbDone += (size_t)n;
}
::close ( fd );
if ( !bOk ) { ZeroVec ( vOut ); vOut.clear(); return IdErrIo; }
return IdOk;
}
void FsyncDirOf ( const std::string &sPath )
{
// The rename is only durable once the DIRECTORY entry is on disk.
std::string sDir = sPath;
size_t iSlash = sDir.find_last_of ( '/' );
if ( iSlash == std::string::npos ) sDir = ".";
else if ( iSlash == 0 ) sDir = "/";
else sDir.erase ( iSlash );
int fd = ::open ( sDir.c_str(), O_RDONLY | O_CLOEXEC );
if ( fd >= 0 ) { ::fsync ( fd ); ::close ( fd ); }
}
IdResult WriteWholeFile ( const char *pszPathUtf8, const unsigned char *pData,
size_t cbData, bool bSecret, bool bExclusive )
{
if ( !pszPathUtf8 || !*pszPathUtf8 ) return IdErrArgs;
std::string sPath = pszPathUtf8;
char szSuffix[32];
std::snprintf ( szSuffix, sizeof(szSuffix), ".%ld.tmp", (long)::getpid() );
std::string sTemp = sPath + szSuffix;
::unlink ( sTemp.c_str() );
// O_EXCL so a symlink planted at the temp path cannot redirect the
// write; the mode is applied at creation, before a byte is written.
int fd = ::open ( sTemp.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC,
bSecret ? 0600 : 0644 );
if ( fd < 0 ) return IdErrIo;
bool bOk = true;
size_t cbDone = 0;
while ( cbDone < cbData )
{
ssize_t n = ::write ( fd, pData + cbDone, cbData - cbDone );
if ( n < 0 ) { if ( errno == EINTR ) continue; bOk = false; break; }
cbDone += (size_t)n;
}
if ( bOk ) bOk = ( ::fsync ( fd ) == 0 );
::close ( fd );
if ( !bOk ) { ::unlink ( sTemp.c_str() ); return IdErrIo; }
if ( bExclusive )
{
// rename() would silently replace. link() is the atomic
// create-if-absent: it fails EEXIST rather than clobbering a key
// another process just wrote.
bool bPlaced = false;
if ( ::link ( sTemp.c_str(), sPath.c_str() ) == 0 )
{
::unlink ( sTemp.c_str() );
bPlaced = true;
}
else
{
int nErr = errno;
// Android's SELinux policy forbids hard links outright (EACCES
// even in /data/local/tmp, and for every app), and some
// filesystems have none (EPERM). renameat2(RENAME_NOREPLACE) is
// the same atomic create-if-absent without a link; called
// through syscall() because bionic wraps it only from API 30.
#if defined(__linux__) && defined(SYS_renameat2)
if ( nErr == EACCES || nErr == EPERM || nErr == ENOSYS || nErr == EMLINK )
{
if ( ::syscall ( SYS_renameat2, AT_FDCWD, sTemp.c_str(),
AT_FDCWD, sPath.c_str(), 1u /* RENAME_NOREPLACE */ ) == 0 )
bPlaced = true;
else
nErr = errno;
}
#endif
if ( !bPlaced )
{
::unlink ( sTemp.c_str() );
return ( nErr == EEXIST ) ? IdErrExists : IdErrIo;
}
}
}
else if ( ::rename ( sTemp.c_str(), sPath.c_str() ) != 0 )
{
::unlink ( sTemp.c_str() );
return IdErrIo;
}
FsyncDirOf ( sPath );
return IdOk;
}
bool FileExists ( const char *pszPathUtf8 )
{
if ( !pszPathUtf8 || !*pszPathUtf8 ) return false;
struct stat st;
return ::stat ( pszPathUtf8, &st ) == 0;
}
void DeleteOneFile ( const char *pszPathUtf8 )
{
if ( pszPathUtf8 && *pszPathUtf8 ) ::unlink ( pszPathUtf8 );
}
#endif // _WIN32
// -------------------------------------------------------------------
// Platform: protect / unprotect
// -------------------------------------------------------------------
IdProtection ResolveProtection ( IdProtection eProtect )
{
if ( eProtect != IdProtect_Default ) return eProtect;
#ifdef _WIN32
return IdProtect_DpapiMachine;
#else
return IdProtect_None; // the 0600 mode is the protection
#endif
}
// IdProtect_External: the host's wrap/unwrap (SetExternalProtector). The
// mutex only orders registration against use; the call itself runs outside
// it, so a slow keystore does not serialise unrelated loads behind a lock.
std::mutex g_oExternalLock;
IdExternalProtectorFn g_pfnExternal = nullptr;
void *g_pExternalCtx = nullptr;
IdResult ExternalPayload ( bool bWrap, KeyKind eKind,
const unsigned char *pIn, size_t cbIn,
std::vector<unsigned char> &vOut )
{
IdExternalProtectorFn pfn;
void *pCtx;
{
std::lock_guard<std::mutex> g ( g_oExternalLock );
pfn = g_pfnExternal;
pCtx = g_pExternalCtx;
}
if ( !pfn ) return IdErrUnsupported;
std::vector<unsigned char> vBuf ( kMaxPayload, 0 );
size_t cb = pfn ( pCtx, bWrap, (int)eKind, pIn, cbIn, &vBuf[0], vBuf.size() );
if ( cb == 0 || cb > vBuf.size() )
{
ZeroVec ( vBuf );
return bWrap ? IdErrProtect : IdErrUnprotect;
}
vOut.assign ( vBuf.begin(), vBuf.begin() + cb );
ZeroVec ( vBuf );
return IdOk;
}
IdResult ProtectPayload ( IdProtection eProtect, KeyKind eKind,
const unsigned char *pIn, size_t cbIn,
std::vector<unsigned char> &vOut )
{
if ( eProtect == IdProtect_None )
{
vOut.assign ( pIn, pIn + cbIn );
return IdOk;
}
if ( eProtect == IdProtect_External )
return ExternalPayload ( true, eKind, pIn, cbIn, vOut );
#ifdef _WIN32
size_t cbEnt = 0;
const char *pEnt = EntropyOf ( eKind, &cbEnt );
DATA_BLOB blobIn;
DATA_BLOB blobEnt;
DATA_BLOB blobOut;
blobIn.cbData = (DWORD)cbIn;
blobIn.pbData = (BYTE *)pIn;
blobEnt.cbData = (DWORD)cbEnt;
blobEnt.pbData = (BYTE *)pEnt;
blobOut.cbData = 0;
blobOut.pbData = nullptr;
// CRYPTPROTECT_UI_FORBIDDEN unconditionally: this runs on service and
// IOCP pump threads, where a prompt would hang the process rather than
// ask anybody anything.
DWORD dwFlags = CRYPTPROTECT_UI_FORBIDDEN;
if ( eProtect == IdProtect_DpapiMachine ) dwFlags |= CRYPTPROTECT_LOCAL_MACHINE;
if ( !CryptProtectData ( &blobIn,
eKind == KindAgreement ? L"Targetcore agreement"
: L"Targetcore identity",
&blobEnt, nullptr, nullptr, dwFlags, &blobOut ) )
return IdErrProtect;
if ( blobOut.cbData == 0 || blobOut.cbData > kMaxPayload )
{
if ( blobOut.pbData ) LocalFree ( blobOut.pbData );
return IdErrProtect;
}
vOut.assign ( blobOut.pbData, blobOut.pbData + blobOut.cbData );
LocalFree ( blobOut.pbData );
return IdOk;
#else
(void)pIn; (void)cbIn; (void)vOut; (void)eKind;
return IdErrUnsupported; // no DPAPI off Windows
#endif
}
IdResult UnprotectPayload ( IdProtection eProtect, KeyKind eKind,
const unsigned char *pIn, size_t cbIn,
std::vector<unsigned char> &vOut )
{
if ( eProtect == IdProtect_None )
{
vOut.assign ( pIn, pIn + cbIn );
return IdOk;
}
if ( eProtect == IdProtect_External )
return ExternalPayload ( false, eKind, pIn, cbIn, vOut );
#ifdef _WIN32
size_t cbEnt = 0;
const char *pEnt = EntropyOf ( eKind, &cbEnt );
DATA_BLOB blobIn;
DATA_BLOB blobEnt;
DATA_BLOB blobOut;
blobIn.cbData = (DWORD)cbIn;
blobIn.pbData = (BYTE *)pIn;
blobEnt.cbData = (DWORD)cbEnt;
blobEnt.pbData = (BYTE *)pEnt;
blobOut.cbData = 0;
blobOut.pbData = nullptr;
// The scope flag is not repeated on the way in - DPAPI reads it from
// the blob. A machine-scope blob moved to another machine, or a
// user-scope blob read by another account, fails HERE, which is the
// protection doing its job and not an error to retry.
if ( !CryptUnprotectData ( &blobIn, nullptr, &blobEnt, nullptr, nullptr,
CRYPTPROTECT_UI_FORBIDDEN, &blobOut ) )
return IdErrUnprotect;
if ( blobOut.cbData == 0 || blobOut.cbData > kMaxPayload )
{
if ( blobOut.pbData )
{
ZeroMem ( blobOut.pbData, blobOut.cbData );
LocalFree ( blobOut.pbData );
}
return IdErrUnprotect;
}
vOut.assign ( blobOut.pbData, blobOut.pbData + blobOut.cbData );
ZeroMem ( blobOut.pbData, blobOut.cbData );
LocalFree ( blobOut.pbData );
return IdOk;
#else
(void)pIn; (void)cbIn; (void)vOut; (void)eKind;
return IdErrUnsupported;
#endif
}
// -------------------------------------------------------------------
// Container build / parse
// -------------------------------------------------------------------
bool DigestOf ( const unsigned char *pHdr16, const unsigned char *pPayload,
size_t cbPayload, unsigned char pOut[kSha256Len] )
{
std::vector<unsigned char> v;
v.reserve ( 16 + cbPayload );
v.insert ( v.end(), pHdr16, pHdr16 + 16 );
if ( cbPayload ) v.insert ( v.end(), pPayload, pPayload + cbPayload );
return Sha256 ( v.empty() ? nullptr : &v[0], v.size(), pOut );
}
IdResult BuildContainer ( IdProtection eProtect, KeyKind eKind,
const std::vector<unsigned char> &vPayload,
std::vector<unsigned char> &vOut )
{
if ( vPayload.empty() || vPayload.size() > kMaxPayload ) return IdErrArgs;
vOut.assign ( kIdHeaderLen + vPayload.size(), 0 );
memcpy ( &vOut[0], MagicOf ( eKind ), sizeof(kMagic) );
PutU16 ( &vOut[8], kVersion );
PutU16 ( &vOut[10], (unsigned int)eProtect );
PutU32 ( &vOut[12], (unsigned long)vPayload.size() );
unsigned char digest[kSha256Len];
if ( !DigestOf ( &vOut[0], &vPayload[0], vPayload.size(), digest ) )
return IdErrIo;
memcpy ( &vOut[16], digest, kSha256Len );
memcpy ( &vOut[kIdHeaderLen], &vPayload[0], vPayload.size() );
return IdOk;
}
IdResult ParseContainer ( const std::vector<unsigned char> &vFile, KeyKind eKind,
IdProtection *peProtect,
std::vector<unsigned char> &vPayload )
{
if ( vFile.size() < kIdHeaderLen ) return IdErrFormat;
// The magic must be the one for the kind the CALLER asked for. An
// agreement file offered to LoadIdentity fails here, which is the point.
if ( memcmp ( &vFile[0], MagicOf ( eKind ), sizeof(kMagic) ) != 0 )
return IdErrFormat;
unsigned int nVersion = GetU16 ( &vFile[8] );
unsigned int nProtect = GetU16 ( &vFile[10] );
unsigned long cbClaim = GetU32 ( &vFile[12] );
if ( nVersion != kVersion ) return IdErrVersion;
if ( nProtect != (unsigned int)IdProtect_None &&
nProtect != (unsigned int)IdProtect_DpapiMachine &&
nProtect != (unsigned int)IdProtect_DpapiUser &&
nProtect != (unsigned int)IdProtect_External )
return IdErrFormat;
if ( cbClaim == 0 || cbClaim > kMaxPayload ) return IdErrFormat;
// The length field must match the file exactly. A shorter file is a
// truncated write; a longer one is trailing garbage that a digest over
// only cbClaim bytes would not notice.
if ( vFile.size() != kIdHeaderLen + (size_t)cbClaim ) return IdErrFormat;
unsigned char digest[kSha256Len];
if ( !DigestOf ( &vFile[0], &vFile[kIdHeaderLen], (size_t)cbClaim, digest ) )
return IdErrIo;
if ( !ConstTimeEqual ( digest, &vFile[16], kSha256Len ) ) return IdErrIntegrity;
*peProtect = (IdProtection)nProtect;
vPayload.assign ( vFile.begin() + kIdHeaderLen, vFile.end() );
return IdOk;
}
// -------------------------------------------------------------------
// Line-oriented text parsing (public key + allow-list)
// -------------------------------------------------------------------
struct Token { const char *psz; size_t cch; };
// Splits one line into up to nMax whitespace-delimited tokens. Everything
// from an unquoted '#' onward is a comment.
size_t Tokenise ( const char *pLine, size_t cchLine, Token *pTok, size_t nMax )
{
size_t nTok = 0, i = 0;
while ( i < cchLine && nTok < nMax )
{
while ( i < cchLine && IsSpace ( pLine[i] ) ) i++;
if ( i >= cchLine || pLine[i] == '#' ) break;
size_t iStart = i;
while ( i < cchLine && !IsSpace ( pLine[i] ) && pLine[i] != '#' ) i++;
pTok[nTok].psz = pLine + iStart;
pTok[nTok].cch = i - iStart;
nTok++;
}
return nTok;
}
// Calls pfnLine(pCtx, tokens, count) per non-empty, non-comment line.
// pfnLine returns an IdResult; anything but IdOk aborts the walk.
template <class F>
IdResult ForEachLine ( const std::vector<unsigned char> &vText, F pfnLine )
{
size_t i = 0;
while ( i < vText.size() )
{
size_t iEnd = i;
while ( iEnd < vText.size() && vText[iEnd] != '\n' ) iEnd++;
size_t cchLine = iEnd - i;
if ( cchLine > kMaxLine ) return IdErrFormat;
const char *pLine = (const char *)&vText[i];
Token aTok[4];
size_t nTok = Tokenise ( pLine, cchLine, aTok, 4 );
if ( nTok )
{
IdResult r = pfnLine ( aTok, nTok );
if ( r != IdOk ) return r;
}
i = ( iEnd < vText.size() ) ? iEnd + 1 : iEnd;
}
return IdOk;
}
// -------------------------------------------------------------------
// Private-key files - one implementation, both kinds
// -------------------------------------------------------------------
// EcdsaP256 and EcdhP256 are unrelated types that happen to share three
// method names and a 96-byte blob shape, so the file dance - export,
// protect, digest, atomic write - is written once here instead of twice
// with a chance to drift apart. The KeyKind decides the magic and the DPAPI
// entropy, and nothing else differs.
template <class K>
IdResult SaveKeyFile ( const char *pszPathUtf8, K &oKey, KeyKind eKind,
size_t cbPriv, IdProtection eProtect, bool bOverwrite )
{
if ( !pszPathUtf8 || !*pszPathUtf8 ) return IdErrArgs;
IdProtection eUse = ResolveProtection ( eProtect );
if ( eUse != IdProtect_None &&
eUse != IdProtect_DpapiMachine &&
eUse != IdProtect_DpapiUser &&
eUse != IdProtect_External )
return IdErrArgs;
std::vector<unsigned char> vPriv ( cbPriv, 0 );
if ( !oKey.ExportPrivate ( &vPriv[0] ) ) { ZeroVec ( vPriv ); return IdErrKey; }
std::vector<unsigned char> vPayload;
IdResult r = ProtectPayload ( eUse, eKind, &vPriv[0], vPriv.size(), vPayload );
ZeroVec ( vPriv );
if ( r != IdOk ) return r;
std::vector<unsigned char> vFile;
r = BuildContainer ( eUse, eKind, vPayload, vFile );
ZeroVec ( vPayload );
if ( r != IdOk ) { ZeroVec ( vFile ); return r; }
r = WriteWholeFile ( pszPathUtf8, &vFile[0], vFile.size(), true, !bOverwrite );
ZeroVec ( vFile );
return r;
}
template <class K>
IdResult LoadKeyFile ( const char *pszPathUtf8, K &oKey, KeyKind eKind,
size_t cbPriv )
{
if ( !pszPathUtf8 || !*pszPathUtf8 ) return IdErrArgs;
std::vector<unsigned char> vFile;
IdResult r = ReadWholeFile ( pszPathUtf8, vFile, true,
kIdHeaderLen + kMaxPayload );
if ( r != IdOk ) return r;
IdProtection eProtect = IdProtect_None;
std::vector<unsigned char> vPayload;
r = ParseContainer ( vFile, eKind, &eProtect, vPayload );
ZeroVec ( vFile );
if ( r != IdOk ) { ZeroVec ( vPayload ); return r; }
std::vector<unsigned char> vPriv;
r = UnprotectPayload ( eProtect, eKind, &vPayload[0], vPayload.size(), vPriv );
ZeroVec ( vPayload );
if ( r != IdOk ) { ZeroVec ( vPriv ); return r; }
if ( vPriv.size() != cbPriv ) { ZeroVec ( vPriv ); return IdErrFormat; }
// ImportPrivate rejects a blob whose public half does not belong to the
// scalar, so a doctored file cannot load as a key that acts as somebody
// else. oKey is only touched here, at the last step - a failed load
// leaves the caller's existing key intact.
bool bImported = oKey.ImportPrivate ( &vPriv[0] );
ZeroVec ( vPriv );
return bImported ? IdOk : IdErrKey;
}
template <class K>
IdResult LoadOrCreateKeyFile ( const char *pszPathUtf8, K &oKey, KeyKind eKind,
size_t cbPriv, bool *pbCreated,
IdProtection eProtect )
{
if ( pbCreated ) *pbCreated = false;
if ( !pszPathUtf8 || !*pszPathUtf8 ) return IdErrArgs;
IdResult r = LoadKeyFile ( pszPathUtf8, oKey, eKind, cbPriv );
if ( r != IdErrNotFound ) return r; // loaded, or failed for a real reason
if ( !oKey.Generate() ) return IdErrKey;
r = SaveKeyFile ( pszPathUtf8, oKey, eKind, cbPriv, eProtect,
/*bOverwrite*/ false );
if ( r == IdErrExists )
return LoadKeyFile ( pszPathUtf8, oKey, eKind, cbPriv ); // another
// process got there first; its key wins
if ( r != IdOk ) return r;
if ( pbCreated ) *pbCreated = true;
return IdOk;
}
// -------------------------------------------------------------------
// Public-point files - one implementation, both kinds
// -------------------------------------------------------------------
template <class K>
IdResult SavePublicFile ( const char *pszPathUtf8, K &oKey, const char *pszWhat,
const char *pszCannot )
{
if ( !pszPathUtf8 || !*pszPathUtf8 ) return IdErrArgs;
unsigned char pub[kEcdsaPubLen]; // == kEcdhPubLen
if ( !oKey.ExportPublic ( pub ) ) return IdErrKey;
char szPrint[kIdFingerprintLen];
if ( !Fingerprint ( pub, szPrint ) ) return IdErrKey;
std::string sHex;
HexEncode ( pub, sizeof(pub), sHex );
std::string sText;
sText = "# Targetcore ";
sText += pszWhat;
sText += " public key - P-256, raw X||Y, hex.\n";
sText += "# Publishable: this is the half a peer needs in order to\n";
sText += "# ";
sText += pszCannot;
sText += "\n# fingerprint: ";
sText += szPrint;
sText += "\n";
sText += sHex;
sText += "\n";
return WriteWholeFile ( pszPathUtf8, (const unsigned char *)sText.data(),
sText.size(), false, false );
}
template <class K>
IdResult LoadPublicFile ( const char *pszPathUtf8, K &oKey )
{
if ( !pszPathUtf8 || !*pszPathUtf8 ) return IdErrArgs;
std::vector<unsigned char> vText;
IdResult r = ReadWholeFile ( pszPathUtf8, vText, false, kMaxTextFile );
if ( r != IdOk ) return r;
unsigned char pub[kEcdsaPubLen];
bool bFound = false;
// The first token that is exactly 128 hex characters wins, so a bare hex
// line and an "<identity> <hex>" allow-list line both load.
r = ForEachLine ( vText, [&] ( const Token *pTok, size_t nTok ) -> IdResult
{
if ( bFound ) return IdOk;
for ( size_t i = 0; i < nTok; i++ )
{
if ( pTok[i].cch != kIdPubHexChars ) continue;
if ( !HexDecodeExact ( pTok[i].psz, pTok[i].cch, pub, sizeof(pub) ) )
continue;
bFound = true;
return IdOk;
}
return IdOk;
} );
if ( r != IdOk ) return r;
if ( !bFound ) return IdErrFormat;
return oKey.ImportPublic ( pub ) ? IdOk : IdErrKey;
}
} // anonymous namespace
// -----------------------------------------------------------------------
// Result text
// -----------------------------------------------------------------------
void SetExternalProtector ( IdExternalProtectorFn pfn, void *pCtx )
{
std::lock_guard<std::mutex> g ( g_oExternalLock );
g_pfnExternal = pfn;
g_pExternalCtx = pfn ? pCtx : nullptr;
}
const char *IdResultText ( IdResult eResult )
{
switch ( eResult )
{
case IdOk: return "ok";
case IdErrArgs: return "invalid argument";
case IdErrIo: return "file I/O failed";
case IdErrNotFound: return "file not found";
case IdErrExists: return "file already exists";
case IdErrFormat: return "malformed file";
case IdErrVersion: return "unsupported container version";
case IdErrIntegrity: return "integrity check failed (file corrupted)";
case IdErrProtect: return "protect failed (DPAPI or the external protector)";
case IdErrUnprotect: return "unprotect failed (wrong machine, wrong user or "
"keystore key, or tampered)";
case IdErrKey: return "invalid or unusable key material";
case IdErrPerms: return "identity file permissions are too permissive";
case IdErrUnsupported: return "not supported on this platform";
case IdErrRevoked: return "key is on the revocation list";
}
return "unknown error";
}
// -----------------------------------------------------------------------