Debian Codegraph @

tpmutil/tbs/tbs_windows.go

raw
1 // Copyright (c) 2018, Google LLC All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package tbs provides an low-level interface directly mapping to Windows
16 // Tbs.dll system library commands:
17 // https://docs.microsoft.com/en-us/windows/desktop/TBS/tpm-base-services-portal
18 // Public field descriptions contain links to the high-level Windows documentation.
19 package tbs
20
21 import (
22 "fmt"
23 "syscall"
24 "unsafe"
25 )
26
27 // Context references the current TPM context
28 type Context uintptr
29
30 // Version of TPM being used by the application.
31 type Version uint32
32
33 // Flag indicates TPM versions that are supported by the application.
34 type Flag uint32
35
36 // CommandPriority is used to determine which pending command to submit whenever the TPM is free.
37 type CommandPriority uint32
38
39 // Command parameters:
40 // https://github.com/tpn/winsdk-10/blob/master/Include/10.0.10240.0/shared/tbs.h
41 const (
42 // https://docs.microsoft.com/en-us/windows/desktop/api/Tbs/ns-tbs-tdtbs_context_params2
43 // OR flags to use multiple.
44 RequestRaw Flag = 1 << iota // Add flag to request raw context
45 IncludeTPM12 // Add flag to support TPM 1.2
46 IncludeTPM20 // Add flag to support TPM 2
47
48 TPMVersion12 Version = 1 // For TPM 1.2 applications
49 TPMVersion20 Version = 2 // For TPM 2 applications or applications using multiple TPM versions
50
51 // https://docs.microsoft.com/en-us/windows/desktop/tbs/command-scheduling
52 // https://docs.microsoft.com/en-us/windows/desktop/api/Tbs/nf-tbs-tbsip_submit_command#parameters
53 LowPriority CommandPriority = 100 // For low priority application use
54 NormalPriority CommandPriority = 200 // For normal priority application use
55 HighPriority CommandPriority = 300 // For high priority application use
56 SystemPriority CommandPriority = 400 // For system tasks that access the TPM
57
58 commandLocalityZero uint32 = 0 // Windows currently only supports TBS_COMMAND_LOCALITY_ZERO.
59 )
60
61 // Error is the return type of all functions in this package.
62 type Error uint32
63
64 func (err Error) Error() string {
65 if description, ok := errorDescriptions[err]; ok {
66 return fmt.Sprintf("TBS Error 0x%X: %s", uint32(err), description)
67 }
68 return fmt.Sprintf("Unrecognized TBS Error 0x%X", uint32(err))
69 }
70
71 func getError(err uintptr) error {
72 // tbs.dll uses 0x0 as the return value for success.
73 if err == 0 {
74 return nil
75 }
76 return Error(err)
77 }
78
79 // TBS Return Codes:
80 // https://docs.microsoft.com/en-us/windows/desktop/TBS/tbs-return-codes
81 const (
82 ErrInternalError Error = 0x80284001
83 ErrBadParameter Error = 0x80284002
84 ErrInvalidOutputPointer Error = 0x80284003
85 ErrInvalidContext Error = 0x80284004
86 ErrInsufficientBuffer Error = 0x80284005
87 ErrIOError Error = 0x80284006
88 ErrInvalidContextParam Error = 0x80284007
89 ErrServiceNotRunning Error = 0x80284008
90 ErrTooManyTBSContexts Error = 0x80284009
91 ErrTooManyResources Error = 0x8028400A
92 ErrServiceStartPending Error = 0x8028400B
93 ErrPPINotSupported Error = 0x8028400C
94 ErrCommandCanceled Error = 0x8028400D
95 ErrBufferTooLarge Error = 0x8028400E
96 ErrTPMNotFound Error = 0x8028400F
97 ErrServiceDisabled Error = 0x80284010
98 ErrNoEventLog Error = 0x80284011
99 ErrAccessDenied Error = 0x80284012
100 ErrProvisioningNotAllowed Error = 0x80284013
101 ErrPPIFunctionUnsupported Error = 0x80284014
102 ErrOwnerauthNotFound Error = 0x80284015
103 )
104
105 var errorDescriptions = map[Error]string{
106 ErrInternalError: "An internal software error occurred.",
107 ErrBadParameter: "One or more parameter values are not valid.",
108 ErrInvalidOutputPointer: "A specified output pointer is bad.",
109 ErrInvalidContext: "The specified context handle does not refer to a valid context.",
110 ErrInsufficientBuffer: "The specified output buffer is too small.",
111 ErrIOError: "An error occurred while communicating with the TPM.",
112 ErrInvalidContextParam: "A context parameter that is not valid was passed when attempting to create a TBS context.",
113 ErrServiceNotRunning: "The TBS service is not running and could not be started.",
114 ErrTooManyTBSContexts: "A new context could not be created because there are too many open contexts.",
115 ErrTooManyResources: "A new virtual resource could not be created because there are too many open virtual resources.",
116 ErrServiceStartPending: "The TBS service has been started but is not yet running.",
117 ErrPPINotSupported: "The physical presence interface is not supported.",
118 ErrCommandCanceled: "The command was canceled.",
119 ErrBufferTooLarge: "The input or output buffer is too large.",
120 ErrTPMNotFound: "A compatible Trusted Platform Module (TPM) Security Device cannot be found on this computer.",
121 ErrServiceDisabled: "The TBS service has been disabled.",
122 ErrNoEventLog: "The TBS event log is not available.",
123 ErrAccessDenied: "The caller does not have the appropriate rights to perform the requested operation.",
124 ErrProvisioningNotAllowed: "The TPM provisioning action is not allowed by the specified flags.",
125 ErrPPIFunctionUnsupported: "The Physical Presence Interface of this firmware does not support the requested method.",
126 ErrOwnerauthNotFound: "The requested TPM OwnerAuth value was not found.",
127 }
128
129 // Tbs.dll provides an API for making calls to the TPM:
130 // https://docs.microsoft.com/en-us/windows/desktop/TBS/tpm-base-services-portal
131 var (
132 tbsDLL = syscall.NewLazyDLL("Tbs.dll")
133 tbsGetDeviceInfo = tbsDLL.NewProc("Tbsi_GetDeviceInfo")
134 tbsCreateContext = tbsDLL.NewProc("Tbsi_Context_Create")
135 tbsContextClose = tbsDLL.NewProc("Tbsip_Context_Close")
136 tbsSubmitCommand = tbsDLL.NewProc("Tbsip_Submit_Command")
137 tbsGetTCGLog = tbsDLL.NewProc("Tbsi_Get_TCG_Log")
138 )
139
140 // Returns the address of the beginning of a slice or 0 for a nil slice.
141 func sliceAddress(s []byte) uintptr {
142 if len(s) == 0 {
143 return 0
144 }
145 return uintptr(unsafe.Pointer(&(s[0])))
146 }
147
148 // DeviceInfo is TPM_DEVICE_INFO from tbs.h
149 type DeviceInfo struct {
150 StructVersion uint32
151 TPMVersion Version
152 TPMInterfaceType uint32
153 TPMImpRevision uint32
154 }
155
156 // GetDeviceInfo gets the DeviceInfo of the current TPM:
157 // https://docs.microsoft.com/en-us/windows/win32/api/tbs/nf-tbs-tbsi_getdeviceinfo
158 func GetDeviceInfo() (*DeviceInfo, error) {
159 info := DeviceInfo{}
160 // TBS_RESULT Tbsi_GetDeviceInfo(
161 // UINT32 Size,
162 // PVOID Info
163 // );
164 if err := tbsGetDeviceInfo.Find(); err != nil {
165 return nil, err
166 }
167 result, _, _ := tbsGetDeviceInfo.Call(
168 unsafe.Sizeof(info),
169 uintptr(unsafe.Pointer(&info)),
170 )
171 return &info, getError(result)
172 }
173
174 // CreateContext creates a new TPM context:
175 // https://docs.microsoft.com/en-us/windows/desktop/api/Tbs/nf-tbs-tbsi_context_create
176 func CreateContext(version Version, flag Flag) (Context, error) {
177 var context Context
178 params := struct {
179 Version
180 Flag
181 }{version, flag}
182 // TBS_RESULT Tbsi_Context_Create(
183 // _In_ PCTBS_CONTEXT_PARAMS pContextParams,
184 // _Out_ PTBS_HCONTEXT *phContext
185 // );
186 if err := tbsCreateContext.Find(); err != nil {
187 return context, err
188 }
189 result, _, _ := tbsCreateContext.Call(
190 uintptr(unsafe.Pointer(&params)),
191 uintptr(unsafe.Pointer(&context)),
192 )
193 return context, getError(result)
194 }
195
196 // Close closes an existing TPM context:
197 // https://docs.microsoft.com/en-us/windows/desktop/api/Tbs/nf-tbs-tbsip_context_close
198 func (context Context) Close() error {
199 // TBS_RESULT Tbsip_Context_Close(
200 // _In_ TBS_HCONTEXT hContext
201 // );
202 if err := tbsContextClose.Find(); err != nil {
203 return err
204 }
205 result, _, _ := tbsContextClose.Call(uintptr(context))
206 return getError(result)
207 }
208
209 // SubmitCommand sends commandBuffer to the TPM, returning the number of bytes
210 // written to responseBuffer. ErrInsufficientBuffer is returned if the
211 // responseBuffer is too short. ErrInvalidOutputPointer is returned if the
212 // responseBuffer is nil. On failure, the returned length is unspecified.
213 // https://docs.microsoft.com/en-us/windows/desktop/api/Tbs/nf-tbs-tbsip_submit_command
214 func (context Context) SubmitCommand(
215 priority CommandPriority,
216 commandBuffer []byte,
217 responseBuffer []byte,
218 ) (uint32, error) {
219 responseBufferLen := uint32(len(responseBuffer))
220
221 // TBS_RESULT Tbsip_Submit_Command(
222 // _In_ TBS_HCONTEXT hContext,
223 // _In_ TBS_COMMAND_LOCALITY Locality,
224 // _In_ TBS_COMMAND_PRIORITY Priority,
225 // _In_ const PCBYTE *pabCommand,
226 // _In_ UINT32 cbCommand,
227 // _Out_ PBYTE *pabResult,
228 // _Inout_ UINT32 *pcbOutput
229 // );
230 if err := tbsSubmitCommand.Find(); err != nil {
231 return 0, err
232 }
233 result, _, _ := tbsSubmitCommand.Call(
234 uintptr(context),
235 uintptr(commandLocalityZero),
236 uintptr(priority),
237 sliceAddress(commandBuffer),
238 uintptr(len(commandBuffer)),
239 sliceAddress(responseBuffer),
240 uintptr(unsafe.Pointer(&responseBufferLen)),
241 )
242 return responseBufferLen, getError(result)
243 }
244
245 // GetTCGLog gets the system event log, returning the number of bytes written
246 // to logBuffer. If logBuffer is nil, the size of the TCG log is returned.
247 // ErrInsufficientBuffer is returned if the logBuffer is too short. On failure,
248 // the returned length is unspecified.
249 // https://docs.microsoft.com/en-us/windows/desktop/api/Tbs/nf-tbs-tbsi_get_tcg_log
250 func (context Context) GetTCGLog(logBuffer []byte) (uint32, error) {
251 logBufferLen := uint32(len(logBuffer))
252
253 // TBS_RESULT Tbsi_Get_TCG_Log(
254 // TBS_HCONTEXT hContext,
255 // PBYTE pOutputBuf,
256 // PUINT32 pOutputBufLen
257 // );
258 if err := tbsGetTCGLog.Find(); err != nil {
259 return 0, err
260 }
261 result, _, _ := tbsGetTCGLog.Call(
262 uintptr(context),
263 sliceAddress(logBuffer),
264 uintptr(unsafe.Pointer(&logBufferLen)),
265 )
266 return logBufferLen, getError(result)
267 }