rpcrt4: Add support for session cookies.
[wine/wine-gecko.git] / dlls / advapi32 / cred.c
blobe17dfb60655195e6b1b3ebb68ee8bc78666abf1b
1 /*
2 * Credential Management APIs
4 * Copyright 2007 Robert Shearman for CodeWeavers
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include <stdarg.h>
22 #include <time.h>
23 #include <limits.h>
25 #ifdef __APPLE__
26 # include <Security/SecKeychain.h>
27 # include <Security/SecKeychainItem.h>
28 # include <Security/SecKeychainSearch.h>
29 #endif
31 #include "windef.h"
32 #include "winbase.h"
33 #include "winreg.h"
34 #include "wincred.h"
35 #include "winternl.h"
37 #include "crypt.h"
39 #include "wine/unicode.h"
40 #include "wine/debug.h"
42 WINE_DEFAULT_DEBUG_CHANNEL(cred);
44 /* the size of the ARC4 key used to encrypt the password data */
45 #define KEY_SIZE 8
47 static const WCHAR wszCredentialManagerKey[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\',
48 'C','r','e','d','e','n','t','i','a','l',' ','M','a','n','a','g','e','r',0};
49 static const WCHAR wszEncryptionKeyValue[] = {'E','n','c','r','y','p','t','i','o','n','K','e','y',0};
51 static const WCHAR wszFlagsValue[] = {'F','l','a','g','s',0};
52 static const WCHAR wszTypeValue[] = {'T','y','p','e',0};
53 static const WCHAR wszCommentValue[] = {'C','o','m','m','e','n','t',0};
54 static const WCHAR wszLastWrittenValue[] = {'L','a','s','t','W','r','i','t','t','e','n',0};
55 static const WCHAR wszPersistValue[] = {'P','e','r','s','i','s','t',0};
56 static const WCHAR wszTargetAliasValue[] = {'T','a','r','g','e','t','A','l','i','a','s',0};
57 static const WCHAR wszUserNameValue[] = {'U','s','e','r','N','a','m','e',0};
58 static const WCHAR wszPasswordValue[] = {'P','a','s','s','w','o','r','d',0};
60 static DWORD read_credential_blob(HKEY hkey, const BYTE key_data[KEY_SIZE],
61 LPBYTE credential_blob,
62 DWORD *credential_blob_size)
64 DWORD ret;
65 DWORD type;
67 *credential_blob_size = 0;
68 ret = RegQueryValueExW(hkey, wszPasswordValue, 0, &type, NULL, credential_blob_size);
69 if (ret != ERROR_SUCCESS)
70 return ret;
71 else if (type != REG_BINARY)
72 return ERROR_REGISTRY_CORRUPT;
73 if (credential_blob)
75 struct ustring data;
76 struct ustring key;
78 ret = RegQueryValueExW(hkey, wszPasswordValue, 0, &type, credential_blob,
79 credential_blob_size);
80 if (ret != ERROR_SUCCESS)
81 return ret;
82 else if (type != REG_BINARY)
83 return ERROR_REGISTRY_CORRUPT;
85 key.Length = key.MaximumLength = KEY_SIZE;
86 key.Buffer = (unsigned char *)key_data;
88 data.Length = data.MaximumLength = *credential_blob_size;
89 data.Buffer = credential_blob;
90 SystemFunction032(&data, &key);
92 return ERROR_SUCCESS;
95 static DWORD registry_read_credential(HKEY hkey, PCREDENTIALW credential,
96 const BYTE key_data[KEY_SIZE],
97 char *buffer, DWORD *len)
99 DWORD type;
100 DWORD ret;
101 DWORD count;
103 ret = RegQueryValueExW(hkey, NULL, 0, &type, NULL, &count);
104 if (ret != ERROR_SUCCESS)
105 return ret;
106 else if (type != REG_SZ)
107 return ERROR_REGISTRY_CORRUPT;
108 *len += count;
109 if (credential)
111 credential->TargetName = (LPWSTR)buffer;
112 ret = RegQueryValueExW(hkey, NULL, 0, &type, (LPVOID)credential->TargetName,
113 &count);
114 if (ret != ERROR_SUCCESS || type != REG_SZ) return ret;
115 buffer += count;
118 ret = RegQueryValueExW(hkey, wszCommentValue, 0, &type, NULL, &count);
119 if (ret != ERROR_FILE_NOT_FOUND && ret != ERROR_SUCCESS)
120 return ret;
121 else if (type != REG_SZ)
122 return ERROR_REGISTRY_CORRUPT;
123 *len += count;
124 if (credential)
126 credential->Comment = (LPWSTR)buffer;
127 ret = RegQueryValueExW(hkey, wszCommentValue, 0, &type, (LPVOID)credential->Comment,
128 &count);
129 if (ret == ERROR_FILE_NOT_FOUND)
130 credential->Comment = NULL;
131 else if (ret != ERROR_SUCCESS)
132 return ret;
133 else if (type != REG_SZ)
134 return ERROR_REGISTRY_CORRUPT;
135 else
136 buffer += count;
139 ret = RegQueryValueExW(hkey, wszTargetAliasValue, 0, &type, NULL, &count);
140 if (ret != ERROR_FILE_NOT_FOUND && ret != ERROR_SUCCESS)
141 return ret;
142 else if (type != REG_SZ)
143 return ERROR_REGISTRY_CORRUPT;
144 *len += count;
145 if (credential)
147 credential->TargetAlias = (LPWSTR)buffer;
148 ret = RegQueryValueExW(hkey, wszTargetAliasValue, 0, &type, (LPVOID)credential->TargetAlias,
149 &count);
150 if (ret == ERROR_FILE_NOT_FOUND)
151 credential->TargetAlias = NULL;
152 else if (ret != ERROR_SUCCESS)
153 return ret;
154 else if (type != REG_SZ)
155 return ERROR_REGISTRY_CORRUPT;
156 else
157 buffer += count;
160 ret = RegQueryValueExW(hkey, wszUserNameValue, 0, &type, NULL, &count);
161 if (ret != ERROR_FILE_NOT_FOUND && ret != ERROR_SUCCESS)
162 return ret;
163 else if (type != REG_SZ)
164 return ERROR_REGISTRY_CORRUPT;
165 *len += count;
166 if (credential)
168 credential->UserName = (LPWSTR)buffer;
169 ret = RegQueryValueExW(hkey, wszUserNameValue, 0, &type, (LPVOID)credential->UserName,
170 &count);
171 if (ret == ERROR_FILE_NOT_FOUND)
172 credential->UserName = NULL;
173 else if (ret != ERROR_SUCCESS)
174 return ret;
175 else if (type != REG_SZ)
176 return ERROR_REGISTRY_CORRUPT;
177 else
178 buffer += count;
181 ret = read_credential_blob(hkey, key_data, NULL, &count);
182 if (ret != ERROR_FILE_NOT_FOUND && ret != ERROR_SUCCESS)
183 return ret;
184 *len += count;
185 if (credential)
187 credential->CredentialBlob = (LPBYTE)buffer;
188 ret = read_credential_blob(hkey, key_data, credential->CredentialBlob, &count);
189 if (ret == ERROR_FILE_NOT_FOUND)
190 credential->CredentialBlob = NULL;
191 else if (ret != ERROR_SUCCESS)
192 return ret;
193 credential->CredentialBlobSize = count;
196 /* FIXME: Attributes */
197 if (credential)
199 credential->AttributeCount = 0;
200 credential->Attributes = NULL;
203 if (!credential) return ERROR_SUCCESS;
205 count = sizeof(credential->Flags);
206 ret = RegQueryValueExW(hkey, wszFlagsValue, NULL, &type, (LPVOID)&credential->Flags,
207 &count);
208 if (ret != ERROR_SUCCESS)
209 return ret;
210 else if (type != REG_DWORD)
211 return ERROR_REGISTRY_CORRUPT;
212 count = sizeof(credential->Type);
213 ret = RegQueryValueExW(hkey, wszTypeValue, NULL, &type, (LPVOID)&credential->Type,
214 &count);
215 if (ret != ERROR_SUCCESS)
216 return ret;
217 else if (type != REG_DWORD)
218 return ERROR_REGISTRY_CORRUPT;
220 count = sizeof(credential->LastWritten);
221 ret = RegQueryValueExW(hkey, wszLastWrittenValue, NULL, &type, (LPVOID)&credential->LastWritten,
222 &count);
223 if (ret != ERROR_SUCCESS)
224 return ret;
225 else if (type != REG_BINARY)
226 return ERROR_REGISTRY_CORRUPT;
227 count = sizeof(credential->Persist);
228 ret = RegQueryValueExW(hkey, wszPersistValue, NULL, &type, (LPVOID)&credential->Persist,
229 &count);
230 if (ret == ERROR_SUCCESS && type != REG_DWORD)
231 return ERROR_REGISTRY_CORRUPT;
232 return ret;
235 #ifdef __APPLE__
236 static DWORD mac_read_credential_from_item(SecKeychainItemRef item, BOOL require_password,
237 PCREDENTIALW credential, char *buffer,
238 DWORD *len)
240 OSStatus status;
241 UInt32 i;
242 UInt32 cred_blob_len;
243 void *cred_blob;
244 LPWSTR domain = NULL;
245 LPWSTR user = NULL;
246 BOOL user_name_present = FALSE;
247 SecKeychainAttributeInfo info;
248 SecKeychainAttributeList *attr_list;
249 UInt32 info_tags[] = { kSecServerItemAttr, kSecSecurityDomainItemAttr, kSecAccountItemAttr,
250 kSecCommentItemAttr, kSecCreationDateItemAttr };
251 info.count = sizeof(info_tags)/sizeof(info_tags[0]);
252 info.tag = info_tags;
253 info.format = NULL;
254 status = SecKeychainItemCopyAttributesAndData(item, &info, NULL, &attr_list, &cred_blob_len, &cred_blob);
255 if (status == errSecAuthFailed && !require_password)
257 cred_blob_len = 0;
258 cred_blob = NULL;
259 status = SecKeychainItemCopyAttributesAndData(item, &info, NULL, &attr_list, &cred_blob_len, NULL);
261 if (status != noErr)
263 WARN("SecKeychainItemCopyAttributesAndData returned status %ld\n", status);
264 return ERROR_NOT_FOUND;
267 for (i = 0; i < attr_list->count; i++)
268 if (attr_list->attr[i].tag == kSecAccountItemAttr && attr_list->attr[i].data)
270 user_name_present = TRUE;
271 break;
273 if (!user_name_present)
275 WARN("no kSecAccountItemAttr for item\n");
276 SecKeychainItemFreeAttributesAndData(attr_list, cred_blob);
277 return ERROR_NOT_FOUND;
280 if (buffer)
282 credential->Flags = 0;
283 credential->Type = CRED_TYPE_DOMAIN_PASSWORD;
284 credential->TargetName = NULL;
285 credential->Comment = NULL;
286 memset(&credential->LastWritten, 0, sizeof(credential->LastWritten));
287 credential->CredentialBlobSize = 0;
288 credential->CredentialBlob = NULL;
289 credential->Persist = CRED_PERSIST_LOCAL_MACHINE;
290 credential->AttributeCount = 0;
291 credential->Attributes = NULL;
292 credential->TargetAlias = NULL;
293 credential->UserName = NULL;
295 for (i = 0; i < attr_list->count; i++)
297 switch (attr_list->attr[i].tag)
299 case kSecServerItemAttr:
300 TRACE("kSecServerItemAttr: %.*s\n", (int)attr_list->attr[i].length,
301 (char *)attr_list->attr[i].data);
302 if (!attr_list->attr[i].data) continue;
303 if (buffer)
305 INT str_len;
306 credential->TargetName = (LPWSTR)buffer;
307 str_len = MultiByteToWideChar(CP_UTF8, 0, attr_list->attr[i].data,
308 attr_list->attr[i].length, (LPWSTR)buffer, 0xffff);
309 credential->TargetName[str_len] = '\0';
310 buffer += (str_len + 1) * sizeof(WCHAR);
311 *len += (str_len + 1) * sizeof(WCHAR);
313 else
315 INT str_len;
316 str_len = MultiByteToWideChar(CP_UTF8, 0, attr_list->attr[i].data,
317 attr_list->attr[i].length, NULL, 0);
318 *len += (str_len + 1) * sizeof(WCHAR);
320 break;
321 case kSecAccountItemAttr:
323 INT str_len;
324 TRACE("kSecAccountItemAttr: %.*s\n", (int)attr_list->attr[i].length,
325 (char *)attr_list->attr[i].data);
326 if (!attr_list->attr[i].data) continue;
327 str_len = MultiByteToWideChar(CP_UTF8, 0, attr_list->attr[i].data,
328 attr_list->attr[i].length, NULL, 0);
329 user = HeapAlloc(GetProcessHeap(), 0, (str_len + 1) * sizeof(WCHAR));
330 MultiByteToWideChar(CP_UTF8, 0, attr_list->attr[i].data,
331 attr_list->attr[i].length, user, str_len);
332 user[str_len] = '\0';
333 break;
335 case kSecCommentItemAttr:
336 TRACE("kSecCommentItemAttr: %.*s\n", (int)attr_list->attr[i].length,
337 (char *)attr_list->attr[i].data);
338 if (!attr_list->attr[i].data) continue;
339 if (buffer)
341 INT str_len;
342 credential->Comment = (LPWSTR)buffer;
343 str_len = MultiByteToWideChar(CP_UTF8, 0, attr_list->attr[i].data,
344 attr_list->attr[i].length, (LPWSTR)buffer, 0xffff);
345 credential->Comment[str_len] = '\0';
346 buffer += (str_len + 1) * sizeof(WCHAR);
347 *len += (str_len + 1) * sizeof(WCHAR);
349 else
351 INT str_len;
352 str_len = MultiByteToWideChar(CP_UTF8, 0, attr_list->attr[i].data,
353 attr_list->attr[i].length, NULL, 0);
354 *len += (str_len + 1) * sizeof(WCHAR);
356 break;
357 case kSecSecurityDomainItemAttr:
359 INT str_len;
360 TRACE("kSecSecurityDomainItemAttr: %.*s\n", (int)attr_list->attr[i].length,
361 (char *)attr_list->attr[i].data);
362 if (!attr_list->attr[i].data) continue;
363 str_len = MultiByteToWideChar(CP_UTF8, 0, attr_list->attr[i].data,
364 attr_list->attr[i].length, NULL, 0);
365 domain = HeapAlloc(GetProcessHeap(), 0, (str_len + 1) * sizeof(WCHAR));
366 MultiByteToWideChar(CP_UTF8, 0, attr_list->attr[i].data,
367 attr_list->attr[i].length, domain, str_len);
368 domain[str_len] = '\0';
369 break;
371 case kSecCreationDateItemAttr:
372 TRACE("kSecCreationDateItemAttr: %.*s\n", (int)attr_list->attr[i].length,
373 (char *)attr_list->attr[i].data);
374 if (buffer)
376 LARGE_INTEGER win_time;
377 struct tm tm;
378 time_t time;
379 memset(&tm, 0, sizeof(tm));
380 strptime(attr_list->attr[i].data, "%Y%m%d%H%M%SZ", &tm);
381 time = mktime(&tm);
382 RtlSecondsSince1970ToTime(time, &win_time);
383 credential->LastWritten.dwLowDateTime = win_time.u.LowPart;
384 credential->LastWritten.dwHighDateTime = win_time.u.HighPart;
386 break;
390 if (user)
392 INT str_len;
393 if (buffer)
394 credential->UserName = (LPWSTR)buffer;
395 if (domain)
397 str_len = strlenW(domain);
398 *len += (str_len + 1) * sizeof(WCHAR);
399 if (buffer)
401 memcpy(credential->UserName, domain, str_len * sizeof(WCHAR));
402 /* FIXME: figure out when to use an '@' */
403 credential->UserName[str_len] = '\\';
404 buffer += (str_len + 1) * sizeof(WCHAR);
407 str_len = strlenW(user);
408 *len += (str_len + 1) * sizeof(WCHAR);
409 if (buffer)
411 memcpy(buffer, user, (str_len + 1) * sizeof(WCHAR));
412 buffer += (str_len + 1) * sizeof(WCHAR);
413 TRACE("UserName = %s\n", debugstr_w(credential->UserName));
416 HeapFree(GetProcessHeap(), 0, user);
417 HeapFree(GetProcessHeap(), 0, domain);
419 if (cred_blob)
421 if (buffer)
423 INT str_len;
424 credential->CredentialBlob = (BYTE *)buffer;
425 str_len = MultiByteToWideChar(CP_UTF8, 0, cred_blob, cred_blob_len,
426 (LPWSTR)buffer, 0xffff);
427 credential->CredentialBlobSize = str_len * sizeof(WCHAR);
428 *len += str_len * sizeof(WCHAR);
430 else
432 INT str_len;
433 str_len = MultiByteToWideChar(CP_UTF8, 0, cred_blob, cred_blob_len,
434 NULL, 0);
435 *len += str_len * sizeof(WCHAR);
438 SecKeychainItemFreeAttributesAndData(attr_list, cred_blob);
439 return ERROR_SUCCESS;
441 #endif
443 static DWORD write_credential_blob(HKEY hkey, LPCWSTR target_name, DWORD type,
444 const BYTE key_data[KEY_SIZE],
445 const BYTE *credential_blob, DWORD credential_blob_size)
447 LPBYTE encrypted_credential_blob;
448 struct ustring data;
449 struct ustring key;
450 DWORD ret;
452 key.Length = key.MaximumLength = KEY_SIZE;
453 key.Buffer = (unsigned char *)key_data;
455 encrypted_credential_blob = HeapAlloc(GetProcessHeap(), 0, credential_blob_size);
456 if (!encrypted_credential_blob) return ERROR_OUTOFMEMORY;
458 memcpy(encrypted_credential_blob, credential_blob, credential_blob_size);
459 data.Length = data.MaximumLength = credential_blob_size;
460 data.Buffer = encrypted_credential_blob;
461 SystemFunction032(&data, &key);
463 ret = RegSetValueExW(hkey, wszPasswordValue, 0, REG_BINARY, encrypted_credential_blob, credential_blob_size);
464 HeapFree(GetProcessHeap(), 0, encrypted_credential_blob);
466 return ret;
469 static DWORD registry_write_credential(HKEY hkey, const CREDENTIALW *credential,
470 const BYTE key_data[KEY_SIZE], BOOL preserve_blob)
472 DWORD ret;
473 FILETIME LastWritten;
475 GetSystemTimeAsFileTime(&LastWritten);
477 ret = RegSetValueExW(hkey, wszFlagsValue, 0, REG_DWORD, (const BYTE*)&credential->Flags,
478 sizeof(credential->Flags));
479 if (ret != ERROR_SUCCESS) return ret;
480 ret = RegSetValueExW(hkey, wszTypeValue, 0, REG_DWORD, (const BYTE*)&credential->Type,
481 sizeof(credential->Type));
482 if (ret != ERROR_SUCCESS) return ret;
483 ret = RegSetValueExW(hkey, NULL, 0, REG_SZ, (LPVOID)credential->TargetName,
484 sizeof(WCHAR)*(strlenW(credential->TargetName)+1));
485 if (ret != ERROR_SUCCESS) return ret;
486 if (credential->Comment)
488 ret = RegSetValueExW(hkey, wszCommentValue, 0, REG_SZ, (LPVOID)credential->Comment,
489 sizeof(WCHAR)*(strlenW(credential->Comment)+1));
490 if (ret != ERROR_SUCCESS) return ret;
492 ret = RegSetValueExW(hkey, wszLastWrittenValue, 0, REG_BINARY, (LPVOID)&LastWritten,
493 sizeof(LastWritten));
494 if (ret != ERROR_SUCCESS) return ret;
495 ret = RegSetValueExW(hkey, wszPersistValue, 0, REG_DWORD, (const BYTE*)&credential->Persist,
496 sizeof(credential->Persist));
497 if (ret != ERROR_SUCCESS) return ret;
498 /* FIXME: Attributes */
499 if (credential->TargetAlias)
501 ret = RegSetValueExW(hkey, wszTargetAliasValue, 0, REG_SZ, (LPVOID)credential->TargetAlias,
502 sizeof(WCHAR)*(strlenW(credential->TargetAlias)+1));
503 if (ret != ERROR_SUCCESS) return ret;
505 if (credential->UserName)
507 ret = RegSetValueExW(hkey, wszUserNameValue, 0, REG_SZ, (LPVOID)credential->UserName,
508 sizeof(WCHAR)*(strlenW(credential->UserName)+1));
509 if (ret != ERROR_SUCCESS) return ret;
511 if (!preserve_blob)
513 ret = write_credential_blob(hkey, credential->TargetName, credential->Type,
514 key_data, credential->CredentialBlob,
515 credential->CredentialBlobSize);
517 return ret;
520 #ifdef __APPLE__
521 static DWORD mac_write_credential(const CREDENTIALW *credential, BOOL preserve_blob)
523 OSStatus status;
524 SecKeychainItemRef keychain_item;
525 char *username;
526 char *domain = NULL;
527 char *password;
528 char *servername;
529 UInt32 userlen;
530 UInt32 domainlen = 0;
531 UInt32 pwlen;
532 UInt32 serverlen;
533 LPCWSTR p;
534 SecKeychainAttribute attrs[1];
535 SecKeychainAttributeList attr_list;
537 if (credential->Flags)
538 FIXME("Flags 0x%x not written\n", credential->Flags);
539 if (credential->Type != CRED_TYPE_DOMAIN_PASSWORD)
540 FIXME("credential type of %d not supported\n", credential->Type);
541 if (credential->Persist != CRED_PERSIST_LOCAL_MACHINE)
542 FIXME("persist value of %d not supported\n", credential->Persist);
543 if (credential->AttributeCount)
544 FIXME("custom attributes not supported\n");
546 p = strchrW(credential->UserName, '\\');
547 if (p)
549 domainlen = WideCharToMultiByte(CP_UTF8, 0, credential->UserName,
550 p - credential->UserName, NULL, 0, NULL, NULL);
551 domain = HeapAlloc(GetProcessHeap(), 0, (domainlen + 1) * sizeof(*domain));
552 WideCharToMultiByte(CP_UTF8, 0, credential->UserName, p - credential->UserName,
553 domain, domainlen, NULL, NULL);
554 domain[domainlen] = '\0';
555 p++;
557 else
558 p = credential->UserName;
559 userlen = WideCharToMultiByte(CP_UTF8, 0, p, -1, NULL, 0, NULL, NULL);
560 username = HeapAlloc(GetProcessHeap(), 0, userlen * sizeof(*username));
561 WideCharToMultiByte(CP_UTF8, 0, p, -1, username, userlen, NULL, NULL);
563 serverlen = WideCharToMultiByte(CP_UTF8, 0, credential->TargetName, -1, NULL, 0, NULL, NULL);
564 servername = HeapAlloc(GetProcessHeap(), 0, serverlen * sizeof(*servername));
565 WideCharToMultiByte(CP_UTF8, 0, credential->TargetName, -1, servername, serverlen, NULL, NULL);
566 pwlen = WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR)credential->CredentialBlob,
567 credential->CredentialBlobSize / sizeof(WCHAR), NULL, 0, NULL, NULL);
568 password = HeapAlloc(GetProcessHeap(), 0, pwlen * sizeof(*domain));
569 WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR)credential->CredentialBlob,
570 credential->CredentialBlobSize / sizeof(WCHAR), password, pwlen, NULL, NULL);
572 TRACE("adding server %s, domain %s, username %s using Keychain\n", servername, domain, username);
573 status = SecKeychainAddInternetPassword(NULL, strlen(servername), servername,
574 strlen(domain), domain, strlen(username),
575 username, 0, NULL, 0,
576 0 /* no protocol */,
577 kSecAuthenticationTypeDefault,
578 strlen(password), password, &keychain_item);
579 if (status != noErr)
580 ERR("SecKeychainAddInternetPassword returned %ld\n", status);
581 if (status == errSecDuplicateItem)
583 SecKeychainItemRef keychain_item;
585 status = SecKeychainFindInternetPassword(NULL, strlen(servername), servername,
586 strlen(domain), domain,
587 strlen(username), username,
588 0, NULL /* any path */, 0,
589 0 /* any protocol */,
590 0 /* any authentication type */,
591 0, NULL, &keychain_item);
592 if (status != noErr)
593 ERR("SecKeychainFindInternetPassword returned %ld\n", status);
595 HeapFree(GetProcessHeap(), 0, domain);
596 HeapFree(GetProcessHeap(), 0, username);
597 HeapFree(GetProcessHeap(), 0, servername);
598 if (status != noErr)
600 HeapFree(GetProcessHeap(), 0, password);
601 return ERROR_GEN_FAILURE;
603 if (credential->Comment)
605 attr_list.count = 1;
606 attr_list.attr = attrs;
607 attrs[0].tag = kSecCommentItemAttr;
608 attrs[0].length = WideCharToMultiByte(CP_UTF8, 0, credential->Comment, -1, NULL, 0, NULL, NULL);
609 if (attrs[0].length) attrs[0].length--;
610 attrs[0].data = HeapAlloc(GetProcessHeap(), 0, attrs[0].length);
611 WideCharToMultiByte(CP_UTF8, 0, credential->Comment, -1, attrs[0].data, attrs[0].length, NULL, NULL);
613 else
615 attr_list.count = 0;
616 attr_list.attr = NULL;
618 status = SecKeychainItemModifyAttributesAndData(keychain_item, &attr_list,
619 preserve_blob ? 0 : strlen(password),
620 preserve_blob ? NULL : password);
621 if (credential->Comment)
622 HeapFree(GetProcessHeap(), 0, attrs[0].data);
623 HeapFree(GetProcessHeap(), 0, password);
624 /* FIXME: set TargetAlias attribute */
625 CFRelease(keychain_item);
626 if (status != noErr)
627 return ERROR_GEN_FAILURE;
628 return ERROR_SUCCESS;
630 #endif
632 static DWORD open_cred_mgr_key(HKEY *hkey, BOOL open_for_write)
634 return RegCreateKeyExW(HKEY_CURRENT_USER, wszCredentialManagerKey, 0,
635 NULL, REG_OPTION_NON_VOLATILE,
636 KEY_READ | (open_for_write ? KEY_WRITE : 0), NULL, hkey, NULL);
639 static DWORD get_cred_mgr_encryption_key(HKEY hkeyMgr, BYTE key_data[KEY_SIZE])
641 static const BYTE my_key_data[KEY_SIZE] = { 0 };
642 DWORD type;
643 DWORD count;
644 FILETIME ft;
645 ULONG seed;
646 ULONG value;
647 DWORD ret;
649 memcpy(key_data, my_key_data, KEY_SIZE);
651 count = KEY_SIZE;
652 ret = RegQueryValueExW(hkeyMgr, wszEncryptionKeyValue, NULL, &type, key_data,
653 &count);
654 if (ret == ERROR_SUCCESS)
656 if (type != REG_BINARY)
657 return ERROR_REGISTRY_CORRUPT;
658 else
659 return ERROR_SUCCESS;
661 if (ret != ERROR_FILE_NOT_FOUND)
662 return ret;
664 GetSystemTimeAsFileTime(&ft);
665 seed = ft.dwLowDateTime;
666 value = RtlUniform(&seed);
667 *(DWORD *)key_data = value;
668 seed = ft.dwHighDateTime;
669 value = RtlUniform(&seed);
670 *(DWORD *)(key_data + 4) = value;
672 ret = RegSetValueExW(hkeyMgr, wszEncryptionKeyValue, 0, REG_BINARY,
673 key_data, KEY_SIZE);
674 if (ret == ERROR_ACCESS_DENIED)
676 ret = open_cred_mgr_key(&hkeyMgr, TRUE);
677 if (ret == ERROR_SUCCESS)
679 ret = RegSetValueExW(hkeyMgr, wszEncryptionKeyValue, 0, REG_BINARY,
680 key_data, KEY_SIZE);
681 RegCloseKey(hkeyMgr);
684 return ret;
687 static LPWSTR get_key_name_for_target(LPCWSTR target_name, DWORD type)
689 static const WCHAR wszGenericPrefix[] = {'G','e','n','e','r','i','c',':',' ',0};
690 static const WCHAR wszDomPasswdPrefix[] = {'D','o','m','P','a','s','s','w','d',':',' ',0};
691 INT len;
692 LPCWSTR prefix = NULL;
693 LPWSTR key_name, p;
695 len = strlenW(target_name);
696 if (type == CRED_TYPE_GENERIC)
698 prefix = wszGenericPrefix;
699 len += sizeof(wszGenericPrefix)/sizeof(wszGenericPrefix[0]);
701 else
703 prefix = wszDomPasswdPrefix;
704 len += sizeof(wszDomPasswdPrefix)/sizeof(wszDomPasswdPrefix[0]);
707 key_name = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
708 if (!key_name) return NULL;
710 strcpyW(key_name, prefix);
711 strcatW(key_name, target_name);
713 for (p = key_name; *p; p++)
714 if (*p == '\\') *p = '_';
716 return key_name;
719 static BOOL registry_credential_matches_filter(HKEY hkeyCred, LPCWSTR filter)
721 LPWSTR target_name;
722 DWORD ret;
723 DWORD type;
724 DWORD count;
725 LPCWSTR p;
727 if (!filter) return TRUE;
729 ret = RegQueryValueExW(hkeyCred, NULL, 0, &type, NULL, &count);
730 if (ret != ERROR_SUCCESS)
731 return FALSE;
732 else if (type != REG_SZ)
733 return FALSE;
735 target_name = HeapAlloc(GetProcessHeap(), 0, count);
736 if (!target_name)
737 return FALSE;
738 ret = RegQueryValueExW(hkeyCred, NULL, 0, &type, (LPVOID)target_name, &count);
739 if (ret != ERROR_SUCCESS || type != REG_SZ)
741 HeapFree(GetProcessHeap(), 0, target_name);
742 return FALSE;
745 TRACE("comparing filter %s to target name %s\n", debugstr_w(filter),
746 debugstr_w(target_name));
748 p = strchrW(filter, '*');
749 ret = CompareStringW(GetThreadLocale(), 0, filter,
750 (p && !p[1] ? p - filter : -1), target_name,
751 (p && !p[1] ? p - filter : -1)) == CSTR_EQUAL;
753 HeapFree(GetProcessHeap(), 0, target_name);
754 return ret;
757 static DWORD registry_enumerate_credentials(HKEY hkeyMgr, LPCWSTR filter,
758 LPWSTR target_name,
759 DWORD target_name_len, const BYTE key_data[KEY_SIZE],
760 PCREDENTIALW *credentials, char **buffer,
761 DWORD *len, DWORD *count)
763 DWORD i;
764 DWORD ret;
765 for (i = 0;; i++)
767 HKEY hkeyCred;
768 ret = RegEnumKeyW(hkeyMgr, i, target_name, target_name_len+1);
769 if (ret == ERROR_NO_MORE_ITEMS)
771 ret = ERROR_SUCCESS;
772 break;
774 else if (ret != ERROR_SUCCESS)
775 continue;
776 TRACE("target_name = %s\n", debugstr_w(target_name));
777 ret = RegOpenKeyExW(hkeyMgr, target_name, 0, KEY_QUERY_VALUE, &hkeyCred);
778 if (ret != ERROR_SUCCESS)
779 continue;
780 if (!registry_credential_matches_filter(hkeyCred, filter))
782 RegCloseKey(hkeyCred);
783 continue;
785 if (buffer)
787 *len = sizeof(CREDENTIALW);
788 credentials[*count] = (PCREDENTIALW)*buffer;
790 else
791 *len += sizeof(CREDENTIALW);
792 ret = registry_read_credential(hkeyCred, buffer ? credentials[*count] : NULL,
793 key_data, buffer ? *buffer + sizeof(CREDENTIALW) : NULL,
794 len);
795 RegCloseKey(hkeyCred);
796 if (ret != ERROR_SUCCESS) break;
797 if (buffer) *buffer += *len;
798 (*count)++;
800 return ret;
803 #ifdef __APPLE__
804 static BOOL mac_credential_matches_filter(void *data, UInt32 data_len, const WCHAR *filter)
806 int len;
807 WCHAR *target_name;
808 const WCHAR *p;
809 BOOL ret;
811 if (!filter) return TRUE;
813 len = MultiByteToWideChar(CP_UTF8, 0, data, data_len, NULL, 0);
814 if (!(target_name = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR)))) return FALSE;
815 MultiByteToWideChar(CP_UTF8, 0, data, data_len, target_name, len);
816 target_name[len] = 0;
818 TRACE("comparing filter %s to target name %s\n", debugstr_w(filter), debugstr_w(target_name));
820 p = strchrW(filter, '*');
821 ret = CompareStringW(GetThreadLocale(), 0, filter,
822 (p && !p[1] ? p - filter : -1), target_name,
823 (p && !p[1] ? p - filter : -1)) == CSTR_EQUAL;
824 HeapFree(GetProcessHeap(), 0, target_name);
825 return ret;
828 static DWORD mac_enumerate_credentials(LPCWSTR filter, PCREDENTIALW *credentials,
829 char *buffer, DWORD *len, DWORD *count)
831 SecKeychainSearchRef search;
832 SecKeychainItemRef item;
833 OSStatus status;
834 Boolean saved_user_interaction_allowed;
835 DWORD ret;
837 SecKeychainGetUserInteractionAllowed(&saved_user_interaction_allowed);
838 SecKeychainSetUserInteractionAllowed(false);
840 status = SecKeychainSearchCreateFromAttributes(NULL, kSecInternetPasswordItemClass, NULL, &search);
841 if (status == noErr)
843 while (SecKeychainSearchCopyNext(search, &item) == noErr)
845 SecKeychainAttributeInfo info;
846 SecKeychainAttributeList *attr_list;
847 UInt32 info_tags[] = { kSecServerItemAttr };
848 BOOL match;
850 info.count = sizeof(info_tags)/sizeof(info_tags[0]);
851 info.tag = info_tags;
852 info.format = NULL;
853 status = SecKeychainItemCopyAttributesAndData(item, &info, NULL, &attr_list, NULL, NULL);
854 if (status != noErr)
856 WARN("SecKeychainItemCopyAttributesAndData returned status %ld\n", status);
857 continue;
859 if (buffer)
861 *len = sizeof(CREDENTIALW);
862 credentials[*count] = (PCREDENTIALW)buffer;
864 else
865 *len += sizeof(CREDENTIALW);
866 if (attr_list->count != 1 || attr_list->attr[0].tag != kSecServerItemAttr)
868 SecKeychainItemFreeAttributesAndData(attr_list, NULL);
869 continue;
871 TRACE("server item: %.*s\n", (int)attr_list->attr[0].length, (char *)attr_list->attr[0].data);
872 match = mac_credential_matches_filter(attr_list->attr[0].data, attr_list->attr[0].length, filter);
873 SecKeychainItemFreeAttributesAndData(attr_list, NULL);
874 if (!match) continue;
875 ret = mac_read_credential_from_item(item, FALSE,
876 buffer ? credentials[*count] : NULL,
877 buffer ? buffer + sizeof(CREDENTIALW) : NULL,
878 len);
879 CFRelease(item);
880 if (ret == ERROR_SUCCESS)
882 (*count)++;
883 if (buffer) buffer += *len;
886 CFRelease(search);
888 else
889 ERR("SecKeychainSearchCreateFromAttributes returned status %ld\n", status);
890 SecKeychainSetUserInteractionAllowed(saved_user_interaction_allowed);
891 return ERROR_SUCCESS;
894 static DWORD mac_delete_credential(LPCWSTR TargetName)
896 OSStatus status;
897 SecKeychainSearchRef search;
898 status = SecKeychainSearchCreateFromAttributes(NULL, kSecInternetPasswordItemClass, NULL, &search);
899 if (status == noErr)
901 SecKeychainItemRef item;
902 while (SecKeychainSearchCopyNext(search, &item) == noErr)
904 SecKeychainAttributeInfo info;
905 SecKeychainAttributeList *attr_list;
906 UInt32 info_tags[] = { kSecServerItemAttr };
907 LPWSTR target_name;
908 INT str_len;
909 info.count = sizeof(info_tags)/sizeof(info_tags[0]);
910 info.tag = info_tags;
911 info.format = NULL;
912 status = SecKeychainItemCopyAttributesAndData(item, &info, NULL, &attr_list, NULL, NULL);
913 if (status != noErr)
915 WARN("SecKeychainItemCopyAttributesAndData returned status %ld\n", status);
916 continue;
918 if (attr_list->count != 1 || attr_list->attr[0].tag != kSecServerItemAttr)
920 CFRelease(item);
921 continue;
923 str_len = MultiByteToWideChar(CP_UTF8, 0, attr_list->attr[0].data, attr_list->attr[0].length, NULL, 0);
924 target_name = HeapAlloc(GetProcessHeap(), 0, (str_len + 1) * sizeof(WCHAR));
925 MultiByteToWideChar(CP_UTF8, 0, attr_list->attr[0].data, attr_list->attr[0].length, target_name, str_len);
926 /* nul terminate */
927 target_name[str_len] = '\0';
928 if (strcmpiW(TargetName, target_name))
930 CFRelease(item);
931 HeapFree(GetProcessHeap(), 0, target_name);
932 continue;
934 HeapFree(GetProcessHeap(), 0, target_name);
935 SecKeychainItemFreeAttributesAndData(attr_list, NULL);
936 SecKeychainItemDelete(item);
937 CFRelease(item);
938 CFRelease(search);
940 return ERROR_SUCCESS;
942 CFRelease(search);
944 return ERROR_NOT_FOUND;
946 #endif
948 /******************************************************************************
949 * convert_PCREDENTIALW_to_PCREDENTIALA [internal]
951 * convert a Credential struct from UNICODE to ANSI and return the needed size in Bytes
955 static INT convert_PCREDENTIALW_to_PCREDENTIALA(const CREDENTIALW *CredentialW, PCREDENTIALA CredentialA, DWORD len)
957 char *buffer;
958 INT string_len;
959 INT needed = sizeof(CREDENTIALA);
961 if (!CredentialA)
963 if (CredentialW->TargetName)
964 needed += WideCharToMultiByte(CP_ACP, 0, CredentialW->TargetName, -1, NULL, 0, NULL, NULL);
965 if (CredentialW->Comment)
966 needed += WideCharToMultiByte(CP_ACP, 0, CredentialW->Comment, -1, NULL, 0, NULL, NULL);
967 needed += CredentialW->CredentialBlobSize;
968 if (CredentialW->TargetAlias)
969 needed += WideCharToMultiByte(CP_ACP, 0, CredentialW->TargetAlias, -1, NULL, 0, NULL, NULL);
970 if (CredentialW->UserName)
971 needed += WideCharToMultiByte(CP_ACP, 0, CredentialW->UserName, -1, NULL, 0, NULL, NULL);
973 return needed;
977 buffer = (char *)CredentialA + sizeof(CREDENTIALA);
978 len -= sizeof(CREDENTIALA);
979 CredentialA->Flags = CredentialW->Flags;
980 CredentialA->Type = CredentialW->Type;
982 if (CredentialW->TargetName)
984 CredentialA->TargetName = buffer;
985 string_len = WideCharToMultiByte(CP_ACP, 0, CredentialW->TargetName, -1, buffer, len, NULL, NULL);
986 buffer += string_len;
987 needed += string_len;
988 len -= string_len;
990 else
991 CredentialA->TargetName = NULL;
992 if (CredentialW->Comment)
994 CredentialA->Comment = buffer;
995 string_len = WideCharToMultiByte(CP_ACP, 0, CredentialW->Comment, -1, buffer, len, NULL, NULL);
996 buffer += string_len;
997 needed += string_len;
998 len -= string_len;
1000 else
1001 CredentialA->Comment = NULL;
1002 CredentialA->LastWritten = CredentialW->LastWritten;
1003 CredentialA->CredentialBlobSize = CredentialW->CredentialBlobSize;
1004 if (CredentialW->CredentialBlobSize && (CredentialW->CredentialBlobSize <= len))
1006 CredentialA->CredentialBlob =(LPBYTE)buffer;
1007 memcpy(CredentialA->CredentialBlob, CredentialW->CredentialBlob,
1008 CredentialW->CredentialBlobSize);
1009 buffer += CredentialW->CredentialBlobSize;
1010 needed += CredentialW->CredentialBlobSize;
1011 len -= CredentialW->CredentialBlobSize;
1013 else
1014 CredentialA->CredentialBlob = NULL;
1015 CredentialA->Persist = CredentialW->Persist;
1016 CredentialA->AttributeCount = 0;
1017 CredentialA->Attributes = NULL; /* FIXME */
1018 if (CredentialW->TargetAlias)
1020 CredentialA->TargetAlias = buffer;
1021 string_len = WideCharToMultiByte(CP_ACP, 0, CredentialW->TargetAlias, -1, buffer, len, NULL, NULL);
1022 buffer += string_len;
1023 needed += string_len;
1024 len -= string_len;
1026 else
1027 CredentialA->TargetAlias = NULL;
1028 if (CredentialW->UserName)
1030 CredentialA->UserName = buffer;
1031 string_len = WideCharToMultiByte(CP_ACP, 0, CredentialW->UserName, -1, buffer, len, NULL, NULL);
1032 needed += string_len;
1034 else
1035 CredentialA->UserName = NULL;
1037 return needed;
1040 /******************************************************************************
1041 * convert_PCREDENTIALA_to_PCREDENTIALW [internal]
1043 * convert a Credential struct from ANSI to UNICODE and return the needed size in Bytes
1046 static INT convert_PCREDENTIALA_to_PCREDENTIALW(const CREDENTIALA *CredentialA, PCREDENTIALW CredentialW, INT len)
1048 char *buffer;
1049 INT string_len;
1050 INT needed = sizeof(CREDENTIALW);
1052 if (!CredentialW)
1054 if (CredentialA->TargetName)
1055 needed += sizeof(WCHAR) * MultiByteToWideChar(CP_ACP, 0, CredentialA->TargetName, -1, NULL, 0);
1056 if (CredentialA->Comment)
1057 needed += sizeof(WCHAR) * MultiByteToWideChar(CP_ACP, 0, CredentialA->Comment, -1, NULL, 0);
1058 needed += CredentialA->CredentialBlobSize;
1059 if (CredentialA->TargetAlias)
1060 needed += sizeof(WCHAR) * MultiByteToWideChar(CP_ACP, 0, CredentialA->TargetAlias, -1, NULL, 0);
1061 if (CredentialA->UserName)
1062 needed += sizeof(WCHAR) * MultiByteToWideChar(CP_ACP, 0, CredentialA->UserName, -1, NULL, 0);
1064 return needed;
1067 buffer = (char *)CredentialW + sizeof(CREDENTIALW);
1068 len -= sizeof(CREDENTIALW);
1069 CredentialW->Flags = CredentialA->Flags;
1070 CredentialW->Type = CredentialA->Type;
1071 if (CredentialA->TargetName)
1073 CredentialW->TargetName = (LPWSTR)buffer;
1074 string_len = MultiByteToWideChar(CP_ACP, 0, CredentialA->TargetName, -1, CredentialW->TargetName, len / sizeof(WCHAR));
1075 buffer += sizeof(WCHAR) * string_len;
1076 needed += sizeof(WCHAR) * string_len;
1077 len -= sizeof(WCHAR) * string_len;
1079 else
1080 CredentialW->TargetName = NULL;
1081 if (CredentialA->Comment)
1083 CredentialW->Comment = (LPWSTR)buffer;
1084 string_len = MultiByteToWideChar(CP_ACP, 0, CredentialA->Comment, -1, CredentialW->Comment, len / sizeof(WCHAR));
1085 buffer += sizeof(WCHAR) * string_len;
1086 needed += sizeof(WCHAR) * string_len;
1087 len -= sizeof(WCHAR) * string_len;
1089 else
1090 CredentialW->Comment = NULL;
1091 CredentialW->LastWritten = CredentialA->LastWritten;
1092 CredentialW->CredentialBlobSize = CredentialA->CredentialBlobSize;
1093 if (CredentialA->CredentialBlobSize)
1095 CredentialW->CredentialBlob =(LPBYTE)buffer;
1096 memcpy(CredentialW->CredentialBlob, CredentialA->CredentialBlob,
1097 CredentialA->CredentialBlobSize);
1098 buffer += CredentialA->CredentialBlobSize;
1099 needed += CredentialA->CredentialBlobSize;
1100 len -= CredentialA->CredentialBlobSize;
1102 else
1103 CredentialW->CredentialBlob = NULL;
1104 CredentialW->Persist = CredentialA->Persist;
1105 CredentialW->AttributeCount = 0;
1106 CredentialW->Attributes = NULL; /* FIXME */
1107 if (CredentialA->TargetAlias)
1109 CredentialW->TargetAlias = (LPWSTR)buffer;
1110 string_len = MultiByteToWideChar(CP_ACP, 0, CredentialA->TargetAlias, -1, CredentialW->TargetAlias, len / sizeof(WCHAR));
1111 buffer += sizeof(WCHAR) * string_len;
1112 needed += sizeof(WCHAR) * string_len;
1113 len -= sizeof(WCHAR) * string_len;
1115 else
1116 CredentialW->TargetAlias = NULL;
1117 if (CredentialA->UserName)
1119 CredentialW->UserName = (LPWSTR)buffer;
1120 string_len = MultiByteToWideChar(CP_ACP, 0, CredentialA->UserName, -1, CredentialW->UserName, len / sizeof(WCHAR));
1121 needed += sizeof(WCHAR) * string_len;
1123 else
1124 CredentialW->UserName = NULL;
1126 return needed;
1129 /******************************************************************************
1130 * CredDeleteA [ADVAPI32.@]
1132 BOOL WINAPI CredDeleteA(LPCSTR TargetName, DWORD Type, DWORD Flags)
1134 LPWSTR TargetNameW;
1135 DWORD len;
1136 BOOL ret;
1138 TRACE("(%s, %d, 0x%x)\n", debugstr_a(TargetName), Type, Flags);
1140 if (!TargetName)
1142 SetLastError(ERROR_INVALID_PARAMETER);
1143 return FALSE;
1146 len = MultiByteToWideChar(CP_ACP, 0, TargetName, -1, NULL, 0);
1147 TargetNameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1148 if (!TargetNameW)
1150 SetLastError(ERROR_OUTOFMEMORY);
1151 return FALSE;
1153 MultiByteToWideChar(CP_ACP, 0, TargetName, -1, TargetNameW, len);
1155 ret = CredDeleteW(TargetNameW, Type, Flags);
1157 HeapFree(GetProcessHeap(), 0, TargetNameW);
1159 return ret;
1162 /******************************************************************************
1163 * CredDeleteW [ADVAPI32.@]
1165 BOOL WINAPI CredDeleteW(LPCWSTR TargetName, DWORD Type, DWORD Flags)
1167 HKEY hkeyMgr;
1168 DWORD ret;
1169 LPWSTR key_name;
1171 TRACE("(%s, %d, 0x%x)\n", debugstr_w(TargetName), Type, Flags);
1173 if (!TargetName)
1175 SetLastError(ERROR_INVALID_PARAMETER);
1176 return FALSE;
1179 if (Type != CRED_TYPE_GENERIC && Type != CRED_TYPE_DOMAIN_PASSWORD)
1181 FIXME("unhandled type %d\n", Type);
1182 SetLastError(ERROR_INVALID_PARAMETER);
1183 return FALSE;
1186 if (Flags)
1188 FIXME("unhandled flags 0x%x\n", Flags);
1189 SetLastError(ERROR_INVALID_FLAGS);
1190 return FALSE;
1193 #ifdef __APPLE__
1194 if (Type == CRED_TYPE_DOMAIN_PASSWORD)
1196 ret = mac_delete_credential(TargetName);
1197 if (ret == ERROR_SUCCESS)
1198 return TRUE;
1200 #endif
1202 ret = open_cred_mgr_key(&hkeyMgr, TRUE);
1203 if (ret != ERROR_SUCCESS)
1205 WARN("couldn't open/create manager key, error %d\n", ret);
1206 SetLastError(ERROR_NO_SUCH_LOGON_SESSION);
1207 return FALSE;
1210 key_name = get_key_name_for_target(TargetName, Type);
1211 ret = RegDeleteKeyW(hkeyMgr, key_name);
1212 HeapFree(GetProcessHeap(), 0, key_name);
1213 RegCloseKey(hkeyMgr);
1214 if (ret != ERROR_SUCCESS)
1216 SetLastError(ERROR_NOT_FOUND);
1217 return FALSE;
1220 return TRUE;
1223 /******************************************************************************
1224 * CredEnumerateA [ADVAPI32.@]
1226 BOOL WINAPI CredEnumerateA(LPCSTR Filter, DWORD Flags, DWORD *Count,
1227 PCREDENTIALA **Credentials)
1229 LPWSTR FilterW;
1230 PCREDENTIALW *CredentialsW;
1231 DWORD i;
1232 INT len;
1233 INT needed;
1234 char *buffer;
1236 TRACE("(%s, 0x%x, %p, %p)\n", debugstr_a(Filter), Flags, Count, Credentials);
1238 if (Filter)
1240 len = MultiByteToWideChar(CP_ACP, 0, Filter, -1, NULL, 0);
1241 FilterW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1242 if (!FilterW)
1244 SetLastError(ERROR_OUTOFMEMORY);
1245 return FALSE;
1247 MultiByteToWideChar(CP_ACP, 0, Filter, -1, FilterW, len);
1249 else
1250 FilterW = NULL;
1252 if (!CredEnumerateW(FilterW, Flags, Count, &CredentialsW))
1254 HeapFree(GetProcessHeap(), 0, FilterW);
1255 return FALSE;
1257 HeapFree(GetProcessHeap(), 0, FilterW);
1259 len = *Count * sizeof(PCREDENTIALA);
1260 for (i = 0; i < *Count; i++)
1261 len += convert_PCREDENTIALW_to_PCREDENTIALA(CredentialsW[i], NULL, 0);
1263 *Credentials = HeapAlloc(GetProcessHeap(), 0, len);
1264 if (!*Credentials)
1266 CredFree(CredentialsW);
1267 SetLastError(ERROR_OUTOFMEMORY);
1268 return FALSE;
1271 buffer = (char *)&(*Credentials)[*Count];
1272 len -= *Count * sizeof(PCREDENTIALA);
1273 for (i = 0; i < *Count; i++)
1275 (*Credentials)[i] = (PCREDENTIALA)buffer;
1276 needed = convert_PCREDENTIALW_to_PCREDENTIALA(CredentialsW[i], (*Credentials)[i], len);
1277 buffer += needed;
1278 len -= needed;
1281 CredFree(CredentialsW);
1283 return TRUE;
1286 /******************************************************************************
1287 * CredEnumerateW [ADVAPI32.@]
1289 BOOL WINAPI CredEnumerateW(LPCWSTR Filter, DWORD Flags, DWORD *Count,
1290 PCREDENTIALW **Credentials)
1292 HKEY hkeyMgr;
1293 DWORD ret;
1294 LPWSTR target_name;
1295 DWORD target_name_len;
1296 DWORD len;
1297 char *buffer;
1298 BYTE key_data[KEY_SIZE];
1300 TRACE("(%s, 0x%x, %p, %p)\n", debugstr_w(Filter), Flags, Count, Credentials);
1302 if (Flags)
1304 SetLastError(ERROR_INVALID_FLAGS);
1305 return FALSE;
1308 ret = open_cred_mgr_key(&hkeyMgr, FALSE);
1309 if (ret != ERROR_SUCCESS)
1311 WARN("couldn't open/create manager key, error %d\n", ret);
1312 SetLastError(ERROR_NO_SUCH_LOGON_SESSION);
1313 return FALSE;
1316 ret = get_cred_mgr_encryption_key(hkeyMgr, key_data);
1317 if (ret != ERROR_SUCCESS)
1319 RegCloseKey(hkeyMgr);
1320 SetLastError(ret);
1321 return FALSE;
1324 ret = RegQueryInfoKeyW(hkeyMgr, NULL, NULL, NULL, NULL, &target_name_len, NULL, NULL, NULL, NULL, NULL, NULL);
1325 if (ret != ERROR_SUCCESS)
1327 RegCloseKey(hkeyMgr);
1328 SetLastError(ret);
1329 return FALSE;
1332 target_name = HeapAlloc(GetProcessHeap(), 0, (target_name_len+1)*sizeof(WCHAR));
1333 if (!target_name)
1335 RegCloseKey(hkeyMgr);
1336 SetLastError(ERROR_OUTOFMEMORY);
1337 return FALSE;
1340 *Count = 0;
1341 len = 0;
1342 ret = registry_enumerate_credentials(hkeyMgr, Filter, target_name, target_name_len,
1343 key_data, NULL, NULL, &len, Count);
1344 #ifdef __APPLE__
1345 if (ret == ERROR_SUCCESS)
1346 ret = mac_enumerate_credentials(Filter, NULL, NULL, &len, Count);
1347 #endif
1348 if (ret == ERROR_SUCCESS && *Count == 0)
1349 ret = ERROR_NOT_FOUND;
1350 if (ret != ERROR_SUCCESS)
1352 HeapFree(GetProcessHeap(), 0, target_name);
1353 RegCloseKey(hkeyMgr);
1354 SetLastError(ret);
1355 return FALSE;
1357 len += *Count * sizeof(PCREDENTIALW);
1359 if (ret == ERROR_SUCCESS)
1361 buffer = HeapAlloc(GetProcessHeap(), 0, len);
1362 *Credentials = (PCREDENTIALW *)buffer;
1363 if (buffer)
1365 buffer += *Count * sizeof(PCREDENTIALW);
1366 *Count = 0;
1367 ret = registry_enumerate_credentials(hkeyMgr, Filter, target_name,
1368 target_name_len, key_data,
1369 *Credentials, &buffer, &len,
1370 Count);
1371 #ifdef __APPLE__
1372 if (ret == ERROR_SUCCESS)
1373 ret = mac_enumerate_credentials(Filter, *Credentials,
1374 buffer, &len, Count);
1375 #endif
1377 else
1378 ret = ERROR_OUTOFMEMORY;
1381 HeapFree(GetProcessHeap(), 0, target_name);
1382 RegCloseKey(hkeyMgr);
1384 if (ret != ERROR_SUCCESS)
1386 SetLastError(ret);
1387 return FALSE;
1389 return TRUE;
1392 /******************************************************************************
1393 * CredFree [ADVAPI32.@]
1395 VOID WINAPI CredFree(PVOID Buffer)
1397 HeapFree(GetProcessHeap(), 0, Buffer);
1400 /******************************************************************************
1401 * CredReadA [ADVAPI32.@]
1403 BOOL WINAPI CredReadA(LPCSTR TargetName, DWORD Type, DWORD Flags, PCREDENTIALA *Credential)
1405 LPWSTR TargetNameW;
1406 PCREDENTIALW CredentialW;
1407 INT len;
1409 TRACE("(%s, %d, 0x%x, %p)\n", debugstr_a(TargetName), Type, Flags, Credential);
1411 if (!TargetName)
1413 SetLastError(ERROR_INVALID_PARAMETER);
1414 return FALSE;
1417 len = MultiByteToWideChar(CP_ACP, 0, TargetName, -1, NULL, 0);
1418 TargetNameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1419 if (!TargetNameW)
1421 SetLastError(ERROR_OUTOFMEMORY);
1422 return FALSE;
1424 MultiByteToWideChar(CP_ACP, 0, TargetName, -1, TargetNameW, len);
1426 if (!CredReadW(TargetNameW, Type, Flags, &CredentialW))
1428 HeapFree(GetProcessHeap(), 0, TargetNameW);
1429 return FALSE;
1431 HeapFree(GetProcessHeap(), 0, TargetNameW);
1433 len = convert_PCREDENTIALW_to_PCREDENTIALA(CredentialW, NULL, 0);
1434 *Credential = HeapAlloc(GetProcessHeap(), 0, len);
1435 if (!*Credential)
1437 SetLastError(ERROR_OUTOFMEMORY);
1438 return FALSE;
1440 convert_PCREDENTIALW_to_PCREDENTIALA(CredentialW, *Credential, len);
1442 CredFree(CredentialW);
1444 return TRUE;
1447 /******************************************************************************
1448 * CredReadW [ADVAPI32.@]
1450 BOOL WINAPI CredReadW(LPCWSTR TargetName, DWORD Type, DWORD Flags, PCREDENTIALW *Credential)
1452 HKEY hkeyMgr;
1453 HKEY hkeyCred;
1454 DWORD ret;
1455 LPWSTR key_name;
1456 DWORD len;
1457 BYTE key_data[KEY_SIZE];
1459 TRACE("(%s, %d, 0x%x, %p)\n", debugstr_w(TargetName), Type, Flags, Credential);
1461 if (!TargetName)
1463 SetLastError(ERROR_INVALID_PARAMETER);
1464 return FALSE;
1467 if (Type != CRED_TYPE_GENERIC && Type != CRED_TYPE_DOMAIN_PASSWORD)
1469 FIXME("unhandled type %d\n", Type);
1470 SetLastError(ERROR_INVALID_PARAMETER);
1471 return FALSE;
1474 if (Flags)
1476 FIXME("unhandled flags 0x%x\n", Flags);
1477 SetLastError(ERROR_INVALID_FLAGS);
1478 return FALSE;
1481 #ifdef __APPLE__
1482 if (Type == CRED_TYPE_DOMAIN_PASSWORD)
1484 OSStatus status;
1485 SecKeychainSearchRef search;
1486 status = SecKeychainSearchCreateFromAttributes(NULL, kSecInternetPasswordItemClass, NULL, &search);
1487 if (status == noErr)
1489 SecKeychainItemRef item;
1490 while (SecKeychainSearchCopyNext(search, &item) == noErr)
1492 SecKeychainAttributeInfo info;
1493 SecKeychainAttributeList *attr_list;
1494 UInt32 info_tags[] = { kSecServerItemAttr };
1495 LPWSTR target_name;
1496 INT str_len;
1497 info.count = sizeof(info_tags)/sizeof(info_tags[0]);
1498 info.tag = info_tags;
1499 info.format = NULL;
1500 status = SecKeychainItemCopyAttributesAndData(item, &info, NULL, &attr_list, NULL, NULL);
1501 len = sizeof(**Credential);
1502 if (status != noErr)
1504 WARN("SecKeychainItemCopyAttributesAndData returned status %ld\n", status);
1505 continue;
1507 if (attr_list->count != 1 || attr_list->attr[0].tag != kSecServerItemAttr)
1509 CFRelease(item);
1510 continue;
1512 str_len = MultiByteToWideChar(CP_UTF8, 0, attr_list->attr[0].data, attr_list->attr[0].length, NULL, 0);
1513 target_name = HeapAlloc(GetProcessHeap(), 0, (str_len + 1) * sizeof(WCHAR));
1514 MultiByteToWideChar(CP_UTF8, 0, attr_list->attr[0].data, attr_list->attr[0].length, target_name, str_len);
1515 /* nul terminate */
1516 target_name[str_len] = '\0';
1517 if (strcmpiW(TargetName, target_name))
1519 CFRelease(item);
1520 HeapFree(GetProcessHeap(), 0, target_name);
1521 continue;
1523 HeapFree(GetProcessHeap(), 0, target_name);
1524 SecKeychainItemFreeAttributesAndData(attr_list, NULL);
1525 ret = mac_read_credential_from_item(item, TRUE, NULL, NULL, &len);
1526 if (ret == ERROR_SUCCESS)
1528 *Credential = HeapAlloc(GetProcessHeap(), 0, len);
1529 if (*Credential)
1531 len = sizeof(**Credential);
1532 ret = mac_read_credential_from_item(item, TRUE, *Credential,
1533 (char *)(*Credential + 1), &len);
1535 else
1536 ret = ERROR_OUTOFMEMORY;
1537 CFRelease(item);
1538 CFRelease(search);
1539 if (ret != ERROR_SUCCESS)
1541 SetLastError(ret);
1542 return FALSE;
1544 return TRUE;
1546 CFRelease(item);
1548 CFRelease(search);
1551 #endif
1553 ret = open_cred_mgr_key(&hkeyMgr, FALSE);
1554 if (ret != ERROR_SUCCESS)
1556 WARN("couldn't open/create manager key, error %d\n", ret);
1557 SetLastError(ERROR_NO_SUCH_LOGON_SESSION);
1558 return FALSE;
1561 ret = get_cred_mgr_encryption_key(hkeyMgr, key_data);
1562 if (ret != ERROR_SUCCESS)
1564 RegCloseKey(hkeyMgr);
1565 SetLastError(ret);
1566 return FALSE;
1569 key_name = get_key_name_for_target(TargetName, Type);
1570 ret = RegOpenKeyExW(hkeyMgr, key_name, 0, KEY_QUERY_VALUE, &hkeyCred);
1571 HeapFree(GetProcessHeap(), 0, key_name);
1572 if (ret != ERROR_SUCCESS)
1574 TRACE("credentials for target name %s not found\n", debugstr_w(TargetName));
1575 SetLastError(ERROR_NOT_FOUND);
1576 return FALSE;
1579 len = sizeof(**Credential);
1580 ret = registry_read_credential(hkeyCred, NULL, key_data, NULL, &len);
1581 if (ret == ERROR_SUCCESS)
1583 *Credential = HeapAlloc(GetProcessHeap(), 0, len);
1584 if (*Credential)
1586 len = sizeof(**Credential);
1587 ret = registry_read_credential(hkeyCred, *Credential, key_data,
1588 (char *)(*Credential + 1), &len);
1590 else
1591 ret = ERROR_OUTOFMEMORY;
1594 RegCloseKey(hkeyCred);
1595 RegCloseKey(hkeyMgr);
1597 if (ret != ERROR_SUCCESS)
1599 SetLastError(ret);
1600 return FALSE;
1602 return TRUE;
1605 /******************************************************************************
1606 * CredReadDomainCredentialsA [ADVAPI32.@]
1608 BOOL WINAPI CredReadDomainCredentialsA(PCREDENTIAL_TARGET_INFORMATIONA TargetInformation,
1609 DWORD Flags, DWORD *Size, PCREDENTIALA **Credentials)
1611 PCREDENTIAL_TARGET_INFORMATIONW TargetInformationW;
1612 INT len;
1613 DWORD i;
1614 WCHAR *buffer, *end;
1615 BOOL ret;
1616 PCREDENTIALW* CredentialsW;
1618 TRACE("(%p, 0x%x, %p, %p)\n", TargetInformation, Flags, Size, Credentials);
1620 /* follow Windows behavior - do not test for NULL, initialize early */
1621 *Size = 0;
1622 *Credentials = NULL;
1624 if (!TargetInformation)
1626 SetLastError(ERROR_INVALID_PARAMETER);
1627 return FALSE;
1630 len = sizeof(*TargetInformationW);
1631 if (TargetInformation->TargetName)
1632 len += MultiByteToWideChar(CP_ACP, 0, TargetInformation->TargetName, -1, NULL, 0) * sizeof(WCHAR);
1633 if (TargetInformation->NetbiosServerName)
1634 len += MultiByteToWideChar(CP_ACP, 0, TargetInformation->NetbiosServerName, -1, NULL, 0) * sizeof(WCHAR);
1635 if (TargetInformation->DnsServerName)
1636 len += MultiByteToWideChar(CP_ACP, 0, TargetInformation->DnsServerName, -1, NULL, 0) * sizeof(WCHAR);
1637 if (TargetInformation->NetbiosDomainName)
1638 len += MultiByteToWideChar(CP_ACP, 0, TargetInformation->NetbiosDomainName, -1, NULL, 0) * sizeof(WCHAR);
1639 if (TargetInformation->DnsDomainName)
1640 len += MultiByteToWideChar(CP_ACP, 0, TargetInformation->DnsDomainName, -1, NULL, 0) * sizeof(WCHAR);
1641 if (TargetInformation->DnsTreeName)
1642 len += MultiByteToWideChar(CP_ACP, 0, TargetInformation->DnsTreeName, -1, NULL, 0) * sizeof(WCHAR);
1643 if (TargetInformation->PackageName)
1644 len += MultiByteToWideChar(CP_ACP, 0, TargetInformation->PackageName, -1, NULL, 0) * sizeof(WCHAR);
1646 TargetInformationW = HeapAlloc(GetProcessHeap(), 0, len);
1647 if (!TargetInformationW)
1649 SetLastError(ERROR_OUTOFMEMORY);
1650 return FALSE;
1652 buffer = (WCHAR*)(TargetInformationW + 1);
1653 end = (WCHAR *)((char *)TargetInformationW + len);
1655 if (TargetInformation->TargetName)
1657 TargetInformationW->TargetName = buffer;
1658 buffer += MultiByteToWideChar(CP_ACP, 0, TargetInformation->TargetName, -1,
1659 TargetInformationW->TargetName, end - buffer);
1660 } else
1661 TargetInformationW->TargetName = NULL;
1663 if (TargetInformation->NetbiosServerName)
1665 TargetInformationW->NetbiosServerName = buffer;
1666 buffer += MultiByteToWideChar(CP_ACP, 0, TargetInformation->NetbiosServerName, -1,
1667 TargetInformationW->NetbiosServerName, end - buffer);
1668 } else
1669 TargetInformationW->NetbiosServerName = NULL;
1671 if (TargetInformation->DnsServerName)
1673 TargetInformationW->DnsServerName = buffer;
1674 buffer += MultiByteToWideChar(CP_ACP, 0, TargetInformation->DnsServerName, -1,
1675 TargetInformationW->DnsServerName, end - buffer);
1676 } else
1677 TargetInformationW->DnsServerName = NULL;
1679 if (TargetInformation->NetbiosDomainName)
1681 TargetInformationW->NetbiosDomainName = buffer;
1682 buffer += MultiByteToWideChar(CP_ACP, 0, TargetInformation->NetbiosDomainName, -1,
1683 TargetInformationW->NetbiosDomainName, end - buffer);
1684 } else
1685 TargetInformationW->NetbiosDomainName = NULL;
1687 if (TargetInformation->DnsDomainName)
1689 TargetInformationW->DnsDomainName = buffer;
1690 buffer += MultiByteToWideChar(CP_ACP, 0, TargetInformation->DnsDomainName, -1,
1691 TargetInformationW->DnsDomainName, end - buffer);
1692 } else
1693 TargetInformationW->DnsDomainName = NULL;
1695 if (TargetInformation->DnsTreeName)
1697 TargetInformationW->DnsTreeName = buffer;
1698 buffer += MultiByteToWideChar(CP_ACP, 0, TargetInformation->DnsTreeName, -1,
1699 TargetInformationW->DnsTreeName, end - buffer);
1700 } else
1701 TargetInformationW->DnsTreeName = NULL;
1703 if (TargetInformation->PackageName)
1705 TargetInformationW->PackageName = buffer;
1706 MultiByteToWideChar(CP_ACP, 0, TargetInformation->PackageName, -1,
1707 TargetInformationW->PackageName, end - buffer);
1708 } else
1709 TargetInformationW->PackageName = NULL;
1711 TargetInformationW->Flags = TargetInformation->Flags;
1712 TargetInformationW->CredTypeCount = TargetInformation->CredTypeCount;
1713 TargetInformationW->CredTypes = TargetInformation->CredTypes;
1715 ret = CredReadDomainCredentialsW(TargetInformationW, Flags, Size, &CredentialsW);
1717 HeapFree(GetProcessHeap(), 0, TargetInformationW);
1719 if (ret)
1721 char *buf;
1722 INT needed;
1724 len = *Size * sizeof(PCREDENTIALA);
1725 for (i = 0; i < *Size; i++)
1726 len += convert_PCREDENTIALW_to_PCREDENTIALA(CredentialsW[i], NULL, 0);
1728 *Credentials = HeapAlloc(GetProcessHeap(), 0, len);
1729 if (!*Credentials)
1731 CredFree(CredentialsW);
1732 SetLastError(ERROR_OUTOFMEMORY);
1733 return FALSE;
1736 buf = (char *)&(*Credentials)[*Size];
1737 len -= *Size * sizeof(PCREDENTIALA);
1738 for (i = 0; i < *Size; i++)
1740 (*Credentials)[i] = (PCREDENTIALA)buf;
1741 needed = convert_PCREDENTIALW_to_PCREDENTIALA(CredentialsW[i], (*Credentials)[i], len);
1742 buf += needed;
1743 len -= needed;
1746 CredFree(CredentialsW);
1748 return ret;
1751 /******************************************************************************
1752 * CredReadDomainCredentialsW [ADVAPI32.@]
1754 BOOL WINAPI CredReadDomainCredentialsW(PCREDENTIAL_TARGET_INFORMATIONW TargetInformation, DWORD Flags,
1755 DWORD *Size, PCREDENTIALW **Credentials)
1757 FIXME("(%p, 0x%x, %p, %p) stub\n", TargetInformation, Flags, Size, Credentials);
1759 /* follow Windows behavior - do not test for NULL, initialize early */
1760 *Size = 0;
1761 *Credentials = NULL;
1762 if (!TargetInformation)
1764 SetLastError(ERROR_INVALID_PARAMETER);
1765 return FALSE;
1768 SetLastError(ERROR_NOT_FOUND);
1769 return FALSE;
1772 /******************************************************************************
1773 * CredWriteA [ADVAPI32.@]
1775 BOOL WINAPI CredWriteA(PCREDENTIALA Credential, DWORD Flags)
1777 BOOL ret;
1778 INT len;
1779 PCREDENTIALW CredentialW;
1781 TRACE("(%p, 0x%x)\n", Credential, Flags);
1783 if (!Credential || !Credential->TargetName)
1785 SetLastError(ERROR_INVALID_PARAMETER);
1786 return FALSE;
1789 len = convert_PCREDENTIALA_to_PCREDENTIALW(Credential, NULL, 0);
1790 CredentialW = HeapAlloc(GetProcessHeap(), 0, len);
1791 if (!CredentialW)
1793 SetLastError(ERROR_OUTOFMEMORY);
1794 return FALSE;
1797 convert_PCREDENTIALA_to_PCREDENTIALW(Credential, CredentialW, len);
1799 ret = CredWriteW(CredentialW, Flags);
1801 HeapFree(GetProcessHeap(), 0, CredentialW);
1803 return ret;
1806 /******************************************************************************
1807 * CredWriteW [ADVAPI32.@]
1809 BOOL WINAPI CredWriteW(PCREDENTIALW Credential, DWORD Flags)
1811 HKEY hkeyMgr;
1812 HKEY hkeyCred;
1813 DWORD ret;
1814 LPWSTR key_name;
1815 BYTE key_data[KEY_SIZE];
1817 TRACE("(%p, 0x%x)\n", Credential, Flags);
1819 if (!Credential || !Credential->TargetName)
1821 SetLastError(ERROR_INVALID_PARAMETER);
1822 return FALSE;
1825 if (Flags & ~CRED_PRESERVE_CREDENTIAL_BLOB)
1827 FIXME("unhandled flags 0x%x\n", Flags);
1828 SetLastError(ERROR_INVALID_FLAGS);
1829 return FALSE;
1832 if (Credential->Type != CRED_TYPE_GENERIC && Credential->Type != CRED_TYPE_DOMAIN_PASSWORD)
1834 FIXME("unhandled type %d\n", Credential->Type);
1835 SetLastError(ERROR_INVALID_PARAMETER);
1836 return FALSE;
1839 TRACE("Credential->Flags = 0x%08x\n", Credential->Flags);
1840 TRACE("Credential->Type = %u\n", Credential->Type);
1841 TRACE("Credential->TargetName = %s\n", debugstr_w(Credential->TargetName));
1842 TRACE("Credential->Comment = %s\n", debugstr_w(Credential->Comment));
1843 TRACE("Credential->Persist = %u\n", Credential->Persist);
1844 TRACE("Credential->TargetAlias = %s\n", debugstr_w(Credential->TargetAlias));
1845 TRACE("Credential->UserName = %s\n", debugstr_w(Credential->UserName));
1847 if (Credential->Type == CRED_TYPE_DOMAIN_PASSWORD)
1849 if (!Credential->UserName ||
1850 (Credential->Persist == CRED_PERSIST_ENTERPRISE &&
1851 (!strchrW(Credential->UserName, '\\') && !strchrW(Credential->UserName, '@'))))
1853 ERR("bad username %s\n", debugstr_w(Credential->UserName));
1854 SetLastError(ERROR_BAD_USERNAME);
1855 return FALSE;
1859 #ifdef __APPLE__
1860 if (!Credential->AttributeCount &&
1861 Credential->Type == CRED_TYPE_DOMAIN_PASSWORD &&
1862 (Credential->Persist == CRED_PERSIST_LOCAL_MACHINE || Credential->Persist == CRED_PERSIST_ENTERPRISE))
1864 ret = mac_write_credential(Credential, Flags & CRED_PRESERVE_CREDENTIAL_BLOB);
1865 if (ret != ERROR_SUCCESS)
1867 SetLastError(ret);
1868 return FALSE;
1870 return TRUE;
1872 #endif
1874 ret = open_cred_mgr_key(&hkeyMgr, FALSE);
1875 if (ret != ERROR_SUCCESS)
1877 WARN("couldn't open/create manager key, error %d\n", ret);
1878 SetLastError(ERROR_NO_SUCH_LOGON_SESSION);
1879 return FALSE;
1882 ret = get_cred_mgr_encryption_key(hkeyMgr, key_data);
1883 if (ret != ERROR_SUCCESS)
1885 RegCloseKey(hkeyMgr);
1886 SetLastError(ret);
1887 return FALSE;
1890 key_name = get_key_name_for_target(Credential->TargetName, Credential->Type);
1891 ret = RegCreateKeyExW(hkeyMgr, key_name, 0, NULL,
1892 Credential->Persist == CRED_PERSIST_SESSION ? REG_OPTION_VOLATILE : REG_OPTION_NON_VOLATILE,
1893 KEY_READ|KEY_WRITE, NULL, &hkeyCred, NULL);
1894 HeapFree(GetProcessHeap(), 0, key_name);
1895 if (ret != ERROR_SUCCESS)
1897 TRACE("credentials for target name %s not found\n",
1898 debugstr_w(Credential->TargetName));
1899 SetLastError(ERROR_NOT_FOUND);
1900 return FALSE;
1903 ret = registry_write_credential(hkeyCred, Credential, key_data,
1904 Flags & CRED_PRESERVE_CREDENTIAL_BLOB);
1906 RegCloseKey(hkeyCred);
1907 RegCloseKey(hkeyMgr);
1909 if (ret != ERROR_SUCCESS)
1911 SetLastError(ret);
1912 return FALSE;
1914 return TRUE;
1917 /******************************************************************************
1918 * CredGetSessionTypes [ADVAPI32.@]
1920 WINADVAPI BOOL WINAPI CredGetSessionTypes(DWORD persistCount, LPDWORD persists)
1922 TRACE("(%u, %p)\n", persistCount, persists);
1924 memset(persists, CRED_PERSIST_NONE, persistCount*sizeof(*persists));
1925 if (CRED_TYPE_GENERIC < persistCount)
1927 persists[CRED_TYPE_GENERIC] = CRED_PERSIST_ENTERPRISE;
1929 if (CRED_TYPE_DOMAIN_PASSWORD < persistCount)
1931 persists[CRED_TYPE_DOMAIN_PASSWORD] = CRED_PERSIST_ENTERPRISE;
1934 return TRUE;
1937 /******************************************************************************
1938 * CredMarshalCredentialA [ADVAPI32.@]
1940 BOOL WINAPI CredMarshalCredentialA( CRED_MARSHAL_TYPE type, PVOID cred, LPSTR *out )
1942 BOOL ret;
1943 WCHAR *outW;
1945 TRACE("%u, %p, %p\n", type, cred, out);
1947 if ((ret = CredMarshalCredentialW( type, cred, &outW )))
1949 int len = WideCharToMultiByte( CP_ACP, 0, outW, -1, NULL, 0, NULL, NULL );
1950 if (!(*out = HeapAlloc( GetProcessHeap(), 0, len )))
1952 HeapFree( GetProcessHeap(), 0, outW );
1953 return FALSE;
1955 WideCharToMultiByte( CP_ACP, 0, outW, -1, *out, len, NULL, NULL );
1956 HeapFree( GetProcessHeap(), 0, outW );
1958 return ret;
1961 static UINT cred_encode( const char *bin, unsigned int len, WCHAR *cred )
1963 static char enc[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789#-";
1964 UINT n = 0, x;
1966 while (len > 0)
1968 cred[n++] = enc[bin[0] & 0x3f];
1969 x = (bin[0] & 0xc0) >> 6;
1970 if (len == 1)
1972 cred[n++] = enc[x];
1973 break;
1975 cred[n++] = enc[((bin[1] & 0xf) << 2) | x];
1976 x = (bin[1] & 0xf0) >> 4;
1977 if (len == 2)
1979 cred[n++] = enc[x];
1980 break;
1982 cred[n++] = enc[((bin[2] & 0x3) << 4) | x];
1983 cred[n++] = enc[(bin[2] & 0xfc) >> 2];
1984 bin += 3;
1985 len -= 3;
1987 return n;
1990 /******************************************************************************
1991 * CredMarshalCredentialW [ADVAPI32.@]
1993 BOOL WINAPI CredMarshalCredentialW( CRED_MARSHAL_TYPE type, PVOID cred, LPWSTR *out )
1995 CERT_CREDENTIAL_INFO *cert = cred;
1996 USERNAME_TARGET_CREDENTIAL_INFO *target = cred;
1997 DWORD len, size;
1998 WCHAR *p;
2000 TRACE("%u, %p, %p\n", type, cred, out);
2002 if (!cred || (type == CertCredential && cert->cbSize < sizeof(*cert)) ||
2003 (type != CertCredential && type != UsernameTargetCredential && type != BinaryBlobCredential) ||
2004 (type == UsernameTargetCredential && (!target->UserName || !target->UserName[0])))
2006 SetLastError( ERROR_INVALID_PARAMETER );
2007 return FALSE;
2009 switch (type)
2011 case CertCredential:
2013 char hash[CERT_HASH_LENGTH + 2];
2015 memcpy( hash, cert->rgbHashOfCert, sizeof(cert->rgbHashOfCert) );
2016 memset( hash + sizeof(cert->rgbHashOfCert), 0, sizeof(hash) - sizeof(cert->rgbHashOfCert) );
2018 size = sizeof(hash) * 4 / 3;
2019 if (!(p = HeapAlloc( GetProcessHeap(), 0, (size + 4) * sizeof(WCHAR) ))) return FALSE;
2020 p[0] = '@';
2021 p[1] = '@';
2022 p[2] = 'A' + type;
2023 len = cred_encode( (const char *)hash, sizeof(hash), p + 3 );
2024 p[len] = 0;
2025 break;
2027 case UsernameTargetCredential:
2029 len = strlenW( target->UserName );
2030 size = (sizeof(DWORD) + len * sizeof(WCHAR) + 2) * 4 / 3;
2031 if (!(p = HeapAlloc( GetProcessHeap(), 0, (size + 4) * sizeof(WCHAR) ))) return FALSE;
2032 p[0] = '@';
2033 p[1] = '@';
2034 p[2] = 'A' + type;
2035 size = len * sizeof(WCHAR);
2036 len = cred_encode( (const char *)&size, sizeof(DWORD), p + 3 );
2037 len += cred_encode( (const char *)target->UserName, size, p + 3 + len );
2038 p[len + 3] = 0;
2039 break;
2041 case BinaryBlobCredential:
2042 FIXME("BinaryBlobCredential not implemented\n");
2043 return FALSE;
2044 default:
2045 return FALSE;
2047 *out = p;
2048 return TRUE;
2051 /******************************************************************************
2052 * CredUnmarshalCredentialA [ADVAPI32.@]
2054 BOOL WINAPI CredUnmarshalCredentialA( LPCSTR cred, PCRED_MARSHAL_TYPE type, PVOID *out )
2056 BOOL ret;
2057 WCHAR *credW = NULL;
2059 TRACE("%s, %p, %p\n", debugstr_a(cred), type, out);
2061 if (cred)
2063 int len = MultiByteToWideChar( CP_ACP, 0, cred, -1, NULL, 0 );
2064 if (!(credW = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) ))) return FALSE;
2065 MultiByteToWideChar( CP_ACP, 0, cred, -1, credW, len );
2067 ret = CredUnmarshalCredentialW( credW, type, out );
2068 HeapFree( GetProcessHeap(), 0, credW );
2069 return ret;
2072 static inline char char_decode( WCHAR c )
2074 if (c >= 'A' && c <= 'Z') return c - 'A';
2075 if (c >= 'a' && c <= 'z') return c - 'a' + 26;
2076 if (c >= '0' && c <= '9') return c - '0' + 52;
2077 if (c == '#') return 62;
2078 if (c == '-') return 63;
2079 return 64;
2082 static BOOL cred_decode( const WCHAR *cred, unsigned int len, char *buf )
2084 unsigned int i = 0;
2085 char c0, c1, c2, c3;
2086 const WCHAR *p = cred;
2088 while (len >= 4)
2090 if ((c0 = char_decode( p[0] )) > 63) return FALSE;
2091 if ((c1 = char_decode( p[1] )) > 63) return FALSE;
2092 if ((c2 = char_decode( p[2] )) > 63) return FALSE;
2093 if ((c3 = char_decode( p[3] )) > 63) return FALSE;
2095 buf[i + 0] = (c1 << 6) | c0;
2096 buf[i + 1] = (c2 << 4) | (c1 >> 2);
2097 buf[i + 2] = (c3 << 2) | (c2 >> 4);
2098 len -= 4;
2099 i += 3;
2100 p += 4;
2102 if (len == 3)
2104 if ((c0 = char_decode( p[0] )) > 63) return FALSE;
2105 if ((c1 = char_decode( p[1] )) > 63) return FALSE;
2106 if ((c2 = char_decode( p[2] )) > 63) return FALSE;
2108 buf[i + 0] = (c1 << 6) | c0;
2109 buf[i + 1] = (c2 << 4) | (c1 >> 2);
2110 buf[i + 2] = c2 >> 4;
2112 else if (len == 2)
2114 if ((c0 = char_decode( p[0] )) > 63) return FALSE;
2115 if ((c1 = char_decode( p[1] )) > 63) return FALSE;
2117 buf[i + 0] = (c1 << 6) | c0;
2118 buf[i + 1] = c1 >> 2;
2119 buf[i + 2] = 0;
2121 else if (len == 1)
2123 if ((c0 = char_decode( p[0] )) > 63) return FALSE;
2125 buf[i + 0] = c0;
2126 buf[i + 1] = 0;
2127 buf[i + 2] = 0;
2129 return TRUE;
2132 /******************************************************************************
2133 * CredUnmarshalCredentialW [ADVAPI32.@]
2135 BOOL WINAPI CredUnmarshalCredentialW( LPCWSTR cred, PCRED_MARSHAL_TYPE type, PVOID *out )
2137 unsigned int len, buflen;
2139 TRACE("%s, %p, %p\n", debugstr_w(cred), type, out);
2141 if (!cred || cred[0] != '@' || cred[1] != '@' || !cred[2] || !cred[3])
2143 SetLastError( ERROR_INVALID_PARAMETER );
2144 return FALSE;
2146 len = strlenW( cred + 3 );
2147 switch (cred[2] - 'A')
2149 case CertCredential:
2151 char hash[CERT_HASH_LENGTH + 2];
2152 CERT_CREDENTIAL_INFO *cert;
2154 if (len != 27 || !cred_decode( cred + 3, len, hash ))
2156 SetLastError( ERROR_INVALID_PARAMETER );
2157 return FALSE;
2159 if (!(cert = HeapAlloc( GetProcessHeap(), 0, sizeof(*cert) ))) return FALSE;
2160 memcpy( cert->rgbHashOfCert, hash, sizeof(cert->rgbHashOfCert) );
2161 cert->cbSize = sizeof(*cert);
2162 *type = CertCredential;
2163 *out = cert;
2164 break;
2166 case UsernameTargetCredential:
2168 USERNAME_TARGET_CREDENTIAL_INFO *target;
2169 ULONGLONG size = 0;
2171 if (len < 9 || !cred_decode( cred + 3, 6, (char *)&size ) ||
2172 !size || size % sizeof(WCHAR) || size > INT_MAX)
2174 SetLastError( ERROR_INVALID_PARAMETER );
2175 return FALSE;
2177 buflen = sizeof(*target) + size + sizeof(WCHAR);
2178 if (!(target = HeapAlloc( GetProcessHeap(), 0, buflen ))) return FALSE;
2179 if (!cred_decode( cred + 9, len - 6, (char *)(target + 1) ))
2181 HeapFree( GetProcessHeap(), 0, target );
2182 return FALSE;
2184 target->UserName = (WCHAR *)(target + 1);
2185 target->UserName[size / sizeof(WCHAR)] = 0;
2186 *type = UsernameTargetCredential;
2187 *out = target;
2188 break;
2190 case BinaryBlobCredential:
2191 FIXME("BinaryBlobCredential not implemented\n");
2192 return FALSE;
2193 default:
2194 WARN("unhandled type %u\n", cred[2] - 'A');
2195 return FALSE;
2197 return TRUE;
2200 /******************************************************************************
2201 * CredIsMarshaledCredentialW [ADVAPI32.@]
2203 * Check, if the name parameter is a marshaled credential, hash or binary blob
2205 * PARAMS
2206 * name the name to check
2208 * RETURNS
2209 * TRUE: the name parameter is a marshaled credential, hash or binary blob
2210 * FALSE: the name is a plain username
2212 BOOL WINAPI CredIsMarshaledCredentialW(LPCWSTR name)
2214 TRACE("(%s)\n", debugstr_w(name));
2216 if (name && name[0] == '@' && name[1] == '@' && name[2] > 'A' && name[3])
2218 char hash[CERT_HASH_LENGTH + 2];
2219 int len = strlenW(name + 3 );
2220 DWORD size;
2222 if ((name[2] - 'A') == CertCredential && (len == 27) && cred_decode(name + 3, len, hash))
2223 return TRUE;
2225 if (((name[2] - 'A') == UsernameTargetCredential) &&
2226 (len >= 9) && cred_decode(name + 3, 6, (char *)&size) && size)
2227 return TRUE;
2229 if ((name[2] - 'A') == BinaryBlobCredential)
2230 FIXME("BinaryBlobCredential not checked\n");
2232 if ((name[2] - 'A') > BinaryBlobCredential)
2233 TRACE("unknown type: %d\n", (name[2] - 'A'));
2236 SetLastError(ERROR_INVALID_PARAMETER);
2237 return FALSE;
2240 /******************************************************************************
2241 * CredIsMarshaledCredentialA [ADVAPI32.@]
2243 * See CredIsMarshaledCredentialW
2246 BOOL WINAPI CredIsMarshaledCredentialA(LPCSTR name)
2248 LPWSTR nameW = NULL;
2249 BOOL res;
2250 int len;
2252 TRACE("(%s)\n", debugstr_a(name));
2254 if (name)
2256 len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
2257 nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
2258 MultiByteToWideChar(CP_ACP, 0, name, -1, nameW, len);
2261 res = CredIsMarshaledCredentialW(nameW);
2262 HeapFree(GetProcessHeap(), 0, nameW);
2263 return res;