Hi Gary,

Gary Yang wrote on Wed, Jan 30, 2008 at 03:54:51PM -0800:

> I need to get a random number whenever the perl script is called.
> Each time the random number I got should be different.
> I use that number to name generated files, i.e. I want the perl
> script to generate different file names whenever it is called.

That's probably a very bad idea in the first place.

Automatic unique filename generation and opening the file for writing
looks like an easy task from a naive point of view, but actually,
it's one of the major sources of security issues, usually involving
race conditions.  There are many different techniques for exploiting
such race conditions, and if your script is running with root
privileges, they usually result in root exploits.

Besides, there is a plethora of standard library routines to
accomplish such tasks, but most of them are no good and should
not be used at all.  There are even cases where the shell version
of a routine is ok, but the C version is not (eg. mktemp).
So you need to be extremely careful.
To understand the basic issues, read:
  http://www.openbsd.org/cgi-bin/man.cgi?query=tmpfile
  http://www.openbsd.org/cgi-bin/man.cgi?query=mktemp&sektion=3
  http://www.openbsd.org/cgi-bin/man.cgi?query=mktemp&sektion=1
These OpenBSD manual pages are describing the issues involved
much better than the corresponding GNU manual pages, so do NOT
try to learn this stuff on a Linux system.

Even if you have understood the basic issues concerning C code,
transferring that knowledge to a different language is non-trivial.
The right tool to use in Perl is the standard module File::Temp.

To summarize, 
 1. Do not naively use random numbers.
 2. Do not use the process number.
 3. Do not use the date or time or anything calculated from it:
    Time might need backward correction, and time is predictable.
 4. Never use tmpnam(3), tempnam(3), mktemp(3), POSIX::tmpnam,
    File::Temp::tmpnam, File::Temp::tempnam, File::Temp::mktemp:
    These functions are inherently unsafe.
 5. Never use tempfile(3), mkdtemp(3) or mkstemps(3):
    These functions are not portable.
 6. In C, use tmpfile(3) when possible.
 7. In C, use mkstemp(3) when you want to keep the file after process
    temination or if you need to know the filename.
 8. In shell scripts, use mktemp(1).
 9. In Perl, use File::Temp::tempfile.

No, this is _not_ simple.

Have fun,
  Ingo

-- 
Ingo Schwarze <[EMAIL PROTECTED]> | Software Engineer | Framework Team
Astaro AG | www.astaro.com | 76227 Karlsruhe | Germany
_______________________________________________
Perl-Unix-Users mailing list
Perl-Unix-Users@listserv.ActiveState.com
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs

Reply via email to