gdi32: Add a SetBoundsRect driver entry point.
[wine/multimedia.git] / dlls / advapi32 / cred.c
blob432eb5c8570f29d995983b3a41502e0c6596dbab
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>
24 #ifdef __APPLE__
25 # include <Security/SecKeychain.h>
26 # include <Security/SecKeychainItem.h>
27 # include <Security/SecKeychainSearch.h>
28 #endif
30 #include "windef.h"
31 #include "winbase.h"
32 #include "winreg.h"
33 #include "wincred.h"
34 #include "winternl.h"
36 #include "crypt.h"
38 #include "wine/unicode.h"
39 #include "wine/debug.h"
41 WINE_DEFAULT_DEBUG_CHANNEL(cred);
43 /* the size of the ARC4 key used to encrypt the password data */
44 #define KEY_SIZE 8
46 static const WCHAR wszCredentialManagerKey[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\',
47 'C','r','e','d','e','n','t','i','a','l',' ','M','a','n','a','g','e','r',0};
48 static const WCHAR wszEncryptionKeyValue[] = {'E','n','c','r','y','p','t','i','o','n','K','e','y',0};
50 static const WCHAR wszFlagsValue[] = {'F','l','a','g','s',0};
51 static const WCHAR wszTypeValue[] = {'T','y','p','e',0};
52 static const WCHAR wszCommentValue[] = {'C','o','m','m','e','n','t',0};
53 static const WCHAR wszLastWrittenValue[] = {'L','a','s','t','W','r','i','t','t','e','n',0};
54 static const WCHAR wszPersistValue[] = {'P','e','r','s','i','s','t',0};
55 static const WCHAR wszTargetAliasValue[] = {'T','a','r','g','e','t','A','l','i','a','s',0};
56 static const WCHAR wszUserNameValue[] = {'U','s','e','r','N','a','m','e',0};
57 static const WCHAR wszPasswordValue[] = {'P','a','s','s','w','o','r','d',0};
59 static DWORD read_credential_blob(HKEY hkey, const BYTE key_data[KEY_SIZE],
60 LPBYTE credential_blob,
61 DWORD *credential_blob_size)
63 DWORD ret;
64 DWORD type;
66 *credential_blob_size = 0;
67 ret = RegQueryValueExW(hkey, wszPasswordValue, 0, &type, NULL, credential_blob_size);
68 if (ret != ERROR_SUCCESS)
69 return ret;
70 else if (type != REG_BINARY)
71 return ERROR_REGISTRY_CORRUPT;
72 if (credential_blob)
74 struct ustring data;
75 struct ustring key;
77 ret = RegQueryValueExW(hkey, wszPasswordValue, 0, &type, credential_blob,
78 credential_blob_size);
79 if (ret != ERROR_SUCCESS)
80 return ret;
81 else if (type != REG_BINARY)
82 return ERROR_REGISTRY_CORRUPT;
84 key.Length = key.MaximumLength = KEY_SIZE;
85 key.Buffer = (unsigned char *)key_data;
87 data.Length = data.MaximumLength = *credential_blob_size;
88 data.Buffer = credential_blob;
89 SystemFunction032(&data, &key);
91 return ERROR_SUCCESS;
94 static DWORD registry_read_credential(HKEY hkey, PCREDENTIALW credential,
95 const BYTE key_data[KEY_SIZE],
96 char *buffer, DWORD *len)
98 DWORD type;
99 DWORD ret;
100 DWORD count;
102 ret = RegQueryValueExW(hkey, NULL, 0, &type, NULL, &count);
103 if (ret != ERROR_SUCCESS)
104 return ret;
105 else if (type != REG_SZ)
106 return ERROR_REGISTRY_CORRUPT;
107 *len += count;
108 if (credential)
110 credential->TargetName = (LPWSTR)buffer;
111 ret = RegQueryValueExW(hkey, NULL, 0, &type, (LPVOID)credential->TargetName,
112 &count);
113 if (ret != ERROR_SUCCESS || type != REG_SZ) return ret;
114 buffer += count;
117 ret = RegQueryValueExW(hkey, wszCommentValue, 0, &type, NULL, &count);
118 if (ret != ERROR_FILE_NOT_FOUND && ret != ERROR_SUCCESS)
119 return ret;
120 else if (type != REG_SZ)
121 return ERROR_REGISTRY_CORRUPT;
122 *len += count;
123 if (credential)
125 credential->Comment = (LPWSTR)buffer;
126 ret = RegQueryValueExW(hkey, wszCommentValue, 0, &type, (LPVOID)credential->Comment,
127 &count);
128 if (ret == ERROR_FILE_NOT_FOUND)
129 credential->Comment = NULL;
130 else if (ret != ERROR_SUCCESS)
131 return ret;
132 else if (type != REG_SZ)
133 return ERROR_REGISTRY_CORRUPT;
134 else
135 buffer += count;
138 ret = RegQueryValueExW(hkey, wszTargetAliasValue, 0, &type, NULL, &count);
139 if (ret != ERROR_FILE_NOT_FOUND && ret != ERROR_SUCCESS)
140 return ret;
141 else if (type != REG_SZ)
142 return ERROR_REGISTRY_CORRUPT;
143 *len += count;
144 if (credential)
146 credential->TargetAlias = (LPWSTR)buffer;
147 ret = RegQueryValueExW(hkey, wszTargetAliasValue, 0, &type, (LPVOID)credential->TargetAlias,
148 &count);
149 if (ret == ERROR_FILE_NOT_FOUND)
150 credential->TargetAlias = NULL;
151 else if (ret != ERROR_SUCCESS)
152 return ret;
153 else if (type != REG_SZ)
154 return ERROR_REGISTRY_CORRUPT;
155 else
156 buffer += count;
159 ret = RegQueryValueExW(hkey, wszUserNameValue, 0, &type, NULL, &count);
160 if (ret != ERROR_FILE_NOT_FOUND && ret != ERROR_SUCCESS)
161 return ret;
162 else if (type != REG_SZ)
163 return ERROR_REGISTRY_CORRUPT;
164 *len += count;
165 if (credential)
167 credential->UserName = (LPWSTR)buffer;
168 ret = RegQueryValueExW(hkey, wszUserNameValue, 0, &type, (LPVOID)credential->UserName,
169 &count);
170 if (ret == ERROR_FILE_NOT_FOUND)
171 credential->UserName = NULL;
172 else if (ret != ERROR_SUCCESS)
173 return ret;
174 else if (type != REG_SZ)
175 return ERROR_REGISTRY_CORRUPT;
176 else
177 buffer += count;
180 ret = read_credential_blob(hkey, key_data, NULL, &count);
181 if (ret != ERROR_FILE_NOT_FOUND && ret != ERROR_SUCCESS)
182 return ret;
183 *len += count;
184 if (credential)
186 credential->CredentialBlob = (LPBYTE)buffer;
187 ret = read_credential_blob(hkey, key_data, credential->CredentialBlob, &count);
188 if (ret == ERROR_FILE_NOT_FOUND)
189 credential->CredentialBlob = NULL;
190 else if (ret != ERROR_SUCCESS)
191 return ret;
192 credential->CredentialBlobSize = count;
193 buffer += 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 return ERROR_NOT_FOUND;
279 if (buffer)
281 credential->Flags = 0;
282 credential->Type = CRED_TYPE_DOMAIN_PASSWORD;
283 credential->TargetName = NULL;
284 credential->Comment = NULL;
285 memset(&credential->LastWritten, 0, sizeof(credential->LastWritten));
286 credential->CredentialBlobSize = 0;
287 credential->CredentialBlob = NULL;
288 credential->Persist = CRED_PERSIST_LOCAL_MACHINE;
289 credential->AttributeCount = 0;
290 credential->Attributes = NULL;
291 credential->TargetAlias = NULL;
292 credential->UserName = NULL;
294 for (i = 0; i < attr_list->count; i++)
296 switch (attr_list->attr[i].tag)
298 case kSecServerItemAttr:
299 TRACE("kSecServerItemAttr: %.*s\n", (int)attr_list->attr[i].length,
300 (char *)attr_list->attr[i].data);
301 if (!attr_list->attr[i].data) continue;
302 if (buffer)
304 INT str_len;
305 credential->TargetName = (LPWSTR)buffer;
306 str_len = MultiByteToWideChar(CP_UTF8, 0, attr_list->attr[i].data,
307 attr_list->attr[i].length, (LPWSTR)buffer, 0xffff);
308 credential->TargetName[str_len] = '\0';
309 buffer += (str_len + 1) * sizeof(WCHAR);
310 *len += (str_len + 1) * sizeof(WCHAR);
312 else
314 INT str_len;
315 str_len = MultiByteToWideChar(CP_UTF8, 0, attr_list->attr[i].data,
316 attr_list->attr[i].length, NULL, 0);
317 *len += (str_len + 1) * sizeof(WCHAR);
319 break;
320 case kSecAccountItemAttr:
322 INT str_len;
323 TRACE("kSecAccountItemAttr: %.*s\n", (int)attr_list->attr[i].length,
324 (char *)attr_list->attr[i].data);
325 if (!attr_list->attr[i].data) continue;
326 str_len = MultiByteToWideChar(CP_UTF8, 0, attr_list->attr[i].data,
327 attr_list->attr[i].length, NULL, 0);
328 user = HeapAlloc(GetProcessHeap(), 0, (str_len + 1) * sizeof(WCHAR));
329 MultiByteToWideChar(CP_UTF8, 0, attr_list->attr[i].data,
330 attr_list->attr[i].length, user, str_len);
331 user[str_len] = '\0';
332 break;
334 case kSecCommentItemAttr:
335 TRACE("kSecCommentItemAttr: %.*s\n", (int)attr_list->attr[i].length,
336 (char *)attr_list->attr[i].data);
337 if (!attr_list->attr[i].data) continue;
338 if (buffer)
340 INT str_len;
341 credential->Comment = (LPWSTR)buffer;
342 str_len = MultiByteToWideChar(CP_UTF8, 0, attr_list->attr[i].data,
343 attr_list->attr[i].length, (LPWSTR)buffer, 0xffff);
344 credential->Comment[str_len] = '\0';
345 buffer += (str_len + 1) * sizeof(WCHAR);
346 *len += (str_len + 1) * sizeof(WCHAR);
348 else
350 INT str_len;
351 str_len = MultiByteToWideChar(CP_UTF8, 0, attr_list->attr[i].data,
352 attr_list->attr[i].length, NULL, 0);
353 *len += (str_len + 1) * sizeof(WCHAR);
355 break;
356 case kSecSecurityDomainItemAttr:
358 INT str_len;
359 TRACE("kSecSecurityDomainItemAttr: %.*s\n", (int)attr_list->attr[i].length,
360 (char *)attr_list->attr[i].data);
361 if (!attr_list->attr[i].data) continue;
362 str_len = MultiByteToWideChar(CP_UTF8, 0, attr_list->attr[i].data,
363 attr_list->attr[i].length, NULL, 0);
364 domain = HeapAlloc(GetProcessHeap(), 0, (str_len + 1) * sizeof(WCHAR));
365 MultiByteToWideChar(CP_UTF8, 0, attr_list->attr[i].data,
366 attr_list->attr[i].length, domain, str_len);
367 domain[str_len] = '\0';
368 break;
370 case kSecCreationDateItemAttr:
371 TRACE("kSecCreationDateItemAttr: %.*s\n", (int)attr_list->attr[i].length,
372 (char *)attr_list->attr[i].data);
373 if (buffer)
375 LARGE_INTEGER win_time;
376 struct tm tm;
377 time_t time;
378 memset(&tm, 0, sizeof(tm));
379 strptime(attr_list->attr[i].data, "%Y%m%d%H%M%SZ", &tm);
380 time = mktime(&tm);
381 RtlSecondsSince1970ToTime(time, &win_time);
382 credential->LastWritten.dwLowDateTime = win_time.u.LowPart;
383 credential->LastWritten.dwHighDateTime = win_time.u.HighPart;
385 break;
389 if (user)
391 INT str_len;
392 if (buffer)
393 credential->UserName = (LPWSTR)buffer;
394 if (domain)
396 str_len = strlenW(domain);
397 *len += (str_len + 1) * sizeof(WCHAR);
398 if (buffer)
400 memcpy(credential->UserName, domain, str_len * sizeof(WCHAR));
401 /* FIXME: figure out when to use an '@' */
402 credential->UserName[str_len] = '\\';
403 buffer += (str_len + 1) * sizeof(WCHAR);
406 str_len = strlenW(user);
407 *len += (str_len + 1) * sizeof(WCHAR);
408 if (buffer)
410 memcpy(buffer, user, (str_len + 1) * sizeof(WCHAR));
411 buffer += (str_len + 1) * sizeof(WCHAR);
412 TRACE("UserName = %s\n", debugstr_w(credential->UserName));
415 HeapFree(GetProcessHeap(), 0, user);
416 HeapFree(GetProcessHeap(), 0, domain);
418 if (cred_blob)
420 if (buffer)
422 INT str_len;
423 credential->CredentialBlob = (BYTE *)buffer;
424 str_len = MultiByteToWideChar(CP_UTF8, 0, cred_blob, cred_blob_len,
425 (LPWSTR)buffer, 0xffff);
426 credential->CredentialBlobSize = str_len * sizeof(WCHAR);
427 buffer += 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 return ERROR_SUCCESS;
628 #endif
630 static DWORD open_cred_mgr_key(HKEY *hkey, BOOL open_for_write)
632 return RegCreateKeyExW(HKEY_CURRENT_USER, wszCredentialManagerKey, 0,
633 NULL, REG_OPTION_NON_VOLATILE,
634 KEY_READ | (open_for_write ? KEY_WRITE : 0), NULL, hkey, NULL);
637 static DWORD get_cred_mgr_encryption_key(HKEY hkeyMgr, BYTE key_data[KEY_SIZE])
639 static const BYTE my_key_data[KEY_SIZE] = { 0 };
640 DWORD type;
641 DWORD count;
642 FILETIME ft;
643 ULONG seed;
644 ULONG value;
645 DWORD ret;
647 memcpy(key_data, my_key_data, KEY_SIZE);
649 count = KEY_SIZE;
650 ret = RegQueryValueExW(hkeyMgr, wszEncryptionKeyValue, NULL, &type, key_data,
651 &count);
652 if (ret == ERROR_SUCCESS)
654 if (type != REG_BINARY)
655 return ERROR_REGISTRY_CORRUPT;
656 else
657 return ERROR_SUCCESS;
659 if (ret != ERROR_FILE_NOT_FOUND)
660 return ret;
662 GetSystemTimeAsFileTime(&ft);
663 seed = ft.dwLowDateTime;
664 value = RtlUniform(&seed);
665 *(DWORD *)key_data = value;
666 seed = ft.dwHighDateTime;
667 value = RtlUniform(&seed);
668 *(DWORD *)(key_data + 4) = value;
670 ret = RegSetValueExW(hkeyMgr, wszEncryptionKeyValue, 0, REG_BINARY,
671 key_data, KEY_SIZE);
672 if (ret == ERROR_ACCESS_DENIED)
674 ret = open_cred_mgr_key(&hkeyMgr, TRUE);
675 if (ret == ERROR_SUCCESS)
677 ret = RegSetValueExW(hkeyMgr, wszEncryptionKeyValue, 0, REG_BINARY,
678 key_data, KEY_SIZE);
679 RegCloseKey(hkeyMgr);
682 return ret;
685 static LPWSTR get_key_name_for_target(LPCWSTR target_name, DWORD type)
687 static const WCHAR wszGenericPrefix[] = {'G','e','n','e','r','i','c',':',' ',0};
688 static const WCHAR wszDomPasswdPrefix[] = {'D','o','m','P','a','s','s','w','d',':',' ',0};
689 INT len;
690 LPCWSTR prefix = NULL;
691 LPWSTR key_name, p;
693 len = strlenW(target_name);
694 if (type == CRED_TYPE_GENERIC)
696 prefix = wszGenericPrefix;
697 len += sizeof(wszGenericPrefix)/sizeof(wszGenericPrefix[0]);
699 else
701 prefix = wszDomPasswdPrefix;
702 len += sizeof(wszDomPasswdPrefix)/sizeof(wszDomPasswdPrefix[0]);
705 key_name = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
706 if (!key_name) return NULL;
708 strcpyW(key_name, prefix);
709 strcatW(key_name, target_name);
711 for (p = key_name; *p; p++)
712 if (*p == '\\') *p = '_';
714 return key_name;
717 static BOOL credential_matches_filter(HKEY hkeyCred, LPCWSTR filter)
719 LPWSTR target_name;
720 DWORD ret;
721 DWORD type;
722 DWORD count;
723 LPCWSTR p;
725 if (!filter) return TRUE;
727 ret = RegQueryValueExW(hkeyCred, NULL, 0, &type, NULL, &count);
728 if (ret != ERROR_SUCCESS)
729 return FALSE;
730 else if (type != REG_SZ)
731 return FALSE;
733 target_name = HeapAlloc(GetProcessHeap(), 0, count);
734 if (!target_name)
735 return FALSE;
736 ret = RegQueryValueExW(hkeyCred, NULL, 0, &type, (LPVOID)target_name, &count);
737 if (ret != ERROR_SUCCESS || type != REG_SZ)
739 HeapFree(GetProcessHeap(), 0, target_name);
740 return FALSE;
743 TRACE("comparing filter %s to target name %s\n", debugstr_w(filter),
744 debugstr_w(target_name));
746 p = strchrW(filter, '*');
747 ret = CompareStringW(GetThreadLocale(), 0, filter,
748 (p && !p[1] ? p - filter : -1), target_name,
749 (p && !p[1] ? p - filter : -1)) == CSTR_EQUAL;
751 HeapFree(GetProcessHeap(), 0, target_name);
752 return ret;
755 static DWORD registry_enumerate_credentials(HKEY hkeyMgr, LPCWSTR filter,
756 LPWSTR target_name,
757 DWORD target_name_len, const BYTE key_data[KEY_SIZE],
758 PCREDENTIALW *credentials, char **buffer,
759 DWORD *len, DWORD *count)
761 DWORD i;
762 DWORD ret;
763 for (i = 0;; i++)
765 HKEY hkeyCred;
766 ret = RegEnumKeyW(hkeyMgr, i, target_name, target_name_len+1);
767 if (ret == ERROR_NO_MORE_ITEMS)
769 ret = ERROR_SUCCESS;
770 break;
772 else if (ret != ERROR_SUCCESS)
774 ret = ERROR_SUCCESS;
775 continue;
777 TRACE("target_name = %s\n", debugstr_w(target_name));
778 ret = RegOpenKeyExW(hkeyMgr, target_name, 0, KEY_QUERY_VALUE, &hkeyCred);
779 if (ret != ERROR_SUCCESS)
781 ret = ERROR_SUCCESS;
782 continue;
784 if (!credential_matches_filter(hkeyCred, filter))
786 RegCloseKey(hkeyCred);
787 continue;
789 if (buffer)
791 *len = sizeof(CREDENTIALW);
792 credentials[*count] = (PCREDENTIALW)*buffer;
794 else
795 *len += sizeof(CREDENTIALW);
796 ret = registry_read_credential(hkeyCred, buffer ? credentials[*count] : NULL,
797 key_data, buffer ? *buffer + sizeof(CREDENTIALW) : NULL,
798 len);
799 RegCloseKey(hkeyCred);
800 if (ret != ERROR_SUCCESS) break;
801 if (buffer) *buffer += *len;
802 (*count)++;
804 return ret;
807 #ifdef __APPLE__
808 static DWORD mac_enumerate_credentials(LPCWSTR filter, PCREDENTIALW *credentials,
809 char *buffer, DWORD *len, DWORD *count)
811 SecKeychainSearchRef search;
812 SecKeychainItemRef item;
813 OSStatus status;
814 Boolean saved_user_interaction_allowed;
815 DWORD ret;
817 SecKeychainGetUserInteractionAllowed(&saved_user_interaction_allowed);
818 SecKeychainSetUserInteractionAllowed(false);
820 status = SecKeychainSearchCreateFromAttributes(NULL, kSecInternetPasswordItemClass, NULL, &search);
821 if (status == noErr)
823 while (SecKeychainSearchCopyNext(search, &item) == noErr)
825 SecKeychainAttributeInfo info;
826 SecKeychainAttributeList *attr_list;
827 UInt32 info_tags[] = { kSecServerItemAttr };
828 info.count = sizeof(info_tags)/sizeof(info_tags[0]);
829 info.tag = info_tags;
830 info.format = NULL;
831 status = SecKeychainItemCopyAttributesAndData(item, &info, NULL, &attr_list, NULL, NULL);
832 if (status != noErr)
834 WARN("SecKeychainItemCopyAttributesAndData returned status %ld\n", status);
835 continue;
837 if (buffer)
839 *len = sizeof(CREDENTIALW);
840 credentials[*count] = (PCREDENTIALW)buffer;
842 else
843 *len += sizeof(CREDENTIALW);
844 if (attr_list->count != 1 || attr_list->attr[0].tag != kSecServerItemAttr) continue;
845 TRACE("server item: %.*s\n", (int)attr_list->attr[0].length, (char *)attr_list->attr[0].data);
846 /* FIXME: filter based on attr_list->attr[0].data */
847 SecKeychainItemFreeAttributesAndData(attr_list, NULL);
848 ret = mac_read_credential_from_item(item, FALSE,
849 buffer ? credentials[*count] : NULL,
850 buffer ? buffer + sizeof(CREDENTIALW) : NULL,
851 len);
852 CFRelease(item);
853 if (ret == ERROR_SUCCESS)
855 (*count)++;
856 if (buffer) buffer += *len;
859 CFRelease(search);
861 else
862 ERR("SecKeychainSearchCreateFromAttributes returned status %ld\n", status);
863 SecKeychainSetUserInteractionAllowed(saved_user_interaction_allowed);
864 return ERROR_SUCCESS;
867 static DWORD mac_delete_credential(LPCWSTR TargetName)
869 OSStatus status;
870 SecKeychainSearchRef search;
871 status = SecKeychainSearchCreateFromAttributes(NULL, kSecInternetPasswordItemClass, NULL, &search);
872 if (status == noErr)
874 SecKeychainItemRef item;
875 while (SecKeychainSearchCopyNext(search, &item) == noErr)
877 SecKeychainAttributeInfo info;
878 SecKeychainAttributeList *attr_list;
879 UInt32 info_tags[] = { kSecServerItemAttr };
880 LPWSTR target_name;
881 INT str_len;
882 info.count = sizeof(info_tags)/sizeof(info_tags[0]);
883 info.tag = info_tags;
884 info.format = NULL;
885 status = SecKeychainItemCopyAttributesAndData(item, &info, NULL, &attr_list, NULL, NULL);
886 if (status != noErr)
888 WARN("SecKeychainItemCopyAttributesAndData returned status %ld\n", status);
889 continue;
891 if (attr_list->count != 1 || attr_list->attr[0].tag != kSecServerItemAttr)
893 CFRelease(item);
894 continue;
896 str_len = MultiByteToWideChar(CP_UTF8, 0, attr_list->attr[0].data, attr_list->attr[0].length, NULL, 0);
897 target_name = HeapAlloc(GetProcessHeap(), 0, (str_len + 1) * sizeof(WCHAR));
898 MultiByteToWideChar(CP_UTF8, 0, attr_list->attr[0].data, attr_list->attr[0].length, target_name, str_len);
899 /* nul terminate */
900 target_name[str_len] = '\0';
901 if (strcmpiW(TargetName, target_name))
903 CFRelease(item);
904 HeapFree(GetProcessHeap(), 0, target_name);
905 continue;
907 HeapFree(GetProcessHeap(), 0, target_name);
908 SecKeychainItemFreeAttributesAndData(attr_list, NULL);
909 SecKeychainItemDelete(item);
910 CFRelease(item);
911 CFRelease(search);
913 return ERROR_SUCCESS;
915 CFRelease(search);
917 return ERROR_NOT_FOUND;
919 #endif
921 /******************************************************************************
922 * convert_PCREDENTIALW_to_PCREDENTIALA [internal]
924 * convert a Credential struct from UNICODE to ANSI and return the needed size in Bytes
928 static INT convert_PCREDENTIALW_to_PCREDENTIALA(const CREDENTIALW *CredentialW, PCREDENTIALA CredentialA, DWORD len)
930 char *buffer;
931 INT string_len;
932 INT needed = sizeof(CREDENTIALA);
934 if (!CredentialA)
936 if (CredentialW->TargetName)
937 needed += WideCharToMultiByte(CP_ACP, 0, CredentialW->TargetName, -1, NULL, 0, NULL, NULL);
938 if (CredentialW->Comment)
939 needed += WideCharToMultiByte(CP_ACP, 0, CredentialW->Comment, -1, NULL, 0, NULL, NULL);
940 needed += CredentialW->CredentialBlobSize;
941 if (CredentialW->TargetAlias)
942 needed += WideCharToMultiByte(CP_ACP, 0, CredentialW->TargetAlias, -1, NULL, 0, NULL, NULL);
943 if (CredentialW->UserName)
944 needed += WideCharToMultiByte(CP_ACP, 0, CredentialW->UserName, -1, NULL, 0, NULL, NULL);
946 return needed;
950 buffer = (char *)CredentialA + sizeof(CREDENTIALA);
951 len -= sizeof(CREDENTIALA);
952 CredentialA->Flags = CredentialW->Flags;
953 CredentialA->Type = CredentialW->Type;
955 if (CredentialW->TargetName)
957 CredentialA->TargetName = buffer;
958 string_len = WideCharToMultiByte(CP_ACP, 0, CredentialW->TargetName, -1, buffer, len, NULL, NULL);
959 buffer += string_len;
960 needed += string_len;
961 len -= string_len;
963 else
964 CredentialA->TargetName = NULL;
965 if (CredentialW->Comment)
967 CredentialA->Comment = buffer;
968 string_len = WideCharToMultiByte(CP_ACP, 0, CredentialW->Comment, -1, buffer, len, NULL, NULL);
969 buffer += string_len;
970 needed += string_len;
971 len -= string_len;
973 else
974 CredentialA->Comment = NULL;
975 CredentialA->LastWritten = CredentialW->LastWritten;
976 CredentialA->CredentialBlobSize = CredentialW->CredentialBlobSize;
977 if (CredentialW->CredentialBlobSize && (CredentialW->CredentialBlobSize <= len))
979 CredentialA->CredentialBlob =(LPBYTE)buffer;
980 memcpy(CredentialA->CredentialBlob, CredentialW->CredentialBlob,
981 CredentialW->CredentialBlobSize);
982 buffer += CredentialW->CredentialBlobSize;
983 needed += CredentialW->CredentialBlobSize;
984 len -= CredentialW->CredentialBlobSize;
986 else
987 CredentialA->CredentialBlob = NULL;
988 CredentialA->Persist = CredentialW->Persist;
989 CredentialA->AttributeCount = 0;
990 CredentialA->Attributes = NULL; /* FIXME */
991 if (CredentialW->TargetAlias)
993 CredentialA->TargetAlias = buffer;
994 string_len = WideCharToMultiByte(CP_ACP, 0, CredentialW->TargetAlias, -1, buffer, len, NULL, NULL);
995 buffer += string_len;
996 needed += string_len;
997 len -= string_len;
999 else
1000 CredentialA->TargetAlias = NULL;
1001 if (CredentialW->UserName)
1003 CredentialA->UserName = buffer;
1004 string_len = WideCharToMultiByte(CP_ACP, 0, CredentialW->UserName, -1, buffer, len, NULL, NULL);
1005 needed += string_len;
1007 else
1008 CredentialA->UserName = NULL;
1010 return needed;
1013 /******************************************************************************
1014 * convert_PCREDENTIALA_to_PCREDENTIALW [internal]
1016 * convert a Credential struct from ANSI to UNICODE and return the needed size in Bytes
1019 static INT convert_PCREDENTIALA_to_PCREDENTIALW(const CREDENTIALA *CredentialA, PCREDENTIALW CredentialW, INT len)
1021 char *buffer;
1022 INT string_len;
1023 INT needed = sizeof(CREDENTIALW);
1025 if (!CredentialW)
1027 if (CredentialA->TargetName)
1028 needed += sizeof(WCHAR) * MultiByteToWideChar(CP_ACP, 0, CredentialA->TargetName, -1, NULL, 0);
1029 if (CredentialA->Comment)
1030 needed += sizeof(WCHAR) * MultiByteToWideChar(CP_ACP, 0, CredentialA->Comment, -1, NULL, 0);
1031 needed += CredentialA->CredentialBlobSize;
1032 if (CredentialA->TargetAlias)
1033 needed += sizeof(WCHAR) * MultiByteToWideChar(CP_ACP, 0, CredentialA->TargetAlias, -1, NULL, 0);
1034 if (CredentialA->UserName)
1035 needed += sizeof(WCHAR) * MultiByteToWideChar(CP_ACP, 0, CredentialA->UserName, -1, NULL, 0);
1037 return needed;
1040 buffer = (char *)CredentialW + sizeof(CREDENTIALW);
1041 len -= sizeof(CREDENTIALW);
1042 CredentialW->Flags = CredentialA->Flags;
1043 CredentialW->Type = CredentialA->Type;
1044 if (CredentialA->TargetName)
1046 CredentialW->TargetName = (LPWSTR)buffer;
1047 string_len = MultiByteToWideChar(CP_ACP, 0, CredentialA->TargetName, -1, CredentialW->TargetName, len / sizeof(WCHAR));
1048 buffer += sizeof(WCHAR) * string_len;
1049 needed += sizeof(WCHAR) * string_len;
1050 len -= sizeof(WCHAR) * string_len;
1052 else
1053 CredentialW->TargetName = NULL;
1054 if (CredentialA->Comment)
1056 CredentialW->Comment = (LPWSTR)buffer;
1057 string_len = MultiByteToWideChar(CP_ACP, 0, CredentialA->Comment, -1, CredentialW->Comment, len / sizeof(WCHAR));
1058 buffer += sizeof(WCHAR) * string_len;
1059 needed += sizeof(WCHAR) * string_len;
1060 len -= sizeof(WCHAR) * string_len;
1062 else
1063 CredentialW->Comment = NULL;
1064 CredentialW->LastWritten = CredentialA->LastWritten;
1065 CredentialW->CredentialBlobSize = CredentialA->CredentialBlobSize;
1066 if (CredentialA->CredentialBlobSize)
1068 CredentialW->CredentialBlob =(LPBYTE)buffer;
1069 memcpy(CredentialW->CredentialBlob, CredentialA->CredentialBlob,
1070 CredentialA->CredentialBlobSize);
1071 buffer += CredentialA->CredentialBlobSize;
1072 needed += CredentialA->CredentialBlobSize;
1073 len -= CredentialA->CredentialBlobSize;
1075 else
1076 CredentialW->CredentialBlob = NULL;
1077 CredentialW->Persist = CredentialA->Persist;
1078 CredentialW->AttributeCount = 0;
1079 CredentialW->Attributes = NULL; /* FIXME */
1080 if (CredentialA->TargetAlias)
1082 CredentialW->TargetAlias = (LPWSTR)buffer;
1083 string_len = MultiByteToWideChar(CP_ACP, 0, CredentialA->TargetAlias, -1, CredentialW->TargetAlias, len / sizeof(WCHAR));
1084 buffer += sizeof(WCHAR) * string_len;
1085 needed += sizeof(WCHAR) * string_len;
1086 len -= sizeof(WCHAR) * string_len;
1088 else
1089 CredentialW->TargetAlias = NULL;
1090 if (CredentialA->UserName)
1092 CredentialW->UserName = (LPWSTR)buffer;
1093 string_len = MultiByteToWideChar(CP_ACP, 0, CredentialA->UserName, -1, CredentialW->UserName, len / sizeof(WCHAR));
1094 needed += sizeof(WCHAR) * string_len;
1096 else
1097 CredentialW->UserName = NULL;
1099 return needed;
1102 /******************************************************************************
1103 * CredDeleteA [ADVAPI32.@]
1105 BOOL WINAPI CredDeleteA(LPCSTR TargetName, DWORD Type, DWORD Flags)
1107 LPWSTR TargetNameW;
1108 DWORD len;
1109 BOOL ret;
1111 TRACE("(%s, %d, 0x%x)\n", debugstr_a(TargetName), Type, Flags);
1113 if (!TargetName)
1115 SetLastError(ERROR_INVALID_PARAMETER);
1116 return FALSE;
1119 len = MultiByteToWideChar(CP_ACP, 0, TargetName, -1, NULL, 0);
1120 TargetNameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1121 if (!TargetNameW)
1123 SetLastError(ERROR_OUTOFMEMORY);
1124 return FALSE;
1126 MultiByteToWideChar(CP_ACP, 0, TargetName, -1, TargetNameW, len);
1128 ret = CredDeleteW(TargetNameW, Type, Flags);
1130 HeapFree(GetProcessHeap(), 0, TargetNameW);
1132 return ret;
1135 /******************************************************************************
1136 * CredDeleteW [ADVAPI32.@]
1138 BOOL WINAPI CredDeleteW(LPCWSTR TargetName, DWORD Type, DWORD Flags)
1140 HKEY hkeyMgr;
1141 DWORD ret;
1142 LPWSTR key_name;
1144 TRACE("(%s, %d, 0x%x)\n", debugstr_w(TargetName), Type, Flags);
1146 if (!TargetName)
1148 SetLastError(ERROR_INVALID_PARAMETER);
1149 return FALSE;
1152 if (Type != CRED_TYPE_GENERIC && Type != CRED_TYPE_DOMAIN_PASSWORD)
1154 FIXME("unhandled type %d\n", Type);
1155 SetLastError(ERROR_INVALID_PARAMETER);
1156 return FALSE;
1159 if (Flags)
1161 FIXME("unhandled flags 0x%x\n", Flags);
1162 SetLastError(ERROR_INVALID_FLAGS);
1163 return FALSE;
1166 #ifdef __APPLE__
1167 if (Type == CRED_TYPE_DOMAIN_PASSWORD)
1169 ret = mac_delete_credential(TargetName);
1170 if (ret == ERROR_SUCCESS)
1171 return TRUE;
1173 #endif
1175 ret = open_cred_mgr_key(&hkeyMgr, TRUE);
1176 if (ret != ERROR_SUCCESS)
1178 WARN("couldn't open/create manager key, error %d\n", ret);
1179 SetLastError(ERROR_NO_SUCH_LOGON_SESSION);
1180 return FALSE;
1183 key_name = get_key_name_for_target(TargetName, Type);
1184 ret = RegDeleteKeyW(hkeyMgr, key_name);
1185 HeapFree(GetProcessHeap(), 0, key_name);
1186 RegCloseKey(hkeyMgr);
1187 if (ret != ERROR_SUCCESS)
1189 SetLastError(ERROR_NOT_FOUND);
1190 return FALSE;
1193 return TRUE;
1196 /******************************************************************************
1197 * CredEnumerateA [ADVAPI32.@]
1199 BOOL WINAPI CredEnumerateA(LPCSTR Filter, DWORD Flags, DWORD *Count,
1200 PCREDENTIALA **Credentials)
1202 LPWSTR FilterW;
1203 PCREDENTIALW *CredentialsW;
1204 DWORD i;
1205 INT len;
1206 INT needed;
1207 char *buffer;
1209 TRACE("(%s, 0x%x, %p, %p)\n", debugstr_a(Filter), Flags, Count, Credentials);
1211 if (Filter)
1213 len = MultiByteToWideChar(CP_ACP, 0, Filter, -1, NULL, 0);
1214 FilterW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1215 if (!FilterW)
1217 SetLastError(ERROR_OUTOFMEMORY);
1218 return FALSE;
1220 MultiByteToWideChar(CP_ACP, 0, Filter, -1, FilterW, len);
1222 else
1223 FilterW = NULL;
1225 if (!CredEnumerateW(FilterW, Flags, Count, &CredentialsW))
1227 HeapFree(GetProcessHeap(), 0, FilterW);
1228 return FALSE;
1230 HeapFree(GetProcessHeap(), 0, FilterW);
1232 len = *Count * sizeof(PCREDENTIALA);
1233 for (i = 0; i < *Count; i++)
1234 len += convert_PCREDENTIALW_to_PCREDENTIALA(CredentialsW[i], NULL, 0);
1236 *Credentials = HeapAlloc(GetProcessHeap(), 0, len);
1237 if (!*Credentials)
1239 CredFree(CredentialsW);
1240 SetLastError(ERROR_OUTOFMEMORY);
1241 return FALSE;
1244 buffer = (char *)&(*Credentials)[*Count];
1245 len -= *Count * sizeof(PCREDENTIALA);
1246 for (i = 0; i < *Count; i++)
1248 (*Credentials)[i] = (PCREDENTIALA)buffer;
1249 needed = convert_PCREDENTIALW_to_PCREDENTIALA(CredentialsW[i], (*Credentials)[i], len);
1250 buffer += needed;
1251 len -= needed;
1254 CredFree(CredentialsW);
1256 return TRUE;
1259 /******************************************************************************
1260 * CredEnumerateW [ADVAPI32.@]
1262 BOOL WINAPI CredEnumerateW(LPCWSTR Filter, DWORD Flags, DWORD *Count,
1263 PCREDENTIALW **Credentials)
1265 HKEY hkeyMgr;
1266 DWORD ret;
1267 LPWSTR target_name;
1268 DWORD target_name_len;
1269 DWORD len;
1270 char *buffer;
1271 BYTE key_data[KEY_SIZE];
1273 TRACE("(%s, 0x%x, %p, %p)\n", debugstr_w(Filter), Flags, Count, Credentials);
1275 if (Flags)
1277 SetLastError(ERROR_INVALID_FLAGS);
1278 return FALSE;
1281 ret = open_cred_mgr_key(&hkeyMgr, FALSE);
1282 if (ret != ERROR_SUCCESS)
1284 WARN("couldn't open/create manager key, error %d\n", ret);
1285 SetLastError(ERROR_NO_SUCH_LOGON_SESSION);
1286 return FALSE;
1289 ret = get_cred_mgr_encryption_key(hkeyMgr, key_data);
1290 if (ret != ERROR_SUCCESS)
1292 RegCloseKey(hkeyMgr);
1293 SetLastError(ret);
1294 return FALSE;
1297 ret = RegQueryInfoKeyW(hkeyMgr, NULL, NULL, NULL, NULL, &target_name_len, NULL, NULL, NULL, NULL, NULL, NULL);
1298 if (ret != ERROR_SUCCESS)
1300 RegCloseKey(hkeyMgr);
1301 SetLastError(ret);
1302 return FALSE;
1305 target_name = HeapAlloc(GetProcessHeap(), 0, (target_name_len+1)*sizeof(WCHAR));
1306 if (!target_name)
1308 RegCloseKey(hkeyMgr);
1309 SetLastError(ERROR_OUTOFMEMORY);
1310 return FALSE;
1313 *Count = 0;
1314 len = 0;
1315 ret = registry_enumerate_credentials(hkeyMgr, Filter, target_name, target_name_len,
1316 key_data, NULL, NULL, &len, Count);
1317 #ifdef __APPLE__
1318 if (ret == ERROR_SUCCESS)
1319 ret = mac_enumerate_credentials(Filter, NULL, NULL, &len, Count);
1320 #endif
1321 if (ret == ERROR_SUCCESS && *Count == 0)
1322 ret = ERROR_NOT_FOUND;
1323 if (ret != ERROR_SUCCESS)
1325 HeapFree(GetProcessHeap(), 0, target_name);
1326 RegCloseKey(hkeyMgr);
1327 SetLastError(ret);
1328 return FALSE;
1330 len += *Count * sizeof(PCREDENTIALW);
1332 if (ret == ERROR_SUCCESS)
1334 buffer = HeapAlloc(GetProcessHeap(), 0, len);
1335 *Credentials = (PCREDENTIALW *)buffer;
1336 if (buffer)
1338 buffer += *Count * sizeof(PCREDENTIALW);
1339 *Count = 0;
1340 ret = registry_enumerate_credentials(hkeyMgr, Filter, target_name,
1341 target_name_len, key_data,
1342 *Credentials, &buffer, &len,
1343 Count);
1344 #ifdef __APPLE__
1345 if (ret == ERROR_SUCCESS)
1346 ret = mac_enumerate_credentials(Filter, *Credentials,
1347 buffer, &len, Count);
1348 #endif
1350 else
1351 ret = ERROR_OUTOFMEMORY;
1354 HeapFree(GetProcessHeap(), 0, target_name);
1355 RegCloseKey(hkeyMgr);
1357 if (ret != ERROR_SUCCESS)
1359 SetLastError(ret);
1360 return FALSE;
1362 return TRUE;
1365 /******************************************************************************
1366 * CredFree [ADVAPI32.@]
1368 VOID WINAPI CredFree(PVOID Buffer)
1370 HeapFree(GetProcessHeap(), 0, Buffer);
1373 /******************************************************************************
1374 * CredReadA [ADVAPI32.@]
1376 BOOL WINAPI CredReadA(LPCSTR TargetName, DWORD Type, DWORD Flags, PCREDENTIALA *Credential)
1378 LPWSTR TargetNameW;
1379 PCREDENTIALW CredentialW;
1380 INT len;
1382 TRACE("(%s, %d, 0x%x, %p)\n", debugstr_a(TargetName), Type, Flags, Credential);
1384 if (!TargetName)
1386 SetLastError(ERROR_INVALID_PARAMETER);
1387 return FALSE;
1390 len = MultiByteToWideChar(CP_ACP, 0, TargetName, -1, NULL, 0);
1391 TargetNameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1392 if (!TargetNameW)
1394 SetLastError(ERROR_OUTOFMEMORY);
1395 return FALSE;
1397 MultiByteToWideChar(CP_ACP, 0, TargetName, -1, TargetNameW, len);
1399 if (!CredReadW(TargetNameW, Type, Flags, &CredentialW))
1401 HeapFree(GetProcessHeap(), 0, TargetNameW);
1402 return FALSE;
1404 HeapFree(GetProcessHeap(), 0, TargetNameW);
1406 len = convert_PCREDENTIALW_to_PCREDENTIALA(CredentialW, NULL, 0);
1407 *Credential = HeapAlloc(GetProcessHeap(), 0, len);
1408 if (!*Credential)
1410 SetLastError(ERROR_OUTOFMEMORY);
1411 return FALSE;
1413 convert_PCREDENTIALW_to_PCREDENTIALA(CredentialW, *Credential, len);
1415 CredFree(CredentialW);
1417 return TRUE;
1420 /******************************************************************************
1421 * CredReadW [ADVAPI32.@]
1423 BOOL WINAPI CredReadW(LPCWSTR TargetName, DWORD Type, DWORD Flags, PCREDENTIALW *Credential)
1425 HKEY hkeyMgr;
1426 HKEY hkeyCred;
1427 DWORD ret;
1428 LPWSTR key_name;
1429 DWORD len;
1430 BYTE key_data[KEY_SIZE];
1432 TRACE("(%s, %d, 0x%x, %p)\n", debugstr_w(TargetName), Type, Flags, Credential);
1434 if (!TargetName)
1436 SetLastError(ERROR_INVALID_PARAMETER);
1437 return FALSE;
1440 if (Type != CRED_TYPE_GENERIC && Type != CRED_TYPE_DOMAIN_PASSWORD)
1442 FIXME("unhandled type %d\n", Type);
1443 SetLastError(ERROR_INVALID_PARAMETER);
1444 return FALSE;
1447 if (Flags)
1449 FIXME("unhandled flags 0x%x\n", Flags);
1450 SetLastError(ERROR_INVALID_FLAGS);
1451 return FALSE;
1454 #ifdef __APPLE__
1455 if (Type == CRED_TYPE_DOMAIN_PASSWORD)
1457 OSStatus status;
1458 SecKeychainSearchRef search;
1459 status = SecKeychainSearchCreateFromAttributes(NULL, kSecInternetPasswordItemClass, NULL, &search);
1460 if (status == noErr)
1462 SecKeychainItemRef item;
1463 while (SecKeychainSearchCopyNext(search, &item) == noErr)
1465 SecKeychainAttributeInfo info;
1466 SecKeychainAttributeList *attr_list;
1467 UInt32 info_tags[] = { kSecServerItemAttr };
1468 LPWSTR target_name;
1469 INT str_len;
1470 info.count = sizeof(info_tags)/sizeof(info_tags[0]);
1471 info.tag = info_tags;
1472 info.format = NULL;
1473 status = SecKeychainItemCopyAttributesAndData(item, &info, NULL, &attr_list, NULL, NULL);
1474 len = sizeof(**Credential);
1475 if (status != noErr)
1477 WARN("SecKeychainItemCopyAttributesAndData returned status %ld\n", status);
1478 continue;
1480 if (attr_list->count != 1 || attr_list->attr[0].tag != kSecServerItemAttr)
1482 CFRelease(item);
1483 continue;
1485 str_len = MultiByteToWideChar(CP_UTF8, 0, attr_list->attr[0].data, attr_list->attr[0].length, NULL, 0);
1486 target_name = HeapAlloc(GetProcessHeap(), 0, (str_len + 1) * sizeof(WCHAR));
1487 MultiByteToWideChar(CP_UTF8, 0, attr_list->attr[0].data, attr_list->attr[0].length, target_name, str_len);
1488 /* nul terminate */
1489 target_name[str_len] = '\0';
1490 if (strcmpiW(TargetName, target_name))
1492 CFRelease(item);
1493 HeapFree(GetProcessHeap(), 0, target_name);
1494 continue;
1496 HeapFree(GetProcessHeap(), 0, target_name);
1497 SecKeychainItemFreeAttributesAndData(attr_list, NULL);
1498 ret = mac_read_credential_from_item(item, TRUE, NULL, NULL, &len);
1499 if (ret == ERROR_SUCCESS)
1501 *Credential = HeapAlloc(GetProcessHeap(), 0, len);
1502 if (*Credential)
1504 len = sizeof(**Credential);
1505 ret = mac_read_credential_from_item(item, TRUE, *Credential,
1506 (char *)(*Credential + 1), &len);
1508 else
1509 ret = ERROR_OUTOFMEMORY;
1510 CFRelease(item);
1511 CFRelease(search);
1512 if (ret != ERROR_SUCCESS)
1514 SetLastError(ret);
1515 return FALSE;
1517 return TRUE;
1519 CFRelease(item);
1521 CFRelease(search);
1524 #endif
1526 ret = open_cred_mgr_key(&hkeyMgr, FALSE);
1527 if (ret != ERROR_SUCCESS)
1529 WARN("couldn't open/create manager key, error %d\n", ret);
1530 SetLastError(ERROR_NO_SUCH_LOGON_SESSION);
1531 return FALSE;
1534 ret = get_cred_mgr_encryption_key(hkeyMgr, key_data);
1535 if (ret != ERROR_SUCCESS)
1537 RegCloseKey(hkeyMgr);
1538 SetLastError(ret);
1539 return FALSE;
1542 key_name = get_key_name_for_target(TargetName, Type);
1543 ret = RegOpenKeyExW(hkeyMgr, key_name, 0, KEY_QUERY_VALUE, &hkeyCred);
1544 HeapFree(GetProcessHeap(), 0, key_name);
1545 if (ret != ERROR_SUCCESS)
1547 TRACE("credentials for target name %s not found\n", debugstr_w(TargetName));
1548 SetLastError(ERROR_NOT_FOUND);
1549 return FALSE;
1552 len = sizeof(**Credential);
1553 ret = registry_read_credential(hkeyCred, NULL, key_data, NULL, &len);
1554 if (ret == ERROR_SUCCESS)
1556 *Credential = HeapAlloc(GetProcessHeap(), 0, len);
1557 if (*Credential)
1559 len = sizeof(**Credential);
1560 ret = registry_read_credential(hkeyCred, *Credential, key_data,
1561 (char *)(*Credential + 1), &len);
1563 else
1564 ret = ERROR_OUTOFMEMORY;
1567 RegCloseKey(hkeyCred);
1568 RegCloseKey(hkeyMgr);
1570 if (ret != ERROR_SUCCESS)
1572 SetLastError(ret);
1573 return FALSE;
1575 return TRUE;
1578 /******************************************************************************
1579 * CredReadDomainCredentialsA [ADVAPI32.@]
1581 BOOL WINAPI CredReadDomainCredentialsA(PCREDENTIAL_TARGET_INFORMATIONA TargetInformation,
1582 DWORD Flags, DWORD *Size, PCREDENTIALA **Credentials)
1584 PCREDENTIAL_TARGET_INFORMATIONW TargetInformationW;
1585 INT len;
1586 DWORD i;
1587 WCHAR *buffer, *end;
1588 BOOL ret;
1589 PCREDENTIALW* CredentialsW;
1591 TRACE("(%p, 0x%x, %p, %p)\n", TargetInformation, Flags, Size, Credentials);
1593 /* follow Windows behavior - do not test for NULL, initialize early */
1594 *Size = 0;
1595 *Credentials = NULL;
1597 if (!TargetInformation)
1599 SetLastError(ERROR_INVALID_PARAMETER);
1600 return FALSE;
1603 len = sizeof(*TargetInformationW);
1604 if (TargetInformation->TargetName)
1605 len += MultiByteToWideChar(CP_ACP, 0, TargetInformation->TargetName, -1, NULL, 0) * sizeof(WCHAR);
1606 if (TargetInformation->NetbiosServerName)
1607 len += MultiByteToWideChar(CP_ACP, 0, TargetInformation->NetbiosServerName, -1, NULL, 0) * sizeof(WCHAR);
1608 if (TargetInformation->DnsServerName)
1609 len += MultiByteToWideChar(CP_ACP, 0, TargetInformation->DnsServerName, -1, NULL, 0) * sizeof(WCHAR);
1610 if (TargetInformation->NetbiosDomainName)
1611 len += MultiByteToWideChar(CP_ACP, 0, TargetInformation->NetbiosDomainName, -1, NULL, 0) * sizeof(WCHAR);
1612 if (TargetInformation->DnsDomainName)
1613 len += MultiByteToWideChar(CP_ACP, 0, TargetInformation->DnsDomainName, -1, NULL, 0) * sizeof(WCHAR);
1614 if (TargetInformation->DnsTreeName)
1615 len += MultiByteToWideChar(CP_ACP, 0, TargetInformation->DnsTreeName, -1, NULL, 0) * sizeof(WCHAR);
1616 if (TargetInformation->PackageName)
1617 len += MultiByteToWideChar(CP_ACP, 0, TargetInformation->PackageName, -1, NULL, 0) * sizeof(WCHAR);
1619 TargetInformationW = HeapAlloc(GetProcessHeap(), 0, len);
1620 if (!TargetInformationW)
1622 SetLastError(ERROR_OUTOFMEMORY);
1623 return FALSE;
1625 buffer = (WCHAR*)(TargetInformationW + 1);
1626 end = (WCHAR *)((char *)TargetInformationW + len);
1628 if (TargetInformation->TargetName)
1630 TargetInformationW->TargetName = buffer;
1631 buffer += MultiByteToWideChar(CP_ACP, 0, TargetInformation->TargetName, -1,
1632 TargetInformationW->TargetName, end - buffer);
1633 } else
1634 TargetInformationW->TargetName = NULL;
1636 if (TargetInformation->NetbiosServerName)
1638 TargetInformationW->NetbiosServerName = buffer;
1639 buffer += MultiByteToWideChar(CP_ACP, 0, TargetInformation->NetbiosServerName, -1,
1640 TargetInformationW->NetbiosServerName, end - buffer);
1641 } else
1642 TargetInformationW->NetbiosServerName = NULL;
1644 if (TargetInformation->DnsServerName)
1646 TargetInformationW->DnsServerName = buffer;
1647 buffer += MultiByteToWideChar(CP_ACP, 0, TargetInformation->DnsServerName, -1,
1648 TargetInformationW->DnsServerName, end - buffer);
1649 } else
1650 TargetInformationW->DnsServerName = NULL;
1652 if (TargetInformation->NetbiosDomainName)
1654 TargetInformationW->NetbiosDomainName = buffer;
1655 buffer += MultiByteToWideChar(CP_ACP, 0, TargetInformation->NetbiosDomainName, -1,
1656 TargetInformationW->NetbiosDomainName, end - buffer);
1657 } else
1658 TargetInformationW->NetbiosDomainName = NULL;
1660 if (TargetInformation->DnsDomainName)
1662 TargetInformationW->DnsDomainName = buffer;
1663 buffer += MultiByteToWideChar(CP_ACP, 0, TargetInformation->DnsDomainName, -1,
1664 TargetInformationW->DnsDomainName, end - buffer);
1665 } else
1666 TargetInformationW->DnsDomainName = NULL;
1668 if (TargetInformation->DnsTreeName)
1670 TargetInformationW->DnsTreeName = buffer;
1671 buffer += MultiByteToWideChar(CP_ACP, 0, TargetInformation->DnsTreeName, -1,
1672 TargetInformationW->DnsTreeName, end - buffer);
1673 } else
1674 TargetInformationW->DnsTreeName = NULL;
1676 if (TargetInformation->PackageName)
1678 TargetInformationW->PackageName = buffer;
1679 buffer += MultiByteToWideChar(CP_ACP, 0, TargetInformation->PackageName, -1,
1680 TargetInformationW->PackageName, end - buffer);
1681 } else
1682 TargetInformationW->PackageName = NULL;
1684 TargetInformationW->Flags = TargetInformation->Flags;
1685 TargetInformationW->CredTypeCount = TargetInformation->CredTypeCount;
1686 TargetInformationW->CredTypes = TargetInformation->CredTypes;
1688 ret = CredReadDomainCredentialsW(TargetInformationW, Flags, Size, &CredentialsW);
1690 HeapFree(GetProcessHeap(), 0, TargetInformationW);
1692 if (ret)
1694 char *buf;
1695 INT needed;
1697 len = *Size * sizeof(PCREDENTIALA);
1698 for (i = 0; i < *Size; i++)
1699 len += convert_PCREDENTIALW_to_PCREDENTIALA(CredentialsW[i], NULL, 0);
1701 *Credentials = HeapAlloc(GetProcessHeap(), 0, len);
1702 if (!*Credentials)
1704 CredFree(CredentialsW);
1705 SetLastError(ERROR_OUTOFMEMORY);
1706 return FALSE;
1709 buf = (char *)&(*Credentials)[*Size];
1710 len -= *Size * sizeof(PCREDENTIALA);
1711 for (i = 0; i < *Size; i++)
1713 (*Credentials)[i] = (PCREDENTIALA)buf;
1714 needed = convert_PCREDENTIALW_to_PCREDENTIALA(CredentialsW[i], (*Credentials)[i], len);
1715 buf += needed;
1716 len -= needed;
1719 CredFree(CredentialsW);
1721 return ret;
1724 /******************************************************************************
1725 * CredReadDomainCredentialsW [ADVAPI32.@]
1727 BOOL WINAPI CredReadDomainCredentialsW(PCREDENTIAL_TARGET_INFORMATIONW TargetInformation, DWORD Flags,
1728 DWORD *Size, PCREDENTIALW **Credentials)
1730 FIXME("(%p, 0x%x, %p, %p) stub\n", TargetInformation, Flags, Size, Credentials);
1732 /* follow Windows behavior - do not test for NULL, initialize early */
1733 *Size = 0;
1734 *Credentials = NULL;
1735 if (!TargetInformation)
1737 SetLastError(ERROR_INVALID_PARAMETER);
1738 return FALSE;
1741 SetLastError(ERROR_NOT_FOUND);
1742 return FALSE;
1745 /******************************************************************************
1746 * CredWriteA [ADVAPI32.@]
1748 BOOL WINAPI CredWriteA(PCREDENTIALA Credential, DWORD Flags)
1750 BOOL ret;
1751 INT len;
1752 PCREDENTIALW CredentialW;
1754 TRACE("(%p, 0x%x)\n", Credential, Flags);
1756 if (!Credential || !Credential->TargetName)
1758 SetLastError(ERROR_INVALID_PARAMETER);
1759 return FALSE;
1762 len = convert_PCREDENTIALA_to_PCREDENTIALW(Credential, NULL, 0);
1763 CredentialW = HeapAlloc(GetProcessHeap(), 0, len);
1764 if (!CredentialW)
1766 SetLastError(ERROR_OUTOFMEMORY);
1767 return FALSE;
1770 convert_PCREDENTIALA_to_PCREDENTIALW(Credential, CredentialW, len);
1772 ret = CredWriteW(CredentialW, Flags);
1774 HeapFree(GetProcessHeap(), 0, CredentialW);
1776 return ret;
1779 /******************************************************************************
1780 * CredWriteW [ADVAPI32.@]
1782 BOOL WINAPI CredWriteW(PCREDENTIALW Credential, DWORD Flags)
1784 HKEY hkeyMgr;
1785 HKEY hkeyCred;
1786 DWORD ret;
1787 LPWSTR key_name;
1788 BYTE key_data[KEY_SIZE];
1790 TRACE("(%p, 0x%x)\n", Credential, Flags);
1792 if (!Credential || !Credential->TargetName)
1794 SetLastError(ERROR_INVALID_PARAMETER);
1795 return FALSE;
1798 if (Flags & ~CRED_PRESERVE_CREDENTIAL_BLOB)
1800 FIXME("unhandled flags 0x%x\n", Flags);
1801 SetLastError(ERROR_INVALID_FLAGS);
1802 return FALSE;
1805 if (Credential->Type != CRED_TYPE_GENERIC && Credential->Type != CRED_TYPE_DOMAIN_PASSWORD)
1807 FIXME("unhandled type %d\n", Credential->Type);
1808 SetLastError(ERROR_INVALID_PARAMETER);
1809 return FALSE;
1812 TRACE("Credential->TargetName = %s\n", debugstr_w(Credential->TargetName));
1813 TRACE("Credential->UserName = %s\n", debugstr_w(Credential->UserName));
1815 if (Credential->Type == CRED_TYPE_DOMAIN_PASSWORD)
1817 if (!Credential->UserName ||
1818 (!strchrW(Credential->UserName, '\\') && !strchrW(Credential->UserName, '@')))
1820 ERR("bad username %s\n", debugstr_w(Credential->UserName));
1821 SetLastError(ERROR_BAD_USERNAME);
1822 return FALSE;
1826 #ifdef __APPLE__
1827 if (!Credential->AttributeCount &&
1828 Credential->Type == CRED_TYPE_DOMAIN_PASSWORD &&
1829 (Credential->Persist == CRED_PERSIST_LOCAL_MACHINE || Credential->Persist == CRED_PERSIST_ENTERPRISE))
1831 ret = mac_write_credential(Credential, Flags & CRED_PRESERVE_CREDENTIAL_BLOB);
1832 if (ret != ERROR_SUCCESS)
1834 SetLastError(ret);
1835 return FALSE;
1837 return TRUE;
1839 #endif
1841 ret = open_cred_mgr_key(&hkeyMgr, FALSE);
1842 if (ret != ERROR_SUCCESS)
1844 WARN("couldn't open/create manager key, error %d\n", ret);
1845 SetLastError(ERROR_NO_SUCH_LOGON_SESSION);
1846 return FALSE;
1849 ret = get_cred_mgr_encryption_key(hkeyMgr, key_data);
1850 if (ret != ERROR_SUCCESS)
1852 RegCloseKey(hkeyMgr);
1853 SetLastError(ret);
1854 return FALSE;
1857 key_name = get_key_name_for_target(Credential->TargetName, Credential->Type);
1858 ret = RegCreateKeyExW(hkeyMgr, key_name, 0, NULL,
1859 Credential->Persist == CRED_PERSIST_SESSION ? REG_OPTION_VOLATILE : REG_OPTION_NON_VOLATILE,
1860 KEY_READ|KEY_WRITE, NULL, &hkeyCred, NULL);
1861 HeapFree(GetProcessHeap(), 0, key_name);
1862 if (ret != ERROR_SUCCESS)
1864 TRACE("credentials for target name %s not found\n",
1865 debugstr_w(Credential->TargetName));
1866 SetLastError(ERROR_NOT_FOUND);
1867 return FALSE;
1870 ret = registry_write_credential(hkeyCred, Credential, key_data,
1871 Flags & CRED_PRESERVE_CREDENTIAL_BLOB);
1873 RegCloseKey(hkeyCred);
1874 RegCloseKey(hkeyMgr);
1876 if (ret != ERROR_SUCCESS)
1878 SetLastError(ret);
1879 return FALSE;
1881 return TRUE;
1884 /******************************************************************************
1885 * CredGetSessionTypes [ADVAPI32.@]
1887 WINADVAPI BOOL WINAPI CredGetSessionTypes(DWORD persistCount, LPDWORD persists)
1889 TRACE("(%u, %p)\n", persistCount, persists);
1891 memset(persists, CRED_PERSIST_NONE, persistCount*sizeof(*persists));
1892 if (CRED_TYPE_GENERIC < persistCount)
1894 persists[CRED_TYPE_GENERIC] = CRED_PERSIST_ENTERPRISE;
1896 if (CRED_TYPE_DOMAIN_PASSWORD < persistCount)
1898 persists[CRED_TYPE_DOMAIN_PASSWORD] = CRED_PERSIST_ENTERPRISE;
1901 return TRUE;
1904 /******************************************************************************
1905 * CredMarshalCredentialA [ADVAPI32.@]
1907 BOOL WINAPI CredMarshalCredentialA( CRED_MARSHAL_TYPE type, PVOID cred, LPSTR *out )
1909 BOOL ret;
1910 WCHAR *outW;
1912 TRACE("%u, %p, %p\n", type, cred, out);
1914 if ((ret = CredMarshalCredentialW( type, cred, &outW )))
1916 int len = WideCharToMultiByte( CP_ACP, 0, outW, -1, NULL, 0, NULL, NULL );
1917 if (!(*out = HeapAlloc( GetProcessHeap(), 0, len )))
1919 HeapFree( GetProcessHeap(), 0, outW );
1920 return FALSE;
1922 WideCharToMultiByte( CP_ACP, 0, outW, -1, *out, len, NULL, NULL );
1923 HeapFree( GetProcessHeap(), 0, outW );
1925 return ret;
1928 static UINT cred_encode( const char *bin, unsigned int len, WCHAR *cred )
1930 static char enc[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789#-";
1931 UINT n = 0, x;
1933 while (len > 0)
1935 cred[n++] = enc[bin[0] & 0x3f];
1936 x = (bin[0] & 0xc0) >> 6;
1937 if (len == 1)
1939 cred[n++] = enc[x];
1940 break;
1942 cred[n++] = enc[((bin[1] & 0xf) << 2) | x];
1943 x = (bin[1] & 0xf0) >> 4;
1944 if (len == 2)
1946 cred[n++] = enc[x];
1947 break;
1949 cred[n++] = enc[((bin[2] & 0x3) << 4) | x];
1950 cred[n++] = enc[(bin[2] & 0xfc) >> 2];
1951 bin += 3;
1952 len -= 3;
1954 return n;
1957 /******************************************************************************
1958 * CredMarshalCredentialW [ADVAPI32.@]
1960 BOOL WINAPI CredMarshalCredentialW( CRED_MARSHAL_TYPE type, PVOID cred, LPWSTR *out )
1962 CERT_CREDENTIAL_INFO *cert = cred;
1963 USERNAME_TARGET_CREDENTIAL_INFO *target = cred;
1964 DWORD len, size;
1965 WCHAR *p;
1967 TRACE("%u, %p, %p\n", type, cred, out);
1969 if (!cred || (type == CertCredential && cert->cbSize < sizeof(*cert)) ||
1970 (type != CertCredential && type != UsernameTargetCredential && type != BinaryBlobCredential) ||
1971 (type == UsernameTargetCredential && (!target->UserName || !target->UserName[0])))
1973 SetLastError( ERROR_INVALID_PARAMETER );
1974 return FALSE;
1976 switch (type)
1978 case CertCredential:
1980 char hash[CERT_HASH_LENGTH + 2];
1982 memcpy( hash, cert->rgbHashOfCert, sizeof(cert->rgbHashOfCert) );
1983 memset( hash + sizeof(cert->rgbHashOfCert), 0, sizeof(hash) - sizeof(cert->rgbHashOfCert) );
1985 size = sizeof(hash) * 4 / 3;
1986 if (!(p = HeapAlloc( GetProcessHeap(), 0, (size + 4) * sizeof(WCHAR) ))) return FALSE;
1987 p[0] = '@';
1988 p[1] = '@';
1989 p[2] = 'A' + type;
1990 len = cred_encode( (const char *)hash, sizeof(hash), p + 3 );
1991 p[len] = 0;
1992 break;
1994 case UsernameTargetCredential:
1996 len = strlenW( target->UserName );
1997 size = (sizeof(DWORD) + len * sizeof(WCHAR) + 2) * 4 / 3;
1998 if (!(p = HeapAlloc( GetProcessHeap(), 0, (size + 4) * sizeof(WCHAR) ))) return FALSE;
1999 p[0] = '@';
2000 p[1] = '@';
2001 p[2] = 'A' + type;
2002 size = len * sizeof(WCHAR);
2003 len = cred_encode( (const char *)&size, sizeof(DWORD), p + 3 );
2004 len += cred_encode( (const char *)target->UserName, size, p + 3 + len );
2005 p[len + 3] = 0;
2006 break;
2008 case BinaryBlobCredential:
2009 FIXME("BinaryBlobCredential not implemented\n");
2010 return FALSE;
2011 default:
2012 return FALSE;
2014 *out = p;
2015 return TRUE;
2018 /******************************************************************************
2019 * CredUnmarshalCredentialA [ADVAPI32.@]
2021 BOOL WINAPI CredUnmarshalCredentialA( LPCSTR cred, PCRED_MARSHAL_TYPE type, PVOID *out )
2023 BOOL ret;
2024 WCHAR *credW = NULL;
2026 TRACE("%s, %p, %p\n", debugstr_a(cred), type, out);
2028 if (cred)
2030 int len = MultiByteToWideChar( CP_ACP, 0, cred, -1, NULL, 0 );
2031 if (!(credW = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) ))) return FALSE;
2032 MultiByteToWideChar( CP_ACP, 0, cred, -1, credW, len );
2034 ret = CredUnmarshalCredentialW( credW, type, out );
2035 HeapFree( GetProcessHeap(), 0, credW );
2036 return ret;
2039 static inline char char_decode( WCHAR c )
2041 if (c >= 'A' && c <= 'Z') return c - 'A';
2042 if (c >= 'a' && c <= 'z') return c - 'a' + 26;
2043 if (c >= '0' && c <= '9') return c - '0' + 52;
2044 if (c == '#') return 62;
2045 if (c == '-') return 63;
2046 return 64;
2049 static BOOL cred_decode( const WCHAR *cred, unsigned int len, char *buf )
2051 unsigned int i = 0;
2052 char c0, c1, c2, c3;
2053 const WCHAR *p = cred;
2055 while (len >= 4)
2057 if ((c0 = char_decode( p[0] )) > 63) return FALSE;
2058 if ((c1 = char_decode( p[1] )) > 63) return FALSE;
2059 if ((c2 = char_decode( p[2] )) > 63) return FALSE;
2060 if ((c3 = char_decode( p[3] )) > 63) return FALSE;
2062 buf[i + 0] = (c1 << 6) | c0;
2063 buf[i + 1] = (c2 << 4) | (c1 >> 2);
2064 buf[i + 2] = (c3 << 2) | (c2 >> 4);
2065 len -= 4;
2066 i += 3;
2067 p += 4;
2069 if (len == 3)
2071 if ((c0 = char_decode( p[0] )) > 63) return FALSE;
2072 if ((c1 = char_decode( p[1] )) > 63) return FALSE;
2073 if ((c2 = char_decode( p[2] )) > 63) return FALSE;
2075 buf[i + 0] = (c1 << 6) | c0;
2076 buf[i + 1] = (c2 << 4) | (c1 >> 2);
2077 buf[i + 2] = c2 >> 4;
2079 else if (len == 2)
2081 if ((c0 = char_decode( p[0] )) > 63) return FALSE;
2082 if ((c1 = char_decode( p[1] )) > 63) return FALSE;
2084 buf[i + 0] = (c1 << 6) | c0;
2085 buf[i + 1] = c1 >> 2;
2086 buf[i + 2] = 0;
2088 else if (len == 1)
2090 if ((c0 = char_decode( p[0] )) > 63) return FALSE;
2092 buf[i + 0] = c0;
2093 buf[i + 1] = 0;
2094 buf[i + 2] = 0;
2096 return TRUE;
2099 /******************************************************************************
2100 * CredUnmarshalCredentialW [ADVAPI32.@]
2102 BOOL WINAPI CredUnmarshalCredentialW( LPCWSTR cred, PCRED_MARSHAL_TYPE type, PVOID *out )
2104 unsigned int len, buflen, size;
2106 TRACE("%s, %p, %p\n", debugstr_w(cred), type, out);
2108 if (!cred || cred[0] != '@' || cred[1] != '@' || !cred[2] || !cred[3])
2110 SetLastError( ERROR_INVALID_PARAMETER );
2111 return FALSE;
2113 len = strlenW( cred + 3 );
2114 switch (cred[2] - 'A')
2116 case CertCredential:
2118 char hash[CERT_HASH_LENGTH + 2];
2119 CERT_CREDENTIAL_INFO *cert;
2121 if (len != 27 || !cred_decode( cred + 3, len, hash ))
2123 SetLastError( ERROR_INVALID_PARAMETER );
2124 return FALSE;
2126 if (!(cert = HeapAlloc( GetProcessHeap(), 0, sizeof(*cert) ))) return FALSE;
2127 memcpy( cert->rgbHashOfCert, hash, sizeof(cert->rgbHashOfCert) );
2128 cert->cbSize = sizeof(*cert);
2129 *type = CertCredential;
2130 *out = cert;
2131 break;
2133 case UsernameTargetCredential:
2135 USERNAME_TARGET_CREDENTIAL_INFO *target;
2137 if (len < 9 || !cred_decode( cred + 3, 6, (char *)&size ) || !size || size % sizeof(WCHAR))
2139 SetLastError( ERROR_INVALID_PARAMETER );
2140 return FALSE;
2142 buflen = sizeof(*target) + size + sizeof(WCHAR);
2143 if (!(target = HeapAlloc( GetProcessHeap(), 0, buflen ))) return FALSE;
2144 if (!cred_decode( cred + 9, len - 6, (char *)(target + 1) ))
2146 HeapFree( GetProcessHeap(), 0, target );
2147 return FALSE;
2149 target->UserName = (WCHAR *)(target + 1);
2150 target->UserName[size / sizeof(WCHAR)] = 0;
2151 *type = UsernameTargetCredential;
2152 *out = target;
2153 break;
2155 case BinaryBlobCredential:
2156 FIXME("BinaryBlobCredential not implemented\n");
2157 return FALSE;
2158 default:
2159 WARN("unhandled type %u\n", cred[2] - 'A');
2160 return FALSE;
2162 return TRUE;