Thursday, March 31, 2011

run apps in the backgroun on Windows

create a runapps.bat file:

start/B while1
start/B printrdtsc 1

while1 is the name of a program; printrdtsc is also the name of another program. 1 is the argument for printrdtsc

Wednesday, March 30, 2011

How to run 100 apps

1. Using shell script, and run all the apps by background

#!/bin/bash
i=1
while [ $i -le 5 ]
do
    ./while1&
    (( i++ ))
done


2. Using fork and exec
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

#define TIMES 100
#define PROGRAM "./while1"

int main()
{
    int pid;
    int i;
    for(i = 0; i< TIMES; i++)
    {
    pid = fork();
    if(pid == -1)
    {
        fprintf(stderr, "fork() failed\n");
        exit(1);
    }
    else if(pid == 0)
    {
        // child process
        execv(PROGRAM, NULL);
    }
    else
    {
        // parent process
        // wait(0); //comment out this line, you only can fork 1 program
    }
    }
//    wait(0); // comment out this line if you want to this process to wait 100 while1 program
    return 1;
}

Friday, March 25, 2011

Settings for Vim on Linux or Mac

set nocompatible        " use vim defaults
set tabstop=8           " numbers of spaces of tab character
set shiftwidth=4        " numbers of spaces to (auto)indent
set showcmd             " display incomplete commands
set nobackup            " do not keep a backup file
set number              " show line numbers
set ignorecase          " ignore case when searching
set autoindent          " always set autoindenting on
set sm                  " show matching braces
syn on                  " syntax highlighing
set syn=auto            " syntax auto
set bkc=no

if has("autocmd")
         " Restore cursor position
         au BufReadPost * if line("'\"") > 0|if line("'\"") <= line("$")|exe(    "norm '\"")|else|exe "norm $"|endif|endif
endif

" Show line numbers
set number

" Make text wrap automatically at 70 columns
" when you type long lines
set textwidth=70

" Automatic indenting
set autoindent
set shiftwidth=4

" Buffer switching using Alt-Left/Right
" (or Command-Left/Right in Mac OS X)
:nnoremap <D-Right> :bnext<CR>
:nnoremap <M-Right> :bnext<CR>
:nnoremap <D-Left> :bprevious<CR>
:nnoremap <M-Left> :bprevious<CR>

Mac lock the screen, but you don't want to sleep the machine

Ctrl+Shift+Eject

rdtsc in Windows and Linux

Code in Windows, you have to compile it by VC++

#include <intrin.h>
unsigned __int64 rdtsc()
{
  return __rdtsc();
}


Code in Linux 

#include <stdint.h>
#include <stdio.h>

  __inline__ uint64_t rdtsc() {
    uint32_t lo, hi;
    __asm__ __volatile__ (      // serialize
    "xorl %%eax,%%eax \n        cpuid"
    ::: "%rax", "%rbx", "%rcx", "%rdx");
    /* We cannot use "=A", since this would use %rax on x86_64 */
    __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
    return (uint64_t)hi << 32 | lo;
  }
int main()
{
    printf("rdtsc is: %llu\n",rdtsc());
    return 1;
}

more detailed information: http://en.wikipedia.org/wiki/Time_Stamp_Counter

Another version in Linux:
/************ Record TSC to SMRAM offset 0xA9000 ****************/
movl $0xA9000, %ebx
rdtsc
movl %eax, (%ebx)
movl %edx, 4(%ebx)

unsigned int lo = *(unsigned int*)(0xA9000);
unsigned int hi = *(unsigned int*)(0xA9004);
unsigned long long beforeConfig = (unsigned long long)hi << 32 | lo;

Thursday, March 24, 2011

copy/paste from one file to another file in vim

if you open one file using: $vim file1, and open another file using: $vim file2
there is no way to copy the content from file1 to file2

but you could open two files by using on vim app, then you could do copy/paste

vim file1 file2
mark with ctrl+v and hit y to yank.
:n or :next to switch to the next file
p to paste
:prev and :previous will switch to the previous file.
you can also use :first and :last

IO/CMOS read/wirte in Windows

In Linux, it is easy to read/write to port, you could just write a user level program, and use function inb(), outb(); you don't need to do kernel operations.

But in Windows, you cannot directly access hardware by using user level program. You could write a device driver to do it, which is in kernel level.
Or you could use some tool to do this:

1. Download tool: read/write everything
http://jacky5488.myweb.hinet.net/

2. Open I/O Index/Data window.
Input 0x70 as index, and 0x71 as data, and it will display all the data in the CMOS. For example, you want to change the 125th = 0x7d byte in CMOS from 0x00 to 0x01, just go 125th byte, and change it.

Print out current time in C on Windows

  typedef struct _SYSTEMTIME {
       WORD wYear;
       WORD wMonth;
       WORD wDayOfWeek;
       WORD wDay;
       WORD wHour;
       WORD wMinute;
       WORD wSecond;
       WORD wMilliseconds;
    } SYSTEMTIME;

     #include <Windows.h>
     #include <stdio.h>

     void main()
     {
         SYSTEMTIME st;
         GetSystemTime(&st);
         printf("Year:%d\nMonth:%d\nDate:%d\nHour:%d\nMin:%d\nSecond:% d\n" ,st.wYear,st.wMonth,st.wDay,st.wHour,st.wMinute,st.wSecond);
     }


more info:
http://www.codersource.net/c/c-tutorials/c-date-and-time.aspx
 

shell script in Windows

create a bat file named run.bat
edit the run.bat
you could put command which windows could understand
E.g.
dir
cmd
measureSuspendTime.ext
psshutdown -d -t 0

Wednesday, March 23, 2011

Suspend Windows from command line by using systerm internals Pstool

http://technet.microsoft.com/en-us/sysinternals/bb897541

User MATLAB to setup the serial port

s=serial('COM8');
set(s,'BaudRate',9600);
fopen(s);

http://newsgroups.derkeiler.com/Archive/Comp/comp.soft-sys.matlab/2008-10/msg05119.html

Sysinternals Site

This is the download site for Windows sysinternals. E.g. Process Explore for process monitoring and PsTools for pm-suspend

http://technet.microsoft.com/en-us/sysinternals/bb545027

Tuesday, March 22, 2011

Serial Port Programming on Windows

Here is a sample code of serial port programming on Windows:
it compile and run at Dev C++, but you need to change CreateFile to CreateFileA on VC++ 2010 express

#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <commdlg.h>
#include <windef.h>

int nread,nwrite;

int main()
{
HANDLE hSerial;
COMMTIMEOUTS timeouts;
COMMCONFIG dcbSerialParams;
char *words, *buffRead, *buffWrite;
DWORD dwBytesWritten, dwBytesRead;
   
hSerial = CreateFile("COM1",
    GENERIC_READ | GENERIC_WRITE,
    0,
    NULL,
    OPEN_EXISTING,
    FILE_ATTRIBUTE_NORMAL,
    NULL);

if ( hSerial == INVALID_HANDLE_VALUE)
{
   if (GetLastError() == ERROR_FILE_NOT_FOUND)
   {
      printf(" serial port does not exist \n");
   }
   printf(" some other error occured. Inform user.\n");
}

//DCB dcbSerialParams ;
//GetCommState( hSerial, &dcbSerialParams.dcb);
if (!GetCommState(hSerial, &dcbSerialParams.dcb))
{
printf("error getting state \n");
}

dcbSerialParams.dcb.DCBlength = sizeof(dcbSerialParams.dcb);

dcbSerialParams.dcb.BaudRate = CBR_38400;
dcbSerialParams.dcb.ByteSize = 8;
dcbSerialParams.dcb.StopBits = TWOSTOPBITS;
dcbSerialParams.dcb.Parity = NOPARITY;

dcbSerialParams.dcb.fBinary = TRUE;
dcbSerialParams.dcb.fDtrControl = DTR_CONTROL_DISABLE;
dcbSerialParams.dcb.fRtsControl = RTS_CONTROL_DISABLE;
dcbSerialParams.dcb.fOutxCtsFlow = FALSE;
dcbSerialParams.dcb.fOutxDsrFlow = FALSE;
dcbSerialParams.dcb.fDsrSensitivity= FALSE;
dcbSerialParams.dcb.fAbortOnError = TRUE;

if (!SetCommState(hSerial, &dcbSerialParams.dcb))
{
printf(" error setting serial port state \n");
}

GetCommTimeouts(hSerial,&timeouts);
//COMMTIMEOUTS timeouts = {0};

timeouts.ReadIntervalTimeout = 50;
timeouts.ReadTotalTimeoutConstant = 50;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 50;
timeouts.WriteTotalTimeoutMultiplier= 10;

if(!SetCommTimeouts(hSerial, &timeouts))
{
printf("error setting port state \n");
}

//****************Write Operation*********************//
words = "This is a string to be written to serial port COM1";
nwrite = strlen(words);

buffWrite = words;
dwBytesWritten = 0;

if (!WriteFile(hSerial, buffWrite, nwrite, &dwBytesWritten, NULL))
{
printf("error writing to output buffer \n");
}
//printf("Data written to write buffer is \n %s \n",buffWrite);

//***************Read Operation******************//
/*
buffRead = 0;
dwBytesRead = 0;
nread = strlen(words);

if (!ReadFile(hSerial, buffRead, nread, &dwBytesRead, NULL))
{
printf("error reading from input buffer \n");
}
printf("Data read from read buffer is \n %s \n",buffRead);
*/

CloseHandle(hSerial);
system("pause");
return 1;
}

CreateFile vs CreateFileW , CreateFileA

This is the simple explaination:
CreateFileW (Unicode) and CreateFileA (ANSI)
both of them defined by CreateFile

If you want to understand CreateFile, go to msdn page(man page of win API):
http://msdn.microsoft.com/en-us/library/aa363858%28v=vs.85%29.aspx

Here is the link talk about the difference:
http://www.osronline.com/showThread.cfm?link=20658

Note: if you compile following code on Visual studio 2010 Express may have errors, just change CreateFile() to CreateFileA()

hSerial = CreateFile("COM1",
    GENERIC_READ | GENERIC_WRITE,
    0,
    NULL,
    OPEN_EXISTING,
    FILE_ATTRIBUTE_NORMAL,
    NULL);

WinObj: useful tool to see system internals

This is the description from MS website:
WinObj is a must-have tool if you are a system administrator concerned about security, a developer tracking down object-related problems, or just curious about the Object Manager namespace

For example, you want to see file name of serail port.
Open WinObj, go to GLOBAL, you will see file name COM1, COM3

Run binary code compiled by Visual studio on another computer which doesn't install Visual studio

If you want to run binary code compiled by Visaul studio on another computer, and you didn't install Visual studio on that computer, you could do following:
Go link, and download the redistribution package:
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=32bc1bee-a3f9-4c13-9c99-220b62a191ee&displaylang=en

This one is for VC++ 2005, and here is the breif discription:
The Microsoft Visual C++ 2005 Redistributable Package (x86) installs runtime components of Visual C++ Libraries required to run applications developed with Visual C++ on a computer that does not have Visual C++ 2005 installed.

Monday, March 14, 2011

HOWTO Oscilloscope

Model Type: Tektronix TDS 220

X coordinate: time, range from 5ns to 5s  
Y coordinate: Voltage, range from 2mV to 5V

Two Input Channel, you could set Alternate Current (AC) and Directive Current (DC).

IE, Chrome, Firefox

Just want to share a funny experience I just had.

I was trying to download and install Visual Studio Express on Windows

Use IE, it blocked itself, you have to turn off the "Pop-up Blcoker" or add www.microsoft.com/express/Downloads site to allow pop-up window.
Use Chrome, it stoped during the middle of downloading
Finally, I used firefox, it finished the task.

I am using firefox on my Linux machine.

Wednesday, March 2, 2011

Virus, Worm, Trojon Horse

http://www.webopedia.com/DidYouKnow/Internet/2004/virus.asp

Time-of-Check-to-Time-of-Use (TOCTOU) attacks on Linux file systems

TOCTOU attack need exploit a race condition in a setuid program

setuid and setgid are Unix access rights flags that allow users to run an executable with the permissions of the executable's owner or group

Example1

buggy setuid program                             attacker 
 
                                      // create a file the attacker can access
                                      touch /home/attack/bad
// check user permissions to file
if (access("/home/attack/bad", R_OK) != 0) 
{
       exit(1);
}
                                      // remove file
                                      rm /home/attacker/bad

                                         // create a symbolic to link secrets
                                         ln -s /top/secret /home/attack/bad
// use file
fd = open("/home/attacker/bad", O_RDONLY);
// Do something about fd...
 
Example2
buggy setuid program                               attacker

                                    // create a symbolic link to a file the attacker can access
                                    ln -s /home/attack/bad /home/attack/symlink
   // check user permissions to file
   if (access("/home/attack/symlink", R_OK) != 0) {
       exit(1);
   }
                                    // update symbolic link to a secret file
                                    ln -sf /top/secret /home/attack/symlink
   // use file
   fd = open("/home/attacker/symlink", O_RDONLY);
   // Do something about fd...
 
 
Why does this work?
1. access check the real user ID permission, not the effective ID permission.
2. open will check the file permission, but it use effective ID permission, since it is a setuid program, it will open the file with program owner's permission
Why TOCTOU target at setuid program?
1. setuid always has this pattern: check permission use access(), then open() the file
2. setuid could open the file using program ower's permission. see man 2 open and man 2 access

more information please see this link

Overriding V.S. Overloading

Overriding is the concept of having functions of same name and signature in different classes. one is base class, and the other one is derived class

Overloading is the concept of having functions of same name, but different signature in same class.

Method overloading is compile time polymorphism, method overriding is runtime polymorphism.

more information please see link

Abstract class and Interface

1. normal class V.S. (abstract class and interface)
why do we need abstract class and interface: because there are some class which we never want to make a instance of.
E.g.
CONTENT
ARTICLE
BLOGS
REVIEW
content is the base class, we never want to make instance of it, so it could be an interface or abstract class. There is another example, CS571 OS class first assignment, we never want to make a instance of vehicle,  we only want to make instance of car or van. 

2. abstract class V.S. interface
Same properties:
1). we cannot make instance of them
2). they could have fields, but fields in interface by default public static final.
3). they could have abstract method. method in interface by default public and abstract. abstract class need to specify the abstract keyword. 
4). when you implement a interface or extend a abstract class. you have to provide the class definition in the derived class. In other words, all the abstract class in base class need to be implemented in the derived class if the derived class is a normal class. 
Different properties: 
1). interface only contains public abstract method by default. abstract class could contain 0 or many abstract method, it also could contain normal method with detailed method definition. if the class contains one or more abstract method, it must be qualified as abstract, otherwise compiler will give you an error message. 
2). interface has multi-inheritance. but abstract doesn't. 
3). interface use implements keyword; abstract use extends keyword.

3. When to use interface and when to use abstract class?
Take the content, blog, article, review example above, suppose content has an "publish" behavior. if the "publish" has some default behavior applies to everyone, we should use abstract class for content. if there is no default behavior for "publish" and every derived class need to implemented their own, we should use interface.Also, there is great article discussion at this link
Another great example is the first assignment of CS571. Runable is an interface,  Vehicle is an abstract class implement Runnable. Car and Van are derived class from Vehicle. 

Tuesday, March 1, 2011

Web application security 2

How to defence attacks like SQL inject, XSS, CSRF:
There are lots ways. on way we could do is Input validation.
In PHP, there are lots of functions protecting from these attacks.


    // retrieve form data
    $username = sqlite_escape_string(htmlentities($_POST['username']));
    $password = sqlite_escape_string(htmlentities($_POST['password']));

Web application security

PHP code
PHP code is execute at the server side, Apache understands the PHP code, after the execution, it will give result of client side. If you run $wget login.php, the login.php will execute at server, and generate the result and pass it to the wget tool.

SQL injection
e.g. by pass the login authentication
This is the PHP code of checking if username and passpword is correct
    function checkuser($username, $password)
    {
    $db = "/home/fz2135/sqlite/cs4180";
    $handle = sqlite_open($db) or die("cannot open db");
    $query = "select * from userinfo where userinfo.password = '$passwordhash' AND username ='$username';";   
    $result= sqlite_query($handle, $query) or die("die in query");
    sqlite_close($handle);
    if(sqlite_num_rows($result) > 0)
        return true;
    else
        return false;   
    }

If I put uername as: user1' or '1=1
and password as random string
I could bypass the login authentication, but user1 need to be a valid username

Cross-site-scripting (XSS)
e.g.  we could inject a java script on the posted message. Post following message:<scirpt>alert("XSS")</script>


Arbitrary Code Execution
For eample, the vulnerable website allow you add attachment, like pictures. For this case, you could upload a php file, which Apache server could understand it. In the php file, you could use shell_exec() function

$output= shell_exec('cp ../../login.php login.txt');
echo $output."<br>";


Cross-Site Request Forgery (CSRF)


You found: if Alice transfer 100 dollars to Bob by using URL

GET http://bank.com/transfer.do?acct=BOB&amount=100 HTTP/1.1

Then you could create a html link, and let Alice to click on:

<a href="http://bank.com/transfer.do?acct=MARIA&amount=100000">View my Pictures!</a>

Then you will get 100000 dollars money into your account

more info:
http://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29

- The Open Web Application Security Project (OWASP),
"Top 10 web application vulnerabilities".
http://www.owasp.org/index.php/Top_10_2007

- milw0rm, "Finding vulnerabilities in PHP scripts".
http://www.milw0rm.com/papers/381