-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathkerberos.rs
171 lines (157 loc) · 6.43 KB
/
kerberos.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
use std::error::Error;
use base64::Engine;
use reqwest::header::{
ACCEPT, ACCEPT_ENCODING, ACCEPT_LANGUAGE, AUTHORIZATION, CONNECTION, CONTENT_LENGTH, HOST, USER_AGENT,
WWW_AUTHENTICATE,
};
use reqwest::StatusCode;
use sspi::{
AcquireCredentialsHandleResult, BufferType, ClientRequestFlags, CredentialsBuffers, DataRepresentation,
InitializeSecurityContextResult, Kerberos, KerberosConfig, SecurityBuffer, SecurityStatus, Sspi, SspiImpl,
Username,
};
use tracing_subscriber::prelude::*;
use tracing_subscriber::{fmt, EnvFilter};
fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let kdc_url = std::env::var("SSPI_KDC_URL").expect("missing KDC URL set in SSPI_KDC_URL"); //tcp://ad-compter-name.domain:88
let hostname = std::env::var("SSPI_WINRM_HOST").expect("missing host name set in SSPI_WINRM_HOST"); // winrm_server_name.domain
let username = std::env::var("SSPI_WINRM_USER").expect("missing username set in SSPI_WINRM_USER"); // username@domain
let password = std::env::var("SSPI_WINRM_PASS").expect("missing password set in SSPI_WINRM_PASS");
let auth_method = std::env::var("SSPI_WINRM_AUTH").expect("missing auth METHOD set in SSPI_WINRM_AUTH"); // Negotiate or Kerberos
tracing_subscriber::registry()
.with(fmt::layer())
.with(EnvFilter::from_env("SSPI_LOG_LEVEL"))
.init();
let kerberos_config = KerberosConfig::new(&kdc_url, hostname.clone());
let mut kerberos = Kerberos::new_client_from_config(kerberos_config).unwrap();
let mut acq_creds_handle_result = get_cred_handle(&mut kerberos, username, password);
let mut input_token = String::new();
let mut client = reqwest::blocking::Client::new(); // super IMPORTANT, KEEP-ALIVE the http connection!
loop {
let (output_token, status) = step(
&mut kerberos,
&mut acq_creds_handle_result.credentials_handle,
&input_token,
&hostname,
);
if status == SecurityStatus::ContinueNeeded || status == SecurityStatus::Ok {
let (token_from_server, status_code) =
process_authentication(&output_token, &mut client, &auth_method, &hostname)?;
if status_code == reqwest::StatusCode::OK {
println!("authenticated");
break Ok(());
}
input_token = token_from_server;
} else {
panic!("Having problem continue authentication");
}
}
}
pub(crate) fn get_cred_handle(
kerberos: &mut Kerberos,
username: String,
password: String,
) -> AcquireCredentialsHandleResult<Option<CredentialsBuffers>> {
let identity = sspi::AuthIdentity {
username: Username::parse(&username).expect("username is not in the correct format"),
password: password.into(),
};
let acq_creds_handle_result = kerberos
.acquire_credentials_handle()
.with_credential_use(sspi::CredentialUse::Outbound)
.with_auth_data(&identity.into())
.execute(kerberos)
.expect("AcquireCredentialsHandle resulted in error");
acq_creds_handle_result
}
pub(crate) fn process_authentication(
token_neeeds_to_be_sent: &String,
client: &mut reqwest::blocking::Client,
auth_method: &str,
hostname: &str,
) -> Result<(String, StatusCode), Box<dyn std::error::Error + Send + Sync>> {
let server_result = send_http(token_neeeds_to_be_sent, client, hostname, auth_method)?;
if server_result.status() == StatusCode::OK {
return Ok((String::new(), StatusCode::OK));
}
let www_authenticate = server_result
.headers()
.get(WWW_AUTHENTICATE)
.ok_or("expecting www-authentication header from server but not found")?;
let server_token = www_authenticate
.to_str()
.unwrap()
.replace(format!("{} ", auth_method).as_str(), "");
Ok((server_token, server_result.status()))
}
pub(crate) fn send_http(
negotiate_token: &String,
client: &mut reqwest::blocking::Client,
hostname: &str,
auth_method: &str,
) -> Result<reqwest::blocking::Response, Box<dyn Error + Send + Sync>> {
let resp = client
.post(format!("http://{}:5985/wsman?PSVersion=7.3.8", hostname))
.header(AUTHORIZATION, format!("{} {}", auth_method, negotiate_token))
.header(HOST, format!("{}:5985", hostname))
.header(CONNECTION, "keep-alive")
.header(CONTENT_LENGTH, "0")
.header(
USER_AGENT,
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/118.0",
)
.header(ACCEPT, "*/*")
.header(ACCEPT_ENCODING, "gzip, deflate")
.header(ACCEPT_LANGUAGE, "en-US,en;q=0.9")
.send()?;
Ok(resp)
}
fn step_helper(
kerberos: &mut Kerberos,
cred_handle: &mut <Kerberos as SspiImpl>::CredentialsHandle,
input_buffer: &mut [SecurityBuffer],
output_buffer: &mut [SecurityBuffer],
hostname: &str,
) -> Result<InitializeSecurityContextResult, Box<dyn std::error::Error>> {
let target_name = format!("HTTP/{}", hostname);
let mut builder = kerberos
.initialize_security_context()
.with_credentials_handle(cred_handle)
.with_context_requirements(ClientRequestFlags::MUTUAL_AUTH)
.with_target_data_representation(DataRepresentation::Native)
.with_target_name(&target_name)
.with_input(input_buffer)
.with_output(output_buffer);
let result = kerberos
.initialize_security_context_impl(&mut builder)?
.resolve_with_default_network_client()?;
Ok(result)
}
pub fn step(
kerberos: &mut Kerberos,
cred_handle: &mut <Kerberos as SspiImpl>::CredentialsHandle,
input_token: &String,
hostname: &str,
) -> (String, SecurityStatus) {
let input_buffer = base64::engine::general_purpose::STANDARD.decode(input_token).unwrap();
let mut secure_input_buffer = vec![SecurityBuffer::new(input_buffer, BufferType::Token)];
let mut secure_output_buffer = vec![SecurityBuffer::new(Vec::new(), BufferType::Token)];
match step_helper(
kerberos,
cred_handle,
&mut secure_input_buffer,
&mut secure_output_buffer,
hostname,
) {
Ok(result) => {
let output_buffer = secure_output_buffer[0].to_owned();
(
base64::engine::general_purpose::STANDARD.encode(output_buffer.buffer),
result.status,
)
}
Err(_) => {
panic!("error stepping");
}
}
}