Skip to main content

handshake_proxy/
handshake_proxy.rs

1//! A "simple" server that gets login information and proxies connections.
2//! After login all connections are encrypted and Azalea cannot read them.
3
4use std::{error::Error, sync::LazyLock};
5
6use azalea_protocol::{
7    connect::Connection,
8    packets::{
9        ClientIntention, PROTOCOL_VERSION, VERSION_NAME,
10        handshake::{
11            ClientboundHandshakePacket, ServerboundHandshakePacket,
12            s_intention::ServerboundIntention,
13        },
14        login::{ServerboundLoginPacket, s_hello::ServerboundHello},
15        status::{
16            ServerboundStatusPacket,
17            c_pong_response::ClientboundPongResponse,
18            c_status_response::{ClientboundStatusResponse, Players, Version},
19        },
20    },
21    read::ReadPacketError,
22};
23use futures::FutureExt;
24use tokio::{
25    io::{self, AsyncWriteExt},
26    net::{TcpListener, TcpStream},
27};
28use tracing::{Level, error, info, warn};
29
30const LISTEN_ADDR: &str = "127.0.0.1:25566";
31const PROXY_ADDR: &str = "127.0.0.1:25565";
32
33const PROXY_DESC: &str = "An Azalea Minecraft Proxy";
34
35// String must be formatted like "data:image/png;base64,<data>"
36static PROXY_FAVICON: LazyLock<Option<String>> = LazyLock::new(|| None);
37
38static PROXY_VERSION: LazyLock<Option<Version>> = LazyLock::new(|| {
39    Some(Version {
40        name: VERSION_NAME.to_string(),
41        protocol: PROTOCOL_VERSION,
42    })
43});
44
45const PROXY_PLAYERS: Option<Players> = Some(Players {
46    max: 1,
47    online: 0,
48    sample: Vec::new(),
49});
50
51const PROXY_SECURE_CHAT: Option<bool> = Some(false);
52
53#[tokio::main]
54async fn main() -> eyre::Result<()> {
55    tracing_subscriber::fmt().with_max_level(Level::INFO).init();
56
57    // Bind to an address and port
58    let listener = TcpListener::bind(LISTEN_ADDR).await?;
59
60    info!("Listening on {LISTEN_ADDR}, proxying to {PROXY_ADDR}");
61
62    loop {
63        // When a connection is made, pass it off to another thread
64        let (stream, _) = listener.accept().await?;
65        tokio::spawn(handle_connection(stream));
66    }
67}
68
69async fn handle_connection(stream: TcpStream) -> eyre::Result<()> {
70    stream.set_nodelay(true)?;
71    let ip = stream.peer_addr()?;
72    let mut conn: Connection<ServerboundHandshakePacket, ClientboundHandshakePacket> =
73        Connection::wrap(stream);
74
75    // The first packet sent from a client is the intent packet.
76    // This specifies whether the client is pinging
77    // the server or is going to join the game.
78    let intent = match conn.read(Default::default()).await {
79        Ok(packet) => match packet {
80            ServerboundHandshakePacket::Intention(packet) => {
81                info!(
82                    "New connection from {}, hostname {:?}:{}, version {}, {:?}",
83                    ip.ip(),
84                    packet.hostname,
85                    packet.port,
86                    packet.protocol_version,
87                    packet.intention
88                );
89                packet
90            }
91        },
92        Err(e) => {
93            let e = e.into();
94            warn!("Error during intent: {e}");
95            return Err(e);
96        }
97    };
98
99    match intent.intention {
100        // If the client is pinging the proxy,
101        // reply with the information below.
102        ClientIntention::Status => {
103            let mut conn = conn.status();
104            loop {
105                match conn.read(Default::default()).await {
106                    Ok(p) => match p {
107                        ServerboundStatusPacket::StatusRequest(_) => {
108                            conn.write(
109                                Default::default(),
110                                ClientboundStatusResponse {
111                                    description: PROXY_DESC.into(),
112                                    favicon: PROXY_FAVICON.clone(),
113                                    players: PROXY_PLAYERS.clone(),
114                                    version: PROXY_VERSION.clone(),
115                                    enforces_secure_chat: PROXY_SECURE_CHAT,
116                                    contact: None,
117                                },
118                            )
119                            .await?;
120                        }
121                        ServerboundStatusPacket::PingRequest(p) => {
122                            conn.write(
123                                Default::default(),
124                                ClientboundPongResponse { time: p.time },
125                            )
126                            .await?;
127                            break;
128                        }
129                    },
130                    Err(e) => match *e {
131                        ReadPacketError::ConnectionClosed => {
132                            break;
133                        }
134                        e => {
135                            warn!("Error during status: {e}");
136                            return Err(e.into());
137                        }
138                    },
139                }
140            }
141        }
142        // If the client intends to join the proxy,
143        // wait for them to send the `Hello` packet to
144        // log their username and uuid, then forward the
145        // connection along to the proxy target.
146        ClientIntention::Login => {
147            let mut conn = conn.login();
148            loop {
149                match conn.read(Default::default()).await {
150                    Ok(p) => {
151                        if let ServerboundLoginPacket::Hello(hello) = p {
152                            info!(
153                                "Player \'{0}\' from {1} logging in with uuid: {2}",
154                                hello.name,
155                                ip.ip(),
156                                hello.profile_id.to_string()
157                            );
158
159                            tokio::spawn(transfer(conn.unwrap()?, intent, hello).map(|r| {
160                                if let Err(e) = r {
161                                    error!("Failed to proxy: {e}");
162                                }
163                            }));
164
165                            break;
166                        }
167                    }
168                    Err(e) => match *e {
169                        ReadPacketError::ConnectionClosed => {
170                            break;
171                        }
172                        e => {
173                            warn!("Error during login: {e}");
174                            return Err(e.into());
175                        }
176                    },
177                }
178            }
179        }
180        ClientIntention::Transfer => {
181            warn!("Client attempted to join via transfer")
182        }
183    }
184
185    Ok(())
186}
187
188async fn transfer(
189    mut inbound: TcpStream,
190    intent: ServerboundIntention,
191    hello: ServerboundHello,
192) -> Result<(), Box<dyn Error>> {
193    let outbound = TcpStream::connect(PROXY_ADDR).await?;
194    let name = hello.name.clone();
195    outbound.set_nodelay(true)?;
196
197    // Repeat the intent and hello packet
198    // received earlier to the proxy target
199    let mut outbound_conn: Connection<ClientboundHandshakePacket, ServerboundHandshakePacket> =
200        Connection::wrap(outbound);
201    outbound_conn.write(Default::default(), intent).await?;
202
203    let mut outbound_conn = outbound_conn.login();
204    outbound_conn.write(Default::default(), hello).await?;
205
206    let mut outbound = outbound_conn.unwrap()?;
207
208    // Split the incoming and outgoing connections in
209    // halves and handle each pair on separate threads.
210    let (mut ri, mut wi) = inbound.split();
211    let (mut ro, mut wo) = outbound.split();
212
213    let client_to_server = async {
214        io::copy(&mut ri, &mut wo).await?;
215        wo.shutdown().await
216    };
217
218    let server_to_client = async {
219        io::copy(&mut ro, &mut wi).await?;
220        wi.shutdown().await
221    };
222
223    tokio::try_join!(client_to_server, server_to_client)?;
224    info!("Player \'{name}\' left the game");
225
226    Ok(())
227}