File: system.cpp

package info (click to toggle)
cyphesis-cpp 0.5.16-1
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 5,084 kB
  • ctags: 3,627
  • sloc: cpp: 30,418; python: 4,812; xml: 4,674; sh: 4,118; makefile: 902; ansic: 617
file content (587 lines) | stat: -rw-r--r-- 16,174 bytes parent folder | download
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
// Cyphesis Online RPG Server and AI Engine
// Copyright (C) 2000-2004 Alistair Riddoch
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

// $Id: system.cpp,v 1.34 2008-04-19 03:44:07 alriddoch Exp $

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "system.h"

#include "log.h"
#include "debug.h"
#include "globals.h"
#include "compose.hpp"

#include <wfmath/MersenneTwister.h>

#include <gcrypt.h>

#include <iostream>

#include <sys/stat.h>

#include <cassert>

extern "C" {
#ifdef HAVE_SYS_UTSNAME_H
    #include <sys/utsname.h>
#endif // HAVE_SYS_UTSNAME_H
    #include <sys/types.h>
#ifdef HAVE_WINSOCK_H
    #undef DATADIR
    #include <winsock.h>
#endif // HAVE_WINSOCK_H
#ifdef HAVE_SYS_WAIT_H
    #include <sys/wait.h>
#endif // HAVE_SYS_WAIT_H
    #include <signal.h>
    #include <fcntl.h>
    #include <unistd.h>
    #include <stdio.h>
}

static const bool debug_flag = false;

const std::string get_hostname()
{
#ifndef HAVE_UNAME
    char hostname_buf[256];

    if (gethostname(hostname_buf, 256) != 0) {
        return "UNKNOWN";
    }
    return std::string(hostname_buf);
#else // HAVE_UNAME
    struct utsname host_ident;
    if (uname(&host_ident) != 0) {
        return "UNKNOWN";
    }
    return std::string(host_ident.nodename);
#endif // HAVE_UNAME
}

unsigned int security_check()
{
#ifdef HAVE_GETUID
    if (getuid() == 0 || geteuid() == 0) {
        log(CYLOG_ERROR, "Running cyphesis as the superuser is dangerous.");
        return 0;
    }
#endif // HAVE_GETUID
    return SECURITY_OKAY;
}

static int security_new_key(const std::string & key_filename)
{
    FILE * key_file = ::fopen(key_filename.c_str(), "wx");

    if (key_file == 0) {
        log(CRITICAL, String::compose("Unable to open file %1 to store server"
                                      " identity", key_filename));
        return -1;
    }

    gcry_check_version(0);
    gcry_control( GCRYCTL_INIT_SECMEM, 16384, 0 );

    gcry_sexp_t key_parameters, key;

    gcry_error_t ret = gcry_sexp_build(&key_parameters, 0,
                                       "(genkey(dsa(nbits %d)))", 1024);

    if (gcry_err_code(ret) != GPG_ERR_NO_ERROR) {
        std::cout << "SEXP FAIL" << std::endl << std::flush;
    }

    ret = gcry_pk_genkey(&key, key_parameters);

    if (gcry_err_code(ret) != GPG_ERR_NO_ERROR) {
        std::cout << "GENKEY FAIL" << std::endl << std::flush;
        return -1;
    }

    gcry_sexp_release(key_parameters);

    ret = gcry_pk_testkey(key);

    if (gcry_err_code(ret) != GPG_ERR_NO_ERROR) {
        std::cout << "TESTKEY FAIL" << std::endl << std::flush;
        return -1;
    }

    size_t ktxtlen = gcry_sexp_sprint(key, GCRYSEXP_FMT_CANON, 0, 0);
    char * key_text = new char[ktxtlen];
    gcry_sexp_sprint(key, GCRYSEXP_FMT_CANON, key_text, ktxtlen);

    fwrite(key_text, ktxtlen, 1, key_file);

    fclose(key_file);

    // gcry_sexp_dump(key);
    gcry_sexp_release(key);

    return 0;
}

static int security_load_key(const std::string & key_filename, size_t len)
{
    FILE * key_file = ::fopen(key_filename.c_str(), "r");

    if (key_file == 0) {
        log(CRITICAL, String::compose("Unable to open file %1 to read server"
                                      " identity", key_filename));
        perror("ARSE!");
        return -1;
    }

    char * key_text = new char[len];

    size_t records = fread(key_text, len, 1, key_file);
    if (records != 1) {
        log(CRITICAL, String::compose("Unable to load identity information"
                                      " from file %1", key_filename));
        return -1;
    }

    gcry_sexp_t key;

    gcry_error_t ret = gcry_sexp_new(&key, key_text, len, 0);

    if (gcry_err_code(ret) != GPG_ERR_NO_ERROR) {
        log(CRITICAL, String::compose("Malformed identity information"
                                      " from file %1", key_filename));
        return -1;
    }

    ret = gcry_pk_testkey(key);

    if (gcry_err_code(ret) != GPG_ERR_NO_ERROR) {
        std::cout << "TESTKEY FAIL" << std::endl << std::flush;
        return -1;
    }

    return 0;
}

unsigned int security_setup()
{
    std::string key_filename;
    char * home = getenv("HOME");
    if (home == 0) {
        std::cout << "No home" << std::endl << std::flush;
        key_filename = String::compose("%1/tmp/cyphesis_%2_id_dsa",
                                       var_directory, instance);
    } else {
        std::cout << "home" << std::endl << std::flush;
        key_filename = String::compose("%1/.cyphesis_%2_id_dsa",
                                       home, instance);
    }

    std::cout << "KEY: " << key_filename << std::endl << std::flush;

    struct stat key_stat;

    if (::stat(key_filename.c_str(), &key_stat) != 0) {
        std::cout << "not yet" << std::endl << std::flush;
        security_new_key(key_filename);
    } else {
        std::cout << "loading" << std::endl << std::flush;
        security_load_key(key_filename, key_stat.st_size);
    }

    return SECURITY_OKAY;
}


void reduce_priority(int p)
{
#ifdef HAVE_NICE
    if (nice(p) < 0) {
        log(ERROR, "Unable to increase nice level to reduce priority");
    }
#endif // HAVE_NICE
}

extern "C" void shutdown_on_signal(int signo)
{
    exit_flag = true;

#if defined(HAVE_SIGACTION)
    struct sigaction action;
    sigemptyset(&action.sa_mask);
    action.sa_flags = 0;
    action.sa_handler = SIG_IGN;
    sigaction(signo, &action, NULL);
#else
    signal(signo, SIG_IGN);
#endif
}

extern "C" void report_segfault(int signo)
{
    log(CRITICAL, "Segmentation fault");
    log(NOTICE, "Please report this bug to " PACKAGE_BUGREPORT);

#if !defined(HAVE_SIGACTION)
    signal(signo, SIG_DFL);
#endif
}

extern "C" void report_abort(int signo)
{
    log(CRITICAL, "Aborted");
    log(NOTICE, "Please report this bug to " PACKAGE_BUGREPORT);

#if !defined(HAVE_SIGACTION)
    signal(signo, SIG_DFL);
#endif
}

extern "C" void report_status(int signo)
{
    if (exit_flag) {
        log(NOTICE, "Shutting down");
    } else {
        log(NOTICE, "Running");
    }
}

extern "C" void rotate_logs(int signo)
{
    rotateLogger();
}

void interactive_signals()
{
#if defined(HAVE_SIGACTION)
    struct sigaction action;

    sigemptyset(&action.sa_mask);
    action.sa_flags = 0;
    action.sa_handler = shutdown_on_signal;
    sigaction(SIGINT, &action, NULL);

    sigemptyset(&action.sa_mask);
    action.sa_flags = 0;
    action.sa_handler = shutdown_on_signal;
    sigaction(SIGTERM, &action, NULL);

    sigemptyset(&action.sa_mask);
    action.sa_flags = 0;
    action.sa_handler = shutdown_on_signal;
    sigaction(SIGQUIT, &action, NULL);

    sigemptyset(&action.sa_mask);
    action.sa_flags = 0;
    action.sa_handler = shutdown_on_signal;
    sigaction(SIGHUP, &action, NULL);

    sigemptyset(&action.sa_mask);
    action.sa_flags = 0;
    action.sa_handler = SIG_IGN;
    sigaction(SIGPIPE, &action, NULL);

    sigemptyset(&action.sa_mask);
    action.sa_flags = SA_RESETHAND;
    action.sa_handler = report_segfault;
    sigaction(SIGSEGV, &action, NULL);

    sigemptyset(&action.sa_mask);
    action.sa_flags = SA_RESETHAND;
    action.sa_handler = report_abort;
    sigaction(SIGABRT, &action, NULL);

#ifdef __APPLE__
#warning Apple
    sigemptyset(&action.sa_mask);
    action.sa_flags = 0;
    action.sa_handler = report_status;
    sigaction(SIGINFO, &action, NULL);
#endif // __APPLE__

#else // defined(HAVE_SIGACTION)
    signal(SIGINT, shutdown_on_signal);
    signal(SIGTERM, shutdown_on_signal);
#ifndef _WIN32
    signal(SIGQUIT, shutdown_on_signal);
    signal(SIGHUP, shutdown_on_signal);
    signal(SIGPIPE, SIG_IGN);
#endif // _WIN32
    signal(SIGSEGV, report_segfault);
    signal(SIGABRT, report_abort);
#endif // defined(HAVE_SIGACTION)
}

void daemon_signals()
{
#if defined(HAVE_SIGACTION)
    struct sigaction action;

    sigemptyset(&action.sa_mask);
    action.sa_flags = 0;
    action.sa_handler = SIG_IGN;
    sigaction(SIGINT, &action, NULL);

    sigemptyset(&action.sa_mask);
    action.sa_flags = 0;
    action.sa_handler = shutdown_on_signal;
    sigaction(SIGTERM, &action, NULL);

    sigemptyset(&action.sa_mask);
    action.sa_flags = 0;
    action.sa_handler = SIG_IGN;
    sigaction(SIGQUIT, &action, NULL);

    sigemptyset(&action.sa_mask);
    action.sa_flags = 0;
    action.sa_handler = rotate_logs;
    sigaction(SIGHUP, &action, NULL);

    sigemptyset(&action.sa_mask);
    action.sa_flags = 0;
    action.sa_handler = SIG_IGN;
    sigaction(SIGPIPE, &action, NULL);

    sigemptyset(&action.sa_mask);
    action.sa_flags = SA_RESETHAND;
    action.sa_handler = report_segfault;
    sigaction(SIGSEGV, &action, NULL);

    sigemptyset(&action.sa_mask);
    action.sa_flags = SA_RESETHAND;
    action.sa_handler = report_abort;
    sigaction(SIGABRT, &action, NULL);
#else
    signal(SIGINT, SIG_IGN);
    signal(SIGTERM, shutdown_on_signal);
#ifndef _WIN32
    signal(SIGQUIT, SIG_IGN);
    signal(SIGHUP, rotate_logs);
    signal(SIGPIPE, SIG_IGN);
#endif // _WIN32
    signal(SIGSEGV, report_segfault);
    signal(SIGABRT, report_abort);
#endif
}

int daemonise()
{
#ifdef HAVE_FORK
    int pid = fork();
    int new_stdio;
    int status = 0;
    int running = false;

    switch (pid) {
        case 0:
            // Child
            // Get rid of controlling tty, and start new session
            setsid();
            // Switch signal behavoir
            daemon_signals();
            // Change current working directory to /
            if (chdir("/") != 0) {
                log(ERROR, "Unable to change current working directory to /");
            }
            // Get rid if stdio
            close(STDIN_FILENO);
            close(STDOUT_FILENO);
            close(STDERR_FILENO);
            // Open /dev/null on the stdio file descriptors to avoid problems
            new_stdio = open("/dev/null", O_RDWR);
            dup2(new_stdio, STDIN_FILENO);
            dup2(new_stdio, STDOUT_FILENO);
            dup2(new_stdio, STDERR_FILENO);
            break;
        case -1:
            // Error

            // We are not the daemon process
            daemon_flag = false;

            log(ERROR, "Failed to fork() to go to the background.");

            break;
        default:
            // Parent

            // We are not the daemon process
            daemon_flag = false;

            // Install handler for SIGUSR1
#if defined(HAVE_SIGACTION)
            struct sigaction action;
            sigemptyset(&action.sa_mask);
            action.sa_flags = 0;
            action.sa_handler = shutdown_on_signal;
            sigaction(SIGUSR1, &action, NULL);
#else
            signal(SIGUSR1, shutdown_on_signal);
#endif

            if (wait4(pid, &status, 0, NULL) < 0) {
                running = true;
            } else {
                pid = -1;
            }

            if (running == true) {
                log(INFO, "Running");
            } else {
                int estatus = WEXITSTATUS(status);
                if (estatus == EXIT_SUCCESS) {
                    log(ERROR, "Cyphesis exited normally at initialisation.");
                } else if (estatus == EXIT_DATABASE_ERROR) {
                    log(ERROR, "Cyphesis was unable to connect to the database.");
                } else if (estatus == EXIT_SOCKET_ERROR) {
                    log(ERROR, "Cyphesis was unable to open a listen socket.");
                } else if (estatus == EXIT_PORT_ERROR) {
                    log(ERROR, "Could not find free client listen socket. "
                               "Init failed.");
                    log(INFO, String::compose("To allocate 8 more ports please"
                                              " run:\n\n    cyconfig "
                                              "--cyphesis:dynamic_port_end=%1"
                                              "\n\n", dynamic_port_end + 8));
                } else {
                    log(ERROR, "Cyphesis exited unexpectedly at initialisation.");
                }
                log(ERROR, "See syslog for details.");
            }

            break;
    }
    return pid;
#else // HAVE_FORK
    // On systems where we can't fork, fool the original process into thinking
    // it is now the child.
    return 0;
#endif // HAVE_FORK
}

void running()
{
#ifdef HAVE_FORK
    if (daemon_flag) {
        kill(getppid(), SIGUSR1);
    }
#endif // HAVE_FORK
}

static const char hex_table[16] = { '0', '1', '2', '3', '4', '5', '6', '7',
                                    '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

static const int hash_algorithm = GCRY_MD_MD5;
static const int hash_salt_size = 8;

void hash_password(const std::string & pwd, const std::string & salt,
                   std::string & hash)
{
    unsigned int digest_length = gcry_md_get_algo_dlen(hash_algorithm);
    unsigned char * buf = new unsigned char[digest_length];
    assert(buf != 0);

    std::string passwd_and_salt = pwd + salt;

    // Generate an MD% hash of the password and salt concatenated
    gcry_md_hash_buffer(hash_algorithm, buf,
                        (const unsigned char *)passwd_and_salt.c_str(),
                        passwd_and_salt.size());
    // Build a string containing the salt and hash together
    // hash = String::compose("$1$%1$", salt);
    if (!salt.empty()) {
        hash = "$1$";
        hash += salt;
        hash += "$";
    } else {
        hash.clear();
    }
    for(unsigned int i = 0; i < digest_length; ++i) {
        hash.push_back(hex_table[buf[i] & 0xf]);
        hash.push_back(hex_table[(buf[i] & 0xf0) >> 4]);
    }
    return;
}

void encrypt_password(const std::string & pwd, std::string & hash)
{
    std::string salt;
    WFMath::MTRand rng;

    // Generate 8 bytes of salt
    for (int i = 0; i < hash_salt_size; ++i) {
        unsigned char b = rng.randInt() & 0xff;
        salt.push_back(hex_table[b & 0xf]);
        salt.push_back(hex_table[(b & 0xf0) >> 4]);
    }

    // Get a hash of password and salt
    hash_password(pwd, salt, hash);
}

int check_password(const std::string & pwd, const std::string & hash)
{
    unsigned int digest_length = gcry_md_get_algo_dlen(hash_algorithm);
    std::string new_hash;
    size_t hash_size = hash.size();

    if (hash_size < (digest_length * 2 + 5) || hash.substr(0, 3) != "$1$") {
        // Get a hash of password with no salt
        hash_password(pwd, "", new_hash);
    } else {
        // Extract the salt from the hash string
        size_t dp = hash.find('$', 3);
        if (dp == std::string::npos) {
            log(CYLOG_ERROR, "Password hash has no $ symbol after the salt.");
            return -1;
        }
        assert(dp > 3);
        std::string salt = hash.substr(3, dp - 3);
        // Get a has of password and salt
        hash_password(pwd, salt, new_hash);
    }
    // Check if the generated hash matches the reference hash
    return hash == new_hash ? 0 : -1;
}

#ifndef HAVE_GETTIMEOFDAY

int gettimeofday(struct timeval * tv, struct timezone * tz)
{
    assert(tz == 0);

    SYSTEMTIME localtime;
    struct tm unix_time;

    GetLocalTime(&localtime);

    unix_time.tm_sec = localtime.wSecond;
    unix_time.tm_min = localtime.wMinute;
    unix_time.tm_hour = localtime.wHour;
    unix_time.tm_mday = localtime.wDay;
    unix_time.tm_mon = localtime.wMonth - 1;
    unix_time.tm_year = localtime.wYear - 1900;

    tv->tv_usec = localtime.wMilliseconds * 1000;

    tv->tv_sec = mktime(&unix_time);

    return 0;
}

#endif