2021-12-26 20:18:42 +00:00
|
|
|
use std::{
|
|
|
|
borrow::Cow,
|
|
|
|
collections::BTreeMap,
|
|
|
|
convert::Infallible,
|
|
|
|
net::{Ipv4Addr, SocketAddr},
|
|
|
|
pin::Pin,
|
|
|
|
sync::Arc,
|
|
|
|
task::{Context, Poll},
|
|
|
|
};
|
|
|
|
|
2022-01-08 19:51:51 +00:00
|
|
|
use aes::{
|
2021-12-26 20:18:42 +00:00
|
|
|
cipher::generic_array::GenericArray,
|
2022-01-08 19:51:51 +00:00
|
|
|
cipher::{NewCipher, StreamCipher},
|
2021-12-26 20:18:42 +00:00
|
|
|
Aes128Ctr,
|
|
|
|
};
|
2021-02-28 23:10:13 +00:00
|
|
|
use futures_core::Stream;
|
2021-12-26 20:18:42 +00:00
|
|
|
use futures_util::{FutureExt, TryFutureExt};
|
2021-02-28 23:10:13 +00:00
|
|
|
use hmac::{Hmac, Mac, NewMac};
|
2021-12-26 20:18:42 +00:00
|
|
|
use hyper::{
|
|
|
|
service::{make_service_fn, service_fn},
|
|
|
|
Body, Method, Request, Response, StatusCode,
|
|
|
|
};
|
|
|
|
use log::{debug, error, warn};
|
2021-02-28 23:10:13 +00:00
|
|
|
use serde_json::json;
|
|
|
|
use sha1::{Digest, Sha1};
|
|
|
|
use tokio::sync::{mpsc, oneshot};
|
|
|
|
|
2021-12-26 20:18:42 +00:00
|
|
|
use super::DiscoveryError;
|
|
|
|
|
2022-01-05 20:15:19 +00:00
|
|
|
use crate::{
|
2022-01-06 08:48:11 +00:00
|
|
|
core::config::DeviceType,
|
2022-01-05 20:15:19 +00:00
|
|
|
core::{authentication::Credentials, diffie_hellman::DhLocalKeys, Error},
|
2021-12-26 20:18:42 +00:00
|
|
|
};
|
2021-02-28 23:10:13 +00:00
|
|
|
|
|
|
|
type Params<'a> = BTreeMap<Cow<'a, str>, Cow<'a, str>>;
|
|
|
|
|
|
|
|
pub struct Config {
|
|
|
|
pub name: Cow<'static, str>,
|
|
|
|
pub device_type: DeviceType,
|
|
|
|
pub device_id: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
struct RequestHandler {
|
|
|
|
config: Config,
|
|
|
|
keys: DhLocalKeys,
|
|
|
|
tx: mpsc::UnboundedSender<Credentials>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl RequestHandler {
|
|
|
|
fn new(config: Config) -> (Self, mpsc::UnboundedReceiver<Credentials>) {
|
|
|
|
let (tx, rx) = mpsc::unbounded_channel();
|
|
|
|
|
|
|
|
let discovery = Self {
|
|
|
|
config,
|
|
|
|
keys: DhLocalKeys::random(&mut rand::thread_rng()),
|
|
|
|
tx,
|
|
|
|
};
|
|
|
|
|
|
|
|
(discovery, rx)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn handle_get_info(&self) -> Response<hyper::Body> {
|
|
|
|
let public_key = base64::encode(&self.keys.public_key());
|
|
|
|
let device_type: &str = self.config.device_type.into();
|
|
|
|
|
|
|
|
let body = json!({
|
|
|
|
"status": 101,
|
|
|
|
"statusString": "ERROR-OK",
|
|
|
|
"spotifyError": 0,
|
2021-12-09 18:00:27 +00:00
|
|
|
"version": crate::core::version::SEMVER,
|
2021-02-28 23:10:13 +00:00
|
|
|
"deviceID": (self.config.device_id),
|
|
|
|
"remoteName": (self.config.name),
|
|
|
|
"activeUser": "",
|
|
|
|
"publicKey": (public_key),
|
|
|
|
"deviceType": (device_type),
|
2021-05-24 09:54:01 +00:00
|
|
|
"libraryVersion": crate::core::version::SEMVER,
|
2021-02-28 23:10:13 +00:00
|
|
|
"accountReq": "PREMIUM",
|
|
|
|
"brandDisplayName": "librespot",
|
|
|
|
"modelDisplayName": "librespot",
|
|
|
|
"resolverVersion": "0",
|
|
|
|
"groupStatus": "NONE",
|
|
|
|
"voiceSupport": "NO",
|
|
|
|
})
|
|
|
|
.to_string();
|
|
|
|
|
|
|
|
Response::new(Body::from(body))
|
|
|
|
}
|
|
|
|
|
2021-12-26 20:18:42 +00:00
|
|
|
fn handle_add_user(&self, params: &Params<'_>) -> Result<Response<hyper::Body>, Error> {
|
|
|
|
let username_key = "userName";
|
|
|
|
let username = params
|
|
|
|
.get(username_key)
|
|
|
|
.ok_or(DiscoveryError::ParamsError(username_key))?
|
|
|
|
.as_ref();
|
|
|
|
|
|
|
|
let blob_key = "blob";
|
|
|
|
let encrypted_blob = params
|
|
|
|
.get(blob_key)
|
|
|
|
.ok_or(DiscoveryError::ParamsError(blob_key))?;
|
|
|
|
|
|
|
|
let clientkey_key = "clientKey";
|
|
|
|
let client_key = params
|
|
|
|
.get(clientkey_key)
|
|
|
|
.ok_or(DiscoveryError::ParamsError(clientkey_key))?;
|
2021-02-28 23:10:13 +00:00
|
|
|
|
2021-12-26 20:18:42 +00:00
|
|
|
let encrypted_blob = base64::decode(encrypted_blob.as_bytes())?;
|
2021-02-28 23:10:13 +00:00
|
|
|
|
2021-12-26 20:18:42 +00:00
|
|
|
let client_key = base64::decode(client_key.as_bytes())?;
|
2021-02-28 23:10:13 +00:00
|
|
|
let shared_key = self.keys.shared_secret(&client_key);
|
|
|
|
|
2021-12-29 22:15:08 +00:00
|
|
|
let encrypted_blob_len = encrypted_blob.len();
|
|
|
|
if encrypted_blob_len < 16 {
|
|
|
|
return Err(DiscoveryError::HmacError(encrypted_blob.to_vec()).into());
|
|
|
|
}
|
|
|
|
|
2021-02-28 23:10:13 +00:00
|
|
|
let iv = &encrypted_blob[0..16];
|
2021-12-29 22:15:08 +00:00
|
|
|
let encrypted = &encrypted_blob[16..encrypted_blob_len - 20];
|
|
|
|
let cksum = &encrypted_blob[encrypted_blob_len - 20..encrypted_blob_len];
|
2021-02-28 23:10:13 +00:00
|
|
|
|
|
|
|
let base_key = Sha1::digest(&shared_key);
|
|
|
|
let base_key = &base_key[..16];
|
|
|
|
|
|
|
|
let checksum_key = {
|
2021-12-26 20:18:42 +00:00
|
|
|
let mut h = Hmac::<Sha1>::new_from_slice(base_key)
|
|
|
|
.map_err(|_| DiscoveryError::HmacError(base_key.to_vec()))?;
|
2021-02-28 23:10:13 +00:00
|
|
|
h.update(b"checksum");
|
|
|
|
h.finalize().into_bytes()
|
|
|
|
};
|
|
|
|
|
|
|
|
let encryption_key = {
|
2021-12-26 20:18:42 +00:00
|
|
|
let mut h = Hmac::<Sha1>::new_from_slice(base_key)
|
|
|
|
.map_err(|_| DiscoveryError::HmacError(base_key.to_vec()))?;
|
2021-02-28 23:10:13 +00:00
|
|
|
h.update(b"encryption");
|
|
|
|
h.finalize().into_bytes()
|
|
|
|
};
|
|
|
|
|
2021-12-26 20:18:42 +00:00
|
|
|
let mut h = Hmac::<Sha1>::new_from_slice(&checksum_key)
|
|
|
|
.map_err(|_| DiscoveryError::HmacError(base_key.to_vec()))?;
|
2021-02-28 23:10:13 +00:00
|
|
|
h.update(encrypted);
|
|
|
|
if h.verify(cksum).is_err() {
|
|
|
|
warn!("Login error for user {:?}: MAC mismatch", username);
|
|
|
|
let result = json!({
|
|
|
|
"status": 102,
|
|
|
|
"spotifyError": 1,
|
|
|
|
"statusString": "ERROR-MAC"
|
|
|
|
});
|
|
|
|
|
|
|
|
let body = result.to_string();
|
2021-12-26 20:18:42 +00:00
|
|
|
return Ok(Response::new(Body::from(body)));
|
2021-02-28 23:10:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
let decrypted = {
|
|
|
|
let mut data = encrypted.to_vec();
|
|
|
|
let mut cipher = Aes128Ctr::new(
|
|
|
|
GenericArray::from_slice(&encryption_key[0..16]),
|
|
|
|
GenericArray::from_slice(iv),
|
|
|
|
);
|
|
|
|
cipher.apply_keystream(&mut data);
|
2021-05-26 18:45:22 +00:00
|
|
|
data
|
2021-02-28 23:10:13 +00:00
|
|
|
};
|
|
|
|
|
2021-12-26 20:18:42 +00:00
|
|
|
let credentials = Credentials::with_blob(username, &decrypted, &self.config.device_id)?;
|
2021-02-28 23:10:13 +00:00
|
|
|
|
2021-12-26 20:18:42 +00:00
|
|
|
self.tx.send(credentials)?;
|
2021-02-28 23:10:13 +00:00
|
|
|
|
|
|
|
let result = json!({
|
|
|
|
"status": 101,
|
|
|
|
"spotifyError": 0,
|
|
|
|
"statusString": "ERROR-OK"
|
|
|
|
});
|
|
|
|
|
|
|
|
let body = result.to_string();
|
2021-12-26 20:18:42 +00:00
|
|
|
Ok(Response::new(Body::from(body)))
|
2021-02-28 23:10:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn not_found(&self) -> Response<hyper::Body> {
|
|
|
|
let mut res = Response::default();
|
|
|
|
*res.status_mut() = StatusCode::NOT_FOUND;
|
|
|
|
res
|
|
|
|
}
|
|
|
|
|
2021-12-26 20:18:42 +00:00
|
|
|
async fn handle(
|
|
|
|
self: Arc<Self>,
|
|
|
|
request: Request<Body>,
|
|
|
|
) -> Result<hyper::Result<Response<Body>>, Error> {
|
2021-02-28 23:10:13 +00:00
|
|
|
let mut params = Params::new();
|
|
|
|
|
|
|
|
let (parts, body) = request.into_parts();
|
|
|
|
|
|
|
|
if let Some(query) = parts.uri.query() {
|
|
|
|
let query_params = form_urlencoded::parse(query.as_bytes());
|
|
|
|
params.extend(query_params);
|
|
|
|
}
|
|
|
|
|
|
|
|
if parts.method != Method::GET {
|
|
|
|
debug!("{:?} {:?} {:?}", parts.method, parts.uri.path(), params);
|
|
|
|
}
|
|
|
|
|
|
|
|
let body = hyper::body::to_bytes(body).await?;
|
|
|
|
|
|
|
|
params.extend(form_urlencoded::parse(&body));
|
|
|
|
|
|
|
|
let action = params.get("action").map(Cow::as_ref);
|
|
|
|
|
2021-12-26 20:18:42 +00:00
|
|
|
Ok(Ok(match (parts.method, action) {
|
2021-02-28 23:10:13 +00:00
|
|
|
(Method::GET, Some("getInfo")) => self.handle_get_info(),
|
2021-12-26 20:18:42 +00:00
|
|
|
(Method::POST, Some("addUser")) => self.handle_add_user(¶ms)?,
|
2021-02-28 23:10:13 +00:00
|
|
|
_ => self.not_found(),
|
2021-12-26 20:18:42 +00:00
|
|
|
}))
|
2021-02-28 23:10:13 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct DiscoveryServer {
|
|
|
|
cred_rx: mpsc::UnboundedReceiver<Credentials>,
|
|
|
|
_close_tx: oneshot::Sender<Infallible>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl DiscoveryServer {
|
2021-12-26 20:18:42 +00:00
|
|
|
pub fn new(config: Config, port: &mut u16) -> Result<hyper::Result<Self>, Error> {
|
2021-02-28 23:10:13 +00:00
|
|
|
let (discovery, cred_rx) = RequestHandler::new(config);
|
|
|
|
let discovery = Arc::new(discovery);
|
|
|
|
|
|
|
|
let (close_tx, close_rx) = oneshot::channel();
|
|
|
|
|
|
|
|
let address = SocketAddr::new(Ipv4Addr::UNSPECIFIED.into(), *port);
|
|
|
|
|
|
|
|
let make_service = make_service_fn(move |_| {
|
|
|
|
let discovery = discovery.clone();
|
|
|
|
async move {
|
2021-12-26 20:18:42 +00:00
|
|
|
Ok::<_, hyper::Error>(service_fn(move |request| {
|
|
|
|
discovery
|
|
|
|
.clone()
|
|
|
|
.handle(request)
|
|
|
|
.inspect_err(|e| error!("could not handle discovery request: {}", e))
|
|
|
|
.and_then(|x| async move { Ok(x) })
|
|
|
|
.map(Result::unwrap) // guaranteed by `and_then` above
|
|
|
|
}))
|
2021-02-28 23:10:13 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
let server = hyper::Server::try_bind(&address)?.serve(make_service);
|
|
|
|
|
|
|
|
*port = server.local_addr().port();
|
|
|
|
debug!("Zeroconf server listening on 0.0.0.0:{}", *port);
|
|
|
|
|
|
|
|
tokio::spawn(async {
|
|
|
|
let result = server
|
|
|
|
.with_graceful_shutdown(async {
|
|
|
|
debug!("Shutting down discovery server");
|
2021-12-26 20:18:42 +00:00
|
|
|
if close_rx.await.is_ok() {
|
|
|
|
debug!("unable to close discovery Rx channel completely");
|
|
|
|
}
|
2021-02-28 23:10:13 +00:00
|
|
|
})
|
|
|
|
.await;
|
|
|
|
|
|
|
|
if let Err(e) = result {
|
|
|
|
warn!("Discovery server failed: {}", e);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2021-12-26 20:18:42 +00:00
|
|
|
Ok(Ok(Self {
|
2021-02-28 23:10:13 +00:00
|
|
|
cred_rx,
|
|
|
|
_close_tx: close_tx,
|
2021-12-26 20:18:42 +00:00
|
|
|
}))
|
2021-02-28 23:10:13 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Stream for DiscoveryServer {
|
|
|
|
type Item = Credentials;
|
|
|
|
|
|
|
|
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Credentials>> {
|
|
|
|
self.cred_rx.poll_recv(cx)
|
|
|
|
}
|
|
|
|
}
|