• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *   Copyright (c) International Business Machines  Corp., 2004
4  *      07/2004 Written by Dan Jones
5  *      07/2004 Ported to LTP format by Robbie Williamson
6  *   Copyright (c) 2019 Martin Doucha <mdoucha@suse.cz>
7  */
8 
9 /*
10  * Test Description:
11  *  Make sure bind() of privileged port gives EACCESS error for non-root users.
12  */
13 
14 #include <string.h>
15 #include <unistd.h>
16 #include <pwd.h>
17 #include <grp.h>
18 
19 #include <sys/types.h>
20 #include <sys/socket.h>
21 #include <netinet/in.h>
22 
23 #include "tst_test.h"
24 
25 /* This port needs to be a privileged port */
26 #define TCP_PRIVILEGED_PORT 463
27 #define TEST_USERNAME "nobody"
28 
run(void)29 static void run(void)
30 {
31 	struct sockaddr_in servaddr;
32 	int sockfd;
33 
34 	sockfd = SAFE_SOCKET(AF_INET, SOCK_STREAM, 0);
35 	memset(&servaddr, 0, sizeof(servaddr));
36 	servaddr.sin_family = AF_INET;
37 	servaddr.sin_port = htons(TCP_PRIVILEGED_PORT);
38 	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
39 	TST_EXP_FAIL(bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)),
40 	             EACCES, "bind()");
41 	SAFE_CLOSE(sockfd);
42 }
43 
setup(void)44 static void setup(void)
45 {
46 	struct passwd *pw;
47 	struct group *gr;
48 
49 	pw = SAFE_GETPWNAM(TEST_USERNAME);
50 	gr = SAFE_GETGRGID(pw->pw_gid);
51 
52 	tst_res(TINFO, "Switching credentials to user: %s, group: %s",
53 		pw->pw_name, gr->gr_name);
54 	SAFE_SETEGID(gr->gr_gid);
55 	SAFE_SETEUID(pw->pw_uid);
56 }
57 
58 static struct tst_test test = {
59 	.test_all = run,
60 	.needs_root = 1,
61 	.setup = setup,
62 };
63