MRMModule.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.CodeDom.Compiler;
  29. using System.Collections;
  30. using System.Collections.Generic;
  31. using System.Diagnostics;
  32. using System.IO;
  33. using System.Reflection;
  34. using System.Security;
  35. using System.Security.Permissions;
  36. using System.Security.Policy;
  37. using System.Text;
  38. using log4net;
  39. using Microsoft.CSharp;
  40. using Nini.Config;
  41. using OpenMetaverse;
  42. using OpenSim.Framework;
  43. using OpenSim.Region.Framework.Interfaces;
  44. using OpenSim.Region.Framework.Scenes;
  45. namespace OpenSim.Region.OptionalModules.Scripting.Minimodule
  46. {
  47. public class MRMModule : IRegionModule, IMRMModule
  48. {
  49. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  50. private Scene m_scene;
  51. private readonly Dictionary<UUID,MRMBase> m_scripts = new Dictionary<UUID, MRMBase>();
  52. private readonly Dictionary<Type,object> m_extensions = new Dictionary<Type, object>();
  53. private static readonly CSharpCodeProvider CScodeProvider = new CSharpCodeProvider();
  54. private readonly MicroScheduler m_microthreads = new MicroScheduler();
  55. private IConfig m_config;
  56. public void RegisterExtension<T>(T instance)
  57. {
  58. m_extensions[typeof (T)] = instance;
  59. }
  60. public void Initialise(Scene scene, IConfigSource source)
  61. {
  62. if (source.Configs["MRM"] != null)
  63. {
  64. m_config = source.Configs["MRM"];
  65. if (source.Configs["MRM"].GetBoolean("Enabled", false))
  66. {
  67. m_log.Info("[MRM]: Enabling MRM Module");
  68. m_scene = scene;
  69. // when hidden, we don't listen for client initiated script events
  70. // only making the MRM engine available for region modules
  71. if (!source.Configs["MRM"].GetBoolean("Hidden", false))
  72. {
  73. scene.EventManager.OnRezScript += EventManager_OnRezScript;
  74. scene.EventManager.OnStopScript += EventManager_OnStopScript;
  75. }
  76. scene.EventManager.OnFrame += EventManager_OnFrame;
  77. scene.RegisterModuleInterface<IMRMModule>(this);
  78. }
  79. }
  80. }
  81. void EventManager_OnStopScript(uint localID, UUID itemID)
  82. {
  83. if (m_scripts.ContainsKey(itemID))
  84. {
  85. m_scripts[itemID].Stop();
  86. }
  87. }
  88. void EventManager_OnFrame()
  89. {
  90. m_microthreads.Tick(1000);
  91. }
  92. static string ConvertMRMKeywords(string script)
  93. {
  94. script = script.Replace("microthreaded void", "IEnumerable");
  95. script = script.Replace("relax;", "yield return null;");
  96. return script;
  97. }
  98. /// <summary>
  99. /// Create an AppDomain that contains policy restricting code to execute
  100. /// with only the permissions granted by a named permission set
  101. /// </summary>
  102. /// <param name="permissionSetName">name of the permission set to restrict to</param>
  103. /// <param name="appDomainName">'friendly' name of the appdomain to be created</param>
  104. /// <exception cref="ArgumentNullException">
  105. /// if <paramref name="permissionSetName"/> is null
  106. /// </exception>
  107. /// <exception cref="ArgumentOutOfRangeException">
  108. /// if <paramref name="permissionSetName"/> is empty
  109. /// </exception>
  110. /// <returns>AppDomain with a restricted security policy</returns>
  111. /// <remarks>Substantial portions of this function from: http://blogs.msdn.com/shawnfa/archive/2004/10/25/247379.aspx
  112. /// Valid permissionSetName values are:
  113. /// * FullTrust
  114. /// * SkipVerification
  115. /// * Execution
  116. /// * Nothing
  117. /// * LocalIntranet
  118. /// * Internet
  119. /// * Everything
  120. /// </remarks>
  121. public static AppDomain CreateRestrictedDomain(string permissionSetName, string appDomainName)
  122. {
  123. if (permissionSetName == null)
  124. throw new ArgumentNullException("permissionSetName");
  125. if (permissionSetName.Length == 0)
  126. throw new ArgumentOutOfRangeException("permissionSetName", permissionSetName,
  127. "Cannot have an empty permission set name");
  128. // Default to all code getting nothing
  129. PolicyStatement emptyPolicy = new PolicyStatement(new PermissionSet(PermissionState.None));
  130. UnionCodeGroup policyRoot = new UnionCodeGroup(new AllMembershipCondition(), emptyPolicy);
  131. bool foundName = false;
  132. PermissionSet setIntersection = new PermissionSet(PermissionState.Unrestricted);
  133. // iterate over each policy level
  134. IEnumerator levelEnumerator = SecurityManager.PolicyHierarchy();
  135. while (levelEnumerator.MoveNext())
  136. {
  137. PolicyLevel level = levelEnumerator.Current as PolicyLevel;
  138. // if this level has defined a named permission set with the
  139. // given name, then intersect it with what we've retrieved
  140. // from all the previous levels
  141. if (level != null)
  142. {
  143. PermissionSet levelSet = level.GetNamedPermissionSet(permissionSetName);
  144. if (levelSet != null)
  145. {
  146. foundName = true;
  147. if (setIntersection != null)
  148. setIntersection = setIntersection.Intersect(levelSet);
  149. }
  150. }
  151. }
  152. // Intersect() can return null for an empty set, so convert that
  153. // to an empty set object. Also return an empty set if we didn't find
  154. // the named permission set we were looking for
  155. if (setIntersection == null || !foundName)
  156. setIntersection = new PermissionSet(PermissionState.None);
  157. else
  158. setIntersection = new NamedPermissionSet(permissionSetName, setIntersection);
  159. // if no named permission sets were found, return an empty set,
  160. // otherwise return the set that was found
  161. PolicyStatement permissions = new PolicyStatement(setIntersection);
  162. policyRoot.AddChild(new UnionCodeGroup(new AllMembershipCondition(), permissions));
  163. // create an AppDomain policy level for the policy tree
  164. PolicyLevel appDomainLevel = PolicyLevel.CreateAppDomainLevel();
  165. appDomainLevel.RootCodeGroup = policyRoot;
  166. // create an AppDomain where this policy will be in effect
  167. string domainName = appDomainName;
  168. AppDomain restrictedDomain = AppDomain.CreateDomain(domainName);
  169. restrictedDomain.SetAppDomainPolicy(appDomainLevel);
  170. return restrictedDomain;
  171. }
  172. void EventManager_OnRezScript(uint localID, UUID itemID, string script, int startParam, bool postOnRez, string engine, int stateSource)
  173. {
  174. if (script.StartsWith("//MRM:C#"))
  175. {
  176. if (m_config.GetBoolean("OwnerOnly", true))
  177. if (m_scene.GetSceneObjectPart(localID).OwnerID != m_scene.RegionInfo.EstateSettings.EstateOwner
  178. || m_scene.GetSceneObjectPart(localID).CreatorID != m_scene.RegionInfo.EstateSettings.EstateOwner)
  179. return;
  180. script = ConvertMRMKeywords(script);
  181. try
  182. {
  183. AppDomain target;
  184. if (m_config.GetBoolean("Sandboxed", true))
  185. {
  186. m_log.Info("[MRM] Found C# MRM - Starting in AppDomain with " +
  187. m_config.GetString("SandboxLevel", "Internet") + "-level security.");
  188. string domainName = UUID.Random().ToString();
  189. target = CreateRestrictedDomain(m_config.GetString("SandboxLevel", "Internet"),
  190. domainName);
  191. }
  192. else
  193. {
  194. m_log.Info("[MRM] Found C# MRM - Starting in current AppDomain");
  195. m_log.Warn(
  196. "[MRM] Security Risk: AppDomain is run in current context. Use only in trusted environments.");
  197. target = AppDomain.CurrentDomain;
  198. }
  199. m_log.Info("[MRM] Unwrapping into target AppDomain");
  200. MRMBase mmb = (MRMBase) target.CreateInstanceFromAndUnwrap(
  201. CompileFromDotNetText(script, itemID.ToString()),
  202. "OpenSim.MiniModule");
  203. m_log.Info("[MRM] Initialising MRM Globals");
  204. InitializeMRM(mmb, localID, itemID);
  205. m_scripts[itemID] = mmb;
  206. m_log.Info("[MRM] Starting MRM");
  207. mmb.Start();
  208. }
  209. catch (UnauthorizedAccessException e)
  210. {
  211. m_log.Error("[MRM] UAE " + e.Message);
  212. m_log.Error("[MRM] " + e.StackTrace);
  213. if (e.InnerException != null)
  214. m_log.Error("[MRM] " + e.InnerException);
  215. m_scene.ForEachClient(delegate(IClientAPI user)
  216. {
  217. user.SendAlertMessage(
  218. "MRM UnAuthorizedAccess: " + e);
  219. });
  220. }
  221. catch (Exception e)
  222. {
  223. m_log.Info("[MRM] Error: " + e);
  224. m_scene.ForEachClient(delegate(IClientAPI user)
  225. {
  226. user.SendAlertMessage(
  227. "Compile error while building MRM script, check OpenSim console for more information.");
  228. });
  229. }
  230. }
  231. }
  232. public void GetGlobalEnvironment(uint localID, out IWorld world, out IHost host)
  233. {
  234. // UUID should be changed to object owner.
  235. UUID owner = m_scene.RegionInfo.EstateSettings.EstateOwner;
  236. SEUser securityUser = new SEUser(owner, "Name Unassigned");
  237. SecurityCredential creds = new SecurityCredential(securityUser, m_scene);
  238. world = new World(m_scene, creds);
  239. host = new Host(new SOPObject(m_scene, localID, creds), m_scene, new ExtensionHandler(m_extensions),
  240. m_microthreads);
  241. }
  242. public void InitializeMRM(MRMBase mmb, uint localID, UUID itemID)
  243. {
  244. m_log.Info("[MRM] Created MRM Instance");
  245. IWorld world;
  246. IHost host;
  247. GetGlobalEnvironment(localID, out world, out host);
  248. mmb.InitMiniModule(world, host, itemID);
  249. }
  250. public void PostInitialise()
  251. {
  252. }
  253. public void Close()
  254. {
  255. foreach (KeyValuePair<UUID, MRMBase> pair in m_scripts)
  256. {
  257. pair.Value.Stop();
  258. }
  259. }
  260. public string Name
  261. {
  262. get { return "MiniRegionModule"; }
  263. }
  264. public bool IsSharedModule
  265. {
  266. get { return false; }
  267. }
  268. /// <summary>
  269. /// Stolen from ScriptEngine Common
  270. /// </summary>
  271. /// <param name="Script"></param>
  272. /// <param name="uuid">Unique ID for this module</param>
  273. /// <returns></returns>
  274. internal string CompileFromDotNetText(string Script, string uuid)
  275. {
  276. m_log.Info("MRM 1");
  277. const string ext = ".cs";
  278. const string FilePrefix = "MiniModule";
  279. // Output assembly name
  280. string OutFile = Path.Combine("MiniModules", Path.Combine(
  281. m_scene.RegionInfo.RegionID.ToString(),
  282. FilePrefix + "_compiled_" + uuid + "_" +
  283. Util.RandomClass.Next(9000) + ".dll"));
  284. // Create Directories for Assemblies
  285. if (!Directory.Exists("MiniModules"))
  286. Directory.CreateDirectory("MiniModules");
  287. string tmp = Path.Combine("MiniModules", m_scene.RegionInfo.RegionID.ToString());
  288. if (!Directory.Exists(tmp))
  289. Directory.CreateDirectory(tmp);
  290. m_log.Info("MRM 2");
  291. try
  292. {
  293. File.Delete(OutFile);
  294. }
  295. catch (UnauthorizedAccessException e)
  296. {
  297. throw new Exception("Unable to delete old existing " +
  298. "script-file before writing new. Compile aborted: " +
  299. e);
  300. }
  301. catch (IOException e)
  302. {
  303. throw new Exception("Unable to delete old existing " +
  304. "script-file before writing new. Compile aborted: " +
  305. e);
  306. }
  307. m_log.Info("MRM 3");
  308. // DEBUG - write source to disk
  309. string srcFileName = FilePrefix + "_source_" +
  310. Path.GetFileNameWithoutExtension(OutFile) + ext;
  311. try
  312. {
  313. File.WriteAllText(Path.Combine(Path.Combine(
  314. "MiniModules",
  315. m_scene.RegionInfo.RegionID.ToString()),
  316. srcFileName), Script);
  317. }
  318. catch (Exception ex) //NOTLEGIT - Should be just FileIOException
  319. {
  320. m_log.Error("[Compiler]: Exception while " +
  321. "trying to write script source to file \"" +
  322. srcFileName + "\": " + ex);
  323. }
  324. m_log.Info("MRM 4");
  325. // Do actual compile
  326. CompilerParameters parameters = new CompilerParameters();
  327. parameters.IncludeDebugInformation = true;
  328. string rootPath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
  329. List<string> libraries = new List<string>();
  330. string[] lines = Script.Split(new string[] {"\n"}, StringSplitOptions.RemoveEmptyEntries);
  331. foreach (string s in lines)
  332. {
  333. if (s.StartsWith("//@DEPENDS:"))
  334. {
  335. libraries.Add(s.Replace("//@DEPENDS:", ""));
  336. }
  337. }
  338. libraries.Add("OpenSim.Region.OptionalModules.dll");
  339. libraries.Add("OpenMetaverseTypes.dll");
  340. libraries.Add("log4net.dll");
  341. foreach (string library in libraries)
  342. {
  343. parameters.ReferencedAssemblies.Add(Path.Combine(rootPath, library));
  344. }
  345. parameters.GenerateExecutable = false;
  346. parameters.OutputAssembly = OutFile;
  347. parameters.IncludeDebugInformation = true;
  348. parameters.TreatWarningsAsErrors = false;
  349. m_log.Info("MRM 5");
  350. CompilerResults results = CScodeProvider.CompileAssemblyFromSource(
  351. parameters, Script);
  352. m_log.Info("MRM 6");
  353. int display = 5;
  354. if (results.Errors.Count > 0)
  355. {
  356. string errtext = String.Empty;
  357. foreach (CompilerError CompErr in results.Errors)
  358. {
  359. // Show 5 errors max
  360. //
  361. if (display <= 0)
  362. break;
  363. display--;
  364. string severity = "Error";
  365. if (CompErr.IsWarning)
  366. {
  367. severity = "Warning";
  368. }
  369. string text = CompErr.ErrorText;
  370. // The Second Life viewer's script editor begins
  371. // countingn lines and columns at 0, so we subtract 1.
  372. errtext += String.Format("Line ({0},{1}): {4} {2}: {3}\n",
  373. CompErr.Line - 1, CompErr.Column - 1,
  374. CompErr.ErrorNumber, text, severity);
  375. }
  376. if (!File.Exists(OutFile))
  377. {
  378. throw new Exception(errtext);
  379. }
  380. }
  381. m_log.Info("MRM 7");
  382. if (!File.Exists(OutFile))
  383. {
  384. string errtext = String.Empty;
  385. errtext += "No compile error. But not able to locate compiled file.";
  386. throw new Exception(errtext);
  387. }
  388. FileInfo fi = new FileInfo(OutFile);
  389. Byte[] data = new Byte[fi.Length];
  390. try
  391. {
  392. FileStream fs = File.Open(OutFile, FileMode.Open, FileAccess.Read);
  393. fs.Read(data, 0, data.Length);
  394. fs.Close();
  395. }
  396. catch (IOException)
  397. {
  398. string errtext = String.Empty;
  399. errtext += "No compile error. But not able to open file.";
  400. throw new Exception(errtext);
  401. }
  402. m_log.Info("MRM 8");
  403. // Convert to base64
  404. //
  405. string filetext = Convert.ToBase64String(data);
  406. ASCIIEncoding enc = new ASCIIEncoding();
  407. Byte[] buf = enc.GetBytes(filetext);
  408. m_log.Info("MRM 9");
  409. FileStream sfs = File.Create(OutFile + ".cil.b64");
  410. sfs.Write(buf, 0, buf.Length);
  411. sfs.Close();
  412. m_log.Info("MRM 10");
  413. return OutFile;
  414. }
  415. }
  416. }