]> git.proxmox.com Git - pve-apiclient.git/blobdiff - PVE/APIClient/LWP.pm
implement api token support
[pve-apiclient.git] / PVE / APIClient / LWP.pm
index 51112e25a22acea8228aaed9d1fb4423fc852816..c18210d88887907cdcbf57161a94bcfd5404e128 100755 (executable)
@@ -11,6 +11,7 @@ use JSON;
 use Data::Dumper; # fixme: remove
 use HTTP::Request::Common;
 use Carp;
+use PVE::APIClient::Exception qw(raise);
 
 my $extract_data = sub {
     my ($res) = @_;
@@ -87,10 +88,27 @@ sub update_ticket {
     $self->{ticket} = $ticket;
 
     my $encticket = uri_escape($ticket);
-    my $cookie = "PVEAuthCookie=$encticket; path=/; secure;";
+    my $cookie = "$self->{cookie_name}=$encticket; path=/; secure;";
     $agent->default_header('Cookie', $cookie);
 }
 
+sub two_factor_auth_login {
+    my ($self, $type, $challenge) = @_;
+
+    if ($type eq 'PVE:tfa') {
+       raise("TFA-enabled login currently works only with a TTY.") if !-t STDIN;
+       print "\nEnter OTP code for user $self->{username}: ";
+       my $tfa_response = <STDIN>;
+       chomp $tfa_response;
+       return $self->post('/api2/json/access/tfa', {response => $tfa_response});
+    } elsif ($type eq 'PVE:u2f') {
+       # TODO: implement u2f-enabled join
+       raise("U2F-enabled login is currently not implemented.");
+    } else {
+       raise("Authentication type '$type' not recognized, aborting!");
+    }
+}
+
 sub login {
     my ($self) = @_;
 
@@ -101,12 +119,13 @@ sub login {
     $uri->path('/api2/json/access/ticket');
 
     my $ua = $self->{useragent};
+    my $username = $self->{username} // 'unknown',
 
     delete $self->{last_unknown_fingerprint};
 
     my $exec_login = sub {
        return $ua->post($uri, {
-           username => $self->{username} || 'unknown',
+           username => $username,
            password => $self->{password} || ''});
     };
 
@@ -121,16 +140,23 @@ sub login {
     }
 
     if (!$response->is_success) {
-       die $response->status_line . "\n";
+       raise($response->status_line ."\n", code => $response->code)
     }
 
     my $res = from_json($response->decoded_content, {utf8 => 1, allow_nonref => 1});
 
     my $data = $extract_data->($res);
-
     $self->update_ticket($data->{ticket});
     $self->update_csrftoken($data->{CSRFPreventionToken});
 
+    # handle two-factor login
+    my $tfa_ticket_re = qr/^([^\s!]+)![^!]*(!([0-9a-zA-Z\/.=_\-+]+))?$/;
+    if ($data->{ticket} =~ m/$tfa_ticket_re/) {
+       my ($type, $challenge) = ($1, $2);
+       $data = $self->two_factor_auth_login($type, $challenge);
+       $self->update_ticket($data->{ticket});
+    }
+
     return $data;
 }
 
@@ -138,20 +164,21 @@ sub manual_verify_fingerprint {
     my ($self, $fingerprint) = @_;
 
     if (!$self->{manual_verification}) {
-       warn "fingerprint: $fingerprint\n";
-       return 0;
+       raise("fingerprint '$fingerprint' not verified, abort!\n");
     }
 
     print "The authenticity of host '$self->{host}' can't be established.\n" .
        "X509 SHA256 key fingerprint is $fingerprint.\n" .
        "Are you sure you want to continue connecting (yes/no)? ";
 
-    my $answer = <>;
+    my $answer = <STDIN>;
 
     my $valid = ($answer =~ m/^\s*yes\s*$/i) ? 1 : 0;
 
     $self->{cached_fingerprints}->{$fingerprint} = $valid;
 
+    raise("Fingerprint not verified, abort!\n") if !$valid;
+
     if (my $cb = $self->{register_fingerprint_cb}) {
        $cb->($fingerprint) if $valid;
     }
@@ -165,12 +192,13 @@ sub call {
     delete $self->{last_unknown_fingerprint};
 
     my $ticket = $self->{ticket};
+    my $apitoken = $self->{apitoken};
 
     my $ua = $self->{useragent};
 
     # fixme: check ticket lifetime?
 
-    if (!$ticket && $self->{username} && $self->{password}) {
+    if (!$ticket && !$apitoken && $self->{username} && $self->{password}) {
        $self->login();
     }
 
@@ -210,7 +238,7 @@ sub call {
        } elsif ($method eq 'DELETE') {
            $response = $ua->request(HTTP::Request::Common::DELETE($uri));
        } else {
-           die "method $method not implemented\n";
+           raise("method $method not implemented\n");
        }
        return $response;
     };
@@ -229,27 +257,21 @@ sub call {
 
     if ($response->is_success) {
 
-       die "got unexpected content type" if $ct !~ m|application/json|;
+       raise("got unexpected content type", code => $response->code)
+           if $ct !~ m|application/json|;
 
        return from_json($response->decoded_content, {utf8 => 1, allow_nonref => 1});
 
     } else {
 
-       my $msg = $response->status_line . "\n";
-       eval {
+       my $msg = $response->message;
+       my $errors = eval {
            return if $ct !~ m|application/json|;
            my $res = from_json($response->decoded_content, {utf8 => 1, allow_nonref => 1});
-           if (my $errors = $res->{errors}) {
-               foreach my $key (keys %$errors) {
-                   my $m = $errors->{$key};
-                   chomp($m);
-                   $m =~s/\n/ -- /g;
-                   $msg .= " $key: $m\n";
-               }
-           }
+           return $res->{errors};
        };
-       die $msg;
 
+       raise("$msg\n", code => $response->code, errors => $errors);
     }
 }
 
@@ -258,11 +280,8 @@ my $verify_cert_callback = sub {
 
     # check server certificate against cache of pinned FPs
     # get fingerprint of server certificate
-    my $fp;
-    eval {
-       $fp = Net::SSLeay::X509_get_fingerprint($cert, 'sha256');
-    };
-    return 0 if $@ || !defined($fp) || $fp eq ''; # error
+    my $fp = Net::SSLeay::X509_get_fingerprint($cert, 'sha256');
+    return 0 if !defined($fp) || $fp eq ''; # error
 
     my $valid = $self->{cached_fingerprints}->{$fp};
     return $valid if defined($valid); # return cached result
@@ -290,6 +309,7 @@ sub new {
        host => $param{host} || 'localhost',
        port => $param{port},
        protocol => $param{protocol},
+       cookie_name => $param{cookie_name} // 'PVEAuthCookie',
        manual_verification => $param{manual_verification},
        cached_fingerprints => $param{cached_fingerprints} || {},
        verify_fingerprint_cb => $param{verify_fingerprint_cb},
@@ -327,9 +347,26 @@ sub new {
 
     $self->{useragent}->default_header('Accept-Encoding' => 'gzip'); # allow gzip
 
-    $self->update_ticket($param{ticket}) if $param{ticket};
+    if ($param{apitoken} && $param{password}) {
+       warn "password will be ignored in favor of API token\n";
+       delete $self->{password};
+    }
+    if ($param{ticket}) {
+       if ($param{apitoken}) {
+           warn "ticket will be ignored in favor of API token\n";
+       } else {
+           $self->update_ticket($param{ticket});
+       }
+    }
     $self->update_csrftoken($param{csrftoken}) if $param{csrftoken};
 
+    if ($param{apitoken}) {
+       my $agent = $self->{useragent};
+
+       $self->{apitoken} = $param{apitoken};
+
+       $agent->default_header('Authorization', $param{apitoken});
+    }
 
     return $self;
 }