Debian Codegraph @

src/App/PropertyPythonObject.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2009 Werner Mayer <wmayer[at]users.sourceforge.net> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This library is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU Library General Public *
8 * License as published by the Free Software Foundation; either *
9 * version 2 of the License, or (at your option) any later version. *
10 * *
11 * This library is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU Library General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Library General Public *
17 * License along with this library; see the file COPYING.LIB. If not, *
18 * write to the Free Software Foundation, Inc., 59 Temple Place, *
19 * Suite 330, Boston, MA 02111-1307, USA *
20 * *
21 ***************************************************************************/
22
23
24
25 #include <algorithm>
26 #include <iostream>
27 #include <string>
28 #include <vector>
29
30 #include <Base/Base64.h>
31 #include <Base/Console.h>
32 #include <Base/Interpreter.h>
33 #include <Base/Reader.h>
34 #include <Base/Writer.h>
35
36 #include "Application.h"
37 #include "PropertyPythonObject.h"
38 #include "DocumentObject.h"
39
40
41 using namespace App;
42
43 namespace {
44
45 /**
46 * @brief Check whether a path starts with a given directory prefix.
47 *
48 * @param[in] filePath The file path to check.
49 * @param[in] directory The directory prefix to match against.
50 * @return @c true if @p filePath starts with @p directory.
51 */
52 bool isUnderDirectory(std::string filePath, std::string directory)
53 {
54 std::ranges::replace(filePath, '\\', '/');
55 std::ranges::replace(directory, '\\', '/');
56 // Collapse repeated slashes (e.g. home path "build/debug//" + "Mod")
57 auto collapseSlashes = [](std::string& s) {
58 auto out = s.begin();
59 for (auto it = s.begin(); it != s.end(); ++it) {
60 if (*it == '/' && out != s.begin() && *(out - 1) == '/') {
61 continue;
62 }
63 *out++ = *it;
64 }
65 s.erase(out, s.end());
66 };
67 collapseSlashes(filePath);
68 collapseSlashes(directory);
69 if (!directory.empty() && directory.back() != '/') {
70 directory += '/';
71 }
72 return filePath.starts_with(directory);
73 }
74
75 /**
76 * @brief Check whether a module import should be allowed during document restore.
77 *
78 * Modules already in @c sys.modules are permitted -- they were loaded by FreeCAD core or addons
79 * during normal startup. For modules not yet loaded we use @c importlib.util.find_spec() to
80 * locate where the module would come from without executing it, then verify that path is under
81 * a FreeCAD module directory. This prevents a crafted FCStd from importing arbitrary modules
82 * (whose <tt>__init__.py</tt> could run malicious code on import) while still allowing
83 * legitimate lazy-loaded FreeCAD workbench modules to restore.
84 *
85 * @param[in] moduleName The fully qualified Python module name to check.
86 * @return @c true if the module is allowed, @c false otherwise.
87 */
88 bool isAllowedModule(const std::string& moduleName)
89 {
90 Py::Dict sysModules(PyImport_GetModuleDict());
91 if (sysModules.isNone()) {
92 return false;
93 }
94
95 // 1) Already loaded? Must be safe.
96 if (sysModules.hasKey(moduleName)) {
97 return true;
98 }
99
100 // 2) Is it *in* an already loaded module? Safe.
101 std::string::size_type dot = moduleName.find('.');
102 if (dot != std::string::npos) {
103 std::string topLevel = moduleName.substr(0, dot);
104 if (sysModules.hasKey(topLevel)) {
105 return true;
106 }
107 }
108
109 // 3) The complicated path. Use importlib.util.find_spec() to find the origin of the module,
110 // being careful to NOT load it (which is the code-execution vulnerability we're trying to
111 // avoid in the first place). See if it's in one of our "safe" paths, and if it is, allow it.
112 // Safe paths are a few subdirectories we recognize in the set "home", "resource", and
113 // "userData" paths. Don't allow modules from outside of these directories. Not 100% mitigation,
114 // but it's better than nothing.
115 PyObject* importlibUtil = PyImport_ImportModule("importlib.util");
116 if (!importlibUtil) {
117 PyErr_Clear();
118 return false;
119 }
120 Py::Module importlib(importlibUtil, true);
121 Py::Callable findSpec(importlib.getAttr("find_spec"));
122
123 // FreeCAD adds each workbench directory to sys.path individually (e.g. .../Mod/Assembly/),
124 // so a module stored as "Assembly.JointObject" in the FCStd is actually importable as just
125 // "JointObject". Try the full name first, then the part after the first dot.
126 std::vector<std::string> namesToTry = {moduleName};
127 if (dot != std::string::npos) {
128 namesToTry.push_back(moduleName.substr(dot + 1));
129 }
130 Py::Object spec;
131 for (const std::string& name : namesToTry) {
132 Py::Tuple args(1);
133 args.setItem(0, Py::String(name));
134 try {
135 spec = findSpec.apply(args);
136 }
137 catch (Py::Exception&) {
138 PyErr_Clear();
139 continue;
140 }
141 if (!spec.isNone()) {
142 break;
143 }
144 }
145 if (spec.isNone()) {
146 return false;
147 }
148
149 // Use FreeCAD.__ModDirs__ as the authoritative list of allowed module directories.
150 // This is populated during startup by FreeCADInit.py and includes built-in workbenches,
151 // user addons, and any additional configured module paths.
152 Py::Module freecad(PyImport_ImportModule("FreeCAD"), true);
153 if (!freecad.hasAttr("__ModDirs__") or !freecad.hasAttr("__MacroDirs__")) {
154 throw Py::RuntimeError("FreeCAD.__ModDirs__ or FreeCAD.__MacroDirs__ not set -- FreeCADInit.py has not run yet");
155 }
156 Py::List allowedDirs(freecad.getAttr("__ModDirs__"));
157 allowedDirs.extend(freecad.getAttr("__MacroDirs__"));
158 const int allowedDirsSize = static_cast<int>(allowedDirs.size());
159
160 auto isUnderFreeCAD = [&](const std::string& path) {
161 for (int i = 0; i < allowedDirsSize; ++i) {
162 if (isUnderDirectory(path, Py::String(allowedDirs[i]).as_std_string())) {
163 return true;
164 }
165 }
166 return false;
167 };
168
169 // Get the origin (i.e. the file path) from the spec.
170 Py::Object origin = spec.getAttr("origin");
171 if (!origin.isNone() && origin.isString()) {
172 return isUnderFreeCAD(Py::String(origin).as_std_string());
173 }
174
175 // No origin -- this could be a built-in module (why is an FCStd trying to load this? Very
176 // suspicious, block it) or a synthetic module from a FreeCAD migration finder like
177 // FemMigrateApp (which we will allow). Check whether the spec's loader itself comes from a
178 // FreeCAD module directory.
179 if (!spec.hasAttr("loader") || spec.getAttr("loader").isNone()) {
180 return false;
181 }
182 Py::Object loader = spec.getAttr("loader");
183 auto loaderType = loader.type();
184 if (!loaderType.hasAttr("__module__")) {
185 return false;
186 }
187 std::string loaderModuleName = Py::String(loaderType.getAttr("__module__")).as_std_string();
188 Py::Object loaderMod = sysModules.getItem(loaderModuleName);
189 return isUnderFreeCAD(Py::String(loaderMod.getAttr("__file__")).as_std_string());
190 }
191
192 } // anonymous namespace
193
194
195 TYPESYSTEM_SOURCE(App::PropertyPythonObject, App::Property)
196
197 PropertyPythonObject::PropertyPythonObject() = default;
198
199 PropertyPythonObject::~PropertyPythonObject()
200 {
201 // this is needed because the release of the pickled object may need the
202 // GIL. Thus, we grab the GIL and replace the pickled with an empty object
203 Base::PyGILStateLocker lock;
204 try {
205 this->object = Py::Object();
206 } catch (Py::TypeError &) {
207 Base::Console().warning("Py::TypeError Exception caught while destroying PropertyPythonObject\n");
208 }
209 }
210
211 void PropertyPythonObject::setValue(const Py::Object& py)
212 {
213 Base::PyGILStateLocker lock;
214 aboutToSetValue();
215 this->object = py;
216 hasSetValue();
217 }
218
219 Py::Object PropertyPythonObject::getValue() const
220 {
221 return object;
222 }
223
224 PyObject* PropertyPythonObject::getPyObject()
225 {
226 return Py::new_reference_to(this->object);
227 }
228
229 void PropertyPythonObject::setPyObject(PyObject* obj)
230 {
231 Base::PyGILStateLocker lock;
232 aboutToSetValue();
233 this->object = obj;
234 hasSetValue();
235 }
236
237 std::string PropertyPythonObject::toString() const
238 {
239 std::string repr;
240 Base::PyGILStateLocker lock;
241 try {
242 Py::Module pickle(PyImport_ImportModule("json"), true);
243 if (pickle.isNull()) {
244 throw Py::Exception();
245 }
246 Py::Callable method(pickle.getAttr(std::string("dumps")));
247 Py::Object dump;
248 if (this->object.hasAttr("dumps")) {
249 Py::Tuple args;
250 Py::Callable state(this->object.getAttr("dumps"));
251 dump = state.apply(args);
252 }
253 // support add-ons that use the old method names
254 else if (this->object.hasAttr("__getstate__")
255 #if PY_VERSION_HEX >= 0x030b0000
256 && this->object.getAttr("__getstate__").hasAttr("__func__")
257 #endif
258 ) {
259 Py::Tuple args;
260 Py::Callable state(this->object.getAttr("__getstate__"));
261 dump = state.apply(args);
262 }
263 else if (this->object.hasAttr("__dict__")) {
264 dump = this->object.getAttr("__dict__");
265 }
266 else {
267 dump = this->object;
268 }
269
270 Py::Tuple args(1);
271 args.setItem(0, dump);
272 Py::Object res = method.apply(args);
273 Py::String str(res);
274 repr = str.as_std_string("ascii");
275 }
276 catch (Py::Exception&) {
277 Py::String typestr(this->object.type().str());
278 Base::Console().error("PropertyPythonObject::toString(): failed for %s\n",
279 typestr.as_string().c_str());
280 Base::PyException e; // extract the Python error text
281 e.reportException();
282 }
283
284 return repr;
285 }
286
287 void PropertyPythonObject::fromString(const std::string& repr)
288 {
289 Base::PyGILStateLocker lock;
290 try {
291 if (repr.empty()) {
292 return;
293 }
294 Py::Module pickle(PyImport_ImportModule("json"), true);
295 if (pickle.isNull()) {
296 throw Py::Exception();
297 }
298 Py::Callable method(pickle.getAttr(std::string("loads")));
299 Py::Tuple args(1);
300 args.setItem(0, Py::String(repr));
301 Py::Object res = method.apply(args);
302
303 if (this->object.hasAttr("loads")) {
304 Py::Tuple args(1);
305 args.setItem(0, res);
306 Py::Callable state(this->object.getAttr("loads"));
307 state.apply(args);
308 }
309 // support add-ons that use the old method names
310 else if (this->object.hasAttr("__setstate__")
311 #if PY_VERSION_HEX >= 0x030b0000
312 && this->object.getAttr("__setstate__").hasAttr("__func__")
313 #endif
314 ) {
315 Py::Tuple args(1);
316 args.setItem(0, res);
317 Py::Callable state(this->object.getAttr("__setstate__"));
318 state.apply(args);
319 }
320 else if (this->object.hasAttr("__dict__")) {
321 if (!res.isNone()) {
322 this->object.setAttr("__dict__", res);
323 }
324 }
325 else {
326 this->object = res;
327 }
328 }
329 catch (Py::Exception&) {
330 Base::PyException e; // extract the Python error text
331 e.reportException();
332 }
333 }
334
335
336 std::string PropertyPythonObject::encodeValue(const std::string& str) const
337 {
338 std::string tmp;
339 for (char it : str) {
340 if (it == '<') {
341 tmp += "&lt;";
342 }
343 else if (it == '"') {
344 tmp += "&quot;";
345 }
346 else if (it == '&') {
347 tmp += "&amp;";
348 }
349 else if (it == '>') {
350 tmp += "&gt";
351 }
352 else if (it == '\n') {
353 tmp += "\\n";
354 }
355 else {
356 tmp += it;
357 }
358 }
359
360 return tmp;
361 }
362
363 std::string PropertyPythonObject::decodeValue(const std::string& str) const
364 {
365 std::string tmp;
366 for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) {
367 if (*it == '\\') {
368 ++it;
369 if (it != str.end() && *it == 'n') {
370 tmp += '\n';
371 }
372 }
373 else {
374 tmp += *it;
375 }
376 }
377
378 return tmp;
379 }
380
381 void PropertyPythonObject::saveObject(Base::Writer& writer) const
382 {
383 Base::PyGILStateLocker lock;
384 try {
385 PropertyContainer* parent = this->getContainer();
386 if (parent->isDerivedFrom(Base::Type::fromName("App::DocumentObject"))) {
387 if (this->object.hasAttr("__object__")) {
388 writer.Stream() << " object=\"yes\"";
389 }
390 }
391 if (parent->isDerivedFrom(Base::Type::fromName("Gui::ViewProvider"))) {
392 if (this->object.hasAttr("__vobject__")) {
393 writer.Stream() << " vobject=\"yes\"";
394 }
395 }
396 }
397 catch (Py::Exception& e) {
398 e.clear();
399 }
400 }
401
402 void PropertyPythonObject::restoreObject(Base::XMLReader& reader)
403 {
404 Base::PyGILStateLocker lock;
405 try {
406 PropertyContainer* parent = this->getContainer();
407 if (reader.hasAttribute("object")) {
408 if (strcmp(reader.getAttribute<const char*>("object"), "yes") == 0) {
409 Py::Object obj = Py::asObject(parent->getPyObject());
410 this->object.setAttr("__object__", obj);
411 }
412 }
413 if (reader.hasAttribute("vobject")) {
414 if (strcmp(reader.getAttribute<const char*>("vobject"), "yes") == 0) {
415 Py::Object obj = Py::asObject(parent->getPyObject());
416 this->object.setAttr("__vobject__", obj);
417 }
418 }
419 }
420 catch (Py::Exception& e) {
421 e.clear();
422 }
423 catch (const Base::Exception& e) {
424 Base::Console().error("%s\n", e.what());
425 }
426 catch (...) {
427 Base::Console().error("Critical error in PropertyPythonObject::restoreObject\n");
428 }
429 }
430
431 void PropertyPythonObject::Save(Base::Writer& writer) const
432 {
433 std::string repr = this->toString();
434 repr = Base::base64_encode((const unsigned char*)repr.c_str(), repr.size());
435 std::string val = /*encodeValue*/ (repr);
436 writer.Stream() << writer.ind() << "<Python value=\"" << val << R"(" encoded="yes")";
437
438 Base::PyGILStateLocker lock;
439 try {
440 if (this->object.hasAttr("__module__") && this->object.hasAttr("__class__")) {
441 Py::String mod(this->object.getAttr("__module__"));
442 Py::Object cls(this->object.getAttr("__class__"));
443 if (cls.hasAttr("__name__")) {
444 Py::String name(cls.getAttr("__name__"));
445 writer.Stream() << " module=\"" << (std::string)mod << "\""
446 << " class=\"" << (std::string)name << "\"";
447 }
448 }
449 else {
450 writer.Stream() << " json=\"yes\"";
451 }
452 }
453 catch (Py::Exception&) {
454 Base::PyException e; // extract the Python error text
455 e.reportException();
456 }
457
458 saveObject(writer);
459 writer.Stream() << "/>" << std::endl;
460 }
461
462 void PropertyPythonObject::Restore(Base::XMLReader& reader)
463 {
464 reader.readElement("Python");
465 if (reader.hasAttribute("file")) {
466 std::string file(reader.getAttribute<const char*>("file"));
467 reader.addFile(file.c_str(), this);
468 }
469 else {
470 bool load_json = false;
471 bool load_failed = false;
472 std::string buffer = reader.getAttribute<const char*>("value");
473 if (reader.hasAttribute("encoded") && strcmp(reader.getAttribute<const char*>("encoded"), "yes") == 0) {
474 buffer = Base::base64_decode(buffer);
475 }
476 else {
477 buffer = decodeValue(buffer);
478 }
479
480 Base::PyGILStateLocker lock;
481 try {
482 if (reader.hasAttribute("module") && reader.hasAttribute("class")) {
483 std::string moduleName = reader.getAttribute<const char*>("module");
484 if (!isAllowedModule(moduleName)) {
485 Base::Console().warning(
486 "PropertyPythonObject::Restore: blocked import of module '%s' during"
487 " document restore. Only modules from FreeCAD or installed addons"
488 " are permitted.\n",
489 moduleName.c_str());
490 throw Py::ImportError("module not permitted: " + moduleName);
491 }
492 Py::Module mod(PyImport_ImportModule(moduleName.c_str()), true);
493 if (mod.isNull()) {
494 throw Py::Exception();
495 }
496 std::string className = reader.getAttribute<const char*>("class");
497 PyObject* cls = mod.getAttr(className).ptr();
498 if (!cls) {
499 std::stringstream s;
500 s << "Module " << moduleName << " has no class " << className;
501 throw Py::AttributeError(s.str());
502 }
503 if (PyType_Check(cls)) {
504 this->object = PyType_GenericAlloc((PyTypeObject*)cls, 0);
505 }
506 else {
507 throw Py::TypeError("neither class nor type object");
508 }
509 load_json = true;
510 }
511 else if (reader.hasAttribute("json")) {
512 load_json = true;
513 }
514 }
515 catch (Py::Exception&) {
516 Base::PyException e; // extract the Python error text
517 e.reportException();
518 this->object = Py::None();
519 load_failed = true;
520 }
521
522 aboutToSetValue();
523 if (load_json) {
524 this->fromString(buffer);
525 }
526 else if (!load_failed) {
527 Base::Console().warning(
528 "PropertyPythonObject::Restore: unsupported serialisation: %s\n",
529 buffer.c_str());
530 }
531 restoreObject(reader);
532 hasSetValue();
533 }
534 }
535
536 void PropertyPythonObject::SaveDocFile(Base::Writer& writer) const
537 {
538 std::string buffer = this->toString();
539 for (char it : buffer) {
540 writer.Stream().put(it);
541 }
542 }
543
544 void PropertyPythonObject::RestoreDocFile(Base::Reader& reader)
545 {
546 aboutToSetValue();
547 std::string buffer;
548 char ch {};
549 while (reader.get(ch)) {
550 buffer.push_back(ch);
551 }
552 this->fromString(buffer);
553 hasSetValue();
554 }
555
556 unsigned int PropertyPythonObject::getMemSize() const
557 {
558 return sizeof(Py::Object);
559 }
560
561 Property* PropertyPythonObject::Copy() const
562 {
563 PropertyPythonObject* p = new PropertyPythonObject();
564 Base::PyGILStateLocker lock;
565 p->object = this->object;
566 return p;
567 }
568
569 void PropertyPythonObject::Paste(const Property& from)
570 {
571 if (from.is<PropertyPythonObject>()) {
572 Base::PyGILStateLocker lock;
573 aboutToSetValue();
574 this->object = static_cast<const PropertyPythonObject&>(from).object;
575 hasSetValue();
576 }
577 }