[pve-devel] [PATCH access-control 2/2] Implement u2f authentication

Wolfgang Bumiller w.bumiller at proxmox.com
Thu May 24 15:28:49 CEST 2018


Signed-off-by: Wolfgang Bumiller <w.bumiller at proxmox.com>
---
 PVE/API2/AccessControl.pm | 215 ++++++++++++++++++++++++++++++++++++++++++++--
 PVE/AccessControl.pm      |  65 ++++++++++++--
 PVE/Auth/AD.pm            |   4 +-
 PVE/Auth/LDAP.pm          |   3 +-
 PVE/Auth/PAM.pm           |   3 +-
 PVE/Auth/PVE.pm           |  69 ++++++++++++---
 PVE/Auth/Plugin.pm        |  16 ++++
 7 files changed, 346 insertions(+), 29 deletions(-)

diff --git a/PVE/API2/AccessControl.pm b/PVE/API2/AccessControl.pm
index e48f0cb..f236651 100644
--- a/PVE/API2/AccessControl.pm
+++ b/PVE/API2/AccessControl.pm
@@ -3,6 +3,8 @@ package PVE::API2::AccessControl;
 use strict;
 use warnings;
 
+use JSON;
+
 use PVE::Exception qw(raise raise_perm_exc);
 use PVE::SafeSyslog;
 use PVE::RPCEnvironment;
@@ -16,6 +18,12 @@ use PVE::API2::Group;
 use PVE::API2::Role;
 use PVE::API2::ACL;
 
+my $u2f_available = 0;
+eval {
+    require PVE::U2F;
+    $u2f_available = 1;
+};
+
 use base qw(PVE::RESTHandler);
 
 __PACKAGE__->register_method ({
@@ -113,21 +121,33 @@ my $verify_auth = sub {
 my $create_ticket = sub {
     my ($rpcenv, $username, $pw_or_ticket, $otp) = @_;
 
-    my $ticketuser;
+    my ($ticketuser, $u2fdata);
     if (($ticketuser = PVE::AccessControl::verify_ticket($pw_or_ticket, 1)) &&
 	($ticketuser eq 'root at pam' || $ticketuser eq $username)) {
 	# valid ticket. Note: root at pam can create tickets for other users
     } else {
-	$username = PVE::AccessControl::authenticate_user($username, $pw_or_ticket, $otp);
+	($username, $u2fdata) = PVE::AccessControl::authenticate_user($username, $pw_or_ticket, $otp);
     }
 
-    my $ticket = PVE::AccessControl::assemble_ticket($username);
+    my %extra;
+    my $ticket_data = $username;
+    if (defined($u2fdata)) {
+	my $u2f = get_u2f_instance($u2fdata->@{qw(publicKey keyHandle)});
+	my $challenge = $u2f->auth_challenge()
+	    or die "failed to get u2f challenge\n";
+	$challenge = decode_json($challenge);
+	$extra{U2FChallenge} = $challenge;
+	$ticket_data = "u2f!$username!$challenge->{challenge}";
+    }
+
+    my $ticket = PVE::AccessControl::assemble_ticket($ticket_data);
     my $csrftoken = PVE::AccessControl::assemble_csrf_prevention_token($username);
 
     return {
 	ticket => $ticket,
 	username => $username,
 	CSRFPreventionToken => $csrftoken,
+	%extra,
     };
 };
 
@@ -246,6 +266,8 @@ __PACKAGE__->register_method ({
 	    username => { type => 'string' },
 	    ticket => { type => 'string', optional => 1},
 	    CSRFPreventionToken => { type => 'string', optional => 1 },
+	    challenge => { type => 'string', optional => 1 },
+	    # cap => computed api permissions, unless there's a u2f challenge
 	}
     },
     code => sub {
@@ -275,7 +297,8 @@ __PACKAGE__->register_method ({
 	    die PVE::Exception->new("authentication failure\n", code => 401);
 	}
 
-	$res->{cap} = &$compute_api_permission($rpcenv, $username);
+	$res->{cap} = &$compute_api_permission($rpcenv, $username)
+	    if !defined($res->{U2FChallenge});
 
 	PVE::Cluster::log_msg('info', 'root at pam', "successful auth for user '$username'");
 
@@ -287,7 +310,7 @@ __PACKAGE__->register_method ({
     path => 'password', 
     method => 'PUT',
     permissions => { 
-	description => "Each user is allowed to change his own password. A user can change the password of another user if he has 'Realm.AllocateUser' (on the realm of user <userid>) and 'User.Modify' permission on /access/groups/<group> on a group where user <userid> is member of.",
+	description => "Each user is allowed to change their own password. A user can change the password of another user if they have 'Realm.AllocateUser' (on the realm of user <userid>) and 'User.Modify' permission on /access/groups/<group> on a group where user <userid> is member of.",
 	check => [ 'or', 
 		   ['userid-param', 'self'],
 		   [ 'and',
@@ -344,4 +367,186 @@ __PACKAGE__->register_method ({
 	return undef;
     }});
 
+sub get_u2f_config() {
+    die "u2f support not available\n" if !$u2f_available;
+
+    my $dc = cfs_read_file('datacenter.cfg');
+    my $u2f = $dc->{u2f};
+    die "u2f not configured in datacenter.cfg\n" if !$u2f;
+    $u2f = PVE::JSONSchema::parse_property_string($PVE::Cluster::u2f_format, $u2f);
+    return $u2f;
+}
+
+sub get_u2f_instance {
+    my ($publicKey, $keyHandle) = @_;
+
+    my $u2fconfig = get_u2f_config();
+    my $u2f = PVE::U2F->new();
+    $u2f->set_appid($u2fconfig->{appid});
+    $u2f->set_origin($u2fconfig->{origin});
+    $u2f->set_publicKey($publicKey) if defined($publicKey);
+    $u2f->set_keyHandle($keyHandle) if defined($keyHandle);
+    return $u2f;
+}
+
+__PACKAGE__->register_method ({
+    name => 'change_u2f',
+    path => 'u2f',
+    method => 'PUT',
+    permissions => {
+	description => 'A user can change their own u2f token.',
+	check => [ 'or',
+		   ['userid-param', 'self'],
+		   [ 'and',
+		     [ 'userid-param', 'Realm.AllocateUser'],
+		     [ 'userid-group', ['User.Modify']]
+		   ]
+	    ],
+    },
+    protected => 1, # else we can't access shadow files
+    description => "Change user u2f authentication.",
+    parameters => {
+	additionalProperties => 0,
+	properties => {
+	    userid => get_standard_option('userid', {
+		completion => \&PVE::AccessControl::complete_username,
+	    }),
+	    password => {
+		optional => 1, # Only required if not root at pam
+		description => "The current password.",
+		type => 'string',
+		minLength => 5,
+		maxLength => 64,
+	    },
+	    action => {
+		description => 'The action to perform',
+		type => 'string',
+		enum => [qw(delete new confirm)],
+	    },
+	    response => {
+		optional => 1,
+		description => 'The response to the current registration challenge.',
+		type => 'string',
+	    },
+	}
+    },
+    returns => { type => 'object' },
+    code => sub {
+	my ($param) = @_;
+
+	my $rpcenv = PVE::RPCEnvironment::get();
+	my $authuser = $rpcenv->get_user();
+
+	my $action = delete $param->{action};
+	my $response = delete $param->{response};
+	my $password = delete($param->{password}) // '';
+
+	my ($userid, $ruid, $realm) = PVE::AccessControl::verify_username($param->{userid});
+	$rpcenv->check_user_exist($userid);
+
+	# Only root may modify root
+	raise_perm_exc() if $userid eq 'root at pam' && $authuser ne 'root at pam';
+
+	# Regular users need to confirm their password to change u2f settings.
+	if ($authuser ne 'root at pam') {
+	    raise_param_exc('password' => 'password is required to modify u2f data')
+		if !defined($password);
+	    my $domain_cfg = cfs_read_file('domains.cfg');
+	    my $cfg = $domain_cfg->{ids}->{$realm};
+	    die "auth domain '$realm' does not exists\n" if !$cfg;
+	    my $plugin = PVE::Auth::Plugin->lookup($cfg->{type});
+	    $plugin->authenticate_user($cfg, $realm, $ruid, $password);
+	}
+
+	if ($action eq 'delete') {
+	    PVE::AccessControl::domain_set_u2f($realm, $ruid, undef);
+	    PVE::Cluster::log_msg('info', $authuser, "deleted u2f data for user '$userid'");
+	} elsif ($action eq 'new') {
+	    my $u2f = get_u2f_instance();
+	    my $challenge = $u2f->registration_challenge()
+		or raise("failed to get u2f challenge");
+	    $challenge = decode_json($challenge);
+	    PVE::AccessControl::domain_set_u2f($realm, $ruid, $challenge);
+	    return $challenge;
+	} elsif ($action eq 'confirm') {
+	    raise_param_exc('response' => "confirm action requires the 'response' parameter to be set")
+		if !defined($response);
+	    my $data = PVE::AccessControl::domain_get_u2f($realm, $ruid);
+	    my $challenge = $data->{challenge}
+		or raise("no active challenge");
+	    my $u2f = get_u2f_instance();
+	    $u2f->set_challenge($challenge);
+	    my ($keyHandle, $publicKey) = $u2f->registration_verify($response);
+	    PVE::AccessControl::domain_set_u2f($realm, $ruid, {
+		keyHandle => $keyHandle,
+		publicKey => $publicKey,
+	    });
+	} else {
+	    die "invalid action: $action\n";
+	}
+
+	return {};
+    }});
+
+__PACKAGE__->register_method({
+    name => 'verify_u2f',
+    path => 'u2f',
+    method => 'POST',
+    permissions => { user => 'all' },
+    protected => 1, # else we can't access shadow files
+    description => 'Finish a u2f challenge.',
+    parameters => {
+	additionalProperties => 0,
+	properties => {
+	    response => {
+		type => 'string',
+		description => 'The response to the current authentication challenge.',
+	    },
+	}
+    },
+    returns => {
+	type => 'object',
+	properties => {
+	    ticket => { type => 'string' },
+	    # cap
+	}
+    },
+    code => sub {
+	my ($param) = @_;
+
+	my $rpcenv = PVE::RPCEnvironment::get();
+	my $challenge = $rpcenv->get_u2f_challenge()
+	    or raise('no active challenge');
+	my $authuser = $rpcenv->get_user();
+	my ($userid, $ruid, $realm) = PVE::AccessControl::verify_username($authuser);
+
+	my $u2fdata = PVE::AccessControl::domain_get_u2f($realm, $ruid)
+	    or raise('no u2f data available');
+
+	my $keyHandle = $u2fdata->{keyHandle};
+	my $publicKey = $u2fdata->{publicKey};
+	raise("incomplete u2f setup")
+	    if !defined($keyHandle) || !defined($publicKey);
+
+	my $u2f = get_u2f_instance($publicKey, $keyHandle);
+	$u2f->set_challenge($challenge);
+
+	eval {
+	    my ($counter, $present) = $u2f->auth_verify($param->{response});
+	    # Do we want to do anything with these?
+	};
+	if (my $err = $@) {
+	    my $clientip = $rpcenv->get_client_ip() || '';
+	    syslog('err', "authentication verification failure; rhost=$clientip user=$authuser msg=$err");
+	    die PVE::Exception->new("authentication failure\n", code => 401);
+	}
+
+	# create a new ticket for the user:
+	my $ticket_data = "u2f!$authuser!verified";
+	return {
+	    ticket => PVE::AccessControl::assemble_ticket($ticket_data),
+	    cap => &$compute_api_permission($rpcenv, $authuser),
+	}
+    }});
+
 1;
diff --git a/PVE/AccessControl.pm b/PVE/AccessControl.pm
index f0fb7dc..4e53504 100644
--- a/PVE/AccessControl.pm
+++ b/PVE/AccessControl.pm
@@ -9,6 +9,7 @@ use Net::SSLeay;
 use Net::IP;
 use MIME::Base64;
 use Digest::SHA;
+use JSON;
 
 use PVE::OTP;
 use PVE::Ticket;
@@ -113,11 +114,11 @@ sub get_privkey {
 }
 
 sub assemble_ticket {
-    my ($username) = @_;
+    my ($data) = @_;
 
     my $rsa_priv = get_privkey();
 
-    return PVE::Ticket::assemble_rsa_ticket($rsa_priv, 'PVE', $username);
+    return PVE::Ticket::assemble_rsa_ticket($rsa_priv, 'PVE', $data);
 }
 
 sub verify_ticket {
@@ -125,14 +126,32 @@ sub verify_ticket {
 
     my $rsa_pub = get_pubkey();
 
-    my ($username, $age) = PVE::Ticket::verify_rsa_ticket(
+    my ($data, $age) = PVE::Ticket::verify_rsa_ticket(
 	$rsa_pub, 'PVE', $ticket, undef, -300, $ticket_lifetime, $noerr);
 
-    return undef if $noerr && !defined($username);
+    return undef if $noerr && !defined($data);
+
+    my ($username, $challenge);
+    if ($data =~ m{^u2f!([^!]+)!([0-9a-zA-Z/.=_\-+]+)$}) {
+	($username, $challenge) = ($1, $2);
+	if ($challenge eq 'verified') {
+	    $challenge = undef;
+	} else {
+	    if (!wantarray) {
+		# A ticket awaiting 2nd factor verification is only valid if
+		# the caller is aware there could be one...
+		return undef if $noerr;
+		# Get the same error we'd get from an invalid ticket:
+		PVE::Ticket::verify_rsa_ticket(undef, 'PVE');
+	    }
+	}
+    } else {
+	$username = $data;
+    }
 
     return undef if !PVE::Auth::Plugin::verify_username($username, $noerr);
 
-    return wantarray ? ($username, $age) : $username;
+    return wantarray ? ($username, $age, $challenge) : $username;
 }
 
 # VNC tickets
@@ -314,14 +333,19 @@ sub authenticate_user {
     my $cfg = $domain_cfg->{ids}->{$realm};
     die "auth domain '$realm' does not exists\n" if !$cfg;
     my $plugin = PVE::Auth::Plugin->lookup($cfg->{type});
-    $plugin->authenticate_user($cfg, $realm, $ruid, $password);
+    my $u2f = $plugin->authenticate_user($cfg, $realm, $ruid, $password);
+
+    if (defined($u2f) && exists($u2f->{challenge})) {
+	# u2f setup was not completed, discard
+	$u2f = undef;
+    }
 
     if ($cfg->{tfa}) {
 	my $tfa_cfg = PVE::Auth::Plugin::parse_tfa_config($cfg->{tfa});
 	verify_one_time_pw($usercfg, $username, $tfa_cfg, $otp);
     }
 
-    return $username;
+    return wantarray ? ($username, $u2f) : $username;
 }
 
 sub domain_set_password {
@@ -1076,6 +1100,33 @@ sub remove_vm_from_pool {
     lock_user_config($delVMfromPoolFn, "pool cleanup for VM $vmid failed");
 }
 
+sub domain_set_u2f {
+    my ($realm, $username, $u2f) = @_;
+
+    die "no auth domain specified" if !$realm;
+
+    my $domain_cfg = cfs_read_file('domains.cfg');
+
+    my $cfg = $domain_cfg->{ids}->{$realm};
+    die "auth domain '$realm' does not exist\n" if !$cfg;
+    my $plugin = PVE::Auth::Plugin->lookup($cfg->{type});
+    $plugin->store_u2f($cfg, $realm, $username, $u2f);
+}
+
+sub domain_get_u2f {
+    my ($realm, $username) = @_;
+
+    die "no auth domain specified" if !$realm;
+
+    my $domain_cfg = cfs_read_file('domains.cfg');
+
+    my $cfg = $domain_cfg->{ids}->{$realm};
+    die "auth domain '$realm' does not exist\n" if !$cfg;
+    my $plugin = PVE::Auth::Plugin->lookup($cfg->{type});
+    return $plugin->get_u2f($cfg, $realm, $username);
+}
+
+
 # bash completion helpers
 
 sub complete_username {
diff --git a/PVE/Auth/AD.pm b/PVE/Auth/AD.pm
index b924b02..d000940 100755
--- a/PVE/Auth/AD.pm
+++ b/PVE/Auth/AD.pm
@@ -128,10 +128,10 @@ sub authenticate_user {
 
     eval { &$authenticate_user_ad($config, $config->{server1}, $username, $password); };
     my $err = $@;
-    return 1 if !$err;
+    return undef if !$err;
     die $err if !$config->{server2};
     &$authenticate_user_ad($config, $config->{server2}, $username, $password);
-    return 1;
+    return undef;
 }
 
 1;
diff --git a/PVE/Auth/LDAP.pm b/PVE/Auth/LDAP.pm
index 9f08504..9a04de5 100755
--- a/PVE/Auth/LDAP.pm
+++ b/PVE/Auth/LDAP.pm
@@ -143,9 +143,10 @@ sub authenticate_user {
 
     eval { &$authenticate_user_ldap($config, $config->{server1}, $username, $password, $realm); };
     my $err = $@;
-    return 1 if !$err;
+    return undef if !$err;
     die $err if !$config->{server2};
     &$authenticate_user_ldap($config, $config->{server2}, $username, $password, $realm);
+    return undef;
 }
 
 1;
diff --git a/PVE/Auth/PAM.pm b/PVE/Auth/PAM.pm
index 42feba8..65c7512 100755
--- a/PVE/Auth/PAM.pm
+++ b/PVE/Auth/PAM.pm
@@ -56,8 +56,7 @@ sub authenticate_user {
     }
 
     $pamh = 0; # call destructor
-
-    return 1;
+    return undef;
 }
 
 
diff --git a/PVE/Auth/PVE.pm b/PVE/Auth/PVE.pm
index de39d35..bdaa29b 100755
--- a/PVE/Auth/PVE.pm
+++ b/PVE/Auth/PVE.pm
@@ -4,6 +4,9 @@ use strict;
 use warnings;
 use Encode;
 
+use MIME::Base64;
+use JSON;
+
 use PVE::Tools;
 use PVE::Auth::Plugin;
 use PVE::Cluster qw(cfs_register_file cfs_read_file cfs_write_file cfs_lock_file);
@@ -26,13 +29,14 @@ sub parse_shadow_passwd {
     while ($raw =~ /^\s*(.+?)\s*$/gm) {
 	my $line = $1;
 
-	if ($line !~ m/^\S+:\S+:$/) {
+	if ($line !~ m@^\S+:\S+:(?:([A-Za-z0-9+/.=]+):)?$@) {
 	    warn "pve shadow password: ignore invalid line $.\n";
 	    next;
 	}
 
-	my ($userid, $crypt_pass) = split (/:/, $line);
+	my ($userid, $crypt_pass, $u2f) = split (/:/, $line);
 	$shadow->{users}->{$userid}->{shadow} = $crypt_pass;
+	$shadow->{users}->{$userid}->{u2f} = length($u2f) ? $u2f : undef;
     }
 
     return $shadow;
@@ -44,7 +48,8 @@ sub write_shadow_config {
     my $data = '';
     foreach my $userid (keys %{$cfg->{users}}) {
 	my $crypt_pass = $cfg->{users}->{$userid}->{shadow};
-	$data .= "$userid:$crypt_pass:\n";
+	my $u2f = $cfg->{users}->{$userid}->{u2f} // '';
+	$data .= "$userid:$crypt_pass:$u2f:\n";
     }
 
     return $data
@@ -72,22 +77,33 @@ sub options {
     };
 }
 
+my $decode_u2f = sub {
+    my ($u2f) = @_;
+    $u2f = decode_json(decode_base64($u2f));
+    if (defined(my $pubkey = $u2f->{publicKey})) {
+	$u2f->{publicKey} = decode_base64($pubkey);
+    }
+    return $u2f;
+};
+
 sub authenticate_user {
     my ($class, $config, $realm, $username, $password) = @_;
 
     die "no password\n" if !$password;
 
     my $shadow_cfg = cfs_read_file($shadowconfigfile);
-    
-    if ($shadow_cfg->{users}->{$username}) {
-	my $encpw = crypt(Encode::encode('utf8', $password),
-			  $shadow_cfg->{users}->{$username}->{shadow});
-       die "invalid credentials\n" if ($encpw ne $shadow_cfg->{users}->{$username}->{shadow});
-    } else {
-	die "no password set\n";
-    }
 
-    return 1;
+    die "no password set\n"
+	if !$shadow_cfg->{users}->{$username};
+
+    my $userdata = $shadow_cfg->{users}->{$username};
+
+    my $encpw = crypt(Encode::encode('utf8', $password), $userdata->{shadow});
+    die "invalid credentials\n" if ($encpw ne $userdata->{shadow});
+    if (defined(my $u2f = $userdata->{u2f})) {
+	return $decode_u2f->($u2f);
+    }
+    return undef;
 }
 
 sub store_password {
@@ -113,4 +129,33 @@ sub delete_user {
    });
 }
 
+sub store_u2f {
+    my ($class, $config, $realm, $username, $u2f) = @_;
+
+    if (defined($u2f)) {
+	if (defined(my $pubkey = $u2f->{publicKey})) {
+	    $u2f->{publicKey} = encode_base64($pubkey, '');
+	}
+	$u2f = encode_base64(encode_json($u2f), '');
+	$u2f =~ s/\n//g;
+    }
+
+    lock_shadow_config(sub {
+	my $shadow_cfg = cfs_read_file($shadowconfigfile);
+	$shadow_cfg->{users}->{$username}->{u2f} = $u2f;
+	cfs_write_file($shadowconfigfile, $shadow_cfg);
+    });
+}
+
+sub get_u2f {
+    my ($class, $config, $realm, $username) = @_;
+
+    my $u2f;
+    lock_shadow_config(sub {
+	my $shadow_cfg = cfs_read_file($shadowconfigfile);
+	$u2f = $shadow_cfg->{users}->{$username}->{u2f};
+    });
+    return defined($u2f) ? $decode_u2f->($u2f) : undef;
+}
+
 1;
diff --git a/PVE/Auth/Plugin.pm b/PVE/Auth/Plugin.pm
index d5d2c06..14909c2 100755
--- a/PVE/Auth/Plugin.pm
+++ b/PVE/Auth/Plugin.pm
@@ -223,4 +223,20 @@ sub delete_user {
     # do nothing by default
 }
 
+sub store_u2f {
+    my ($class, $config, $realm, $username, $token) = @_;
+
+    my $type = $class->type();
+
+    die "can't modify u2f data on auth type '$type'\n";
+}
+
+sub get_u2f {
+    my ($class, $config, $realm, $username) = @_;
+
+    my $type = $class->type();
+
+    die "can't get u2f data on auth type '$type'\n";
+}
+
 1;
-- 
2.11.0




More information about the pve-devel mailing list