FreeRDP/server/proxy/pf_client.c

416 lines
12 KiB
C
Raw Normal View History

First version of an RDP proxy (#5372) * server: Add proxy dir with barebones server * sever/proxy: Remove licensing * server/proxy: Add client files * server/proxy: rm binary * server/proxy: Formatting * server/proxy: Fixed includes and added basic client creation functionality * server/proxy: Remove licensing and fix ifndef * proxy/server: Fix cmake indentation * server/proxy: Fix licensing * server/proxy: Forward connection on peer_post_connect * server/proxy: Fix function signature * server/proxy: Changed function signature of proxy_client_start * server/proxy: Now peer_post_connect calls proxy_client_start in a new thread * pfreerdp.c: Clean up useless comments and logs * server/proxy: Fix license * server/proxy: Remove all non-connection related data from proxy_context * server/proxy: Move Log Tag definition to pf_log.h * server/proxy: Move context definition to pf_context * server/proxy: Delete pfreerdp.h * pfreerdp.c: Move context callbacks to pf_context.c * server/proxy: Update CMakeLists.txt * pf_channels: Use new proxy context API * pf_client: Move context to pf_context * pf_client.c: Remove unnessecary event handling * server/proxy: Formatting * proxy/server: Move server logic to pf_server.c * server/proxy: Handle client disconnection * Merge stash * pf_server.c: Open GFX Connection to client * server: CMakeLists: build proxy along with other servers * server: proxy: get target server from rdpNego->RoutingToken Iv'e omitted a check from which im not sure is right. Should check in docs * server/proxy: Handle remote server -> client disconnection * server/proxy: Move common function to pf_common.c * server/proxy: Move common function to pf_common.c * rdpgfx.h: Add reference to freerdp.h for rdpContext * pf_channels: Pipe GFX on channel connection * server/proxy: Add pf_rdpgfx for proxy gfx callbacks * pf_client: Declare dynvc and gfx capabilities on connection * server/proxy: Add graphics callbacks * server/proxy: Add graphics callbacks * pf_server: Listen to channel events * Pass user settings to server * pf_server: Proxy mouse events * fixup! server/proxy: Add graphics callbacks * pf_client: Fix setting initialization * Merge feat/proxy-gfx to feat/proxy * pf_server: Fix double freed credentials * server/proxy: Remove unnecessary call to freerdp_client_settings_parse_command_line * server/proxy: Refactor re-activation code * server/proxy: Run format scripts * server/proxy: Fix segfault when post_disconnect return FALSE * server/proxy: Refactor proxy_settings_mirror * server/proxy: Redirect credentials * server/proxy: move proxy_settings_mirror to pf_common.c * server/proxy: Redirect desktop_resize event * pf_client: Remove interactive CLI auth methods * fixup! server/proxy: Redirect credentials * server/proxy: Rename proxy_mirror_settings to pf_common_copy_settings * pf_server.c: Fixed non-freed context When the disconnection is forced by the target server, the function `pf_server_handle_client_disconnection` isn't called. Therefore, the context of the connection between the proxy to tagrget isn't freed. * fixup! pf_server.c: Fixed non-freed context * pf_client: Prefix all client methods with pf_client * pf_context: Add init client to proxy context method * pf_server: Confirm all GFX caps regardless of settings * pf_server: Prefix all methods with pf_server * pf_server: Move variable decleration to start of method * pf_server: Fix client setting * pf_server: Fix GFX init method * pf_server: Move variable decleration to start of methods * server/proxy: Formatting * Merge feat/proxy * pf_server: Proxy synchronize event * pf_server: Proxy refresh rect update events * pf_server: Proxy suppress output messages * server/proxy: Fix licensing * server/proxy: Move client input callbacks to pf_input * server/proxy: Move client update callbacks to pf_update * server/proxy: Fix non-terminated target host string * Feat/proxy config (#2) * server/proxy: Add config loading support * server/proxy: Add config file * server/proxy: Format code * server/proxy: Code refactor, rename update_register_callbacks and input_register_callbacks * server/proxy: Update config file * server/proxy: Remove config.ini from root directory * Remove comment from config file * server/proxy: Fix leak in pf_server_load_config * server/proxy: Add rdpServerProxy struct and embed it in proxyContext * server/proxy: Load configuration and pass it inside every proxyContext instance * server/proxy: Move rdpProxyServer to proxy.h * server/proxy: Use configuration while proxying input events * server/proxy: Update CMakeLists * server/proxy: Refactor pf_input.c * server/proxy: Add AllowedChannels, DeniedChannels in configuration * server/proxy: Remove unnecessary variable from parse_channels_from_str * server/proxy: Update config file * server/proxy: config: Rename to * server/proxy: config: Add mode - blacklist/whitelist * server/proxy: Refactor, fix NULL deref * server/proxy: Add license to proxy.h * server/proxy: Fix newline in pf_config.c * server/proxy: config: Rename Mode to WhitelistMode * Add target in config. Add checks for configuration validity (#3) * Add target in config. Add checks for configuration validity * Update config file * libfreerdp: nego: revert commented out check of routingToken length * pf_server: Fix target host info from RoutingToken * pf_server: Remove hardcoded lenght of routing token prefix * Feat/refactor context (#8) * Refactor main structs * Update CMakeLists.txt * pf_server.c: Free pdata at the end of the connection * Run format scripts * Rename tf to pc * Fix licenses * pf_server: Refactor names of structs and functions * proxy: gfx: sync caps (#4) * proxy: gfx: sync caps * proxy: gfx: sync caps, hook gfx client's OnClose() call and close server resources * fixup! Feat/refactor context (#8) * fixup! fixup! Feat/refactor context (#8) * rdpgfx/client: Fix rdpgfx_recv_caps_confirm_pdu caps set length parsing * Run format scripts * proxy config.ini: Change default port to 3389 * pf_rdpgfx: Limit caps version to freerdp's supported versions * Gfx OnOpen() wait for dynvc ready (#10) * proxy/gfx: Wait for dynvc ready state before open * pf_channels: Initialize pc->gfx * pf_rdpgfx: Add log and fix comments * rdpgfx: Fix GFX v10.6 PDUs parsing and naming according to the spec * pf_rdpgfx: Proxy rdpgfx v10.6 PDUs * gfx client: Publish FrameAck sending and add auto ack flag * proxy/gfx: Forward frame ack messages * pf_context: Forward domain on connection * pf_rdpgfx: Change max supported caps to 10.6 * proxy: Update config * server/proxy: Use configuration in pf_server_handle_client * rdpgfx/client: Fix size of surface_to_scaled_window, surface_to_window * pf_rdpgfx: Fix formatting * pf_server.c: Fix comments * Move pf_server_rdpgfx_init to pf_rdpgfx * server/proxy/CMakeLists.txt: Fix formatting * pf_client.c: Add comment in proxy_server_reactivate * Fixed const correctness of gfx function pointer Signed-off-by: Mati Shabtay <matishabtay@gmail.com> * server: proxy: update copyright * server: proxy: wrap rdpNego and add a getter for routing token * Refactor routing token getter (#14) * Refactor routing token getter * pf_server_parse_target_from_routing_token change routing_token_length to be DWORD * libfreerdp/core/nego.c: Run format script * pf_server: Run format script * server/proxy: Fix os msbuild tests * pf_channels.c: Remove unused channels * pf_client: Remove unused callbacks * proxy: Remove encomsp callbacks from proxy's client * client/rdpgfx_main.c: Fix msbuild test * pf_config.c: Use StrSep instead of strsep for Windows builds * Removed nego struct from direct access. Signed-off-by: Mati Shabtay <matishabtay@gmail.com> * proxy: Rename binary to freerdp-proxy * rdpgfx_main.c: Revert unwanted double change to send_supported_caps * Cleaned up proxy server code. * All internal functions static * Added simple command line argument to supply a config file * Silence compiler warnings Signed-off-by: kubistika <kmizrachi18@gmail.com>
2019-05-17 15:32:54 +03:00
/**
* FreeRDP: A Remote Desktop Protocol Implementation
* FreeRDP Proxy Server
*
* Copyright 2019 Mati Shabtay <matishabtay@gmail.com>
* Copyright 2019 Kobi Mizrachi <kmizrachi18@gmail.com>
* Copyright 2019 Idan Freiberg <speidy@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <freerdp/freerdp.h>
#include <freerdp/constants.h>
#include <freerdp/gdi/gdi.h>
#include <freerdp/utils/signal.h>
#include <freerdp/client/file.h>
#include <freerdp/client/cmdline.h>
#include <freerdp/client/cliprdr.h>
#include <freerdp/client/channels.h>
#include <freerdp/channels/channels.h>
#include <winpr/crt.h>
#include <winpr/synch.h>
#include <freerdp/log.h>
#include "pf_channels.h"
#include "pf_gdi.h"
#include "pf_graphics.h"
#include "pf_common.h"
#include "pf_client.h"
#include "pf_context.h"
#include "pf_log.h"
#define TAG PROXY_TAG("client")
/**
* Re-negociate with original client after negociation between the proxy
* and the target has finished.
*/
static void proxy_server_reactivate(rdpContext* client, rdpContext* target)
{
pf_common_copy_settings(client->settings, target->settings);
/* DesktopResize causes internal function rdp_server_reactivate to be called,
* which causes the reactivation.
*/
client->update->DesktopResize(client);
}
/**
* This function is called whenever a new frame starts.
* It can be used to reset invalidated areas.
*/
static BOOL pf_client_begin_paint(rdpContext* context)
{
pClientContext* pc = (pClientContext*) context;
proxyData* pdata = pc->pdata;
rdpContext* ps = (rdpContext*)pdata->ps;
return ps->update->BeginPaint(ps);
}
/**
* This function is called when the library completed composing a new
* frame. Read out the changed areas and blit them to your output device.
* The image buffer will have the format specified by gdi_init
*/
static BOOL pf_client_end_paint(rdpContext* context)
{
pClientContext* pc = (pClientContext*) context;
proxyData* pdata = pc->pdata;
rdpContext* ps = (rdpContext*)pdata->ps;
return ps->update->EndPaint(ps);
}
/**
* Called before a connection is established.
*
* TODO: Take client to proxy settings and use channel whitelist to filter out
* unwanted channels.
*/
static BOOL pf_client_pre_connect(freerdp* instance)
{
rdpSettings* settings = instance->settings;
settings->OsMajorType = OSMAJORTYPE_UNIX;
settings->OsMinorType = OSMINORTYPE_NATIVE_XSERVER;
/**
* settings->OrderSupport is initialized at this point.
* Only override it if you plan to implement custom order
* callbacks or deactiveate certain features.
*/
/**
* Register the channel listeners.
* They are required to set up / tear down channels if they are loaded.
*/
PubSub_SubscribeChannelConnected(instance->context->pubSub,
pf_OnChannelConnectedEventHandler);
PubSub_SubscribeChannelDisconnected(instance->context->pubSub,
pf_OnChannelDisconnectedEventHandler);
/**
* Load all required plugins / channels / libraries specified by current
* settings.
*/
WLog_INFO(TAG, "Loading addins");
if (!freerdp_client_load_addins(instance->context->channels,
instance->settings))
{
WLog_ERR(TAG, "Failed to load addins");
return FALSE;
}
return TRUE;
}
static BOOL pf_client_bitmap_update(rdpContext* context, const BITMAP_UPDATE* bitmap)
{
pClientContext* pc = (pClientContext*) context;
proxyData* pdata = pc->pdata;
rdpContext* ps = (rdpContext*)pdata->ps;
return ps->update->BitmapUpdate(ps, bitmap);
}
static BOOL pf_client_desktop_resize(rdpContext* context)
{
pClientContext* pc = (pClientContext*) context;
proxyData* pdata = pc->pdata;
rdpContext* ps = (rdpContext*)pdata->ps;
return ps->update->DesktopResize(ps);
}
/**
* Called after a RDP connection was successfully established.
* Settings might have changed during negociation of client / server feature
* support.
*
* Set up local framebuffers and painting callbacks.
* If required, register pointer callbacks to change the local mouse cursor
* when hovering over the RDP window
*/
static BOOL pf_client_post_connect(freerdp* instance)
{
rdpContext* context;
rdpSettings* settings;
rdpUpdate* update;
pClientContext* pc;
rdpContext* ps;
if (!gdi_init(instance, PIXEL_FORMAT_XRGB32))
return FALSE;
context = instance->context;
settings = instance->settings;
update = instance->update;
pc = (pClientContext*) context;
if (!pf_register_pointer(context->graphics))
return FALSE;
if (!settings->SoftwareGdi)
{
if (!pf_register_graphics(context->graphics))
{
WLog_ERR(TAG, "failed to register graphics");
return FALSE;
}
pf_gdi_register_update_callbacks(update);
brush_cache_register_callbacks(instance->update);
glyph_cache_register_callbacks(instance->update);
bitmap_cache_register_callbacks(instance->update);
offscreen_cache_register_callbacks(instance->update);
palette_cache_register_callbacks(instance->update);
}
update->BeginPaint = pf_client_begin_paint;
update->EndPaint = pf_client_end_paint;
update->BitmapUpdate = pf_client_bitmap_update;
update->DesktopResize = pf_client_desktop_resize;
ps = (rdpContext*) pc->pdata->ps;
proxy_server_reactivate(ps, context);
return TRUE;
}
/* This function is called whether a session ends by failure or success.
* Clean up everything allocated by pre_connect and post_connect.
*/
static void pf_client_post_disconnect(freerdp* instance)
{
pClientContext* context;
proxyData* pdata;
rdpContext* ps;
freerdp_peer* peer;
if (!instance)
return;
if (!instance->context)
return;
context = (pClientContext*) instance->context;
pdata = context->pdata;
PubSub_UnsubscribeChannelConnected(instance->context->pubSub,
pf_OnChannelConnectedEventHandler);
PubSub_UnsubscribeChannelDisconnected(instance->context->pubSub,
pf_OnChannelDisconnectedEventHandler);
gdi_free(instance);
ps = (rdpContext*) pdata->ps;
if (!pf_common_connection_aborted_by_peer(pdata))
{
SetEvent(pdata->connectionClosed);
WLog_INFO(TAG, "connectionClosed event is not set; closing connection with client");
peer = ps->peer;
peer->Disconnect(peer);
}
/* It's important to avoid calling `freerdp_peer_context_free` and `freerdp_peer_free` here,
* in order to avoid double-free. Those objects will be freed by the server when needed.
*/
}
/**
* RDP main loop.
* Connects RDP, loops while running and handles event and dispatch, cleans up
* after the connection ends.
*/
static DWORD WINAPI pf_client_thread_proc(LPVOID arg)
{
freerdp* instance = (freerdp*)arg;
DWORD nCount;
DWORD status;
HANDLE handles[64];
if (!freerdp_connect(instance))
{
WLog_ERR(TAG, "connection failure");
return 0;
}
while (!freerdp_shall_disconnect(instance))
{
nCount = freerdp_get_event_handles(instance->context, &handles[0], 64);
if (nCount == 0)
{
WLog_ERR(TAG, "%s: freerdp_get_event_handles failed", __FUNCTION__);
break;
}
status = WaitForMultipleObjects(nCount, handles, FALSE, 100);
if (status == WAIT_FAILED)
{
WLog_ERR(TAG, "%s: WaitForMultipleObjects failed with %"PRIu32"", __FUNCTION__,
status);
break;
}
if (freerdp_shall_disconnect(instance))
break;
if (!freerdp_check_event_handles(instance->context))
{
if (freerdp_get_last_error(instance->context) == FREERDP_ERROR_SUCCESS)
WLog_ERR(TAG, "Failed to check FreeRDP event handles");
break;
}
}
freerdp_disconnect(instance);
return 0;
}
/**
* Optional global initializer.
* Here we just register a signal handler to print out stack traces
* if available.
* */
static BOOL pf_client_global_init(void)
{
if (freerdp_handle_signals() != 0)
return FALSE;
return TRUE;
}
static int pf_logon_error_info(freerdp* instance, UINT32 data, UINT32 type)
{
pClientContext* pc;
const char* str_data = freerdp_get_logon_error_info_data(data);
const char* str_type = freerdp_get_logon_error_info_type(type);
if (!instance || !instance->context)
return -1;
pc = (pClientContext*) instance->context;
WLog_INFO(TAG, "Logon Error Info %s [%s]", str_data, str_type);
return 1;
}
/**
* Callback set in the rdp_freerdp structure, and used to make a certificate validation
* when the connection requires it.
* This function will actually be called by tls_verify_certificate().
* @see rdp_client_connect() and tls_connect()
* @param instance pointer to the rdp_freerdp structure that contains the connection settings
* @param host The host currently connecting to
* @param port The port currently connecting to
* @param common_name The common name of the certificate, should match host or an alias of it
* @param subject The subject of the certificate
* @param issuer The certificate issuer name
* @param fingerprint The fingerprint of the certificate
* @param flags See VERIFY_CERT_FLAG_* for possible values.
*
* @return 1 if the certificate is trusted, 2 if temporary trusted, 0 otherwise.
*/
static DWORD pf_client_verify_certificate_ex(freerdp* instance, const char* host, UINT16 port,
const char* common_name,
const char* subject, const char* issuer,
const char* fingerprint, DWORD flags)
{
/* TODO: Add trust level to proxy configurable settings */
return 1;
}
/**
* Callback set in the rdp_freerdp structure, and used to make a certificate validation
* when a stored certificate does not match the remote counterpart.
* This function will actually be called by tls_verify_certificate().
* @see rdp_client_connect() and tls_connect()
* @param instance pointer to the rdp_freerdp structure that contains the connection settings
* @param host The host currently connecting to
* @param port The port currently connecting to
* @param common_name The common name of the certificate, should match host or an alias of it
* @param subject The subject of the certificate
* @param issuer The certificate issuer name
* @param fingerprint The fingerprint of the certificate
* @param old_subject The subject of the previous certificate
* @param old_issuer The previous certificate issuer name
* @param old_fingerprint The fingerprint of the previous certificate
* @param flags See VERIFY_CERT_FLAG_* for possible values.
*
* @return 1 if the certificate is trusted, 2 if temporary trusted, 0 otherwise.
*/
static DWORD pf_client_verify_changed_certificate_ex(freerdp* instance,
const char* host, UINT16 port,
const char* common_name,
const char* subject, const char* issuer,
const char* fingerprint,
const char* old_subject, const char* old_issuer,
const char* old_fingerprint, DWORD flags)
{
/* TODO: Add trust level to proxy configurable settings */
return 1;
}
static BOOL pf_client_client_new(freerdp* instance, rdpContext* context)
{
if (!instance || !context)
return FALSE;
instance->PreConnect = pf_client_pre_connect;
instance->PostConnect = pf_client_post_connect;
instance->PostDisconnect = pf_client_post_disconnect;
instance->VerifyCertificateEx = pf_client_verify_certificate_ex;
instance->VerifyChangedCertificateEx = pf_client_verify_changed_certificate_ex;
instance->LogonErrorInfo = pf_logon_error_info;
return TRUE;
}
int RdpClientEntry(RDP_CLIENT_ENTRY_POINTS* pEntryPoints)
{
ZeroMemory(pEntryPoints, sizeof(RDP_CLIENT_ENTRY_POINTS));
pEntryPoints->Version = RDP_CLIENT_INTERFACE_VERSION;
pEntryPoints->Size = sizeof(RDP_CLIENT_ENTRY_POINTS_V1);
pEntryPoints->GlobalInit = pf_client_global_init;
pEntryPoints->ContextSize = sizeof(pClientContext);
/* Client init and finish */
pEntryPoints->ClientNew = pf_client_client_new;
return 0;
}
/**
* Starts running a client connection towards target server.
*/
DWORD WINAPI pf_client_start(LPVOID arg)
{
rdpContext* context = (rdpContext*)arg;
if (freerdp_client_start(context) != 0)
return 1;
return pf_client_thread_proc(context->instance);
}