root/regress/sys/kern/setuid/setegid.c
/*      $OpenBSD: setegid.c,v 1.3 2021/12/15 18:42:38 anton Exp $       */
/*
 *      Written by Bret Stephen Lambert <blambert@openbsd.org> 2014
 *      Public Domain.
 */

#include <sys/types.h>
#include <sys/signal.h>
#include <sys/proc.h>
#include <sys/sysctl.h>
#include <sys/wait.h>

#include <err.h>
#include <stdio.h>
#include <stdlib.h>
#include <pwd.h>
#include <unistd.h>

#include "setuid_regress.h"

int
main(int argc, const char *argv[])
{
        struct kinfo_proc        kproc;
        struct passwd           *pw;
        gid_t                    gid;

        gid = getgid();

        if ((pw = getpwnam(_SETUID_REGRESS_USER)) == NULL)
                err(1, "unknown user \"%s\"", _SETUID_REGRESS_USER);

        if (setegid(pw->pw_gid) == -1)
                err(1, "setegid 0");

        if (getegid() != pw->pw_gid)
                errx(1, "mismatched effective gids");

        /* should only respond to setuid upon exec */
        if (issetugid())
                errx(1, "process incorrectly marked as issetugid()");

        if (read_kproc_pid(&kproc, getpid()) == -1)
                err(1, "kproc read 0 failed");

        if (!(kproc.p_psflags & PS_SUGID))
                errx(1, "PS_SUGID not set");
        if (kproc.p_psflags & PS_SUGIDEXEC)
                errx(1, "PS_SUGIDEXEC incorrectly set");

        /* at this point, we should be able to reset our gid */
        if (setegid(gid) == -1)
                err(1, "setegid 1");

        if (read_kproc_pid(&kproc, getpid()) == -1)
                err(1, "kproc read 0 failed");

        if (!(kproc.p_psflags & PS_SUGID))
                errx(1, "PS_SUGID not set");
        if (kproc.p_psflags & PS_SUGIDEXEC)
                errx(1, "PS_SUGIDEXEC incorrectly set");

        exit(0);
}