erdigo-sdk 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
erdigo_sdk/__init__.py ADDED
@@ -0,0 +1,50 @@
1
+ """Official Erdigo SDK for Python.
2
+
3
+ Write pins, markers, notes, photos and tracks to an Erdigo receiver on the local network, over the integration-v1
4
+ protocol. See README.md for how to pair and write, and spec/integration-v1.md for the protocol.
5
+ """
6
+
7
+ from .client import ErdigoClient, RetryPolicy
8
+ from .discovery import DISCOVER, ReceiverTarget
9
+ from .errors import ErdigoError, ErrorKind, StorageProblem
10
+ from .identity import DeviceIdentity, ReceiverPairing
11
+ from .messages import ReceiverError
12
+ from .model import LIMITS_V1, Coordinate, ItemKind, Limits, MarkerColor, PairingCode, PairingTicket, PhotoType, TrackPoint
13
+ from .pairing import SDK_NAME, ConfirmReceiverKey, pair
14
+ from .protocol import ErrorCode, WireError, fingerprint, short_fingerprint
15
+ from .store import DeviceStore, FileDeviceStore, InMemoryDeviceStore, default_directory
16
+
17
+ __version__ = "1.0.0"
18
+
19
+ __all__ = [
20
+ "DISCOVER",
21
+ "LIMITS_V1",
22
+ "SDK_NAME",
23
+ "ConfirmReceiverKey",
24
+ "Coordinate",
25
+ "DeviceIdentity",
26
+ "DeviceStore",
27
+ "ErdigoClient",
28
+ "ErdigoError",
29
+ "ErrorCode",
30
+ "ErrorKind",
31
+ "FileDeviceStore",
32
+ "InMemoryDeviceStore",
33
+ "ItemKind",
34
+ "Limits",
35
+ "MarkerColor",
36
+ "PairingCode",
37
+ "PairingTicket",
38
+ "PhotoType",
39
+ "ReceiverError",
40
+ "ReceiverPairing",
41
+ "ReceiverTarget",
42
+ "RetryPolicy",
43
+ "StorageProblem",
44
+ "TrackPoint",
45
+ "WireError",
46
+ "default_directory",
47
+ "fingerprint",
48
+ "pair",
49
+ "short_fingerprint",
50
+ ]
erdigo_sdk/__main__.py ADDED
@@ -0,0 +1,7 @@
1
+ """``python -m erdigo_sdk`` runs the erdigo-send tool."""
2
+
3
+ import sys
4
+
5
+ from .cli import main
6
+
7
+ sys.exit(main())
erdigo_sdk/_windows.py ADDED
@@ -0,0 +1,254 @@
1
+ """DPAPI and file access lists on Windows, through ctypes. Nothing here is used on other systems."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ctypes
6
+ import sys
7
+ from ctypes import wintypes
8
+
9
+ if sys.platform != "win32": # pragma: no cover - imported on Windows only
10
+ raise ImportError("Windows only")
11
+
12
+ _crypt32 = ctypes.WinDLL("crypt32", use_last_error=True)
13
+ _kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
14
+ _advapi32 = ctypes.WinDLL("advapi32", use_last_error=True)
15
+
16
+ _CRYPTPROTECT_UI_FORBIDDEN = 0x1
17
+ _TOKEN_QUERY = 0x0008
18
+ _TOKEN_USER = 1
19
+ _SE_FILE_OBJECT = 1
20
+ _OWNER_SECURITY_INFORMATION = 0x1
21
+ _DACL_SECURITY_INFORMATION = 0x4
22
+ _ACL_SIZE_INFORMATION = 2
23
+ _ACCESS_ALLOWED_ACE_TYPE = 0x0
24
+ #: Every type of ACE that allows something. Only the plain one names a SID where this code reads it.
25
+ _ALLOWED_ACE_TYPES = {0x0, 0x4, 0x5, 0x9, 0xB}
26
+ _WIN_LOCAL_SYSTEM_SID = 22
27
+ _WIN_BUILTIN_ADMINISTRATORS_SID = 26
28
+ _SDDL_REVISION_1 = 1
29
+
30
+
31
+ class _DataBlob(ctypes.Structure):
32
+ _fields_ = [("cbData", wintypes.DWORD), ("pbData", ctypes.POINTER(ctypes.c_char))]
33
+
34
+
35
+ class _AceHeader(ctypes.Structure):
36
+ _fields_ = [("AceType", wintypes.BYTE), ("AceFlags", wintypes.BYTE), ("AceSize", wintypes.WORD)]
37
+
38
+
39
+ class _AclSizeInformation(ctypes.Structure):
40
+ _fields_ = [("AceCount", wintypes.DWORD), ("AclBytesInUse", wintypes.DWORD), ("AclBytesFree", wintypes.DWORD)]
41
+
42
+
43
+ class _SecurityAttributes(ctypes.Structure):
44
+ _fields_ = [("nLength", wintypes.DWORD), ("lpSecurityDescriptor", wintypes.LPVOID), ("bInheritHandle", wintypes.BOOL)]
45
+
46
+
47
+ _crypt32.CryptProtectData.argtypes = [
48
+ ctypes.POINTER(_DataBlob), wintypes.LPCWSTR, ctypes.POINTER(_DataBlob), wintypes.LPVOID, wintypes.LPVOID, wintypes.DWORD,
49
+ ctypes.POINTER(_DataBlob),
50
+ ]
51
+ _crypt32.CryptProtectData.restype = wintypes.BOOL
52
+ _crypt32.CryptUnprotectData.argtypes = [
53
+ ctypes.POINTER(_DataBlob), ctypes.POINTER(wintypes.LPWSTR), ctypes.POINTER(_DataBlob), wintypes.LPVOID, wintypes.LPVOID,
54
+ wintypes.DWORD, ctypes.POINTER(_DataBlob),
55
+ ]
56
+ _crypt32.CryptUnprotectData.restype = wintypes.BOOL
57
+ _kernel32.LocalFree.argtypes = [wintypes.HLOCAL]
58
+ _kernel32.LocalFree.restype = wintypes.HLOCAL
59
+ _kernel32.GetCurrentProcess.restype = wintypes.HANDLE
60
+ _kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
61
+ _kernel32.CreateDirectoryW.argtypes = [wintypes.LPCWSTR, ctypes.POINTER(_SecurityAttributes)]
62
+ _kernel32.CreateDirectoryW.restype = wintypes.BOOL
63
+ _advapi32.OpenProcessToken.argtypes = [wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE)]
64
+ _advapi32.OpenProcessToken.restype = wintypes.BOOL
65
+ _advapi32.GetTokenInformation.argtypes = [wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)]
66
+ _advapi32.GetTokenInformation.restype = wintypes.BOOL
67
+ _advapi32.GetNamedSecurityInfoW.argtypes = [
68
+ wintypes.LPCWSTR, ctypes.c_int, wintypes.DWORD, ctypes.POINTER(wintypes.LPVOID), ctypes.POINTER(wintypes.LPVOID),
69
+ ctypes.POINTER(wintypes.LPVOID), ctypes.POINTER(wintypes.LPVOID), ctypes.POINTER(wintypes.LPVOID),
70
+ ]
71
+ _advapi32.GetNamedSecurityInfoW.restype = wintypes.DWORD
72
+ _advapi32.GetAclInformation.argtypes = [wintypes.LPVOID, wintypes.LPVOID, wintypes.DWORD, ctypes.c_int]
73
+ _advapi32.GetAclInformation.restype = wintypes.BOOL
74
+ _advapi32.GetAce.argtypes = [wintypes.LPVOID, wintypes.DWORD, ctypes.POINTER(wintypes.LPVOID)]
75
+ _advapi32.GetAce.restype = wintypes.BOOL
76
+ _advapi32.EqualSid.argtypes = [wintypes.LPVOID, wintypes.LPVOID]
77
+ _advapi32.EqualSid.restype = wintypes.BOOL
78
+ _advapi32.IsWellKnownSid.argtypes = [wintypes.LPVOID, ctypes.c_int]
79
+ _advapi32.IsWellKnownSid.restype = wintypes.BOOL
80
+ _advapi32.IsValidSid.argtypes = [wintypes.LPVOID]
81
+ _advapi32.IsValidSid.restype = wintypes.BOOL
82
+ _advapi32.ConvertSidToStringSidW.argtypes = [wintypes.LPVOID, ctypes.POINTER(wintypes.LPWSTR)]
83
+ _advapi32.ConvertSidToStringSidW.restype = wintypes.BOOL
84
+ _advapi32.ConvertStringSidToSidW.argtypes = [wintypes.LPCWSTR, ctypes.POINTER(wintypes.LPVOID)]
85
+ _advapi32.ConvertStringSidToSidW.restype = wintypes.BOOL
86
+ _advapi32.ConvertStringSecurityDescriptorToSecurityDescriptorW.argtypes = [
87
+ wintypes.LPCWSTR, wintypes.DWORD, ctypes.POINTER(wintypes.LPVOID), ctypes.POINTER(wintypes.ULONG),
88
+ ]
89
+ _advapi32.ConvertStringSecurityDescriptorToSecurityDescriptorW.restype = wintypes.BOOL
90
+
91
+ _ENTROPY = b"erdigo-integration-v1/device-key"
92
+
93
+
94
+ class DpapiError(OSError):
95
+ """DPAPI refused. The key belongs to another Windows user or computer, or the data is damaged."""
96
+
97
+
98
+ def _blob(data: bytes) -> tuple:
99
+ buffer = ctypes.create_string_buffer(data, len(data))
100
+ return _DataBlob(len(data), ctypes.cast(buffer, ctypes.POINTER(ctypes.c_char))), buffer
101
+
102
+
103
+ def _take(blob: _DataBlob) -> bytes:
104
+ try:
105
+ return ctypes.string_at(blob.pbData, blob.cbData)
106
+ finally:
107
+ _kernel32.LocalFree(ctypes.cast(blob.pbData, wintypes.HLOCAL))
108
+
109
+
110
+ def protect(data: bytes) -> bytes:
111
+ """Encrypts with DPAPI for the current user, with entropy that ties the result to this purpose."""
112
+ source, _source_buffer = _blob(data)
113
+ entropy, _entropy_buffer = _blob(_ENTROPY)
114
+ output = _DataBlob()
115
+ if not _crypt32.CryptProtectData(ctypes.byref(source), None, ctypes.byref(entropy), None, None, _CRYPTPROTECT_UI_FORBIDDEN, ctypes.byref(output)):
116
+ raise DpapiError(ctypes.get_last_error(), "Windows could not encrypt the device key")
117
+ return _take(output)
118
+
119
+
120
+ def unprotect(data: bytes) -> bytes:
121
+ source, _source_buffer = _blob(data)
122
+ entropy, _entropy_buffer = _blob(_ENTROPY)
123
+ output = _DataBlob()
124
+ if not _crypt32.CryptUnprotectData(ctypes.byref(source), None, ctypes.byref(entropy), None, None, _CRYPTPROTECT_UI_FORBIDDEN, ctypes.byref(output)):
125
+ raise DpapiError(ctypes.get_last_error(), "Windows could not decrypt the device key")
126
+ return _take(output)
127
+
128
+
129
+ def _current_user_sid() -> ctypes.Array:
130
+ """The current user's SID, copied into a buffer this module owns."""
131
+ token = wintypes.HANDLE()
132
+ if not _advapi32.OpenProcessToken(_kernel32.GetCurrentProcess(), _TOKEN_QUERY, ctypes.byref(token)):
133
+ raise ctypes.WinError(ctypes.get_last_error())
134
+ try:
135
+ needed = wintypes.DWORD()
136
+ _advapi32.GetTokenInformation(token, _TOKEN_USER, None, 0, ctypes.byref(needed))
137
+ buffer = ctypes.create_string_buffer(needed.value)
138
+ if not _advapi32.GetTokenInformation(token, _TOKEN_USER, buffer, needed, ctypes.byref(needed)):
139
+ raise ctypes.WinError(ctypes.get_last_error())
140
+ # TOKEN_USER starts with SID_AND_ATTRIBUTES, which starts with a pointer to the SID inside this buffer.
141
+ return buffer
142
+ finally:
143
+ _kernel32.CloseHandle(token)
144
+
145
+
146
+ def _sid_pointer(token_user: ctypes.Array) -> wintypes.LPVOID:
147
+ return ctypes.cast(token_user, ctypes.POINTER(wintypes.LPVOID))[0]
148
+
149
+
150
+ def _current_user_sid_string() -> str:
151
+ token_user = _current_user_sid()
152
+ text = wintypes.LPWSTR()
153
+ if not _advapi32.ConvertSidToStringSidW(_sid_pointer(token_user), ctypes.byref(text)):
154
+ raise ctypes.WinError(ctypes.get_last_error())
155
+ try:
156
+ return text.value
157
+ finally:
158
+ _kernel32.LocalFree(ctypes.cast(text, wintypes.HLOCAL))
159
+
160
+
161
+ #: OWNER RIGHTS, which stands for whoever owns the object.
162
+ _OWNER_RIGHTS = "S-1-3-4"
163
+
164
+
165
+ def _sid_from_string(text: str) -> wintypes.LPVOID:
166
+ """A SID from its text. The caller frees it with LocalFree."""
167
+ sid = wintypes.LPVOID()
168
+ if not _advapi32.ConvertStringSidToSidW(text, ctypes.byref(sid)):
169
+ raise ctypes.WinError(ctypes.get_last_error())
170
+ return sid
171
+
172
+
173
+ def has_private_access_list(path: str) -> bool:
174
+ """True if nobody but the current user, SYSTEM and the Administrators group is allowed anything on ``path``.
175
+
176
+ An entry for OWNER RIGHTS counts as the owner, and so is allowed when one of those owns ``path``. Python 3.13 and
177
+ later give a folder made with mode 0o700 on Windows, as ``tempfile.mkdtemp`` makes it, exactly that entry beside
178
+ SYSTEM and the Administrators group, and the files made in it inherit it.
179
+
180
+ A missing access list allows everyone, so it is refused. An allowing entry of a kind this code does not read is
181
+ refused too, rather than guessed at.
182
+ """
183
+ token_user = _current_user_sid()
184
+ user = _sid_pointer(token_user)
185
+ owner_rights = _sid_from_string(_OWNER_RIGHTS)
186
+ try:
187
+ return _has_private_access_list(path, user, owner_rights)
188
+ finally:
189
+ _kernel32.LocalFree(ctypes.cast(owner_rights, wintypes.HLOCAL))
190
+
191
+
192
+ def _has_private_access_list(path: str, user: wintypes.LPVOID, owner_rights: wintypes.LPVOID) -> bool:
193
+ def trusted(sid: wintypes.LPVOID) -> bool:
194
+ return bool(
195
+ _advapi32.EqualSid(sid, user)
196
+ or _advapi32.IsWellKnownSid(sid, _WIN_LOCAL_SYSTEM_SID)
197
+ or _advapi32.IsWellKnownSid(sid, _WIN_BUILTIN_ADMINISTRATORS_SID)
198
+ )
199
+
200
+ owner = wintypes.LPVOID()
201
+ dacl = wintypes.LPVOID()
202
+ descriptor = wintypes.LPVOID()
203
+ status = _advapi32.GetNamedSecurityInfoW(
204
+ path, _SE_FILE_OBJECT, _OWNER_SECURITY_INFORMATION | _DACL_SECURITY_INFORMATION,
205
+ ctypes.byref(owner), None, ctypes.byref(dacl), None, ctypes.byref(descriptor),
206
+ )
207
+ if status != 0:
208
+ raise ctypes.WinError(status)
209
+ try:
210
+ owner_is_trusted = bool(owner.value) and _advapi32.IsValidSid(owner) and trusted(owner)
211
+ if not dacl.value:
212
+ return False
213
+ information = _AclSizeInformation()
214
+ if not _advapi32.GetAclInformation(dacl, ctypes.byref(information), ctypes.sizeof(information), _ACL_SIZE_INFORMATION):
215
+ raise ctypes.WinError(ctypes.get_last_error())
216
+ for index in range(information.AceCount):
217
+ ace = wintypes.LPVOID()
218
+ if not _advapi32.GetAce(dacl, index, ctypes.byref(ace)):
219
+ raise ctypes.WinError(ctypes.get_last_error())
220
+ header = ctypes.cast(ace, ctypes.POINTER(_AceHeader)).contents
221
+ if header.AceType not in _ALLOWED_ACE_TYPES:
222
+ continue
223
+ if header.AceType != _ACCESS_ALLOWED_ACE_TYPE:
224
+ return False
225
+ # ACCESS_ALLOWED_ACE: the header, a 4-byte mask, then the SID.
226
+ sid = wintypes.LPVOID(ace.value + ctypes.sizeof(_AceHeader) + 4)
227
+ if not _advapi32.IsValidSid(sid):
228
+ return False
229
+ if trusted(sid):
230
+ continue
231
+ if owner_is_trusted and _advapi32.EqualSid(sid, owner_rights):
232
+ continue
233
+ return False
234
+ return True
235
+ finally:
236
+ _kernel32.LocalFree(ctypes.cast(descriptor, wintypes.HLOCAL))
237
+
238
+
239
+ def create_private_directory(path: str) -> None:
240
+ """Creates a folder whose access list is protected from inheritance and grants the current user alone. Files made
241
+ in it inherit that list. Raises FileExistsError if it is already there."""
242
+ sddl = f"D:P(A;OICI;FA;;;{_current_user_sid_string()})"
243
+ descriptor = wintypes.LPVOID()
244
+ if not _advapi32.ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl, _SDDL_REVISION_1, ctypes.byref(descriptor), None):
245
+ raise ctypes.WinError(ctypes.get_last_error())
246
+ try:
247
+ attributes = _SecurityAttributes(ctypes.sizeof(_SecurityAttributes), descriptor, False)
248
+ if not _kernel32.CreateDirectoryW(path, ctypes.byref(attributes)):
249
+ error = ctypes.get_last_error()
250
+ if error == 183: # ERROR_ALREADY_EXISTS
251
+ raise FileExistsError(path)
252
+ raise ctypes.WinError(error)
253
+ finally:
254
+ _kernel32.LocalFree(ctypes.cast(descriptor, wintypes.HLOCAL))