Skip to content

Commit b52eb46

Browse files
authored
Fix #12065 restrict PATH to OM directories (#13369)
* Fix #12065: restrict PATH to OM directories * boost system library is not needed anymore
1 parent 203c26b commit b52eb46

File tree

17 files changed

+138
-48
lines changed

17 files changed

+138
-48
lines changed

OMCompiler/Compiler/Script/CevalScriptBackend.mo

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1427,21 +1427,21 @@ algorithm
14271427

14281428
result_file := selectResultFile(result_file, simflags);
14291429

1430-
executableSuffixedExe := stringAppend(executable, getSimulationExtension(Config.simCodeTarget(),Autoconf.platform));
1431-
logFile := stringAppend(executable,".log");
1432-
// adrpo: log file is deleted by buildModel! do NOT DELETE IT AGAIN!
1433-
// we should really have different log files for simulation/compilation!
1434-
// as the buildModel log file will be deleted here and that gives less information to the user!
1435-
if System.regularFileExists(logFile) then
1436-
0 := System.removeFile(logFile);
1437-
end if;
1438-
sim_call := stringAppendList({"\"",exeDir,executableSuffixedExe,"\""," ",simflags});
1439-
System.realtimeTick(ClockIndexes.RT_CLOCK_SIMULATE_SIMULATION);
1440-
SimulationResults.close() "Windows cannot handle reading and writing to the same file from different processes like any real OS :(";
1441-
1442-
resI := System.systemCall(sim_call, logFile);
1443-
1444-
timeSimulation := System.realtimeTock(ClockIndexes.RT_CLOCK_SIMULATE_SIMULATION);
1430+
executableSuffixedExe := stringAppend(executable, getSimulationExtension(Config.simCodeTarget(),Autoconf.platform));
1431+
logFile := stringAppend(executable,".log");
1432+
// adrpo: log file is deleted by buildModel! do NOT DELETE IT AGAIN!
1433+
// we should really have different log files for simulation/compilation!
1434+
// as the buildModel log file will be deleted here and that gives less information to the user!
1435+
if System.regularFileExists(logFile) then
1436+
0 := System.removeFile(logFile);
1437+
end if;
1438+
sim_call := stringAppendList({"\"",exeDir,executableSuffixedExe,"\""," ",simflags});
1439+
System.realtimeTick(ClockIndexes.RT_CLOCK_SIMULATE_SIMULATION);
1440+
SimulationResults.close() "Windows cannot handle reading and writing to the same file from different processes like any real OS :(";
1441+
1442+
resI := System.systemCallRestrictedEnv(sim_call, logFile);
1443+
1444+
timeSimulation := System.realtimeTock(ClockIndexes.RT_CLOCK_SIMULATE_SIMULATION);
14451445

14461446
else
14471447
result_file := "";
@@ -1537,7 +1537,7 @@ algorithm
15371537
System.realtimeTick(ClockIndexes.RT_CLOCK_SIMULATE_SIMULATION);
15381538
SimulationResults.close() "Windows cannot handle reading and writing to the same file from different processes like any real OS :(";
15391539

1540-
if 0 == System.systemCall(sim_call, logFile) then
1540+
if 0 == System.systemCallRestrictedEnv(sim_call, logFile) then
15411541
result_file = stringAppendList(List.consOnTrue(not Testsuite.isRunning(),compileDir,{executable,"_res.",outputFormat_str}));
15421542
timeSimulation = System.realtimeTock(ClockIndexes.RT_CLOCK_SIMULATE_SIMULATION);
15431543
timeTotal = System.realtimeTock(ClockIndexes.RT_CLOCK_SIMULATE_TOTAL);
@@ -1601,7 +1601,7 @@ algorithm
16011601
sim_call = stringAppendList({"\"",exeDir,executableSuffixedExe,"\""," ",simflags});
16021602
System.realtimeTick(ClockIndexes.RT_CLOCK_SIMULATE_SIMULATION);
16031603
SimulationResults.close() "Windows cannot handle reading and writing to the same file from different processes like any real OS :(";
1604-
resI = System.systemCall(sim_call, logFile);
1604+
resI = System.systemCallRestrictedEnv(sim_call, logFile);
16051605
timeSimulation = System.realtimeTock(ClockIndexes.RT_CLOCK_SIMULATE_SIMULATION);
16061606
else
16071607
result_file = "";
@@ -3730,7 +3730,7 @@ algorithm
37303730
cmakeCall + " && " +
37313731
Autoconf.cmake + " --build . --parallel " + getProcsStr() + " --target install && " +
37323732
"cd .. && rm -rf " + buildDir;
3733-
if 0 <> System.systemCall(cmd, outFile=logfile) then
3733+
if 0 <> System.systemCallRestrictedEnv(cmd, outFile=logfile) then
37343734
Error.addMessage(Error.SIMULATOR_BUILD_ERROR, {"cmd: " + cmd + "\n" + System.readFile(logfile)});
37353735
fail();
37363736
end if;
@@ -3749,7 +3749,7 @@ algorithm
37493749
cmakeCall + " && " +
37503750
Autoconf.cmake + " --build . --parallel " + getProcsStr() + " --target install && " +
37513751
"cd .. && rm -rf " + buildDir;
3752-
if 0 <> System.systemCall(cmd, outFile=logfile) then
3752+
if 0 <> System.systemCallRestrictedEnv(cmd, outFile=logfile) then
37533753
Error.addMessage(Error.SIMULATOR_BUILD_ERROR, {"cmd: " + cmd + "\n" + System.readFile(logfile)});
37543754
fail();
37553755
end if;
@@ -3986,7 +3986,7 @@ algorithm
39863986
cmd := "cd \"" + fmutmp + "/sources\" && ./configure --host="+quote+platform+quote+
39873987
" CFLAGS=" + quote + "-Os" + quote + " CPPFLAGS=" + quote + CPPFLAGS + quote+
39883988
" LDFLAGS= && " + nozip;
3989-
if 0 <> System.systemCall(cmd, outFile=logfile) then
3989+
if 0 <> System.systemCallRestrictedEnv(cmd, outFile=logfile) then
39903990
Error.addMessage(Error.SIMULATOR_BUILD_ERROR, {System.readFile(logfile)});
39913991
System.removeFile(logfile);
39923992
fail();
@@ -4076,7 +4076,7 @@ algorithm
40764076
ExecStat.execStat("buildModelFMU: configured platform " + platform + " using " + cmd);
40774077
if not finishedBuild then
40784078
if not isWindows then
4079-
if 0 <> System.systemCall("cd " + dir + " && "+ Autoconf.make + " clean > /dev/null 2>&1") then
4079+
if 0 <> System.systemCallRestrictedEnv("cd " + dir + " && "+ Autoconf.make + " clean > /dev/null 2>&1") then
40804080
Error.addMessage(Error.SIMULATOR_BUILD_ERROR, {"Failed to make clean"});
40814081
fail();
40824082
end if;
@@ -4353,7 +4353,7 @@ algorithm
43534353
end if;
43544354
ExecStat.execStat("buildModelFMU: Generate C++ for platform " + platform);
43554355
end for;
4356-
if 0 <> System.systemCall(Autoconf.make + " -f " + filenameprefix + "_FMU.makefile clean", outFile=logfile) then
4356+
if 0 <> System.systemCallRestrictedEnv(Autoconf.make + " -f " + filenameprefix + "_FMU.makefile clean", outFile=logfile) then
43574357
// do nothing
43584358
end if;
43594359
return;

OMCompiler/Compiler/SimCode/SimCodeFunctionUtil.mo

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2573,7 +2573,7 @@ algorithm
25732573
cflags := if stringEq(Config.simCodeTarget(),"JavaScript") then "-Os -Wno-warn-absolute-paths" else cflags;
25742574
ldflags := System.getLDFlags();
25752575
if Flags.getConfigBool(Flags.PARMODAUTO) then
2576-
ldflags := " -lParModelicaAuto -ltbb_static -lboost_system " + ldflags;
2576+
ldflags := " -lParModelicaAuto -ltbb_static " + ldflags;
25772577
end if;
25782578
rtlibs := if isFunction then Autoconf.ldflags_runtime else (if isFMU then Autoconf.ldflags_runtime_fmu else Autoconf.ldflags_runtime_sim);
25792579
platform := System.modelicaPlatform();

OMCompiler/Compiler/SimCode/SimCodeUtil.mo

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15983,7 +15983,7 @@ protected
1598315983
Integer numMatches;
1598415984
String cmakeVersionString;
1598515985
algorithm
15986-
retVal := System.systemCall(pathToCMake + " --version", cmakeVersionLogFile);
15986+
retVal := System.systemCallRestrictedEnv(pathToCMake + " --version", cmakeVersionLogFile);
1598715987
if 0 <> retVal then
1598815988
System.removeFile(cmakeVersionLogFile);
1598915989
Error.addInternalError("Failed to get version from " + pathToCMake, sourceInfo());

OMCompiler/Compiler/Template/CodegenFMUCpp.tpl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -830,7 +830,7 @@ case SIMCODE(modelInfo=MODELINFO(__), makefileParams=MAKEFILE_PARAMS(__), simula
830830

831831
# need boost system lib prior to C++11, forcing also dynamic libs
832832
ifeq ($(findstring USE_CPP_03,$(CFLAGS)),USE_CPP_03)
833-
$(eval LIBS=$(LIBS) -L"$(BOOST_LIBS)" -l$(BOOST_SYSTEM_LIB))
833+
$(eval LIBS=$(LIBS) -L"$(BOOST_LIBS)")
834834
$(eval BINARIES=$(BINARIES) $(BOOST_LIBS)/lib$(BOOST_SYSTEM_LIB)$(DLLEXT) <%platformbins%>)
835835
# link static libs to avoid dependencies; can't link all static under Linux
836836
else ifeq ($(findstring gcc,$(CC)),gcc)

OMCompiler/Compiler/Template/CodegenFMUCppOMSI.tpl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -791,7 +791,7 @@ case SIMCODE(modelInfo=MODELINFO(__), makefileParams=MAKEFILE_PARAMS(__), simula
791791

792792
# need boost system lib prior to C++11, forcing also dynamic libs
793793
ifeq ($(findstring USE_CPP_03,$(CFLAGS)),USE_CPP_03)
794-
$(eval LIBS=$(LIBS) -L"$(BOOST_LIBS)" -l$(BOOST_SYSTEM_LIB))
794+
$(eval LIBS=$(LIBS) -L"$(BOOST_LIBS)")
795795
$(eval BINARIES=$(BINARIES) $(BOOST_LIBS)/lib$(BOOST_SYSTEM_LIB)$(DLLEXT) <%platformbins%>)
796796
# link static libs to avoid dependencies; can't link all static under Linux
797797
else ifeq ($(findstring gcc,$(CC)),gcc)

OMCompiler/Compiler/Util/System.mo

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ encapsulated package System
4141
protected
4242
import Autoconf;
4343
import Error;
44+
import Settings;
4445

4546
public function trim
4647
"removes chars in charsToRemove from begin and end of inString"
@@ -312,6 +313,77 @@ public function readFile
312313
external "C" outString = System_readFile(inString) annotation(Library = "omcruntime");
313314
end readFile;
314315

316+
public function systemCallRestrictedEnv
317+
"@author: adrpo
318+
This function will call system with restricted environment to make sure we do not pick executables or dlls from the PATH.
319+
Only keep the OM or OMDev directories and the Windows ones in the PATH for the system call.
320+
After the execution the PATH will be set back."
321+
input String command;
322+
input String outFile = "" "empty file means no redirection unless it is part of the command";
323+
output Integer outInteger;
324+
protected
325+
String savedPATH = "", newPATH = "", windowsPath = "", omInstallPath = "", omDevPath = "", pfix = "";
326+
algorithm
327+
if Autoconf.os == "Windows_NT" then
328+
// save path
329+
try
330+
savedPATH := readEnv("PATH");
331+
else
332+
savedPATH := "";
333+
Error.addInternalError(getInstanceName() + " failed for: " + command + "! Could not read PATH environment variable.", sourceInfo());
334+
fail();
335+
end try;
336+
// construct restricted path
337+
newPATH := "";
338+
// keep the OM or OMDev directories and the Windows ones
339+
windowsPath := System.stringReplace(winGetSystemDirectory(), "\\", "/");
340+
omInstallPath := System.stringReplace(Settings.getInstallationDirectoryPath(), "\\", "/");
341+
try
342+
omDevPath := System.stringReplace(readEnv("OMDEV"), "\\", "/");
343+
else
344+
omDevPath := "";
345+
end try;
346+
for p in listReverse(strtok(savedPATH, ";")) loop
347+
pfix := System.stringReplace(p, "\\", "/");
348+
if (0 == stringFind(pfix, windowsPath)) or
349+
(0 == stringFind(pfix, omInstallPath)) or
350+
(0 == stringFind(pfix, omDevPath))
351+
then
352+
newPATH := p + ";" + newPATH;
353+
end if;
354+
end for;
355+
if stringEqual(newPATH, "") then
356+
Error.addInternalError(getInstanceName() + " failed for: " + command + "! Failed to filter the PATH: " + savedPATH, sourceInfo());
357+
fail();
358+
end if;
359+
setEnv("PATH", newPATH, true);
360+
try
361+
outInteger := systemCall(command, outFile);
362+
else
363+
Error.addInternalError(getInstanceName() + " failed for: " + command + "! Failed in the system call with restricted PATH: " + newPATH, sourceInfo());
364+
setEnv("PATH", savedPATH, true);
365+
fail();
366+
end try;
367+
setEnv("PATH", savedPATH, true);
368+
else
369+
outInteger := systemCall(command, outFile);
370+
end if;
371+
end systemCallRestrictedEnv;
372+
373+
public function winGetSystemDirectory "returns the Windows system directory on Windows and empty string on Linux"
374+
output String outDirectory = "";
375+
algorithm
376+
outDirectory := "";
377+
if Autoconf.os == "Windows_NT" then
378+
outDirectory := winGetSystemDirectoryA();
379+
end if;
380+
end winGetSystemDirectory;
381+
382+
protected function winGetSystemDirectoryA
383+
output String str;
384+
external "C" str=SystemImpl__winGetSystemDirectoryA() annotation(Library = "omcruntime");
385+
end winGetSystemDirectoryA;
386+
315387
public function systemCall
316388
input String command;
317389
input String outFile = "" "empty file means no redirection unless it is part of the command";

OMCompiler/Compiler/runtime/systemimpl.c

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,8 @@ static char *linker = (char *)def_linker;
160160
static char *cflags = (char *)def_cflags;
161161
static char *ldflags= (char *)def_ldflags;
162162

163+
static char *winDirectory = NULL;
164+
163165
/* TODO! FIXME!
164166
* we need to move these to threadData if we are to run things in parallel in OMC!
165167
*/
@@ -653,6 +655,36 @@ int runProcess(const char* cmd, const char* outFile)
653655
}
654656
#endif
655657

658+
char* SystemImpl__winGetSystemDirectoryA()
659+
{
660+
#if defined(__MINGW32__) || defined(_MSC_VER)
661+
if (winDirectory) {
662+
return winDirectory;
663+
}
664+
char* winDirectory = (char*) omc_alloc_interface.malloc(MAXPATHLEN * sizeof(char*));
665+
if (!GetSystemDirectoryA(winDirectory, MAXPATHLEN-1)) {
666+
LPVOID lpMsgBuf;
667+
const char* ctokens[2];
668+
FormatMessage(
669+
FORMAT_MESSAGE_ALLOCATE_BUFFER |
670+
FORMAT_MESSAGE_FROM_SYSTEM |
671+
FORMAT_MESSAGE_IGNORE_INSERTS,
672+
NULL,
673+
GetLastError(),
674+
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
675+
(LPTSTR) &lpMsgBuf,
676+
0, NULL );
677+
ctokens[0] = lpMsgBuf;
678+
ctokens[1] = "";
679+
c_add_message(NULL,-1, ErrorType_runtime,ErrorLevel_error, gettext("OMC unable to get the Windows system directory %s%s.\n"), ctokens, 2);
680+
LocalFree(lpMsgBuf);
681+
}
682+
return winDirectory;
683+
#else
684+
return "";
685+
#endif
686+
}
687+
656688
int SystemImpl__systemCall(const char* str, const char* outFile)
657689
{
658690
int status = -1,ret_val = -1;

OMCompiler/SimulationRuntime/OMSICpp/CMakeLists.txt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -483,9 +483,9 @@ ELSEIF(NOT FMU_TARGET)
483483
ENDIF(NOT(COMPILER_SUPPORTS_CXX11))
484484

485485
IF(NOT FMU_TARGET)
486-
FIND_PACKAGE(Boost REQUIRED COMPONENTS filesystem system serialization program_options)
486+
FIND_PACKAGE(Boost REQUIRED COMPONENTS filesystem serialization program_options)
487487
ELSE(NOT FMU_TARGET)
488-
FIND_PACKAGE(Boost COMPONENTS filesystem system serialization program_options)
488+
FIND_PACKAGE(Boost COMPONENTS filesystem serialization program_options)
489489
ENDIF(NOT FMU_TARGET)
490490

491491
# Use old C++ ABI for cross compilation of FMUs

OMCompiler/SimulationRuntime/OMSICpp/README

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,8 +78,8 @@ The following section explains the arguments that can be passed in more detail.
7878
linked statically.
7979

8080
Sometimes it's necessary to link boost against it's real path libraries.
81-
This means for example, that instead of linking against “-lboost_system”, the
82-
makefiles will link against “-lboost1.55_system”. Use the BOOST_REALPATHS
81+
This means for example, that instead of linking against “-lboost_filesystem”, the
82+
makefiles will link against “-lboost1.55_filesystem”. Use the BOOST_REALPATHS
8383
argument for this purpose.
8484

8585
If profiling informations for the runtime are required, they can be turned on

OMCompiler/SimulationRuntime/OMSICpp/runtime/src/Core/Modelica/CMakeLists.txt

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,6 @@ if(${CMAKE_SYSTEM_NAME} MATCHES "Windows")
3838
set(FMI_ARCH_DIR "win32")
3939
endif(${CMAKE_SYSTEM_NAME} MATCHES "Windows")
4040

41-
#GET_TARGET_PROPERTY(libboostSystem ${Boost_SYSTEM_LIBRARY} LOCATION)
42-
#GET_FILENAME_COMPONENT(libboostSystemNAME ${libboostSystem} NAME)
43-
#set(Boost_SYSTEM_LIBRARY_NAME ${libboostSystemNAME})
44-
4541
set (BOOST_INCLUDE ${Boost_INCLUDE_DIRS})
4642

4743
set (MODELICA_SYSTEM_LIB_EXT ${libModelicaSystemNameExt})
@@ -67,7 +63,6 @@ ENDFUNCTION()
6763

6864
prepareBoostVar(Boost_FILESYSTEM_LIBRARY Boost_FILESYSTEM_LIBRARY_RELEASE Boost_FILESYSTEM_LIBRARY_DEBUG)
6965
prepareBoostVar(Boost_SERIALIZATION_LIBRARY Boost_SERIALIZATION_LIBRARY_RELEASE Boost_SERIALIZATION_LIBRARY_DEBUG)
70-
prepareBoostVar(Boost_SYSTEM_LIBRARY Boost_SYSTEM_LIBRARY_RELEASE Boost_SYSTEM_LIBRARY_DEBUG)
7166
prepareBoostVar(Boost_THREAD_LIBRARY Boost_THREAD_LIBRARY_RELEASE Boost_THREAD_LIBRARY_DEBUG)
7267
prepareBoostVar(Boost_PROGRAM_OPTIONS_LIBRARY Boost_PROGRAM_OPTIONS_LIBRARY_RELEASE Boost_PROGRAM_OPTIONS_LIBRARY_DEBUG)
7368
prepareBoostVar(Boost_LOG_LIBRARY Boost_LOG_LIBRARY_RELEASE Boost_LOG_LIBRARY_DEBUG)

0 commit comments

Comments
 (0)