Skip to content

armgit / soju

Public Imported from GitHub
0

Play Windows games on Apple Silicon Macs. Free, open-source app that installs the official Battle.net, Steam, Epic and GOG launchers and lists your games in one library.

ncrypt: keep named CNG keys on disk so Epic stops issuing a session per launch

mikey92a44bafefdcdb
diff --git a/README.ko.md b/README.ko.md
index 48baa2302cd..a23b1ba1c1a 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -128,6 +128,8 @@ GPTK 안의 `libd3dshared.dylib`는 그래픽만이 아닙니다. **D2R 로더(
- **배틀넷 로그인 화면이 가끔 깜빡임(~1분 1회)** → 알려진 외관 이슈이며 자동으로 복구됩니다.
- **언리얼 엔진 게임 시작 시 "AMD graphics driver has known issues" 경고**(Hogwarts Legacy 등): D3DMetal이 자신을 구형 드라이버의 AMD 카드로 소개해 UE4의 드라이버 검사가 걸리는 것입니다. 무해하며 OK로 넘어가면 됩니다. 없애려면 게임의 사용자 `Engine.ini`(`AppData/Local/<게임>/Saved/Config/WindowsNoEditor/`)에 `[SystemSettings]` / `r.WarnOfBadDrivers=0`을 추가하세요.
- **GOG GALAXY: 알림 토스트가 뜨는 동안 오른쪽 아래가 검은 사각형으로 가려짐**, 토스트가 사라지면 함께 사라짐. 토스트는 GOG 알림 렌더러의 투명 레이어 창인데 Wine에는 DWM 합성이 없어 투명 영역이 검게 칠해집니다. 무해하며, GOG 설정에서 데스크톱 알림을 끄면 안 뜹니다.
+- **Epic: "your account has too many active logins"**, 모든 기기에서 로그아웃하거나 비밀번호를 재설정해도 그대로인 경우. 서버가 실제로 답하는 것은 `too_many_sessions`(18048)이고, 이는 보유 중인 세션이 아니라 *발급된* 세션 수에 대한 제한이라 재시도할수록 나빠진다. 예전 엔진에서는 런처의 기기 키를 wine이 저장하지 못해 몇 번만 실행해도 걸렸다(`patches/ncrypt-persisted-keys.patch` 참고). 보틀을 끄고(`soju epic-kill`) 몇 시간 두어 카운터가 비워진 뒤 한 번만 실행하세요.
+
- **BLZBNTBNA00000005** → `play.sh`가 서명된 exe를 자동으로 넣어 줍니다.
## 라이선스
diff --git a/README.md b/README.md
index a43a9c370dc..b3dad346f9f 100644
--- a/README.md
+++ b/README.md
@@ -133,6 +133,7 @@ Start with `soju doctor`: it checks most of the items below and tells you which
- **Battle.net login webview may flicker (~once a minute)** -> known cosmetic issue; it recovers automatically and login works.
- **"The installed version of the AMD graphics driver has known issues" when an Unreal Engine game starts** (Hogwarts Legacy and others): D3DMetal presents itself as an AMD adapter with an old driver version, so UE4's driver check fires. Harmless, click OK; to silence it add `[SystemSettings]` / `r.WarnOfBadDrivers=0` to the game's user `Engine.ini` (under `AppData/Local/<Game>/Saved/Config/WindowsNoEditor/`).
- **GOG GALAXY: a black rectangle appears at the bottom right while a notification toast is shown** and disappears with it. The toast is a transparent layered window from GOG's notifications renderer; without DWM composition Wine paints its transparent area black. Harmless. Turning off desktop notifications in GOG's settings avoids it.
+- **Epic: "your account has too many active logins"** and logging out everywhere or resetting the password does not help. The account service is really answering `too_many_sessions` (18048), a limit on how many sessions were *issued*, not how many are held, so retrying makes it worse. Older engines hit this within a handful of launches because Wine could not keep the launcher's device key: see `patches/ncrypt-persisted-keys.patch`. Stop the bottle (`soju epic-kill`), leave it alone for a few hours so the counter clears, then start it once.
- **BLZBNTBNA00000005** -> `play.sh` seeds the signed exe automatically; make sure you launch through it.
### Leftover Wine processes
diff --git a/README.zh.md b/README.zh.md
index 527343f2d50..c3f0069ae79 100644
--- a/README.zh.md
+++ b/README.zh.md
@@ -133,6 +133,7 @@ scripts/play.sh steam-kill # 停止 Steam bottle
- **战网登录 webview 偶尔闪烁(约一分钟一次)** -> 已知的外观问题;会自动恢复,不影响登录。
- **虚幻引擎游戏启动时提示 "The installed version of the AMD graphics driver has known issues"**(《霍格沃茨之遗》等):D3DMetal 把自己伪装成旧驱动版本的 AMD 显卡,触发了 UE4 的驱动检查。无害,点确定即可;想彻底关掉就在游戏的用户 `Engine.ini`(`AppData/Local/<游戏>/Saved/Config/WindowsNoEditor/` 下)加入 `[SystemSettings]` / `r.WarnOfBadDrivers=0`。
- **GOG GALAXY:通知弹出时右下角出现黑色矩形**,随通知一起消失。通知是 GOG 通知渲染器的透明分层窗口;没有 DWM 合成时 Wine 会把透明区域涂黑。无害。在 GOG 设置里关闭桌面通知即可避免。
+- **Epic 提示 "your account has too many active logins"**,而且在所有设备退出登录、甚至重置密码后依旧如此。账号服务实际返回的是 `too_many_sessions`(18048),限制的是*已发放*的会话数量而非当前持有的数量,所以反复重试只会更糟。旧引擎上启动几次就会触发,因为 Wine 无法保存登录器的设备密钥,详见 `patches/ncrypt-persisted-keys.patch`。先停掉 bottle(`soju epic-kill`),放置几个小时等计数器清零,然后只启动一次。
- **BLZBNTBNA00000005** -> `play.sh` 会自动播种签名 exe;请确认是通过它启动的。
### 残留的 Wine 进程
diff --git a/docs/DIAGNOSIS.md b/docs/DIAGNOSIS.md
index ce31d1de0d7..f9173ee6e3f 100644
--- a/docs/DIAGNOSIS.md
+++ b/docs/DIAGNOSIS.md
@@ -131,6 +131,85 @@ winemac 패치의 `WINE_DOCK_REOPEN_CMD`(보이는 창이 없을 때 독 클릭
- Epic: 트레이 더블클릭 시퀀스 재현(`tools/soju-epic-restore.c`, 위 참조).
- GOG: `RestoreClientMessage` 직접 전송(`tools/soju-gog-restore.c`, 위 참조).
+## Epic 로그인 `too_many_sessions`: ncrypt에 영구 키가 없어서 매번 새 기기가 된다 (2026-08-31)
+
+### 증상
+
+Epic Games Launcher 로그인 화면에서 계속 거부된다.
+
+```
+Sorry, your account has too many active logins.
+Please log out of one of the places you are using your account and try again.
+```
+
+화면 문구는 "다른 곳에서 로그아웃하라"지만, 서버가 실제로 돌려주는 것은 다른 이야기다.
+
+```
+code=400 errorcode=errors.com.epicgames.account.oauth.too_many_sessions
+numericErrorCode=18048
+"Sorry too many sessions have been issued for your account. Please try again later"
+```
+
+`issued`(발급됨)이지 `active`(사용 중)가 아니다. 보유 중인 세션 수 제한이 아니라 일정 시간 안에
+발급된 토큰 수에 대한 레이트 리밋이다. 그래서 모든 기기에서 로그아웃해도, 비밀번호를 재설정해
+기존 세션을 전부 무효화해도 풀리지 않는다. 오히려 재시도할 때마다 카운터가 더 찬다.
+
+### 근본 원인
+
+런처 로그 17개를 확인하니 **매 실행마다** 같은 줄이 먼저 나온다.
+
+```
+LogDPoP: Error: Failed to create persistent DPoP key (Status: 0x80090029)
+LogDPoP: Warning: Cannot build DPoP proof: no public JWK available
+LogOnlineIdentity: Warning: OSS: DPoP enabled but proof build failed - sending request without DPoP header
+```
+
+DPoP(RFC 9449)는 발급한 토큰을 그 기기의 서명 키에 묶는 방식이다. Epic은 이 키로 "같은 기기가
+맞다"를 확인하고, 맞으면 저장된 세션을 갱신해서 재사용한다. 키를 못 만들면 매 실행이 처음 보는
+기기가 되므로 갱신 대신 **새 세션 발급**이 일어난다. 열 번 실행하면 세션도 그만큼 새로 발급된다.
+
+0x80090029는 `NTE_NOT_SUPPORTED`다. 엔진에서 직접 확인한 결과:
+
+```
+NCryptOpenStorageProvider = 0x00000000
+NCryptOpenKey (기존 키 열기) = 0x80090029
+NCryptCreatePersistedKey ES256 = 0x80090029
+```
+
+wine의 `dlls/ncrypt/main.c`를 보면 이유가 그대로 적혀 있다. `NCryptCreatePersistedKey`는 키 이름을
+받으면 `FIXME("Persistent keys are not supported")`를 찍고 무시하며, `NCryptOpenKey`는 통째로
+스텁이다. 게다가 이 버전은 RSA만 처리해서 DPoP가 쓰는 ECDSA P-256은 아예 거부한다. 즉 wine에서
+CNG 키는 프로세스와 함께 사라지고, 같은 이름으로 다시 열 방법이 없다.
+
+### 해결책 (`patches/ncrypt-persisted-keys.patch`)
+
+이름이 붙은 키를 Windows가 쓰는 위치(`%APPDATA%\Microsoft\Crypto\Keys`)에 저장하고 다시 읽는다.
+
+- `NCryptCreatePersistedKey`: 이름을 기억하고, ECDSA P-256/P-384를 RSA와 함께 처리한다
+- `NCryptFinalizeKey`: 키가 확정된 뒤 개인키 blob을 파일로 내보낸다 (EC 키는 곡선이 길이를 정하므로
+ `BCryptSetProperty(BCRYPT_KEY_LENGTH)`를 건너뛴다)
+- `NCryptOpenKey`: 저장된 키를 불러온다. 저장된 적이 없으면 Windows와 같이 `NTE_BAD_KEYSET`을
+ 돌려줘서, 호출자가 포기하지 않고 새로 만들도록 한다
+- `NCryptDeleteKey`: 저장 파일도 함께 지운다
+
+### 검증
+
+프로브를 두 번 실행:
+
+```
+1회차: NCryptOpenKey = 0x80090016 (아직 없음) -> Create/Finalize 성공 -> 공개키 72바이트, 서명 64바이트
+2회차: NCryptOpenKey = 0x00000000 (저장된 키 로드) -> 공개키 바이트가 1회차와 동일
+```
+
+2회차의 공개키가 1회차와 같다는 것이 핵심이다. 새로 만든 것이 아니라 디스크에서 같은 키를 불러왔다는
+뜻이고, DPoP가 요구하는 성질이 바로 이것이다.
+
+회귀는 wine의 ncrypt 적합성 테스트로 확인했다. 원본과 패치본 모두 436개 실행, 176개 todo,
+**0 failures**로 동일하다. 배틀넷도 패치본 엔진에서 정상 부팅한다(BREAKPOINT 0, ncrypt 오류 0).
+
+아직 Epic 로그인으로 끝까지 확인하지는 못했다. 이미 걸린 레이트 리밋이 풀려야 시도할 수 있고,
+재시도 자체가 리밋을 다시 채우기 때문이다.
+
## 벽 2: Battle.net Agent caller 서명 검증 실패 (해결됨)
### 증상
diff --git a/patches/ncrypt-persisted-keys.patch b/patches/ncrypt-persisted-keys.patch
new file mode 100644
index 00000000000..b447d0a6c72
--- /dev/null
+++ b/patches/ncrypt-persisted-keys.patch
@@ -0,0 +1,400 @@
+Store CNG keys created with a name so they survive the process.
+
+Wine's ncrypt keeps a key only for the lifetime of the process that made it:
+NCryptCreatePersistedKey ignores the name it is given and NCryptOpenKey is a
+stub returning NTE_NOT_SUPPORTED, so a program that asks the key store for the
+same key twice gets a different key the second time.
+
+The Epic Games Launcher creates a persistent EC key and signs a DPoP proof with
+it (RFC 9449), which is how the account service recognises the machine a token
+was issued to. With the key gone on every start the launcher logs
+
+ LogDPoP: Error: Failed to create persistent DPoP key (Status: 0x80090029)
+ LogDPoP: Warning: Cannot build DPoP proof: no public JWK available
+
+and falls back to sending the request unsigned, so the service treats each start
+as a new device and issues a new session instead of refreshing the stored one.
+After a handful of launches the account hits the issuance limit and every login
+fails with
+
+ errors.com.epicgames.account.oauth.too_many_sessions (18048)
+ "Sorry too many sessions have been issued for your account."
+
+which no amount of logging out or resetting the password clears, because the
+limit counts sessions issued rather than sessions held.
+
+Named keys are now written to %APPDATA%\Microsoft\Crypto\Keys, where Windows
+keeps them, once the key is finalized, and read back by NCryptOpenKey; opening a
+name that was never stored returns NTE_BAD_KEYSET so callers create one instead
+of giving up. ECDSA P-256 and P-384 are handled alongside RSA, since a key
+store that cannot hold the curve DPoP uses would not help here.
+
+--- a/dlls/ncrypt/ncrypt_internal.h
++++ b/dlls/ncrypt/ncrypt_internal.h
+@@ -26,12 +26,15 @@
+ RSA,
+ DSA,
+ ECDSA,
++ ECDSA_P256,
++ ECDSA_P384,
+ };
+
+ struct key
+ {
+ enum algid algid;
+ BCRYPT_KEY_HANDLE bcrypt_key;
++ WCHAR *name;
+ };
+
+ struct storage_provider
+--- a/dlls/ncrypt/main.c
++++ b/dlls/ncrypt/main.c
+@@ -126,6 +126,162 @@
+ return ERROR_SUCCESS;
+ }
+
++/* Persistent key storage.
++ *
++ * Windows keeps a user's CNG keys under %APPDATA%\Microsoft\Crypto\Keys, so a
++ * named key created by one run of a program is still there for the next one.
++ * Callers that bind a token to a device key (DPoP, for instance) treat the key
++ * as the identity of the machine and issue a fresh login whenever it changes,
++ * so the key has to outlive the process. */
++
++#define KEY_STORE_MAGIC 0x314b4a53
++
++struct key_store_header
++{
++ DWORD magic;
++ DWORD algid;
++ DWORD blob_len;
++};
++
++static const WCHAR *blob_type_for_algid(enum algid algid)
++{
++ switch (algid)
++ {
++ case RSA: return BCRYPT_RSAFULLPRIVATE_BLOB;
++ case ECDSA_P256:
++ case ECDSA_P384: return BCRYPT_ECCPRIVATE_BLOB;
++ default: return NULL;
++ }
++}
++
++static BCRYPT_ALG_HANDLE alg_handle_for_algid(enum algid algid)
++{
++ switch (algid)
++ {
++ case RSA: return BCRYPT_RSA_ALG_HANDLE;
++ case ECDSA_P256: return BCRYPT_ECDSA_P256_ALG_HANDLE;
++ case ECDSA_P384: return BCRYPT_ECDSA_P384_ALG_HANDLE;
++ default: return NULL;
++ }
++}
++
++/* Build %APPDATA%\Microsoft\Crypto\Keys\<name>.key, creating the directories.
++ * Characters that cannot appear in a file name are folded to '_'; a caller
++ * that picks two names differing only in those is left sharing one file. */
++static WCHAR *key_store_path(const WCHAR *name)
++{
++ static const WCHAR keysW[] = L"\\Microsoft\\Crypto\\Keys";
++ static const WCHAR extW[] = L".key";
++ WCHAR appdata[MAX_PATH], *path, *p;
++ DWORD len;
++ size_t i;
++
++ if (!name || !*name) return NULL;
++ if (!(len = GetEnvironmentVariableW(L"APPDATA", appdata, MAX_PATH)) || len >= MAX_PATH) return NULL;
++
++ len = lstrlenW(appdata) + ARRAY_SIZE(keysW) + lstrlenW(name) + ARRAY_SIZE(extW) + 1;
++ if (!(path = malloc(len * sizeof(WCHAR)))) return NULL;
++
++ lstrcpyW(path, appdata);
++ lstrcatW(path, keysW);
++
++ /* create the directories one component at a time */
++ for (p = path + lstrlenW(appdata) + 1; *p; p++)
++ {
++ if (*p != '\\') continue;
++ *p = 0;
++ CreateDirectoryW(path, NULL);
++ *p = '\\';
++ }
++ CreateDirectoryW(path, NULL);
++
++ lstrcatW(path, L"\\");
++ i = lstrlenW(path);
++ for (; *name; name++, i++)
++ {
++ WCHAR c = *name;
++ if (c < ' ' || c == '\\' || c == '/' || c == ':' || c == '*' ||
++ c == '?' || c == '"' || c == '<' || c == '>' || c == '|') c = '_';
++ path[i] = c;
++ }
++ path[i] = 0;
++ lstrcatW(path, extW);
++ return path;
++}
++
++static SECURITY_STATUS write_key_store(const WCHAR *name, enum algid algid, BCRYPT_KEY_HANDLE bcrypt_key)
++{
++ struct key_store_header header;
++ const WCHAR *blob_type;
++ SECURITY_STATUS ret = NTE_INTERNAL_ERROR;
++ BYTE *blob = NULL;
++ WCHAR *path;
++ DWORD blob_len = 0, written;
++ NTSTATUS status;
++ HANDLE file;
++
++ if (!(blob_type = blob_type_for_algid(algid))) return NTE_NOT_SUPPORTED;
++ if (!(path = key_store_path(name))) return NTE_INTERNAL_ERROR;
++
++ status = BCryptExportKey(bcrypt_key, NULL, blob_type, NULL, 0, &blob_len, 0);
++ if (status != STATUS_SUCCESS) goto done;
++ if (!(blob = malloc(blob_len))) { ret = NTE_NO_MEMORY; goto done; }
++ status = BCryptExportKey(bcrypt_key, NULL, blob_type, blob, blob_len, &blob_len, 0);
++ if (status != STATUS_SUCCESS) goto done;
++
++ file = CreateFileW(path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
++ if (file == INVALID_HANDLE_VALUE) goto done;
++
++ header.magic = KEY_STORE_MAGIC;
++ header.algid = algid;
++ header.blob_len = blob_len;
++ if (WriteFile(file, &header, sizeof(header), &written, NULL) && written == sizeof(header) &&
++ WriteFile(file, blob, blob_len, &written, NULL) && written == blob_len)
++ ret = ERROR_SUCCESS;
++ CloseHandle(file);
++ if (ret != ERROR_SUCCESS) DeleteFileW(path);
++
++done:
++ free(blob);
++ free(path);
++ return ret;
++}
++
++static SECURITY_STATUS read_key_store(const WCHAR *name, enum algid *algid, BCRYPT_KEY_HANDLE *bcrypt_key)
++{
++ struct key_store_header header;
++ SECURITY_STATUS ret = NTE_BAD_KEYSET;
++ BYTE *blob = NULL;
++ WCHAR *path;
++ DWORD read;
++ HANDLE file;
++
++ if (!(path = key_store_path(name))) return NTE_BAD_KEYSET;
++
++ file = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
++ free(path);
++ if (file == INVALID_HANDLE_VALUE) return NTE_BAD_KEYSET;
++
++ if (!ReadFile(file, &header, sizeof(header), &read, NULL) || read != sizeof(header) ||
++ header.magic != KEY_STORE_MAGIC || !header.blob_len || header.blob_len > 0x10000)
++ goto done;
++ if (!blob_type_for_algid(header.algid) || !alg_handle_for_algid(header.algid)) goto done;
++ if (!(blob = malloc(header.blob_len))) { ret = NTE_NO_MEMORY; goto done; }
++ if (!ReadFile(file, blob, header.blob_len, &read, NULL) || read != header.blob_len) goto done;
++
++ if (BCryptImportKeyPair(alg_handle_for_algid(header.algid), NULL, blob_type_for_algid(header.algid),
++ bcrypt_key, blob, header.blob_len, 0) != STATUS_SUCCESS)
++ goto done;
++
++ *algid = header.algid;
++ ret = ERROR_SUCCESS;
++
++done:
++ free(blob);
++ CloseHandle(file);
++ return ret;
++}
++
+ static struct object *create_key_object(enum algid algid, NCRYPT_PROV_HANDLE provider)
+ {
+ NCRYPT_SUPPORTED_LENGTHS supported_lengths = {512, 16384, 8, 1024};
+@@ -150,6 +306,26 @@
+ set_object_property(object, BCRYPT_SIGNATURE_LENGTH, (BYTE *)&dw_value, sizeof(dw_value));
+ break;
+
++ case ECDSA_P256:
++ case ECDSA_P384:
++ {
++ const WCHAR *alg = (algid == ECDSA_P256) ? BCRYPT_ECDSA_P256_ALGORITHM : BCRYPT_ECDSA_P384_ALGORITHM;
++ DWORD bitlen = (algid == ECDSA_P256) ? 256 : 384;
++ NCRYPT_SUPPORTED_LENGTHS ec_lengths = {bitlen, bitlen, 0, bitlen};
++
++ if (!(object = allocate_object(KEY))) return NULL;
++
++ object->key.algid = algid;
++ set_object_property(object, NCRYPT_ALGORITHM_PROPERTY, (BYTE *)alg, (lstrlenW(alg) + 1) * sizeof(WCHAR));
++ set_object_property(object, NCRYPT_ALGORITHM_GROUP_PROPERTY, (BYTE *)L"ECDSA", sizeof(L"ECDSA"));
++ set_object_property(object, NCRYPT_LENGTHS_PROPERTY, (BYTE *)&ec_lengths, sizeof(ec_lengths));
++ dw_value = bitlen / 8;
++ set_object_property(object, NCRYPT_BLOCK_LENGTH_PROPERTY, (BYTE *)&dw_value, sizeof(dw_value));
++ dw_value = bitlen / 4;
++ set_object_property(object, BCRYPT_SIGNATURE_LENGTH, (BYTE *)&dw_value, sizeof(dw_value));
++ break;
++ }
++
+ default:
+ ERR("Invalid algid %#x\n", algid);
+ return NULL;
+@@ -175,7 +351,6 @@
+
+ if (!provider) return NTE_INVALID_HANDLE;
+ if (!algid) return HRESULT_FROM_WIN32(RPC_X_NULL_REF_POINTER);
+- if (name) FIXME("Persistent keys are not supported\n");
+
+ if (!lstrcmpiW(algid, BCRYPT_RSA_ALGORITHM))
+ {
+@@ -199,12 +374,39 @@
+ set_object_property(object, NCRYPT_LENGTH_PROPERTY, (BYTE *)&default_bitlen, sizeof(default_bitlen));
+ set_object_property(object, BCRYPT_PUBLIC_KEY_LENGTH, (BYTE *)&default_bitlen, sizeof(default_bitlen));
+ }
++ else if (!lstrcmpiW(algid, BCRYPT_ECDSA_P256_ALGORITHM) || !lstrcmpiW(algid, BCRYPT_ECDSA_P384_ALGORITHM))
++ {
++ enum algid id = !lstrcmpiW(algid, BCRYPT_ECDSA_P256_ALGORITHM) ? ECDSA_P256 : ECDSA_P384;
++ DWORD bitlen = (id == ECDSA_P256) ? 256 : 384;
++ NTSTATUS status;
++
++ if (!(object = create_key_object(id, provider))) return NTE_NO_MEMORY;
++
++ status = BCryptGenerateKeyPair(alg_handle_for_algid(id), &object->key.bcrypt_key, bitlen, 0);
++ if (status != STATUS_SUCCESS)
++ {
++ ERR("Error generating key pair %#lx\n", status);
++ free(object);
++ return map_ntstatus(status);
++ }
++
++ set_object_property(object, NCRYPT_LENGTH_PROPERTY, (BYTE *)&bitlen, sizeof(bitlen));
++ set_object_property(object, BCRYPT_PUBLIC_KEY_LENGTH, (BYTE *)&bitlen, sizeof(bitlen));
++ }
+ else
+ {
+ FIXME("Algorithm not handled %s\n", wine_dbgstr_w(algid));
+ return NTE_NOT_SUPPORTED;
+ }
+
++ /* A named key is written out once it is finalized, not here: the key
++ * material is not generated yet. */
++ if (name && !(object->key.name = wcsdup(name)))
++ {
++ NCryptFreeObject((NCRYPT_HANDLE)object);
++ return NTE_NO_MEMORY;
++ }
++
+ *key = (NCRYPT_KEY_HANDLE)object;
+ return ERROR_SUCCESS;
+ }
+@@ -219,8 +421,19 @@
+
+ SECURITY_STATUS WINAPI NCryptDeleteKey(NCRYPT_KEY_HANDLE key, DWORD flags)
+ {
+- FIXME("(%#Ix, %#lx): stub\n", key, flags);
+- return NTE_NOT_SUPPORTED;
++ struct object *object = (struct object *)key;
++ WCHAR *path;
++
++ TRACE("(%#Ix, %#lx)\n", key, flags);
++
++ if (!object || object->type != KEY) return NTE_INVALID_HANDLE;
++
++ if (object->key.name && (path = key_store_path(object->key.name)))
++ {
++ DeleteFileW(path);
++ free(path);
++ }
++ return NCryptFreeObject((NCRYPT_HANDLE)key);
+ }
+
+ SECURITY_STATUS WINAPI NCryptEncrypt(NCRYPT_KEY_HANDLE key, BYTE *input, DWORD insize, void *padding,
+@@ -277,11 +490,16 @@
+
+ if (!(prop = get_object_property(object, NCRYPT_LENGTH_PROPERTY))) return NTE_INVALID_HANDLE;
+ key_length = *(DWORD *)prop->value;
+- status = BCryptSetProperty(object->key.bcrypt_key, BCRYPT_KEY_LENGTH, (UCHAR *)&key_length, sizeof(key_length), 0);
+- if (status != STATUS_SUCCESS)
++
++ /* the length of an EC key is fixed by its curve, and setting it fails */
++ if (object->key.algid != ECDSA_P256 && object->key.algid != ECDSA_P384)
+ {
+- ERR("Error setting key length property\n");
+- return map_ntstatus(status);
++ status = BCryptSetProperty(object->key.bcrypt_key, BCRYPT_KEY_LENGTH, (UCHAR *)&key_length, sizeof(key_length), 0);
++ if (status != STATUS_SUCCESS)
++ {
++ ERR("Error setting key length property\n");
++ return map_ntstatus(status);
++ }
+ }
+
+ status = BCryptFinalizeKeyPair(object->key.bcrypt_key, 0);
+@@ -291,6 +509,13 @@
+ return map_ntstatus(status);
+ }
+
++ if (object->key.name)
++ {
++ SECURITY_STATUS ret = write_key_store(object->key.name, object->key.algid, object->key.bcrypt_key);
++ if (ret != ERROR_SUCCESS)
++ WARN("could not store key %s, it will not survive this process\n", wine_dbgstr_w(object->key.name));
++ }
++
+ return ERROR_SUCCESS;
+ }
+
+@@ -302,6 +527,8 @@
+
+ static SECURITY_STATUS free_key_object(struct key *key)
+ {
++ free(key->name);
++ key->name = NULL;
+ return map_ntstatus( BCryptDestroyKey(key->bcrypt_key) );
+ }
+
+@@ -512,8 +739,42 @@
+ SECURITY_STATUS WINAPI NCryptOpenKey(NCRYPT_PROV_HANDLE provider, NCRYPT_KEY_HANDLE *key,
+ const WCHAR *name, DWORD keyspec, DWORD flags)
+ {
+- FIXME("(%#Ix, %p, %s, %#lx, %#lx): stub\n", provider, key, wine_dbgstr_w(name), keyspec, flags);
+- return NTE_NOT_SUPPORTED;
++ BCRYPT_KEY_HANDLE bcrypt_key = NULL;
++ struct object *object;
++ SECURITY_STATUS ret;
++ enum algid algid;
++ DWORD bitlen;
++
++ TRACE("(%#Ix, %p, %s, %#lx, %#lx)\n", provider, key, wine_dbgstr_w(name), keyspec, flags);
++
++ if (!provider) return NTE_INVALID_HANDLE;
++ if (!key || !name) return NTE_INVALID_PARAMETER;
++
++ if ((ret = read_key_store(name, &algid, &bcrypt_key))) return ret;
++
++ if (!(object = create_key_object(algid, provider)))
++ {
++ BCryptDestroyKey(bcrypt_key);
++ return NTE_NO_MEMORY;
++ }
++ object->key.bcrypt_key = bcrypt_key;
++ if (!(object->key.name = wcsdup(name)))
++ {
++ NCryptFreeObject((NCRYPT_HANDLE)object);
++ return NTE_NO_MEMORY;
++ }
++
++ switch (algid)
++ {
++ case ECDSA_P256: bitlen = 256; break;
++ case ECDSA_P384: bitlen = 384; break;
++ default: bitlen = 1024; break;
++ }
++ set_object_property(object, NCRYPT_LENGTH_PROPERTY, (BYTE *)&bitlen, sizeof(bitlen));
++ set_object_property(object, BCRYPT_PUBLIC_KEY_LENGTH, (BYTE *)&bitlen, sizeof(bitlen));
++
++ *key = (NCRYPT_KEY_HANDLE)object;
++ return ERROR_SUCCESS;
+ }
+
+ SECURITY_STATUS WINAPI NCryptOpenStorageProvider(NCRYPT_PROV_HANDLE *provider, const WCHAR *name, DWORD flags)
diff --git a/scripts/build-engine.sh b/scripts/build-engine.sh
index 39981451ad8..17daa6e276c 100755
--- a/scripts/build-engine.sh
+++ b/scripts/build-engine.sh
@@ -39,6 +39,10 @@ if ! grep -q "soju_append_chromium_flags" "$WINE/dlls/kernelbase/process.c"; the
echo "==> Applying patches/chromium-flags-append.patch (SOJU_CHROMIUM_FLAGS hook for Qt launchers)"
patch -p1 -d "$WINE" < "$SCRIPT_DIR/../patches/chromium-flags-append.patch"
fi
+if ! grep -q "KEY_STORE_MAGIC" "$WINE/dlls/ncrypt/main.c"; then
+ echo "==> Applying patches/ncrypt-persisted-keys.patch (named CNG keys survive the process)"
+ patch -p1 -d "$WINE" < "$SCRIPT_DIR/../patches/ncrypt-persisted-keys.patch"
+fi
echo "==> Building x86_64 freetype (Rosetta)"
[ -f "$WORK/ft.tar.gz" ] || curl -fL "$FT_URL" -o "$WORK/ft.tar.gz"