title: Considerations for a setuid wrapper
body: <p>A Python extension I've written requires root access to do a single hardware initialisation call. I'd rather not run the whole script as root just for this one call in my extension, so I would like to write a wrapper to do this initialisation before dropping to user privileges and running the actual script.</p>
  
  <p>I intend for this wrapper to be run via <code>sudo</code>, eg</p>
  
  <pre><code>$ sudo devwrap python somescript.py
  </code></pre>
  
  <p>I was considering something like (<em>updated to fix a couple of bugs</em>):</p>
  
  <pre><code>int main(int argc, char * argv[])
  {
    if(argc &lt; 2) return 0;
  
    int res = do_hardware_init();
    if(res != OK_VALUE)
    {
      // Print error message
      return HW_ERR;
    }
  
    const char *sudo_uid = getenv("SUDO_UID");
    if(sudo_uid)
    {
        int real_uid = (int) strtol(sudo_uid, NULL, 0);
        setuid(real_uid);
    }
  
    return execvp(argv[1], &amp;argv[1]); // No return if successful
  
  }
  </code></pre>
  
  <p>So I have three questions:</p>
  
  <ol>
  <li>Does this look sane? I don't usually need to mess with the *uid() calls, so I'm not familiar with the usual pitfalls. The <code>execvp</code> call also looks a little bizarre, but as far as I can see it has arguments in the right place).</li>
  <li>The <code>execvp</code> man page says that <em>"The environ array should not be accessed directly by the application"</em> - does this make the <code>getenv</code> call a bad idea?</li>
  <li>Is there a better call than <code>execvp</code>, so I can do <code>sudo devwrap somescript.py</code> (note absence of "python")</li>
  </ol>