Files
mars_nwe_pcab/tests/test_identity.c

16 lines
2.5 KiB
C

#define _GNU_SOURCE
#include "identity.h"
#include <assert.h>
#include <pwd.h>
#include <grp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <errno.h>
#include <sys/wait.h>
#include <fcntl.h>
static void file_rights(const struct mars_identity *a,const struct mars_identity *b){if(geteuid()!=0){puts("SKIP kernel UID permission test (not root)");return;}char dir[]="/tmp/mars-identity-rights-XXXXXX",file[512];assert(mkdtemp(dir));assert(!chmod(dir,0755));snprintf(file,sizeof file,"%s/private",dir);int fd=open(file,O_WRONLY|O_CREAT|O_EXCL,0600);assert(fd>=0);assert(!fchown(fd,a->uid,a->uid));close(fd);const struct mars_identity *ids[]={a,b};for(int j=0;j<2;j++){pid_t pid=fork();assert(pid>=0);if(!pid){assert(!initgroups(ids[j]->alias,ids[j]->uid));assert(!setgid(ids[j]->uid)&&!setuid(ids[j]->uid));int f=open(file,O_RDONLY);if(j==0)assert(f>=0);else assert(f<0&&errno==EACCES);if(f>=0)close(f);_exit(0);}int st;assert(waitpid(pid,&st,0)==pid&&WIFEXITED(st)&&WEXITSTATUS(st)==0);}unlink(file);rmdir(dir);puts("PASS actual kernel UID-based file permission separation");}
int main(void){unlink(MARS_ID_DB);struct mars_identity a,b,c;assert(mars_id_lookup("marsv200000000",0,&c)==1);assert(mars_id_reserve("SUPERVISOR",&c));assert(mars_id_reserve("alice",&c));assert(!mars_id_reserve("ALICE",&a));assert(!mars_id_reserve("BOB",&b));assert(a.uid>=MARS_UID_FIRST&&b.uid>a.uid);assert(!mars_id_lookup(NULL,a.uid,&c)&&!strcmp(c.name,"ALICE"));struct passwd *p=getpwnam(a.alias);assert(p&&p->pw_uid==(uid_t)a.uid&&p->pw_gid==(gid_t)a.uid&&!strcmp(p->pw_passwd,"!")&&!strcmp(p->pw_shell,"/usr/sbin/nologin"));p=getpwuid(b.uid);assert(p&&!strcmp(p->pw_name,b.alias));struct passwd st,*r=NULL;char buf[512];assert(getpwnam_r(a.alias,&st,buf,2,&r)==ERANGE&&!r);assert(!getpwnam_r(a.alias,&st,buf,sizeof buf,&r)&&r&&r->pw_uid==(uid_t)a.uid);struct group *g=getgrgid(a.uid);assert(g&&g->gr_gid==(gid_t)a.uid&&g->gr_mem&&!g->gr_mem[0]);int n=1;gid_t gs[1];assert(getgrouplist(a.alias,a.uid,gs,&n)==1&&gs[0]==(gid_t)a.uid);assert(getpwnam("root")&&getpwnam("root")->pw_uid==0);struct stat f;assert(!stat(MARS_ID_DB,&f)&&(f.st_mode&0777)==0644);assert(!chmod(MARS_ID_DB,0666));assert(!getpwnam(a.alias));assert(!chmod(MARS_ID_DB,0644));file_rights(&a,&b);assert(!mars_id_reserve("ALICE",&c)&&c.uid>b.uid);unlink(MARS_ID_DB);assert(!symlink("/etc/passwd",MARS_ID_DB));assert(mars_id_reserve("ALICE",&c));unlink(MARS_ID_DB);puts("PASS virtual UID/GID allocation, persistence, libc lookups, groups, permission and symlink rejection, no reuse");return 0;}