• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  This program is free software; you can redistribute it and/or modify
3  *  it under the terms of the GNU General Public License version 2.
4  *
5  *  This program is distributed in the hope that it will be useful,
6  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
7  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
8  *  GNU General Public License for more details.
9  *
10  * Test that the mlock() function sets errno = EPERM if the calling process
11  * does not have the appropriate privilege to perform the requested operation
12  * (Linux 2.6.9 and later) and its RLIMIT_MEMLOCK soft resource limit set to 0.
13  */
14 
15 #define _XOPEN_SOURCE 600
16 
17 #include <sys/mman.h>
18 #include <stdio.h>
19 #include <unistd.h>
20 #include <stdlib.h>
21 #include <errno.h>
22 #include <sys/types.h>
23 #include <pwd.h>
24 #include <string.h>
25 #include <sys/resource.h>
26 #include "posixtest.h"
27 
28 #define BUFSIZE 8
29 
30 /** Set the euid of this process to a non-root uid */
set_nonroot()31 int set_nonroot()
32 {
33 	struct passwd *pw;
34 	struct rlimit rlim;
35 	int ret = 0;
36 
37 	setpwent();
38 	/* search for the first user which is non root */
39 	while ((pw = getpwent()) != NULL)
40 		if (strcmp(pw->pw_name, "root"))
41 			break;
42 	endpwent();
43 	if (pw == NULL) {
44 		printf("There is no other user than current and root.\n");
45 		return 1;
46 	}
47 
48 	/*
49 	 * mlock()
50 	 * EPERM:
51 	 * (Linux 2.6.9 and later) the caller was not privileged (CAP_IPC_LOCK)
52 	 * and its RLIMIT_MEMLOCK soft resource limit was 0.
53 	 */
54 
55 	rlim.rlim_cur = 0;
56 	rlim.rlim_max = 0;
57 	if ((ret = setrlimit(RLIMIT_MEMLOCK, &rlim)) != 0)
58 		printf("Failed at setrlimit() return %d \n", ret);
59 
60 	if (seteuid(pw->pw_uid) != 0) {
61 		if (errno == EPERM) {
62 			printf
63 			    ("You don't have permission to change your UID.\n");
64 			return 1;
65 		}
66 		perror("An error occurs when calling seteuid()");
67 		return 1;
68 	}
69 
70 	printf("Testing with user '%s' (uid: %d)\n",
71 	       pw->pw_name, (int)geteuid());
72 	return 0;
73 }
74 
main(void)75 int main(void)
76 {
77 	int result;
78 	void *ptr;
79 
80 	/* This test should be run under standard user permissions */
81 	if (getuid() == 0) {
82 		if (set_nonroot() != 0) {
83 			printf("Cannot run this test as non-root user\n");
84 			return PTS_UNTESTED;
85 		}
86 	}
87 
88 	ptr = malloc(BUFSIZE);
89 	if (ptr == NULL) {
90 		printf("Can not allocate memory.\n");
91 		return PTS_UNRESOLVED;
92 	}
93 
94 	result = mlock(ptr, BUFSIZE);
95 
96 	if (result == -1 && errno == EPERM) {
97 		printf("Test PASSED\n");
98 		return PTS_PASS;
99 	} else if (result == 0) {
100 		printf("You have the right to call mlock\n");
101 		return PTS_FAIL;
102 	} else {
103 		perror("Unexpected error");
104 		return PTS_UNRESOLVED;
105 	}
106 
107 }
108