#pragma once #include #include #include #include #include #pragma comment(lib,"advapi32.lib") namespace licensing::saved_login { inline constexpr const wchar_t* target=L"amnesia/client/remembered-login/v1"; struct credentials { std::string api,username,password; ~credentials(){if(!password.empty())SecureZeroMemory(password.data(),password.size());} credentials()=default;credentials(const credentials&)=delete;credentials& operator=(const credentials&)=delete; }; inline bool forget(const wchar_t* key=target) { return CredDeleteW(key,CRED_TYPE_GENERIC,0) || GetLastError()==ERROR_NOT_FOUND; } inline bool save(const std::string& api,const std::string& username,const std::string& password,const wchar_t* key=target) { if(api.empty() || api.size()>512 || username.size()<3 || username.size()>24 || password.empty() || password.size()>512)return false; const uint32_t lengths[]{uint32_t(api.size()),uint32_t(username.size()),uint32_t(password.size())}; std::string blob("AML1",4);blob.append(reinterpret_cast(lengths),sizeof(lengths));blob+=api;blob+=username;blob+=password; struct wipe {std::string& value;~wipe(){if(!value.empty())SecureZeroMemory(value.data(),value.size());}} clear{blob}; CREDENTIALW credential{};credential.Type=CRED_TYPE_GENERIC;credential.TargetName=const_cast(key); credential.Persist=CRED_PERSIST_LOCAL_MACHINE;credential.CredentialBlobSize=DWORD(blob.size()); credential.CredentialBlob=reinterpret_cast(blob.data()); std::wstring name(username.begin(),username.end());credential.UserName=name.data(); const bool okay=CredWriteW(&credential,0)!=FALSE; SecureZeroMemory(blob.data(),blob.size());return okay; } inline bool load(credentials& out,const wchar_t* key=target) { PCREDENTIALW credential=nullptr;if(!CredReadW(key,CRED_TYPE_GENERIC,0,&credential))return false; struct cleanup {PCREDENTIALW value;~cleanup(){if(value->CredentialBlob && value->CredentialBlobSize)SecureZeroMemory(value->CredentialBlob,value->CredentialBlobSize);CredFree(value);}} release{credential}; if(!credential->CredentialBlob || credential->CredentialBlobSize<16 || credential->CredentialBlobSize>CRED_MAX_CREDENTIAL_BLOB_SIZE)return false; const auto* blob=reinterpret_cast(credential->CredentialBlob);uint32_t lengths[3]{}; if(memcmp(blob,"AML1",4))return false;memcpy(lengths,blob+4,sizeof(lengths)); if(!lengths[0] || lengths[0]>512 || lengths[1]<3 || lengths[1]>24 || !lengths[2] || lengths[2]>512 || uint64_t(16)+lengths[0]+lengths[1]+lengths[2]!=credential->CredentialBlobSize)return false; out.api.assign(blob+16,lengths[0]);out.username.assign(blob+16+lengths[0],lengths[1]); if(!out.password.empty())SecureZeroMemory(out.password.data(),out.password.size()); out.password.assign(blob+16+lengths[0]+lengths[1],lengths[2]);return true; } }