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
};
196 my $ua = $self->{useragent
};
198 # fixme: check ticket lifetime?
200 if (!$ticket && $self->{username
} && $self->{password
}) {
204 my $uri = URI-
>new();
205 $uri->scheme($self->{protocol
});
206 $uri->host($self->{host
});
207 $uri->port($self->{port
});
211 if ($path !~ m!^api2/!) {
212 $uri->path("api2/json/$path");
217 #print "CALL $method : " . $uri->as_string() . "\n";
219 my $exec_method = sub {
222 if ($method eq 'GET') {
223 $uri->query_form($param);
224 $response = $ua->request(HTTP
::Request
::Common
::GET
($uri));
225 } elsif ($method eq 'POST') {
226 $response = $ua->request(HTTP
::Request
::Common
::POST
($uri, Content
=> $param));
227 } elsif ($method eq 'PUT') {
228 # We use another temporary URI object to format
229 # the application/x-www-form-urlencoded content.
231 my $tmpurl = URI-
>new('http:');
232 $tmpurl->query_form(%$param);
233 my $content = $tmpurl->query;
235 $response = $ua->request(HTTP
::Request
::Common
::PUT
($uri, 'Content-Type' => 'application/x-www-form-urlencoded', Content
=> $content));
237 } elsif ($method eq 'DELETE') {
238 $response = $ua->request(HTTP
::Request
::Common
::DELETE
($uri));
240 raise
("method $method not implemented\n");
245 my $response = $exec_method->();
247 if (my $fp = delete($self->{last_unknown_fingerprint
})) {
248 if ($self->manual_verify_fingerprint($fp)) {
249 $response = $exec_method->(); # try again
253 #print "RESP: " . Dumper($response) . "\n";
255 my $ct = $response->header('Content-Type') || '';
257 if ($response->is_success) {
259 raise
("got unexpected content type", code
=> $response->code)
260 if $ct !~ m
|application
/json
|;
262 return from_json
($response->decoded_content, {utf8
=> 1, allow_nonref
=> 1});
266 my $msg = $response->message;
268 return if $ct !~ m
|application
/json
|;
269 my $res = from_json
($response->decoded_content, {utf8
=> 1, allow_nonref
=> 1});
270 return $res->{errors
};
273 raise
("$msg\n", code
=> $response->code, errors
=> $errors);
277 my $verify_cert_callback = sub {
278 my ($self, $cert) = @_;
280 # check server certificate against cache of pinned FPs
281 # get fingerprint of server certificate
282 my $fp = Net
::SSLeay
::X509_get_fingerprint
($cert, 'sha256');
283 return 0 if !defined($fp) || $fp eq ''; # error
285 my $valid = $self->{cached_fingerprints
}->{$fp};
286 return $valid if defined($valid); # return cached result
288 if (my $cb = $self->{verify_fingerprint_cb
}) {
289 $valid = $cb->($cert);
290 $self->{cached_fingerprints
}->{$fp} = $valid;
294 $self->{last_unknown_fingerprint
} = $fp;
300 my ($class, %param) = @_;
302 my $ssl_default_opts = { verify_hostname
=> 0 };
303 my $ssl_opts = $param{ssl_opts
} || $ssl_default_opts;
306 username
=> $param{username
},
307 password
=> $param{password
},
308 host
=> $param{host
} || 'localhost',
309 port
=> $param{port
},
310 protocol
=> $param{protocol
},
311 cookie_name
=> $param{cookie_name
} // 'PVEAuthCookie',
312 manual_verification
=> $param{manual_verification
},
313 cached_fingerprints
=> $param{cached_fingerprints
} || {},
314 verify_fingerprint_cb
=> $param{verify_fingerprint_cb
},
315 register_fingerprint_cb
=> $param{register_fingerprint_cb
},
316 ssl_opts
=> $ssl_opts,
317 timeout
=> $param{timeout
} || 60,
321 if (!$ssl_opts->{SSL_verify_callback
}) {
322 $ssl_opts->{'SSL_verify_mode'} = SSL_VERIFY_PEER
;
323 $ssl_opts->{'SSL_verify_callback'} = sub {
324 my (undef, undef, undef, undef, $cert, $depth) = @_;
326 # we don't care about intermediate or root certificates
327 return 1 if $depth != 0;
329 return $verify_cert_callback->($self, $cert);
333 if (!$self->{port
}) {
334 $self->{port
} = $self->{host
} eq 'localhost' ?
85 : 8006;
336 if (!$self->{protocol
}) {
337 $self->{protocol
} = $self->{host
} eq 'localhost' ?
'http' : 'https';
340 $self->{useragent
} = LWP
::UserAgent-
>new(
341 protocols_allowed
=> [ 'http', 'https'],
342 ssl_opts
=> $ssl_opts,
343 timeout
=> $self->{timeout
},
344 keep_alive
=> $param{keep_alive
} // 50,
347 $self->{useragent
}->default_header('Accept-Encoding' => 'gzip'); # allow gzip
349 $self->update_ticket($param{ticket
}) if $param{ticket
};
350 $self->update_csrftoken($param{csrftoken
}) if $param{csrftoken
};