Package paramiko :: Module _winapi
[frames] | no frames]

Source Code for Module paramiko._winapi

  1  """ 
  2  Windows API functions implemented as ctypes functions and classes as found 
  3  in jaraco.windows (2.10). 
  4   
  5  If you encounter issues with this module, please consider reporting the issues 
  6  in jaraco.windows and asking the author to port the fixes back here. 
  7  """ 
  8   
  9  import ctypes 
 10  import ctypes.wintypes 
 11  from paramiko.py3compat import u 
 12  try: 
 13      import builtins 
 14  except ImportError: 
 15      import __builtin__ as builtins 
 16   
 17  try: 
 18      USHORT = ctypes.wintypes.USHORT 
 19  except AttributeError: 
 20      USHORT = ctypes.c_ushort 
21 22 ###################### 23 # jaraco.windows.error 24 25 -def format_system_message(errno):
26 """ 27 Call FormatMessage with a system error number to retrieve 28 the descriptive error message. 29 """ 30 # first some flags used by FormatMessageW 31 ALLOCATE_BUFFER = 0x100 32 ARGUMENT_ARRAY = 0x2000 33 FROM_HMODULE = 0x800 34 FROM_STRING = 0x400 35 FROM_SYSTEM = 0x1000 36 IGNORE_INSERTS = 0x200 37 38 # Let FormatMessageW allocate the buffer (we'll free it below) 39 # Also, let it know we want a system error message. 40 flags = ALLOCATE_BUFFER | FROM_SYSTEM 41 source = None 42 message_id = errno 43 language_id = 0 44 result_buffer = ctypes.wintypes.LPWSTR() 45 buffer_size = 0 46 arguments = None 47 format_bytes = ctypes.windll.kernel32.FormatMessageW( 48 flags, 49 source, 50 message_id, 51 language_id, 52 ctypes.byref(result_buffer), 53 buffer_size, 54 arguments, 55 ) 56 # note the following will cause an infinite loop if GetLastError 57 # repeatedly returns an error that cannot be formatted, although 58 # this should not happen. 59 handle_nonzero_success(format_bytes) 60 message = result_buffer.value 61 ctypes.windll.kernel32.LocalFree(result_buffer) 62 return message
63
64 65 -class WindowsError(builtins.WindowsError):
66 "more info about errors at http://msdn.microsoft.com/en-us/library/ms681381(VS.85).aspx" 67
68 - def __init__(self, value=None):
69 if value is None: 70 value = ctypes.windll.kernel32.GetLastError() 71 strerror = format_system_message(value) 72 super(WindowsError, self).__init__(value, strerror)
73 74 @property
75 - def message(self):
76 return self.strerror
77 78 @property
79 - def code(self):
80 return self.winerror
81
82 - def __str__(self):
83 return self.message
84
85 - def __repr__(self):
86 return '{self.__class__.__name__}({self.winerror})'.format(**vars())
87
88 -def handle_nonzero_success(result):
89 if result == 0: 90 raise WindowsError()
91 92 93 CreateFileMapping = ctypes.windll.kernel32.CreateFileMappingW 94 CreateFileMapping.argtypes = [ 95 ctypes.wintypes.HANDLE, 96 ctypes.c_void_p, 97 ctypes.wintypes.DWORD, 98 ctypes.wintypes.DWORD, 99 ctypes.wintypes.DWORD, 100 ctypes.wintypes.LPWSTR, 101 ] 102 CreateFileMapping.restype = ctypes.wintypes.HANDLE 103 104 MapViewOfFile = ctypes.windll.kernel32.MapViewOfFile 105 MapViewOfFile.restype = ctypes.wintypes.HANDLE
106 107 -class MemoryMap(object):
108 """ 109 A memory map object which can have security attributes overrideden. 110 """
111 - def __init__(self, name, length, security_attributes=None):
112 self.name = name 113 self.length = length 114 self.security_attributes = security_attributes 115 self.pos = 0
116
117 - def __enter__(self):
118 p_SA = ( 119 ctypes.byref(self.security_attributes) 120 if self.security_attributes else None 121 ) 122 INVALID_HANDLE_VALUE = -1 123 PAGE_READWRITE = 0x4 124 FILE_MAP_WRITE = 0x2 125 filemap = ctypes.windll.kernel32.CreateFileMappingW( 126 INVALID_HANDLE_VALUE, p_SA, PAGE_READWRITE, 0, self.length, 127 u(self.name)) 128 handle_nonzero_success(filemap) 129 if filemap == INVALID_HANDLE_VALUE: 130 raise Exception("Failed to create file mapping") 131 self.filemap = filemap 132 self.view = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, 0) 133 return self
134
135 - def seek(self, pos):
136 self.pos = pos
137
138 - def write(self, msg):
139 n = len(msg) 140 if self.pos + n >= self.length: # A little safety. 141 raise ValueError("Refusing to write %d bytes" % n) 142 ctypes.windll.kernel32.RtlMoveMemory(self.view + self.pos, msg, n) 143 self.pos += n
144
145 - def read(self, n):
146 """ 147 Read n bytes from mapped view. 148 """ 149 out = ctypes.create_string_buffer(n) 150 ctypes.windll.kernel32.RtlMoveMemory(out, self.view + self.pos, n) 151 self.pos += n 152 return out.raw
153
154 - def __exit__(self, exc_type, exc_val, tb):
155 ctypes.windll.kernel32.UnmapViewOfFile(self.view) 156 ctypes.windll.kernel32.CloseHandle(self.filemap)
157
158 ######################### 159 # jaraco.windows.security 160 161 -class TokenInformationClass:
162 TokenUser = 1
163
164 -class TOKEN_USER(ctypes.Structure):
165 num = 1 166 _fields_ = [ 167 ('SID', ctypes.c_void_p), 168 ('ATTRIBUTES', ctypes.wintypes.DWORD), 169 ]
170
171 172 -class SECURITY_DESCRIPTOR(ctypes.Structure):
173 """ 174 typedef struct _SECURITY_DESCRIPTOR 175 { 176 UCHAR Revision; 177 UCHAR Sbz1; 178 SECURITY_DESCRIPTOR_CONTROL Control; 179 PSID Owner; 180 PSID Group; 181 PACL Sacl; 182 PACL Dacl; 183 } SECURITY_DESCRIPTOR; 184 """ 185 SECURITY_DESCRIPTOR_CONTROL = USHORT 186 REVISION = 1 187 188 _fields_ = [ 189 ('Revision', ctypes.c_ubyte), 190 ('Sbz1', ctypes.c_ubyte), 191 ('Control', SECURITY_DESCRIPTOR_CONTROL), 192 ('Owner', ctypes.c_void_p), 193 ('Group', ctypes.c_void_p), 194 ('Sacl', ctypes.c_void_p), 195 ('Dacl', ctypes.c_void_p), 196 ]
197
198 -class SECURITY_ATTRIBUTES(ctypes.Structure):
199 """ 200 typedef struct _SECURITY_ATTRIBUTES { 201 DWORD nLength; 202 LPVOID lpSecurityDescriptor; 203 BOOL bInheritHandle; 204 } SECURITY_ATTRIBUTES; 205 """ 206 _fields_ = [ 207 ('nLength', ctypes.wintypes.DWORD), 208 ('lpSecurityDescriptor', ctypes.c_void_p), 209 ('bInheritHandle', ctypes.wintypes.BOOL), 210 ] 211
212 - def __init__(self, *args, **kwargs):
213 super(SECURITY_ATTRIBUTES, self).__init__(*args, **kwargs) 214 self.nLength = ctypes.sizeof(SECURITY_ATTRIBUTES)
215
216 - def _get_descriptor(self):
217 return self._descriptor
218 - def _set_descriptor(self, descriptor):
219 self._descriptor = descriptor 220 self.lpSecurityDescriptor = ctypes.addressof(descriptor)
221 descriptor = property(_get_descriptor, _set_descriptor)
222
223 -def GetTokenInformation(token, information_class):
224 """ 225 Given a token, get the token information for it. 226 """ 227 data_size = ctypes.wintypes.DWORD() 228 ctypes.windll.advapi32.GetTokenInformation(token, information_class.num, 229 0, 0, ctypes.byref(data_size)) 230 data = ctypes.create_string_buffer(data_size.value) 231 handle_nonzero_success(ctypes.windll.advapi32.GetTokenInformation(token, 232 information_class.num, 233 ctypes.byref(data), ctypes.sizeof(data), 234 ctypes.byref(data_size))) 235 return ctypes.cast(data, ctypes.POINTER(TOKEN_USER)).contents
236
237 -class TokenAccess:
238 TOKEN_QUERY = 0x8
239
240 -def OpenProcessToken(proc_handle, access):
241 result = ctypes.wintypes.HANDLE() 242 proc_handle = ctypes.wintypes.HANDLE(proc_handle) 243 handle_nonzero_success(ctypes.windll.advapi32.OpenProcessToken( 244 proc_handle, access, ctypes.byref(result))) 245 return result
246
247 -def get_current_user():
248 """ 249 Return a TOKEN_USER for the owner of this process. 250 """ 251 process = OpenProcessToken( 252 ctypes.windll.kernel32.GetCurrentProcess(), 253 TokenAccess.TOKEN_QUERY, 254 ) 255 return GetTokenInformation(process, TOKEN_USER)
256
257 -def get_security_attributes_for_user(user=None):
258 """ 259 Return a SECURITY_ATTRIBUTES structure with the SID set to the 260 specified user (uses current user if none is specified). 261 """ 262 if user is None: 263 user = get_current_user() 264 265 assert isinstance(user, TOKEN_USER), "user must be TOKEN_USER instance" 266 267 SD = SECURITY_DESCRIPTOR() 268 SA = SECURITY_ATTRIBUTES() 269 # by attaching the actual security descriptor, it will be garbage- 270 # collected with the security attributes 271 SA.descriptor = SD 272 SA.bInheritHandle = 1 273 274 ctypes.windll.advapi32.InitializeSecurityDescriptor(ctypes.byref(SD), 275 SECURITY_DESCRIPTOR.REVISION) 276 ctypes.windll.advapi32.SetSecurityDescriptorOwner(ctypes.byref(SD), 277 user.SID, 0) 278 return SA
279