2016-05-27 17:46:15 +02:00
|
|
|
// Copyright 2015, 2016 Ethcore (UK) Ltd.
|
|
|
|
// This file is part of Parity.
|
|
|
|
|
|
|
|
// Parity is free software: you can redistribute it and/or modify
|
|
|
|
// it under the terms of the GNU General Public License as published by
|
|
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
|
|
// (at your option) any later version.
|
|
|
|
|
|
|
|
// Parity is distributed in the hope that it will be useful,
|
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
// GNU General Public License for more details.
|
|
|
|
|
|
|
|
// You should have received a copy of the GNU General Public License
|
|
|
|
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
|
|
|
|
//! Session handlers factory.
|
|
|
|
|
|
|
|
use ws;
|
2016-06-07 17:21:19 +02:00
|
|
|
use authcode_store::AuthCodes;
|
|
|
|
use std::path::{PathBuf, Path};
|
2016-05-27 17:46:15 +02:00
|
|
|
use std::sync::Arc;
|
2016-06-07 17:21:19 +02:00
|
|
|
use std::str::FromStr;
|
2016-05-27 17:46:15 +02:00
|
|
|
use jsonrpc_core::IoHandler;
|
2016-09-01 12:01:44 +02:00
|
|
|
use util::{H256, Mutex, version};
|
2016-05-27 17:46:15 +02:00
|
|
|
|
2016-07-13 11:10:43 +02:00
|
|
|
#[cfg(feature = "ui")]
|
2016-10-17 11:56:42 +02:00
|
|
|
mod ui {
|
|
|
|
extern crate parity_ui as ui;
|
|
|
|
extern crate parity_dapps_glue as dapps;
|
|
|
|
|
|
|
|
use self::dapps::WebApp;
|
2016-07-12 20:15:36 +02:00
|
|
|
|
2016-10-15 14:44:08 +02:00
|
|
|
#[derive(Default)]
|
|
|
|
pub struct Handler {
|
2016-10-17 11:56:42 +02:00
|
|
|
ui: ui::App,
|
2016-10-15 14:44:08 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Handler {
|
|
|
|
pub fn handle(&self, req: &str) -> Option<&dapps::File> {
|
|
|
|
let file = match req {
|
|
|
|
"" | "/" => "index.html",
|
|
|
|
path => &path[1..],
|
|
|
|
};
|
2016-10-17 11:56:42 +02:00
|
|
|
self.ui.file(file)
|
2016-10-15 14:44:08 +02:00
|
|
|
}
|
2016-07-12 20:15:36 +02:00
|
|
|
}
|
|
|
|
}
|
2016-07-13 11:10:43 +02:00
|
|
|
#[cfg(not(feature = "ui"))]
|
2016-10-17 11:56:42 +02:00
|
|
|
mod ui {
|
2016-07-12 20:15:36 +02:00
|
|
|
pub struct File {
|
2016-10-16 00:20:11 +02:00
|
|
|
pub content: &'static [u8],
|
2016-10-15 14:44:08 +02:00
|
|
|
pub content_type: &'static str,
|
2016-07-12 20:15:36 +02:00
|
|
|
}
|
|
|
|
|
2016-10-15 14:44:08 +02:00
|
|
|
#[derive(Default)]
|
2016-10-17 11:56:42 +02:00
|
|
|
pub struct Handler;
|
2016-10-15 14:44:08 +02:00
|
|
|
|
|
|
|
impl Handler {
|
|
|
|
pub fn handle(&self, _req: &str) -> Option<&File> {
|
|
|
|
None
|
|
|
|
}
|
2016-07-12 20:15:36 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-07-12 10:28:35 +02:00
|
|
|
fn origin_is_allowed(self_origin: &str, header: Option<&[u8]>) -> bool {
|
2016-06-06 12:01:59 +02:00
|
|
|
match header {
|
|
|
|
None => false,
|
|
|
|
Some(h) => {
|
2016-07-12 10:28:35 +02:00
|
|
|
let v = String::from_utf8(h.to_owned()).ok();
|
2016-06-06 12:01:59 +02:00
|
|
|
match v {
|
|
|
|
Some(ref origin) if origin.starts_with("chrome-extension://") => true,
|
|
|
|
Some(ref origin) if origin.starts_with(self_origin) => true,
|
|
|
|
Some(ref origin) if origin.starts_with(&format!("http://{}", self_origin)) => true,
|
|
|
|
_ => false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-09-21 12:44:49 +02:00
|
|
|
fn auth_is_valid(codes_path: &Path, protocols: ws::Result<Vec<&str>>) -> bool {
|
2016-06-07 17:21:19 +02:00
|
|
|
match protocols {
|
|
|
|
Ok(ref protocols) if protocols.len() == 1 => {
|
|
|
|
protocols.iter().any(|protocol| {
|
|
|
|
let mut split = protocol.split('_');
|
|
|
|
let auth = split.next().and_then(|v| H256::from_str(v).ok());
|
|
|
|
let time = split.next().and_then(|v| u64::from_str_radix(v, 10).ok());
|
|
|
|
|
|
|
|
if let (Some(auth), Some(time)) = (auth, time) {
|
|
|
|
// Check if the code is valid
|
2016-09-21 12:44:49 +02:00
|
|
|
AuthCodes::from_file(codes_path)
|
|
|
|
.map(|mut codes| {
|
|
|
|
let res = codes.is_valid(&auth, time);
|
|
|
|
// make sure to save back authcodes - it might have been modified
|
|
|
|
if let Err(_) = codes.to_file(codes_path) {
|
|
|
|
warn!(target: "signer", "Couldn't save authorization codes to file.");
|
|
|
|
}
|
|
|
|
res
|
|
|
|
})
|
2016-06-07 17:21:19 +02:00
|
|
|
.unwrap_or(false)
|
|
|
|
} else {
|
|
|
|
false
|
|
|
|
}
|
|
|
|
})
|
|
|
|
},
|
|
|
|
_ => false
|
|
|
|
}
|
2016-06-06 12:01:59 +02:00
|
|
|
}
|
|
|
|
|
2016-06-27 10:56:26 +02:00
|
|
|
fn add_headers(mut response: ws::Response, mime: &str) -> ws::Response {
|
|
|
|
let content_len = format!("{}", response.len());
|
|
|
|
{
|
|
|
|
let mut headers = response.headers_mut();
|
|
|
|
headers.push(("X-Frame-Options".into(), b"SAMEORIGIN".to_vec()));
|
2016-10-19 11:02:21 +02:00
|
|
|
headers.push(("X-XSS-Protection".into(), b"1; mode=block".to_vec()));
|
|
|
|
headers.push(("X-Content-Type-Options".into(), b"nosniff".to_vec()));
|
2016-06-27 10:56:26 +02:00
|
|
|
headers.push(("Server".into(), b"Parity/SignerUI".to_vec()));
|
|
|
|
headers.push(("Content-Length".into(), content_len.as_bytes().to_vec()));
|
|
|
|
headers.push(("Content-Type".into(), mime.as_bytes().to_vec()));
|
|
|
|
headers.push(("Connection".into(), b"close".to_vec()));
|
|
|
|
}
|
|
|
|
response
|
|
|
|
}
|
|
|
|
|
2016-05-27 17:46:15 +02:00
|
|
|
pub struct Session {
|
2016-09-01 12:00:00 +02:00
|
|
|
out: Arc<Mutex<ws::Sender>>,
|
2016-08-02 18:53:53 +02:00
|
|
|
skip_origin_validation: bool,
|
2016-06-06 12:01:59 +02:00
|
|
|
self_origin: String,
|
2016-06-07 17:21:19 +02:00
|
|
|
authcodes_path: PathBuf,
|
2016-05-27 17:46:15 +02:00
|
|
|
handler: Arc<IoHandler>,
|
2016-10-17 11:56:42 +02:00
|
|
|
file_handler: Arc<ui::Handler>,
|
2016-05-27 17:46:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
impl ws::Handler for Session {
|
2016-08-03 19:01:48 +02:00
|
|
|
#[cfg_attr(feature="dev", allow(collapsible_if))]
|
2016-05-31 20:12:47 +02:00
|
|
|
fn on_request(&mut self, req: &ws::Request) -> ws::Result<(ws::Response)> {
|
2016-07-12 10:28:35 +02:00
|
|
|
let origin = req.header("origin").or_else(|| req.header("Origin")).map(|x| &x[..]);
|
|
|
|
let host = req.header("host").or_else(|| req.header("Host")).map(|x| &x[..]);
|
2016-09-01 10:16:04 +02:00
|
|
|
// Styles file is allowed for error pages to display nicely.
|
|
|
|
let is_styles_file = req.resource() == "/styles.css";
|
2016-06-06 12:01:59 +02:00
|
|
|
|
|
|
|
// Check request origin and host header.
|
2016-08-02 18:53:53 +02:00
|
|
|
if !self.skip_origin_validation {
|
2016-09-01 10:16:04 +02:00
|
|
|
let is_valid = origin_is_allowed(&self.self_origin, origin) || (origin.is_none() && origin_is_allowed(&self.self_origin, host));
|
|
|
|
let is_valid = is_styles_file || is_valid;
|
|
|
|
|
|
|
|
if !is_valid {
|
2016-08-02 18:53:53 +02:00
|
|
|
warn!(target: "signer", "Blocked connection to Signer API from untrusted origin.");
|
2016-08-31 16:53:22 +02:00
|
|
|
return Ok(error(
|
|
|
|
ErrorType::Forbidden,
|
|
|
|
"URL Blocked",
|
|
|
|
"You are not allowed to access Trusted Signer using this URL.",
|
|
|
|
Some(&format!("Use: http://{}", self.self_origin)),
|
|
|
|
));
|
2016-08-02 18:53:53 +02:00
|
|
|
}
|
2016-06-06 12:01:59 +02:00
|
|
|
}
|
|
|
|
|
2016-09-01 10:16:04 +02:00
|
|
|
// Detect if it's a websocket request
|
|
|
|
// (styles file skips origin validation, so make sure to prevent WS connections on this resource)
|
|
|
|
if req.header("sec-websocket-key").is_some() && !is_styles_file {
|
2016-06-07 17:21:19 +02:00
|
|
|
// Check authorization
|
|
|
|
if !auth_is_valid(&self.authcodes_path, req.protocols()) {
|
|
|
|
info!(target: "signer", "Unauthorized connection to Signer API blocked.");
|
2016-08-31 16:53:22 +02:00
|
|
|
return Ok(error(ErrorType::Forbidden, "Not Authorized", "Request to this API was not authorized.", None));
|
2016-06-07 17:21:19 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
let protocols = req.protocols().expect("Existence checked by authorization.");
|
|
|
|
let protocol = protocols.get(0).expect("Proved by authorization.");
|
|
|
|
return ws::Response::from_request(req).map(|mut res| {
|
|
|
|
// To make WebSockets connection successful we need to send back the protocol header.
|
|
|
|
res.set_protocol(protocol);
|
|
|
|
res
|
|
|
|
});
|
2016-05-31 20:12:47 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise try to serve a page.
|
2016-10-15 14:44:08 +02:00
|
|
|
Ok(self.file_handler.handle(req.resource())
|
2016-05-31 20:21:46 +02:00
|
|
|
.map_or_else(
|
2016-06-27 10:56:26 +02:00
|
|
|
// return 404 not found
|
2016-08-31 16:53:22 +02:00
|
|
|
|| error(ErrorType::NotFound, "Not found", "Requested file was not found.", None),
|
2016-05-31 20:21:46 +02:00
|
|
|
// or serve the file
|
2016-10-15 14:44:08 +02:00
|
|
|
|f| add_headers(ws::Response::ok_raw(f.content.to_vec()), f.content_type)
|
2016-06-27 10:56:26 +02:00
|
|
|
))
|
2016-05-31 20:12:47 +02:00
|
|
|
}
|
|
|
|
|
2016-05-27 17:46:15 +02:00
|
|
|
fn on_message(&mut self, msg: ws::Message) -> ws::Result<()> {
|
|
|
|
let req = try!(msg.as_text());
|
2016-09-01 12:00:00 +02:00
|
|
|
if let Some(async) = self.handler.handle_request(req) {
|
|
|
|
let out = self.out.clone();
|
|
|
|
async.on_result(move |result| {
|
|
|
|
let res = out.lock().send(result);
|
|
|
|
if let Err(e) = res {
|
|
|
|
warn!(target: "signer", "Error while sending response: {:?}", e);
|
|
|
|
}
|
|
|
|
});
|
2016-05-27 17:46:15 +02:00
|
|
|
}
|
2016-09-01 12:00:00 +02:00
|
|
|
Ok(())
|
2016-05-27 17:46:15 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct Factory {
|
|
|
|
handler: Arc<IoHandler>,
|
2016-08-02 18:53:53 +02:00
|
|
|
skip_origin_validation: bool,
|
2016-06-06 12:01:59 +02:00
|
|
|
self_origin: String,
|
2016-06-07 17:21:19 +02:00
|
|
|
authcodes_path: PathBuf,
|
2016-10-17 11:56:42 +02:00
|
|
|
file_handler: Arc<ui::Handler>,
|
2016-05-27 17:46:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Factory {
|
2016-08-02 18:53:53 +02:00
|
|
|
pub fn new(handler: Arc<IoHandler>, self_origin: String, authcodes_path: PathBuf, skip_origin_validation: bool) -> Self {
|
2016-05-27 17:46:15 +02:00
|
|
|
Factory {
|
|
|
|
handler: handler,
|
2016-08-02 18:53:53 +02:00
|
|
|
skip_origin_validation: skip_origin_validation,
|
2016-06-06 12:01:59 +02:00
|
|
|
self_origin: self_origin,
|
2016-06-07 17:21:19 +02:00
|
|
|
authcodes_path: authcodes_path,
|
2016-10-17 11:56:42 +02:00
|
|
|
file_handler: Arc::new(ui::Handler::default()),
|
2016-05-27 17:46:15 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ws::Factory for Factory {
|
|
|
|
type Handler = Session;
|
|
|
|
|
|
|
|
fn connection_made(&mut self, sender: ws::Sender) -> Self::Handler {
|
|
|
|
Session {
|
2016-09-01 12:00:00 +02:00
|
|
|
out: Arc::new(Mutex::new(sender)),
|
2016-05-27 17:46:15 +02:00
|
|
|
handler: self.handler.clone(),
|
2016-08-02 18:53:53 +02:00
|
|
|
skip_origin_validation: self.skip_origin_validation,
|
2016-06-07 17:21:19 +02:00
|
|
|
self_origin: self.self_origin.clone(),
|
|
|
|
authcodes_path: self.authcodes_path.clone(),
|
2016-10-15 14:44:08 +02:00
|
|
|
file_handler: self.file_handler.clone(),
|
2016-05-27 17:46:15 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2016-08-31 16:53:22 +02:00
|
|
|
|
|
|
|
enum ErrorType {
|
|
|
|
NotFound,
|
|
|
|
Forbidden,
|
|
|
|
}
|
|
|
|
|
|
|
|
fn error(error: ErrorType, title: &str, message: &str, details: Option<&str>) -> ws::Response {
|
|
|
|
let content = format!(
|
2016-09-01 10:16:04 +02:00
|
|
|
include_str!("./error_tpl.html"),
|
2016-08-31 16:53:22 +02:00
|
|
|
title=title,
|
|
|
|
meta="",
|
|
|
|
message=message,
|
|
|
|
details=details.unwrap_or(""),
|
|
|
|
version=version(),
|
|
|
|
);
|
|
|
|
let res = match error {
|
|
|
|
ErrorType::NotFound => ws::Response::not_found(content),
|
|
|
|
ErrorType::Forbidden => ws::Response::forbidden(content),
|
|
|
|
};
|
|
|
|
add_headers(res, "text/html")
|
|
|
|
}
|