20 #include <freerdp/config.h>
25 #include <freerdp/crypto/crypto.h>
26 #include <freerdp/crypto/privatekey.h>
27 #include "../crypto/privatekey.h"
28 #include <freerdp/utils/http.h>
29 #include <freerdp/utils/aad.h>
31 #include <winpr/crypto.h>
32 #include <winpr/json.h>
34 #include "transport.h"
42 rdpContext* rdpcontext;
43 rdpTransport* transport;
55 static BOOL aad_fetch_wellknown(rdpAad* aad);
56 static BOOL get_encoded_rsa_params(wLog* wlog, rdpPrivateKey* key,
char** e,
char** n);
57 static BOOL generate_pop_key(rdpAad* aad);
59 WINPR_ATTR_FORMAT_ARG(2, 3)
60 static SSIZE_T stream_sprintf(
wStream* s, WINPR_FORMAT_ARG const
char* fmt, ...)
64 const int rc = vsnprintf(NULL, 0, fmt, ap);
70 if (!Stream_EnsureRemainingCapacity(s, (
size_t)rc + 1))
73 char* ptr = Stream_PointerAs(s,
char);
75 const int rc2 = vsnprintf(ptr, WINPR_ASSERTING_INT_CAST(
size_t, rc) + 1, fmt, ap);
79 if (!Stream_SafeSeek(s, (
size_t)rc2))
84 static BOOL json_get_object(wLog* wlog, WINPR_JSON* json,
const char* key, WINPR_JSON** obj)
91 WLog_Print(wlog, WLOG_ERROR,
"[json] does not contain a key '%s'", key);
98 WLog_Print(wlog, WLOG_ERROR,
"[json] object for key '%s' is NULL", key);
105 static BOOL json_get_number(wLog* wlog, WINPR_JSON* json,
const char* key,
double* result)
108 WINPR_JSON* prop = NULL;
109 if (!json_get_object(wlog, json, key, &prop))
114 WLog_Print(wlog, WLOG_ERROR,
"[json] object for key '%s' is NOT a NUMBER", key);
125 static BOOL json_get_const_string(wLog* wlog, WINPR_JSON* json,
const char* key,
129 WINPR_ASSERT(result);
133 WINPR_JSON* prop = NULL;
134 if (!json_get_object(wlog, json, key, &prop))
139 WLog_Print(wlog, WLOG_ERROR,
"[json] object for key '%s' is NOT a STRING", key);
145 WLog_Print(wlog, WLOG_ERROR,
"[json] object for key '%s' is NULL", key);
153 static BOOL json_get_string_alloc(wLog* wlog, WINPR_JSON* json,
const char* key,
char** result)
155 const char* str = NULL;
156 if (!json_get_const_string(wlog, json, key, &str))
159 *result = _strdup(str);
161 WLog_Print(wlog, WLOG_ERROR,
"[json] object for key '%s' strdup is NULL", key);
162 return *result != NULL;
165 static INLINE
const char* aad_auth_result_to_string(DWORD code)
167 #define ERROR_CASE(cd, x) \
168 if ((cd) == (DWORD)(x)) \
171 ERROR_CASE(code, S_OK)
172 ERROR_CASE(code, SEC_E_INVALID_TOKEN)
173 ERROR_CASE(code, E_ACCESSDENIED)
174 ERROR_CASE(code, STATUS_LOGON_FAILURE)
175 ERROR_CASE(code, STATUS_NO_LOGON_SERVERS)
176 ERROR_CASE(code, STATUS_INVALID_LOGON_HOURS)
177 ERROR_CASE(code, STATUS_INVALID_WORKSTATION)
178 ERROR_CASE(code, STATUS_PASSWORD_EXPIRED)
179 ERROR_CASE(code, STATUS_ACCOUNT_DISABLED)
180 return "Unknown error";
183 static BOOL aad_get_nonce(rdpAad* aad)
186 BYTE* response = NULL;
188 size_t response_length = 0;
189 WINPR_JSON* json = NULL;
192 WINPR_ASSERT(aad->rdpcontext);
194 rdpRdp* rdp = aad->rdpcontext->rdp;
200 WLog_Print(aad->log, WLOG_ERROR,
"wellknown does not have 'token_endpoint', aborting");
206 WLog_Print(aad->log, WLOG_ERROR,
207 "wellknown does have 'token_endpoint=NULL' value, aborting");
211 if (!freerdp_http_request(url,
"grant_type=srv_challenge", &resp_code, &response,
214 WLog_Print(aad->log, WLOG_ERROR,
"nonce request failed");
218 if (resp_code != HTTP_STATUS_OK)
220 WLog_Print(aad->log, WLOG_ERROR,
221 "Server unwilling to provide nonce; returned status code %li", resp_code);
222 if (response_length > 0)
223 WLog_Print(aad->log, WLOG_ERROR,
"[status message] %s", response);
230 WLog_Print(aad->log, WLOG_ERROR,
"Failed to parse nonce response");
234 if (!json_get_string_alloc(aad->log, json,
"Nonce", &aad->nonce))
245 int aad_client_begin(rdpAad* aad)
250 WINPR_ASSERT(aad->rdpcontext);
252 rdpSettings* settings = aad->rdpcontext->settings;
253 WINPR_ASSERT(settings);
255 freerdp* instance = aad->rdpcontext->instance;
256 WINPR_ASSERT(instance);
264 WLog_Print(aad->log, WLOG_ERROR,
"FreeRDP_ServerHostname == NULL");
268 aad->hostname = _strdup(hostname);
271 WLog_Print(aad->log, WLOG_ERROR,
"_strdup(FreeRDP_ServerHostname) == NULL");
275 char* p = strchr(aad->hostname,
'.');
279 if (winpr_asprintf(&aad->scope, &size,
280 "ms-device-service%%3A%%2F%%2Ftermsrv.wvd.microsoft.com%%2Fname%%2F%s%%"
281 "2Fuser_impersonation",
285 if (!generate_pop_key(aad))
289 if (!instance->GetAccessToken)
291 WLog_Print(aad->log, WLOG_ERROR,
"instance->GetAccessToken == NULL");
295 if (!aad_fetch_wellknown(aad))
298 const BOOL arc = instance->GetAccessToken(instance, ACCESS_TOKEN_TYPE_AAD, &aad->access_token,
299 2, aad->scope, aad->kid);
302 WLog_Print(aad->log, WLOG_ERROR,
"Unable to obtain access token");
307 if (!aad_get_nonce(aad))
309 WLog_Print(aad->log, WLOG_ERROR,
"Unable to obtain nonce");
316 static char* aad_create_jws_header(rdpAad* aad)
322 size_t bufferlen = 0;
324 winpr_asprintf(&buffer, &bufferlen,
"{\"alg\":\"RS256\",\"kid\":\"%s\"}", aad->kid);
328 char* jws_header = crypto_base64url_encode((
const BYTE*)buffer, bufferlen);
333 static char* aad_create_jws_payload(rdpAad* aad,
const char* ts_nonce)
335 const time_t ts = time(NULL);
341 if (!get_encoded_rsa_params(aad->log, aad->key, &e, &n))
346 size_t bufferlen = 0;
348 winpr_asprintf(&buffer, &bufferlen,
352 "\"u\":\"ms-device-service://termsrv.wvd.microsoft.com/name/%s\","
354 "\"cnf\":{\"jwk\":{\"kty\":\"RSA\",\"e\":\"%s\",\"n\":\"%s\"}},"
355 "\"client_claims\":\"{\\\"aad_nonce\\\":\\\"%s\\\"}\""
357 ts, aad->access_token, aad->hostname, ts_nonce, e, n, aad->nonce);
364 char* jws_payload = crypto_base64url_encode((BYTE*)buffer, bufferlen);
369 static BOOL aad_update_digest(rdpAad* aad, WINPR_DIGEST_CTX* ctx,
const char* what)
375 const BOOL dsu1 = winpr_DigestSign_Update(ctx, what, strlen(what));
378 WLog_Print(aad->log, WLOG_ERROR,
"winpr_DigestSign_Update [%s] failed", what);
384 static char* aad_final_digest(rdpAad* aad, WINPR_DIGEST_CTX* ctx)
386 char* jws_signature = NULL;
392 const int dsf = winpr_DigestSign_Final(ctx, NULL, &siglen);
395 WLog_Print(aad->log, WLOG_ERROR,
"winpr_DigestSign_Final failed with %d", dsf);
399 char* buffer = calloc(siglen + 1,
sizeof(
char));
402 WLog_Print(aad->log, WLOG_ERROR,
"calloc %" PRIuz
" bytes failed", siglen + 1);
406 size_t fsiglen = siglen;
407 const int dsf2 = winpr_DigestSign_Final(ctx, (BYTE*)buffer, &fsiglen);
410 WLog_Print(aad->log, WLOG_ERROR,
"winpr_DigestSign_Final failed with %d", dsf2);
414 if (siglen != fsiglen)
416 WLog_Print(aad->log, WLOG_ERROR,
417 "winpr_DigestSignFinal returned different sizes, first %" PRIuz
" then %" PRIuz,
421 jws_signature = crypto_base64url_encode((
const BYTE*)buffer, fsiglen);
424 return jws_signature;
427 static char* aad_create_jws_signature(rdpAad* aad,
const char* jws_header,
const char* jws_payload)
429 char* jws_signature = NULL;
433 WINPR_DIGEST_CTX* md_ctx = freerdp_key_digest_sign(aad->key, WINPR_MD_SHA256);
436 WLog_Print(aad->log, WLOG_ERROR,
"winpr_Digest_New failed");
440 if (!aad_update_digest(aad, md_ctx, jws_header))
442 if (!aad_update_digest(aad, md_ctx,
"."))
444 if (!aad_update_digest(aad, md_ctx, jws_payload))
447 jws_signature = aad_final_digest(aad, md_ctx);
449 winpr_Digest_Free(md_ctx);
450 return jws_signature;
453 static int aad_send_auth_request(rdpAad* aad,
const char* ts_nonce)
456 char* jws_header = NULL;
457 char* jws_payload = NULL;
458 char* jws_signature = NULL;
461 WINPR_ASSERT(ts_nonce);
463 wStream* s = Stream_New(NULL, 1024);
468 jws_header = aad_create_jws_header(aad);
473 jws_payload = aad_create_jws_payload(aad, ts_nonce);
478 jws_signature = aad_create_jws_signature(aad, jws_header, jws_payload);
483 if (stream_sprintf(s,
"{\"rdp_assertion\":\"%s.%s.%s\"}", jws_header, jws_payload,
488 Stream_Write_UINT8(s, 0);
490 Stream_SealLength(s);
492 if (transport_write(aad->transport, s) < 0)
494 WLog_Print(aad->log, WLOG_ERROR,
"transport_write [%" PRIdz
" bytes] failed",
500 aad->state = AAD_STATE_AUTH;
503 Stream_Free(s, TRUE);
511 static int aad_parse_state_initial(rdpAad* aad,
wStream* s)
513 const char* jstr = Stream_PointerAs(s,
char);
514 const size_t jlen = Stream_GetRemainingLength(s);
515 const char* ts_nonce = NULL;
517 WINPR_JSON* json = NULL;
519 if (!Stream_SafeSeek(s, jlen))
526 if (!json_get_const_string(aad->log, json,
"ts_nonce", &ts_nonce))
529 ret = aad_send_auth_request(aad, ts_nonce);
535 static int aad_parse_state_auth(rdpAad* aad,
wStream* s)
539 DWORD error_code = 0;
540 WINPR_JSON* json = NULL;
541 const char* jstr = Stream_PointerAs(s,
char);
542 const size_t jlength = Stream_GetRemainingLength(s);
544 if (!Stream_SafeSeek(s, jlength))
551 if (!json_get_number(aad->log, json,
"authentication_result", &result))
553 error_code = (DWORD)result;
555 if (error_code != S_OK)
557 WLog_Print(aad->log, WLOG_ERROR,
"Authentication result: %s (0x%08" PRIx32
")",
558 aad_auth_result_to_string(error_code), error_code);
561 aad->state = AAD_STATE_FINAL;
568 int aad_recv(rdpAad* aad,
wStream* s)
575 case AAD_STATE_INITIAL:
576 return aad_parse_state_initial(aad, s);
578 return aad_parse_state_auth(aad, s);
579 case AAD_STATE_FINAL:
581 WLog_Print(aad->log, WLOG_ERROR,
"Invalid AAD_STATE %d", aad->state);
586 static BOOL generate_rsa_2048(rdpAad* aad)
589 return freerdp_key_generate(aad->key, 2048);
592 static char* generate_rsa_digest_base64_str(rdpAad* aad,
const char* input,
size_t ilen)
595 WINPR_DIGEST_CTX* digest = winpr_Digest_New();
598 WLog_Print(aad->log, WLOG_ERROR,
"winpr_Digest_New failed");
602 if (!winpr_Digest_Init(digest, WINPR_MD_SHA256))
604 WLog_Print(aad->log, WLOG_ERROR,
"winpr_Digest_Init(WINPR_MD_SHA256) failed");
608 if (!winpr_Digest_Update(digest, (
const BYTE*)input, ilen))
610 WLog_Print(aad->log, WLOG_ERROR,
"winpr_Digest_Update(%" PRIuz
") failed", ilen);
614 BYTE hash[WINPR_SHA256_DIGEST_LENGTH] = { 0 };
615 if (!winpr_Digest_Final(digest, hash,
sizeof(hash)))
617 WLog_Print(aad->log, WLOG_ERROR,
"winpr_Digest_Final(%" PRIuz
") failed",
sizeof(hash));
622 b64 = crypto_base64url_encode(hash,
sizeof(hash));
625 winpr_Digest_Free(digest);
629 static BOOL generate_json_base64_str(rdpAad* aad,
const char* b64_hash)
635 const int length = winpr_asprintf(&buffer, &blen,
"{\"kid\":\"%s\"}", b64_hash);
641 aad->kid = crypto_base64url_encode((
const BYTE*)buffer, (
size_t)length);
651 BOOL generate_pop_key(rdpAad* aad)
655 char* b64_hash = NULL;
662 if (!generate_rsa_2048(aad))
666 if (!get_encoded_rsa_params(aad->log, aad->key, &e, &n))
671 winpr_asprintf(&buffer, &blen,
"{\"e\":\"%s\",\"kty\":\"RSA\",\"n\":\"%s\"}", e, n);
676 b64_hash = generate_rsa_digest_base64_str(aad, buffer, blen);
681 ret = generate_json_base64_str(aad, b64_hash);
691 static char* bn_to_base64_url(wLog* wlog, rdpPrivateKey* key,
enum FREERDP_KEY_PARAM param)
697 BYTE* bn = freerdp_key_get_param(key, param, &len);
701 char* b64 = crypto_base64url_encode(bn, len);
705 WLog_Print(wlog, WLOG_ERROR,
"failed base64 url encode BIGNUM");
710 BOOL get_encoded_rsa_params(wLog* wlog, rdpPrivateKey* key,
char** pe,
char** pn)
724 e = bn_to_base64_url(wlog, key, FREERDP_KEY_PARAM_RSA_E);
727 WLog_Print(wlog, WLOG_ERROR,
"failed base64 url encode RSA E");
731 n = bn_to_base64_url(wlog, key, FREERDP_KEY_PARAM_RSA_N);
734 WLog_Print(wlog, WLOG_ERROR,
"failed base64 url encode RSA N");
753 int aad_client_begin(rdpAad* aad)
756 WLog_Print(aad->log, WLOG_ERROR,
"AAD security not compiled in, aborting!");
759 int aad_recv(rdpAad* aad,
wStream* s)
762 WLog_Print(aad->log, WLOG_ERROR,
"AAD security not compiled in, aborting!");
767 rdpAad* aad_new(rdpContext* context, rdpTransport* transport)
769 WINPR_ASSERT(transport);
770 WINPR_ASSERT(context);
772 rdpAad* aad = (rdpAad*)calloc(1,
sizeof(rdpAad));
777 aad->log = WLog_Get(FREERDP_TAG(
"aad"));
778 aad->key = freerdp_key_new();
781 aad->rdpcontext = context;
782 aad->transport = transport;
786 WINPR_PRAGMA_DIAG_PUSH
787 WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC
789 WINPR_PRAGMA_DIAG_POP
793 void aad_free(rdpAad* aad)
801 free(aad->access_token);
803 freerdp_key_free(aad->key);
808 AAD_STATE aad_get_state(rdpAad* aad)
814 BOOL aad_is_supported(
void)
823 char* freerdp_utils_aad_get_access_token(wLog* log,
const char* data,
size_t length)
826 WINPR_JSON* access_token_prop = NULL;
827 const char* access_token_str = NULL;
832 WLog_Print(log, WLOG_ERROR,
"Failed to parse access token response [got %" PRIuz
" bytes",
838 if (!access_token_prop)
840 WLog_Print(log, WLOG_ERROR,
"Response has no \"access_token\" property");
845 if (!access_token_str)
847 WLog_Print(log, WLOG_ERROR,
"Invalid value for \"access_token\"");
851 token = _strdup(access_token_str);
858 BOOL aad_fetch_wellknown(rdpAad* aad)
861 WINPR_ASSERT(aad->rdpcontext);
863 rdpRdp* rdp = aad->rdpcontext->rdp;
871 const BOOL useTenant =
873 const char* tenantid =
"common";
877 rdp->wellknown = freerdp_utils_aad_get_wellknown(aad->log, base, tenantid);
878 return rdp->wellknown ? TRUE : FALSE;
881 const char* freerdp_utils_aad_get_wellknown_string(rdpContext* context, AAD_WELLKNOWN_VALUES which)
883 return freerdp_utils_aad_get_wellknown_custom_string(
884 context, freerdp_utils_aad_wellknwon_value_name(which));
887 const char* freerdp_utils_aad_get_wellknown_custom_string(rdpContext* context,
const char* which)
889 WINPR_ASSERT(context);
890 WINPR_ASSERT(context->rdp);
892 if (!context->rdp->wellknown)
902 const char* freerdp_utils_aad_wellknwon_value_name(AAD_WELLKNOWN_VALUES which)
906 case AAD_WELLKNOWN_token_endpoint:
907 return "token_endpoint";
908 case AAD_WELLKNOWN_token_endpoint_auth_methods_supported:
909 return "token_endpoint_auth_methods_supported";
910 case AAD_WELLKNOWN_jwks_uri:
912 case AAD_WELLKNOWN_response_modes_supported:
913 return "response_modes_supported";
914 case AAD_WELLKNOWN_subject_types_supported:
915 return "subject_types_supported";
916 case AAD_WELLKNOWN_id_token_signing_alg_values_supported:
917 return "id_token_signing_alg_values_supported";
918 case AAD_WELLKNOWN_response_types_supported:
919 return "response_types_supported";
920 case AAD_WELLKNOWN_scopes_supported:
921 return "scopes_supported";
922 case AAD_WELLKNOWN_issuer:
924 case AAD_WELLKNOWN_request_uri_parameter_supported:
925 return "request_uri_parameter_supported";
926 case AAD_WELLKNOWN_userinfo_endpoint:
927 return "userinfo_endpoint";
928 case AAD_WELLKNOWN_authorization_endpoint:
929 return "authorization_endpoint";
930 case AAD_WELLKNOWN_device_authorization_endpoint:
931 return "device_authorization_endpoint";
932 case AAD_WELLKNOWN_http_logout_supported:
933 return "http_logout_supported";
934 case AAD_WELLKNOWN_frontchannel_logout_supported:
935 return "frontchannel_logout_supported";
936 case AAD_WELLKNOWN_end_session_endpoint:
937 return "end_session_endpoint";
938 case AAD_WELLKNOWN_claims_supported:
939 return "claims_supported";
940 case AAD_WELLKNOWN_kerberos_endpoint:
941 return "kerberos_endpoint";
942 case AAD_WELLKNOWN_tenant_region_scope:
943 return "tenant_region_scope";
944 case AAD_WELLKNOWN_cloud_instance_name:
945 return "cloud_instance_name";
946 case AAD_WELLKNOWN_cloud_graph_host_name:
947 return "cloud_graph_host_name";
948 case AAD_WELLKNOWN_msgraph_host:
949 return "msgraph_host";
950 case AAD_WELLKNOWN_rbac_url:
957 WINPR_JSON* freerdp_utils_aad_get_wellknown_object(rdpContext* context, AAD_WELLKNOWN_VALUES which)
959 return freerdp_utils_aad_get_wellknown_custom_object(
960 context, freerdp_utils_aad_wellknwon_value_name(which));
963 WINPR_JSON* freerdp_utils_aad_get_wellknown_custom_object(rdpContext* context,
const char* which)
965 WINPR_ASSERT(context);
966 WINPR_ASSERT(context->rdp);
968 if (!context->rdp->wellknown)
975 WINPR_JSON* freerdp_utils_aad_get_wellknown(wLog* log, const
char* base, const
char* tenantid)
978 WINPR_ASSERT(tenantid);
982 winpr_asprintf(&str, &len,
"https://%s/%s/v2.0/.well-known/openid-configuration", base,
987 WLog_Print(log, WLOG_ERROR,
"failed to create request URL for tenantid='%s'", tenantid);
991 BYTE* response = NULL;
993 size_t response_length = 0;
994 const BOOL rc = freerdp_http_request(str, NULL, &resp_code, &response, &response_length);
995 if (!rc || (resp_code != HTTP_STATUS_OK))
997 WLog_Print(log, WLOG_ERROR,
"request for '%s' failed with: %s", str,
998 freerdp_http_status_string(resp_code));
1009 WLog_Print(log, WLOG_ERROR,
"failed to parse response as JSON");
WINPR_API BOOL WINPR_JSON_HasObjectItem(const WINPR_JSON *object, const char *string)
Check if JSON has an object matching the name.
WINPR_API WINPR_JSON * WINPR_JSON_ParseWithLength(const char *value, size_t buffer_length)
Parse a JSON string.
WINPR_API BOOL WINPR_JSON_IsString(const WINPR_JSON *item)
Check if JSON item is of type String.
WINPR_API double WINPR_JSON_GetNumberValue(const WINPR_JSON *item)
Return the Number value of a JSON item.
WINPR_API BOOL WINPR_JSON_IsNumber(const WINPR_JSON *item)
Check if JSON item is of type Number.
WINPR_API void WINPR_JSON_Delete(WINPR_JSON *item)
Delete a WinPR JSON wrapper object.
WINPR_API WINPR_JSON * WINPR_JSON_GetObjectItem(const WINPR_JSON *object, const char *string)
Return a pointer to an JSON object item.
WINPR_API const char * WINPR_JSON_GetStringValue(WINPR_JSON *item)
Return the String value of a JSON item.
FREERDP_API BOOL freerdp_settings_get_bool(const rdpSettings *settings, FreeRDP_Settings_Keys_Bool id)
Returns a boolean settings value.
FREERDP_API const char * freerdp_settings_get_string(const rdpSettings *settings, FreeRDP_Settings_Keys_String id)
Returns a immutable string settings value.