⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 perlsec.pod

📁 视频监控网络部分的协议ddns,的模块的实现代码,请大家大胆指正.
💻 POD
📖 第 1 页 / 共 2 页
字号:
going to turn around and execute some other program that is dependent onyour PATH, it makes sure you set the PATH.The PATH isn't the only environment variable which can cause problems.Because some shells may use the variables IFS, CDPATH, ENV, andBASH_ENV, Perl checks that those are either empty or untainted whenstarting subprocesses. You may wish to add something like this to yoursetid and taint-checking scripts.    delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};   # Make %ENV saferIt's also possible to get into trouble with other operations that don'tcare whether they use tainted values.  Make judicious use of the filetests in dealing with any user-supplied filenames.  When possible, doopens and such B<after> properly dropping any special user (or group!)privileges. Perl doesn't prevent you from opening tainted filenames for reading,so be careful what you print out.  The tainting mechanism is intended toprevent stupid mistakes, not to remove the need for thought.Perl does not call the shell to expand wild cards when you pass C<system>and C<exec> explicit parameter lists instead of strings with possible shellwildcards in them.  Unfortunately, the C<open>, C<glob>, andbacktick functions provide no such alternate calling convention, so moresubterfuge will be required.Perl provides a reasonably safe way to open a file or pipe from a setuidor setgid program: just create a child process with reduced privilege whodoes the dirty work for you.  First, fork a child using the specialC<open> syntax that connects the parent and child by a pipe.  Now thechild resets its ID set and any other per-process attributes, likeenvironment variables, umasks, current working directories, back to theoriginals or known safe values.  Then the child process, which no longerhas any special permissions, does the C<open> or other system call.Finally, the child passes the data it managed to access back to theparent.  Because the file or pipe was opened in the child while runningunder less privilege than the parent, it's not apt to be tricked intodoing something it shouldn't.Here's a way to do backticks reasonably safely.  Notice how the C<exec> isnot called with a string that the shell could expand.  This is by far thebest way to call something that might be subjected to shell escapes: justnever call the shell at all.          use English '-no_match_vars';        die "Can't fork: $!" unless defined($pid = open(KID, "-|"));        if ($pid) {           # parent            while (<KID>) {                # do something            }            close KID;        } else {            my @temp     = ($EUID, $EGID);            my $orig_uid = $UID;            my $orig_gid = $GID;            $EUID = $UID;            $EGID = $GID;            # Drop privileges            $UID  = $orig_uid;            $GID  = $orig_gid;            # Make sure privs are really gone            ($EUID, $EGID) = @temp;            die "Can't drop privileges"                unless $UID == $EUID  && $GID eq $EGID;            $ENV{PATH} = "/bin:/usr/bin"; # Minimal PATH.	    # Consider sanitizing the environment even more.            exec 'myprog', 'arg1', 'arg2'                or die "can't exec myprog: $!";        }A similar strategy would work for wildcard expansion via C<glob>, althoughyou can use C<readdir> instead.Taint checking is most useful when although you trust yourself not to havewritten a program to give away the farm, you don't necessarily trust thosewho end up using it not to try to trick it into doing something bad.  Thisis the kind of security checking that's useful for set-id programs andprograms launched on someone else's behalf, like CGI programs.This is quite different, however, from not even trusting the writer of thecode not to try to do something evil.  That's the kind of trust neededwhen someone hands you a program you've never seen before and says, "Here,run this."  For that kind of safety, check out the Safe module,included standard in the Perl distribution.  This module allows theprogrammer to set up special compartments in which all system operationsare trapped and namespace access is carefully controlled.=head2 Security BugsBeyond the obvious problems that stem from giving special privileges tosystems as flexible as scripts, on many versions of Unix, set-id scriptsare inherently insecure right from the start.  The problem is a racecondition in the kernel.  Between the time the kernel opens the file tosee which interpreter to run and when the (now-set-id) interpreter turnsaround and reopens the file to interpret it, the file in question may havechanged, especially if you have symbolic links on your system.Fortunately, sometimes this kernel "feature" can be disabled.Unfortunately, there are two ways to disable it.  The system can simplyoutlaw scripts with any set-id bit set, which doesn't help much.Alternately, it can simply ignore the set-id bits on scripts.  If thelatter is true, Perl can emulate the setuid and setgid mechanism when itnotices the otherwise useless setuid/gid bits on Perl scripts.  It doesthis via a special executable called F<suidperl> that is automaticallyinvoked for you if it's needed.However, if the kernel set-id script feature isn't disabled, Perl willcomplain loudly that your set-id script is insecure.  You'll need toeither disable the kernel set-id script feature, or put a C wrapper aroundthe script.  A C wrapper is just a compiled program that does nothingexcept call your Perl program.   Compiled programs are not subject to thekernel bug that plagues set-id scripts.  Here's a simple wrapper, writtenin C:    #define REAL_PATH "/path/to/script"    main(ac, av)	char **av;    {	execv(REAL_PATH, av);    }Compile this wrapper into a binary executable and then make I<it> ratherthan your script setuid or setgid.In recent years, vendors have begun to supply systems free of thisinherent security bug.  On such systems, when the kernel passes the nameof the set-id script to open to the interpreter, rather than using apathname subject to meddling, it instead passes I</dev/fd/3>.  This is aspecial file already opened on the script, so that there can be no racecondition for evil scripts to exploit.  On these systems, Perl should becompiled with C<-DSETUID_SCRIPTS_ARE_SECURE_NOW>.  The F<Configure>program that builds Perl tries to figure this out for itself, so youshould never have to specify this yourself.  Most modern releases ofSysVr4 and BSD 4.4 use this approach to avoid the kernel race condition.Prior to release 5.6.1 of Perl, bugs in the code of F<suidperl> couldintroduce a security hole.=head2 Protecting Your ProgramsThere are a number of ways to hide the source to your Perl programs,with varying levels of "security".First of all, however, you I<can't> take away read permission, becausethe source code has to be readable in order to be compiled andinterpreted.  (That doesn't mean that a CGI script's source isreadable by people on the web, though.)  So you have to leave thepermissions at the socially friendly 0755 level.  This lets people on your local system only see your source.Some people mistakenly regard this as a security problem.  If your program doesinsecure things, and relies on people not knowing how to exploit thoseinsecurities, it is not secure.  It is often possible for someone todetermine the insecure things and exploit them without viewing thesource.  Security through obscurity, the name for hiding your bugsinstead of fixing them, is little security indeed.You can try using encryption via source filters (Filter::* from CPAN,or Filter::Util::Call and Filter::Simple since Perl 5.8).But crackers might be able to decrypt it.  You can try using the bytecode compiler and interpreter described below, but crackers might beable to de-compile it.  You can try using the native-code compilerdescribed below, but crackers might be able to disassemble it.  Thesepose varying degrees of difficulty to people wanting to get at yourcode, but none can definitively conceal it (this is true of everylanguage, not just Perl).If you're concerned about people profiting from your code, then thebottom line is that nothing but a restrictive licence will give youlegal security.  License your software and pepper it with threateningstatements like "This is unpublished proprietary software of XYZ Corp.Your access to it does not give you permission to use it blah blahblah."  You should see a lawyer to be sure your licence's wording willstand up in court.=head2 UnicodeUnicode is a new and complex technology and one may easily overlookcertain security pitfalls.  See L<perluniintro> for an overview andL<perlunicode> for details, and L<perlunicode/"Security Implicationsof Unicode"> for security implications in particular.=head2 Algorithmic Complexity AttacksCertain internal algorithms used in the implementation of Perl canbe attacked by choosing the input carefully to consume large amountsof either time or space or both.  This can lead into the so-calledI<Denial of Service> (DoS) attacks.=over 4=item *Hash Function - the algorithm used to "order" hash elements has beenchanged several times during the development of Perl, mainly to bereasonably fast.  In Perl 5.8.1 also the security aspect was takeninto account.In Perls before 5.8.1 one could rather easily generate data that ashash keys would cause Perl to consume large amounts of time becauseinternal structure of hashes would badly degenerate.  In Perl 5.8.1the hash function is randomly perturbed by a pseudorandom seed whichmakes generating such naughty hash keys harder.See L<perlrun/PERL_HASH_SEED> for more information.The random perturbation is done by default but if one wants for somereason emulate the old behaviour one can set the environment variablePERL_HASH_SEED to zero (or any other integer).  One possible reasonfor wanting to emulate the old behaviour is that in the new behaviourconsecutive runs of Perl will order hash keys differently, which mayconfuse some applications (like Data::Dumper: the outputs of twodifferent runs are no more identical).B<Perl has never guaranteed any ordering of the hash keys>, and theordering has already changed several times during the lifetime ofPerl 5.  Also, the ordering of hash keys has always been, andcontinues to be, affected by the insertion order.Also note that while the order of the hash elements might berandomised, this "pseudoordering" should B<not> be used forapplications like shuffling a list randomly (use List::Util::shuffle()for that, see L<List::Util>, a standard core module since Perl 5.8.0;or the CPAN module Algorithm::Numerical::Shuffle), or for generatingpermutations (use e.g. the CPAN modules Algorithm::Permute orAlgorithm::FastPermute), or for any cryptographic applications.=item *Regular expressions - Perl's regular expression engine is so called NFA(Non-deterministic Finite Automaton), which among other things means thatit can rather easily consume large amounts of both time and space if theregular expression may match in several ways.  Careful crafting of theregular expressions can help but quite often there really isn't muchone can do (the book "Mastering Regular Expressions" is requiredreading, see L<perlfaq2>).  Running out of space manifests itself byPerl running out of memory.=item *Sorting - the quicksort algorithm used in Perls before 5.8.0 toimplement the sort() function is very easy to trick into misbehavingso that it consumes a lot of time.  Nothing more is required thanresorting a list already sorted.  Starting from Perl 5.8.0 a differentsorting algorithm, mergesort, is used.  Mergesort is insensitive toits input data, so it cannot be similarly fooled.=backSee L<http://www.cs.rice.edu/~scrosby/hash/> for more information,and any computer science textbook on the algorithmic complexity.=head1 SEE ALSOL<perlrun> for its description of cleaning up environment variables.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -