17 Aralık 2015 Perşembe

SSL/TLS based communication between Mosquitto Broker and Mqtt Java Client

I see that there is not so many source to provide SSL/TLS based communication between Mosquitto broker and Mqtt client on Windows. I have gained some experinces about it while developing Mqtt java client. I'll share main points of them;

:. MQTT provides username/password authentication as part of the protocol. Use 'password_file' option on mosquitto.conf to define usernames/passwords. Be sure to use network encryption if you are using this option otherwise the username and password will be vulnerable to interception (1).

.: As a network encryption, SSL/TLS feature of Mosquitto should be used. There are two encryption models in Mosquitto; certificate based encryption and pre-shared key based encryption.

a) I used certificate based encryption with username/password authentication. First, I created username/password from command prompt by using mosquitto_passwd(2);
mosquitto_passwd -c /demo username
b) To create certificates,  I downloaded OpenSSL v1.0.2e (If Visual C++ 2008 Redistributables is not installed already, it should be downloaded and setup initially). I set some environment variables before I start OpenSSL; 
set RANDFILE=c:\demo\.rnd
set OPENSSL_CONF=C:\OpenSSL-Win32\bin\openssl.cfg
c) I started OpenSSL by running start "openssl.exe" in directory of OpenSSL. Then, I created certificates by using OpenSSL. I followed instructions on (3)The root CA certificate (ca.crt) was created initially.


Related certificate information is shown above. I also entered "trialca" as PEM password for ca.crt. Then, I created server.key, server.csr and server crt;


client.key and client.crt was created like server.key and server.crt.

d) I made some configuration on mosquitto conf;
# Default listener;
listener 1883 127.0.0.1

# Certificate based SSL/TLS support(for default listener);
require_certificate false
use_identity_as_username false

# Extra listeners;
listener 8883

# Certificate based SSL/TLS support(for extra listeners);
cafile /demo/ca.crt
certfile /demo/server.crt
keyfile /server.key
require_certificate true
use_identity_as_username false

# Security;
allow_anonymous false

# Default authentication and topic access control
password_file /demo/mosquitto_passFile 
(username and password is added by using mosquitto_passwd)
e) I loaded mosquitto.conf from command prompt on Mosquitto server running on PC. 
c:\Program Files (x86)\mosquitto> mosquitto -c mosquitto.conf
f) To run these new configuration on Mosquitto, Mosquitto-service should be restarted from 'Services' on Windows.

Note: I had entered "trialsrv" as a password for server.key, but while Mosquitto was made restarted, it could not be started. It threw an error. About this problem, I wrote an question on stackoverflow.com (4) . I used the recommendation in this link and removed password for server.key. Then, I saw that Mosquitto could be restarted properly!

**  Configuration of Mosquitto broker was finished!

g)  For the client's side, first, I added ca.crt, client.key and client.crt in Mqtt Java client project.that is already developed by using Eclipse MQTT Paho Project (5). My client project is a kind of web application (used JSF framework), that's why I added certificates under the folder - WebContent/resources/certificates/.

h) Then, I googled for some Mqtt SSL/TLS java codes to give me an idea about how to bind my project with the broker. I found Sharonbn's SslUtil java class(6) and a new version of Sharonbn's class by Rohanag12(7). I used Rohanag12 solution, because it was newer and compatible with Mqtt and related other libraries.

i) I included path of certificates, that were added in the project in (g), in my codes. 
ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
conOpt.setSocketFactory(SslUtil.getSocketFactory(servletContext.getRealPath("/resources/certificates/ca.crt"), servletContext.getRealPath("/resources/certificates/client.crt"), servletContext.getRealPath("/resources/certificates/client.key"), "trialclt"));

Eureka! Setup of SSL/TLS based authentication and messaging is made successfully. 

Note: Be careful! Firewall of antivirus programs and Windows firewall may prevent communication between Mosquitto broker and Mqtt java client.

References: 
1) https://eclipse.org/mosquitto/man/mosquitto-conf-5.php/
2) https://eclipse.org/mosquitto/man/mosquitto_passwd-1.php/
3) https://eclipse.org/mosquitto/man/mosquitto-tls-7.php/
4) http://stackoverflow.com/questions/34226717/how-to-provide-ssl-tls-based-communication-on-mosquitto/
5) https://www.eclipse.org/paho/
6) https://gist.github.com/sharonbn/4104301/
7) https://gist.github.com/rohanag12/07ab7eb22556244e9698/
8) http://blog.didierstevens.com/2015/03/30/howto-make-your-own-cert-with-openssl-on-windows/

11 Kasım 2015 Çarşamba

How to create standalone executable file of Windows Forms Application project?

When you build a Windows Forms Application project, a single executable file and some other related files to be needed for the application are created in debug or release folder in the project directory. When you copy this executable file outside of the folder(debug/release) and run, you see that it does not work properly.

If you want to use a single executable file while running Windows Forms Application, all images and .dll files used in the application should be embedded into this executable file;

1) Images should be added into Resources;

2) Images should be configured as embedded resource in build action of properties of related image file;
3) .dll files should be added into Resources;
4) Some code should be added into Test.cs that contains Test.Designer.cs or any related C# file;
public Test()
{
    AppDomain.CurrentDomain.AssemblyResolve +=new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}

private System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    string dllName = args.Name.Contains(',') ? args.Name.Substring(0, args.Name.IndexOf(',')) : args.Name.Replace(".dll","");

    dllName = dllName.Replace(".", "_");

    if (dllName.EndsWith("_resources")) return null;

    System.Resources.ResourceManager rm = new System.Resources.ResourceManager(GetType().Namespace + ".Properties.Resources", System.Reflection.Assembly.GetExecutingAssembly());

    byte[] bytes = (byte[])rm.GetObject(dllName);

    return System.Reflection.Assembly.Load(bytes);
}
5) Build your project! Executable file of your project is ready to be used independently. You can copy/paste and run it anywhere else. Well done!

References: 
* http://codeblog.larsholm.net/2011/06/embed-dlls-easily-in-a-net-assembly/

2 Ekim 2015 Cuma

What is "Event Bubbling" in JS?

When an event is occured, this event reaches root of DOM tree.

For example, imagine that there are two DOM element that has click events. If child element is clicked, then event of parent element is also fired.

To prevent this, use properties or methods of event object of child element.

* Here is process that shows an element during event bubbling;
--------------------------------------------------------------------------
 $("p").click( function(event) {
      alert ( event.currentTarget === this ); // returns true!
 });
--------------------------------------------------------------------------

* The code below prevents "Event Bubbling” that is defined above.
It keeps the event happened in child element out of parent elements.
--------------------------------------------------------------------------
$("p").click( function(event) {
     event.stopPropagation();
     // Do smth.
});
--------------------------------------------------------------------------

References: 
1) http://ulviercan.com/teknoblog/jquery/jquery-ve-olaylar-events/
2) http://www.kazimsoylu.com/javascript/event-bubbling-javascript.html
3) http://javascript.info/tutorial/bubbling-and-capturing

What is the CSS feature - "box-sizing"?

For W3C, width and height values contain only content area. Padding and border values are not contained by these values. Most browsers use this standart.

However, IE6 and previous versions of IE6 accept such a rule that width and height values contain not only content area, but also padding and border values.

Because of this, W3C creates a feature in css to give a chance to user for selection of box-sizing type;

Structure : box-sizing: <value>
Values : content-box | border-box
Default value: content-box
Applicable elements: All elements
Inheritence: No

References: 
1) https://css-tricks.com/box-sizing/
2) http://fatihhayrioglu.com/css3-box-sizing-ozelligi/
3) http://www.w3schools.com/cssref/css3_pr_box-sizing.asp

10 Nisan 2015 Cuma

Object.wait() & Object.notifyAll() methods in Synchronization Block

Example Code:
public class MyClass {
  private List temp = new ArrayList();

  public void addItem(V obj) {
    synchronized (temp) {
      while (temp.size() >= maxSize) {
        temp.wait();
      }
      temp.add(obj);
    }
  }

  public void clear() {
    synchronized (temp) {
      temp.clear();
      temp.notifyAll();
    }
  }
}
At the first look, some questions come to my mind such as;

1) If "temp"(monitor object) is locked in sychronized block of addItem method, how can processor pass over "synchronized (temp)" in clear method and run "temp.notifyAll()" to wake up monitor object?

Answer: Object.wait() releases the monitor object! Hence, processor can get into synchronized code block in clear method and notify all threads that are put waiting.

2) Is it possible that Object.wait() is used without synchronized block?

Answer: Maybe not in this example above, but the condition in "while" may be set by a separate thread. Hence, synchronization code block is required to have this work correctly.

2 Nisan 2015 Perşembe

How to update the page when some events are occurred at the server on JSF

In simple JSF project, client request the server dynamically to get javascript and HTML codes. But, how can we see changes on HTML page when some events are occurred at the server-side?

Standart JSF 2.0 components does not supply this feature, that's why third party libraries are used to push HTML page, such as; Primefaces(<p:push>), RichFaces(<a4j:push>) and IceFaces(IcePush). However, while applying these features of these libraries, we may get in trouble with the server that we use. It may take time to configure the server and reach the solution!

Hence, I recommend <p:poll> of Primefaces. In polling mechanism, client sends ajax request to the server every 'X' seconds that we can configure. Then, server can update HTML page within necessities.

 It is very easy to apply it on JSF projects;
<p:poll interval="10" listener="#{bean.checkNotification}" oncomplete="prepareUI()" update=":form:growl :form:isUpdated" />

Specification of Port Number on Socket Programming

In applications that provide communication via socket, it is important that port number should not be between 1 and 1024. Ports between these numbers are used by root for other specific processes. If we choose a number between 1 and 1024 to specify port, we meet "Bind Permission Error" in our program!