]> git.proxmox.com Git - pve-apiclient.git/blobdiff - PVE/APIClient/LWP.pm
fix #2227: enable totp codes to be passed in cli
[pve-apiclient.git] / PVE / APIClient / LWP.pm
index 81906a14e554dfb8d09dd2658916a6ea5fad6320..97fd64fba4f1497614d50882958bea522b3a06b5 100755 (executable)
@@ -92,6 +92,23 @@ sub update_ticket {
     $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) = @_;
 
@@ -102,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} || ''});
     };
 
@@ -128,10 +146,17 @@ sub login {
     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;
 }
 
@@ -139,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;
     }