Meep

pun instantiate security

Jul 28th, 2021 (edited)
511
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Validates whether instantiation is malformed before attempting to run it
  2. // The optional parameter allows a rate limiter to be setup
  3.  
  4. public static bool ValidateInstantiate(EventData eventData, RateLimit limiter = null)
  5. {
  6.     if (eventData == null)
  7.         return false;
  8.  
  9.     if (!(eventData.CustomData is Hashtable tableInst))
  10.         return false;
  11.  
  12.     // Keys 1-2 sometimes don't exist, we should validate them if they do though
  13.     if (tableInst.Count < 4 || tableInst.Count > 6)
  14.         return false;
  15.  
  16.     if (tableInst.ContainsKey((byte)0) && // Prefab name
  17.         tableInst.ContainsKey((byte)4) && // PhotonView children ID array
  18.         tableInst.ContainsKey((byte)6) && // Servertime
  19.         tableInst.ContainsKey((byte)7))   // Root PhotonView ID
  20.     {
  21.         // Vector3/Quaternion are optional segments of data
  22.         // We should validate them anyway when they do infact appear
  23.         if (tableInst.ContainsKey((byte)1))
  24.             if (!(tableInst[(byte)1] is Vector3))
  25.                 return false;
  26.         if (tableInst.ContainsKey((byte)2))
  27.             if (!(tableInst[(byte)2] is Quaternion))
  28.                 return false;
  29.  
  30.         if (!(tableInst[(byte)0] is string prefabName))
  31.             return false;
  32.         if (!(tableInst[(byte)4] is int[]))
  33.             return false;
  34.         if (!(tableInst[(byte)6] is int))
  35.             return false;
  36.         if (!(tableInst[(byte)7] is int))
  37.             return false;
  38.  
  39.         // A whitelist for which prefabs can be instantiated would be a good addition
  40.         // Trying to instantiate a prefab which doesn't exist will cause an error
  41.         // In games compiled with IL2CPP, spamming this can be dangerous for performance
  42.         if (limiter != null)
  43.             return limiter.IsSafeToRun($"INSTANTIATE_{prefabName}", eventData.Sender);
  44.  
  45.         return true;
  46.     }
  47.  
  48.     return false;
  49. }
RAW Paste Data