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

[ARC-144] Replace Network Client with Generator Enumerator #176

Merged
merged 1 commit into from
Sep 26, 2023
Merged
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
12 changes: 12 additions & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ rustls = { version = "0.21", features = ["dangerous_configuration"], optional =
zeroize = { version = "1.6", features = ["zeroize_derive"] }
tokio = { version = "1.32", features = ["time", "rt"], optional = true }
pcsc = { version = "2.8", optional = true }
async-recursion = "1.0.5"
irvingoujAtDevolution marked this conversation as resolved.
Show resolved Hide resolved

[target.'cfg(windows)'.dependencies]
winreg = "0.51"
Expand Down
8 changes: 6 additions & 2 deletions examples/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,9 @@ fn do_authentication(ntlm: &mut Ntlm, identity: &AuthIdentity, mut stream: &mut
.with_target_name(username.as_str())
.with_output(&mut output_buffer);

let _result = ntlm.initialize_security_context_impl(&mut builder)?;
let _result = ntlm
.initialize_security_context_impl(&mut builder)
.resolve_to_result()?;

write_message(&mut stream, &output_buffer[0].buffer)?;

Expand All @@ -104,7 +106,9 @@ fn do_authentication(ntlm: &mut Ntlm, identity: &AuthIdentity, mut stream: &mut
.with_input(&mut input_buffer)
.with_output(&mut output_buffer);

let result = ntlm.initialize_security_context_impl(&mut builder)?;
let result = ntlm
.initialize_security_context_impl(&mut builder)
.resolve_to_result()?;

if [SecurityStatus::CompleteAndContinue, SecurityStatus::CompleteNeeded].contains(&result.status) {
println!("Completing the token...");
Expand Down
2 changes: 0 additions & 2 deletions ffi/src/macros.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
macro_rules! try_execute {
($x:expr) => {{
use num_traits::ToPrimitive;

match $x {
Ok(value) => value,
Err(err) => {
Expand Down
35 changes: 15 additions & 20 deletions ffi/src/sec_handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ use sspi::credssp::sspi_cred_ssp;
use sspi::credssp::sspi_cred_ssp::SspiCredSsp;
use sspi::credssp::SspiContext;
use sspi::kerberos::config::KerberosConfig;
use sspi::network_client::reqwest_network_client::{RequestClientFactory, ReqwestNetworkClient};
use sspi::ntlm::NtlmConfig;
use sspi::{
kerberos, negotiate, ntlm, pku2u, ClientRequestFlags, CredentialsBuffers, DataRepresentation, Error, ErrorKind,
Expand Down Expand Up @@ -91,21 +90,16 @@ fn create_negotiate_context(attributes: &CredentialsAttributes) -> Result<Negoti
let hostname = attributes.workstation.clone().unwrap_or_else(whoami::hostname);

if let Some(kdc_url) = attributes.kdc_url() {
let kerberos_config = KerberosConfig::new(&kdc_url, Box::<ReqwestNetworkClient>::default(), hostname.clone());
let negotiate_config = NegotiateConfig::new(
Box::new(kerberos_config),
attributes.package_list.clone(),
hostname,
Box::new(RequestClientFactory),
);
let kerberos_config = KerberosConfig::new(&kdc_url, hostname.clone());
let negotiate_config =
NegotiateConfig::new(Box::new(kerberos_config), attributes.package_list.clone(), hostname);

Negotiate::new(negotiate_config)
} else {
let negotiate_config = NegotiateConfig {
protocol_config: Box::new(NtlmConfig::new(hostname.clone())),
package_list: attributes.package_list.clone(),
hostname,
network_client_factory: Box::new(RequestClientFactory),
};
Negotiate::new(negotiate_config)
}
Expand Down Expand Up @@ -153,13 +147,13 @@ pub(crate) unsafe fn p_ctxt_handle_to_sspi_context(

if let Some(kdc_url) = attributes.kdc_url() {
SspiContext::Kerberos(Kerberos::new_client_from_config(KerberosConfig::new(
&kdc_url,
Box::<ReqwestNetworkClient>::default(),
hostname,
&kdc_url, hostname,
))?)
} else {
let mut krb_config = KerberosConfig::from_env();
krb_config.hostname = Some(hostname);
let krb_config = KerberosConfig {
hostname: Some(hostname),
url: None,
};
SspiContext::Kerberos(Kerberos::new_client_from_config(krb_config)?)
}
}
Expand Down Expand Up @@ -380,7 +374,7 @@ pub unsafe extern "system" fn InitializeSecurityContextA(
.with_target_name(service_principal)
.with_input(&mut input_tokens)
.with_output(&mut output_tokens);
let result_status = sspi_context.initialize_security_context_impl(&mut builder);
let result_status = sspi_context.initialize_security_context_impl(&mut builder).resolve_with_default_network_client();

let context_requirements = ClientRequestFlags::from_bits_retain(f_context_req);
let allocate = context_requirements.contains(ClientRequestFlags::ALLOCATE_MEMORY);
Expand Down Expand Up @@ -479,7 +473,7 @@ pub unsafe extern "system" fn InitializeSecurityContextW(
.with_target_name(&service_principal)
.with_input(&mut input_tokens)
.with_output(&mut output_tokens);
let result_status = sspi_context.initialize_security_context_impl(&mut builder);
let result_status = sspi_context.initialize_security_context_impl(&mut builder).resolve_with_default_network_client();

let context_requirements = ClientRequestFlags::from_bits_retain(f_context_req);
let allocate = context_requirements.contains(ClientRequestFlags::ALLOCATE_MEMORY);
Expand Down Expand Up @@ -939,13 +933,14 @@ pub unsafe extern "system" fn ChangeAccountPasswordA(
protocol_config: Box::new(NtlmConfig::new(whoami::hostname())),
package_list: None,
hostname: whoami::hostname(),
network_client_factory: Box::new(RequestClientFactory),
};
SspiContext::Negotiate(try_execute!(Negotiate::new(negotiate_config)))
},
kerberos::PKG_NAME => {
let mut krb_config = KerberosConfig::from_env();
krb_config.hostname = Some(whoami::hostname());
let krb_config = KerberosConfig{
hostname:Some(whoami::hostname()),
url:None
};
SspiContext::Kerberos(try_execute!(Kerberos::new_client_from_config(
krb_config
)))
Expand All @@ -956,7 +951,7 @@ pub unsafe extern "system" fn ChangeAccountPasswordA(
}
};

let result_status = sspi_context.change_password(change_password);
let result_status = sspi_context.change_password(change_password).resolve_with_default_network_client();

copy_to_c_sec_buffer((*p_output).p_buffers, &output_tokens, false);

Expand Down
133 changes: 86 additions & 47 deletions src/credssp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ use ts_request::{NONCE_SIZE, TS_REQUEST_VERSION};
use self::sspi_cred_ssp::SspiCredSsp;
use crate::builders::{ChangePassword, EmptyInitializeSecurityContext};
use crate::crypto::compute_sha256;
use crate::generator::{
Generator, GeneratorChangePassword, GeneratorInitSecurityContext, NetworkRequest, YieldPointLocal,
};
use crate::kerberos::config::KerberosConfig;
use crate::kerberos::{self, Kerberos};
use crate::ntlm::{self, Ntlm, NtlmConfig, SIGNATURE_SIZE};
Expand Down Expand Up @@ -228,7 +231,20 @@ impl CredSspClient {
}

#[instrument(fields(state = ?self.state), skip_all)]
pub fn process(&mut self, mut ts_request: TsRequest) -> crate::Result<ClientState> {
pub fn process<'a>(
&'a mut self,
ts_request: TsRequest,
) -> Generator<'a, NetworkRequest, crate::Result<Vec<u8>>, crate::Result<ClientState>> {
Generator::<'a, NetworkRequest, crate::Result<Vec<u8>>, crate::Result<ClientState>>::new(
move |mut yield_point| async move { self.process_impl(&mut yield_point, ts_request).await },
)
}

async fn process_impl(
&mut self,
yield_point: &mut YieldPointLocal,
mut ts_request: TsRequest,
) -> crate::Result<ClientState> {
ts_request.check_error()?;
if let Some(ref mut context) = self.context {
context.check_peer_version(ts_request.version)?;
Expand Down Expand Up @@ -282,7 +298,8 @@ impl CredSspClient {
.with_output(&mut output_token);
let result = cred_ssp_context
.sspi_context
.initialize_security_context_impl(&mut builder)?;
.initialize_security_context_impl(yield_point, &mut builder)
.await?;
self.credentials_handle = credentials_handle;
ts_request.nego_tokens = Some(output_token.remove(0).buffer);

Expand Down Expand Up @@ -643,41 +660,6 @@ impl SspiImpl for SspiContext {
})
}

#[instrument(ret, fields(security_package = self.package_name()), skip_all)]
fn initialize_security_context_impl<'a>(
&mut self,
builder: &mut FilledInitializeSecurityContext<'a, Self::CredentialsHandle>,
) -> crate::Result<InitializeSecurityContextResult> {
match self {
SspiContext::Ntlm(ntlm) => {
let mut auth_identity = if let Some(Some(CredentialsBuffers::AuthIdentity(ref identity))) =
builder.credentials_handle_mut()
{
Some(identity.clone())
} else {
None
};
let mut new_builder = builder.full_transform(Some(&mut auth_identity));
ntlm.initialize_security_context_impl(&mut new_builder)
}
SspiContext::Kerberos(kerberos) => kerberos.initialize_security_context_impl(builder),
SspiContext::Negotiate(negotiate) => negotiate.initialize_security_context_impl(builder),
SspiContext::Pku2u(pku2u) => {
let mut auth_identity = if let Some(Some(CredentialsBuffers::AuthIdentity(ref identity))) =
builder.credentials_handle_mut()
{
Some(identity.clone())
} else {
None
};
let mut new_builder = builder.full_transform(Some(&mut auth_identity));
pku2u.initialize_security_context_impl(&mut new_builder)
}
#[cfg(feature = "tsssp")]
SspiContext::CredSsp(credssp) => credssp.initialize_security_context_impl(builder),
}
}

#[instrument(ret, fields(security_package = self.package_name()), skip_all)]
fn accept_security_context_impl<'a>(
&'a mut self,
Expand Down Expand Up @@ -714,6 +696,69 @@ impl SspiImpl for SspiContext {
SspiContext::CredSsp(credssp) => builder.transform(credssp).execute(),
}
}

fn initialize_security_context_impl<'a>(
&'a mut self,
builder: &'a mut FilledInitializeSecurityContext<'a, Self::CredentialsHandle>,
) -> GeneratorInitSecurityContext {
Generator::new(move |mut yield_point| async move {
self.initialize_security_context_impl(&mut yield_point, builder).await
})
}
}

impl<'a> SspiContext {
#[instrument(ret, fields(security_package = self.package_name()), skip_all)]
async fn change_password_impl(
&'a mut self,
yield_point: &mut YieldPointLocal,
change_password: ChangePassword<'a>,
) -> crate::Result<()> {
match self {
SspiContext::Kerberos(kerberos) => kerberos.change_password(yield_point, change_password).await,
SspiContext::Negotiate(negotiate) => negotiate.change_password(yield_point, change_password).await,
_ => Err(crate::Error::new(
ErrorKind::UnsupportedFunction,
"Change password not supported for this protocol",
)),
}
}

#[instrument(ret, fields(security_package = self.package_name()), skip_all)]
async fn initialize_security_context_impl(
irvingoujAtDevolution marked this conversation as resolved.
Show resolved Hide resolved
&'a mut self,
yield_point: &mut YieldPointLocal,
builder: &'a mut FilledInitializeSecurityContext<'_, <Self as SspiImpl>::CredentialsHandle>,
) -> crate::Result<InitializeSecurityContextResult> {
match self {
SspiContext::Ntlm(ntlm) => {
let mut auth_identity = if let Some(Some(CredentialsBuffers::AuthIdentity(ref identity))) =
builder.credentials_handle_mut()
{
Some(identity.clone())
} else {
None
};
let mut new_builder = builder.full_transform(Some(&mut auth_identity));
ntlm.initialize_security_context_impl(&mut new_builder)
}
SspiContext::Kerberos(kerberos) => kerberos.initialize_security_context_impl(yield_point, builder).await,
SspiContext::Negotiate(negotiate) => negotiate.initialize_security_context_impl(yield_point, builder).await,
SspiContext::Pku2u(pku2u) => {
let mut auth_identity = if let Some(Some(CredentialsBuffers::AuthIdentity(ref identity))) =
builder.credentials_handle_mut()
{
Some(identity.clone())
} else {
None
};
let mut new_builder = builder.full_transform(Some(&mut auth_identity));
pku2u.initialize_security_context_impl(&mut new_builder)
}
#[cfg(feature = "tsssp")]
SspiContext::CredSsp(credssp) => credssp.initialize_security_context_impl(yield_point, builder).await,
}
}
}

impl Sspi for SspiContext {
Expand Down Expand Up @@ -858,16 +903,10 @@ impl Sspi for SspiContext {
}
}

#[instrument(ret, fields(security_package = self.package_name()), skip_all)]
irvingoujAtDevolution marked this conversation as resolved.
Show resolved Hide resolved
fn change_password(&mut self, change_password: ChangePassword) -> crate::Result<()> {
match self {
SspiContext::Ntlm(ntlm) => ntlm.change_password(change_password),
SspiContext::Kerberos(kerberos) => kerberos.change_password(change_password),
SspiContext::Negotiate(negotiate) => negotiate.change_password(change_password),
SspiContext::Pku2u(pku2u) => pku2u.change_password(change_password),
#[cfg(feature = "tsssp")]
SspiContext::CredSsp(credssp) => credssp.change_password(change_password),
}
fn change_password<'a>(&'a mut self, change_password: ChangePassword<'a>) -> GeneratorChangePassword {
GeneratorChangePassword::new(move |mut yield_point| async move {
self.change_password_impl(&mut yield_point, change_password).await
})
}
}

Expand Down
Loading