1 /*
2 * Copyright (c) 2016-2019 The Khronos Group Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 * OpenCL is a trademark of Apple Inc. used under license by Khronos.
17 */
18
19 #include <icd.h>
20 #include <stdbool.h>
21 #include <windows.h>
22
khrIcd_getenv(const char * name)23 char *khrIcd_getenv(const char *name) {
24 char *retVal;
25 DWORD valSize;
26
27 valSize = GetEnvironmentVariableA(name, NULL, 0);
28
29 // valSize DOES include the null terminator, so for any set variable
30 // will always be at least 1. If it's 0, the variable wasn't set.
31 if (valSize == 0) return NULL;
32
33 // Allocate the space necessary for the registry entry
34 retVal = (char *)malloc(valSize);
35
36 if (NULL != retVal) {
37 GetEnvironmentVariableA(name, retVal, valSize);
38 }
39
40 return retVal;
41 }
42
khrIcd_IsHighIntegrityLevel()43 static bool khrIcd_IsHighIntegrityLevel()
44 {
45 bool isHighIntegrityLevel = false;
46
47 HANDLE processToken;
48 if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_QUERY_SOURCE, &processToken)) {
49 // Maximum possible size of SID_AND_ATTRIBUTES is maximum size of a SID + size of attributes DWORD.
50 char mandatoryLabelBuffer[SECURITY_MAX_SID_SIZE + sizeof(DWORD)] = {0};
51 DWORD bufferSize;
52 if (GetTokenInformation(processToken, TokenIntegrityLevel, mandatoryLabelBuffer, sizeof(mandatoryLabelBuffer),
53 &bufferSize) != 0) {
54 const TOKEN_MANDATORY_LABEL* mandatoryLabel = (const TOKEN_MANDATORY_LABEL*)(mandatoryLabelBuffer);
55 const DWORD subAuthorityCount = *GetSidSubAuthorityCount(mandatoryLabel->Label.Sid);
56 const DWORD integrityLevel = *GetSidSubAuthority(mandatoryLabel->Label.Sid, subAuthorityCount - 1);
57
58 isHighIntegrityLevel = integrityLevel > SECURITY_MANDATORY_MEDIUM_RID;
59 }
60
61 CloseHandle(processToken);
62 }
63
64 return isHighIntegrityLevel;
65 }
66
khrIcd_secure_getenv(const char * name)67 char *khrIcd_secure_getenv(const char *name) {
68 if (khrIcd_IsHighIntegrityLevel()) {
69 KHR_ICD_TRACE("Running at a high integrity level, so secure_getenv is returning NULL\n");
70 return NULL;
71 }
72
73 return khrIcd_getenv(name);
74 }
75
khrIcd_free_getenv(char * val)76 void khrIcd_free_getenv(char *val) {
77 free((void *)val);
78 }
79