• 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 
16 #include <sys/mman.h>
17 #include <stdio.h>
18 #include <unistd.h>
19 #include <stdlib.h>
20 #include <errno.h>
21 #include <sys/types.h>
22 #include <pwd.h>
23 #include <string.h>
24 #include <sys/resource.h>
25 #include "posixtest.h"
26 
27 #define BUFSIZE 8
28 
29 /** Set the euid of this process to a non-root uid */
set_nonroot()30 static int set_nonroot()
31 {
32 	struct passwd *pw;
33 	struct rlimit rlim;
34 	int ret = 0;
35 
36 	setpwent();
37 	/* search for the first user which is non root */
38 	while ((pw = getpwent()) != NULL)
39 		if (strcmp(pw->pw_name, "root"))
40 			break;
41 	endpwent();
42 	if (pw == NULL) {
43 		printf("There is no other user than current and root.\n");
44 		return 1;
45 	}
46 
47 	/*
48 	 * mlock()
49 	 * EPERM:
50 	 * (Linux 2.6.9 and later) the caller was not privileged (CAP_IPC_LOCK)
51 	 * and its RLIMIT_MEMLOCK soft resource limit was 0.
52 	 */
53 
54 	rlim.rlim_cur = 0;
55 	rlim.rlim_max = 0;
56 	if ((ret = setrlimit(RLIMIT_MEMLOCK, &rlim)) != 0)
57 		printf("Failed at setrlimit() return %d \n", ret);
58 
59 	if (seteuid(pw->pw_uid) != 0) {
60 		if (errno == EPERM) {
61 			printf
62 			    ("You don't have permission to change your UID.\n");
63 			return 1;
64 		}
65 		perror("An error occurs when calling seteuid()");
66 		return 1;
67 	}
68 
69 	printf("Testing with user '%s' (uid: %d)\n",
70 	       pw->pw_name, (int)geteuid());
71 	return 0;
72 }
73 
main(void)74 int main(void)
75 {
76 	int result;
77 	void *ptr;
78 
79 	/* This test should be run under standard user permissions */
80 	if (getuid() == 0) {
81 		if (set_nonroot() != 0) {
82 			printf("Cannot run this test as non-root user\n");
83 			return PTS_UNTESTED;
84 		}
85 	}
86 
87 	ptr = malloc(BUFSIZE);
88 	if (ptr == NULL) {
89 		printf("Can not allocate memory.\n");
90 		return PTS_UNRESOLVED;
91 	}
92 
93 	result = mlock(ptr, BUFSIZE);
94 
95 	if (result == -1 && errno == EPERM) {
96 		printf("Test PASSED\n");
97 		return PTS_PASS;
98 	} else if (result == 0) {
99 		printf("You have the right to call mlock\n");
100 		return PTS_FAIL;
101 	} else {
102 		perror("Unexpected error");
103 		return PTS_UNRESOLVED;
104 	}
105 
106 }
107