CryptoGridAssetClient.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. /*
  2. * Copyright (c) Contributors, http://www.openmetaverse.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 OpenSim 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. /*
  28. * This file includes content derived from Obviex.
  29. * Copyright (C) 2002 Obviex(TM). All rights reserved.
  30. * http://www.obviex.com/samples/Encryption.aspx
  31. */
  32. using System;
  33. using System.Collections.Generic;
  34. using System.IO;
  35. using System.Reflection;
  36. using System.Text;
  37. using System.Xml.Serialization;
  38. using log4net;
  39. using OpenSim.Framework.Servers;
  40. using System.Security.Cryptography;
  41. namespace OpenSim.Framework.Communications.Cache
  42. {
  43. public class CryptoGridAssetClient : AssetServerBase
  44. {
  45. #region Keyfile Classes
  46. [Serializable]
  47. private class RjinKeyfile
  48. {
  49. public string Secret;
  50. public string AlsoKnownAs;
  51. public int Keysize;
  52. public string IVBytes;
  53. public string Description = "OpenSim Key";
  54. private static string SHA1Hash(byte[] bytes)
  55. {
  56. SHA1 sha1 = SHA1CryptoServiceProvider.Create();
  57. byte[] dataMd5 = sha1.ComputeHash(bytes);
  58. StringBuilder sb = new StringBuilder();
  59. for (int i = 0; i < dataMd5.Length; i++)
  60. sb.AppendFormat("{0:x2}", dataMd5[i]);
  61. return sb.ToString();
  62. }
  63. public void GenerateRandom()
  64. {
  65. RNGCryptoServiceProvider Gen = new RNGCryptoServiceProvider();
  66. byte[] genSec = new byte[32];
  67. byte[] genAKA = new byte[32];
  68. byte[] genIV = new byte[32];
  69. Gen.GetBytes(genSec);
  70. Gen.GetBytes(genAKA);
  71. Gen.GetBytes(genIV);
  72. Secret = SHA1Hash(genSec);
  73. AlsoKnownAs = SHA1Hash(genAKA);
  74. IVBytes = SHA1Hash(genIV).Substring(0, 16);
  75. Keysize = 256;
  76. }
  77. }
  78. #endregion
  79. #region Rjindael
  80. /// <summary>
  81. /// This class uses a symmetric key algorithm (Rijndael/AES) to encrypt and
  82. /// decrypt data. As long as encryption and decryption routines use the same
  83. /// parameters to generate the keys, the keys are guaranteed to be the same.
  84. /// The class uses static functions with duplicate code to make it easier to
  85. /// demonstrate encryption and decryption logic. In a real-life application,
  86. /// this may not be the most efficient way of handling encryption, so - as
  87. /// soon as you feel comfortable with it - you may want to redesign this class.
  88. /// </summary>
  89. private class UtilRijndael
  90. {
  91. /// <summary>
  92. /// Encrypts specified plaintext using Rijndael symmetric key algorithm
  93. /// and returns a base64-encoded result.
  94. /// </summary>
  95. /// <param name="plainText">
  96. /// Plaintext value to be encrypted.
  97. /// </param>
  98. /// <param name="passPhrase">
  99. /// Passphrase from which a pseudo-random password will be derived. The
  100. /// derived password will be used to generate the encryption key.
  101. /// Passphrase can be any string. In this example we assume that this
  102. /// passphrase is an ASCII string.
  103. /// </param>
  104. /// <param name="saltValue">
  105. /// Salt value used along with passphrase to generate password. Salt can
  106. /// be any string. In this example we assume that salt is an ASCII string.
  107. /// </param>
  108. /// <param name="hashAlgorithm">
  109. /// Hash algorithm used to generate password. Allowed values are: "MD5" and
  110. /// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
  111. /// </param>
  112. /// <param name="passwordIterations">
  113. /// Number of iterations used to generate password. One or two iterations
  114. /// should be enough.
  115. /// </param>
  116. /// <param name="initVector">
  117. /// Initialization vector (or IV). This value is required to encrypt the
  118. /// first block of plaintext data. For RijndaelManaged class IV must be
  119. /// exactly 16 ASCII characters long.
  120. /// </param>
  121. /// <param name="keySize">
  122. /// Size of encryption key in bits. Allowed values are: 128, 192, and 256.
  123. /// Longer keys are more secure than shorter keys.
  124. /// </param>
  125. /// <returns>
  126. /// Encrypted value formatted as a base64-encoded string.
  127. /// </returns>
  128. public static byte[] Encrypt(byte[] plainText,
  129. string passPhrase,
  130. string saltValue,
  131. string hashAlgorithm,
  132. int passwordIterations,
  133. string initVector,
  134. int keySize)
  135. {
  136. // Convert strings into byte arrays.
  137. // Let us assume that strings only contain ASCII codes.
  138. // If strings include Unicode characters, use Unicode, UTF7, or UTF8
  139. // encoding.
  140. byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
  141. byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
  142. // Convert our plaintext into a byte array.
  143. // Let us assume that plaintext contains UTF8-encoded characters.
  144. byte[] plainTextBytes = plainText;
  145. // First, we must create a password, from which the key will be derived.
  146. // This password will be generated from the specified passphrase and
  147. // salt value. The password will be created using the specified hash
  148. // algorithm. Password creation can be done in several iterations.
  149. PasswordDeriveBytes password = new PasswordDeriveBytes(
  150. passPhrase,
  151. saltValueBytes,
  152. hashAlgorithm,
  153. passwordIterations);
  154. // Use the password to generate pseudo-random bytes for the encryption
  155. // key. Specify the size of the key in bytes (instead of bits).
  156. byte[] keyBytes = password.GetBytes(keySize / 8);
  157. // Create uninitialized Rijndael encryption object.
  158. RijndaelManaged symmetricKey = new RijndaelManaged();
  159. // It is reasonable to set encryption mode to Cipher Block Chaining
  160. // (CBC). Use default options for other symmetric key parameters.
  161. symmetricKey.Mode = CipherMode.CBC;
  162. // Generate encryptor from the existing key bytes and initialization
  163. // vector. Key size will be defined based on the number of the key
  164. // bytes.
  165. ICryptoTransform encryptor = symmetricKey.CreateEncryptor(
  166. keyBytes,
  167. initVectorBytes);
  168. // Define memory stream which will be used to hold encrypted data.
  169. MemoryStream memoryStream = new MemoryStream();
  170. // Define cryptographic stream (always use Write mode for encryption).
  171. CryptoStream cryptoStream = new CryptoStream(memoryStream,
  172. encryptor,
  173. CryptoStreamMode.Write);
  174. // Start encrypting.
  175. cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
  176. // Finish encrypting.
  177. cryptoStream.FlushFinalBlock();
  178. // Convert our encrypted data from a memory stream into a byte array.
  179. byte[] cipherTextBytes = memoryStream.ToArray();
  180. // Close both streams.
  181. memoryStream.Close();
  182. cryptoStream.Close();
  183. // Return encrypted string.
  184. return cipherTextBytes;
  185. }
  186. /// <summary>
  187. /// Decrypts specified ciphertext using Rijndael symmetric key algorithm.
  188. /// </summary>
  189. /// <param name="cipherText">
  190. /// Base64-formatted ciphertext value.
  191. /// </param>
  192. /// <param name="passPhrase">
  193. /// Passphrase from which a pseudo-random password will be derived. The
  194. /// derived password will be used to generate the encryption key.
  195. /// Passphrase can be any string. In this example we assume that this
  196. /// passphrase is an ASCII string.
  197. /// </param>
  198. /// <param name="saltValue">
  199. /// Salt value used along with passphrase to generate password. Salt can
  200. /// be any string. In this example we assume that salt is an ASCII string.
  201. /// </param>
  202. /// <param name="hashAlgorithm">
  203. /// Hash algorithm used to generate password. Allowed values are: "MD5" and
  204. /// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
  205. /// </param>
  206. /// <param name="passwordIterations">
  207. /// Number of iterations used to generate password. One or two iterations
  208. /// should be enough.
  209. /// </param>
  210. /// <param name="initVector">
  211. /// Initialization vector (or IV). This value is required to encrypt the
  212. /// first block of plaintext data. For RijndaelManaged class IV must be
  213. /// exactly 16 ASCII characters long.
  214. /// </param>
  215. /// <param name="keySize">
  216. /// Size of encryption key in bits. Allowed values are: 128, 192, and 256.
  217. /// Longer keys are more secure than shorter keys.
  218. /// </param>
  219. /// <returns>
  220. /// Decrypted string value.
  221. /// </returns>
  222. /// <remarks>
  223. /// Most of the logic in this function is similar to the Encrypt
  224. /// logic. In order for decryption to work, all parameters of this function
  225. /// - except cipherText value - must match the corresponding parameters of
  226. /// the Encrypt function which was called to generate the
  227. /// ciphertext.
  228. /// </remarks>
  229. public static byte[] Decrypt(byte[] cipherText,
  230. string passPhrase,
  231. string saltValue,
  232. string hashAlgorithm,
  233. int passwordIterations,
  234. string initVector,
  235. int keySize)
  236. {
  237. // Convert strings defining encryption key characteristics into byte
  238. // arrays. Let us assume that strings only contain ASCII codes.
  239. // If strings include Unicode characters, use Unicode, UTF7, or UTF8
  240. // encoding.
  241. byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
  242. byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
  243. // Convert our ciphertext into a byte array.
  244. byte[] cipherTextBytes = cipherText;
  245. // First, we must create a password, from which the key will be
  246. // derived. This password will be generated from the specified
  247. // passphrase and salt value. The password will be created using
  248. // the specified hash algorithm. Password creation can be done in
  249. // several iterations.
  250. PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase,
  251. saltValueBytes,
  252. hashAlgorithm,
  253. passwordIterations);
  254. // Use the password to generate pseudo-random bytes for the encryption
  255. // key. Specify the size of the key in bytes (instead of bits).
  256. byte[] keyBytes = password.GetBytes(keySize / 8);
  257. // Create uninitialized Rijndael encryption object.
  258. RijndaelManaged symmetricKey = new RijndaelManaged();
  259. // It is reasonable to set encryption mode to Cipher Block Chaining
  260. // (CBC). Use default options for other symmetric key parameters.
  261. symmetricKey.Mode = CipherMode.CBC;
  262. // Generate decryptor from the existing key bytes and initialization
  263. // vector. Key size will be defined based on the number of the key
  264. // bytes.
  265. ICryptoTransform decryptor = symmetricKey.CreateDecryptor(
  266. keyBytes,
  267. initVectorBytes);
  268. // Define memory stream which will be used to hold encrypted data.
  269. MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
  270. // Define cryptographic stream (always use Read mode for encryption).
  271. CryptoStream cryptoStream = new CryptoStream(memoryStream,
  272. decryptor,
  273. CryptoStreamMode.Read);
  274. // Since at this point we don't know what the size of decrypted data
  275. // will be, allocate the buffer long enough to hold ciphertext;
  276. // plaintext is never longer than ciphertext.
  277. byte[] plainTextBytes = new byte[cipherTextBytes.Length];
  278. // Start decrypting.
  279. int decryptedByteCount = cryptoStream.Read(plainTextBytes,
  280. 0,
  281. plainTextBytes.Length);
  282. // Close both streams.
  283. memoryStream.Close();
  284. cryptoStream.Close();
  285. byte[] plainText = new byte[decryptedByteCount];
  286. int i;
  287. for (i = 0; i < decryptedByteCount; i++)
  288. plainText[i] = plainTextBytes[i];
  289. // Return decrypted string.
  290. return plainText;
  291. }
  292. }
  293. #endregion
  294. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  295. private readonly string _assetServerUrl;
  296. private readonly bool m_encryptOnUpload;
  297. private readonly RjinKeyfile m_encryptKey;
  298. private readonly Dictionary<string,RjinKeyfile> m_keyfiles = new Dictionary<string, RjinKeyfile>();
  299. public CryptoGridAssetClient(string serverUrl, string keydir, bool decOnly)
  300. {
  301. _assetServerUrl = serverUrl;
  302. string[] keys = Directory.GetFiles(keydir, "*.deckey");
  303. foreach (string key in keys)
  304. {
  305. XmlSerializer xs = new XmlSerializer(typeof (RjinKeyfile));
  306. FileStream file = new FileStream(key, FileMode.Open, FileAccess.Read);
  307. RjinKeyfile rjkey = (RjinKeyfile) xs.Deserialize(file);
  308. file.Close();
  309. m_keyfiles.Add(rjkey.AlsoKnownAs, rjkey);
  310. }
  311. keys = Directory.GetFiles(keydir, "*.enckey");
  312. if (keys.Length == 1)
  313. {
  314. string Ekey = keys[0];
  315. XmlSerializer Exs = new XmlSerializer(typeof (RjinKeyfile));
  316. FileStream Efile = new FileStream(Ekey, FileMode.Open, FileAccess.Read);
  317. RjinKeyfile Erjkey = (RjinKeyfile) Exs.Deserialize(Efile);
  318. Efile.Close();
  319. m_keyfiles.Add(Erjkey.AlsoKnownAs, Erjkey);
  320. m_encryptKey = Erjkey;
  321. } else
  322. {
  323. if (keys.Length > 1)
  324. throw new Exception(
  325. "You have more than one asset *encryption* key. (You should never have more than one)," +
  326. "If you downloaded this key from someone, rename it to <filename>.deckey to convert it to" +
  327. "a decryption-only key.");
  328. m_log.Warn("No encryption key found, generating a new one for you...");
  329. RjinKeyfile encKey = new RjinKeyfile();
  330. encKey.GenerateRandom();
  331. m_encryptKey = encKey;
  332. FileStream encExportFile = new FileStream("mysecretkey_rename_me.enckey",FileMode.CreateNew);
  333. XmlSerializer xs = new XmlSerializer(typeof(RjinKeyfile));
  334. xs.Serialize(encExportFile, encKey);
  335. encExportFile.Flush();
  336. encExportFile.Close();
  337. m_log.Info(
  338. "Encryption file generated, please rename 'mysecretkey_rename_me.enckey' to something more appropriate (however preserve the file extension).");
  339. }
  340. // If Decrypt-Only, dont encrypt on upload
  341. m_encryptOnUpload = !decOnly;
  342. }
  343. private static void EncryptAssetBase(AssetBase x, RjinKeyfile file)
  344. {
  345. // Make a salt
  346. RNGCryptoServiceProvider RandomGen = new RNGCryptoServiceProvider();
  347. byte[] rand = new byte[32];
  348. RandomGen.GetBytes(rand);
  349. string salt = Convert.ToBase64String(rand);
  350. x.Data = UtilRijndael.Encrypt(x.Data, file.Secret, salt, "SHA1", 2, file.IVBytes, file.Keysize);
  351. x.Description = String.Format("ENCASS#:~:#{0}#:~:#{1}#:~:#{2}#:~:#{3}",
  352. "OPENSIM_AES_AF1",
  353. file.AlsoKnownAs,
  354. salt,
  355. x.Description);
  356. }
  357. private bool DecryptAssetBase(AssetBase x)
  358. {
  359. // Check it's encrypted first.
  360. if (!x.Description.Contains("ENCASS"))
  361. return true;
  362. // ENCASS:ALG:AKA:SALT:Description
  363. // 0 1 2 3 4
  364. string[] splitchars = new string[1];
  365. splitchars[0] = "#:~:#";
  366. string[] meta = x.Description.Split(splitchars, StringSplitOptions.None);
  367. if (meta.Length < 5)
  368. {
  369. m_log.Warn("[ENCASSETS] Recieved Encrypted Asset, but header is corrupt");
  370. return false;
  371. }
  372. // Check if we have a matching key
  373. if (m_keyfiles.ContainsKey(meta[2]))
  374. {
  375. RjinKeyfile deckey = m_keyfiles[meta[2]];
  376. x.Description = meta[4];
  377. switch (meta[1])
  378. {
  379. case "OPENSIM_AES_AF1":
  380. x.Data = UtilRijndael.Decrypt(x.Data,
  381. deckey.Secret,
  382. meta[3],
  383. "SHA1",
  384. 2,
  385. deckey.IVBytes,
  386. deckey.Keysize);
  387. // Decrypted Successfully
  388. return true;
  389. default:
  390. m_log.Warn(
  391. "[ENCASSETS] Recieved Encrypted Asset, but we dont know how to decrypt '" + meta[1] + "'.");
  392. // We dont understand this encryption scheme
  393. return false;
  394. }
  395. }
  396. m_log.Warn("[ENCASSETS] Recieved Encrypted Asset, but we do not have the decryption key.");
  397. return false;
  398. }
  399. #region IAssetServer Members
  400. protected override AssetBase GetAsset(AssetRequest req)
  401. {
  402. #if DEBUG
  403. //m_log.DebugFormat("[GRID ASSET CLIENT]: Querying for {0}", req.AssetID.ToString());
  404. #endif
  405. RestClient rc = new RestClient(_assetServerUrl);
  406. rc.AddResourcePath("assets");
  407. rc.AddResourcePath(req.AssetID.ToString());
  408. if (req.IsTexture)
  409. rc.AddQueryParameter("texture");
  410. rc.RequestMethod = "GET";
  411. Stream s = rc.Request();
  412. if (s == null)
  413. return null;
  414. if (s.Length > 0)
  415. {
  416. XmlSerializer xs = new XmlSerializer(typeof(AssetBase));
  417. AssetBase encAsset = (AssetBase)xs.Deserialize(s);
  418. // Try decrypt it
  419. if (DecryptAssetBase(encAsset))
  420. return encAsset;
  421. }
  422. return null;
  423. }
  424. public override void UpdateAsset(AssetBase asset)
  425. {
  426. throw new Exception("The method or operation is not implemented.");
  427. }
  428. public override void StoreAsset(AssetBase asset)
  429. {
  430. if (m_encryptOnUpload)
  431. EncryptAssetBase(asset, m_encryptKey);
  432. try
  433. {
  434. string assetUrl = _assetServerUrl + "/assets/";
  435. m_log.InfoFormat("[CRYPTO GRID ASSET CLIENT]: Sending store request for asset {0}", asset.FullID);
  436. RestObjectPoster.BeginPostObject<AssetBase>(assetUrl, asset);
  437. }
  438. catch (Exception e)
  439. {
  440. m_log.ErrorFormat("[CRYPTO GRID ASSET CLIENT]: {0}", e);
  441. }
  442. }
  443. public override void Close()
  444. {
  445. throw new Exception("The method or operation is not implemented.");
  446. }
  447. #endregion
  448. }
  449. }