Wednesday, November 28, 2007

Some experience with C string operation

After my C project work. Accumulate some tips.

List here in case :)


Bad :
char buf[10];
scanf(
"%s", buf);
Good way:
char buf[10];
scanf(
"%9s", buf);


Bad :
char buf[BUFSIZ];
gets(buf);

Good way:
char buf[BUFSIZ];
int ch;
char *p;

if (fgets(buf, sizeof(buf), stdin)) {
/* fgets succeeds, scan for newline character */
p = strchr(buf, '\n');
if (p) {
*p = '\0';
}
else {
/* newline not found, flush stdin to end of line */
while (((ch = getchar()) != '\n') && !feof(stdin) && !ferror(stdin) );
}
}
else {
/* fgets failed, handle error */
}

OR:

char buf[BUFSIZ];

if (gets_s(buf, BUFSIZ) == NULL) {
/* handle error */
}
Bad :
char buf[BUFSIZ], *p;
int ch;
p = buf;
while ( ((ch = getchar()) != '\n') && !feof(stdin) && !ferror(stdin)) {
*p++ = ch;
}


*p++ = 0;
Good way :
unsigned char buf[BUFSIZ];
int ch;
int index = 0;
int chars_read = 0;
while ( ( (ch = getchar()) != '\n') && !feof(stdin) && !ferror(stderr) ) {
if (index < class="code-object">char)ch;
}
chars_read++;
} /* end while */
buf[index] = '\0'; /* terminate NTBS */
if (feof(stdin)) {
/* handle EOF */
}
if (ferror(stdin)) {
/* handle error */
}
if (chars_read > index) {
/* handle truncation */
}


Reference:
https://www.securecoding.cert.org/confluence/display/seccode/FIO43-C.+Do+not+copy+data+from+an+unbounded+source+to+a+fixed-length+array

Monday, November 26, 2007

How to generate keys by ssh command

Finally get the clue with the help of Zeba's website.

1. On the machine you want to use to call another machine, say A ->B
We would like A to ssh B without inputing the password.

2. In A machine, type the command: ssh-keygen -t dsa -b 1024
no key phrases

3. Copy the key to machine B by: scp
id_dsa.pub user@192.168.X.X:/home/user/.ssh (this might be changed according to different setting)

4. cat id_dsa.pub >> /path/.ssh/authorizedkeys

5. Now you can ssh B without password from A.

for details I need to read more on security authentication...