Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Net.Sockets;
- using System.Net;
- using System.Security.Cryptography.X509Certificates;
- using System.Net.Security;
- using System.IO;
- using System.Diagnostics;
- using System.Linq;
- using System.Threading;
- namespace WiKIDclient
- {
- public interface IwClient
- {
- bool RegisterUsername(string username, string registrationCode, string serverCode);
- bool RegisterUsername(string username, string registrationCode, string serverCode, string passCode);
- bool CheckCredentials(string username, string passCode, string serverCode);
- string FindUserByName(string username, string serverCode);
- string GetUserInfo(string username, string serverCode);
- string DeleteUser(string username, string serverCode);
- string UnlockUser(string username, string serverCode);
- }
- public sealed class WiKIDSingleton : IwClient , IDisposable
- {
- #region local variables
- private string serverAddress = "192.168.1.11"; // Change to the real address of your WiKID Server
- private int serverPort = 8388; // 8388 is the default port number
- private string certificateFileName = "C:\\WiKID\\WebServer.p12"; // Change to your real certificate
- private string certPassPhrase = "test123"; // You did write it down, didn't you?
- string _serverAddress;
- int _serverPort;
- X509Certificate2 _certificate;
- TcpClient _tcpClient;
- SslStream _sslStream;
- int _sslStreamReadTimeout = 60000; //milliseconds
- bool _caseSensitive = false; // Change to true to not force usernames to lowercase
- String _connectTx = "<transaction><type>1</type><data>" +
- "<client-string>WiKID C# Client 3.01</client-string>" +
- "<server-string></server-string>" +
- "<result></result></data></transaction>\n";
- String _registerTx = "<transaction><type format=\"new\">4</type><data>" +
- "<user-id>{0}</user-id>" +
- "<registration-code>{1}</registration-code>" +
- "<domaincode>{2}</domaincode>" +
- "<passcode>{3}</passcode>" +
- "<error-code></error-code><result></result></data></transaction>\n";
- String _checkCredsTx = "<transaction><type format=\"base\">2</type><data>" +
- "<user-id>{0}</user-id>" +
- "<passcode>{1}</passcode>" +
- "<domaincode>{2}</domaincode>" +
- "<offline-challenge encoding=\"none\"></offline-challenge>" +
- "<offline-response encoding=\"none\"></offline-response>" +
- "<chap-password encoding=\"base64\"></chap-password>" +
- "<chap-challenge encoding=\"base64\"></chap-challenge>" +
- "<result></result></data></transaction>\n";
- String _findUserTx = "<transaction><type>5</type><data>" +
- "<user-id>{0}</user-id>" +
- "<domaincode>{1}</domaincode>" +
- "<result>null</result>" +
- "<return-code>-2147483648</return-code>" +
- "</data></transaction>\n";
- String _deleteUserTx = "<transaction><type>7</type><data>{0}<result>null</result>" +
- "<return-code>-2147483648</return-code></data></transaction>\n";
- String _unlockUserTx = "<transaction><type>6</type><data>{0}<result>null</result>" +
- "<return-code>-2147483648</return-code></data></transaction>\n";
- #endregion
- private static readonly Lazy<WiKIDSingleton> _instance = new Lazy<WiKIDSingleton>(() => new WiKIDSingleton());
- public static WiKIDSingleton Instance { get { return _instance.Value; } }
- private WiKIDSingleton()
- {
- init(serverAddress, serverPort, certificateFileName, certPassPhrase);
- }
- private void init(string serverAddress, int serverPort, string certificateFileName, string certPassPhrase)
- {
- if (!File.Exists(certificateFileName)) throw new FileNotFoundException("Certificate file not found");
- X509Certificate2 certificate = new X509Certificate2(certificateFileName, certPassPhrase, X509KeyStorageFlags.MachineKeySet);
- // init sslStream
- _serverAddress = serverAddress;
- _serverPort = serverPort;
- _certificate = certificate;
- TestConnection();
- }
- /// <summary>
- /// Max time we are waiting for data come from server
- /// </summary>
- public int ReadTimeout
- {
- get { return _sslStreamReadTimeout; }
- set
- {
- _sslStreamReadTimeout = value;
- if (_sslStream != null) _sslStream.ReadTimeout = value;
- }
- }
- /// <summary>
- /// Register User at WiKID server
- /// </summary>
- /// <param name="username">User Name</param>
- /// <param name="registrationCode">Registration code aquired by token client</param>
- /// <param name="serverCode">Server Code (domain) we are registering user at</param>
- /// <returns>true if registration succeeded, false - otherway</returns>
- public bool RegisterUsername(string username, string registrationCode, string serverCode)
- {
- return RegisterUsername(username, registrationCode, serverCode, string.Empty);
- }
- /// <summary>
- /// Register User at WiKID server
- /// </summary>
- /// <param name="username">User Name</param>
- /// <param name="registrationCode">Registration code aquired by token client</param>
- /// <param name="serverCode">Server Code (domain) we are registering user at</param>
- /// <param name="passCode">PassCode, acquired by token client. Optional</param>
- /// <returns></returns>
- public bool RegisterUsername(string username, string registrationCode, string serverCode, string passCode)
- {
- if (!_tcpClient.Connected) Connect();
- if (!_caseSensitive) username = username.ToLower();
- string transaction = String.Format(_registerTx, username, registrationCode, serverCode, passCode);
- string response = Send(transaction);
- return response != null && response.IndexOf("<result>SUCESS</result>") != -1;
- }
- /// <summary>
- /// Check Entered credentials at WiKID server
- /// </summary>
- /// <param name="username">User Name</param>
- /// <param name="passCode">PassCode aquired by token client</param>
- /// <param name="serverCode">Server Code (domain) we are checking credentials against</param>
- /// <returns>true if credentials are verified and accepted</returns>
- public bool CheckCredentials(string username, string passCode, string serverCode)
- {
- if (!_tcpClient.Connected) Connect();
- if (!_caseSensitive) username = username.ToLower();
- string transaction = String.Format(_checkCredsTx, username, passCode, serverCode);
- string response = Send(transaction);
- return response != null && response.IndexOf("<result>VALID</result>") != -1;
- }
- /// <summary>
- /// Find User by Name at WiKID Server
- /// </summary>
- /// <param name="username">User Name</param>
- /// <param name="serverCode">Server Code (domain) we are checking credentials against</param>
- /// <returns>response string xml</returns>
- public string FindUserByName(string username, string serverCode)
- {
- if (!_tcpClient.Connected) Connect();
- if (!_caseSensitive) username = username.ToLower();
- string transaction = String.Format(_findUserTx, username, serverCode);
- string response = Send(transaction);
- return response;
- }
- /// <summary>
- /// Return User Object
- /// </summary>
- /// <param name="username">User Name</param>
- /// <param name="serverCode">Server Code (domain) we are checking credentials against</param>
- /// <returns>user information xml fragment</returns>
- public string GetUserInfo(string username, string serverCode)
- {
- if (!_caseSensitive) username = username.ToLower();
- string userinfo = FindUserByName(username, serverCode);
- if (userinfo.IndexOf("<user>") < 0) return userinfo;
- userinfo = userinfo.Substring(userinfo.IndexOf("<user>"));
- userinfo = userinfo.Substring(0, userinfo.IndexOf("</user>") + 7);
- return userinfo;
- }
- /// <summary>
- /// Delete User at WiKID Server
- /// </summary>
- /// <param name="username">User Name</param>
- /// <param name="serverCode">Server Code (domain) we are checking credentials against</param>
- /// <returns>response string xml</returns>
- public string DeleteUser(string username, string serverCode)
- {
- if (!_caseSensitive) username = username.ToLower();
- string userinfo = GetUserInfo(username, serverCode);
- if (userinfo.IndexOf("<user>") < 0) return userinfo;
- if (!_tcpClient.Connected) Connect();
- string transaction = String.Format(_deleteUserTx, userinfo);
- string response = Send(transaction);
- return response;
- }
- /// <summary>
- /// Unlock User at WiKID Server
- /// </summary>
- /// <param name="username">User Name</param>
- /// <param name="serverCode">Server Code (domain) we are checking credentials against</param>
- /// <returns>response string xml</returns>
- public string UnlockUser(string username, string serverCode)
- {
- if (!_caseSensitive) username = username.ToLower();
- string userinfo = GetUserInfo(username, serverCode);
- if (userinfo.IndexOf("<user>") < 0) return userinfo;
- string userinfo1 = userinfo.Substring(0, userinfo.IndexOf("<status>") + 8);
- string userinfo2 = userinfo.Substring(userinfo.IndexOf("</status>"));
- userinfo = userinfo1 + "1" + userinfo2;
- userinfo1 = userinfo.Substring(0, userinfo.IndexOf("<bad-passcode-attempts>") + 23);
- userinfo2 = userinfo.Substring(userinfo.IndexOf("</bad-passcode-attempts>"));
- userinfo = userinfo1 + "0" + userinfo2;
- userinfo1 = userinfo.Substring(0, userinfo.IndexOf("<bad-pin-attempts>") + 18);
- userinfo2 = userinfo.Substring(userinfo.IndexOf("</bad-pin-attempts>"));
- userinfo = userinfo1 + "0" + userinfo2;
- userinfo1 = userinfo.Substring(0, userinfo.IndexOf("<changed>") + 9);
- userinfo2 = userinfo.Substring(userinfo.IndexOf("</changed>"));
- userinfo = userinfo1 + "true" + userinfo2;
- string userinfo3 = userinfo.Substring(0, userinfo.IndexOf("<token>"));
- string userinfo4 = userinfo.Substring(userinfo.IndexOf("</token>") + 8);
- string userinfo5 = userinfo.Substring(userinfo.IndexOf("<token>"), userinfo.IndexOf("</token>") + 8 - userinfo.IndexOf("<token>"));
- /* return userinfo5; */
- string userinfo6 = userinfo5.Substring(0, userinfo5.IndexOf("<status>") + 8);
- string userinfo7 = userinfo5.Substring(userinfo5.IndexOf("</status>"));
- userinfo5 = userinfo6 + "1" + userinfo7;
- userinfo = userinfo3 + userinfo5 + userinfo4;
- /* return userinfo; */
- if (!_tcpClient.Connected) Connect();
- string transaction = String.Format(_unlockUserTx, userinfo);
- string response = Send(transaction);
- return response;
- }
- #region connection helper functions
- private void Connect()
- {
- if (_tcpClient == null || !_tcpClient.Connected)
- {
- _tcpClient = new TcpClient(_serverAddress, _serverPort);
- _sslStream = new SslStream(_tcpClient.GetStream(), true, new RemoteCertificateValidationCallback(ValidateServerCertificate)); //, new LocalCertificateSelectionCallback(getClientCertificate));
- _sslStream.ReadTimeout = _sslStreamReadTimeout;
- _sslStream.AuthenticateAsClient(_serverAddress, new X509Certificate2Collection(_certificate), System.Security.Authentication.SslProtocols.Tls, false);
- }
- }
- private string Send(string message)
- {
- byte[] m = Encoding.ASCII.GetBytes(message);
- _sslStream.Write(m);
- return ReadMessage(_sslStream);
- }
- private void Disconnect()
- {
- if (_tcpClient.Connected)
- Send("QUIT\n");
- _sslStream.Close();
- _tcpClient.Close();
- }
- public void TestConnection()
- {
- Connect();
- string response = Send(_connectTx);
- if (response == null || response.IndexOf("<result>ACCEPT</result>", StringComparison.InvariantCultureIgnoreCase) == -1)
- throw new Exception("wrong response: " + response);
- }
- // The following method is invoked by the RemoteCertificateValidationDelegate.
- internal static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
- {
- // allow this client to communicate to any server
- return true;
- //if (sslPolicyErrors == SslPolicyErrors.None) return true;
- // Do not allow this client to communicate with unauthenticated servers.
- //return false;
- }
- // The following method is invoked by the LocalCertificateSelectionCallback
- internal X509Certificate getClientCertificate(Object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers)
- {
- return _certificate;
- }
- #region ReadMessage
- string ReadMessage(SslStream sslStream)
- {
- // Read the message sent by the server.
- // The end of the message is signaled using the
- // "<EOF>" marker.
- byte[] buffer = new byte[2048];
- StringBuilder messageData = new StringBuilder();
- int bytes = -1;
- do
- {
- bytes = sslStream.Read(buffer, 0, buffer.Length);
- // Use Decoder class to convert from bytes to UTF8
- // in case a character spans two buffers.
- Decoder decoder = Encoding.UTF8.GetDecoder();
- char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
- decoder.GetChars(buffer, 0, bytes, chars, 0);
- messageData.Append(chars);
- // Check for End of line.
- if (messageData.ToString().IndexOf("\n") != -1)
- {
- break;
- }
- } while (bytes != 0);
- return messageData.ToString();
- }
- #endregion
- #endregion
- #region IDisposable Members
- public void Dispose()
- {
- Disconnect();
- }
- #endregion
- }
- public class wClient : IwClient
- {
- #region local variables
- private WiKIDSingleton wc = WiKIDSingleton.Instance;
- #endregion
- public bool RegisterUsername(string username, string registrationCode, string serverCode)
- {
- return wc.RegisterUsername(username, registrationCode, serverCode);
- }
- public bool RegisterUsername(string username, string registrationCode, string serverCode, string passCode)
- {
- return wc.RegisterUsername(username, registrationCode, serverCode, passCode);
- }
- public bool CheckCredentials(string username, string passCode, string serverCode)
- {
- return wc.CheckCredentials(username, passCode, serverCode);
- }
- public string FindUserByName(string username, string serverCode)
- {
- return wc.FindUserByName(username, serverCode);
- }
- public string GetUserInfo(string username, string serverCode)
- {
- return wc.GetUserInfo(username, serverCode);
- }
- public string DeleteUser(string username, string serverCode)
- {
- return wc.DeleteUser(username, serverCode);
- }
- public string UnlockUser(string username, string serverCode)
- {
- return wc.UnlockUser(username, serverCode);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment