I've got a Perl script that's known as either via Apache or around the command-line.

For testing reasons, I pass it the username I would like the Perl script to function with, and employ POSIX::setuid to create the uid.

Basically run the script in the command line, then your uid is placed correctly:

use CGI::Pretty qw/:standard/;
use POSIX qw(setuid getuid);

...
my ($pwName, $pwCode, $pwUid, $pwGid, $pwQuota, $pwComment, 
    $pwGcos, $pwHome, $pwLogprog) = getpwnam($username);

if ((defined $pwUid) && (getuid() == $pwUid)) {
    setuid($pwUid);
    print header;
    print Dumper $<;
}
else {
    print header(-status => 401);
    print "Could not setuid to correct uid (currently: )".getuid()."\n";
}

The command-line output shows the right uid from the specified $username, rather than the uid from the test account that began running the script.

Basically call the script via Apache, then your uid remains set towards the id from the apache user, rather than changes.

I do not believe I'm able to use suExec here, because, after reading through the documentation:

  1. I can not put a duplicate of the script into http://www.example.com/~username for each $username. The script must run in one location, and I have to specify the uid from inside the script.

  2. I have to possess the script run because the specified username at runtime, and never like a single username specified occasionally virtual host directive within an Apache configuration file. Altering this configuration file and restarting Apache whenever a new user runs this script isn't realistic.

How do you obtain a Perl script running like a cgi-bin to alter the uid properly, when utilizing setuid()?

The only method you are able to setuid for an arbitrary uid would be to run as root.[1]

I'm not sure in regards to you, but the thought of a CGI program running as root provides me with bad dreams.

What's this code designed to really do after altering uid? Possibly there's a method to make this happen without needing to setuid?

[1] Based on your code and it is security model, you might have the ability to collect anyone's password and employ su/sudo[2] to operate another command-line program to operate the particular procedures outdoors from the web server atmosphere, but su/sudo can do this because they are suid root also it would still open most/all the issues connected with running CGI code as root anyhow. Even when you remove root being an invalid username, having the ability to masquerade every arbitrary user reveals lots of possibilities for abuse.

[2] sudo can also be set up to permit it without needing your password, but there be dragons lower that path. Make sure guess what happens you are doing should you attempt it, lest you allow your customers free reign to impersonate one another when needed.