Wednesday, September 28, 2011

AD RMS Library Works At last part 1

Hello every one once again.

you know sometimes I'm asking my self why am I publishing my work on my blog. and the only answer that comes to my mind I don't want the people to suffer as I suffered.  really i spent a lot of my time reinventing the wheel, because the wheel which is available for every one didn't work for me. or i couldn't find any wheel out there to use.

and the funny thing this is exactly what happened to me with AD RMS or Active directory rights management system, and i suffered big time to make it work with some tiny documentation from here and there. :) specially when it comes to their fucked up SDK. so what im going to publish is how exacly RMS works in preproduction environment taking into consideration this is the only environment that you can use if you didn't sign your code from Micro-Fuck-Soft.

what is AD RMS : it is a very unique and powerful infrastructure that you install to be able to protect office documents, but if you extended the functionality you can protect PDFs or any document type you code think of if you know how the header is being organized.

what type of protection does it provide ?? its a very good question.

it gives you the functionality to restrict editing writing reading forwarding printing ... etc and you can configure the document to get expired after sometime. you can assign who should read who should write .... etc per document.

why do you need it : you need it when you have some confidential documents you which to share with some people on private or public network.

don't get me wrong on this i really hate Microsoft pretty much but this product is very fascinating one, and I'm thinking seriously about reverse engineer it and write it for open office. and if any body out there who is interested in doing so. i will be glad if we worked together.

so lets jump to the hardcore stuff since the introduction could be found out there easily and all of them is much better than mine. but what I am about to provide from hardcore point of view will never be found any where :)

how RMS Works from Developer point of view every thing starts by creating a client session to RMS Server : the functions below have a good description in microsoft MSDN so i will not spend the time addressing something which is already addressed there unless I found that I need to.

1. DRMCreateClientSession 


DRMEXPORT HRESULT UDAPICALL DRMCreateClientSession(
                        IN  DRMCALLBACK  pfnCallback,            // Callback 
                        IN  UINT         uCallbackVersion,                 // Version of the callback
                        __in     PWSTR        wszGroupIDProviderType, // one of WINDOWSAUTH/PASSPORT
                        __in_opt PWSTR        wszGroupID,             // Group ID
                        OUT DRMHSESSION* phClient );

this function will return client session handler to be used later on in  a couple of activation routines and a couple of other functions. don't worry I will iterate through all of them :)

2. DoMachineActivation



DRMEXPORT HRESULT UDAPICALL DRMActivate(
                        IN DRMHSESSION    hClient,   // Client session
                        IN UINT           uFlags,                 // One/both: DRM_ACTIVATE_MACHINE/GROUPIDENTITY
                        IN UINT           uLangID,             // Language ID
                        IN DRM_ACTSERV_INFO* pActServInfo,  // Optional activation server info
                        IN VOID*          pvContext,                // Context used for callback
                        IN HWND           hParentWnd);        // Parent window Handle


this fuction will do machine activation  by creating a file called CERT-Machine under Users - your username - AppData - Local - Microsoft - DRM this file is XML file hold certificate chain and at the end of the chain is the machine public key signed by RMS Production or Preproduction certificate Hierarchy  which allows the RMS Server to uniquely identify the machine is being used.

Machine certificate holds the following attributes

1.  issuance date and time.
2. certificate type ID and name.
3. name and ID of the issuer.
4. location from which the certificate was retrieved.
5. principal ID, public key, digest and security processor.
6. signature created by using the private key of the AD RMS activation service.
7. certificate chain that contains the server licensor certificate and one or more CA certificates.


I got bored of writing so i will continue tomorrow stay tuned my friends. :)



  

SNMP MIBs Extentions and how to use it in Linux

Hello Everyone today we will blabber for a short time about SNMP.
 I don't  now if any you are familiar with snmp configuration directives but what is very interesting for me at least is  extend, and one of the most interesting thing about that directive  that you can define your own script to be executed and assign the output to your variable name in nsExtendOutput1Line which we can use later on to create more convenient graphs using MRTG or RRD related to our needs :)  


maybe my words sounded cryptic but let me show you how this thing is being done

lets create a script to get Packet sent/recieve and both per second from one interface such as eth0 every five minutes: below is the script

#!/bin/bash


stats=$(sar -n DEV -s $(date --date='5 mins ago' +%T) | grep eth0 | tail -n2 |head -n1)

case $1 in
    received )   echo $stats | awk ' { print $6 } ';;
    sent)        echo $stats | awk ' { print $7 } ';;
    both)        echo $stats | awk ' { print $6 + $7 } ';;
esac

save it any where and make it executable . then lets go to update snmp.conf a little by add the following :


extend networktraffic /etc/snmp/myscript.sh both
extend networktrafficrcvd /etc/snmp/myscript.sh received
extend networktrafficsent /etc/snmp/myscript.sh sent

now lets do snmpwalk and check the output by executing below command if you are using snmp v3


snmpwalk -v3 -u testuser2 -l authNoPriv -a MD5 -A "pass" localhost .1|grep networktraffic

or by excuting below command if you'r configuration is
snmpwalk -v 2c -c public localhost .1|grep networktraffic

and the output will look something like this: note the ones which is marked by red


HOST-RESOURCES-MIB::hrSWRunParameters.12938 = STRING: "networktraffic"
NET-SNMP-EXTEND-MIB::nsExtendCommand."networktraffic" = STRING: /etc/snmp/myscript.sh
NET-SNMP-EXTEND-MIB::nsExtendCommand."networktrafficrcvd" = STRING: /etc/snmp//myscript.sh
NET-SNMP-EXTEND-MIB::nsExtendCommand."networktrafficsent" = STRING: /etc/snmp//myscript.sh
NET-SNMP-EXTEND-MIB::nsExtendArgs."networktraffic" = STRING: both
NET-SNMP-EXTEND-MIB::nsExtendArgs."networktrafficrcvd" = STRING: received
NET-SNMP-EXTEND-MIB::nsExtendArgs."networktrafficsent" = STRING: sent
NET-SNMP-EXTEND-MIB::nsExtendInput."networktraffic" = STRING:
NET-SNMP-EXTEND-MIB::nsExtendInput."networktrafficrcvd" = STRING:
NET-SNMP-EXTEND-MIB::nsExtendInput."networktrafficsent" = STRING:
NET-SNMP-EXTEND-MIB::nsExtendCacheTime."networktraffic" = INTEGER: 5
NET-SNMP-EXTEND-MIB::nsExtendCacheTime."networktrafficrcvd" = INTEGER: 5
NET-SNMP-EXTEND-MIB::nsExtendCacheTime."networktrafficsent" = INTEGER: 5
NET-SNMP-EXTEND-MIB::nsExtendExecType."networktraffic" = INTEGER: exec(1)
NET-SNMP-EXTEND-MIB::nsExtendExecType."networktrafficrcvd" = INTEGER: exec(1)
NET-SNMP-EXTEND-MIB::nsExtendExecType."networktrafficsent" = INTEGER: exec(1)
NET-SNMP-EXTEND-MIB::nsExtendRunType."networktraffic" = INTEGER: run-on-read(1)
NET-SNMP-EXTEND-MIB::nsExtendRunType."networktrafficrcvd" = INTEGER: run-on-read(1)
NET-SNMP-EXTEND-MIB::nsExtendRunType."networktrafficsent" = INTEGER: run-on-read(1)
NET-SNMP-EXTEND-MIB::nsExtendStorage."networktraffic" = INTEGER: permanent(4)
NET-SNMP-EXTEND-MIB::nsExtendStorage."networktrafficrcvd" = INTEGER: permanent(4)
NET-SNMP-EXTEND-MIB::nsExtendStorage."networktrafficsent" = INTEGER: permanent(4)
NET-SNMP-EXTEND-MIB::nsExtendStatus."networktraffic" = INTEGER: active(1)
NET-SNMP-EXTEND-MIB::nsExtendStatus."networktrafficrcvd" = INTEGER: active(1)
NET-SNMP-EXTEND-MIB::nsExtendStatus."networktrafficsent" = INTEGER: active(1)
NET-SNMP-EXTEND-MIB::nsExtendOutput1Line."networktraffic" = STRING: 12145.6
NET-SNMP-EXTEND-MIB::nsExtendOutput1Line."networktrafficrcvd" = STRING: 6309.75
NET-SNMP-EXTEND-MIB::nsExtendOutput1Line."networktrafficsent" = STRING: 5835.86
NET-SNMP-EXTEND-MIB::nsExtendOutputFull."networktraffic" = STRING: 12145.6
NET-SNMP-EXTEND-MIB::nsExtendOutputFull."networktrafficrcvd" = STRING: 6309.75
NET-SNMP-EXTEND-MIB::nsExtendOutputFull."networktrafficsent" = STRING: 5835.86
NET-SNMP-EXTEND-MIB::nsExtendOutNumLines."networktraffic" = INTEGER: 1
NET-SNMP-EXTEND-MIB::nsExtendOutNumLines."networktrafficrcvd" = INTEGER: 1
NET-SNMP-EXTEND-MIB::nsExtendOutNumLines."networktrafficsent" = INTEGER: 1
NET-SNMP-EXTEND-MIB::nsExtendResult."networktraffic" = INTEGER: 0
NET-SNMP-EXTEND-MIB::nsExtendResult."networktrafficrcvd" = INTEGER: 0
NET-SNMP-EXTEND-MIB::nsExtendResult."networktrafficsent" = INTEGER: 0
NET-SNMP-EXTEND-MIB::nsExtendOutLine."networktraffic".1 = STRING: 12145.6
NET-SNMP-EXTEND-MIB::nsExtendOutLine."networktrafficrcvd".1 = STRING: 6309.75
NET-SNMP-EXTEND-MIB::nsExtendOutLine."networktrafficsent".1 = STRING: 5835.86








Windows Active Directory Search Library in Java

Hello Every one.

I was updating my Java library for Active directory Searching because of Microsoft Lync server integration with the in-housed belling system. because there is some attributes that you cant get from Lync monitoring server and you need to get it from active directory. and I want to share it with everybody

1.  I created an Enum so i don't bother my self to know which attribute represents what, and not to bother my self regarding case sensitivity below is the Enum

DBName : represents Database fields names
ADName: represents Active directory Attributes names


/**
* Created by Saddam Abu Ghaida
* @author sghaida
*
*/

public enum LDAPAtributesEnum {
    login       ("login",                           "sAMAccountName"),
    email       ("email",                           "mail"),
    first_name ("first_name",                   "givenName"),
    last_name   ("last_name",                    "sn"),
    title              ("title",                               "description"),
    dept       ("dept",                             "department"),
    company              ("company",                       "company"),
    employee_id ("employee_id", "employeeID"),
    location   ("location",                         "l"),
    country ("country", "c"),
    ext                       ("ext",                                "extensionAttribute1"),
    home_tel   ("home_tel",                      "homePhone"),
    home_addr   ("home_addr",                  "streetAddress"),
    emp_id                ("emp_id",                         "employeeID"),
    sip_account ("sip_account",         "msRTCSIP-PrimaryUserAddress"),
    sip_extention ("sip_extention",                 "msRTCSIP-Line"),
    sip_gateway ("sip_gateway",         "msRTCSIP-PrimaryHomeServer"),
    gateway_hostname("gateway_hostname",      "dNSHostName"),
 
    public final String ADName;
    public final String DBName;
 
    LDAPAtributesEnum(String DBName,String ADName) {
this.ADName = ADName;
this.DBName = DBName;
}

}

2.  now the fun part this class will do everything related to search

Note: I'm using GXT BaseModels as a structured output "serialized" because I am writing BaseModels to database directly, but you can customize the output the way you like. if there is some ambiguity in the code. don't hesitate  to comment and i will be more that happy to replay.

in order to be able to run this library in the current shap you need the following

1. GXT-2.2.4-GWT[xx].JAR
2. GWT-SERVLET.JAR
3. JNDI.JAR
4. LDAP.JAR


/**
* Created by Saddam Abu Ghaida
* @author sghaida
*
*/


import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import javax.security.cert.CertificateException;

import com.extjs.gxt.ui.client.data.BaseModel;

public class ADLib {
   
     /**
     * @param args
     */
   
     @SuppressWarnings("unchecked")
     static     Hashtable<String, String> envGC = new Hashtable();

     static String adminName;
     static String adminPassword;
     static String urlGC;

     static LdapContext ctxGC;

     private String searchBase = "";
     private String searchFilter = "";
   
     String returnedAtts[]={
    "cn",
    "sn",
    "givenName",
    "sAMAccountName",
    "mail","distinguishedName",
    "msRTCSIP-PrimaryUserAddress",
    "msRTCSIP-Line","msRTCSIP-PrimaryHomeServer"};

     private boolean DEBUG=true;
   

     /**
     *
     * @param searchBase search base, e.g. "dc=example,dc=com";
     * @param ADHostName  Host name or IP address of AD Server
     * @param user Username to connect to AD server
     * @param password Password to connecto AD server
     * @throws NamingException
     */
     public ADLib(String searchBase, String ADHostName, String user, String password) throws NamingException
     {
         
           //get AD properties
           this.searchBase = searchBase;
           urlGC = "ldap://" + ADHostName+ ":3268";
           adminName = user;
           adminPassword = password;
         
           envGC.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
           envGC.put(Context.SECURITY_AUTHENTICATION,"simple");
           envGC.put("java.naming.ldap.attributes.binary","userCertificate");
           envGC.put(Context.SECURITY_PRINCIPAL,adminName);
           envGC.put(Context.SECURITY_CREDENTIALS,adminPassword);
          //connect to both a GC
           envGC.put(Context.PROVIDER_URL,urlGC);
       
           //Create the initial directory context for both DC and GC
           ctxGC = new InitialLdapContext(envGC,null);
     }
   
     /**
     * @param name
     * @return list<BaseModel>
     * @throws NamingException
     */
     public List<BaseModel> searchResults(String searchFilter ) throws NamingException
     {
           //Create the search controls      
           SearchControls searchCtls = new SearchControls();
         
           //Specify the attributes to return
           searchCtls.setReturningAttributes(returnedAtts);
               
           //Specify the search scope
           searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
       
           //initialize counter to total the results
           int totalResults = 0;
         
           //Search for objects in the GC using the filter
           NamingEnumeration answer = ctxGC.search(searchBase, searchFilter, searchCtls);
       
           List<BaseModel> results = new ArrayList<BaseModel>();
         
           while (answer.hasMoreElements()) {
             
                SearchResult sr = (SearchResult)answer.next();
                totalResults++;
             
                // Print out some of the attributes, catch the exception if the attributes have no values
             
                Attributes attrs = sr.getAttributes();
                if (attrs != null) {
                     try {
                         
                           NamingEnumeration allAtributes = attrs.getAll();
                           BaseModel bm = new BaseModel();
                           Attribute a;
                         
                           if(DEBUG)System.out.println("-----------------------------------");
                           if(allAtributes != null && allAtributes.hasMore()){
                                while(allAtributes.hasMore()){
                                     a = (Attribute)allAtributes.next();
                                     String name = a.getID();
                                     Object value = a.get();
                                   
                                     if(name.equals("msRTCSIP-Line") && !value.equals(null))
                                         value = ((String)value).replaceAll("tel:", "");
                         
                                     if (name.equals("msRTCSIP-PrimaryUserAddress") && !value.equals(null))
                                    value = ((String)value).replaceAll("sip:", "");
                                   
                                     if (name.equals("msRTCSIP-PrimaryHomeServer") && !value.equals(null))
                                        value = ((String)value).replaceAll("CN=Lc Services,CN=Microsoft,", "");                      
                                                                       
                                     bm.set(name, value);
                                   
                                     String s = "";
                                     try{
                                           if(value!=null && value instanceof String)
                                                s = (String)value;
                                     }catch (Exception e) {
                                           e.printStackTrace();
                                     }
                                     if(DEBUG)System.out.println(name+" = "+s.replaceAll("\\p{Cntrl}", ""));
                                }
                           }
                         
                           results.add(bm);
                     }
                     catch (NullPointerException e)  {
                           System.err.println("Problem listing attributes from Global Catalog: " + e);
                           e.printStackTrace();
                     }
             
                }
   
           }
           ctxGC.close();
           return results;
         
     }
     /**
      * gets LDAP SearchBase for ldap query
      * @return LDAP search base
      */
     public String getSearchBase() {
           return searchBase;
     }

     /**
      * Sets LDAP SearchBase for ldap query
      * @param searchBase
      */
     public void setSearchBase(String searchBase) {
           this.searchBase = searchBase;
     }
   
     /**
      * gets search filter to be used in querying LDAP
      * @return
      */
     public String getSearchFiltter()
     {
    return searchFilter;
     }
   
     /**
      * sets the search filter to be used in querying LDAP
      * @param searchFilter
      */
     public void setSearchFilter(String searchFilter)
     {
    this.searchFilter = searchFilter;
     }

     public boolean isDebug() {
           return DEBUG;
     }

     public void setDebug(boolean debug) {
           this.DEBUG = debug;
     }


     /**
      * Sets the LDAP attributes to be returned to user
      * @return
      */
     public String[] getReturnedAtts() {
           return returnedAtts;
     }

     /**
      * returns the LYNC server hostname/Gateway which is associated with the sip account
      * @param gateway
      * @return
      * @throws NamingException
      */
     public String getGateway(Object gateway) throws NamingException
     {
    String searchFilter = "(distinguishedName=" + ((String)gateway).replaceAll("CN=Lc Services,CN=Microsoft,", "") + ")";      
         String attributes[] = {"dNSHostName"};
         setSearchBase("DC=ccg,DC=resource");
         setReturnedAtts(attributes);
         return searchResults(searchFilter).get(0).get("dNSHostName");
   
     }
   
     /**
      *
      * @param sipAccount
      * @return
      */
     public String getSipAccount(Object sipAccount)
     {
    return ((String)sipAccount).replaceAll("sip:", "");
     }
   
     /**
      *
      * @param sipExtention
      * @return
      */
     public String getSipExtention(Object sipExtention)
     {
    return ((String)sipExtention).replaceAll("tel:", "");
     }
   
     /**
     * Set which attributes to return from the query
     * @param returnedAtts array of attribute names, e.g. {"cn","sn","givenName","sAMAccountName","mail","distinguishedName"}.
     * Set to null to return all of the attributes
     */
     public void setReturnedAtts(String[] returnedAtts) {
           this.returnedAtts = returnedAtts;
     }

     /**
     * @param args
     * @throws CertificateException
     * @throws NamingException
     */
    public static void main(String[] args) throws CertificateException, NamingException {
         
         
           ADLib connector = new ADLib("dc=example,dc=com", "1.1.1.1", "CN=sghaida, CN=Users, DC=example, DC=com", "xxxxxxx");
       
           //specify the LDAP search filter
           connector.setSearchBase("dc=example,dc=com");
         
           //String searchFilter = "(&(&(objectClass=user)(!(objectClass=contact)))(!(objectClass=computer)))";
           String searchFilter = "(&(objectClass=msRTCSIP-Pool)(cn=1:1))";
           String attributes[]={LDAPAtributesEnum.gateway_hostname.ADName};
           connector.setReturnedAtts(attributes);
           //String attributes[]={LDAPAtributesEnum.first_name.ADName, LDAPAtributesEnum.last_name.ADName, "mail",LDAPAtributesEnum.dept.ADName};
           List<BaseModel> results = connector.searchResults(searchFilter);
       
     }

}








Wednesday, September 7, 2011

IStorage

I was doing some development for AD RMS, which is creating a dll for 3d party applications to be able to use AD RMS features, i was doing it based on AD RMS SDK. so i had a lot of problems with Windows cryptic C/C++, but i managed around. for me it was the first time I used VC++ for something very complicated like AD RMS development.

During my development I stumbled upon one function. and the function is


WINOLEAPI StgCreateStorageEx(
  __in   const WCHAR *pwcsName,
  __in   DWORD grfMode,
  __in   STGFMT stgfmt,
  __in   DWORD grfAttrs,
  __in   STGOPTIONS *pStgOptions,
  __in   PSECURITY_DESCRIPTOR *pSecurityDescriptor,
  __in   REFIID riid,
  __out  void **ppObjectOpen
);
and the funny thing about it  is the last parameter description. And quoting from Microsoft 
"ppObjectOpen [out] A pointer to an interface pointer variable that receives a pointer for an interface on the new storage object; contains NULL if operation failed."
I wonder why Microsoft stopped speaking English any more. and for the same reason I prefer to develop under Unix/Linux platforms where there is no terms like the mentioned above and every thing is understandable, and organized 




DHCP and BIND dynamic updates

i want to share with you how to configure DHCP dynamic updates .
first you need to create key , either by using rndc-confgen or dnssec-keygen , it will give you the same results
you need only the following attributes form the result : algorithm and secret ,
in the dhcp server edit /etc/dhcpd.conf  and add the following

in global config add :


ddns-update-style interim;
ddns-updates on;
ddns-ttl 1800;
ignore client-updates;


key "keyname" {
       algorithm hmac-md5;
       secret "T7AUeDuMo7ZadiUz1VRB1w==";
};

in scope configuration add the following


option domain-name "xxx.yyy";
option domain-name-servers 1.1.1.1,2.2.2.2;
option ntp-servers 10.1.46.50;
zone xxx.yyy. { primary 127.0.0.1; key keyname; }
zone 1.1.1.in-addr.arpa. { primary 127.0.0.1;key  keyname; }

and from the DNS part add the following to named.conf in the global configuration area, taking into consideration that it is the same key has been added to DHCP configuration


key "keyname" {
        algorithm hmac-md5;
        secret "T7AUeDuMo7ZadiUz1VRB1w==";
};

and for every zone you wish the DHCP server to update add the following
allow-update { key keyname; };

Notes :

1. if the DHCP and BIND located in the same server. you better allow update only through loopback interface
2. dhcpd user should have a write access to zones directory and it could be done by using setfacl

NTP client for Linux VM on ESX server

i had a problem long time ago with Linux VMs on ESX host, and one of the problems is NTP sync

so the solution for who he still has the issue is the following
edit /boot/grub/menu.lst or /boot/grub/grub.conf and append the following to the kernel line:clocksource=acpi_pm clock=pits 
and it will work like charm .

SSH connectivity library

Hello again

this library has been written to help accessing Unix\ Linux servers with private key. it needs  ganymed-ssh2-build210.jar to work


package lib;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

public class SSHLib
{
       static String sshPrivateKey;
static Connection conn = null;
static Session session = null;
       static String sshUsername;
String output ="";


       public SSHLib() throws IOException
{
init();
}
 
       private void init() throws IOException{
char privateKeyChar[] = sshPrivateKey.toCharArray();

conn = new Connection(ftpHostname,22);
conn.connect();

boolean isAuthenticated = conn.authenticateWithPublicKey(sshUsername, privateKeyChar, null);
if (isAuthenticated == false)
throw new IOException("Authentication failed.");

session = conn.openSession();
}
       
        public String excuteCMD(String cmd) throws IOException
{
session = conn.openSession();
session.execCommand(cmd);
InputStream stdout = new StreamGobbler(session.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));

while (true)
{

String line = br.readLine();
if (line == null)
break;
else
output+=line;
}

return output;
}

public Integer getExitStatus()
{
return session.getExitStatus();
}

        public void disconnect()
{
session.close();
conn.close();
}

        public String getSize(String ftpAccount , String path) throws IOException {

return excuteCMD("du -sh " + path + "|" + "awk '{print $1}'" );
}

        public void deleteFolder(String path) throws IOException{

excuteCMD("rm -rf " + path);
}

       public static void main(String[] args) throws IOException {

SSHLib ssh = new SSHLib();
Integer x = ssh.getExitStatus();
//System.out.println("exit status :" + x);
System.out.println(ssh.getSize(null, "/home/"));
ssh.disconnect();
}
       

}

Monday, September 5, 2011

Definition of emotions

recently something happened to me , which made we ask my self again what is emotions, what is the definition of such a word, have human created this kind of phrases to close some vocabulary gaps, or they put it there so it could be defined later on.

i asked my self this question long time ago , and i thought the answer that i had is convincing at least for me . And here is my definition

 a collective of emotions represented by actions, interpretation of those actions defers form one human being to another human being, and this thing making me confused big time . come on there is no standards. why every thing in life has a standards, and emotions has non, and the answer its is ; emotions which is  a deferent level of being, and the language of this being is not understandable by mind, so mind tries to simplify this language understanding to specific set of reactions represents the phenomena of the emotions, which defers based on your mind maturity, and this is why actions defers from one and another, but this is not my problem.

my problem is . Why the representation of that emotions when it is communicated by mind language is not understood.  Could it be because i have a problem regarding expressing my self ?? no. could it be because the opposing one is not intellectually mature enough to understand ?? Maybe. in this case how could you express your reactions for less intellectual being. Could it be because i have problem in the definition, and i inducted wrong results ?? Maybe.

But i believe that i sacrificed a lot for selfish people out of my emotional structure, and they always ask for more, without understanding if there is more without giving compromises from their part, and actually they don't care, they are pretty convinced that "more" should be provided as an emotional obligation, otherwise your are condiment by their intellectual reactions, and you should understand.

it seems that the previous paragraph is so complicated even i couldn't understand it. Funny isn't it ??
i hope that emotional structure is a solid mathematical structure so it could be understood. but this is just a hope that i don't want to see it comes true. because people will stop caring about emotions and start searching for something new like Zara who dropped every thing and starting building from scratch once again

and now emotions for me is just a word "i feel so and so ", and the replay is either confirmation or negation

 

  

IP and Subnetting Java Library

its been a while since i posted any thing , and since AD RMS development eats my time, I decided to post and old library I created in Java for IP related calculations. I created this library because I wanted to manage subnets creation , IPs assignments, .... etc. , and i couldn't find any opensource library out there to this very simple task

below is the Source code for this class, I've done this library with the help of my friend Nicolai Tufar, i hope that somebody will find it useful. without blabbering too much check the following source code and if any body has a question don't hesitate to contact me.


/*
Copyright (c) 2010, Saddam Abu Ghaida, Nicolai Tufar
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
 * Neither the name of the Saddam Abu Ghaida or Nicolai Tufar nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Saddam Abu Ghaida or Nicolai Tufar BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package com.tufar.IPCalculator.client;

import java.util.ArrayList;
import java.util.List;

public class IPv4 {
int baseIPnumeric;
int netmaskNumeric;

/**
* Specify IP address and netmask like: new
* IPv4("10.1.0.25","255.255.255.16")
*
* @param symbolicIP
* @param netmask
*/
public IPv4(String symbolicIP, String netmask) throws NumberFormatException {

/* IP */
String[] st = symbolicIP.split("\\.");

if (st.length != 4)
throw new NumberFormatException("Invalid IP address: " + symbolicIP);

int i = 24;
baseIPnumeric = 0;

for (int n = 0; n < st.length; n++) {

int value = Integer.parseInt(st[n]);

if (value != (value & 0xff)) {

throw new NumberFormatException("Invalid IP address: "
+ symbolicIP);
}

baseIPnumeric += value << i;
i -= 8;

}

/* Netmask */
st = netmask.split("\\.");

if (st.length != 4)
throw new NumberFormatException("Invalid netmask address: "

+ netmask);

i = 24;
netmaskNumeric = 0;

if (Integer.parseInt(st[0]) < 255) {

throw new NumberFormatException(
"The first byte of netmask can not be less than 255");
}
for (int n = 0; n < st.length; n++) {

int value = Integer.parseInt(st[n]);

if (value != (value & 0xff)) {

throw new NumberFormatException("Invalid netmask address: "
+ netmask);
}

netmaskNumeric += value << i;
i -= 8;

}

/*
* see if there are zeroes inside netmask, like: 1111111101111 This is
* illegal, throw exception if encountered. Netmask should always have
* only ones, then only zeroes, like: 11111111110000
*/
boolean encounteredOne = false;
int ourMaskBitPattern = 1;

for (i = 0; i < 32; i++) {

if ((netmaskNumeric & ourMaskBitPattern) != 0) {

encounteredOne = true; // the bit is 1
} else { // the bit is 0
if (encounteredOne == true)

throw new NumberFormatException("Invalid netmask: "
+ netmask + " (bit " + (i + 1) + ")");

}

ourMaskBitPattern = ourMaskBitPattern << 1;
}

}

/**
* Specify IP in CIDR format like: new IPv4("10.1.0.25/16");
*
* @param IPinCIDRFormat
*/
public IPv4(String IPinCIDRFormat) throws NumberFormatException {

String[] st = IPinCIDRFormat.split("\\/");
if (st.length != 2)

throw new NumberFormatException("Invalid CIDR format '"
+ IPinCIDRFormat + "', should be: xx.xx.xx.xx/xx");

String symbolicIP = st[0];
String symbolicCIDR = st[1];

Integer numericCIDR = new Integer(symbolicCIDR);
if (numericCIDR > 32)

throw new NumberFormatException("CIDR can not be greater than 32");

/* IP */
st = symbolicIP.split("\\.");

if (st.length != 4)
throw new NumberFormatException("Invalid IP address: " + symbolicIP);

int i = 24;
baseIPnumeric = 0;

for (int n = 0; n < st.length; n++) {

int value = Integer.parseInt(st[n]);

if (value != (value & 0xff)) {

throw new NumberFormatException("Invalid IP address: "
+ symbolicIP);
}

baseIPnumeric += value << i;
i -= 8;

}

/* netmask from CIDR */
if (numericCIDR < 8)
throw new NumberFormatException(

"Netmask CIDR can not be less than 8");
netmaskNumeric = 0xffffffff;
netmaskNumeric = netmaskNumeric << (32 - numericCIDR);

}

/**
* Get the IP in symbolic form, i.e. xxx.xxx.xxx.xxx
*
* @return
*/
public String getIP() {
return convertNumericIpToSymbolic(baseIPnumeric);

}

private String convertNumericIpToSymbolic(Integer ip) {
StringBuffer sb = new StringBuffer(15);

for (int shift = 24; shift > 0; shift -= 8) {

// process 3 bytes, from high order byte down.
sb.append(Integer.toString((ip >>> shift) & 0xff));

sb.append('.');
}
sb.append(Integer.toString(ip & 0xff));

return sb.toString();
}

/**
* Get the net mask in symbolic form, i.e. xxx.xxx.xxx.xxx
*
* @return
*/

public String getNetmask() {
StringBuffer sb = new StringBuffer(15);

for (int shift = 24; shift > 0; shift -= 8) {

// process 3 bytes, from high order byte down.
sb.append(Integer.toString((netmaskNumeric >>> shift) & 0xff));

sb.append('.');
}
sb.append(Integer.toString(netmaskNumeric & 0xff));

return sb.toString();
}

/**
* Get the IP and netmask in CIDR form, i.e. xxx.xxx.xxx.xxx/xx
*
* @return
*/

public String getCIDR() {
int i;
for (i = 0; i < 32; i++) {

if ((netmaskNumeric << i) == 0)
break;

}
return convertNumericIpToSymbolic(baseIPnumeric & netmaskNumeric) + "/"

+ i;
}

/**
* Get an arry of all the IP addresses available for the IP and netmask/CIDR
* given at initialization
*
* @return
*/
public List<String> getAvailableIPs(Integer numberofIPs) {

ArrayList<String> result = new ArrayList<String>();
int numberOfBits;

for (numberOfBits = 0; numberOfBits < 32; numberOfBits++) {

if ((netmaskNumeric << numberOfBits) == 0)
break;

}
Integer numberOfIPs = 0;
for (int n = 0; n < (32 - numberOfBits); n++) {

numberOfIPs = numberOfIPs << 1;
numberOfIPs = numberOfIPs | 0x01;

}

Integer baseIP = baseIPnumeric & netmaskNumeric;

for (int i = 1; i < (numberOfIPs) && i < numberofIPs; i++) {

Integer ourIP = baseIP + i;

String ip = convertNumericIpToSymbolic(ourIP);

result.add(ip);
}

return result;

}

/**
* Range of hosts
*
* @return
*/
public String getHostAddressRange() {

int numberOfBits;
for (numberOfBits = 0; numberOfBits < 32; numberOfBits++) {

if ((netmaskNumeric << numberOfBits) == 0)
break;

}
Integer numberOfIPs = 0;
for (int n = 0; n < (32 - numberOfBits); n++) {

numberOfIPs = numberOfIPs << 1;
numberOfIPs = numberOfIPs | 0x01;

}

Integer baseIP = baseIPnumeric & netmaskNumeric;
String firstIP = convertNumericIpToSymbolic(baseIP + 1);

String lastIP = convertNumericIpToSymbolic(baseIP + numberOfIPs - 1);

return firstIP + " - " + lastIP;
}

/**
* Returns number of hosts available in given range
*
* @return number of hosts
*/
public Long getNumberOfHosts() {
int numberOfBits;

for (numberOfBits = 0; numberOfBits < 32; numberOfBits++) {

if ((netmaskNumeric << numberOfBits) == 0)
break;

}

Double x = Math.pow(2, (32 - numberOfBits));

if (x == -1)
x = 1D;

return x.longValue();
}

/**
* The XOR of the netmask
*
* @return wildcard mask in text form, i.e. 0.0.15.255
*/

public String getWildcardMask() {
Integer wildcardMask = netmaskNumeric ^ 0xffffffff;

StringBuffer sb = new StringBuffer(15);
for (int shift = 24; shift > 0; shift -= 8) {

// process 3 bytes, from high order byte down.
sb.append(Integer.toString((wildcardMask >>> shift) & 0xff));

sb.append('.');
}
sb.append(Integer.toString(wildcardMask & 0xff));

return sb.toString();

}

public String getBroadcastAddress() {

if (netmaskNumeric == 0xffffffff)
return "0.0.0.0";

int numberOfBits;
for (numberOfBits = 0; numberOfBits < 32; numberOfBits++) {

if ((netmaskNumeric << numberOfBits) == 0)
break;

}
Integer numberOfIPs = 0;
for (int n = 0; n < (32 - numberOfBits); n++) {

numberOfIPs = numberOfIPs << 1;
numberOfIPs = numberOfIPs | 0x01;

}

Integer baseIP = baseIPnumeric & netmaskNumeric;
Integer ourIP = baseIP + numberOfIPs;

String ip = convertNumericIpToSymbolic(ourIP);

return ip;

}

private String getBinary(Integer number) {
String result = "";

Integer ourMaskBitPattern = 1;
for (int i = 1; i <= 32; i++) {

if ((number & ourMaskBitPattern) != 0) {

result = "1" + result; // the bit is 1
} else { // the bit is 0

result = "0" + result;
}
if ((i % 8) == 0 && i != 0 && i != 32)

result = "." + result;
ourMaskBitPattern = ourMaskBitPattern << 1;

}
return result;
}

public String getNetmaskInBinary() {

return getBinary(netmaskNumeric);
}

/**
* Checks if the given IP address contains in subnet
*
* @param IPaddress
* @return
*/
public boolean contains(String IPaddress) {

Integer checkingIP = 0;
String[] st = IPaddress.split("\\.");

if (st.length != 4)
throw new NumberFormatException("Invalid IP address: " + IPaddress);

int i = 24;
for (int n = 0; n < st.length; n++) {

int value = Integer.parseInt(st[n]);

if (value != (value & 0xff)) {

throw new NumberFormatException("Invalid IP address: "
+ IPaddress);
}

checkingIP += value << i;
i -= 8;

}

if ((baseIPnumeric & netmaskNumeric) == (checkingIP & netmaskNumeric))

return true;
else
return false;
}

public boolean contains(IPv4 child) {

Integer subnetID = child.baseIPnumeric;

Integer subnetMask = child.netmaskNumeric;

if ((subnetID & this.netmaskNumeric) == (this.baseIPnumeric & this.netmaskNumeric)) {

if ((this.netmaskNumeric < subnetMask) == true
&& this.baseIPnumeric <= subnetID) {

return true;
}

}
return false;

}

public boolean validateIPAddress() {
String IPAddress = getIP();

if (IPAddress.startsWith("0")) {
return false;

}

if (IPAddress.isEmpty()) {

return false;
}

if (IPAddress
.matches("\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z")) {

return true;
}
return false;
}

/**
* @param args
*/
/**
* @param args
*/
public static void main(String[] args) {

// ipv4.setIP("10.20.30.5", "255.255.255.200");
// System.out.println(ipv4.getIP());
// System.out.println(ipv4.getNetmask());
// System.out.println(ipv4.getCIDR());

/*
* IPv4 ipv4 = new IPv4("10.1.17.0/20");
* System.out.println(ipv4.getIP());
* System.out.println(ipv4.getNetmask());
* System.out.println(ipv4.getCIDR());
*
* System.out.println("============= Available IPs ===============");
* List<String> availableIPs = ipv4.getAvailableIPs(); int counter=0;
* for (String ip : availableIPs) { System.out.print(ip);
* System.out.print(" "); counter++; if((counter%10)==0)
* System.out.print("\n"); }
*/

IPv4 ipv4 = new IPv4("12.12.12.0/16");

IPv4 ipv4Child = new IPv4("12.12.12.0/17");
// IPv4 ipv4 = new IPv4("192.168.20.0/16");
// System.out.println(ipv4.getIP());
// System.out.println(ipv4.getNetmask());

// System.out.println(ipv4.getCIDR());
// System.out.println("======= MATCHES =======");
// System.out.println(ipv4.getBinary(ipv4.baseIPnumeric));
// System.out.println(ipv4.getBinary(ipv4.netmaskNumeric));

System.out.println(ipv4.contains(ipv4Child));

System.out.println(ipv4.getBinary(ipv4.baseIPnumeric));
System.out.println(ipv4.getBinary(ipv4.netmaskNumeric));

System.out.println(ipv4Child.getBinary(ipv4Child.baseIPnumeric));

System.out.println(ipv4Child.getBinary(ipv4Child.netmaskNumeric));

System.out.println("==============output================");
System.out.println(ipv4.contains(ipv4Child));

// ipv4.contains("192.168.50.11");
// System.out.println("======= DOES NOT MATCH =======");
// ipv4.contains("10.2.3.4");
// System.out.println(ipv4.validateIPAddress());
// System.out.println(ipv4.getBinary(ipv4.baseIPnumeric));
// System.out.println(ipv4.getBinary(ipv4.netmaskNumeric));
}

}