aboutsummaryrefslogtreecommitdiff
path: root/server.c
blob: c1c664c846676184f49b1da1d064fbfff3a07d94 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
/*
 * Copyright (c) 2012 Kyle Isom <kyle@tyrfingr.is>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */


#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netinet/in.h>
#ifdef _BSD_SOURCE                  /* _BSD_SOURCE is only defined on */
#include <bsd/string.h>             /* linux hosts, we need to use the */
#endif                              /* BSD string library */

#include <err.h>
#include <grp.h>
#include <pwd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
#include <time.h>
#include <unistd.h>

#include "server.h"

#include "request.h"
#include "srvwd.h"


static time_t           last_interrupt;

static void      sigchld_handler(int);
static void      sigint_handler(int);


/*
 * reap child processes
 */
void
sigchld_handler(int sig)
{
    sig = 0;      /* we don't need s, but all sig handlers need s */
    while (waitpid(-1, NULL, WNOHANG) > 0) ;
}


/*
 * determine an appropriate response to SIGINT
 */
void
sigint_handler(int sig)
{
    time_t this_interrupt;
    sig = 0;

    /* clever ruse to work around the -Wunused-variables error */
    print_downloads = 1;

    this_interrupt = time(NULL);
    if ((this_interrupt - last_interrupt) < 3)
        shutdown_server = 1;
    else
        last_interrupt = this_interrupt;
}


/*
 * chroot to the target directory and drop privileges.
 */
int
init_srvwd(char *path, char *user, char *group)
{
    int i;
    uid_t uid;

    uid = getuid();

    if (server_chroot && 0 != uid)
        errx(EX_NOPERM, "chroot(2) requires root privileges.");

    for (i = 0; i < (PATH_MAX + 1); ++i)
        server_root[i] = '\0';

   if (-1 == get_credentials(user, group, &_uid, &_gid))
        warnx("failed to set proper credentials!");

    if (-1 == chdir(path))
        err(EX_DATAERR, "invalid work dir %s", path);

    if (server_chroot) {
        if (0 != chroot(path)) {
            err(EX_OSERR, "chroot failed");
        } else
            printf("[+] chroot to %s\n", path);
    }

    if (NULL == getcwd(server_root, SRVWD_ROOT_LEN))
        errx(EX_OSERR, "failed to get current working directory!");

    if (0 == strncmp(server_root, "/", 2))
        server_root[0] = '\0';
 
    if ((-1 == setregid(_gid, _gid)) || (-1 == setreuid(_uid, _uid)))
        err(EX_OSERR, "failed to set permissions properly!");

    printf("[+] running as uid: %u\tgid: %u\n",
            (unsigned int)getuid(),
            (unsigned int)getgid());
    return EX_OK;
}


/*
 * given the user and group names, set the uid and gid to the appropriate
 * values. this is used for privilege dropping.
 *
 * returns EX_OK on success, or a sysexits(3) error otherwise. a return value
 * other than EX_OK means the uid and gid variables have not been changed.
 */
int
get_credentials(char *user, char *group, uid_t *uid, gid_t *gid)
{
    struct passwd *pwd; 
    struct group  *grp;
    int res;
    uid_t temp_uid = UINT_MAX;
    gid_t temp_gid = UINT_MAX;

    res = EX_OSERR;

    pwd = getpwnam(user);
    if (NULL == pwd)
        warnx("user not found");
    else {
        res = EX_OK;
        temp_uid = pwd->pw_uid;
    }

    grp = getgrnam(group);
    if (NULL == grp) {
        res = EX_OSERR;
        warnx("group not found");
    } else
        temp_gid = grp->gr_gid;

    if (EX_OK == res) {
        *uid = temp_uid;
        *gid = temp_gid;
    }
    return res;
}


/*
 * set up listener socket.
 *
 * returns socket file descriptor.
 */
int
init_socket(uint16_t port)
{
    int sockfd;
    int yes;
    struct sockaddr_in saddr;
    struct sigaction sa;

    memset(saddr.sin_zero, '\0', sizeof saddr.sin_zero);
    saddr.sin_family = AF_INET;
    saddr.sin_port   = htons(port);
    saddr.sin_addr.s_addr = INADDR_ANY;

    yes = 1;
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (-1 == sockfd)
        err(EX_OSERR, "failed to create socket");

    if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, 
                   sizeof(int)) == -1) {
        err(EX_OSERR, "failed to set socket to reuse address");
    } 
    if (-1 == bind(sockfd, (struct sockaddr *)&saddr, 
                   (socklen_t)sizeof saddr)) {
        warn("failed to bind!");
        close(sockfd);
        return -1;
    }
    
    sa.sa_handler = sigchld_handler;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;

    if (sigaction(SIGCHLD, &sa, NULL) == -1) 
        err(EX_OSERR, "failed to set handler for SIGCHLD");

    sa.sa_handler = sigint_handler;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;

    if (sigaction(SIGINT, &sa, NULL) == -1)
        err(EX_OSERR, "failed to set handler for SIGINT");

    printf("[+] listening on %u\n", ntohs(saddr.sin_port));

    return sockfd;
}


/*
 * start listening for incoming requests. returns 
 */
int
run_server(int sockfd, int listeners)
{
    struct sockaddr_in client_addr;
    int i, sin_size, clientfd;
    int res = EXIT_FAILURE;
    pid_t parent;

    if (-1 == listen(sockfd, SRVWD_BACKLOG)) {
        warn("listen failed");
        return res;
    }

   
    printf("[+] listening for new connections...\n");

    /* spawn any additional listeners */
    parent = getpid();
    for (i = 0; i < listeners - 1; ++i)
        if (!fork())
            break;

    while (1) {
        clientfd = accept(sockfd, (struct sockaddr *)&client_addr, 
                          (socklen_t *)&sin_size);
        if (clientfd > 0 && !fork()) {
            close(sockfd);
            request_handler(clientfd, &client_addr);
            shutdown(clientfd, SHUT_RDWR);
            close(clientfd);
            _exit(EX_OK);
        } else
            close(clientfd);

        if (getppid() == getpid() && print_downloads) {
            printf("[!] download count not implemented yet\n");
            print_downloads = 0;
        }

        if (shutdown_server) {
            res = EX_OK;

            /* kill off child processes */
            if (getpid() != parent) {
                while ((waitpid(-1, NULL, WNOHANG)) > 0);
                _exit(EX_OK);
            } else {
                printf("\n[+] shutting down server...\n");
                while ((waitpid(-1, NULL, WNOHANG)) > 0);
                break;
            }
        }
    }
  
   return res; 
}