title: Debugging a setuid program / "Permission denied" with setuid
body: <p>This is actually a three-part question, which I'll explain below, but the questions are:</p>
  
  <ul>
  <li>Using gdb, how can I run part of a program with root authority, and the rest with normal?</li>
  <li>Why would I get "permission denied" using mkstemp to create a file in /tmp
          in a setuid (to root) program?</li>
  <li>Why would "sudo program_name" perform any differently from just ./program_name with setuid to root?</li>
  </ul>
  
  <p>I have a C program running on Linux (multiple distributions) that normally is run by a user with normal privileges, but some parts of the program must run with root authority.  For this, I have used the set-UID flag, and that works fine, as far as it goes.</p>
  
  <p>However, now I would like to debug the program with normal user authority, and I find I have a catch-22.  I have just added a function to create a temporary file (/tmp/my_name-XXXXXX), and that function is called from many points within the program.  For whatever reason, this function issues the following message when running:</p>
  
  <pre><code>sh: /tmp/my_name-hhnNuM: Permission denied
  </code></pre>
  
  <p>(of course, the actual name varies.)  And yet, the program is able to execute raw socket function that I absolutely know cannot be done by users other than root.  (If I remove the setuid flag, the program fails miserably.)</p>
  
  <p>If I run this program via gdb without sudo, it dies on the raw socket stuff (since gdb apparently doesn't --or probably cannot-- honor the setuid flag on the program).  If I run it under "sudo gdb" then everything works fine.  If I run it as "sudo ./my_name, everything works fine.</p>
  
  <p>Here is the ls -l output for that program:</p>
  
  <pre><code>-rwsr-xr-x 1 root root 48222 Jun 23 08:14 my_name
  </code></pre>
  
  <p>So my questions, in no particular order:</p>
  
  <ul>
  <li>(How) can I run different parts of a program with different effective UID under gdb?</li>
  <li>Why is "sudo ./program" different from "./program" when ./program has set-uid to root?</li>
  <li>Why would mkstemp fail when called by a normal user in a setuid (to root) program?</li>
  </ul>