1 /* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
2 /* lib/krb5/ccache/cc_mslsa.c */
4 * Copyright 2007 Secure Endpoints Inc.
6 * Copyright 2003,2004 by the Massachusetts Institute of Technology.
9 * Export of this software from the United States of America may
10 * require a specific license from the United States Government.
11 * It is the responsibility of any person or organization contemplating
12 * export to obtain such a license before exporting.
14 * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
15 * distribute this software and its documentation for any purpose and
16 * without fee is hereby granted, provided that the above copyright
17 * notice appear in all copies and that both that copyright notice and
18 * this permission notice appear in supporting documentation, and that
19 * the name of M.I.T. not be used in advertising or publicity pertaining
20 * to distribution of the software without specific, written prior
21 * permission. Furthermore if you modify this software you must label
22 * your software as modified software and not distribute it in such a
23 * fashion that it might be confused with the original M.I.T. software.
24 * M.I.T. makes no representations about the suitability of
25 * this software for any purpose. It is provided "as is" without express
26 * or implied warranty.
28 * Copyright 2000 by Carnegie Mellon University
32 * Permission to use, copy, modify, and distribute this software and its
33 * documentation for any purpose and without fee is hereby granted,
34 * provided that the above copyright notice appear in all copies and that
35 * both that copyright notice and this permission notice appear in
36 * supporting documentation, and that the name of Carnegie Mellon
37 * University not be used in advertising or publicity pertaining to
38 * distribution of the software without specific, written prior
41 * CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
42 * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
43 * FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE FOR
44 * ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
45 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
46 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
47 * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
49 * Implementation of microsoft windows lsa credentials cache
57 #define WIN32_NO_STATUS
68 #define SECURITY_WIN32
73 #define _WIN32_WINNT 0x0600
77 #define MAX_MSG_SIZE 256
78 #define MAX_MSPRINC_SIZE 1024
81 * The function does_query_ticket_cache_ex2()
82 * contains static variables to cache the responses of the tests being
83 * performed. There is no harm in the test being performed more than
84 * once since the result will always be the same.
87 typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
90 ShowWinError(LPSTR szAPI, DWORD dwError)
93 // TODO - Write errors to event log so that scripts that don't
94 // check for errors will still get something in the event log
96 // This code is completely unsafe for use on non-English systems
97 // Any call to this function will result in the FormatMessage
98 // call failing and the program terminating. This might have
99 // been acceptable when this code was part of ms2mit.exe as
100 // a standalone executable but it is not appropriate for a library
103 WCHAR szMsgBuf[MAX_MSG_SIZE];
106 printf("Error calling function %s: %lu\n", szAPI, dwError);
108 dwRes = FormatMessage (
109 FORMAT_MESSAGE_FROM_SYSTEM,
112 MAKELANGID (LANG_ENGLISH, SUBLANG_ENGLISH_US),
117 printf("FormatMessage failed with %d\n", GetLastError());
118 ExitProcess(EXIT_FAILURE);
121 printf("%S",szMsgBuf);
126 ShowLsaError(LPSTR szAPI, NTSTATUS Status)
129 // Convert the NTSTATUS to Winerror. Then call ShowWinError().
131 ShowWinError(szAPI, LsaNtStatusToWinError(Status));
136 UnicodeToANSI(LPTSTR lpInputString, LPSTR lpszOutputString, int nOutStringLen)
140 GetCPInfo(CP_ACP, &CodePageInfo);
142 if (CodePageInfo.MaxCharSize > 1) {
143 // Only supporting non-Unicode strings
144 int reqLen = WideCharToMultiByte(CP_ACP, 0, (LPCWSTR) lpInputString, -1,
145 NULL, 0, NULL, NULL);
146 if ( reqLen > nOutStringLen)
150 if (WideCharToMultiByte(CP_ACP,
151 /* WC_NO_BEST_FIT_CHARS | */ WC_COMPOSITECHECK,
152 (LPCWSTR) lpInputString, -1,
154 nOutStringLen, NULL, NULL) == 0)
160 // Looks like unicode, better translate it
161 if (WideCharToMultiByte(CP_ACP,
162 /* WC_NO_BEST_FIT_CHARS | */ WC_COMPOSITECHECK,
163 (LPCWSTR) lpInputString, -1,
165 nOutStringLen, NULL, NULL) == 0)
174 ANSIToUnicode(LPCSTR lpInputString, LPWSTR lpszOutputString, int nOutStringLen)
179 GetCPInfo(CP_ACP, &CodePageInfo);
181 MultiByteToWideChar(CP_ACP, 0, lpInputString, -1,
182 lpszOutputString, nOutStringLen);
187 MITPrincToMSPrinc(krb5_context context, krb5_principal principal, UNICODE_STRING * msprinc)
191 if (!krb5_unparse_name(context, principal, &aname)) {
192 msprinc->Length = strlen(aname) * sizeof(WCHAR);
193 if ( msprinc->Length <= msprinc->MaximumLength )
194 ANSIToUnicode(aname, msprinc->Buffer, msprinc->MaximumLength);
197 krb5_free_unparsed_name(context,aname);
202 UnicodeStringToMITPrinc(UNICODE_STRING *service, UNICODE_STRING *realm,
203 krb5_context context, krb5_principal *principal)
209 /* Convert the realm to a wchar string. */
211 wcsncpy(realmbuf, realm->Buffer, realm->Length / sizeof(WCHAR));
212 realmbuf[realm->Length / sizeof(WCHAR)] = 0;
213 /* Convert the principal components to a wchar string. */
215 wcsncpy(princbuf, service->Buffer, service->Length/sizeof(WCHAR));
216 princbuf[service->Length/sizeof(WCHAR)]=0;
217 wcscat(princbuf, L"@");
218 wcscat(princbuf, realmbuf);
219 if (UnicodeToANSI(princbuf, aname, sizeof(aname))) {
220 if (krb5_parse_name(context, aname, principal) == 0)
228 KerbExternalNameToMITPrinc(KERB_EXTERNAL_NAME *msprinc, WCHAR *realm, krb5_context context,
229 krb5_principal *principal)
231 WCHAR princbuf[512],tmpbuf[128];
235 for (i=0;i<msprinc->NameCount;i++) {
236 wcsncpy(tmpbuf, msprinc->Names[i].Buffer,
237 msprinc->Names[i].Length/sizeof(WCHAR));
238 tmpbuf[msprinc->Names[i].Length/sizeof(WCHAR)]=0;
240 wcscat(princbuf, L"/");
241 wcscat(princbuf, tmpbuf);
243 wcscat(princbuf, L"@");
244 wcscat(princbuf, realm);
245 if (UnicodeToANSI(princbuf, aname, sizeof(aname))) {
246 if (krb5_parse_name(context, aname, principal) == 0)
253 FileTimeToUnixTime(LARGE_INTEGER *ltime)
255 FILETIME filetime, localfiletime;
258 filetime.dwLowDateTime=ltime->LowPart;
259 filetime.dwHighDateTime=ltime->HighPart;
260 FileTimeToLocalFileTime(&filetime, &localfiletime);
261 FileTimeToSystemTime(&localfiletime, &systime);
262 utime.tm_sec=systime.wSecond;
263 utime.tm_min=systime.wMinute;
264 utime.tm_hour=systime.wHour;
265 utime.tm_mday=systime.wDay;
266 utime.tm_mon=systime.wMonth-1;
267 utime.tm_year=systime.wYear-1900;
269 return(mktime(&utime));
273 MSSessionKeyToMITKeyblock(KERB_CRYPTO_KEY *mskey, krb5_context context, krb5_keyblock *keyblock)
275 krb5_keyblock tmpblock;
276 tmpblock.magic=KV5M_KEYBLOCK;
277 tmpblock.enctype=mskey->KeyType;
278 tmpblock.length=mskey->Length;
279 tmpblock.contents=mskey->Value;
280 krb5_copy_keyblock_contents(context, &tmpblock, keyblock);
284 IsMSSessionKeyNull(KERB_CRYPTO_KEY *mskey)
288 if (mskey->KeyType == KERB_ETYPE_NULL)
291 for ( i=0; i<mskey->Length; i++ ) {
300 MSFlagsToMITFlags(ULONG msflags, ULONG *mitflags)
306 MSTicketToMITTicket(KERB_EXTERNAL_TICKET *msticket, krb5_context context, krb5_data *ticket)
308 krb5_data tmpdata, *newdata = 0;
311 tmpdata.magic=KV5M_DATA;
312 tmpdata.length=msticket->EncodedTicketSize;
313 tmpdata.data=msticket->EncodedTicket;
315 // this is ugly and will break krb5_free_data()
316 // now that this is being done within the library it won't break krb5_free_data()
317 rc = krb5_copy_data(context, &tmpdata, &newdata);
321 memcpy(ticket, newdata, sizeof(krb5_data));
327 MSCredToMITCred(KERB_EXTERNAL_TICKET *msticket, UNICODE_STRING ClientRealm,
328 krb5_context context, krb5_creds *creds)
331 ZeroMemory(creds, sizeof(krb5_creds));
332 creds->magic=KV5M_CREDS;
334 // construct Client Principal
335 wcsncpy(wrealm, ClientRealm.Buffer, ClientRealm.Length/sizeof(WCHAR));
336 wrealm[ClientRealm.Length/sizeof(WCHAR)]=0;
337 if (!KerbExternalNameToMITPrinc(msticket->ClientName, wrealm, context, &creds->client))
340 // construct Service Principal
341 wcsncpy(wrealm, msticket->DomainName.Buffer,
342 msticket->DomainName.Length/sizeof(WCHAR));
343 wrealm[msticket->DomainName.Length/sizeof(WCHAR)]=0;
344 if (!KerbExternalNameToMITPrinc(msticket->ServiceName, wrealm, context, &creds->server))
346 MSSessionKeyToMITKeyblock(&msticket->SessionKey, context,
348 MSFlagsToMITFlags(msticket->TicketFlags, &creds->ticket_flags);
349 creds->times.starttime=FileTimeToUnixTime(&msticket->StartTime);
350 creds->times.endtime=FileTimeToUnixTime(&msticket->EndTime);
351 creds->times.renew_till=FileTimeToUnixTime(&msticket->RenewUntil);
353 creds->addresses = NULL;
355 return MSTicketToMITTicket(msticket, context, &creds->ticket);
358 /* CacheInfoEx2ToMITCred is used when we do not need the real ticket */
360 CacheInfoEx2ToMITCred(KERB_TICKET_CACHE_INFO_EX2 *info,
361 krb5_context context, krb5_creds *creds)
363 ZeroMemory(creds, sizeof(krb5_creds));
364 creds->magic=KV5M_CREDS;
366 // construct Client Principal
367 if (!UnicodeStringToMITPrinc(&info->ClientName, &info->ClientRealm,
368 context, &creds->client))
371 // construct Service Principal
372 if (!UnicodeStringToMITPrinc(&info->ServerName, &info->ServerRealm,
373 context, &creds->server))
376 creds->keyblock.magic = KV5M_KEYBLOCK;
377 creds->keyblock.enctype = info->SessionKeyType;
378 creds->ticket_flags = info->TicketFlags;
379 MSFlagsToMITFlags(info->TicketFlags, &creds->ticket_flags);
380 creds->times.starttime=FileTimeToUnixTime(&info->StartTime);
381 creds->times.endtime=FileTimeToUnixTime(&info->EndTime);
382 creds->times.renew_till=FileTimeToUnixTime(&info->RenewTime);
384 /* MS Tickets are addressless. MIT requires an empty address
385 * not a NULL list of addresses.
387 creds->addresses = (krb5_address **)malloc(sizeof(krb5_address *));
388 if (creds->addresses == NULL)
390 memset(creds->addresses, 0, sizeof(krb5_address *));
396 PackageConnectLookup(HANDLE *pLogonHandle, ULONG *pPackageId)
401 Status = LsaConnectUntrusted(
407 ShowLsaError("LsaConnectUntrusted", Status);
411 Name.Buffer = MICROSOFT_KERBEROS_NAME_A;
412 Name.Length = strlen(Name.Buffer);
413 Name.MaximumLength = Name.Length + 1;
415 Status = LsaLookupAuthenticationPackage(
423 ShowLsaError("LsaLookupAuthenticationPackage", Status);
432 * This runtime check is only needed on Windows XP and Server 2003.
433 * It can safely be removed when we no longer wish to support any
434 * versions of those platforms.
437 does_query_ticket_cache_ex2 (void)
439 static BOOL fChecked = FALSE;
440 static BOOL fEx2Response = FALSE;
445 NTSTATUS SubStatus = 0;
449 PKERB_QUERY_TKT_CACHE_REQUEST pCacheRequest = NULL;
450 PKERB_QUERY_TKT_CACHE_EX2_RESPONSE pCacheResponse = NULL;
453 RequestSize = sizeof(*pCacheRequest) + 1;
455 if (!PackageConnectLookup(&LogonHandle, &PackageId))
458 pCacheRequest = (PKERB_QUERY_TKT_CACHE_REQUEST) LocalAlloc(LMEM_ZEROINIT, RequestSize);
459 if (!pCacheRequest) {
460 LsaDeregisterLogonProcess(LogonHandle);
464 pCacheRequest->MessageType = KerbQueryTicketCacheEx2Message;
465 pCacheRequest->LogonId.LowPart = 0;
466 pCacheRequest->LogonId.HighPart = 0;
468 Status = LsaCallAuthenticationPackage( LogonHandle,
477 LocalFree(pCacheRequest);
478 LsaDeregisterLogonProcess(LogonHandle);
480 if (!(FAILED(Status) || FAILED(SubStatus))) {
481 LsaFreeReturnBuffer(pCacheResponse);
491 ConcatenateUnicodeStrings(UNICODE_STRING *pTarget, UNICODE_STRING Source1, UNICODE_STRING Source2)
494 // The buffers for Source1 and Source2 cannot overlap pTarget's
495 // buffer. Source1.Length + Source2.Length must be <= 0xFFFF,
496 // otherwise we overflow...
499 USHORT TotalSize = Source1.Length + Source2.Length;
500 PBYTE buffer = (PBYTE) pTarget->Buffer;
502 if (TotalSize > pTarget->MaximumLength)
503 return ERROR_INSUFFICIENT_BUFFER;
505 if ( pTarget->Buffer != Source1.Buffer )
506 memcpy(buffer, Source1.Buffer, Source1.Length);
507 memcpy(buffer + Source1.Length, Source2.Buffer, Source2.Length);
509 pTarget->Length = TotalSize;
510 return ERROR_SUCCESS;
514 get_STRING_from_registry(HKEY hBaseKey, char * key, char * value, char * outbuf, DWORD outlen)
520 if (!outbuf || outlen == 0)
523 rc = RegOpenKeyExA(hBaseKey, key, 0, KEY_QUERY_VALUE, &hKey);
528 rc = RegQueryValueExA(hKey, value, 0, 0, (LPBYTE) outbuf, &dwCount);
531 return rc?FALSE:TRUE;
535 GetSecurityLogonSessionData(PSECURITY_LOGON_SESSION_DATA * ppSessionData)
539 TOKEN_STATISTICS Stats;
545 *ppSessionData = NULL;
547 Success = OpenProcessToken( GetCurrentProcess(), TOKEN_QUERY, &TokenHandle );
551 Success = GetTokenInformation( TokenHandle, TokenStatistics, &Stats, sizeof(TOKEN_STATISTICS), &ReqLen );
552 CloseHandle( TokenHandle );
556 Status = LsaGetLogonSessionData( &Stats.AuthenticationId, ppSessionData );
557 if ( FAILED(Status) || !ppSessionData )
564 ConstructTicketRequest(UNICODE_STRING DomainName, PKERB_RETRIEVE_TKT_REQUEST * outRequest, ULONG * outSize)
567 UNICODE_STRING TargetPrefix;
570 PKERB_RETRIEVE_TKT_REQUEST pTicketRequest = NULL;
576 // Set up the "krbtgt/" target prefix into a UNICODE_STRING so we
577 // can easily concatenate it later.
580 TargetPrefix.Buffer = L"krbtgt/";
581 TargetPrefix.Length = wcslen(TargetPrefix.Buffer) * sizeof(WCHAR);
582 TargetPrefix.MaximumLength = TargetPrefix.Length;
585 // We will need to concatenate the "krbtgt/" prefix and the
586 // Logon Session's DnsDomainName into our request's target name.
588 // Therefore, first compute the necessary buffer size for that.
590 // Note that we might theoretically have integer overflow.
593 TargetSize = TargetPrefix.Length + DomainName.Length;
596 // The ticket request buffer needs to be a single buffer. That buffer
597 // needs to include the buffer for the target name.
600 RequestSize = sizeof(*pTicketRequest) + TargetSize;
603 // Allocate the request buffer and make sure it's zero-filled.
606 pTicketRequest = (PKERB_RETRIEVE_TKT_REQUEST) LocalAlloc(LMEM_ZEROINIT, RequestSize);
608 return GetLastError();
611 // Concatenate the target prefix with the previous reponse's
615 pTicketRequest->TargetName.Length = 0;
616 pTicketRequest->TargetName.MaximumLength = TargetSize;
617 pTicketRequest->TargetName.Buffer = (PWSTR) (pTicketRequest + 1);
618 Error = ConcatenateUnicodeStrings(&(pTicketRequest->TargetName),
621 *outRequest = pTicketRequest;
622 *outSize = RequestSize;
627 PurgeAllTickets(HANDLE LogonHandle, ULONG PackageId)
630 NTSTATUS SubStatus = 0;
631 KERB_PURGE_TKT_CACHE_REQUEST PurgeRequest;
633 PurgeRequest.MessageType = KerbPurgeTicketCacheMessage;
634 PurgeRequest.LogonId.LowPart = 0;
635 PurgeRequest.LogonId.HighPart = 0;
636 PurgeRequest.ServerName.Buffer = L"";
637 PurgeRequest.ServerName.Length = 0;
638 PurgeRequest.ServerName.MaximumLength = 0;
639 PurgeRequest.RealmName.Buffer = L"";
640 PurgeRequest.RealmName.Length = 0;
641 PurgeRequest.RealmName.MaximumLength = 0;
642 Status = LsaCallAuthenticationPackage(LogonHandle,
645 sizeof(PurgeRequest),
650 if (FAILED(Status) || FAILED(SubStatus))
656 PurgeTicketEx(HANDLE LogonHandle, ULONG PackageId,
657 krb5_context context, krb5_flags flags, krb5_creds *cred)
660 NTSTATUS SubStatus = 0;
661 KERB_PURGE_TKT_CACHE_EX_REQUEST * pPurgeRequest;
662 DWORD dwRequestLen = sizeof(KERB_PURGE_TKT_CACHE_EX_REQUEST) + 4096;
663 char * cname = NULL, * crealm = NULL;
664 char * sname = NULL, * srealm = NULL;
666 if (krb5_unparse_name(context, cred->client, &cname))
669 if (krb5_unparse_name(context, cred->server, &sname)) {
670 krb5_free_unparsed_name(context, cname);
674 pPurgeRequest = malloc(dwRequestLen);
675 if ( pPurgeRequest == NULL )
677 memset(pPurgeRequest, 0, dwRequestLen);
679 crealm = strrchr(cname, '@');
683 srealm = strrchr(sname, '@');
687 pPurgeRequest->MessageType = KerbPurgeTicketCacheExMessage;
688 pPurgeRequest->LogonId.LowPart = 0;
689 pPurgeRequest->LogonId.HighPart = 0;
690 pPurgeRequest->Flags = 0;
691 pPurgeRequest->TicketTemplate.ClientName.Buffer = (PWSTR)((CHAR *)pPurgeRequest + sizeof(KERB_PURGE_TKT_CACHE_EX_REQUEST));
692 pPurgeRequest->TicketTemplate.ClientName.Length = strlen(cname)*sizeof(WCHAR);
693 pPurgeRequest->TicketTemplate.ClientName.MaximumLength = 256;
694 ANSIToUnicode(cname, pPurgeRequest->TicketTemplate.ClientName.Buffer,
695 pPurgeRequest->TicketTemplate.ClientName.MaximumLength);
697 pPurgeRequest->TicketTemplate.ClientRealm.Buffer = (PWSTR)(((CHAR *)pPurgeRequest)+sizeof(KERB_PURGE_TKT_CACHE_EX_REQUEST) + 512);
698 pPurgeRequest->TicketTemplate.ClientRealm.Length = strlen(crealm)*sizeof(WCHAR);
699 pPurgeRequest->TicketTemplate.ClientRealm.MaximumLength = 256;
700 ANSIToUnicode(crealm, pPurgeRequest->TicketTemplate.ClientRealm.Buffer,
701 pPurgeRequest->TicketTemplate.ClientRealm.MaximumLength);
703 pPurgeRequest->TicketTemplate.ServerName.Buffer = (PWSTR)(((CHAR *)pPurgeRequest)+sizeof(KERB_PURGE_TKT_CACHE_EX_REQUEST) + 1024);
704 pPurgeRequest->TicketTemplate.ServerName.Length = strlen(sname)*sizeof(WCHAR);
705 pPurgeRequest->TicketTemplate.ServerName.MaximumLength = 256;
706 ANSIToUnicode(sname, pPurgeRequest->TicketTemplate.ServerName.Buffer,
707 pPurgeRequest->TicketTemplate.ServerName.MaximumLength);
709 pPurgeRequest->TicketTemplate.ServerRealm.Buffer = (PWSTR)(((CHAR *)pPurgeRequest)+sizeof(KERB_PURGE_TKT_CACHE_EX_REQUEST) + 1536);
710 pPurgeRequest->TicketTemplate.ServerRealm.Length = strlen(srealm)*sizeof(WCHAR);
711 pPurgeRequest->TicketTemplate.ServerRealm.MaximumLength = 256;
712 ANSIToUnicode(srealm, pPurgeRequest->TicketTemplate.ServerRealm.Buffer,
713 pPurgeRequest->TicketTemplate.ServerRealm.MaximumLength);
715 pPurgeRequest->TicketTemplate.StartTime;
716 pPurgeRequest->TicketTemplate.EndTime;
717 pPurgeRequest->TicketTemplate.RenewTime;
718 pPurgeRequest->TicketTemplate.EncryptionType = cred->keyblock.enctype;
719 pPurgeRequest->TicketTemplate.TicketFlags = flags;
721 Status = LsaCallAuthenticationPackage( LogonHandle,
730 krb5_free_unparsed_name(context,cname);
731 krb5_free_unparsed_name(context,sname);
733 if (FAILED(Status) || FAILED(SubStatus))
739 KerbSubmitTicket( HANDLE LogonHandle, ULONG PackageId,
740 krb5_context context, krb5_creds *cred)
743 NTSTATUS SubStatus = 0;
744 KERB_SUBMIT_TKT_REQUEST * pSubmitRequest = NULL;
746 krb5_auth_context auth_context = NULL;
747 krb5_keyblock * keyblock = 0;
748 krb5_replay_data replaydata;
749 krb5_data * krb_cred = 0;
753 if (krb5_auth_con_init(context, &auth_context)) {
757 if (krb5_auth_con_setflags(context, auth_context,
758 KRB5_AUTH_CONTEXT_RET_TIME)) {
762 krb5_auth_con_getsendsubkey(context, auth_context, &keyblock);
763 if (keyblock == NULL)
764 krb5_auth_con_getkey(context, auth_context, &keyblock);
766 /* make up a key, any key, that can be used to generate the
767 * encrypted KRB_CRED pdu. The Vista release LSA requires
768 * that an enctype other than NULL be used. */
769 if (keyblock == NULL) {
770 keyblock = (krb5_keyblock *)malloc(sizeof(krb5_keyblock));
771 if (keyblock == NULL)
773 keyblock->enctype = ENCTYPE_ARCFOUR_HMAC;
774 keyblock->length = 16;
775 keyblock->contents = (krb5_octet *)malloc(16);
776 if (keyblock->contents == NULL)
778 keyblock->contents[0] = 0xde;
779 keyblock->contents[1] = 0xad;
780 keyblock->contents[2] = 0xbe;
781 keyblock->contents[3] = 0xef;
782 keyblock->contents[4] = 0xfe;
783 keyblock->contents[5] = 0xed;
784 keyblock->contents[6] = 0xf0;
785 keyblock->contents[7] = 0xd;
786 keyblock->contents[8] = 0xde;
787 keyblock->contents[9] = 0xad;
788 keyblock->contents[10] = 0xbe;
789 keyblock->contents[11] = 0xef;
790 keyblock->contents[12] = 0xfe;
791 keyblock->contents[13] = 0xed;
792 keyblock->contents[14] = 0xf0;
793 keyblock->contents[15] = 0xd;
794 krb5_auth_con_setsendsubkey(context, auth_context, keyblock);
796 rc = krb5_mk_1cred(context, auth_context, cred, &krb_cred, &replaydata);
800 dwRequestLen = sizeof(KERB_SUBMIT_TKT_REQUEST) + krb_cred->length + (keyblock ? keyblock->length : 0);
802 pSubmitRequest = (PKERB_SUBMIT_TKT_REQUEST)malloc(dwRequestLen);
803 if (pSubmitRequest == NULL)
805 memset(pSubmitRequest, 0, dwRequestLen);
807 pSubmitRequest->MessageType = KerbSubmitTicketMessage;
808 pSubmitRequest->LogonId.LowPart = 0;
809 pSubmitRequest->LogonId.HighPart = 0;
810 pSubmitRequest->Flags = 0;
813 pSubmitRequest->Key.KeyType = keyblock->enctype;
814 pSubmitRequest->Key.Length = keyblock->length;
815 pSubmitRequest->Key.Offset = sizeof(KERB_SUBMIT_TKT_REQUEST)+krb_cred->length;
817 pSubmitRequest->Key.KeyType = ENCTYPE_NULL;
818 pSubmitRequest->Key.Length = 0;
819 pSubmitRequest->Key.Offset = 0;
821 pSubmitRequest->KerbCredSize = krb_cred->length;
822 pSubmitRequest->KerbCredOffset = sizeof(KERB_SUBMIT_TKT_REQUEST);
823 memcpy(((CHAR *)pSubmitRequest)+sizeof(KERB_SUBMIT_TKT_REQUEST),
824 krb_cred->data, krb_cred->length);
826 memcpy(((CHAR *)pSubmitRequest)+sizeof(KERB_SUBMIT_TKT_REQUEST)+krb_cred->length,
827 keyblock->contents, keyblock->length);
828 Status = LsaCallAuthenticationPackage( LogonHandle,
837 rv = (!FAILED(Status) && !FAILED(SubStatus));
840 free(pSubmitRequest);
841 krb5_free_keyblock(context, keyblock);
842 krb5_free_data(context, krb_cred);
843 krb5_auth_con_free(context, auth_context);
849 * A simple function to determine if there is an exact match between two tickets
850 * We rely on the fact that the external tickets contain the raw Kerberos ticket.
851 * If the EncodedTicket fields match, the KERB_EXTERNAL_TICKETs must be the same.
854 KerbExternalTicketMatch( PKERB_EXTERNAL_TICKET one, PKERB_EXTERNAL_TICKET two )
856 if ( one->EncodedTicketSize != two->EncodedTicketSize )
859 if ( memcmp(one->EncodedTicket, two->EncodedTicket, one->EncodedTicketSize) )
866 krb5_is_permitted_tgs_enctype(krb5_context context, krb5_const_principal princ, krb5_enctype etype)
868 krb5_enctype *list, *ptr;
871 if (krb5_get_tgs_ktypes(context, princ, &list))
876 for (ptr = list; *ptr; ptr++)
880 krb5_free_enctypes(context, list);
885 // to allow the purging of expired tickets from LSA cache. This is necessary
886 // to force the retrieval of new TGTs. Microsoft does not appear to retrieve
887 // new tickets when they expire. Instead they continue to accept the expired
888 // tickets. This is safe to do because the LSA purges its cache when it
889 // retrieves a new TGT (ms calls this renew) but not when it renews the TGT
890 // (ms calls this refresh).
891 // UAC-limited processes are not allowed to obtain a copy of the MSTGT
892 // session key. We used to check for UAC-limited processes and refuse all
893 // access to the TGT, but this makes the MSLSA ccache completely unusable.
894 // Instead we ought to just flag that the tgt session key is not valid.
897 GetMSTGT(krb5_context context, HANDLE LogonHandle, ULONG PackageId, KERB_EXTERNAL_TICKET **ticket, BOOL enforce_tgs_enctypes)
902 // (FAILED(Status) || FAILED(SubStatus)) ==> error
903 // bIsLsaError ==> LsaCallAuthenticationPackage() error
906 BOOL bIsLsaError = FALSE;
908 NTSTATUS SubStatus = 0;
911 KERB_QUERY_TKT_CACHE_REQUEST CacheRequest;
912 PKERB_RETRIEVE_TKT_REQUEST pTicketRequest = NULL;
913 PKERB_RETRIEVE_TKT_RESPONSE pTicketResponse = NULL;
917 int ignore_cache = 0;
918 krb5_enctype *etype_list = NULL, *ptr = NULL, etype = 0;
920 memset(&CacheRequest, 0, sizeof(KERB_QUERY_TKT_CACHE_REQUEST));
921 CacheRequest.MessageType = KerbRetrieveTicketMessage;
922 CacheRequest.LogonId.LowPart = 0;
923 CacheRequest.LogonId.HighPart = 0;
925 Status = LsaCallAuthenticationPackage(
929 sizeof(CacheRequest),
937 // if the call to LsaCallAuthenticationPackage failed we cannot
938 // perform any queries most likely because the Kerberos package
939 // is not available or we do not have access
944 if (FAILED(SubStatus)) {
945 PSECURITY_LOGON_SESSION_DATA pSessionData = NULL;
946 BOOL Success = FALSE;
947 OSVERSIONINFOEX verinfo;
950 // SubStatus 0x8009030E is not documented. However, it appears
951 // to mean there is no TGT
952 if (SubStatus != 0x8009030E) {
957 verinfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
958 GetVersionEx((OSVERSIONINFO *)&verinfo);
959 supported = (verinfo.dwMajorVersion > 5) ||
960 (verinfo.dwMajorVersion == 5 && verinfo.dwMinorVersion >= 1);
962 // If we could not get a TGT from the cache we won't know what the
963 // Kerberos Domain should have been. On Windows XP and 2003 Server
964 // we can extract it from the Security Logon Session Data. However,
965 // the required fields are not supported on Windows 2000. :(
966 if ( supported && GetSecurityLogonSessionData(&pSessionData) ) {
967 if ( pSessionData->DnsDomainName.Buffer ) {
968 Error = ConstructTicketRequest(pSessionData->DnsDomainName,
969 &pTicketRequest, &RequestSize);
970 LsaFreeReturnBuffer(pSessionData);
974 LsaFreeReturnBuffer(pSessionData);
979 CHAR UserDnsDomain[256];
980 WCHAR UnicodeUserDnsDomain[256];
981 UNICODE_STRING wrapper;
982 if ( !get_STRING_from_registry(HKEY_CURRENT_USER,
983 "Volatile Environment",
986 sizeof(UserDnsDomain)
992 ANSIToUnicode(UserDnsDomain,UnicodeUserDnsDomain,256);
993 wrapper.Buffer = UnicodeUserDnsDomain;
994 wrapper.Length = wcslen(UnicodeUserDnsDomain) * sizeof(WCHAR);
995 wrapper.MaximumLength = 256;
997 Error = ConstructTicketRequest(wrapper,
998 &pTicketRequest, &RequestSize);
1003 /* We have succeeded in obtaining a credential from the cache.
1004 * Assuming the enctype is one that we support and the ticket
1005 * has not expired and is not marked invalid we will use it.
1006 * Otherwise, we must create a new ticket request and obtain
1007 * a credential we can use.
1010 /* Check Supported Enctypes */
1011 if ( !enforce_tgs_enctypes ||
1012 IsMSSessionKeyNull(&pTicketResponse->Ticket.SessionKey) ||
1013 krb5_is_permitted_tgs_enctype(context, NULL, pTicketResponse->Ticket.SessionKey.KeyType) ) {
1014 FILETIME Now, MinLife, EndTime, LocalEndTime;
1016 // FILETIME is in units of 100 nano-seconds
1017 // If obtained tickets are either expired or have a lifetime
1018 // less than 20 minutes, retry ...
1019 GetSystemTimeAsFileTime(&Now);
1020 EndTime.dwLowDateTime=pTicketResponse->Ticket.EndTime.LowPart;
1021 EndTime.dwHighDateTime=pTicketResponse->Ticket.EndTime.HighPart;
1022 FileTimeToLocalFileTime(&EndTime, &LocalEndTime);
1023 temp = Now.dwHighDateTime;
1025 temp = Now.dwLowDateTime;
1026 temp += 1200 * 10000;
1027 MinLife.dwHighDateTime = (DWORD)((temp >> 32) & 0xFFFFFFFF);
1028 MinLife.dwLowDateTime = (DWORD)(temp & 0xFFFFFFFF);
1029 if (CompareFileTime(&MinLife, &LocalEndTime) >= 0) {
1032 if (pTicketResponse->Ticket.TicketFlags & KERB_TICKET_FLAGS_invalid) {
1033 ignore_cache = 1; // invalid, need to attempt a TGT request
1035 goto cleanup; // we have a valid ticket, all done
1041 Error = ConstructTicketRequest(pTicketResponse->Ticket.TargetDomainName,
1042 &pTicketRequest, &RequestSize);
1048 // Free the previous response buffer so we can get the new response.
1051 if ( pTicketResponse ) {
1052 memset(pTicketResponse,0,sizeof(KERB_RETRIEVE_TKT_RESPONSE));
1053 LsaFreeReturnBuffer(pTicketResponse);
1054 pTicketResponse = NULL;
1057 if ( purge_cache ) {
1059 // Purge the existing tickets which we cannot use so new ones can
1060 // be requested. It is not possible to purge just the TGT. All
1061 // service tickets must be purged.
1063 PurgeAllTickets(LogonHandle, PackageId);
1068 // Intialize the request of the request.
1071 pTicketRequest->MessageType = KerbRetrieveEncodedTicketMessage;
1072 pTicketRequest->LogonId.LowPart = 0;
1073 pTicketRequest->LogonId.HighPart = 0;
1074 // Note: pTicketRequest->TargetName set up above
1075 pTicketRequest->CacheOptions = ((ignore_cache || !purge_cache) ?
1076 KERB_RETRIEVE_TICKET_DONT_USE_CACHE : 0L);
1077 pTicketRequest->TicketFlags = 0L;
1078 pTicketRequest->EncryptionType = 0L;
1080 Status = LsaCallAuthenticationPackage( LogonHandle,
1089 if (FAILED(Status) || FAILED(SubStatus))
1096 // Check to make sure the new tickets we received are of a type we support
1099 /* Check Supported Enctypes */
1100 if ( !enforce_tgs_enctypes ||
1101 krb5_is_permitted_tgs_enctype(context, NULL, pTicketResponse->Ticket.SessionKey.KeyType) ) {
1102 goto cleanup; // we have a valid ticket, all done
1105 if (krb5_get_tgs_ktypes(context, NULL, &etype_list)) {
1106 ptr = etype_list = NULL;
1107 etype = ENCTYPE_DES_CBC_CRC;
1109 ptr = etype_list + 1;
1110 etype = *etype_list;
1114 // Try once more but this time specify the Encryption Type
1115 // (This will not store the retrieved tickets in the LSA cache unless
1117 pTicketRequest->EncryptionType = etype;
1118 pTicketRequest->CacheOptions = KERB_RETRIEVE_TICKET_CACHE_TICKET;
1120 if ( pTicketResponse ) {
1121 memset(pTicketResponse,0,sizeof(KERB_RETRIEVE_TKT_RESPONSE));
1122 LsaFreeReturnBuffer(pTicketResponse);
1123 pTicketResponse = NULL;
1126 Status = LsaCallAuthenticationPackage( LogonHandle,
1135 if (FAILED(Status) || FAILED(SubStatus))
1141 if ( pTicketResponse->Ticket.SessionKey.KeyType == etype &&
1142 (!enforce_tgs_enctypes ||
1143 krb5_is_permitted_tgs_enctype(context, NULL, pTicketResponse->Ticket.SessionKey.KeyType)) ) {
1144 goto cleanup; // we have a valid ticket, all done
1156 krb5_free_enctypes(context, etype_list);
1158 if ( pTicketRequest )
1159 LocalFree(pTicketRequest);
1161 if (FAILED(Status) || FAILED(SubStatus))
1165 // XXX - Will be fixed later
1167 ShowLsaError("LsaCallAuthenticationPackage", Status);
1168 if (FAILED(SubStatus))
1169 ShowLsaError("LsaCallAuthenticationPackage", SubStatus);
1173 ShowWinError("GetMSTGT", Status);
1176 if (pTicketResponse) {
1177 memset(pTicketResponse,0,sizeof(KERB_RETRIEVE_TKT_RESPONSE));
1178 LsaFreeReturnBuffer(pTicketResponse);
1179 pTicketResponse = NULL;
1184 *ticket = &(pTicketResponse->Ticket);
1189 GetQueryTktCacheResponseEx(HANDLE LogonHandle, ULONG PackageId,
1190 PKERB_QUERY_TKT_CACHE_EX_RESPONSE * ppResponse)
1192 NTSTATUS Status = 0;
1193 NTSTATUS SubStatus = 0;
1195 KERB_QUERY_TKT_CACHE_REQUEST CacheRequest;
1196 PKERB_QUERY_TKT_CACHE_EX_RESPONSE pQueryResponse = NULL;
1199 CacheRequest.MessageType = KerbQueryTicketCacheExMessage;
1200 CacheRequest.LogonId.LowPart = 0;
1201 CacheRequest.LogonId.HighPart = 0;
1203 Status = LsaCallAuthenticationPackage(
1207 sizeof(CacheRequest),
1213 if ( !(FAILED(Status) || FAILED(SubStatus)) ) {
1214 *ppResponse = pQueryResponse;
1222 GetQueryTktCacheResponseEx2(HANDLE LogonHandle, ULONG PackageId,
1223 PKERB_QUERY_TKT_CACHE_EX2_RESPONSE * ppResponse)
1225 NTSTATUS Status = 0;
1226 NTSTATUS SubStatus = 0;
1228 KERB_QUERY_TKT_CACHE_REQUEST CacheRequest;
1229 PKERB_QUERY_TKT_CACHE_EX2_RESPONSE pQueryResponse = NULL;
1232 CacheRequest.MessageType = KerbQueryTicketCacheEx2Message;
1233 CacheRequest.LogonId.LowPart = 0;
1234 CacheRequest.LogonId.HighPart = 0;
1236 Status = LsaCallAuthenticationPackage(
1240 sizeof(CacheRequest),
1246 if ( !(FAILED(Status) || FAILED(SubStatus)) ) {
1247 *ppResponse = pQueryResponse;
1255 GetMSCacheTicketFromMITCred( HANDLE LogonHandle, ULONG PackageId,
1256 krb5_context context, krb5_creds *creds,
1257 PKERB_EXTERNAL_TICKET *ticket)
1259 NTSTATUS Status = 0;
1260 NTSTATUS SubStatus = 0;
1262 PKERB_RETRIEVE_TKT_REQUEST pTicketRequest = NULL;
1263 PKERB_RETRIEVE_TKT_RESPONSE pTicketResponse = NULL;
1266 RequestSize = sizeof(*pTicketRequest) + MAX_MSPRINC_SIZE;
1268 pTicketRequest = (PKERB_RETRIEVE_TKT_REQUEST) LocalAlloc(LMEM_ZEROINIT, RequestSize);
1269 if (!pTicketRequest)
1272 pTicketRequest->MessageType = KerbRetrieveEncodedTicketMessage;
1273 pTicketRequest->LogonId.LowPart = 0;
1274 pTicketRequest->LogonId.HighPart = 0;
1276 pTicketRequest->TargetName.Length = 0;
1277 pTicketRequest->TargetName.MaximumLength = MAX_MSPRINC_SIZE;
1278 pTicketRequest->TargetName.Buffer = (PWSTR) (pTicketRequest + 1);
1279 MITPrincToMSPrinc(context, creds->server, &pTicketRequest->TargetName);
1280 pTicketRequest->CacheOptions = KERB_RETRIEVE_TICKET_CACHE_TICKET;
1281 pTicketRequest->TicketFlags = creds->ticket_flags;
1282 pTicketRequest->EncryptionType = creds->keyblock.enctype;
1284 Status = LsaCallAuthenticationPackage( LogonHandle,
1293 LocalFree(pTicketRequest);
1295 if (FAILED(Status) || FAILED(SubStatus))
1298 /* otherwise return ticket */
1299 *ticket = &(pTicketResponse->Ticket);
1304 GetMSCacheTicketFromCacheInfoEx(HANDLE LogonHandle, ULONG PackageId,
1305 PKERB_TICKET_CACHE_INFO_EX tktinfo,
1306 PKERB_EXTERNAL_TICKET *ticket)
1308 NTSTATUS Status = 0;
1309 NTSTATUS SubStatus = 0;
1311 PKERB_RETRIEVE_TKT_REQUEST pTicketRequest = NULL;
1312 PKERB_RETRIEVE_TKT_RESPONSE pTicketResponse = NULL;
1315 RequestSize = sizeof(*pTicketRequest) + tktinfo->ServerName.Length;
1317 pTicketRequest = (PKERB_RETRIEVE_TKT_REQUEST) LocalAlloc(LMEM_ZEROINIT, RequestSize);
1318 if (!pTicketRequest)
1321 pTicketRequest->MessageType = KerbRetrieveEncodedTicketMessage;
1322 pTicketRequest->LogonId.LowPart = 0;
1323 pTicketRequest->LogonId.HighPart = 0;
1324 pTicketRequest->TargetName.Length = tktinfo->ServerName.Length;
1325 pTicketRequest->TargetName.MaximumLength = tktinfo->ServerName.Length;
1326 pTicketRequest->TargetName.Buffer = (PWSTR) (pTicketRequest + 1);
1327 memcpy(pTicketRequest->TargetName.Buffer,tktinfo->ServerName.Buffer, tktinfo->ServerName.Length);
1328 pTicketRequest->CacheOptions = 0;
1329 pTicketRequest->EncryptionType = tktinfo->EncryptionType;
1330 pTicketRequest->TicketFlags = 0;
1331 if ( tktinfo->TicketFlags & KERB_TICKET_FLAGS_forwardable )
1332 pTicketRequest->TicketFlags |= KDC_OPT_FORWARDABLE;
1333 if ( tktinfo->TicketFlags & KERB_TICKET_FLAGS_forwarded )
1334 pTicketRequest->TicketFlags |= KDC_OPT_FORWARDED;
1335 if ( tktinfo->TicketFlags & KERB_TICKET_FLAGS_proxiable )
1336 pTicketRequest->TicketFlags |= KDC_OPT_PROXIABLE;
1337 if ( tktinfo->TicketFlags & KERB_TICKET_FLAGS_renewable )
1338 pTicketRequest->TicketFlags |= KDC_OPT_RENEWABLE;
1340 Status = LsaCallAuthenticationPackage(
1350 LocalFree(pTicketRequest);
1352 if (FAILED(Status) || FAILED(SubStatus))
1355 /* otherwise return ticket */
1356 *ticket = &(pTicketResponse->Ticket);
1358 /* set the initial flag if we were attempting to retrieve one
1359 * because Windows won't necessarily return the initial ticket
1362 if ( tktinfo->TicketFlags & KERB_TICKET_FLAGS_initial )
1363 (*ticket)->TicketFlags |= KERB_TICKET_FLAGS_initial;
1369 GetMSCacheTicketFromCacheInfoEx2(HANDLE LogonHandle, ULONG PackageId,
1370 PKERB_TICKET_CACHE_INFO_EX2 tktinfo,
1371 PKERB_EXTERNAL_TICKET *ticket)
1373 NTSTATUS Status = 0;
1374 NTSTATUS SubStatus = 0;
1376 PKERB_RETRIEVE_TKT_REQUEST pTicketRequest = NULL;
1377 PKERB_RETRIEVE_TKT_RESPONSE pTicketResponse = NULL;
1380 RequestSize = sizeof(*pTicketRequest) + tktinfo->ServerName.Length;
1382 pTicketRequest = (PKERB_RETRIEVE_TKT_REQUEST) LocalAlloc(LMEM_ZEROINIT, RequestSize);
1383 if (!pTicketRequest)
1386 pTicketRequest->MessageType = KerbRetrieveEncodedTicketMessage;
1387 pTicketRequest->LogonId.LowPart = 0;
1388 pTicketRequest->LogonId.HighPart = 0;
1389 pTicketRequest->TargetName.Length = tktinfo->ServerName.Length;
1390 pTicketRequest->TargetName.MaximumLength = tktinfo->ServerName.Length;
1391 pTicketRequest->TargetName.Buffer = (PWSTR) (pTicketRequest + 1);
1392 memcpy(pTicketRequest->TargetName.Buffer,tktinfo->ServerName.Buffer, tktinfo->ServerName.Length);
1393 pTicketRequest->CacheOptions = KERB_RETRIEVE_TICKET_CACHE_TICKET;
1394 pTicketRequest->EncryptionType = tktinfo->SessionKeyType;
1395 pTicketRequest->TicketFlags = 0;
1396 if ( tktinfo->TicketFlags & KERB_TICKET_FLAGS_forwardable )
1397 pTicketRequest->TicketFlags |= KDC_OPT_FORWARDABLE;
1398 if ( tktinfo->TicketFlags & KERB_TICKET_FLAGS_forwarded )
1399 pTicketRequest->TicketFlags |= KDC_OPT_FORWARDED;
1400 if ( tktinfo->TicketFlags & KERB_TICKET_FLAGS_proxiable )
1401 pTicketRequest->TicketFlags |= KDC_OPT_PROXIABLE;
1402 if ( tktinfo->TicketFlags & KERB_TICKET_FLAGS_renewable )
1403 pTicketRequest->TicketFlags |= KDC_OPT_RENEWABLE;
1405 Status = LsaCallAuthenticationPackage(
1415 LocalFree(pTicketRequest);
1417 if (FAILED(Status) || FAILED(SubStatus))
1420 /* otherwise return ticket */
1421 *ticket = &(pTicketResponse->Ticket);
1424 /* set the initial flag if we were attempting to retrieve one
1425 * because Windows won't necessarily return the initial ticket
1428 if ( tktinfo->TicketFlags & KERB_TICKET_FLAGS_initial )
1429 (*ticket)->TicketFlags |= KERB_TICKET_FLAGS_initial;
1434 static krb5_error_code KRB5_CALLCONV krb5_lcc_close
1435 (krb5_context, krb5_ccache id);
1437 static krb5_error_code KRB5_CALLCONV krb5_lcc_destroy
1438 (krb5_context, krb5_ccache id);
1440 static krb5_error_code KRB5_CALLCONV krb5_lcc_end_seq_get
1441 (krb5_context, krb5_ccache id, krb5_cc_cursor *cursor);
1443 static krb5_error_code KRB5_CALLCONV krb5_lcc_generate_new
1444 (krb5_context, krb5_ccache *id);
1446 static const char * KRB5_CALLCONV krb5_lcc_get_name
1447 (krb5_context, krb5_ccache id);
1449 static krb5_error_code KRB5_CALLCONV krb5_lcc_get_principal
1450 (krb5_context, krb5_ccache id, krb5_principal *princ);
1452 static krb5_error_code KRB5_CALLCONV krb5_lcc_initialize
1453 (krb5_context, krb5_ccache id, krb5_principal princ);
1455 static krb5_error_code KRB5_CALLCONV krb5_lcc_next_cred
1456 (krb5_context, krb5_ccache id, krb5_cc_cursor *cursor,
1459 static krb5_error_code KRB5_CALLCONV krb5_lcc_resolve
1460 (krb5_context, krb5_ccache *id, const char *residual);
1462 static krb5_error_code KRB5_CALLCONV krb5_lcc_retrieve
1463 (krb5_context, krb5_ccache id, krb5_flags whichfields,
1464 krb5_creds *mcreds, krb5_creds *creds);
1466 static krb5_error_code KRB5_CALLCONV krb5_lcc_start_seq_get
1467 (krb5_context, krb5_ccache id, krb5_cc_cursor *cursor);
1469 static krb5_error_code KRB5_CALLCONV krb5_lcc_store
1470 (krb5_context, krb5_ccache id, krb5_creds *creds);
1472 static krb5_error_code KRB5_CALLCONV krb5_lcc_set_flags
1473 (krb5_context, krb5_ccache id, krb5_flags flags);
1475 static krb5_error_code KRB5_CALLCONV krb5_lcc_get_flags
1476 (krb5_context, krb5_ccache id, krb5_flags *flags);
1478 extern const krb5_cc_ops krb5_lcc_ops;
1480 krb5_error_code krb5_change_cache (void);
1483 krb5int_cc_creds_match_request(krb5_context, krb5_flags whichfields, krb5_creds *mcreds, krb5_creds *creds);
1487 typedef struct _krb5_lcc_data {
1491 krb5_principal princ;
1495 typedef struct _krb5_lcc_cursor {
1497 PKERB_QUERY_TKT_CACHE_RESPONSE w2k;
1498 PKERB_QUERY_TKT_CACHE_EX_RESPONSE xp;
1499 PKERB_QUERY_TKT_CACHE_EX2_RESPONSE ex2;
1502 PKERB_EXTERNAL_TICKET mstgt;
1508 * residual is ignored
1514 * Acccess the MS Kerberos LSA cache in the current logon session
1515 * Ignore the residual.
1518 * A filled in krb5_ccache structure "id".
1521 * KRB5_CC_NOMEM - there was insufficient memory to allocate the
1523 * krb5_ccache. id is undefined.
1526 static krb5_error_code KRB5_CALLCONV
1527 krb5_lcc_resolve (krb5_context context, krb5_ccache *id, const char *residual)
1530 krb5_lcc_data *data;
1533 PKERB_QUERY_TKT_CACHE_EX_RESPONSE pResponse;
1535 if (!PackageConnectLookup(&LogonHandle, &PackageId))
1536 return KRB5_FCC_NOFILE;
1538 lid = (krb5_ccache) malloc(sizeof(struct _krb5_ccache));
1540 LsaDeregisterLogonProcess(LogonHandle);
1541 return KRB5_CC_NOMEM;
1544 lid->ops = &krb5_lcc_ops;
1546 lid->data = (krb5_pointer) malloc(sizeof(krb5_lcc_data));
1547 if (lid->data == NULL) {
1549 LsaDeregisterLogonProcess(LogonHandle);
1550 return KRB5_CC_NOMEM;
1553 lid->magic = KV5M_CCACHE;
1554 data = (krb5_lcc_data *)lid->data;
1555 data->LogonHandle = LogonHandle;
1556 data->PackageId = PackageId;
1560 data->cc_name = (char *)malloc(strlen(residual)+1);
1561 if (data->cc_name == NULL) {
1564 LsaDeregisterLogonProcess(LogonHandle);
1565 return KRB5_CC_NOMEM;
1567 strcpy(data->cc_name, residual);
1569 /* If there are already tickets present, grab a client principal name. */
1570 if (GetQueryTktCacheResponseEx(LogonHandle, PackageId, &pResponse)) {
1571 /* Take the first client principal we find; they should all be the
1573 for (i = 0; i < pResponse->CountOfTickets; i++) {
1574 if (UnicodeStringToMITPrinc(&pResponse->Tickets[i].ClientName,
1575 &pResponse->Tickets[i].ClientRealm,
1576 context, &data->princ))
1580 LsaFreeReturnBuffer(pResponse);
1584 * other routines will get errors on open, and callers must expect them,
1585 * if cache is non-existent/unusable
1592 * return success although we do not do anything
1593 * We should delete all tickets belonging to the specified principal
1596 static krb5_error_code KRB5_CALLCONV
1597 krb5_lcc_remove_cred(krb5_context context, krb5_ccache id, krb5_flags flags,
1600 static krb5_error_code KRB5_CALLCONV
1601 krb5_lcc_initialize(krb5_context context, krb5_ccache id, krb5_principal princ)
1603 krb5_cc_cursor cursor;
1604 krb5_error_code code;
1607 code = krb5_cc_start_seq_get(context, id, &cursor);
1609 if (code == KRB5_CC_NOTFOUND)
1614 while ( !(code = krb5_cc_next_cred(context, id, &cursor, &cred)) )
1616 if ( krb5_principal_compare(context, princ, cred.client) ) {
1617 code = krb5_lcc_remove_cred(context, id, 0, &cred);
1619 krb5_free_cred_contents(context, &cred);
1622 if (code == KRB5_CC_END || code == KRB5_CC_NOTFOUND)
1624 krb5_cc_end_seq_get(context, id, &cursor);
1635 * Closes the microsoft lsa cache, invalidates the id, and frees any resources
1636 * associated with the cache.
1638 static krb5_error_code KRB5_CALLCONV
1639 krb5_lcc_close(krb5_context context, krb5_ccache id)
1641 int closeval = KRB5_OK;
1642 krb5_lcc_data *data;
1645 data = (krb5_lcc_data *) id->data;
1648 LsaDeregisterLogonProcess(data->LogonHandle);
1650 free(data->cc_name);
1660 * Destroys the contents of id.
1665 static krb5_error_code KRB5_CALLCONV
1666 krb5_lcc_destroy(krb5_context context, krb5_ccache id)
1668 krb5_lcc_data *data;
1671 data = (krb5_lcc_data *) id->data;
1673 return PurgeAllTickets(data->LogonHandle, data->PackageId) ? KRB5_OK : KRB5_FCC_INTERNAL;
1675 return KRB5_FCC_INTERNAL;
1680 * Prepares for a sequential search of the credentials cache.
1681 * Returns a krb5_cc_cursor to be used with krb5_lcc_next_cred and
1682 * krb5_lcc_end_seq_get.
1684 * If the cache is modified between the time of this call and the time
1685 * of the final krb5_lcc_end_seq_get, the results are undefined.
1689 * KRB5_FCC_INTERNAL - system errors
1691 static krb5_error_code KRB5_CALLCONV
1692 krb5_lcc_start_seq_get(krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor)
1694 krb5_lcc_cursor *lcursor;
1695 krb5_lcc_data *data = (krb5_lcc_data *)id->data;
1697 lcursor = (krb5_lcc_cursor *) malloc(sizeof(krb5_lcc_cursor));
1698 if (lcursor == NULL) {
1700 return KRB5_CC_NOMEM;
1704 * obtain a tgt to refresh the ccache in case the ticket is expired
1706 if (!GetMSTGT(context, data->LogonHandle, data->PackageId, &lcursor->mstgt, TRUE)) {
1709 return KRB5_CC_NOTFOUND;
1712 if ( does_query_ticket_cache_ex2() ) {
1713 if (!GetQueryTktCacheResponseEx2(data->LogonHandle, data->PackageId,
1714 &lcursor->response.ex2)) {
1715 LsaFreeReturnBuffer(lcursor->mstgt);
1718 return KRB5_FCC_INTERNAL;
1721 if (!GetQueryTktCacheResponseEx(data->LogonHandle, data->PackageId,
1722 &lcursor->response.xp)) {
1723 LsaFreeReturnBuffer(lcursor->mstgt);
1726 return KRB5_FCC_INTERNAL;
1729 *cursor = (krb5_cc_cursor) lcursor;
1736 * cursor is a krb5_cc_cursor originally obtained from
1737 * krb5_lcc_start_seq_get.
1743 * Fills in creds with the TGT obtained from the MS LSA
1745 * The cursor is updated to indicate TGT retrieval
1749 * KRB5_FCC_INTERNAL - system errors
1751 static krb5_error_code KRB5_CALLCONV
1752 krb5_lcc_next_cred(krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor, krb5_creds *creds)
1754 krb5_lcc_cursor *lcursor = (krb5_lcc_cursor *) *cursor;
1755 krb5_lcc_data *data;
1756 KERB_EXTERNAL_TICKET *msticket;
1757 krb5_error_code retval = KRB5_OK;
1759 data = (krb5_lcc_data *)id->data;
1762 if ( does_query_ticket_cache_ex2() ) {
1763 if ( lcursor->index >= lcursor->response.ex2->CountOfTickets ) {
1764 if (retval == KRB5_OK)
1767 LsaFreeReturnBuffer(lcursor->mstgt);
1768 LsaFreeReturnBuffer(lcursor->response.ex2);
1775 if ( data->flags & KRB5_TC_NOTICKET ) {
1776 if (!CacheInfoEx2ToMITCred( &lcursor->response.ex2->Tickets[lcursor->index++],
1778 retval = KRB5_FCC_INTERNAL;
1783 if (!GetMSCacheTicketFromCacheInfoEx2(data->LogonHandle,
1785 &lcursor->response.ex2->Tickets[lcursor->index++],&msticket)) {
1786 retval = KRB5_FCC_INTERNAL;
1791 if (lcursor->index >= lcursor->response.xp->CountOfTickets) {
1792 if (retval == KRB5_OK) {
1795 LsaFreeReturnBuffer(lcursor->mstgt);
1796 LsaFreeReturnBuffer(lcursor->response.xp);
1803 if (!GetMSCacheTicketFromCacheInfoEx(data->LogonHandle,
1805 &lcursor->response.xp->Tickets[lcursor->index++],
1807 retval = KRB5_FCC_INTERNAL;
1812 /* Don't return tickets with NULL Session Keys */
1813 if ( IsMSSessionKeyNull(&msticket->SessionKey) ) {
1814 LsaFreeReturnBuffer(msticket);
1818 /* convert the ticket */
1819 if ( does_query_ticket_cache_ex2() ) {
1820 if (!MSCredToMITCred(msticket, lcursor->response.ex2->Tickets[lcursor->index-1].ClientRealm, context, creds))
1821 retval = KRB5_FCC_INTERNAL;
1823 if (!MSCredToMITCred(msticket,
1824 lcursor->response.xp->Tickets[lcursor->index -
1827 retval = KRB5_FCC_INTERNAL;
1829 LsaFreeReturnBuffer(msticket);
1835 * cursor is a krb5_cc_cursor originally obtained from
1836 * krb5_lcc_start_seq_get.
1842 * Finishes sequential processing of the file credentials ccache id,
1843 * and invalidates the cursor (it must never be used after this call).
1846 static krb5_error_code KRB5_CALLCONV
1847 krb5_lcc_end_seq_get(krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor)
1849 krb5_lcc_cursor *lcursor = (krb5_lcc_cursor *) *cursor;
1852 LsaFreeReturnBuffer(lcursor->mstgt);
1853 if ( does_query_ticket_cache_ex2() )
1854 LsaFreeReturnBuffer(lcursor->response.ex2);
1856 LsaFreeReturnBuffer(lcursor->response.xp);
1867 * KRB5_CC_READONLY - not supported
1869 static krb5_error_code KRB5_CALLCONV
1870 krb5_lcc_generate_new (krb5_context context, krb5_ccache *id)
1872 return KRB5_CC_READONLY;
1877 * id is a ms lsa credential cache
1880 * The ccname specified during the krb5_lcc_resolve call
1882 static const char * KRB5_CALLCONV
1883 krb5_lcc_get_name (krb5_context context, krb5_ccache id)
1889 return (char *) ((krb5_lcc_data *) id->data)->cc_name;
1897 * Retrieves the primary principal from id, as set with
1898 * krb5_lcc_initialize. The principal is returned is allocated
1899 * storage that must be freed by the caller via krb5_free_principal.
1905 static krb5_error_code KRB5_CALLCONV
1906 krb5_lcc_get_principal(krb5_context context, krb5_ccache id, krb5_principal *princ)
1908 PKERB_QUERY_TKT_CACHE_EX_RESPONSE pResponse;
1909 krb5_lcc_data *data = (krb5_lcc_data *)id->data;
1912 /* obtain principal */
1914 return krb5_copy_principal(context, data->princ, princ);
1916 if (GetQueryTktCacheResponseEx(data->LogonHandle, data->PackageId,
1918 /* Take the first client principal we find; they should all be the
1920 for (i = 0; i < pResponse->CountOfTickets; i++) {
1921 if (UnicodeStringToMITPrinc(&pResponse->Tickets[i].ClientName,
1922 &pResponse->Tickets[i].ClientRealm,
1923 context, &data->princ))
1926 LsaFreeReturnBuffer(pResponse);
1928 return krb5_copy_principal(context, data->princ, princ);
1931 return KRB5_CC_NOTFOUND;
1935 static krb5_error_code KRB5_CALLCONV
1936 krb5_lcc_retrieve(krb5_context context, krb5_ccache id, krb5_flags whichfields,
1937 krb5_creds *mcreds, krb5_creds *creds)
1939 krb5_error_code kret = KRB5_OK;
1940 krb5_lcc_data *data = (krb5_lcc_data *)id->data;
1941 KERB_EXTERNAL_TICKET *msticket = 0, *mstgt = 0, *mstmp = 0;
1942 krb5_creds * mcreds_noflags = 0;
1943 krb5_creds fetchcreds;
1944 PKERB_QUERY_TKT_CACHE_EX_RESPONSE pResponse = 0;
1947 memset(&fetchcreds, 0, sizeof(krb5_creds));
1949 /* first try to find out if we have an existing ticket which meets the requirements */
1950 kret = k5_cc_retrieve_cred_default(context, id, whichfields, mcreds,
1952 /* This sometimes returns a zero-length ticket; work around it. */
1953 if ( !kret && creds->ticket.length > 0 )
1956 /* if not, we must try to get a ticket without specifying any flags or etypes */
1957 kret = krb5_copy_creds(context, mcreds, &mcreds_noflags);
1960 mcreds_noflags->ticket_flags = 0;
1961 mcreds_noflags->keyblock.enctype = 0;
1963 if (!GetMSCacheTicketFromMITCred(data->LogonHandle, data->PackageId, context, mcreds_noflags, &msticket)) {
1964 kret = KRB5_CC_NOTFOUND;
1968 /* try again to find out if we have an existing ticket which meets the requirements */
1969 kret = k5_cc_retrieve_cred_default(context, id, whichfields, mcreds,
1971 /* This sometimes returns a zero-length ticket; work around it. */
1972 if ( !kret && creds->ticket.length > 0 )
1975 /* if not, obtain a ticket using the request flags and enctype even though it may not
1976 * be stored in the LSA cache for future use.
1979 LsaFreeReturnBuffer(msticket);
1983 if (!GetMSCacheTicketFromMITCred(data->LogonHandle, data->PackageId, context, mcreds, &msticket)) {
1984 kret = KRB5_CC_NOTFOUND;
1988 /* convert the ticket */
1990 * We can obtain the correct client realm for a ticket by walking the
1991 * cache contents until we find the matching service ticket.
1994 if (!GetQueryTktCacheResponseEx(data->LogonHandle, data->PackageId,
1996 kret = KRB5_FCC_INTERNAL;
2000 for (i = 0; i < pResponse->CountOfTickets; i++) {
2001 if (!GetMSCacheTicketFromCacheInfoEx(data->LogonHandle,
2003 &pResponse->Tickets[i], &mstmp)) {
2007 if (KerbExternalTicketMatch(msticket,mstmp))
2010 LsaFreeReturnBuffer(mstmp);
2014 if (!MSCredToMITCred(msticket, mstmp ?
2015 pResponse->Tickets[i].ClientRealm :
2016 msticket->DomainName, context, &fetchcreds)) {
2017 LsaFreeReturnBuffer(pResponse);
2018 kret = KRB5_FCC_INTERNAL;
2021 LsaFreeReturnBuffer(pResponse);
2024 /* check to see if this ticket matches the request using logic from
2025 * k5_cc_retrieve_cred_default()
2027 if ( krb5int_cc_creds_match_request(context, whichfields, mcreds, &fetchcreds) ) {
2028 *creds = fetchcreds;
2030 krb5_free_cred_contents(context, &fetchcreds);
2031 kret = KRB5_CC_NOTFOUND;
2036 LsaFreeReturnBuffer(mstmp);
2038 LsaFreeReturnBuffer(mstgt);
2040 LsaFreeReturnBuffer(msticket);
2041 if ( mcreds_noflags )
2042 krb5_free_creds(context, mcreds_noflags);
2048 * We can't write to the MS LSA cache. So we request the cache to obtain a ticket for the same
2049 * principal in the hope that next time the application requires a ticket for the service it
2050 * is attempt to store, the retrieved ticket will be good enough.
2053 * KRB5_CC_READONLY - not supported
2055 static krb5_error_code KRB5_CALLCONV
2056 krb5_lcc_store(krb5_context context, krb5_ccache id, krb5_creds *creds)
2058 krb5_error_code kret = KRB5_OK;
2059 krb5_lcc_data *data = (krb5_lcc_data *)id->data;
2060 KERB_EXTERNAL_TICKET *msticket = 0, *msticket2 = 0;
2061 krb5_creds * creds_noflags = 0;
2063 if (krb5_is_config_principal(context, creds->server)) {
2064 /* mslsa cannot store config creds, so we have to bail.
2065 * The 'right' thing to do would be to return an appropriate error,
2066 * but that would require modifying the calling code to check
2067 * for that error and ignore it.
2072 if (KerbSubmitTicket( data->LogonHandle, data->PackageId, context, creds ))
2075 /* If not, lets try to obtain a matching ticket from the KDC */
2076 if ( creds->ticket_flags != 0 && creds->keyblock.enctype != 0 ) {
2077 /* if not, we must try to get a ticket without specifying any flags or etypes */
2078 kret = krb5_copy_creds(context, creds, &creds_noflags);
2080 creds_noflags->ticket_flags = 0;
2081 creds_noflags->keyblock.enctype = 0;
2083 GetMSCacheTicketFromMITCred(data->LogonHandle, data->PackageId, context, creds_noflags, &msticket2);
2084 krb5_free_creds(context, creds_noflags);
2088 GetMSCacheTicketFromMITCred(data->LogonHandle, data->PackageId, context, creds, &msticket);
2089 if (msticket || msticket2) {
2091 LsaFreeReturnBuffer(msticket);
2093 LsaFreeReturnBuffer(msticket2);
2096 return KRB5_CC_READONLY;
2100 * Individual credentials can be implemented differently depending
2101 * on the operating system version. (undocumented.)
2106 static krb5_error_code KRB5_CALLCONV
2107 krb5_lcc_remove_cred(krb5_context context, krb5_ccache id, krb5_flags flags,
2110 krb5_lcc_data *data = (krb5_lcc_data *)id->data;
2112 if (PurgeTicketEx(data->LogonHandle, data->PackageId, context, flags,
2116 return KRB5_CC_READONLY;
2124 static krb5_error_code KRB5_CALLCONV
2125 krb5_lcc_set_flags(krb5_context context, krb5_ccache id, krb5_flags flags)
2127 krb5_lcc_data *data = (krb5_lcc_data *)id->data;
2129 data->flags = flags;
2133 static krb5_error_code KRB5_CALLCONV
2134 krb5_lcc_get_flags(krb5_context context, krb5_ccache id, krb5_flags *flags)
2136 krb5_lcc_data *data = (krb5_lcc_data *)id->data;
2138 *flags = data->flags;
2142 static krb5_error_code KRB5_CALLCONV
2143 krb5_lcc_ptcursor_new(krb5_context context, krb5_cc_ptcursor *cursor)
2145 krb5_cc_ptcursor new_cursor = (krb5_cc_ptcursor )malloc(sizeof(*new_cursor));
2148 new_cursor->ops = &krb5_lcc_ops;
2149 new_cursor->data = (krb5_pointer)(1);
2150 *cursor = new_cursor;
2155 static krb5_error_code KRB5_CALLCONV
2156 krb5_lcc_ptcursor_next(krb5_context context, krb5_cc_ptcursor cursor, krb5_ccache *ccache)
2158 krb5_error_code code = 0;
2160 if (cursor->data == NULL)
2163 cursor->data = NULL;
2164 if ((code = krb5_lcc_resolve(context, ccache, ""))) {
2165 if (code != KRB5_FCC_NOFILE)
2166 /* Note that we only want to return serious errors.
2167 * Any non-zero return code will prevent the cccol iterator
2168 * from advancing to the next ccache collection. */
2174 static krb5_error_code KRB5_CALLCONV
2175 krb5_lcc_ptcursor_free(krb5_context context, krb5_cc_ptcursor *cursor)
2184 const krb5_cc_ops krb5_lcc_ops = {
2189 krb5_lcc_generate_new,
2190 krb5_lcc_initialize,
2195 krb5_lcc_get_principal,
2196 krb5_lcc_start_seq_get,
2198 krb5_lcc_end_seq_get,
2199 krb5_lcc_remove_cred,
2202 krb5_lcc_ptcursor_new,
2203 krb5_lcc_ptcursor_next,
2204 krb5_lcc_ptcursor_free,
2206 NULL, /* lastchange */
2207 NULL, /* wasdefault */
2210 NULL, /* switch_to */