Dec 21, 2007

C pointer FAQ :D

Of course, pointers are not limited to ints. It's quite common to use pointers to other types, especially char. Here is the innards of the mystrcmp function we saw in a previous chapter, rewritten to use pointers. (mystrcmp, you may recall, compares two strings, character by character.)

    // p1, p2 point to the address of the first character in str1, str2 respectively
    char *p1 = &str1[0], *p2 = &str2[0];

    while(1)
        {
            // compare the values of str1[x], str[x] at the position x. Not equal
            if(*p1 != *p2)
                return *p1 - *p2;
            // we reached the end of both str1, str2 -> they are equal.
            if(*p1 == '\0' || *p2 == '\0')
                return 0;
            // p1++ and p2++ do the increment of p1 and p2.
            // i.e., the next characters in str1 ( str[x + 1] and str2 ( str2[ x + 1]
            p1++;
            p2++;
        }


As another example, here is the strcpy (string copy) loop from a previous chapter, rewritten to use pointers:

    char *dp = &dest[0], *sp = &src[0];
    while(*sp != '\0')
        // *dp++ means *(dp++), i.e., the value of the pointer next to dp.
        // to access the address of the next pointer of dp, use (*dp)++
        *dp++ = *sp++;
    *dp = '\0';

(One question that comes up is whether the expression *dp++ increments p or what it points to. The answer is that it increments p. To increment what p points to, you can use (*dp)++.)

ref: http://www.eskimo.com/~scs/cclass/notes/sx10b.html

Read and write png files bytes by bytes

#include 
#include 
#include 

#define WIDTH  (3)
#define HEIGHT (3)

int main()
{
    unsigned char   **image;                                // image[HEIGHT][WIDTH]の形式です
    int             i, j;

    image = (png_bytepp)malloc(HEIGHT * sizeof(png_bytep)); // 以下3行は2次元配列を確保します
    for (j = 0; j < HEIGHT; j++)
            image[j] = (png_bytep)malloc(WIDTH * sizeof(png_byte));


    for (i = 0; i < WIDTH; i++) {                           // 以下5行は単純なテストパターンを作ります
            for (j = 0; j < HEIGHT; j++) {
                    image[j][i] = (unsigned char)i;
            }
    }


    unsigned char *image2;

    image2 = (png_bytep) malloc( HEIGHT * WIDTH * sizeof(png_byte));

    for (i = 0; i < WIDTH; i++) {                           // 以下5行は単純なテストパターンを作ります
            for (j = 0; j < HEIGHT; j++) {
                    //printf("%d ", image[j][i]);
                    image2[j * WIDTH + i] = image[j][i];
                    printf("%d ", image2[j * WIDTH + i]);

            }
    }
    // TODO: write image2 to png stream
    // http://www.jah.ne.jp/~naoyuki/Writings/MngPng.html
    return 0;
}

Solaris 10: vim 7.1 color

Solaris 10 vim71 color
wget vim-7.1.tar.gz
tar xzvf vim-7.1.tar.gz
cd vim71
./configure --prefix=$HOME CC=gcc
make; make install
echo "syntax on" > .vimrc
export TERM=sun-color ( or echo "export TERM=sun-color" >> $HOME/.bash_profile

or TERM=xterm
or TERM=xtermc

Dec 20, 2007

Solars 10: Graphics Magick 1.10 installation

/bin/bash ../../libtool --silent   --mode=link g++  -D_REENTRANT -pthreads -version-info 1:3:0 -L/usr/sfw/lib -L/usr/lib -o libGraphicsMagick++.la -rpath /export/home/vuhung/lib Blob.lo BlobRef.lo CoderInfo.lo Color.lo Drawable.lo Exception.lo Functions.lo Geometry.lo Image.lo ImageRef.lo Montage.lo Options.lo Pixels.lo STL.lo Thread.lo TypeMetric.lo ../../magick/libGraphicsMagick.la
libtool: link: `/usr/sfw/lib/libstdc++.la' is not a valid libtool archive
make[3]: *** [libGraphicsMagick++.la] Error 1
make[3]: Leaving directory `/export/home/vuhung/usr/src/GraphicsMagick-1.1.10/Magick++/lib'
make[2]: *** [all-recursive] Error 1
make[2]: Leaving directory `/export/home/vuhung/usr/src/GraphicsMagick-1.1.10/Magick++/lib'
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory `/export/home/vuhung/usr/src/GraphicsMagick-1.1.10/Magick++'
make: *** [all-recursive] Error 1



232  ~/bin/tar xjvf GraphicsMagick-1.1.10.tar.bz2
233  cd GraphicsMagick-1.1.10
257  ./configure --prefix=$HOME CC=gcc CXX=g++  --enable-ccmalloc -without-perl
258  ~/bin/make
269  make install

bash-3.00# diff /usr/sfw/lib/libstdc++.la /usr/sfw/lib/libstdc++.la.original.2007-12-19.vh
1,32d0
< # libstdc++.la - a libtool library file
< # Generated by ltmain.sh - GNU libtool 1.4a-GCC3.0 (1.641.2.256 2001/05/28 20:09:07 with GCC-local changes)
< #
< # Please DO NOT delete this file!
< # It is necessary for linking the library.
<
< # The name that we can dlopen(3).
< dlname='libstdc++.so.6'
<
< # Names of this library.
< library_names='libstdc++.so.6.0.3 libstdc++.so.6 libstdc++.so'
<
< # The name of the static archive.
< old_library='libstdc++.a'
<
< # Libraries that this one depends upon.
< dependency_libs='-lc -lm -L/usr/sfw/lib -lgcc_s'
<
< # Version information for libstdc++.
< current=6
< age=0
< revision=3
<
< # Is this an already installed library?
< installed=yes
<
< # Files to dlopen/dlpreopen
< dlopen=''
< dlpreopen=''
<
< # Directory that this library needs to be installed in:
< libdir='/usr/sfw/lib'

bash-3.00# cat /etc/release
                     Solaris 10 6/06 s10s_u2wos_09a SPARC
         Copyright 2006 Sun Microsystems, Inc.  All Rights Reserved.
                      Use is subject to license terms.
                           Assembled 09 June 2006
                         Preinstall P/N 259-4616-01
                            Built 13 August 2006
bash-3.00# uname -a
SunOS soltest01 5.10 Generic_118833-22 sun4u sparc SUNW,Sun-Fire-V215
bash-3.00#
http://forum.java.sun.com/thread.jspa?threadID=5073150

Open Solaris 10 pkgrm pkgadd

-> pkgrm pkgname then -> pkgadd -d pkgnameFULL bash-3.00# pkgadd -d libgcc-3.4.6-sol10-sparc-local The following packages are available: 1 SMClgcc346 libgcc (sparc) 3.4.6 Select package(s) you wish to process (or 'all' to process all packages). (default: all) [?,??,q]: aa ERROR: Entry does not match available menu selection. Enter the number of the menu item you wish to select, or the token which is associated with the menu item, or a partial string which uniquely identifies the token for the menu item. Enter ?? to reprint the menu. Select package(s) you wish to process (or 'all' to process all packages). (default: all) [?,??,q]: all 中のパッケージインスタンス を処理中です。 libgcc(sparc) 3.4.6 FSF をパッケージのベースディレクトリとして使用します。 ## パッケージ情報を処理中です。 ## システム情報を処理中です。 5 個のパッケージパス名がすでに正しくインストールされています。 ## ディスク領域の要件を確認中です。 ## すでにインストール済みのパッケージとの重複を確認中です。 次のファイルは、すでにシステムにインストールされていますが、 現在、他 のパッケージが使用中です: /usr/local/lib/libg2c.so.0.0.0 /usr/local/lib/libgcc_s.so.1 /usr/local/lib/libstdc++.so.6.0.3 これらの重複しているファイルをインストールしますか [y,n,?,q] y ## setuid/setgid を行うプログラムを検査中です。 libgcc を としてインストール中です。 ## 1/1 部分をインストールしています。 /usr/local/lib/libg2c.so.0.0.0 /usr/local/lib/libgcc_s.so.1 /usr/local/lib/libstdc++.so.6.0.3 [ クラス を検査しています ] のインストールに成功しました。 bash-3.00# pkgadd -d gcc-3.4.6-sol10-sparc-local The following packages are available: 1 SMCgcc gcc (sparc) 3.4.6 Select package(s) you wish to process (or 'all' to process all packages). (default: all) [?,??,q]: all 中のパッケージインスタンス を処理中です。 gcc(sparc) 3.4.6 現在の管理上では、 パッケージに固有なインスタンスを作成する必 要があります。ただし、同じシステム上で 1 度にサポートできる最大数の パッケージインスがすでに存在しています。 システムは変更されていません。

Dec 11, 2007

Callback function

/** $g++ callback.c -o callback ./callback Item 4 http://en.wikipedia.org/wiki/Callback_%28computer_science%29 */ #include /* LIBRARY CODE */ int traverseWith(int array[], size_t length, int (*callback)(int index, int item, void *param), void *param) { int exitCode = 0; for (int i = 0; i < length; i++) { exitCode = callback(i, array[i], param); if (exitCode != 0) { break; } } return exitCode; } /* APPLICATION CODE */ int search (int index, int item, void *param) { if (item > 5) { *(int *)param = index; return 1; } else { return 0; } } main() { /* (in another function) */ int index; int found; int array[] = {1, 2, 3, 4, 7, 10, 12, 15 }; int length = 6; found = traverseWith(array, length, &search, &index); if (found) { printf("Item %d\n", index); } else { printf("Not found\n"); } }

Dec 9, 2007

pngcrush; png optimizer

[地図ログ] [vuhung@aoclife pngcrush-1.6.4]$ ./pngcrush 14_1689_295.png 14_1689_295.png.crush | pngcrush 1.6.4 | Copyright (C) 1998-2002,2006 Glenn Randers-Pehrson | Copyright (C) 2005 Greg Roelofs | This is a free, open-source program. Permission is irrevocably | granted to everyone to use this version of pngcrush without | payment of any fee. | Executable name is pngcrush | It was built with libpng version 1.2.11beta4, and is | running with libpng version 1.2.11beta4 - June 7, 2006 (header) | Copyright (C) 1998-2004,2006 Glenn Randers-Pehrson, | Copyright (C) 1996, 1997 Andreas Dilger, | Copyright (C) 1995, Guy Eric Schalnat, Group 42 Inc., | and zlib version 1.2.3, Copyright (C) 1998-2002 (or later), | Jean-loup Gailly and Mark Adler. | It was compiled with gcc version 4.1.1 20070105 (Red Hat 4.1.1-52) and gas version 2.17.50.0.6-2.el5. Recompressing 14_1689_295.png Total length of data found in IDAT chunks = 24878 unknown chunk handling done. IDAT length with method 1 (fm 0 zl 4 zs 0) = 25646 IDAT length with method 2 (fm 1 zl 4 zs 0) = 29197 IDAT length with method 3 (fm 5 zl 4 zs 1) = 31397 IDAT length with method 4 (fm 0 zl 9 zs 1) = 25218 IDAT length with method 7 (fm 0 zl 9 zs 0) = 24212 Best pngcrush method = 7 (fm 0 zl 9 zs 0) for 14_1689_295.png.crush (2.68% IDAT reduction) (2.75% filesize reduction) CPU time used = 0.210 seconds (decoding 0.030, encoding 0.180, other 0.000 seconds) [vuhung@aoclife pngcrush-1.6.4]$ ls -l 14_1689_295.png* -rw-rw-r-- 1 vuhung vuhung 25565 12\u6708 9 03:20 14_1689_295.png -rw-rw-r-- 1 vuhung vuhung 24863 12\u6708 9 03:20 14_1689_295.png.crush [google] [vuhung@aoclife pngcrush-1.6.4]$ ./pngcrush mt_024.png mt_024.png.crush | pngcrush 1.6.4 | Copyright (C) 1998-2002,2006 Glenn Randers-Pehrson | Copyright (C) 2005 Greg Roelofs | This is a free, open-source program. Permission is irrevocably | granted to everyone to use this version of pngcrush without | payment of any fee. | Executable name is pngcrush | It was built with libpng version 1.2.11beta4, and is | running with libpng version 1.2.11beta4 - June 7, 2006 (header) | Copyright (C) 1998-2004,2006 Glenn Randers-Pehrson, | Copyright (C) 1996, 1997 Andreas Dilger, | Copyright (C) 1995, Guy Eric Schalnat, Group 42 Inc., | and zlib version 1.2.3, Copyright (C) 1998-2002 (or later), | Jean-loup Gailly and Mark Adler. | It was compiled with gcc version 4.1.1 20070105 (Red Hat 4.1.1-52) and gas version 2.17.50.0.6-2.el5. Recompressing mt_024.png Total length of data found in IDAT chunks = 16658 unknown chunk handling done. IDAT length with method 1 (fm 0 zl 4 zs 0) = 17939 IDAT length with method 2 (fm 1 zl 4 zs 0) = 20757 IDAT length with method 3 (fm 5 zl 4 zs 1) = 25521 IDAT length with method 4 (fm 0 zl 9 zs 1) = 17030 IDAT length with method 7 (fm 0 zl 9 zs 0) = 16686 Best pngcrush method = 0 (fm 5 zl 9 zs 1) for mt_024.png.crush (no IDAT change) (no filesize change) CPU time used = 0.220 seconds (decoding 0.020, encoding 0.180, other 0.020 seconds)

Dec 3, 2007

Good Temporary Files ( or randomness )

This issue of correctly performing atomic operations particularly comes up when creating temporary files. Temporary files in Unix-like systems are traditionally created in the /tmp or /var/tmp directories, which are shared by all users. A common trick by attackers is to create symbolic links in the temporary directory to some other file (e.g., /etc/passwd) while your secure program is running. The attacker's goal is to create a situation where the secure program determines that a given filename doesn't exist, the attacker then creates the symbolic link to another file, and then the secure program performs some operation (but now it actually opened an unintended file). Often important files can be clobbered or modified this way. There are many variations to this attack, such as creating normal files, all based on the idea that the attacker can create (or sometimes otherwise access) file system objects in the same directory used by the secure program for temporary files. Michal Zalewski exposed in 2002 another serious problem with temporary directories involving automatic cleaning of temporary directories. For more information, see his posting to Bugtraq dated December 20, 2002, (subject "[RAZOR] Problems with mkstemp()"). Basically, Zalewski notes that it's a common practice to have a program automatically sweep temporary directories like /tmp and /var/tmp and remove "old" files that have not been accessed for a while (e.g., several days). Such programs are sometimes called "tmp cleaners" (pronounced "temp cleaners"). Possibly the most common tmp cleaner is "tmpwatch" by Erik Troan and Preston Brown of Red Hat Software; another common one is 'stmpclean' by Stanislav Shalunov; many administrators roll their own as well. Unfortunately, the existance of tmp cleaners creates an opportunity for new security-critical race conditions; an attacker may be able to arrange things so that the tmp cleaner interferes with the secure program. For example, an attacker could create an "old" file, arrange for the tmp cleaner to plan to delete the file, delete the file himself, and run a secure program that creates the same file - now the tmp cleaner will delete the secure program's file! Or, imagine that a secure program can have long delays after using the file (e.g., a setuid program stopped with SIGSTOP and resumed after many days with SIGCONT, or simply intentionally creating a lot of work). If the temporary file isn't used for long enough, its temporary files are likely to be removed by the tmp cleaner. The general problem when creating files in these shared directories is that you must guarantee that the filename you plan to use doesn't already exist at time of creation, and atomically create the file. Checking ``before'' you create the file doesn't work, because after the check occurs, but before creation, another process can create that file with that filename. Using an ``unpredictable'' or ``unique'' filename doesn't work in general, because another process can often repeatedly guess until it succeeds. Once you create the file atomically, you must alway use the returned file descriptor (or file stream, if created from the file descriptor using routines like fdopen()). You must never re-open the file, or use any operations that use the filename as a parameter - always use the file descriptor or associated stream. Otherwise, the tmpwatch race issues noted above will cause problems. You can't even create the file, close it, and re-open it, even if the permissions limit who can open it. Note that comparing the descriptor and a reopened file to verify inode numbers, creation times or file ownership is not sufficient - please refer to "Symlinks and Cryogenic Sleep" by Olaf Kirch. Fundamentally, to create a temporary file in a shared (sticky) directory, you must repetitively: (1) create a ``random'' filename, (2) open it using O_CREAT | O_EXCL and very narrow permissions (which atomically creates the file and fails if it's not created), and (3) stop repeating when the open succeeds. According to the 1997 ``Single Unix Specification'', the preferred method for creating an arbitrary temporary file (using the C interface) is tmpfile(3). The tmpfile(3) function creates a temporary file and opens a corresponding stream, returning that stream (or NULL if it didn't). Unfortunately, the specification doesn't make any guarantees that the file will be created securely. In earlier versions of this book, I stated that I was concerned because I could not assure myself that all implementations do this securely. I've since found that older System V systems have an insecure implementation of tmpfile(3) (as well as insecure implementations of tmpnam(3) and tempnam(3)), so on at least some systems it's absolutely useless. Library implementations of tmpfile(3) should securely create such files, of course, but users don't always realize that their system libraries have this security flaw, and sometimes they can't do anything about it. Kris Kennaway recommends using mkstemp(3) for making temporary files in general. His rationale is that you should use well-known library functions to perform this task instead of rolling your own functions, and that this function has well-known semantics. This is certainly a reasonable position. I would add that, if you use mkstemp(3), be sure to use umask(2) to limit the resulting temporary file permissions to only the owner. This is because some implementations of mkstemp(3) (basically older ones) make such files readable and writable by all, creating a condition in which an attacker can read or write private data in this directory. A minor nuisance is that mkstemp(3) doesn't directly support the environment variables TMP or TMPDIR (as discussed below), so if you want to support them you have to add code to do so. Here's a program in C that demonstrates how to use mkstemp(3) for this purpose, both directly and when adding support for TMP and TMPDIR: #include #include #include #include void failure(msg) { fprintf(stderr, "%s\n", msg); exit(1); } /* * Given a "pattern" for a temporary filename * (starting with the directory location and ending in XXXXXX), * create the file and return it. * This routines unlinks the file, so normally it won't appear in * a directory listing. * The pattern will be changed to show the final filename. */ FILE *create_tempfile(char *temp_filename_pattern) { int temp_fd; mode_t old_mode; FILE *temp_file; old_mode = umask(077); /* Create file with restrictive permissions */ temp_fd = mkstemp(temp_filename_pattern); (void) umask(old_mode); if (temp_fd == -1) { failure("Couldn't open temporary file"); } if (!(temp_file = fdopen(temp_fd, "w+b"))) { failure("Couldn't create temporary file's file descriptor"); } if (unlink(temp_filename_pattern) == -1) { failure("Couldn't unlink temporary file"); } return temp_file; } /* * Given a "tag" (a relative filename ending in XXXXXX), * create a temporary file using the tag. The file will be created * in the directory specified in the environment variables * TMPDIR or TMP, if defined and we aren't setuid/setgid, otherwise * it will be created in /tmp. Note that root (and su'd to root) * _will_ use TMPDIR or TMP, if defined. * */ FILE *smart_create_tempfile(char *tag) { char *tmpdir = NULL; char *pattern; FILE *result; if ((getuid()==geteuid()) && (getgid()==getegid())) { if (! ((tmpdir=getenv("TMPDIR")))) { tmpdir=getenv("TMP"); } } if (!tmpdir) {tmpdir = "/tmp";} pattern = malloc(strlen(tmpdir)+strlen(tag)+2); if (!pattern) { failure("Could not malloc tempfile pattern"); } strcpy(pattern, tmpdir); strcat(pattern, "/"); strcat(pattern, tag); result = create_tempfile(pattern); free(pattern); return result; } main() { int c; FILE *demo_temp_file1; FILE *demo_temp_file2; char demo_temp_filename1[] = "/tmp/demoXXXXXX"; char demo_temp_filename2[] = "second-demoXXXXXX"; demo_temp_file1 = create_tempfile(demo_temp_filename1); demo_temp_file2 = smart_create_tempfile(demo_temp_filename2); fprintf(demo_temp_file2, "This is a test.\n"); printf("Printing temporary file contents:\n"); rewind(demo_temp_file2); while ( (c=fgetc(demo_temp_file2)) != EOF) { putchar(c); } putchar('\n'); printf("Exiting; you'll notice that there are no temporary files on exit.\n"); } Kennaway states that if you can't use mkstemp(3), then make yourself a directory using mkdtemp(3), which is protected from the outside world. However, as Michal Zalewski notes, this is a bad idea if there are tmp cleaners in use; instead, use a directory inside the user's HOME. Finally, if you really have to use the insecure mktemp(3), use lots of X's - he suggests 10 (if your libc allows it) so that the filename can't easily be guessed (using only 6 X's means that 5 are taken up by the PID, leaving only one random character and allowing an attacker to mount an easy race condition). Note that this is fundamentally insecure, so you should normally not do this. I add that you should avoid tmpnam(3) as well - some of its uses aren't reliable when threads are present, and it doesn't guarantee that it will work correctly after TMP_MAX uses (yet most practical uses must be inside a loop). In general, you should avoid using the insecure functions such as mktemp(3) or tmpnam(3), unless you take specific measures to counter their insecurities or test for a secure library implementation as part of your installation routines. If you ever want to make a file in /tmp or a world-writable directory (or group-writable, if you don't trust the group) and don't want to use mk*temp() (e.g. you intend for the file to be predictably named), then always use the O_CREAT and O_EXCL flags to open() and check the return value. If you fail the open() call, then recover gracefully (e.g. exit). The GNOME programming guidelines recommend the following C code when creating filesystem objects in shared (temporary) directories to securely open temporary files [Quintero 2000]: char *filename; int fd; do { filename = tempnam (NULL, "foo"); fd = open (filename, O_CREAT | O_EXCL | O_TRUNC | O_RDWR, 0600); free (filename); } while (fd == -1); Note that, although the insecure function tempnam(3) is being used, it is wrapped inside a loop using O_CREAT and O_EXCL to counteract its security weaknesses, so this use is okay. Note that you need to free() the filename. You should close() and unlink() the file after you are done. If you want to use the Standard C I/O library, you can use fdopen() with mode "w+b" to transform the file descriptor into a FILE *. Note that this approach won't work over NFS version 2 (v2) systems, because older NFS doesn't correctly support O_EXCL. Note that one minor disadvantage to this approach is that, since tempnam can be used insecurely, various compilers and security scanners may give you spurious warnings about its use. This isn't a problem with mkstemp(3). If you need a temporary file in a shell script, you're probably best off using pipes, using a local directory (e.g., something inside the user's home directory), or in some cases using the current directory. That way, there's no sharing unless the user permits it. If you really want/need the temporary file to be in a shared directory like /tmp, do not use the traditional shell technique of using the process id in a template and just creating the file using normal operations like ">". Shell scripts can use "$$" to indicate the PID, but the PID can be easily determined or guessed by an attacker, who can then pre-create files or links with the same name. Thus the following "typical" shell script is unsafe: echo "This is a test" > /tmp/test$$ # DON'T DO THIS. If you need a temporary file or directory in a shell script, and you want it in /tmp, a solution sometimes suggested is to use mktemp(1), which is intended for use in shell scripts (note that mktemp(1) and mktemp(3) are different things). However, as Michal Zalewski notes, this is insecure in many environments that run tmp cleaners; the problem is that when a privileged program sweeps through a temporary directory, it will probably expose a race condition. Even if this weren't true, I do not recommend using shell scripts that create temporary files in shared directories; creating such files in private directories or using pipes instead is generally preferable, even if you're sure your tmpwatch program is okay (or that you have no local users). If you must use mktemp(1), note that mktemp(1) takes a template, then creates a file or directory using O_EXCL and returns the resulting name; thus, mktemp(1) won't work on NFS version 2 filesystems. Here are some examples of correct use of mktemp(1) in Bourne shell scripts; these examples are straight from the mktemp(1) man page: # Simple use of mktemp(1), where the script should quit # if it can't get a safe temporary file. # Note that this will be INSECURE on many systems, since they use # tmpwatch-like programs that will erase "old" files and expose race # conditions. TMPFILE=`mktemp /tmp/$0.XXXXXX` || exit 1 echo "program output" >> $TMPFILE # Simple example, if you want to catch the error: TMPFILE=`mktemp -q /tmp/$0.XXXXXX` if [ $? -ne 0 ]; then echo "$0: Can't create temp file, exiting..." exit 1 fi Perl programmers should use File::Temp, which tries to provide a cross-platform means of securely creating temporary files. However, read the documentation carefully on how to use it properly first; it includes interfaces to unsafe functions as well. I suggest explicitly setting its safe_level to HIGH; this will invoke additional security checks. The Perl 5.8 documentation of File::Temp is available on-line. Don't reuse a temporary filename (i.e. remove and recreate it), no matter how you obtained the ``secure'' temporary filename in the first place. An attacker can observe the original filename and hijack it before you recreate it the second time. And of course, always use appropriate file permissions. For example, only allow world/group access if you need the world or a group to access the file, otherwise keep it mode 0600 (i.e., only the owner can read or write it). Clean up after yourself, either by using an exit handler, or making use of UNIX filesystem semantics and unlink()ing the file immediately after creation so the directory entry goes away but the file itself remains accessible until the last file descriptor pointing to it is closed. You can then continue to access it within your program by passing around the file descriptor. Unlinking the file has a lot of advantages for code maintenance: the file is automatically deleted, no matter how your program crashes. It also decreases the likelihood that a maintainer will insecurely use the filename (they need to use the file descriptor instead). The one minor problem with immediate unlinking is that it makes it slightly harder for administrators to see how disk space is being used, since they can't simply look at the file system by name. You might consider ensuring that your code for Unix-like systems respects the environment variables TMP or TMPDIR if the provider of these variable values is trusted. By doing so, you make it possible for users to move their temporary files into an unshared directory (and eliminating the problems discussed here), such as a subdirectory inside their home directory. Recent versions of Bastille can set these variables to reduce the sharing between users. Unfortunately, many users set TMP or TMPDIR to a shared directory (say /tmp), so your secure program must still correctly create temporary files even if these environment variables are set. This is one advantage of the GNOME approach, since at least on some systems tempnam(3) automatically uses TMPDIR, while the mkstemp(3) approach requires more code to do this. Please don't create yet more environment variables for temporary directories (such as TEMP), and in particular don't create a different environment name for each application (e.g., don't use "MYAPP_TEMP"). Doing so greatly complicates managing systems, and users wanting a special temporary directory for a specific application can just set the environment variable specially when running that particular application. Of course, if these environment variables might have been set by an untrusted source, you should ignore them - which you'll do anyway if you follow the advice in Section 5.2.3. These techniques don't work if the temporary directory is remotely mounted using NFS version 2 (NFSv2), because NFSv2 doesn't properly support O_EXCL. See Section 7.10.2.1 for more information. NFS version 3 and later properly support O_EXCL; the simple solution is to ensure that temporary directories are either local or, if mounted using NFS, mounted using NFS version 3 or later. There is a technique for safely creating temporary files on NFS v2, involving the use of link(2) and stat(2), but it's complex; see Section 7.10.2.1 which has more information about this. As an aside, it's worth noting that FreeBSD has recently changed the mk*temp() family to get rid of the PID component of the filename and replace the entire thing with base-62 encoded randomness. This drastically raises the number of possible temporary files for the "default" usage of 6 X's, meaning that even mktemp(3) with 6 X's is reasonably (probabilistically) secure against guessing, except under very frequent usage. However, if you also follow the guidance here, you'll eliminate the problem they're addressing. Much of this information on temporary files was derived from Kris Kennaway's posting to Bugtraq about temporary files on December 15, 2000. I should note that the Openwall Linux patch from http://www.openwall.com/linux/ includes an optional ``temporary file directory'' policy that counters many temporary file based attacks. The Linux Security Module (LSM) project includes an "owlsm" module that implements some of the OpenWall ideas, so Linux Kernels with LSM can quickly insert these rules into a running system. When enabled, it has two protections: * Hard links: Processes may not make hard links to files in certain cases. The OpenWall documentation states that "Processes may not make hard links to files they do not have write access to." In the LSM version, the rules are as follows: if both the process' uid and fsuid (usually the same as the euid) is is different from the linked-to-file's uid, the process uid is not root, and the process lacks the FOWNER capability, then the hard link is forbidden. The check against the process uid may be dropped someday (they are work-arounds for the atd(8) program), at which point the rules would be: if both the process' fsuid (usually the same as the euid) is is different from the linked-to-file's uid and and the process lacks the FOWNER capability, then the hard link is forbidden. In other words, you can only create hard links to files you own, unless you have the FOWNER capability. * Symbolic links (symlinks): Certain symlinks are not followed. The original OpenWall documentation states that "root processes may not follow symlinks that are not owned by root", but the actual rules (from looking at the code) are more complicated. In the LSM version, if the directory is sticky ("+t" mode, used in shared directories like /tmp), symlinks are not followed if the symlink was created by anyone other than either the owner of the directory or the current process' fsuid (which is usually the effective uid). Many systems do not implement this openwall policy, so you can't depend on this in general protecting your system. However, I encourage using this policy on your own system, and please make sure that your application will work when this policy is in place.

Nov 29, 2007

How did they find me through search engines?

[root@aoclife etc]# diff -u webalizer.conf.2007-11-29.no.JP.searchEngine webalizer.conf --- webalizer.conf.2007-11-29.no.JP.searchEngine 2007-11-29 23:34:18.000000000 +0900 +++ webalizer.conf 2007-11-29 23:34:38.000000000 +0900 @@ -529,6 +529,16 @@ SearchEngine alltheweb.com query= SearchEngine northernlight.com qr= + +SearchEngine infoseek.co.jp qt= +SearchEngine excite.co.jp search= +SearchEngine yahoo.co.jp p= +SearchEngine yahoo.co.jp q= +SearchEngine google.co.jp q= +SearchEngine goo.ne.jp MT= +SearchEngine biglobe.ne.jp q= +SearchEngine msn.co.jp q= + # The Dump* keywords allow the dumping of Sites, URL's, Referrers # User Agents, Usernames and Search strings to seperate tab delimited # text files, suitable for import into most database or spreadsheet [root@aoclife etc]#

Nov 21, 2007

aoclife harddisk full

[root@aoclife /]# du -sh *
7.0M    bin
4.5M    boot
128K    dev
69M     etc
17G     home
68M     lib
16K     lost+found
12K     media
0       misc
40K     mnt
0       net
139M    opt
du: `proc/fs/vmblock/mountPoint': そのようなファイルやディレクトリはありません
0       proc
8.9M    root
24M     sbin
0       selinux
8.0K    srv
0       sys
180K    tmp
3.7G    usr
9.4G    var

[root@aoclife /]# df -h
Filesystem          サイズ  使用  残り 使用% マウント位置
/dev/sda2              14G   13G     0 100% /
/dev/sda1              99M   10M   84M  11% /boot
tmpfs                1014M     0 1014M   0% /dev/shm
/dev/sda6              18G   16G  1.4G  92% /home
/dev/sda3             965M   44M  872M   5% /usr/local

[root@aoclife /]# cd /var
[root@aoclife var]# du -sh *
12K     account
539M    cache
8.0K    cvs
28K     db
32K     empty
8.0K    games
111M    lib
8.0K    local
168K    lock
59M     log
4.0K    mail
8.0K    nis
8.0K    opt
8.0K    preserve
8.0K    racoon
568K    run
150M    spool
2.5M    tmp
8.6G    www

[root@aoclife var]# cd www
[root@aoclife www]# du -sh *
8.0K    cgi-bin
304K    error
8.6G    html
1.8M    icons
352K    usage
[root@aoclife www

[root@aoclife html]# du -sh *
7.6G    aoc
16K     aoc2
8.0K    favicon.ico
8.0K    i.php
8.0K    index.html
36M     openkh
5.8M    squirrelmail-1.4.11
968M    tmp
324K    usage
4.0K    webalizer
4.0K    webmail


[root@aoclife www]# cd html/
[root@aoclife html]# du -sh *
7.6G    aoc
16K     aoc2
8.0K    favicon.ico
8.0K    i.php
8.0K    index.html
36M     openkh
5.8M    squirrelmail-1.4.11
968M    tmp
324K    usage
4.0K    webalizer
4.0K    webmail
[root@aoclife html]# cd tmp/
[root@aoclife tmp]# du -sh *
53M     Bryan Peterson - Learn to See Creatively (Revised Edition).pdf
4.8M    Free Open-Source Software Development (2005).pdf
701M    Hostel 2.avi
85M     K'ARUMANTA
4.5M    LichSuPhanMemFPT
8.0K    OK.txt
96K     RapidSoftwareTesting.pdf
73M     SONCCO LLACTA
792K    The.Seven.Habits.Of.Highly.Effective.People.pdf
1.7M    Thomas.L.Friedman.-.The.World.Is.Flat.A.Brief.History.Of.The.21St.Century.by.VeryCD.pdf
19M     computer.org.articles
4.0K    ds
25M     tretodaydvd
2.9M    vieclamhanoi_data.sql


[root@aoclife tmp]# echo "" > "Hostel 2.avi"
[root@aoclife tmp]# df -h
Filesystem          サイズ  使用  残り 使用% マウント位置
/dev/sda2              14G   12G  701M  95% /
/dev/sda1              99M   10M   84M  11% /boot
tmpfs                1014M     0 1014M   0% /dev/shm
/dev/sda6              18G   16G  1.4G  92% /home
/dev/sda3             965M   44M  872M   5% /usr/local

Nov 19, 2007

Nintendo DS games

0211 - Real Time Conflict - Shogun Empires (U) (MODE7).nds28-Nov-2005 11:48 32M
0258 - Shichida Shiki Training - Unou Tanren Unotan DS - Shun Kan Shoubu! Handanryoku (J).nds06-Jan-2006 04:25 16M
0260 - Shichida Shiki Training - Unou Tanren Unotan DS - Shun Kan Shoubu! Kiokuryoku (J).nds09-Jan-2006 17:52 16M
0366 - Tetris DS .nds20-Mar-2006 15:57 16M
6rz-cdscCrossword_DS_And_Sekai_1_Shuu_Cross_JPN.nds08-Nov-2007 02:07 8.0M
6rz-etdsEijukugo_Target_1000_DS_JPN.nds11-Nov-2007 10:10 64M
6rz-knij. 家庭の医学.nds16-Nov-2007 01:02 64M
6rz-scsy 佐伯チズの美肌技術と美容理論.nds18-Oct-2007 21:09 128M
6rz-tskd 図書館DS.nds11-Nov-2007 10:11 32M
1044 - Final Fantasy III (E).nds13-Sep-2008 12:38 128M
1664 - Cooking Mama 2 - Dinner with Friends (U).nds14-Nov-2007 13:57 64M
DSOrganize_3_1.zip16-Nov-2007 01:26 4.3M
ck-sds - Soroban_DS_JPN_NDS-Chikan.nds12-Jul-2007 01:00 32M
cvn-mgth - Shaberu__DS_Oryouri_Navi_Marugot...oku_Hotel__JPN___1024Mbit___Caravan.nds21-Jun-2007 00:00 128M
d-picross.nds26-Jun-2006 11:32 32M
frx-r08e- Real Football 2008.nds10-Oct-2007 17:38 32M
frx-sime-SimCity.nds20-Jun-2007 11:50 64M
ind-ffta2 Final Fantasy II.nds20-Oct-2007 21:01 128M
ind-odjc旺文社 でる順地理DS.nds31-Jul-2007 06:23 16M
ind-odjk旺文社 でる順 国語DS.nds31-Jul-2007 06:23 16M
ind-sgk2 Sangokushi DS 2.nds13-Nov-2007 00:00 64M
ind-skds-_Shikaku_Kentei_DS__J.nds07-Aug-2007 06:37 64M
ind-spm 大人の思考センス.nds22-Oct-2007 21:42 32M
ipt-edoh えんぴつで奥の細道.nds12-Jun-2007 17:12 64M
lmp-ng-1.02 DS Ipod.nds26-Feb-2007 21:47 826K
pup-svre WWE_Smackdown_vs_Raw_2008_MULTi4_EUR_NDS-PUPPA .nds08-Nov-2007 16:06 64M
sq-psudo Platinum Sudoku.nds10-Jul-2007 02:31 8.0M
svg-ycee-Chess-Master.nds14-Nov-2007 02:11 32M
svg-ymje-Disney-Princess.nds11-Nov-2007 14:44 64M
svg-ymje Disney Princess - Magical Jewels .nds11-Nov-2007 14:44 64M
sx-kcsae - Konami Classics Series Arcade Hits .NDS24-Oct-2007 18:57 16M
trm-sm1p Super Mario 64 DS v1.1 PROPER.nds29-Jun-2005 04:37 16M
trm-smjp-Super_20Mario_2064_20DS_20_J__Trashman.nds01-Jul-2005 03:03 16M
xms-cd4f Call_Of_Duty_4_Modern_Warfare_FRA_NDS-EXiMiUS.nds09-Nov-2007 20:43 64M
xpa-cm2u - Cooking Mama 2 - Dinner With Friends.nds14-Nov-2007 13:57 64M
xpa-mwce-MyWordCoachEURNDS-XPA.nds14-Nov-2007 14:43 64M
xpa-nfsp - Need for Speed - Pro Street.nds14-Nov-2007 13:44 64M
xpa-rdcr Race_Driver_Create_And_Race.nds27-Sep-2007 15:53 64M
xpa-umku Ultimate Mortal Kombat.nds13-Nov-2007 15:35 64M