Compare commits

..

47 Commits

Author SHA1 Message Date
Patrick Van der Veken
99bcd4b590 Update README 2025-07-25 21:50:22 +02:00
Patrick Van der Veken
4d7a988618 Add logic to create $HOME/.ssh if not exists, but only as user root. 2025-07-25 21:15:13 +02:00
64bb1b31d7 Add license info and update README 2025-04-27 09:07:29 +02:00
8f12a0b976 Update vars & version 2025-04-27 08:19:32 +02:00
b484d9a264 * Add ignore_errors flag to skip errors during key deployment
* Some other minor updates
2025-04-27 08:15:52 +02:00
b8b5851705 Update link 2024-08-03 20:21:42 +02:00
Patrick Van der Veken
520db1e36d
Merge pull request #2 from pstoops/patch-1
Update manage_ssh.conf
2024-03-16 12:09:11 +01:00
Peter Stoops
ed4f078b9a
Update manage_ssh.conf
BatchMode prevents password prompt if SSH key auth fails
2024-03-01 13:01:34 +01:00
71eb0acc02 Fixes in resolve_alias() & resolve_targets() 2021-06-16 22:25:43 +02:00
Patrick Van der Veken
c8297aaad2 Version up 2021-03-24 11:24:32 +01:00
Patrick Van der Veken
902dd31116 Fix wrong pattern match 2021-03-24 11:23:55 +01:00
Patrick Van der Veken
d90ad7d30b Bad copy/paste, urgh 2021-03-24 11:23:03 +01:00
f1bcf88a7d Update documentation link 2021-02-01 21:01:33 +01:00
Patrick Van der Veken
dfb8da92c8 Switch position of blacklist handling (to make $hostname known) 2021-01-12 14:05:17 +01:00
Patrick Van der Veken
ec158b2c62 whitespace fix 2021-01-11 16:03:35 +01:00
Patrick Van der Veken
c3fdf58666 ksh88 fix 2021-01-11 15:52:32 +01:00
Patrick Van der Veken
fe836edadf * Fix problem in count_fields() with old AWK
* Make fingerprinting more robust (incl support for newer key types).
2021-01-09 14:20:09 +01:00
Patrick Van der Veken
7c9f951f62 Fix for key location logic 2020-12-30 20:17:20 +01:00
Patrick Van der Veken
a311d00924 Fix in README 2020-12-30 18:04:33 +01:00
Patrick Van der Veken
77a332e324 * added support for standard home directory location for public keys ($HOME/.ssh). Set $key_location=use_sshd in update_ssh.conf[.local] with AuthorizedKeysFile set to the default value in sshd_config (or use the value .ssh/authorized_keys).
* added support for SELinux (CentOS/RHEL 8.x)
* various fixes (incl. shellcheck + quoting)
2020-12-30 17:06:02 +01:00
Patrick Van der Veken
b8004afe62 * Fixed bug in sftp_file(): when file does not contain a directory path, the $TRANSFER_DIR was wrongly calculated
* Fixed wrong filename in distribute2host()
2020-05-28 17:31:55 +02:00
patvdv
9e6ca1b813 Fix for ksh93 -> ksh88 compatability (Peter Stoops) 2018-11-24 10:12:24 +01:00
patvdv
de2065b20a Doc update 2018-11-03 23:35:56 +01:00
patvdv
5cee831a59 Doc update 2018-11-03 23:21:26 +01:00
patvdv
ff9f1b3f93 Doc update 2018-11-03 16:59:22 +01:00
patvdv
a99decbf95 * Added support to specify @group values for the --targets parameter and in the targets file(s)
* Added support for nested aliases: up to 5 levels deep instead of just
one level
* Added --resolve-alias/--alias command-line parameter to manually check
the resolution any alias
* Fixed propagation of --debug flag (to clients & slaves)
* Fixed propagation of --create-dir flag (to clients & slaves)
* Fixed problem in --fix-local routine (by adding optional --fix-user
command-line parameter and code)
* Fixed check when adding key to ssh-agent
* Added checking on alias resolution in --check-syntax routine
* Better trap setting
* Added typeset-ing to vars
* Switched version numbering (now date based)
* Code cleanup (now error & warning free in shellcheck/perlcritic
linters)
2018-11-03 16:35:36 +01:00
patvdv
af8bf6a665 Fix comments + linter erors 2018-10-28 21:44:55 +01:00
patvdv
65e336d1b1 Fix linter errors 2018-10-28 21:35:07 +01:00
patvdv
d59f91997a Stupid fix 2018-08-18 18:20:52 +02:00
patvdv
f18086b0e2 * Fix for poor awk statements in update_fingerprints (Credits: Peter Stoops)
* Added FINGERPRINT_TYPE as configuration option (md5,sha256) (OpenSSH >v6.8)
2018-08-18 18:18:46 +02:00
Van der Veken Patrick
69ef9a72e0 Added missing code for --make-finger. Removed HISTORY comments 2017-10-26 09:09:33 +02:00
patvdv
ad9f5782a4 Comment update 2015-12-13 15:12:52 +01:00
patvdv
49229f9d55 fix for DO_SLAVE, improved check_root_user() calls (VRF 1.5.2) [Patrick Van der Veken] 2015-12-13 15:07:40 +01:00
patvdv
b1db0c5a9b Update doc 2015-10-10 21:17:04 +02:00
patvdv
f03a0403ca simplified handling of SSH agent handling, obsoleted DO_SLAVE_SSH_AGENT option (VRF 1.5.1) [Patrick Van der Veken] 2015-10-10 21:15:06 +02:00
patvdv
c377ee9a7a Update doc for master->slave operations 2015-10-03 20:05:34 +02:00
patvdv
7f23f5ac8b added --slave option, 3 new configuration parameters & supporting functions for master->slave operations, several bug fixes (VRF 1.5.0) [Patrick Van der Veken] 2015-10-03 20:03:06 +02:00
patvdv
da24312c22 Update doc 2015-09-27 17:59:54 +02:00
patvdv
9aa4d8cbd3 added SSH host keys discovery, re-assigned '-d' command-line option to this function, 2 new parameters in manage_ssh.conf (VRF 1.4.0) [Patrick Van der Veken] 2015-09-27 17:53:33 +02:00
Patrick Van der Veken
7ca0a08be7 added $GLOBAL_CONFIG_FILE
added $GLOBAL_CONFIG_FILE to fix ownership/permissions routine (VRF
1.3.3) [Patrick Van der Veken]
2015-09-23 13:13:47 +02:00
Patrick Van der Veken
871e7ca1bb small fix in wait_for_children()
# @(#) 2015-09-15: small fix in wait_for_children() (VRF 1.3.2) [Patrick
Van der Veken]
2015-09-15 12:35:25 +02:00
Patrick Van der Veken
7d337f3185 Failure in local update should be die() 2015-09-09 13:22:15 +02:00
Patrick Van der Veken
34f358f7fb Log handling
better handling of leading log sigils in die(), log(), logc() and
warn(), fix in count_fields() (VRF 1.3.1)
2015-09-09 12:50:18 +02:00
patvdv
19cccb4a4c VRF 1.3.0: proper error checking for asynchronous jobs, using logc(). Other fixes. 2015-09-06 12:58:50 +02:00
Patrick Van der Veken
be909a8f5b Fix in wait_for_children()
wait should not be called in a sub-shell
2015-09-04 09:57:08 +02:00
Patrick Van der Veken
bc952e64c2 check_config() update
check_config() update
2015-08-28 08:55:05 +02:00
Patrick Van der Veken
0db8e3c51d Change option
DO_SFTP_CHMOD=1
2015-08-28 08:49:37 +02:00
7 changed files with 1821 additions and 536 deletions

View File

@ -1,11 +1,21 @@
# SSH Controls
<p align="center"><img src="logo.png" alt="SSH Controls Logo"></p>
## What's new
:loudspeaker: **25/07/2025**:
* added the creation of the `$HOME/.ssh` directory when running as `root`.
## About
SSH Controls is a light-weight SSH **public key** distribution & management framework
* uses a **desired state** model: SSH Controls pushes public keys from a key master server onto client host and applies them according to the central configuration.
* uses a **desired state** model: SSH Controls *pushes* public keys from a key master (or slave) server onto client host(s) and applies them according to the central configuration.
* uses **SSH** as **transport** mechanism: eat your own dog food. SSH Controls connects to client hosts through the secure path of SSH and using a public key that is under its own control.
* **shields** public keys from owners/users on client systems: SSH Controls requires the standard sshd_config to be reconfigured with an alternate path for the AuthorizedKeysFile setting so that public keys are stored in common location which cannot be manipulated by the owners of the public keys. This allows for more administrative control and better security.
* supports a **Master→Slave→Client** model so that information can be propagated within more complex LAN set-ups.
* can **shield** public keys from owners/users on client systems: SSH Controls may require the standard `sshd_config` to be reconfigured with an alternate path for the `AuthorizedKeysFile` setting so that public keys are stored in common location which cannot be manipulated by the owners of the public keys. This allows for more administrative control and better security.
* performs operations with **least privileges**: copy/distribute operations are performed with a low-privileged account. Only the actual key updates requires super-user privileges which need to be configured via SUDO.
@ -13,10 +23,16 @@ SSH Controls is a light-weight SSH **public key** distribution & management fram
* can assign a single public key to **multiple** OS accounts: SSH Controls allows an user to log on under multiple accounts using the same key. Auditing of the connecting user and the target account is possible using fingerprinting.
* allows the use of (nested) **groups** in the master configuration: users, keys and hosts can be grouped in the SSH master configuration files to allow a simplified configuration. Nesting of groups is allowed up to one level deep.
* allows the use of (nested) **groups** in the master configuration: users, keys and hosts can be grouped in the SSH master configuration files to allow a simplified configuration. Nesting of groups is allowed up to *5 levels* deep.
* allows the use of (nested) **groups** in the specification of the *push* targets. Either via the `--targets` command-line parameter or via the `targets` configuration file.
* allows compromised public keys to be **blacklisted**: SSH Controls will deny the use of public keys that have been administrative blacklisted. Blacklisting happens on the SSH master and is applied to all client hosts.
* can discover host public keys to (re)create `known_hosts` file(s) for a large amount of hosts
* supports *md5* and *sha512* fingerprint **hashes** (if the installed SSH version supports these hash types)
* requires **no client agent** component and is **stateless**: SSH Controls performs operations by pushing keys or commands to client hosts. Update processes on the client hosts will only be started on-demand. If the SSH master is - for whatever reason - unavailable then active keys on a client host remain in place and logons are still possible.
* is **easy** to **configure** and **maintain** (command-line based): the configuration is stored in a limited number of flat files and be easily updated. A very rudimentary syntax checking facility is also available to check the consistency of the most important (master) configuration files.
@ -26,6 +42,6 @@ SSH Controls does NOT:
* manage or distribute SSH **private keys**: SSH private keys should be controlled and managed (and safeguarded!) by the actual owners. Though one could consider SSH key pairs of generic accounts (such as application accounts) as an exception, SSH Controls currently does not support the management of private keys.
* discover SSH **host keys**: SSH Controls will silently ignore any questions related to host keys discoveries upon the first connection to client hosts. If you are managing a large number of client hosts, you may want to prepare a known_hosts file in advance or else let the host keys be added automatically upon first public key distribution.
More documentation can be found at <https://www.kudos.be/ssh_controls/>
More documentation can be found at http://www.kudos.be/Projects/SSH_Controls.html
*Logo created with [Free Logo Maker](https://logomakr.com)*

View File

@ -2,7 +2,7 @@
#******************************************************************************
# @(#) convert_pubkey.pl
#******************************************************************************
# @(#) Copyright (C) 2014 by KUDOS BVBA <info@kudos.be>. All rights reserved.
# @(#) Copyright (C) 2014 by KUDOS BV <info@kudos.be>. All rights reserved.
#
# This program is a free software; you can redistribute it and/or modify
# it under the same terms of the GNU General Public License as published by
@ -29,7 +29,7 @@ use Pod::Usage;
# ------------------------- CONFIGURATION starts here -------------------------
# define the V.R.F (version/release/fix)
my $MY_VRF = "1.0.0";
my $script_version = "2025-04-27";
# always assume RSA keys!
my $key_algo = 'ssh-rsa';
# ------------------------- CONFIGURATION ends here ---------------------------
@ -62,7 +62,7 @@ pod2usage(-verbose => 0) unless (%options);
# check version parameter
if ($options{'version'}) {
print "INFO: $0: version $MY_VRF";
print "INFO: $0: version $script_version";
exit (0);
}
# check help parameter
@ -194,8 +194,4 @@ S< >Show version of the script.
=head1 AUTHOR
(c) KUDOS BVBA, Patrick Van der Veken
=head1 HISTORY
@(#) 2014-12-20: VRF 1.0.0: first version [Patrick Van der Veken]
(c) KUDOS BV, Patrick Van der Veken

BIN
logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

View File

@ -13,17 +13,17 @@
# (leave blank for current user)
SSH_TRANSFER_USER=""
# name of the OS group that should own the SSH controls files
# name of the UNIX group that should own the SSH controls files (must exist already)
SSH_OWNER_GROUP="sshadmin"
# whether a 'chmod' needs to be executed after each sftp transfer [0=Yes; 1=No]
DO_SFTP_CHMOD=0
# whether a 'chmod' needs to be executed after each sftp transfer [0=No; 1=Yes]
DO_SFTP_CHMOD=1
# extra arguments/options for the SFTP command
SFTP_ARGS="-o StrictHostKeyChecking=no -o ConnectTimeout=10 -b - "
SFTP_ARGS="-o StrictHostKeyChecking=no -o ConnectTimeout=10 -o BatchMode=yes -b - "
# extra arguments/options for the SSH command
SSH_ARGS="-o StrictHostKeyChecking=no -o ConnectTimeout=10 -n"
SSH_ARGS="-o StrictHostKeyChecking=no -o ConnectTimeout=10 -o BatchMode=yes -n"
# location of the local SSH controls directory
LOCAL_DIR="/etc/ssh_master"
@ -32,12 +32,27 @@ LOCAL_DIR="/etc/ssh_master"
REMOTE_DIR="/etc/ssh_controls/holding"
# name of the user account performing the SSH controls update
# (leave blank for current user but user should have remote sudo root privs)
# (leave blank for current user running script)
# user should have remote sudo root privs (except when using user 'root')
SSH_UPDATE_USER=""
# options to pass to update_ssh.pl when executing a key update
SSH_UPDATE_OPTS="--verbose --remove"
# path to the ssh-keyscan too
SSH_KEYSCAN_BIN="/usr/bin/ssh-keyscan"
# extra arguments/options for the ssh-keyscan command
# by default -f <file> is used by manage_sudo.sh to supply hostnames, do not add here
SSH_KEYSCAN_ARGS="-t rsa"
# whether to start an SSH agent process for the master->client operations [0=No; 1=Yes]
DO_SSH_AGENT=0
# location of the SSH private key that should be added to the SSH agent process
# must be a passphrase-less key (required when using DO_SSH_AGENT)
SSH_PRIVATE_KEY="$HOME/.ssh/id_rsa"
# maximum number of background process to spawn (~maxuprc, ~nstrpty etc)
MAX_BACKGROUND_PROCS=30
@ -47,6 +62,10 @@ BACKUP_DIR="${LOCAL_DIR}/backup"
# location of log directory (default), see --log-dir)
LOG_DIR="/var/log"
# type of fingerpint (md5, sha256)
FINGERPRINT_TYPE="md5"
#******************************************************************************
# End of FILE
#******************************************************************************

File diff suppressed because it is too large Load Diff

View File

@ -12,11 +12,22 @@
# use short hostnames or FQDN (0=short names; 1=FQDN) [default: 0]
use_fqdn=1
# ignore errors during key deployment (0=no; 1=yes [default: 0])
ignore_errors=0
# target directory for allowed SSH key files
access_dir=/etc/kudos/ssh_controls/keys.d
access_dir=/etc/ssh_controls/keys.d
# toggle to specify the final location of public keys by allowing to override
# the value of $access_dir with the 'AuthorizedKeysFile' in sshd (=enables the
# use of $HOME/.ssh for public keys for example):
# 'use_controls': take the value from the configured 'access_dir' option
# 'use_sshd' : use the value from 'AuthorizedKeysFile' setting in sshd
# [default: use_controls]
key_location=use_controls
# location of the keys blacklist file
blacklist_file=/etc/kudos/ssh_controls/keys.blacklisted
blacklist_file=/etc/ssh_controls/keys.blacklisted
#******************************************************************************
# End of FILE

View File

@ -2,7 +2,7 @@
#******************************************************************************
# @(#) update_ssh.pl
#******************************************************************************
# @(#) Copyright (C) 2014 by KUDOS BVBA <info@kudos.be>. All rights reserved.
# @(#) Copyright (C) 2014 by KUDOS BV <info@kudos.be>. All rights reserved.
#
# This program is a free software; you can redistribute it and/or modify
# it under the same terms of the GNU General Public License as published by
@ -41,23 +41,34 @@ use Pod::Usage;
#******************************************************************************
# ------------------------- CONFIGURATION starts here -------------------------
# define the V.R.F (version/release/fix)
my $MY_VRF = "1.2.0";
# define the version (YYYY-MM-DD)
my $script_version = "2025-07-25";
# name of global configuration file (no path, must be located in the script directory)
my $global_config_file = "update_ssh.conf";
# name of localized configuration file (no path, must be located in the script directory)
my $local_config_file = "update_ssh.conf.local";
# maxiumum level of recursion for alias resolution
my $max_recursion = 5;
# selinux context labels of key files for different RHEL version
my %selinux_contexts = ( '5' => 'sshd_key_t',
'6' => 'ssh_home_t',
'7' => 'ssh_home_t');
'7' => 'ssh_home_t',
'8' => 'ssh_home_t',
'9' => 'ssh_home_t',
'10' => 'ssh_home_t');
# disallowed paths for home directories for accounts
my @disallowed_homes = ('/', '/etc', '/bin', '/sbin', '/usr/bin', '/usr/sbin');
# disallowed login shells for @accounts
my @disallowed_shells = ('/bin/nologin','/bin/false','/sbin/nologin','/sbin/false');
# default toggle for key location
my $key_location='use_controls';
# ------------------------- CONFIGURATION ends here ---------------------------
# initialize variables
my ($debug, $verbose, $preview, $remove, $global, $use_fqdn) = (0,0,0,0,0,0);
my ($debug, $verbose, $preview, $remove, $global, $use_fqdn, $ignore_errors) = (0,0,0,0,0,0,0);
my (@config_files, @zombie_files, $access_dir, $blacklist_file);
my (%options, @uname, @pwgetent, @accounts, %aliases, %keys, %access, @blacklist);
my ($os, $hostname, $run_dir);
my ($selinux_status, $selinux_context, $linux_version, $has_selinux) = ("","","",0);
my ($os, $hostname, $run_dir, $authorizedkeys_option);
my ($selinux_status, $selinux_context, $linux_version, $has_selinux, $recursion_count) = ("","","",0,1);
$|++;
@ -87,7 +98,7 @@ sub parse_config_file {
my $config_file = shift;
unless (open (CONF_FD, "<", $config_file)) {
do_log ("ERROR: failed to open the configuration file ${config_file} [$! $hostname]")
do_log ("ERROR: failed to open the configuration file ${config_file} [$!/$hostname]")
and exit (1);
}
while (<CONF_FD>) {
@ -96,14 +107,25 @@ sub parse_config_file {
if (/^\s*$/ || /^#/) {
next;
} else {
if (/^\s*use_fqdn\s*=\s*([0-9]+)\s*$/) {
if (/^\s*use_fqdn\s*=\s*(0|1)\s*$/) {
$use_fqdn = $1;
do_log ("DEBUG: picking up setting: use_fqdn=${use_fqdn}");
}
if (/^\s*ignore_errors\s*=\s*(0|1)\s*$/) {
$ignore_errors = $1;
do_log ("DEBUG: picking up setting: ignore_errors=${ignore_errors}");
}
if (/^\s*access_dir\s*=\s*([0-9A-Za-z_\-\.\/~]+)\s*$/) {
$access_dir = $1;
do_log ("DEBUG: picking up setting: access_dir=${access_dir}");
}
if (/^\s*key_location\s*=\s*(use_controls|use_sshd)\s*/) {
$key_location = $1;
do_log ("DEBUG: picking up setting: key_location=${key_location}");
if ($key_location eq 'use_sshd') {
do_log ("DEBUG: applied setting: key_location=${key_location}");
}
}
if (/^\s*blacklist_file\s*=\s*([0-9A-Za-z_\-\.\/~]+)\s*$/) {
$blacklist_file = $1;
# support tilde (~) expansion for ~root
@ -148,12 +170,24 @@ sub set_file {
my ($file, $perm, $uid, $gid) = @_;
chmod ($perm, "$file")
or do_log ("ERROR: cannot set permissions on $file [$! $hostname]")
and exit (1);
chown ($uid, $gid, "$file")
or do_log ("ERROR: cannot set ownerships on $file [$! $hostname]")
and exit (1);
my $rc = chmod ($perm, "$file");
if (!$rc) {
if ($ignore_errors) {
do_log ("ERROR: cannot set permissions on $file [$!/$hostname] -- IGNORED");
} else {
do_log ("ERROR: cannot set permissions on $file [$!/$hostname]");
exit (1);
}
}
my $rc = chown ($uid, $gid, "$file");
if (!$rc) {
if ($ignore_errors) {
do_log ("ERROR: cannot set ownerships on $file [$!/$hostname] -- IGNORED");
} else {
do_log ("ERROR: cannot set ownerships on $file [$!/$hostname]");
exit (1);
}
}
return (1);
}
@ -174,6 +208,7 @@ if ( @ARGV > 0 ) {
debug|d
help|h|?
global|g
ignore|i
preview|p
remove|r
verbose|v
@ -185,7 +220,7 @@ pod2usage(-verbose => 0) unless (%options);
# check version parameter
if ($options{'version'}) {
$verbose = 1;
do_log ("INFO: $0: version $MY_VRF");
do_log ("INFO: $0: version $script_version");
exit (0);
}
# check help parameter
@ -197,6 +232,10 @@ if ($options{'help'}) {
if ($options{'global'}) {
$global = 1;
}
# check ignore parameter
if ($options{'ignore'}) {
$ignore_errors = 1;
}
# check preview parameter
if ($options{'preview'}) {
$preview = 1;
@ -226,7 +265,7 @@ $verbose = 1 if ($options{'verbose'});
# where am I? (1/2)
$0 =~ /^(.+[\\\/])[^\\\/]+[\\\/]*$/;
my $run_dir = $1 || ".";
$run_dir = $1 || ".";
$run_dir =~ s#/$##; # remove trailing slash
# don't do anything without configuration file(s)
@ -243,31 +282,20 @@ foreach my $config_file (@config_files) {
parse_config_file ($config_file);
}
# is the target directory for keys present? (not for global preview)
unless ($preview and $global) {
do_log ("INFO: checking for SSH control mode ...");
# is the target directory for keys present? (not for global preview and
# not when $key_location is use_sshd)
unless (($preview and $global) or $key_location eq 'use_sshd') {
do_log ("INFO: checking for SSH controls mode ...");
if (-d $access_dir) {
do_log ("INFO: host is under SSH control via $access_dir");
do_log ("INFO: host is under SSH controls via $access_dir");
} else {
if ($key_location eq 'use_sshd') {
do_log ("INFO: skipped check since public key location is determined by sshd [$hostname]")
} else {
do_log ("ERROR: host is not under SSH keys only control [$hostname]")
and exit (1);
}
}
# do we have a blacklist file? (optional) (not for global preview)
unless ($preview and $global) {
do_log ("INFO: checking for keys blacklist file ...");
if (-f $blacklist_file) {
open (BLACKLIST, "<", $blacklist_file) or \
do_log ("ERROR: cannot read keys blacklist file [$! $hostname]")
and exit (1);
@blacklist = <BLACKLIST>;
close (BLACKLIST);
do_log ("INFO: keys blacklist file found with ".scalar (@blacklist)." entr(y|ies) on $hostname");
print Dumper (\@blacklist) if $debug;
} else {
do_log ("WARN: no keys blacklist file found [$hostname]");
}
}
# what am I?
@ -289,6 +317,49 @@ if ($use_fqdn) {
do_log ("INFO: runtime info: ".getpwuid ($<)."; ${hostname}\@${run_dir}; Perl v$]");
# -----------------------------------------------------------------------------
# handle blacklist file
# -----------------------------------------------------------------------------
# do we have a blacklist file? (optional) (not for global preview)
unless ($preview and $global) {
do_log ("INFO: checking for keys blacklist file ...");
if (-f $blacklist_file) {
open (BLACKLIST, "<", $blacklist_file) or \
do_log ("ERROR: cannot read keys blacklist file [$!/$hostname]")
and exit (1);
@blacklist = <BLACKLIST>;
close (BLACKLIST);
do_log ("INFO: keys blacklist file found with ".scalar (@blacklist)." entr(y|ies) on $hostname");
print Dumper (\@blacklist) if $debug;
} else {
do_log ("WARN: no keys blacklist file found [$hostname]");
}
}
# -----------------------------------------------------------------------------
# resolve and check key location
# -----------------------------------------------------------------------------
if ($key_location eq 'use_sshd') {
# get sshd setting but only take 1st path into account
$authorizedkeys_option = qx#sshd -T | grep "authorizedkeysfile" 2>/dev/null | cut -f2 -d' '#;
chomp ($authorizedkeys_option);
if (defined ($authorizedkeys_option)) {
do_log ("INFO: AuthorizedkeysFile resolves to $authorizedkeys_option [$hostname]");
} else {
do_log ("ERROR: unable to get AuthorizedkeysFile value from sshd [$hostname]")
and exit (1);
}
} else {
# for SSH controls native logic we require an absolute path
if ($authorizedkeys_option =~ /^\//) {
do_log ("ERROR: option \$access_dir requires and absolute path [$hostname]")
and exit (1);
}
do_log ("DEBUG: applied default setting: key_location=${key_location}");
}
# -----------------------------------------------------------------------------
# collect user accounts via getpwent()
# result: @accounts
@ -310,14 +381,14 @@ do_log ("INFO: ".scalar (@accounts)." user accounts found on $hostname");
print Dumper (\@accounts) if $debug;
# -----------------------------------------------------------------------------
# read aliases for teams, servers and users
# read aliases for teams, servers and users (and resolve group definitions)
# result: %aliases
# -----------------------------------------------------------------------------
do_log ("INFO: reading 'alias' file ...");
open (ALIASES, "<", "${run_dir}/alias")
or do_log ("ERROR: cannot read 'alias' file [$! $hostname]") and exit (1);
or do_log ("ERROR: cannot read 'alias' file [$!/$hostname]") and exit (1);
while (<ALIASES>) {
my ($key, $value, @values);
@ -334,13 +405,45 @@ close (ALIASES);
do_log ("DEBUG: dumping unexpanded aliases:");
print Dumper (\%aliases) if $debug;
# we can nest aliases one level deep, so do a one-level recursive sort of lookup
# of the remaining '@' aliases. Input should be passed as comma-separated
# string to resolve_aliases so don't forget to smash everything back together
# first.
# resolve aliases recursively to a maxium of $max_recursion
while ($recursion_count <= $max_recursion) {
# crawl over all items in the hash %aliases
foreach my $key (keys (%aliases)) {
$aliases{$key} = [resolve_aliases (join (",", @{$aliases{$key}}))];
# crawl over all items in the array @{aliases{$key}}
my @new_array; my @filtered_array; # these are the working stashes
do_log ("DEBUG: expanded alias $key before recursion $recursion_count [$hostname]");
print Dumper (\@{$aliases{$key}}) if $debug;
foreach my $item (@{$aliases{$key}}) {
# is it a group?
if ($item =~ /^\@/) {
# expand the group if it exists
if ($aliases{$item}) {
# add current and new items to the working stash
if (@new_array) {
push (@new_array, @{$aliases{$item}});
} else {
@new_array = (@{$aliases{$key}}, @{$aliases{$item}});
}
# remove the original group item from the working stash
@filtered_array = grep { $_ ne $item } @new_array;
@new_array = @filtered_array;
} else {
do_log ("WARN: unable to resolve alias $item [$hostname]");
}
# no group, just add the item as-is to working stash
} else {
push (@new_array, $item);
}
}
# filter out dupes
my %seen;
@filtered_array = grep { not $seen{$_}++ } @new_array;
# re-assign working stash back to our original hash key
@{$aliases{$key}} = @filtered_array;
do_log ("DEBUG: expanded alias $key after recursion $recursion_count [$hostname]");
print Dumper (\@{$aliases{$key}}) if $debug;
}
$recursion_count++;
}
do_log ("INFO: ".scalar (keys (%aliases))." aliases found on $hostname");
@ -364,7 +467,7 @@ if (-d "${run_dir}/keys.d" && -f "${run_dir}/keys") {
if (-d "${run_dir}/keys.d") {
do_log ("INFO: local 'keys' are stored in a DIRECTORY on $hostname");
opendir (KEYS_DIR, "${run_dir}/keys.d")
or do_log ("ERROR: cannot open 'keys.d' directory [$! $hostname]")
or do_log ("ERROR: cannot open 'keys.d' directory [$!/$hostname]")
and exit (1);
while (my $key_file = readdir (KEYS_DIR)) {
next if ($key_file =~ /^\./);
@ -382,7 +485,7 @@ if (-d "${run_dir}/keys.d") {
# process 'keys' files
foreach my $key_file (@key_files) {
open (KEYS, "<", $key_file)
or do_log ("ERROR: cannot read 'keys' file [$! $hostname]") and exit (1);
or do_log ("ERROR: cannot read 'keys' file [$!/$hostname]") and exit (1);
do_log ("INFO: reading public keys from file: $key_file");
while (<KEYS>) {
@ -420,7 +523,7 @@ print Dumper(\%keys) if $debug;
do_log ("INFO: reading 'access' file ...");
open (ACCESS, "<", "${run_dir}/access")
or do_log ("ERROR: cannot read 'access' file [$! $hostname]") and exit (1);
or do_log ("ERROR: cannot read 'access' file [$!/$hostname]") and exit (1);
while (<ACCESS>) {
my ($who, $where, $what, @who, @where, @what);
@ -473,7 +576,7 @@ if ($preview && $global) {
do_log ("INFO: display GLOBAL configuration ....");
open (ACCESS, "<", "${run_dir}/access")
or do_log ("ERROR: cannot read 'access' file [$! $hostname]") and exit (1);
or do_log ("ERROR: cannot read 'access' file [$!/$hostname]") and exit (1);
while (<ACCESS>) {
my ($who, $where, $what, @who, @where, @what);
@ -508,7 +611,8 @@ if ($preview && $global) {
}
# -----------------------------------------------------------------------------
# distribute keys into authorized_keys files in $access_dir
# distribute keys into authorized_keys files
# (defined by $key_location and/or $access_dir)
# -----------------------------------------------------------------------------
do_log ("INFO: applying SSH access rules ....");
@ -544,6 +648,18 @@ unless ($preview) {
$linux_version = 7;
last SWITCH_RELEASE;
};
$release_string =~ m/release 8/i && do {
$linux_version = 8;
last SWITCH_RELEASE;
};
$release_string =~ m/release 9/i && do {
$linux_version = 9;
last SWITCH_RELEASE;
};
$release_string =~ m/release 10/i && do {
$linux_version = 8;
last SWITCH_RELEASE;
};
}
}
# use fall back in case we cannot determine the version
@ -565,17 +681,62 @@ unless ($preview) {
# only add authorized_keys for existing accounts,
# otherwise revoke access if needed
foreach my $account (sort (@accounts)) {
SET_KEY: foreach my $account (sort (@accounts)) {
my $access_file = "$access_dir/$account";
my ($access_file, $authorizedkeys_file, $uid, $gid, $home_dir, $login_shell) = (undef, undef, undef, undef, undef, undef);
# set $access_file when using SSH controls logic
if ($key_location eq 'use_sshd' and defined ($authorizedkeys_option)) {
# use sshd logic (replacing %u,%h, %%)
$authorizedkeys_file = $authorizedkeys_option;
$authorizedkeys_file =~ s/%u/$account/g;
$authorizedkeys_file =~ s/%h/$hostname/g;
$authorizedkeys_file =~ s/%%/%/g;
# check relative path (assume $HOME needs to be added)
if ($authorizedkeys_file !~ /^\//) {
($uid, $gid, $home_dir, $login_shell) = (getpwnam($account))[2,3,7,8];
# do not accept invalid $HOME or shells
if (defined ($home_dir)) {
if (grep( /^$home_dir$/, @disallowed_homes) or grep( /^$login_shell/, @disallowed_shells)) {
do_log ("DEBUG: invalid HOME or SHELL for $account [$hostname]");
next SET_KEY;
} else {
$authorizedkeys_file = $home_dir."/".$authorizedkeys_file;
do_log ("DEBUG: adding $home_dir to public key path for $account [$hostname]");
}
} else {
do_log ("ERROR: unable to get HOME for $account [$hostname]");
next SET_KEY;
}
}
$access_file = $authorizedkeys_file;
} else {
# use native SSH controls logic
$access_file = "$access_dir/$account";
}
do_log ("DEBUG: public key location for $account resolves to $access_file [$hostname]");
# only add authorised_keys if there are access definitions
if ($access{$account}) {
unless ($preview) {
# create $HOME/.ssh if needed but only when we are root
if ($key_location eq 'use_sshd' and defined ($authorizedkeys_option)) {
if ($> == 0) {
if (! -d "$home_dir/.ssh") {
mkdir ("$home_dir/.ssh", 0700)
or do_log "ERROR: failed to create the $home_dir/.ssh directory [$!/$hostname]"
and next SET_KEY;
chown ($uid, $gid, "$home_dir/.ssh")
or do_log "ERROR: failed to set onwerships on the $home_dir/.ssh directory [$!/$hostname]"
and next SET_KEY;
do_log ("DEBUG: created directory $home_dir/.ssh for $account [$hostname]");
}
}
}
open (KEYFILE, "+>", $access_file)
or do_log ("ERROR: cannot open file for writing in $access_dir [$! $hostname]")
and exit (1);
or do_log ("ERROR: cannot open file for writing at $access_file [$!/$hostname]")
and next SET_KEY;
}
foreach my $person (sort (@{$access{$account}})) {
my $real_name = $person;
@ -592,9 +753,13 @@ foreach my $account (sort (@accounts)) {
}
close (KEYFILE) unless $preview;
# set permissions to world readable and check for SELinux context
# set ownerships/permissions on public key file and check for SELinux context
unless ($preview) {
if ($key_location eq 'use_controls') {
set_file ($access_file, 0644, 0, 0);
} else {
set_file ($access_file, 0600, $uid, $gid);
}
# selinux labels
SWITCH: {
$os eq "Linux" && do {
@ -611,7 +776,7 @@ foreach my $account (sort (@accounts)) {
if (-f $access_file) {
unless ($preview) {
unlink ($access_file)
or do_log ("ERROR: cannot remove obsolete access file(s) [$! $hostname]")
or do_log ("ERROR: cannot remove obsolete access file $access_file [$!/$hostname]")
and exit (1);
} else {
do_log ("INFO: removing obsolete access $access_file on $hostname");
@ -621,14 +786,16 @@ foreach my $account (sort (@accounts)) {
}
# -----------------------------------------------------------------------------
# alert on/remove extraneous authorized_keys files
# alert on/remove extraneous authorized_keys files (SSH controls logic only)
# (access files for which no longer a valid UNIX account exists)
# -----------------------------------------------------------------------------
if ($key_location eq 'use_controls') {
do_log ("INFO: checking for extraneous access files ....");
opendir (ACCESS_DIR, $access_dir)
or do_log ("ERROR: cannot open directory $access_dir [$! $hostname]")
or do_log ("ERROR: cannot open directory $access_dir [$!/$hostname]")
and exit (1);
while (my $access_file = readdir (ACCESS_DIR)) {
next if ($access_file =~ /^\./);
@ -644,10 +811,11 @@ print Dumper (\@zombie_files) if $debug;
# remove if requested and needed
if ($remove && @zombie_files) {
my $count = unlink (@zombie_files)
or do_log ("ERROR: cannot remove extraneous access file(s) [$! $hostname]")
or do_log ("ERROR: cannot remove extraneous access file(s) [$!/$hostname]")
and exit (1);
do_log ("INFO: $count extraneous access files removed $hostname");
}
}
exit (0);
@ -669,6 +837,7 @@ update_ssh.pl - distributes SSH public keys in a desired state model.
update_ssh.pl[-d|--debug]
[-h|--help]
[-i|--ignore]
([-p|--preview] [-g|--global]) | [-r|--remove]
[-v|--verbose]
[-V|--version]
@ -677,9 +846,11 @@ update_ssh.pl - distributes SSH public keys in a desired state model.
=head1 DESCRIPTION
B<update_ssh.pl> distributes SSH keys to the appropriate files (.e. 'authorized_keys') into the C<$access_dir> repository based on the F<access>, F<alias> and F<keys> files.
Alternatively B<update_ssh.pl> can distribute public keys to the location specified in the AuthorizedkeysFile setting of F<sshd_config> (allowing public keys to be distributed
to the traditional location in a user's HOME directory). See C<key_location> setting in F<update_ssh.conf[.local]>for more information.
This script should be run on each host where SSH key authentication is the exclusive method of (remote) authentication.
For update SSH public keys must be stored in a generic F<keys> file within the same directory as B<update_ssh.pl> script.
Orginally SSH public keys must be stored in a generic F<keys> file within the same directory as B<update_ssh.pl> script.
Alternatively key files may be stored as set of individual key files within a called sub-directory called F<keys.d>.
Both methods are mutually exclusive and the latter always take precedence.
@ -703,8 +874,12 @@ Following settings must be configured:
=item * B<use_fqdn> : whether to use short or FQDN host names
=item * B<ignore_errors> : whether to ignore errors during key deployment
=item * B<access_dir> : target directory for allowed SSH public key files
=item * B<key_location> : whether or not to use AuthorizedkeysFile setting in sshd_config for overriding $access_dir
=item * B<blacklist_file> : location of the file with blacklisted SSH public keys
=back
@ -712,7 +887,7 @@ Following settings must be configured:
=head1 BLACKLISTING
Key blacklisting can be performed by adding a public key definition in its entirety to the blacklist keys file. When a blacklisted key is
found in the available F<keys> file(s) during SSH control updates, an alert will be shown on STDOUT and the key will be ignored for the rest.
found in the available F<keys> file(s) during SSH controls updates, an alert will be shown on STDOUT and the key will be ignored for the rest.
Examples:
@ -731,11 +906,15 @@ S< >Be I<very> verbose during execution; show array/hash dumps.
S< >Show the help page.
=item -i | --ignore
S< >Ignore errors during key deployment.
=item -p | --preview
S< >Do not actually distribute any SSH public keys, nor update/remove any 'authorized_keys' files.
=item -p | --global
=item -g | --global
S< >Must be used in conjunction with the --preview option. This will dump the global namespace/configuration to STDOUT.
@ -765,12 +944,4 @@ S< >Show version of the script.
=head1 AUTHOR
(c) KUDOS BVBA, Patrick Van der Veken
=head1 history
@(#) 2014-12-04: VRF 1.0.0: first version [Patrick Van der Veken]
@(#) 2014-12-16: VRF 1.0.1: added SELinux context, new config option 'selinux_context' [Patrick Van der Veken]
@(#) 2015-08-08: VRF 1.0.2: small fix for 'cut' command [Patrick Van der Veken]
@(#) 2015-08-15: VRF 1.1.0: replace uname/hostname syscalls, now support for FQDN via $use_fqdn, other fixes [Patrick Van der Veken]
@(#) 2015-08-26: VRF 1.2.0: replace read of /etc/passwd by pwgetent() call, small and not so small fixes [Patrick Van der Veken]
(c) KUDOS BV, Patrick Van der Veken