1 package PVE
::APIClient
::LWP
;
6 use IO
::Socket
::SSL
; # important for SSL_verify_callback
11 use Data
::Dumper
; # fixme: remove
12 use HTTP
::Request
::Common
;
14 use PVE
::APIClient
::Exception
qw(raise);
16 my $extract_data = sub {
19 croak
"undefined result" if !defined($res);
20 croak
"undefined result data" if !exists($res->{data
});
26 my ($self, $path, $param) = @_;
28 return $self->call('GET', $path, $param);
32 my ($self, $path, $param) = @_;
34 return $extract_data->($self->call('GET', $path, $param));
38 my ($self, $path, $param) = @_;
40 return $self->call('POST', $path, $param);
44 my ($self, $path, $param) = @_;
46 return $extract_data->($self->call('POST', $path, $param));
50 my ($self, $path, $param) = @_;
52 return $self->call('PUT', $path, $param);
56 my ($self, $path, $param) = @_;
58 return $extract_data->($self->call('PUT', $path, $param));
62 my ($self, $path, $param) = @_;
64 return $self->call('DELETE', $path, $param);
68 my ($self, $path, $param) = @_;
70 return $extract_data->($self->call('DELETE', $path, $param));
73 sub update_csrftoken
{
74 my ($self, $csrftoken) = @_;
76 $self->{csrftoken
} = $csrftoken;
78 my $agent = $self->{useragent
};
80 $agent->default_header('CSRFPreventionToken', $self->{csrftoken
});
84 my ($self, $ticket) = @_;
86 my $agent = $self->{useragent
};
88 $self->{ticket
} = $ticket;
90 my $encticket = uri_escape
($ticket);
91 my $cookie = "$self->{cookie_name}=$encticket; path=/; secure;";
92 $agent->default_header('Cookie', $cookie);
95 sub two_factor_auth_login
{
96 my ($self, $type, $challenge) = @_;
98 if ($type eq 'PVE:tfa') {
99 raise
("TFA-enabled login currently works only with a TTY.") if !-t STDIN
;
100 print "\nEnter OTP code for user $self->{username}: ";
101 my $tfa_response = <STDIN
>;
103 return $self->post('/api2/json/access/tfa', {response
=> $tfa_response});
104 } elsif ($type eq 'PVE:u2f') {
105 # TODO: implement u2f-enabled join
106 raise
("U2F-enabled login is currently not implemented.");
108 raise
("Authentication type '$type' not recognized, aborting!");
115 my $uri = URI-
>new();
116 $uri->scheme($self->{protocol
});
117 $uri->host($self->{host
});
118 $uri->port($self->{port
});
119 $uri->path('/api2/json/access/ticket');
121 my $ua = $self->{useragent
};
122 my $username = $self->{username
} // 'unknown',
124 delete $self->{last_unknown_fingerprint
};
126 my $exec_login = sub {
127 return $ua->post($uri, {
128 username
=> $username,
129 password
=> $self->{password
} || ''});
132 my $response = $exec_login->();
134 if (!$response->is_success) {
135 if (my $fp = delete($self->{last_unknown_fingerprint
})) {
136 if ($self->manual_verify_fingerprint($fp)) {
137 $response = $exec_login->(); # try again
142 if (!$response->is_success) {
143 raise
($response->status_line ."\n", code
=> $response->code)
146 my $res = from_json
($response->decoded_content, {utf8
=> 1, allow_nonref
=> 1});
148 my $data = $extract_data->($res);
149 $self->update_ticket($data->{ticket
});
150 $self->update_csrftoken($data->{CSRFPreventionToken
});
152 # handle two-factor login
153 my $tfa_ticket_re = qr/^([^\s!]+)![^!]*(!([0-9a-zA-Z\/.=_\
-+]+))?
$/;
154 if ($data->{ticket
} =~ m/$tfa_ticket_re/) {
155 my ($type, $challenge) = ($1, $2);
156 $data = $self->two_factor_auth_login($type, $challenge);
157 $self->update_ticket($data->{ticket
});
163 sub manual_verify_fingerprint
{
164 my ($self, $fingerprint) = @_;
166 if (!$self->{manual_verification
}) {
167 raise
("fingerprint '$fingerprint' not verified, abort!\n");
170 print "The authenticity of host '$self->{host}' can't be established.\n" .
171 "X509 SHA256 key fingerprint is $fingerprint.\n" .
172 "Are you sure you want to continue connecting (yes/no)? ";
174 my $answer = <STDIN
>;
176 my $valid = ($answer =~ m/^\s*yes\s*$/i) ?
1 : 0;
178 $self->{cached_fingerprints
}->{$fingerprint} = $valid;
180 raise
("Fingerprint not verified, abort!\n") if !$valid;
182 if (my $cb = $self->{register_fingerprint_cb
}) {
183 $cb->($fingerprint) if $valid;
190 my ($self, $method, $path, $param) = @_;
192 delete $self->{last_unknown_fingerprint
};
194 my $ticket = $self->{ticket
};
195 my $apitoken = $self->{apitoken
};
197 my $ua = $self->{useragent
};
199 # fixme: check ticket lifetime?
201 if (!$ticket && !$apitoken && $self->{username
} && $self->{password
}) {
205 my $uri = URI-
>new();
206 $uri->scheme($self->{protocol
});
207 $uri->host($self->{host
});
208 $uri->port($self->{port
});
212 if ($path !~ m!^api2/!) {
213 $uri->path("api2/json/$path");
218 #print "CALL $method : " . $uri->as_string() . "\n";
220 my $exec_method = sub {
223 if ($method eq 'GET') {
224 $uri->query_form($param);
225 $response = $ua->request(HTTP
::Request
::Common
::GET
($uri));
226 } elsif ($method eq 'POST') {
227 $response = $ua->request(HTTP
::Request
::Common
::POST
($uri, Content
=> $param));
228 } elsif ($method eq 'PUT') {
229 # We use another temporary URI object to format
230 # the application/x-www-form-urlencoded content.
232 my $tmpurl = URI-
>new('http:');
233 $tmpurl->query_form(%$param);
234 my $content = $tmpurl->query;
236 $response = $ua->request(HTTP
::Request
::Common
::PUT
($uri, 'Content-Type' => 'application/x-www-form-urlencoded', Content
=> $content));
238 } elsif ($method eq 'DELETE') {
239 $response = $ua->request(HTTP
::Request
::Common
::DELETE
($uri));
241 raise
("method $method not implemented\n");
246 my $response = $exec_method->();
248 if (my $fp = delete($self->{last_unknown_fingerprint
})) {
249 if ($self->manual_verify_fingerprint($fp)) {
250 $response = $exec_method->(); # try again
254 #print "RESP: " . Dumper($response) . "\n";
256 my $ct = $response->header('Content-Type') || '';
258 if ($response->is_success) {
260 raise
("got unexpected content type", code
=> $response->code)
261 if $ct !~ m
|application
/json
|;
263 return from_json
($response->decoded_content, {utf8
=> 1, allow_nonref
=> 1});
267 my $msg = $response->message;
269 return if $ct !~ m
|application
/json
|;
270 my $res = from_json
($response->decoded_content, {utf8
=> 1, allow_nonref
=> 1});
271 return $res->{errors
};
274 raise
("$msg\n", code
=> $response->code, errors
=> $errors);
278 my $verify_cert_callback = sub {
279 my ($self, $cert) = @_;
281 # check server certificate against cache of pinned FPs
282 # get fingerprint of server certificate
283 my $fp = Net
::SSLeay
::X509_get_fingerprint
($cert, 'sha256');
284 return 0 if !defined($fp) || $fp eq ''; # error
286 my $valid = $self->{cached_fingerprints
}->{$fp};
287 return $valid if defined($valid); # return cached result
289 if (my $cb = $self->{verify_fingerprint_cb
}) {
290 $valid = $cb->($cert);
291 $self->{cached_fingerprints
}->{$fp} = $valid;
295 $self->{last_unknown_fingerprint
} = $fp;
301 my ($class, %param) = @_;
303 my $ssl_default_opts = { verify_hostname
=> 0 };
304 my $ssl_opts = $param{ssl_opts
} || $ssl_default_opts;
307 username
=> $param{username
},
308 password
=> $param{password
},
309 host
=> $param{host
} || 'localhost',
310 port
=> $param{port
},
311 protocol
=> $param{protocol
},
312 cookie_name
=> $param{cookie_name
} // 'PVEAuthCookie',
313 manual_verification
=> $param{manual_verification
},
314 cached_fingerprints
=> $param{cached_fingerprints
} || {},
315 verify_fingerprint_cb
=> $param{verify_fingerprint_cb
},
316 register_fingerprint_cb
=> $param{register_fingerprint_cb
},
317 ssl_opts
=> $ssl_opts,
318 timeout
=> $param{timeout
} || 60,
322 if (!$ssl_opts->{SSL_verify_callback
}) {
323 $ssl_opts->{'SSL_verify_mode'} = SSL_VERIFY_PEER
;
324 $ssl_opts->{'SSL_verify_callback'} = sub {
325 my (undef, undef, undef, undef, $cert, $depth) = @_;
327 # we don't care about intermediate or root certificates
328 return 1 if $depth != 0;
330 return $verify_cert_callback->($self, $cert);
334 if (!$self->{port
}) {
335 $self->{port
} = $self->{host
} eq 'localhost' ?
85 : 8006;
337 if (!$self->{protocol
}) {
338 $self->{protocol
} = $self->{host
} eq 'localhost' ?
'http' : 'https';
341 $self->{useragent
} = LWP
::UserAgent-
>new(
342 protocols_allowed
=> [ 'http', 'https'],
343 ssl_opts
=> $ssl_opts,
344 timeout
=> $self->{timeout
},
345 keep_alive
=> $param{keep_alive
} // 50,
348 $self->{useragent
}->default_header('Accept-Encoding' => 'gzip'); # allow gzip
350 if ($param{apitoken
} && $param{password
}) {
351 warn "password will be ignored in favor of API token\n";
352 delete $self->{password
};
354 if ($param{ticket
}) {
355 if ($param{apitoken
}) {
356 warn "ticket will be ignored in favor of API token\n";
358 $self->update_ticket($param{ticket
});
361 $self->update_csrftoken($param{csrftoken
}) if $param{csrftoken
};
363 if ($param{apitoken
}) {
364 my $agent = $self->{useragent
};
366 $self->{apitoken
} = $param{apitoken
};
368 $agent->default_header('Authorization', $param{apitoken
});