#!/usr/bin/perl -wT
# +=======================================================================+
# || cipux_mkcertkey                                                     ||
# ||                                                                     ||
# || Create a TLS certificate for stunnel. To change the default         ||
# || settings, edit /etc/cipux/cipux-cert.conf                           ||
# ||                                                                     ||
# || Copyright (C) 2008 by Christian Kuelker. All rights reserved.       ||
# ||                                                                     ||
# || License: GNU General Public License - GNU GPL - version 2           ||
# ||          or (at your opinion) any later version.                    ||
# ||                                                                     ||
# +=======================================================================+
# ID:       $Id$
# Revision: $Revision$
# Head URL: $HeadURL$
# Date:     $Date$
# Source:   $Source$

use strict;
use warnings;
use 5.008001;
use re 'taint';    # Keep data captured by parens tainted
use Carp;
use CipUX;
use File::stat;
use Cwd;
use POSIX qw(sysconf _PC_CHOWN_RESTRICTED);
use Readonly;
use Fatal qw(open close);
use English qw( -no_match_vars);
use version; our $VERSION = qv('3.4.0.0');

# +=======================================================================+
# || GLOBAL CONSTANTS                                                    ||
# +=======================================================================+

delete @ENV{qw(PATH IFS CDPATH ENV BASH_ENV)};    # Make %ENV safer
Readonly::Scalar my $EMPTY_STRING => q{};
Readonly::Scalar my $SCRIPT       => 'cipux_mkcertkey';
Readonly::Scalar my $OPENSSLBIN   => '/usr/bin/openssl';
Readonly::Scalar my $CERTCONF     => '/etc/cipux/stunnel-cert.conf';
Readonly::Scalar my $KEYDIR       => '/etc/cipux/stunnel';
Readonly::Scalar my $KEY          => $KEYDIR . '/stunnel-key.pem';
Readonly::Scalar my $CERT         => $KEYDIR . '/stunnel-cert.pem';
Readonly::Scalar my $S4USER       => 'stunnel4';

Readonly::Scalar my $SOME_ELSE_CAN_WRITE => oct 22;      # 022
Readonly::Scalar my $STICKY_BIT          => oct 1000;    # 01000

# +=======================================================================+
# || GLOBAL VARS                                                         ||
# +=======================================================================+
my $debug = 0;

# +=======================================================================+
# || TESTS                                                               ||
# +=======================================================================+

# test if we have some tiny configuration file
if ( not -e $CERTCONF ) {
    croak 'Cannot find certificate configuration: ' . $CERTCONF . "\n";
}

# test if we have some tool for creating the cert
if ( not -x $OPENSSLBIN ) {
    croak 'Cannot find openssl executable: ' . $OPENSSLBIN . "\n";
}

# test if there is a sneaky dir for storing certs
if ( not -d $KEYDIR ) {
    croak 'Directory to store certs do not exist: ' . $KEYDIR . "\n";
}

# test if KEY dir is save: mode 700, owner root
if ( not is_verysafe($KEYDIR) ) {
    my $msg = 'Directory to store certs is not save!';
    $msg .= ' Should be for example: drwx------ 2 root root';
    $msg .= ' 4096 2008-04-17 21:15 /etc/cipux/stunnel ';
    croak $msg . "\n";
}

# +=======================================================================+
# || GENERATE CERT                                                       ||
# +=======================================================================+

# +=======================================================================+
# ||                                                                     ||
# +=======================================================================+

# openssl req -new -x509 -nodes -days 365
#         -out stunnel.pem -keyout stunnel.pem

my $cmd = $OPENSSLBIN . ' req -new -x509 -nodes ';
$cmd .= ' -config ' . $CERTCONF . ' -out ' . $CERT;
$cmd .= ' -keyout ' . $KEY;
open my $cert, q{|-}, $cmd
    or croak 'Cannot execute ' . $cmd . "\n";
my @out = <$cert>;
close $cert or croak "Can not close $cmd \n";

# print out errors or other stuff in clean untainted manner:
my $C = CipUX->new( { debug => $debug } );
foreach my $line (@out) {
    chomp $line;
    $C->l($line);
    print $line . "\n" or croak 'Can not print to STDOUT!';
}

# change owner
my ( $login, $pass, $uid, $gid ) = getpwnam $S4USER
    or croak "$S4USER not known to the system!";
chown $uid, $gid, $KEY;
chown $uid, $gid, $CERT;

# change file mode
my $mode = '0600';
chmod oct($mode), $KEY;
chmod oct($mode), $CERT;

# change owner KYEDIR
chown $uid, $gid, $KEYDIR;

exit 0;

sub is_safe {

    my $path = shift;

    my $info = stat $path;

    return if not $info;

    # owner neither superuser nor me
    # the real uid is in stored in the $< variable or ($REAL_USER_ID)
    if ( ( $info->uid != 0 ) && ( $info->uid != $REAL_USER_ID ) ) {
        return 0;
    }

    # check whether group or other can write file.
    # use 066 to detect either reading or writing
    if ( $info->mode & $SOME_ELSE_CAN_WRITE ) {  # someone else can write this
        return 0 if not -d _;                    # non-directories aren't safe
             # but directories with the sticky bit (01000) are
        return 0 if not( $info->mode & $STICKY_BIT );
    }
    return 1;
}

sub is_verysafe {

    my $path = shift;

    return is_safe($path) if sysconf(_PC_CHOWN_RESTRICTED);

    if ( $path !~ m{^/}xms ) {
        $path = getcwd() . q{/} . $path;
    }
    while ( length $path ) {
        return if not is_safe($path);
        $path =~ s{([^/]+|/)$}{}xms;    # dirname
        if ( length($path) > 1 ) {
            $path =~ s{/$}{}xms;
        }
    }

    return 1;
}

__END__

#===========================================================================
#==== Documentation ========================================================
#===========================================================================

=pod

=head1 NAME

cipux_mkcertkey


=head1 VERSION

version 3.4.0.0

=head1 SYNOPSIS

        cipux_mkcertkey

=head1 REQUIRED ARGUMENTS

None.

=head1 ABSTRACT

In order to add security to your XML-RPC server you should generate a
certificate. This script shows a simple method to do that. You have to take the
responsibility by yourself to make sure you understand what you do.

=head1 DESCRIPTION

Generates a certificate and a key in /etc/cipux/stunnel.

=head1 USAGE

 cipux_mkcertkey

=head1 OPTIONS

None.

=head1 CERTIFICATE

Each SSL enabled XML-RPC server needs to present a valid X.509 certificate to
the peer and it also needs a private key to decrypt the incoming data.  The
easiest way to obtain a certificate and a key is to generate them with the free
openssl package. You can find more information on certificates generation
below.  The certificates must be in PEM format and must be sorted starting with
the certificate to the highest level (root CA)

Two things are important when generating the certificate-key pairs.

(1) Because the server has no way to obtain the password from the user, the
private key cannot be encrypted.  To create an unencrypted key add the "-nodes"
option when running the req command from the openssl kit.

(2) The order of contents of the .pem file is also important. It should contain
the unencrypted private key first, then a signed certificate (not certificate
request). There should be also empty lines after certificate and private key.
Plaintext certificate information appended on the top of generated certificate
should be discarded. So the file should look like this:

             -----BEGIN RSA PRIVATE KEY-----
             [encoded key]
             -----END RSA PRIVATE KEY-----
             [empty line]
             -----BEGIN CERTIFICATE-----
             [encoded certificate]
             -----END CERTIFICATE-----
             [empty line]

This can be stored in one file or in two files. This script stores the in to
files to have the flexibility to use the certificate in other location. This to
files will be created:

 stunnel-cert.pem
 stunnel-key.pem

=head1 DIAGNOSTICS

TODO: write explanations to the messages.

=over

=item C<< Cannot find certificate configuration: %s >>

=item C<< Cannot find openssl executable: %s >>

=item C<< Directory to store certs do not exist: %s >>

=item C<< Directory to store certs is not save!... >>

 Directory to store certs is not save!
 Should be for example:
 drwx------ 2 root root 4096 2008-04-17 21:15 /etc/cipux/stunnel

=item C<< Cannot execute %s >>

=item C<< Can not close %s >>

=item C<< Can not print to STDOUT! >>

=item C<< %s not known to the system! >>

=back

=head1 CONFIGURATION

TODO.

=head1 DEPENDENCIES

Carp
CipUX
File::stat
Cwd
POSIX
Readonly
Fatal
English
version

=head1 INCOMPATIBILITIES

Not known.

=head1 BUGS AND LIMITATIONS

Not known.

=head1 SEE ALSO

See the CipUX webpage and the manual at L<http://www.cipux.org>
See the mailing list L<http://sympa.cipworx.org/wws/info/cipux-devel>

=head1 AUTHOR

Christian Kuelker  E<lt>christian.kuelker@cipworx.orgE<gt>

=head1 LICENSE AND COPYRIGHT

Copyright (C) 2008 by Christian Kuelker

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, 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., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA

=cut

