Guest User

Untitled

a guest
Oct 16th, 2012
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.59 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Net.Sockets;
  5. using System.Net;
  6. using System.Security.Cryptography.X509Certificates;
  7. using System.Net.Security;
  8. using System.IO;
  9. using System.Diagnostics;
  10. using System.Linq;
  11. using System.Threading;
  12.  
  13. namespace WiKIDclient
  14. {
  15.  
  16. public interface IwClient
  17. {
  18. bool RegisterUsername(string username, string registrationCode, string serverCode);
  19. bool RegisterUsername(string username, string registrationCode, string serverCode, string passCode);
  20. bool CheckCredentials(string username, string passCode, string serverCode);
  21. string FindUserByName(string username, string serverCode);
  22. string GetUserInfo(string username, string serverCode);
  23. string DeleteUser(string username, string serverCode);
  24. string UnlockUser(string username, string serverCode);
  25. }
  26.  
  27. public sealed class WiKIDSingleton : IwClient , IDisposable
  28. {
  29.  
  30. #region local variables
  31. private string serverAddress = "192.168.1.11"; // Change to the real address of your WiKID Server
  32. private int serverPort = 8388; // 8388 is the default port number
  33. private string certificateFileName = "C:\\WiKID\\WebServer.p12"; // Change to your real certificate
  34. private string certPassPhrase = "test123"; // You did write it down, didn't you?
  35. string _serverAddress;
  36. int _serverPort;
  37. X509Certificate2 _certificate;
  38. TcpClient _tcpClient;
  39. SslStream _sslStream;
  40. int _sslStreamReadTimeout = 60000; //milliseconds
  41. bool _caseSensitive = false; // Change to true to not force usernames to lowercase
  42.  
  43. String _connectTx = "<transaction><type>1</type><data>" +
  44. "<client-string>WiKID C# Client 3.01</client-string>" +
  45. "<server-string></server-string>" +
  46. "<result></result></data></transaction>\n";
  47. String _registerTx = "<transaction><type format=\"new\">4</type><data>" +
  48. "<user-id>{0}</user-id>" +
  49. "<registration-code>{1}</registration-code>" +
  50. "<domaincode>{2}</domaincode>" +
  51. "<passcode>{3}</passcode>" +
  52. "<error-code></error-code><result></result></data></transaction>\n";
  53. String _checkCredsTx = "<transaction><type format=\"base\">2</type><data>" +
  54. "<user-id>{0}</user-id>" +
  55. "<passcode>{1}</passcode>" +
  56. "<domaincode>{2}</domaincode>" +
  57. "<offline-challenge encoding=\"none\"></offline-challenge>" +
  58. "<offline-response encoding=\"none\"></offline-response>" +
  59. "<chap-password encoding=\"base64\"></chap-password>" +
  60. "<chap-challenge encoding=\"base64\"></chap-challenge>" +
  61. "<result></result></data></transaction>\n";
  62. String _findUserTx = "<transaction><type>5</type><data>" +
  63. "<user-id>{0}</user-id>" +
  64. "<domaincode>{1}</domaincode>" +
  65. "<result>null</result>" +
  66. "<return-code>-2147483648</return-code>" +
  67. "</data></transaction>\n";
  68. String _deleteUserTx = "<transaction><type>7</type><data>{0}<result>null</result>" +
  69. "<return-code>-2147483648</return-code></data></transaction>\n";
  70. String _unlockUserTx = "<transaction><type>6</type><data>{0}<result>null</result>" +
  71. "<return-code>-2147483648</return-code></data></transaction>\n";
  72.  
  73. #endregion
  74.  
  75. private static readonly Lazy<WiKIDSingleton> _instance = new Lazy<WiKIDSingleton>(() => new WiKIDSingleton());
  76.  
  77. public static WiKIDSingleton Instance { get { return _instance.Value; } }
  78.  
  79. private WiKIDSingleton()
  80. {
  81. init(serverAddress, serverPort, certificateFileName, certPassPhrase);
  82. }
  83.  
  84.  
  85. private void init(string serverAddress, int serverPort, string certificateFileName, string certPassPhrase)
  86. {
  87. if (!File.Exists(certificateFileName)) throw new FileNotFoundException("Certificate file not found");
  88. X509Certificate2 certificate = new X509Certificate2(certificateFileName, certPassPhrase, X509KeyStorageFlags.MachineKeySet);
  89.  
  90. // init sslStream
  91. _serverAddress = serverAddress;
  92. _serverPort = serverPort;
  93. _certificate = certificate;
  94.  
  95. TestConnection();
  96. }
  97. /// <summary>
  98. /// Max time we are waiting for data come from server
  99. /// </summary>
  100. public int ReadTimeout
  101. {
  102. get { return _sslStreamReadTimeout; }
  103. set
  104. {
  105. _sslStreamReadTimeout = value;
  106. if (_sslStream != null) _sslStream.ReadTimeout = value;
  107. }
  108. }
  109.  
  110. /// <summary>
  111. /// Register User at WiKID server
  112. /// </summary>
  113. /// <param name="username">User Name</param>
  114. /// <param name="registrationCode">Registration code aquired by token client</param>
  115. /// <param name="serverCode">Server Code (domain) we are registering user at</param>
  116. /// <returns>true if registration succeeded, false - otherway</returns>
  117. public bool RegisterUsername(string username, string registrationCode, string serverCode)
  118. {
  119. return RegisterUsername(username, registrationCode, serverCode, string.Empty);
  120. }
  121. /// <summary>
  122. /// Register User at WiKID server
  123. /// </summary>
  124. /// <param name="username">User Name</param>
  125. /// <param name="registrationCode">Registration code aquired by token client</param>
  126. /// <param name="serverCode">Server Code (domain) we are registering user at</param>
  127. /// <param name="passCode">PassCode, acquired by token client. Optional</param>
  128. /// <returns></returns>
  129. public bool RegisterUsername(string username, string registrationCode, string serverCode, string passCode)
  130. {
  131. if (!_tcpClient.Connected) Connect();
  132. if (!_caseSensitive) username = username.ToLower();
  133. string transaction = String.Format(_registerTx, username, registrationCode, serverCode, passCode);
  134. string response = Send(transaction);
  135. return response != null && response.IndexOf("<result>SUCESS</result>") != -1;
  136.  
  137. }
  138. /// <summary>
  139. /// Check Entered credentials at WiKID server
  140. /// </summary>
  141. /// <param name="username">User Name</param>
  142. /// <param name="passCode">PassCode aquired by token client</param>
  143. /// <param name="serverCode">Server Code (domain) we are checking credentials against</param>
  144. /// <returns>true if credentials are verified and accepted</returns>
  145. public bool CheckCredentials(string username, string passCode, string serverCode)
  146. {
  147. if (!_tcpClient.Connected) Connect();
  148. if (!_caseSensitive) username = username.ToLower();
  149. string transaction = String.Format(_checkCredsTx, username, passCode, serverCode);
  150. string response = Send(transaction);
  151. return response != null && response.IndexOf("<result>VALID</result>") != -1;
  152. }
  153. /// <summary>
  154. /// Find User by Name at WiKID Server
  155. /// </summary>
  156. /// <param name="username">User Name</param>
  157. /// <param name="serverCode">Server Code (domain) we are checking credentials against</param>
  158. /// <returns>response string xml</returns>
  159. public string FindUserByName(string username, string serverCode)
  160. {
  161. if (!_tcpClient.Connected) Connect();
  162. if (!_caseSensitive) username = username.ToLower();
  163. string transaction = String.Format(_findUserTx, username, serverCode);
  164. string response = Send(transaction);
  165. return response;
  166. }
  167. /// <summary>
  168. /// Return User Object
  169. /// </summary>
  170. /// <param name="username">User Name</param>
  171. /// <param name="serverCode">Server Code (domain) we are checking credentials against</param>
  172. /// <returns>user information xml fragment</returns>
  173. public string GetUserInfo(string username, string serverCode)
  174. {
  175. if (!_caseSensitive) username = username.ToLower();
  176. string userinfo = FindUserByName(username, serverCode);
  177. if (userinfo.IndexOf("<user>") < 0) return userinfo;
  178. userinfo = userinfo.Substring(userinfo.IndexOf("<user>"));
  179. userinfo = userinfo.Substring(0, userinfo.IndexOf("</user>") + 7);
  180. return userinfo;
  181. }
  182. /// <summary>
  183. /// Delete User at WiKID Server
  184. /// </summary>
  185. /// <param name="username">User Name</param>
  186. /// <param name="serverCode">Server Code (domain) we are checking credentials against</param>
  187. /// <returns>response string xml</returns>
  188. public string DeleteUser(string username, string serverCode)
  189. {
  190. if (!_caseSensitive) username = username.ToLower();
  191. string userinfo = GetUserInfo(username, serverCode);
  192. if (userinfo.IndexOf("<user>") < 0) return userinfo;
  193. if (!_tcpClient.Connected) Connect();
  194. string transaction = String.Format(_deleteUserTx, userinfo);
  195. string response = Send(transaction);
  196. return response;
  197. }
  198. /// <summary>
  199. /// Unlock User at WiKID Server
  200. /// </summary>
  201. /// <param name="username">User Name</param>
  202. /// <param name="serverCode">Server Code (domain) we are checking credentials against</param>
  203. /// <returns>response string xml</returns>
  204. public string UnlockUser(string username, string serverCode)
  205. {
  206. if (!_caseSensitive) username = username.ToLower();
  207. string userinfo = GetUserInfo(username, serverCode);
  208. if (userinfo.IndexOf("<user>") < 0) return userinfo;
  209. string userinfo1 = userinfo.Substring(0, userinfo.IndexOf("<status>") + 8);
  210. string userinfo2 = userinfo.Substring(userinfo.IndexOf("</status>"));
  211. userinfo = userinfo1 + "1" + userinfo2;
  212.  
  213. userinfo1 = userinfo.Substring(0, userinfo.IndexOf("<bad-passcode-attempts>") + 23);
  214. userinfo2 = userinfo.Substring(userinfo.IndexOf("</bad-passcode-attempts>"));
  215. userinfo = userinfo1 + "0" + userinfo2;
  216.  
  217. userinfo1 = userinfo.Substring(0, userinfo.IndexOf("<bad-pin-attempts>") + 18);
  218. userinfo2 = userinfo.Substring(userinfo.IndexOf("</bad-pin-attempts>"));
  219. userinfo = userinfo1 + "0" + userinfo2;
  220.  
  221. userinfo1 = userinfo.Substring(0, userinfo.IndexOf("<changed>") + 9);
  222. userinfo2 = userinfo.Substring(userinfo.IndexOf("</changed>"));
  223. userinfo = userinfo1 + "true" + userinfo2;
  224.  
  225. string userinfo3 = userinfo.Substring(0, userinfo.IndexOf("<token>"));
  226. string userinfo4 = userinfo.Substring(userinfo.IndexOf("</token>") + 8);
  227. string userinfo5 = userinfo.Substring(userinfo.IndexOf("<token>"), userinfo.IndexOf("</token>") + 8 - userinfo.IndexOf("<token>"));
  228. /* return userinfo5; */
  229. string userinfo6 = userinfo5.Substring(0, userinfo5.IndexOf("<status>") + 8);
  230. string userinfo7 = userinfo5.Substring(userinfo5.IndexOf("</status>"));
  231. userinfo5 = userinfo6 + "1" + userinfo7;
  232. userinfo = userinfo3 + userinfo5 + userinfo4;
  233.  
  234. /* return userinfo; */
  235. if (!_tcpClient.Connected) Connect();
  236. string transaction = String.Format(_unlockUserTx, userinfo);
  237. string response = Send(transaction);
  238. return response;
  239. }
  240.  
  241. #region connection helper functions
  242. private void Connect()
  243. {
  244. if (_tcpClient == null || !_tcpClient.Connected)
  245. {
  246. _tcpClient = new TcpClient(_serverAddress, _serverPort);
  247. _sslStream = new SslStream(_tcpClient.GetStream(), true, new RemoteCertificateValidationCallback(ValidateServerCertificate)); //, new LocalCertificateSelectionCallback(getClientCertificate));
  248. _sslStream.ReadTimeout = _sslStreamReadTimeout;
  249. _sslStream.AuthenticateAsClient(_serverAddress, new X509Certificate2Collection(_certificate), System.Security.Authentication.SslProtocols.Tls, false);
  250. }
  251. }
  252. private string Send(string message)
  253. {
  254. byte[] m = Encoding.ASCII.GetBytes(message);
  255. _sslStream.Write(m);
  256. return ReadMessage(_sslStream);
  257. }
  258. private void Disconnect()
  259. {
  260. if (_tcpClient.Connected)
  261. Send("QUIT\n");
  262. _sslStream.Close();
  263. _tcpClient.Close();
  264. }
  265.  
  266. public void TestConnection()
  267. {
  268. Connect();
  269. string response = Send(_connectTx);
  270. if (response == null || response.IndexOf("<result>ACCEPT</result>", StringComparison.InvariantCultureIgnoreCase) == -1)
  271. throw new Exception("wrong response: " + response);
  272. }
  273. // The following method is invoked by the RemoteCertificateValidationDelegate.
  274. internal static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
  275. {
  276. // allow this client to communicate to any server
  277. return true;
  278. //if (sslPolicyErrors == SslPolicyErrors.None) return true;
  279. // Do not allow this client to communicate with unauthenticated servers.
  280. //return false;
  281. }
  282.  
  283. // The following method is invoked by the LocalCertificateSelectionCallback
  284. internal X509Certificate getClientCertificate(Object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers)
  285. {
  286. return _certificate;
  287. }
  288.  
  289. #region ReadMessage
  290. string ReadMessage(SslStream sslStream)
  291. {
  292. // Read the message sent by the server.
  293. // The end of the message is signaled using the
  294. // "<EOF>" marker.
  295. byte[] buffer = new byte[2048];
  296. StringBuilder messageData = new StringBuilder();
  297. int bytes = -1;
  298. do
  299. {
  300. bytes = sslStream.Read(buffer, 0, buffer.Length);
  301.  
  302. // Use Decoder class to convert from bytes to UTF8
  303. // in case a character spans two buffers.
  304. Decoder decoder = Encoding.UTF8.GetDecoder();
  305. char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
  306. decoder.GetChars(buffer, 0, bytes, chars, 0);
  307. messageData.Append(chars);
  308. // Check for End of line.
  309. if (messageData.ToString().IndexOf("\n") != -1)
  310. {
  311. break;
  312. }
  313. } while (bytes != 0);
  314.  
  315. return messageData.ToString();
  316. }
  317. #endregion
  318. #endregion
  319. #region IDisposable Members
  320.  
  321. public void Dispose()
  322. {
  323. Disconnect();
  324. }
  325.  
  326. #endregion
  327. }
  328.  
  329. public class wClient : IwClient
  330. {
  331. #region local variables
  332. private WiKIDSingleton wc = WiKIDSingleton.Instance;
  333. #endregion
  334.  
  335. public bool RegisterUsername(string username, string registrationCode, string serverCode)
  336. {
  337. return wc.RegisterUsername(username, registrationCode, serverCode);
  338. }
  339.  
  340. public bool RegisterUsername(string username, string registrationCode, string serverCode, string passCode)
  341. {
  342. return wc.RegisterUsername(username, registrationCode, serverCode, passCode);
  343. }
  344.  
  345. public bool CheckCredentials(string username, string passCode, string serverCode)
  346. {
  347. return wc.CheckCredentials(username, passCode, serverCode);
  348. }
  349.  
  350. public string FindUserByName(string username, string serverCode)
  351. {
  352. return wc.FindUserByName(username, serverCode);
  353. }
  354.  
  355. public string GetUserInfo(string username, string serverCode)
  356. {
  357. return wc.GetUserInfo(username, serverCode);
  358. }
  359.  
  360. public string DeleteUser(string username, string serverCode)
  361. {
  362. return wc.DeleteUser(username, serverCode);
  363. }
  364.  
  365. public string UnlockUser(string username, string serverCode)
  366. {
  367. return wc.UnlockUser(username, serverCode);
  368. }
  369. }
  370. }
Advertisement
Add Comment
Please, Sign In to add comment