EldoS | Feel safer!

Software components for data protection, secure storage and transfer

Multi clients communication

Also by EldoS: Rethync
The cross-platform framework that simplifies synchronizing data between mobile and desktop applications and servers and cloud storages
#6506
Posted: 06/05/2008 16:56:49
by Nature  (Basic support level)
Joined: 05/28/2008
Posts: 4

Hi, i try to develop a TLS server/client application that the server can accept multiple clients and communicate with them. I used the sample code in SSLBlackbox\Server\Chat as a base and create two console applications (i.e. client and server), however, i keep getting "handshake failure" and "insufficient security" errors. i am wondering if i have done anything wrong with the certificates.

here is my code:

SERVER:
public static class TlsServerWrapUp
{
static Socket _server;

public static void Run()
{
SBUtils.Unit.SetLicenseKey(SBUtils.Unit.BytesOfString("0645...589D"));
IPHostEntry entry = Dns.GetHostByAddress("127.0.0.1");
IPAddress hostadd = entry.AddressList[0];
IPEndPoint localEndpoint = new IPEndPoint(hostadd,
6589);
_server = new Socket(AddressFamily.InterNetwork,
System.Net.Sockets.SocketType.Stream, ProtocolType.Tcp);

_server.Bind(localEndpoint);
_server.Listen(100);
_server.BeginAccept(new AsyncCallback(AsyncAcceptCallback), _server);

Console.WriteLine("Server started....");

Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}

private static void AsyncAcceptCallback(IAsyncResult ar)
{
Socket socket = _server.EndAccept(ar);
_server.BeginAccept(new AsyncCallback(AsyncAcceptCallback), _server);

Thread tr = new Thread(new ParameterizedThreadStart(StartNewListening));
tr.Start(socket);

Console.WriteLine("Client accepted");

}
private static void StartNewListening(object socket)
{
ServerListener sl = new ServerListener((Socket)socket);
}
}

class ServerListener
{
private Socket _client;
private SBServer.TElSecureServer _secureServer = null;
private byte[] _inBuffer = null;
private int _inBufferOffset = 0;
private TElMemoryCertStorage _FMemoryCertStorage;
private const string _sDefCertPswdInCustStorage = "{37907B5C-B309-4AE4-AFD2-2EAE948EADA2}";

public ServerListener(Socket socket)
{
_client = socket;
_secureServer = new SBServer.TElSecureServer(null);
_secureServer.ClientAuthentication = true;
_secureServer.Enabled = true;
_secureServer.ForceCertificateChain = false;

_secureServer.Versions = SBConstants.Unit.sbSSL2 | SBConstants.Unit.sbSSL3 |
SBConstants.Unit.sbTLS1 | SBConstants.Unit.sbTLS11;

_secureServer.OnData += new SBSSLCommon.TSBDataEvent(ElSecureServerOnData);
_secureServer.OnSend += new SBSSLCommon.TSBSendEvent(ElSecureServerSend);
_secureServer.OnReceive += new SBSSLCommon.TSBReceiveEvent(ElSecureServerReceive);
_secureServer.OnCertificateValidate += new SBSSLCommon.TSBCertificateValidateEvent(ElSecureServerCertificateValidate);
_secureServer.OnError += new SBSSLCommon.TSBErrorEvent(secureServer_OnError);
_secureServer.Open();

_FMemoryCertStorage = new TElMemoryCertStorage();
_inBuffer = new byte[1000];
LoadStorage("CertStorageDef.ucs", _FMemoryCertStorage);

_secureServer.set_CipherSuites(SBConstants.Unit.SB_SUITE_DH_ANON_RC4_MD5, true);
_secureServer.Open();

Thread trR = new Thread(new ThreadStart(ReceiveMsgFromClient));
trR.Start();

//Thread trS = new Thread(new ThreadStart(SendMsgToClient));
//trS.Start();
}

private void SendMsgToClient()
{
string msg = "Greetings from server...";
byte[] buff = Encoding.Default.GetBytes(msg);
while (_client.Connected && _secureServer.Active)
{
_secureServer.SendData(buff);
Thread.Sleep(1000);
}
}

private void ReceiveMsgFromClient()
{
while (_client.Connected)
{
_inBufferOffset += _client.Receive(_inBuffer);
if (_inBufferOffset == 0)
throw new Exception("Connection lost");

while (_inBufferOffset > 0)
_secureServer.DataAvailable();
if (_client == null) { break; }
}
Console.WriteLine("Connection closed");
}

private void ElSecureServerOnData(Object sender, byte[] buffer)
{
string msg = Encoding.Default.GetString(buffer);
Console.WriteLine("Message from client: " + msg);
}

private void ElSecureServerReceive(Object sender,
ref byte[] buffer, int maxSize, out int written)
{
int len = Math.Min(maxSize, _inBufferOffset);
written = len;
_inBufferOffset -= len;

for (int i = 0; i < len; i++)
buffer[i] = _inBuffer[i];

for (int i = len; i < _inBufferOffset + len; i++)
_inBuffer[i - len] = _inBuffer[i];
}

private void ElSecureServerSend(Object sender, byte[] buffer)
{
string msg = Encoding.Default.GetString(buffer);
Console.WriteLine("Sending message to client: " + msg);
_client.Send(buffer);
Console.WriteLine("Message sent.");
}

private void ElSecureServerCertificateValidate(object Sender,
TElX509Certificate X509Certificate, ref bool Validate)
{
Validate = true;
// NEVER do this in real life since this makes security void.
// Instead validate the certificate as described on http://www.eldos.com/sbb/articles/1966.php
}

public static bool LoadStorage(string sFileName, TElCustomCertStorage CertStorage)
{
bool res = false;
if (!File.Exists(sFileName))
return false;

FileStream fs = new FileStream(sFileName, FileMode.Open);
try
{
CheckSBB(
CertStorage.LoadFromStreamPFX(fs, _sDefCertPswdInCustStorage, 0),
"Cannot load certificates from file storage: '" + sFileName + "'"
);
res = true;
}
finally
{
fs.Close();
}
return res;
}

public static void CheckSBB(int iErrorCode, string sErrorMessage)
{
if (iErrorCode != 0)
throw new Exception(sErrorMessage + ". Error code: '" + iErrorCode.ToString() + "'.");
}

private static void secureServer_OnError(object Sender, int ErrorCode,
bool Fatal, bool Remote)
{
Console.WriteLine("Sender: " + Sender + ", Error:" + ErrorCode.ToString());
}
}

-------------------------------------------------------------
CLIENT:
public static class TlsClientWrapUp
{
private static SBClient.TElSecureClient secureClient = null;
private static Socket clientSocket = null;
private static byte[] inBuffer = null;
private static int _inBufferOffset = 0;
private static TElMemoryCertStorage FCertStorage = null;
private const string _sDefCertPswdInCustStorage = "{37907B5C-B309-4AE4-AFD2-2EAE948EADA2}";

public static void Run()
{
Socket _client;
IPHostEntry entry = Dns.GetHostByAddress("127.0.0.1");
IPAddress hostadd = entry.AddressList[0];
IPEndPoint localEndpoint = new IPEndPoint(hostadd,
6589);
_client = new Socket(AddressFamily.InterNetwork,
System.Net.Sockets.SocketType.Stream, ProtocolType.Tcp);

_client.Connect(localEndpoint);
Console.WriteLine("Connected");

StartTlsClient(_client);
}

private static void StartTlsClient(Socket socket)
{
FCertStorage = new TElMemoryCertStorage();
LoadStorage("CertStorageDef.ucs", FCertStorage);

clientSocket = socket;
secureClient = new SBClient.TElSecureClient(null);
secureClient.Enabled = true;
secureClient.Versions = SBConstants.Unit.sbSSL2 | SBConstants.Unit.sbSSL3 |
SBConstants.Unit.sbTLS1 | SBConstants.Unit.sbTLS11;

secureClient.OnData += new SBSSLCommon.TSBDataEvent(ElSecureClientOnData);
secureClient.OnSend += new SBSSLCommon.TSBSendEvent(ElSecureClientSend);
secureClient.OnReceive += new SBSSLCommon.TSBReceiveEvent(ElSecureClientReceive);
secureClient.OnCertificateValidate += new SBSSLCommon.TSBCertificateValidateEvent(ElSecureClientCertificateValidate);
secureClient.OnCertificateNeededEx += new SBClient.TSBCertificateNeededExEvent(ElSecureClientCertificateNeededEx);
secureClient.OnError += new SBSSLCommon.TSBErrorEvent(secureClient_OnError);
secureClient.Open();

inBuffer = new byte[8192];

string msg = "Incoming from client...";
byte[] buff = Encoding.Default.GetBytes(msg);

while (clientSocket.Connected)
{
secureClient.SendData(buff);

_inBufferOffset += clientSocket.Receive(inBuffer);
if (_inBufferOffset == 0)
throw new Exception("Connection lost");

while (_inBufferOffset > 0)
secureClient.DataAvailable();
if (clientSocket == null) { break; }
}
Console.WriteLine("Connection closed");
}


private static void SendMsgToServer()
{
string msg = "Incoming from client...";
byte[] buff = Encoding.Default.GetBytes(msg);
while (clientSocket.Connected)
{
secureClient.SendData(buff);
Thread.Sleep(1000);
}
}

private static void ReceiveMsgFromServer()
{
while (clientSocket.Connected)
{
_inBufferOffset += clientSocket.Receive(inBuffer);
if (_inBufferOffset == 0)
throw new Exception("Connection lost");

while (_inBufferOffset > 0)
secureClient.DataAvailable();
if (clientSocket == null) { break; }
}
Console.WriteLine("Connection closed");
}

private static void ElSecureClientOnData(Object sender, byte[] buffer)
{
string msg = Encoding.Default.GetString(buffer);
Console.WriteLine("Message from Server: " + msg);
}

private static void ElSecureClientSend(Object sender, byte[] buffer)
{
Console.WriteLine("Sending message to Server... ");
clientSocket.Send(buffer);
Console.WriteLine("Message sent. ");
}

private static void ElSecureClientReceive(Object sender,
ref byte[] buffer, int maxSize, out int written)
{
int len = Math.Min(maxSize, _inBufferOffset);
written = len;
_inBufferOffset -= len;

for (int i = 0; i < len; i++)
buffer[i] = inBuffer[i];

for (int i = len; i < _inBufferOffset + len; i++)
inBuffer[i - len] = inBuffer[i];
}

private static void ElSecureClientCertificateNeededEx(object Sender
, ref TElX509Certificate Certificate)
{
Certificate = FCertStorage.get_Certificates(FCertStorage.Count - 1);
}

private static void ElSecureClientCertificateValidate(Object sender,
SBX509.TElX509Certificate certificate,
ref bool validate)
{
validate = true;
// NEVER do this in real life since this makes security void.
// Instead validate the certificate as described on http://www.eldos.com/sbb/articles/1966.php
}

private static void secureClient_OnError(object Sender, int ErrorCode, bool Fatal, bool Remote)
{
Console.WriteLine("Sender: " + Sender + ", " + String.Format("SSL Error occured: \"{0}\"", ErrorCode));
}


private static bool LoadStorage(string sFileName, TElCustomCertStorage CertStorage)
{
bool res = false;
if (!File.Exists(sFileName))
return false;

FileStream fs = new FileStream(sFileName, FileMode.Open);
try
{
CheckSBB(
CertStorage.LoadFromStreamPFX(fs, _sDefCertPswdInCustStorage, 0),
"Cannot load certificates from file storage: '" + sFileName + "'"
);
res = true;
}
finally
{
fs.Close();
}
return res;
}

public static void CheckSBB(int iErrorCode, string sErrorMessage)
{
if (iErrorCode != 0)
throw new Exception(sErrorMessage + ". Error code: '" + iErrorCode.ToString() + "'.");
}

private static void WaitForUserCommand(string msg)
{
Console.Write(msg);
string input = Console.ReadLine();//wait for user command
}
}
------------------------------------------------------------------

Thank you very much for your time
#6512
Posted: 06/06/2008 03:10:44
by Ken Ivanov (EldoS Corp.)

1) You are not assigning the server certificate storage to the CertStorage property of TElSecureServer object. That's why TElSecureServer does not see the certificates you have loaded into the _FMemoryCertStorage object.

2) You are calling TElSecureServer.Open method twice.
#6522
Posted: 06/08/2008 16:34:32
by Nature  (Basic support level)
Joined: 05/28/2008
Posts: 4

Thanks very much for your reply.

I v delete the first call of the open method and assign the certificate right after i load the certificates

however, the program is still not working, and now i am getting an additional error besides the previous 2:

first SSL_HANDSHAKE_FAILURE, then SSL_ILLEGAL_PARAMETER and then INSUFFICIENT_SECURITY each time the thread is sending a message
#6523
Posted: 06/08/2008 16:52:45
by Nature  (Basic support level)
Joined: 05/28/2008
Posts: 4

and, the sample c# program for tls seem doesn't work?
the SSLBlackbox\Server\Chat\ program
#6525
Posted: 06/08/2008 23:37:17
by Eugene Mayevski (EldoS Corp.)

"It doesn't work" is not something we can help with, sorry.


Sincerely yours
Eugene Mayevski
Also by EldoS: BizCrypto
Components for BizTalk® and SQL Server® Integration Services that let you securely store and transfer information in your business automation solutions.

Reply

Statistics

Topic viewed 2010 times

Number of guests: 1, registered members: 0, in total hidden: 0




|

Back to top

As of July 15, 2016 EldoS Corporation will operate as a division of /n software inc. For more information, please read the announcement.

Got it!