Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Eliminate most uses of util module #668

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ jobs:
matrix:
os: [ubuntu-latest]
toolchain:
- 1.42.0 # MSRV (Minimum supported rust version)
- 1.45.0 # MSRV (Minimum supported rust version)
- stable
- beta
experimental: [false]
Expand Down
8 changes: 5 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion connect/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ edition = "2018"
aes-ctr = "0.6"
base64 = "0.13"
block-modes = "0.7"
form_urlencoded = "1.0"
futures-core = "0.3"
futures-util = { version = "0.3", default_features = false }
hmac = "0.10"
hyper = { version = "0.14", features = ["server", "http1", "tcp"] }
log = "0.4"
num-bigint = "0.3"
protobuf = "~2.14.0"
rand = "0.8"
serde = { version = "1.0", features = ["derive"] }
Expand Down
27 changes: 9 additions & 18 deletions connect/src/discovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use futures_core::Stream;
use hmac::{Hmac, Mac, NewMac};
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Method, Request, Response, StatusCode};
use num_bigint::BigUint;
use serde_json::json;
use sha1::{Digest, Sha1};
use tokio::sync::{mpsc, oneshot};
Expand All @@ -15,8 +14,7 @@ use dns_sd::DNSService;

use librespot_core::authentication::Credentials;
use librespot_core::config::ConnectConfig;
use librespot_core::diffie_hellman::{DH_GENERATOR, DH_PRIME};
use librespot_core::util;
use librespot_core::diffie_hellman::DHLocalKeys;

use std::borrow::Cow;
use std::collections::BTreeMap;
Expand All @@ -34,8 +32,7 @@ struct Discovery(Arc<DiscoveryInner>);
struct DiscoveryInner {
config: ConnectConfig,
device_id: String,
private_key: BigUint,
public_key: BigUint,
keys: DHLocalKeys,
tx: mpsc::UnboundedSender<Credentials>,
}

Expand All @@ -46,24 +43,18 @@ impl Discovery {
) -> (Discovery, mpsc::UnboundedReceiver<Credentials>) {
let (tx, rx) = mpsc::unbounded_channel();

let key_data = util::rand_vec(&mut rand::thread_rng(), 95);
let private_key = BigUint::from_bytes_be(&key_data);
let public_key = util::powm(&DH_GENERATOR, &private_key, &DH_PRIME);

let discovery = Discovery(Arc::new(DiscoveryInner {
config,
device_id,
private_key,
public_key,
keys: DHLocalKeys::random(&mut rand::thread_rng()),
tx,
}));

(discovery, rx)
}

fn handle_get_info(&self, _: BTreeMap<Cow<'_, str>, Cow<'_, str>>) -> Response<hyper::Body> {
let public_key = self.0.public_key.to_bytes_be();
let public_key = base64::encode(&public_key);
let public_key = base64::encode(&self.0.keys.public_key());

let result = json!({
"status": 101,
Expand Down Expand Up @@ -98,16 +89,16 @@ impl Discovery {

let encrypted_blob = base64::decode(encrypted_blob.as_bytes()).unwrap();

let client_key = base64::decode(client_key.as_bytes()).unwrap();
let client_key = BigUint::from_bytes_be(&client_key);

let shared_key = util::powm(&client_key, &self.0.private_key, &DH_PRIME);
let shared_key = self
.0
.keys
.shared_secret(&base64::decode(client_key.as_bytes()).unwrap());

let iv = &encrypted_blob[0..16];
let encrypted = &encrypted_blob[16..encrypted_blob.len() - 20];
let cksum = &encrypted_blob[encrypted_blob.len() - 20..encrypted_blob.len()];

let base_key = Sha1::digest(&shared_key.to_bytes_be());
let base_key = Sha1::digest(&shared_key);
let base_key = &base_key[..16];

let checksum_key = {
Expand Down
7 changes: 5 additions & 2 deletions connect/src/spirc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use crate::core::config::{ConnectConfig, VolumeCtrl};
use crate::core::mercury::{MercuryError, MercurySender};
use crate::core::session::Session;
use crate::core::spotify_id::{SpotifyAudioType, SpotifyId, SpotifyIdError};
use crate::core::util::url_encode;
use crate::core::util::SeqGenerator;
use crate::core::version;
use crate::playback::mixer::Mixer;
Expand Down Expand Up @@ -244,6 +243,10 @@ fn volume_to_mixer(volume: u16, volume_ctrl: &VolumeCtrl) -> u16 {
}
}

fn url_encode(bytes: impl AsRef<[u8]>) -> String {
form_urlencoded::byte_serialize(bytes.as_ref()).collect()
}

impl Spirc {
pub fn new(
config: ConnectConfig,
Expand All @@ -256,7 +259,7 @@ impl Spirc {
let ident = session.device_id().to_owned();

// Uri updated in response to issue #288
debug!("canonical_username: {}", url_encode(&session.username()));
debug!("canonical_username: {}", &session.username());
let uri = format!("hm://remote/user/{}/", url_encode(&session.username()));

let subscription = Box::pin(
Expand Down
3 changes: 2 additions & 1 deletion core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,14 @@ base64 = "0.13"
byteorder = "1.4"
bytes = "1.0"
cfg-if = "1"
form_urlencoded = "1.0"
futures-core = { version = "0.3", default-features = false }
futures-util = { version = "0.3", default-features = false, features = ["alloc", "bilock", "unstable", "sink"] }
hmac = "0.10"
httparse = "1.3"
hyper = { version = "0.14", optional = true, features = ["client", "tcp", "http1"] }
log = "0.4"
num-bigint = "0.3"
num-bigint = { version = "0.4", features = ["rand"] }
num-integer = "0.1"
num-traits = "0.2"
once_cell = "1.5.2"
Expand Down
8 changes: 5 additions & 3 deletions core/src/connection/handshake.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use byteorder::{BigEndian, ByteOrder, WriteBytesExt};
use hmac::{Hmac, Mac, NewMac};
use protobuf::{self, Message};
use rand::thread_rng;
use rand::{thread_rng, RngCore};
use sha1::Sha1;
use std::io;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
Expand All @@ -11,7 +11,6 @@ use super::codec::APCodec;
use crate::diffie_hellman::DHLocalKeys;
use crate::protocol;
use crate::protocol::keyexchange::{APResponseMessage, ClientHello, ClientResponsePlaintext};
use crate::util;

pub async fn handshake<T: AsyncRead + AsyncWrite + Unpin>(
mut connection: T,
Expand Down Expand Up @@ -40,6 +39,9 @@ async fn client_hello<T>(connection: &mut T, gc: Vec<u8>) -> io::Result<Vec<u8>>
where
T: AsyncWrite + Unpin,
{
let mut client_nonce = vec![0; 0x10];
thread_rng().fill_bytes(&mut client_nonce);

let mut packet = ClientHello::new();
packet
.mut_build_info()
Expand All @@ -59,7 +61,7 @@ where
.mut_login_crypto_hello()
.mut_diffie_hellman()
.set_server_keys_known(1);
packet.set_client_nonce(util::rand_vec(&mut thread_rng(), 0x10));
packet.set_client_nonce(client_nonce);
packet.set_padding(vec![0x1e]);

let mut buffer = vec![0, 4];
Expand Down
38 changes: 26 additions & 12 deletions core/src/diffie_hellman.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use num_bigint::BigUint;
use num_bigint::{BigUint, RandBigInt};
use num_integer::Integer;
use num_traits::{One, Zero};
use once_cell::sync::Lazy;
use rand::Rng;
use rand::{CryptoRng, Rng};

use crate::util;

pub static DH_GENERATOR: Lazy<BigUint> = Lazy::new(|| BigUint::from_bytes_be(&[0x02]));
pub static DH_PRIME: Lazy<BigUint> = Lazy::new(|| {
static DH_GENERATOR: Lazy<BigUint> = Lazy::new(|| BigUint::from_bytes_be(&[0x02]));
static DH_PRIME: Lazy<BigUint> = Lazy::new(|| {
BigUint::from_bytes_be(&[
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, 0xda, 0xa2, 0x21, 0x68, 0xc2,
0x34, 0xc4, 0xc6, 0x62, 0x8b, 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67,
Expand All @@ -17,17 +17,31 @@ pub static DH_PRIME: Lazy<BigUint> = Lazy::new(|| {
])
});

fn powm(base: &BigUint, exp: &BigUint, modulus: &BigUint) -> BigUint {
let mut base = base.clone();
let mut exp = exp.clone();
let mut result: BigUint = One::one();

while !exp.is_zero() {
if exp.is_odd() {
result = (result * &base) % modulus;
}
exp >>= 1;
base = (&base * &base) % modulus;
}

result
}

pub struct DHLocalKeys {
private_key: BigUint,
public_key: BigUint,
}

impl DHLocalKeys {
pub fn random<R: Rng>(rng: &mut R) -> DHLocalKeys {
let key_data = util::rand_vec(rng, 95);

let private_key = BigUint::from_bytes_be(&key_data);
let public_key = util::powm(&DH_GENERATOR, &private_key, &DH_PRIME);
pub fn random<R: Rng + CryptoRng>(rng: &mut R) -> DHLocalKeys {
let private_key = rng.gen_biguint(95 * 8);
let public_key = powm(&DH_GENERATOR, &private_key, &DH_PRIME);

DHLocalKeys {
private_key,
Expand All @@ -40,7 +54,7 @@ impl DHLocalKeys {
}

pub fn shared_secret(&self, remote_key: &[u8]) -> Vec<u8> {
let shared_key = util::powm(
let shared_key = powm(
&BigUint::from_bytes_be(remote_key),
&self.private_key,
&DH_PRIME,
Expand Down
2 changes: 2 additions & 0 deletions core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,13 @@ pub mod cache;
pub mod channel;
pub mod config;
mod connection;
#[doc(hidden)]
pub mod diffie_hellman;
pub mod keymaster;
pub mod mercury;
mod proxytunnel;
pub mod session;
pub mod spotify_id;
#[doc(hidden)]
pub mod util;
pub mod version;
3 changes: 1 addition & 2 deletions core/src/mercury/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ use bytes::Bytes;
use tokio::sync::{mpsc, oneshot};

use crate::protocol;
use crate::util::url_encode;
use crate::util::SeqGenerator;

mod types;
Expand Down Expand Up @@ -199,7 +198,7 @@ impl MercuryManager {
let header: protocol::mercury::Header = protobuf::parse_from_bytes(&header_data).unwrap();

let response = MercuryResponse {
uri: url_encode(header.get_uri()),
uri: form_urlencoded::byte_serialize(header.get_uri().as_bytes()).collect(),
status_code: header.get_status_code(),
payload: pending.parts,
};
Expand Down
46 changes: 0 additions & 46 deletions core/src/util.rs
Original file line number Diff line number Diff line change
@@ -1,50 +1,4 @@
use num_bigint::BigUint;
use num_integer::Integer;
use num_traits::{One, Zero};
use rand::Rng;
use std::mem;
use std::ops::{Mul, Rem, Shr};

pub fn rand_vec<G: Rng>(rng: &mut G, size: usize) -> Vec<u8> {
::std::iter::repeat(())
.map(|()| rng.gen())
.take(size)
.collect()
}

pub fn url_encode(inp: &str) -> String {
let mut encoded = String::new();

for c in inp.as_bytes().iter() {
match *c as char {
'A'..='Z' | 'a'..='z' | '0'..='9' | '-' | '_' | '.' | '~' | ':' | '/' => {
encoded.push(*c as char)
}
c => encoded.push_str(format!("%{:02X}", c as u32).as_str()),
};
}

encoded
}

pub fn powm(base: &BigUint, exp: &BigUint, modulus: &BigUint) -> BigUint {
let mut base = base.clone();
let mut exp = exp.clone();
let mut result: BigUint = One::one();

while !exp.is_zero() {
if exp.is_odd() {
result = result.mul(&base).rem(modulus);
}
exp = exp.shr(1);
base = (&base).mul(&base).rem(modulus);
}

result
}

pub trait ReadSeek: ::std::io::Read + ::std::io::Seek {}
impl<T: ::std::io::Read + ::std::io::Seek> ReadSeek for T {}

pub trait Seq {
fn next(&self) -> Self;
Expand Down