Monday, September 23, 2013

const char * vs char * const

I came across the question 'What is the difference between const char * vs char * const many times. After trying several sample programs, here is a simple way to understand the differences. Let us see what char * means:
char * p; // defines a buffer where characters can be stored
          // returns a pointer that is pointing to the first element in the buffer and is denoted by p

When const is applied on char *, depending on the position of const,
different things happen on the buffer+pointer.
const char * p ->  buffer contents are a constant. Pointer variable p can be modified to point to a different buffer.
char * const p ->  buffer contents can be modified. Pointer variable p cannot be modified. p points to the same location, all the time.
const char * const p -> means that the buffer and the pointer cannot be modified

Summary:
DefinitionBufferPointer
const char * pCannot changeCan change
char * const pCan changeCannot change
const char * const pCannot changeCannot change

Saturday, September 14, 2013

Linux Commands

A list of Linux commands

How ToCommands
Disable Firewall $ service iptables stop # stops firewall $ chkconfig iptables off # disables firewall $ service iptables status # status of firewall

Friday, September 13, 2013

Renew IP Address

When computers are moved from one network to another network, its IP address changes. This change is not reflected immediately in network adapters. In order to force a reset of these adapters, the following commands are used.
Renew IP Address

Windows
1. Open a cmd prompt in elevated mode
2. Execute the command
    c:\windows\system32> ipconfig /renew


Linux
1. Open a Terminal as root
2. Execute the command
    $ ifconfig eth0 down
    $ ifconfig eth0 up

Thursday, August 29, 2013

Schema conversion - AUTO_INCREMENT (MySQL) and SEQUENCE (PostgreSQL)

Auto increment is achieved in MySQL using the keyword AUTO_INCREMENT. It is achieved in PostgreSQL using a SEQUENCE statement. Consider the following problem: Create a table with a field, to auto increment starting with the value 5.

MySQL
CREATE TABLE hello (
    idHello int NOT NULL AUTO_INCREMENT
) AUTO_INCREMENT=5;


PostgreSQL
CREATE SEQUENCE hello_idHello_sequence START 5;
CREATE TABLE hello (
    idHello integer NOT NULL DEFAULT nextval('hello_idHello_sequence')
);
ALTER SEQUENCE hello_idHello_sequence OWNED BY hello.idHello;

Friday, August 16, 2013

Threat Modeling - STRIDE

While performing threat modeling on software, verify that every data item, end point crossing a boundary, open port etc are subject to the categorization defined by STRIDE. Each item under consideration may fall under more than one category.

STRIDE Definition

Spoofing User: Accessing and using a resource by masquerading as another user 
Tampering Data: Modifying data maliciously, so that the original data is unavailable and/or malicious                              data is introduced
Repudiation: Denying by a user or system, that an action has been performed by them
Information Disclosure: Disclosure of information to an unauthorized user or system
Denial of Service: Denying the Service to legitimate users or system
Elevation of Privilege: Unauthorized elevation of privileges by an unprivileged user

For more information, refer to Security Design by Threat Modeling



Sunday, August 11, 2013

Tomcat - Application System Error - Access is Denied

Application: Tomcat
OS: Windows
Error: Unable to open the service 'Tomcat7'

When you install Tomcat on a Windows machine, the following error is seen on rebooting the machine.


Reason: Tomcat7w.exe accesses resources that require administrator privileges.
Solutions: Configure Tomcat7w.exe to run as administrator. To configure Tomcat7w.exe run as administrator
    • Right-click on Tomcat7w.exe
    • Click on Properties
    • Click on Compatibility
    • Under Privilege Level, check the box 'Run this program as an administrator'
    • Click OK
    • Reboot the machine

Saturday, August 10, 2013

Programs for Windows Administration

This is a list of programs, that you can use for Windows administration.

  1. Computer Management: compmgmt.msc
  2. Component Services: comexp.msc 
  3. Event Viewer: eventvwr.exe 
  4. Local Security Policy: secpol.msc 
  5. ODBC Data Sources: odbcad32.exe
  6. Performance Monitor: perfmon.msc
  7. Print Management: printmanagement.msc
  8. Services: services.msc
  9. System Configuration: msconfig.exe 
  10. Task Scheduler:taskschd.msc
  11. Windows Firewall with Advanced Security: WF.msc 

Linux Commands

Here are some common Unix/Linux commands
  1. OS bitness 32 or 64: getconf KERNEL_BITS
  2. architecture of processor: file /usr/bin/w
  3. disk space usage: du
  4. enable backspace: stty erase hit_the_backspace_key
  5. split a vim screen vertically: Ctrl+wv
  6. list of open ports: netstat
  7. list of processes: ps
  8. rename a file: mv original_filename renamed_filename
  9. move a file: mv filepath/filename target_filepath/filename
  10. change permissions: chmod
  11. change owner: chown

Windows Batch Files - Common Tips

Lessons learnt while writing Windows Batch Scripts

  1. @echo off -> used as the first line in a batch script, to suppress the output of current command to console
  2. REM this is how a comment is made
  3. echo "this is how to print something to console"

Common Tools for Regular Use

I use a variety of tools during development. Here is a list of some of them. This list keeps growing as I use additional software.

  1. Beyond Compare: for file, folder comparison and file merge
  2. gVim: for file editing, comparison and merge
  3. WinMerge: file comparison and merge
  4. Application Verifier: runtime verification of c, c++ code on Windows
  5. Driver Verifier: Windows kernel mode driver runtime verifier
  6. WinDbg: debugging C and C++ code on Windows
  7. WireShark: network packet analysis and sniffing
  8. Maven: build, package
  9. Gradle: build, package, deploy
  10. Selenium: web site testing
  11. JUnit: framework for unit testing of Java code
  12. Fortify SCA: source code analysis
  13. Clover: code coverage for Java and Groovy code
  14. SonarQube: for trend analysis of various aspects in a project
  15. BlackDuck: open source software management
  16. VMWare Player: free virtual machine software
  17. psftp: sftp client
  18. putty: telnet client
  19. pscp: scp client
  20. tomcat: web server
  21. process explorer: Windows processes, open files, handles etc
  22. dependency finder: for finding dependencies in java code
  23. lattix: for finding dependencies in java/c/c++/.net/database code

Disclaimer: This is just a list of software that I used. I do not make any recommendations regarding the software that I listed here.

Java - Overriding hashCode() and equals()

Java provides a convenient way to calculate 'deep comparison' of objects via hashCode() and equals() methods. Every object has the default implementation for these methods. Deep comparison of objects can be implemented by overriding hashCode() and equals() methods. Several rules are defined by Java creators which we go through in the following sections. You can access these rules from Javadocs of Object.

Rules to override hashCode()

  1. Invocations of hashCode() should return the same value when fields of object do not change
  2. If two objects are equal based on equals() method, both the objects should return the same hashCode()
  3. It is not required that the hashCode() be dissimilar when two objects are not equal based on equals()

Rules to override equals()

  1. Reflexive: An object should be equal to itself: a.equals(a) is true
  2. Symmetric: If an object is equal to another object based on equals(), then these objects should be equal irrespective of which object's equal method is called: => if a.equals(b) is true then b.equals(a) is also true 
  3. Transitive: if two objects are equal based on equals(), then these objects are equal to any other objects that are equal to any of these objects: if a.equals(b) is true and b.equals(c) is true, then a.equals(c) is true
  4. Consistent: multiple invocations of equals() on objects should return the same value, if the underlying values used to check equality are not modified
  5. Equality check with null is false 

Example: Consider the following class that contains an int and the way hashCode() and equals() are overridden.

    class A
    {
        int x;
        public int setX(int x);
        {
            this.x = x;
        }
        public int getX()
        {
            return this.x;
        }
        public int hashCode()
        {
            return x;
        }
        public int equals(Object object)
        {
            boolean isEqual = true;
            if(object == null)
            {
                isEqual = false;
            }
            else if(Class.forName(object) != this.class))
            {
                isEqual = false;
            }
            else
            { 
                A compareObject = (A) object;
                if(this.x != compareObject.x)
                {
                    isEqual = false;
                }
            }
            return isEqual;
        }
    }

Verify that the rules for hashCode() and equals() are satisfied: Example:

A a,b,c,d;
a.setX(5);
b.setX(5);
c.setX(5);
d.setX(6);

Rules for hashCode():
  1. a.hashCode() will always return 5
  2. a.equals(b) is true. also, a.hashCode() and b.hashCode() return 5
  3. a.equals(d) is false (5 != 6). though a.hashCode() can be same as d.hashCode(), in our implementation they are different

Rules for equals():
  1. a.equals(a) will always return true
  2. a.equals(b) is true and b.equals(a) is true
  3. a.equals(b) is true and b.equals(c) is true and c.equals(a) is also true
  4. a.equals(b) is true as long as the 'x' value of the objects is not changed
  5. a.equals(null) is false

Sunday, July 21, 2013

Popular git commands

Git is a distributed version control and source code management system. Some popular git commands that we use are

git clone 
git push heroku master
git add &ltfilename&gt
git commit -m "description message"
git config --global user.name "&ltusername&gt"
git config --global user.email "&ltemail&gt"
git push origin master

Saturday, July 20, 2013

Maven Fortify Plugin

Fortify provides the source code to create a plugin for Maven. The GAV co-ordinates for maven fortify plugin are

<groupId>com.fortify.ps.maven.plugin</groupId>
<artifactId>sca-maven-plugin</artifactId>
<version>3.90</version>
To install Fortify maven plugin and run Fortify SCA in a Maven build, perform the following

1. Copy the folder %FORTIFY_INSTALLATION_DIRECTORY%\HP_FORTIFY\HP_Fortify_SCA_and_Apps_3.90\Samples\advanced\maven-plugin to c:\temp
2. Open a cmd prompt and change directory to c:\temp\maven-plugin
3. Execute the following command. This compiles the maven-plugin and adds maven plugin to local repository
mvn clean package install
4. Change directory to your project folder on which you want to run Fortify 5. Execute the following commands
mvn com.fortify.ps.maven.plugin:sca-maven-plugin:3.90:clean
mvn com.fortify.ps.maven.plugin:sca-maven-plugin:3.90:translate -Dfortify.sca.verbose=true -Dfortify.sca.debug=true
mvn com.fortify.ps.maven.plugin:sca-maven-plugin:3.90:scan -Dfortify.sca.verbose=true -Dfortify.sca.debug=true
6. Search for .fpr in the project directory for Fortify SCA report

Windows - Auto Logon

In order to perform auto-logon in Windows
1. Create a batch file with the following content

set autologon_username=
set autologon_password=
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /f /v AutoAdminLogon /t REG_SZ /d 1
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /f /v DefaultUserName /t REG_SZ /d %autologon_username%
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /f /v DefaultUserName /t REG_SZ /d %autologon_password%

2. Execute the batch file in an elevated mode
On rebooting the machine, you should be able to logon automatically to the user account specified with .
Note:Revealing password in plain text is a bad idea. Use this feature cautiously because you are exposing the plain text password.

Windows - Reboot from cmd

In order to reboot from the cmd prompt in Windows, execute the following command. Make sure you saved all open files before executing this command.

shutdown -r

Tomcat Version

Here is a way to find the version of Tomcat installation. Run the following in your command prompt

java -classpath %CATALINA_HOME%\server\lib\catalina.jar org.apache.catalina.util.ServerInfo

PowerPoint Tip - Dark or White Screen

While presenting using PowerPoint slides, you can make the screen completely dark or completely white by using the following keys
b - to make the screen dark (when the room has lighting)
w - to make the screen white (when the room is dark)

Fortify SCA - Location of .fpr file

Fortify Source Code Analyzer creates the scan result file with an extension .fpr in

%LOCALAPPDATA%\Fortify\AWB-&ltversion&gt\&ltapplicationName&gt

C# - Constructing File Paths

When you want to construct file paths, use the following


String filename = "cmd.exe";
String fullpath = System.IO.Path.Combine (Environment.SystemDirectory, filename);
Console.WriteLine(fullpath);

Output:
C:\Windows\System32\cmd.exe

C# - Thread Safe Increment, Decrement

When incrementing or decrementing values such as ++i, --i in a multi-threaded program, use the methods from Thread class.

System.Threading.Interlocked.Increment(i);
System.Threading.Interlocked.Decrement(i);

PowerShell - PSCredential

You can find the usage of PowerShell PSCredential from my other blog post on MSDN http://blogs.msdn.com/b/koteshb/archive/2010/02/13/powershell-creating-a-pscredential-object.aspx

Java - New Line Separator


A string can be constructed to have new line as 
String string = "Hello" + "\n" + "World"; 

Output 

Hello
World

Instead of using "\n", a better way to get the new line is from the System class.
A new line separator is stored in the System class in a Properties object. 
The new line separator can be retrieved by the following line 

System.getProperty("line.separator");


Java - Exception Stack Trace

Stack traces are helpful when a Java application throws exception. When the Java application is running in a console, we see the trace in console window. In order to log the trace to a file, we have to capture the stack trace in such a way, so as to be able to print it with the structure in tact.  The following Java code snippet, converts a stack trace to String format that can be used to save it to a file.

public static String printStackTrace (Throwable throwable)
{
    final Writer writer = new StringWriter ();
    final PrintWriter printWriter = new PrintWriter (writer);
    throwable.printStackTrace (printWriter);
    return writer.ToString();
}