From 78acedb40ee275b6aadcb6a5fbfc8922ea30835a Mon Sep 17 00:00:00 2001 From: akallabeth Date: Mon, 14 Oct 2024 15:50:38 +0200 Subject: [PATCH] [warnigns] fix Wshorten-64-to-32 --- channels/audin/client/alsa/audin_alsa.c | 2 +- channels/audin/server/audin.c | 4 +- channels/cliprdr/client/cliprdr_format.c | 3 +- channels/cliprdr/client/cliprdr_main.c | 10 +- channels/cliprdr/server/cliprdr_main.c | 6 +- channels/disp/server/disp_main.c | 8 +- channels/location/server/location_main.c | 3 +- channels/printer/client/printer_main.c | 17 ++- channels/rdpdr/client/rdpdr_main.c | 15 +- channels/rdpdr/server/rdpdr_main.c | 3 +- channels/rdpecam/client/encoding.c | 5 +- .../server/camera_device_enumerator_main.c | 4 +- channels/rdpecam/server/camera_device_main.c | 6 +- channels/rdpei/client/rdpei_main.c | 41 +++--- channels/rdpei/server/rdpei_main.c | 9 +- channels/rdpemsc/server/mouse_cursor_main.c | 4 +- channels/rdpgfx/client/rdpgfx_codec.c | 21 ++- channels/rdpgfx/client/rdpgfx_main.c | 2 +- channels/rdpgfx/server/rdpgfx_main.c | 46 ++++--- channels/rdpsnd/client/pulse/rdpsnd_pulse.c | 9 +- channels/rdpsnd/client/rdpsnd_main.c | 6 +- channels/rdpsnd/server/rdpsnd_main.c | 100 ++++++++------ channels/remdesk/client/remdesk_main.c | 130 ++++++++++++------ channels/remdesk/server/remdesk_main.c | 22 ++- channels/urbdrc/client/urbdrc_main.c | 13 +- channels/video/client/video_main.c | 24 ++-- .../SDL2/dialogs/sdl_connection_dialog.cpp | 6 +- client/SDL/SDL2/dialogs/sdl_input_widgets.cpp | 7 +- client/SDL/SDL2/dialogs/sdl_selectlist.cpp | 13 +- client/SDL/SDL2/dialogs/sdl_widget.cpp | 5 +- client/SDL/SDL2/sdl_disp.cpp | 4 +- client/SDL/SDL2/sdl_freerdp.cpp | 4 +- .../SDL3/dialogs/sdl_connection_dialog.cpp | 6 +- client/SDL/SDL3/dialogs/sdl_input_widgets.cpp | 10 +- client/SDL/SDL3/dialogs/sdl_selectlist.cpp | 16 ++- client/SDL/SDL3/dialogs/sdl_widget.cpp | 17 ++- client/SDL/SDL3/sdl_clip.cpp | 100 +++++++------- client/SDL/SDL3/sdl_disp.cpp | 4 +- client/SDL/SDL3/sdl_freerdp.cpp | 4 +- client/Wayland/wlf_cliprdr.c | 4 +- client/Wayland/wlf_disp.c | 3 +- client/Wayland/wlfreerdp.c | 11 +- client/X11/xf_client.c | 2 +- client/X11/xf_cliprdr.c | 34 +++-- client/X11/xf_event.c | 18 ++- client/X11/xf_floatbar.c | 13 +- client/X11/xf_keyboard.c | 3 +- client/X11/xf_monitor.c | 38 ++--- client/X11/xf_rail.c | 30 ++-- client/X11/xf_rail.h | 2 +- client/X11/xf_window.c | 20 ++- client/X11/xfreerdp.h | 2 +- client/common/client.c | 2 +- client/common/client_cliprdr_file.c | 21 ++- client/common/cmdline.c | 5 +- client/common/file.c | 6 +- libfreerdp/cache/glyph.c | 2 +- libfreerdp/cache/persistent.c | 2 +- libfreerdp/cache/pointer.c | 8 +- libfreerdp/codec/color.c | 26 ++-- libfreerdp/codec/mppc.c | 5 +- libfreerdp/codec/ncrush.c | 6 +- libfreerdp/codec/nsc.c | 4 +- libfreerdp/codec/nsc_types.h | 2 +- libfreerdp/codec/planar.c | 23 +++- libfreerdp/codec/region.c | 11 +- libfreerdp/codec/rfx.c | 17 ++- libfreerdp/codec/rfx_decode.c | 3 +- libfreerdp/codec/rfx_rlgr.c | 29 ++-- libfreerdp/codec/xcrush.c | 20 ++- libfreerdp/codec/zgfx.c | 38 ++--- libfreerdp/common/settings.c | 4 +- libfreerdp/core/capabilities.c | 6 +- libfreerdp/core/channels.c | 16 ++- libfreerdp/core/connection.c | 16 +-- libfreerdp/core/credssp_auth.c | 30 ++-- libfreerdp/core/gateway/arm.c | 18 ++- libfreerdp/core/gateway/http.c | 35 +++-- libfreerdp/core/gateway/http.h | 2 +- libfreerdp/core/gateway/ncacn_http.c | 31 +++-- libfreerdp/core/gateway/rdg.c | 66 +++++---- libfreerdp/core/gateway/rpc.h | 2 +- libfreerdp/core/gateway/rpc_client.c | 26 ++-- libfreerdp/core/gateway/rts.c | 26 ++-- libfreerdp/core/gateway/tsg.c | 10 +- libfreerdp/core/gateway/websocket.c | 31 ++--- libfreerdp/core/gateway/wst.c | 15 +- libfreerdp/core/listener.c | 8 +- libfreerdp/core/message.c | 2 +- libfreerdp/core/orders.c | 7 +- libfreerdp/core/rdp.c | 6 +- libfreerdp/core/redirection.c | 21 ++- libfreerdp/core/security.c | 3 +- libfreerdp/core/server.c | 68 +++++---- libfreerdp/core/tcp.c | 19 +-- libfreerdp/crypto/er.c | 4 +- libfreerdp/crypto/tls.c | 24 ++-- libfreerdp/emu/scard/smartcard_emulate.c | 18 ++- libfreerdp/emu/scard/smartcard_virtual_gids.c | 4 +- libfreerdp/gdi/region.c | 42 +++--- libfreerdp/locale/keyboard.c | 12 +- libfreerdp/primitives/prim_YUV.c | 60 ++++---- libfreerdp/primitives/prim_set.c | 8 +- libfreerdp/primitives/sse/prim_YUV_ssse3.c | 20 +-- libfreerdp/primitives/sse/prim_add_sse3.c | 2 +- libfreerdp/primitives/sse/prim_copy_avx2.c | 4 +- libfreerdp/primitives/sse/prim_copy_sse4_1.c | 4 +- libfreerdp/utils/http.c | 21 ++- libfreerdp/utils/passphrase.c | 3 +- libfreerdp/utils/pcap.c | 6 +- server/Sample/sfreerdp.c | 15 +- server/proxy/channels/pf_channel_drdynvc.c | 10 +- server/proxy/pf_client.c | 4 +- server/proxy/pf_config.c | 2 +- server/proxy/pf_server.c | 2 +- server/shadow/X11/x11_shadow.c | 11 +- server/shadow/X11/x11_shadow.h | 2 +- server/shadow/shadow_capture.c | 12 +- winpr/libwinpr/clipboard/synthetic.c | 25 ++-- winpr/libwinpr/comm/comm.c | 2 +- winpr/libwinpr/comm/comm_io.c | 7 +- winpr/libwinpr/crt/string.c | 5 +- winpr/libwinpr/crt/unicode.c | 17 ++- winpr/libwinpr/crypto/md4.c | 8 +- winpr/libwinpr/crypto/rc4.c | 4 +- winpr/libwinpr/file/file.c | 4 +- winpr/libwinpr/input/scancode.c | 14 +- winpr/libwinpr/ncrypt/ncrypt_pkcs11.c | 28 +++- .../libwinpr/path/include/PathAllocCombine.h | 65 ++++----- winpr/libwinpr/shell/shell.c | 10 +- winpr/libwinpr/sspi/Kerberos/kerberos.c | 12 +- winpr/libwinpr/sspi/Kerberos/krb5glue_mit.c | 9 +- winpr/libwinpr/sspi/Negotiate/negotiate.c | 22 ++- winpr/libwinpr/sspi/sspi_gss.c | 2 +- winpr/libwinpr/sspi/sspi_winpr.c | 21 ++- winpr/libwinpr/sspicli/sspicli.c | 9 +- winpr/libwinpr/utils/image.c | 26 +++- winpr/libwinpr/winsock/winsock.c | 9 +- 138 files changed, 1307 insertions(+), 869 deletions(-) diff --git a/channels/audin/client/alsa/audin_alsa.c b/channels/audin/client/alsa/audin_alsa.c index 7b71990f2..e74097129 100644 --- a/channels/audin/client/alsa/audin_alsa.c +++ b/channels/audin/client/alsa/audin_alsa.c @@ -182,7 +182,7 @@ static DWORD WINAPI audin_alsa_thread_func(LPVOID arg) } else if (framesRead < 0) { - WLog_Print(alsa->log, WLOG_ERROR, "snd_pcm_readi (%s)", snd_strerror(framesRead)); + WLog_Print(alsa->log, WLOG_ERROR, "snd_pcm_readi (%s)", snd_strerror((int)framesRead)); error = ERROR_INTERNAL_ERROR; break; } diff --git a/channels/audin/server/audin.c b/channels/audin/server/audin.c index 91387268e..0ea728d9d 100644 --- a/channels/audin/server/audin.c +++ b/channels/audin/server/audin.c @@ -569,9 +569,7 @@ static UINT audin_server_packet_send(audin_server_context* context, wStream* s) WINPR_ASSERT(s); const size_t pos = Stream_GetPosition(s); - if (pos > UINT32_MAX) - return ERROR_INVALID_PARAMETER; - + WINPR_ASSERT(pos <= UINT32_MAX); if (!WTSVirtualChannelWrite(audin->audin_channel, Stream_BufferAs(s, char), (UINT32)pos, &written)) { diff --git a/channels/cliprdr/client/cliprdr_format.c b/channels/cliprdr/client/cliprdr_format.c index 8b13af453..41978d988 100644 --- a/channels/cliprdr/client/cliprdr_format.c +++ b/channels/cliprdr/client/cliprdr_format.c @@ -98,7 +98,8 @@ CLIPRDR_FORMAT_LIST cliprdr_filter_format_list(const CLIPRDR_FORMAT_LIST* list, } } } - filtered.numFormats = wpos; + WINPR_ASSERT(wpos <= UINT32_MAX); + filtered.numFormats = (UINT32)wpos; return filtered; } diff --git a/channels/cliprdr/client/cliprdr_main.c b/channels/cliprdr/client/cliprdr_main.c index f1b64aa23..7202cae4e 100644 --- a/channels/cliprdr/client/cliprdr_main.c +++ b/channels/cliprdr/client/cliprdr_main.c @@ -59,17 +59,17 @@ CliprdrClientContext* cliprdr_get_client_interface(cliprdrPlugin* cliprdr) */ static UINT cliprdr_packet_send(cliprdrPlugin* cliprdr, wStream* s) { - size_t pos = 0; - UINT32 dataLen = 0; UINT status = CHANNEL_RC_OK; WINPR_ASSERT(cliprdr); WINPR_ASSERT(s); - pos = Stream_GetPosition(s); - dataLen = pos - 8; + const size_t pos = Stream_GetPosition(s); + const size_t dataLen = pos - 8; + WINPR_ASSERT(dataLen <= UINT32_MAX); + Stream_SetPosition(s, 4); - Stream_Write_UINT32(s, dataLen); + Stream_Write_UINT32(s, (UINT32)dataLen); Stream_SetPosition(s, pos); WLog_DBG(TAG, "Cliprdr Sending (%" PRIu32 " bytes)", dataLen + 8); diff --git a/channels/cliprdr/server/cliprdr_main.c b/channels/cliprdr/server/cliprdr_main.c index e46410fea..9467f9ded 100644 --- a/channels/cliprdr/server/cliprdr_main.c +++ b/channels/cliprdr/server/cliprdr_main.c @@ -96,12 +96,8 @@ static UINT cliprdr_server_packet_send(CliprdrServerPrivate* cliprdr, wStream* s dataLen = (UINT32)(pos - 8); Stream_SetPosition(s, 4); Stream_Write_UINT32(s, dataLen); - if (pos > UINT32_MAX) - { - rc = ERROR_INVALID_DATA; - goto fail; - } + WINPR_ASSERT(pos <= UINT32_MAX); status = WTSVirtualChannelWrite(cliprdr->ChannelHandle, Stream_BufferAs(s, char), (UINT32)pos, &written); rc = status ? CHANNEL_RC_OK : ERROR_INTERNAL_ERROR; diff --git a/channels/disp/server/disp_main.c b/channels/disp/server/disp_main.c index 297c80d1b..a80c11d76 100644 --- a/channels/disp/server/disp_main.c +++ b/channels/disp/server/disp_main.c @@ -493,13 +493,9 @@ static UINT disp_server_packet_send(DispServerContext* context, wStream* s) WINPR_ASSERT(s); const size_t pos = Stream_GetPosition(s); - if (pos > UINT32_MAX) - { - ret = ERROR_INTERNAL_ERROR; - goto out; - } - if (!WTSVirtualChannelWrite(context->priv->disp_channel, Stream_BufferAs(s, char), pos, + WINPR_ASSERT(pos <= UINT32_MAX); + if (!WTSVirtualChannelWrite(context->priv->disp_channel, Stream_BufferAs(s, char), (UINT32)pos, &written)) { WLog_ERR(TAG, "WTSVirtualChannelWrite failed!"); diff --git a/channels/location/server/location_main.c b/channels/location/server/location_main.c index d2c86e771..e7a505217 100644 --- a/channels/location/server/location_main.c +++ b/channels/location/server/location_main.c @@ -546,8 +546,7 @@ static UINT location_server_packet_send(LocationServerContext* context, wStream* WINPR_ASSERT(s); const size_t pos = Stream_GetPosition(s); - if (pos > UINT32_MAX) - return ERROR_OUTOFMEMORY; + WINPR_ASSERT(pos <= UINT32_MAX); if (!WTSVirtualChannelWrite(location->location_channel, Stream_BufferAs(s, char), (ULONG)pos, &written)) { diff --git a/channels/printer/client/printer_main.c b/channels/printer/client/printer_main.c index 4bb61a0a9..01c572ee1 100644 --- a/channels/printer/client/printer_main.c +++ b/channels/printer/client/printer_main.c @@ -103,7 +103,6 @@ static BOOL printer_write_setting(const char* path, prn_conf_t type, const void* DWORD written = 0; BOOL rc = FALSE; HANDLE file = NULL; - size_t b64len = 0; char* base64 = NULL; const char* name = filemap[type]; char* abs = GetCombinedPath(path, name); @@ -129,8 +128,8 @@ static BOOL printer_write_setting(const char* path, prn_conf_t type, const void* /* base64 char represents 6bit -> 4*(n/3) is the length which is * always smaller than 2*n */ - b64len = strnlen(base64, 2 * length); - rc = WriteFile(file, base64, b64len, &written, NULL); + const size_t b64len = strnlen(base64, 2 * length); + rc = WriteFile(file, base64, (UINT32)b64len, &written, NULL); if (b64len != written) rc = FALSE; @@ -313,7 +312,12 @@ static BOOL printer_load_from_config(const rdpSettings* settings, rdpPrinter* pr wlen++; path = get_printer_config_path(settings, wname, wlen * sizeof(WCHAR)); - PrinterNameLen = wlen * sizeof(WCHAR); + { + const size_t plen = wlen * sizeof(WCHAR); + if (plen > UINT32_MAX) + goto fail; + PrinterNameLen = (UINT32)plen; + } if (!path) goto fail; @@ -331,7 +335,10 @@ static BOOL printer_load_from_config(const rdpSettings* settings, rdpPrinter* pr DriverName = ConvertUtf8ToWCharAlloc(printer->driver, &len); if (!DriverName) goto fail; - DriverNameLen = (len + 1) * sizeof(WCHAR); + const size_t dlen = (len + 1) * sizeof(WCHAR); + if (dlen > UINT32_MAX) + goto fail; + DriverNameLen = (UINT32)dlen; } if (!printer_read_setting(path, PRN_CONF_DATA, &CachedPrinterConfigData, &CachedFieldsLen)) diff --git a/channels/rdpdr/client/rdpdr_main.c b/channels/rdpdr/client/rdpdr_main.c index 56b806390..78324f8dc 100644 --- a/channels/rdpdr/client/rdpdr_main.c +++ b/channels/rdpdr/client/rdpdr_main.c @@ -27,6 +27,7 @@ #include #include #include +#include #include #include @@ -938,6 +939,7 @@ static BOOL hotplug_delete_foreach(ULONG_PTR key, void* element, void* data) WINPR_ASSERT(arg); WINPR_ASSERT(arg->rdpdr); WINPR_ASSERT(arg->dev_array || (arg->dev_array_size == 0)); + WINPR_ASSERT(key <= UINT32_MAX); if (!device_ext || (device_ext->device.type != RDPDR_DTYP_FILESYSTEM) || !device_ext->path || !device_ext->automount) @@ -968,7 +970,7 @@ static BOOL hotplug_delete_foreach(ULONG_PTR key, void* element, void* data) if (!dev_found) { UINT error = 0; - UINT32 ids[1] = { key }; + UINT32 ids[1] = { (UINT32)key }; WINPR_ASSERT(arg->rdpdr->devman); devman_unregister_device(arg->rdpdr->devman, (void*)key); @@ -1878,7 +1880,6 @@ static UINT rdpdr_process_receive(rdpdrPlugin* rdpdr, wStream* s) */ UINT rdpdr_send(rdpdrPlugin* rdpdr, wStream* s) { - UINT status = 0; rdpdrPlugin* plugin = rdpdr; if (!s) @@ -1894,9 +1895,13 @@ UINT rdpdr_send(rdpdrPlugin* rdpdr, wStream* s) } const size_t pos = Stream_GetPosition(s); - rdpdr_dump_send_packet(rdpdr->log, WLOG_TRACE, s, "[rdpdr-channel] send"); - status = plugin->channelEntryPoints.pVirtualChannelWriteEx( - plugin->InitHandle, plugin->OpenHandle, Stream_Buffer(s), pos, s); + UINT status = ERROR_INTERNAL_ERROR; + if (pos <= UINT32_MAX) + { + rdpdr_dump_send_packet(rdpdr->log, WLOG_TRACE, s, "[rdpdr-channel] send"); + status = plugin->channelEntryPoints.pVirtualChannelWriteEx( + plugin->InitHandle, plugin->OpenHandle, Stream_Buffer(s), (UINT32)pos, s); + } if (status != CHANNEL_RC_OK) { diff --git a/channels/rdpdr/server/rdpdr_main.c b/channels/rdpdr/server/rdpdr_main.c index 806624bf9..3822f6bfc 100644 --- a/channels/rdpdr/server/rdpdr_main.c +++ b/channels/rdpdr/server/rdpdr_main.c @@ -206,7 +206,6 @@ static RDPDR_IRP* rdpdr_server_dequeue_irp(RdpdrServerContext* context, UINT32 c static UINT rdpdr_seal_send_free_request(RdpdrServerContext* context, wStream* s) { BOOL status = 0; - size_t length = 0; ULONG written = 0; WINPR_ASSERT(context); @@ -214,7 +213,7 @@ static UINT rdpdr_seal_send_free_request(RdpdrServerContext* context, wStream* s WINPR_ASSERT(s); Stream_SealLength(s); - length = Stream_Length(s); + const size_t length = Stream_Length(s); WINPR_ASSERT(length <= UINT32_MAX); Stream_SetPosition(s, 0); diff --git a/channels/rdpecam/client/encoding.c b/channels/rdpecam/client/encoding.c index 5292fc0cc..0bc5c061f 100644 --- a/channels/rdpecam/client/encoding.c +++ b/channels/rdpecam/client/encoding.c @@ -161,8 +161,9 @@ static BOOL ecam_encoder_compress_h264(CameraDeviceStream* stream, const BYTE* s #if defined(WITH_INPUT_FORMAT_MJPG) if (inputFormat == CAM_MEDIA_FORMAT_MJPG) { - stream->avInputPkt->data = WINPR_CAST_CONST_PTR_AWAY(srcData, BYTE*); - stream->avInputPkt->size = srcSize; + stream->avInputPkt->data = WINPR_CAST_CONST_PTR_AWAY(srcData, uint8_t*); + WINPR_ASSERT(srcSize <= INT32_MAX); + stream->avInputPkt->size = (int)srcSize; if (avcodec_send_packet(stream->avContext, stream->avInputPkt) < 0) { diff --git a/channels/rdpecam/server/camera_device_enumerator_main.c b/channels/rdpecam/server/camera_device_enumerator_main.c index 500e14861..79c18bd4f 100644 --- a/channels/rdpecam/server/camera_device_enumerator_main.c +++ b/channels/rdpecam/server/camera_device_enumerator_main.c @@ -535,8 +535,10 @@ static UINT enumerator_server_packet_send(CamDevEnumServerContext* context, wStr UINT error = CHANNEL_RC_OK; ULONG written = 0; + const size_t len = Stream_GetPosition(s); + WINPR_ASSERT(len <= UINT32_MAX); if (!WTSVirtualChannelWrite(enumerator->enumerator_channel, Stream_BufferAs(s, char), - Stream_GetPosition(s), &written)) + (UINT32)len, &written)) { WLog_ERR(TAG, "WTSVirtualChannelWrite failed!"); error = ERROR_INTERNAL_ERROR; diff --git a/channels/rdpecam/server/camera_device_main.c b/channels/rdpecam/server/camera_device_main.c index 1d15dfe89..535d38d5a 100644 --- a/channels/rdpecam/server/camera_device_main.c +++ b/channels/rdpecam/server/camera_device_main.c @@ -708,8 +708,10 @@ static UINT device_server_packet_send(CameraDeviceServerContext* context, wStrea WINPR_ASSERT(context); WINPR_ASSERT(s); - if (!WTSVirtualChannelWrite(device->device_channel, Stream_BufferAs(s, char), - Stream_GetPosition(s), &written)) + const size_t len = Stream_GetPosition(s); + WINPR_ASSERT(len <= UINT32_MAX); + if (!WTSVirtualChannelWrite(device->device_channel, Stream_BufferAs(s, char), (UINT32)len, + &written)) { WLog_ERR(TAG, "WTSVirtualChannelWrite failed!"); error = ERROR_INTERNAL_ERROR; diff --git a/channels/rdpei/client/rdpei_main.c b/channels/rdpei/client/rdpei_main.c index 23cc8b8e0..9169a3d8e 100644 --- a/channels/rdpei/client/rdpei_main.c +++ b/channels/rdpei/client/rdpei_main.c @@ -24,6 +24,7 @@ #include #include #include +#include #include #include @@ -217,20 +218,23 @@ static UINT rdpei_add_frame(RdpeiClientContext* context) * @return 0 on success, otherwise a Win32 error code */ static UINT rdpei_send_pdu(GENERIC_CHANNEL_CALLBACK* callback, wStream* s, UINT16 eventId, - UINT32 pduLength) + size_t pduLength) { UINT status = 0; if (!callback || !s || !callback->channel || !callback->channel->Write) return ERROR_INTERNAL_ERROR; + if (pduLength > UINT32_MAX) + return ERROR_INVALID_PARAMETER; + RDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)callback->plugin; if (!rdpei) return ERROR_INTERNAL_ERROR; Stream_SetPosition(s, 0); Stream_Write_UINT16(s, eventId); /* eventId (2 bytes) */ - Stream_Write_UINT32(s, pduLength); /* pduLength (4 bytes) */ + Stream_Write_UINT32(s, (UINT32)pduLength); /* pduLength (4 bytes) */ Stream_SetPosition(s, Stream_Length(s)); status = callback->channel->Write(callback->channel, (UINT32)Stream_Length(s), Stream_Buffer(s), NULL); @@ -295,14 +299,19 @@ static UINT rdpei_write_pen_frame(wStream* s, const RDPINPUT_PEN_FRAME* frame) return CHANNEL_RC_OK; } -static UINT rdpei_send_pen_event_pdu(GENERIC_CHANNEL_CALLBACK* callback, UINT32 frameOffset, - const RDPINPUT_PEN_FRAME* frames, UINT16 count) +static UINT rdpei_send_pen_event_pdu(GENERIC_CHANNEL_CALLBACK* callback, size_t frameOffset, + const RDPINPUT_PEN_FRAME* frames, size_t count) { UINT status = 0; wStream* s = NULL; WINPR_ASSERT(callback); + if (frameOffset > UINT32_MAX) + return ERROR_INVALID_PARAMETER; + if (count > UINT16_MAX) + return ERROR_INVALID_PARAMETER; + RDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)callback->plugin; if (!rdpei) return ERROR_INTERNAL_ERROR; @@ -323,10 +332,11 @@ static UINT rdpei_send_pen_event_pdu(GENERIC_CHANNEL_CALLBACK* callback, UINT32 * the time that has elapsed (in milliseconds) from when the oldest touch frame * was generated to when it was encoded for transmission by the client. */ - rdpei_write_4byte_unsigned(s, frameOffset); /* encodeTime (FOUR_BYTE_UNSIGNED_INTEGER) */ - rdpei_write_2byte_unsigned(s, count); /* (frameCount) TWO_BYTE_UNSIGNED_INTEGER */ + rdpei_write_4byte_unsigned(s, + (UINT32)frameOffset); /* encodeTime (FOUR_BYTE_UNSIGNED_INTEGER) */ + rdpei_write_2byte_unsigned(s, (UINT16)count); /* (frameCount) TWO_BYTE_UNSIGNED_INTEGER */ - for (UINT16 x = 0; x < count; x++) + for (size_t x = 0; x < count; x++) { if ((status = rdpei_write_pen_frame(s, &frames[x]))) { @@ -696,13 +706,10 @@ static UINT rdpei_send_touch_event_pdu(GENERIC_CHANNEL_CALLBACK* callback, RDPINPUT_TOUCH_FRAME* frame) { UINT status = 0; - wStream* s = NULL; - UINT32 pduLength = 0; - RDPEI_PLUGIN* rdpei = NULL; WINPR_ASSERT(callback); - rdpei = (RDPEI_PLUGIN*)callback->plugin; + RDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)callback->plugin; if (!rdpei || !rdpei->rdpcontext) return ERROR_INTERNAL_ERROR; if (freerdp_settings_get_bool(rdpei->rdpcontext->settings, FreeRDP_SuspendInput)) @@ -711,8 +718,8 @@ static UINT rdpei_send_touch_event_pdu(GENERIC_CHANNEL_CALLBACK* callback, if (!frame) return ERROR_INTERNAL_ERROR; - pduLength = 64 + (frame->contactCount * 64); - s = Stream_New(NULL, pduLength); + size_t pduLength = 64ULL + (64ULL * frame->contactCount); + wStream* s = Stream_New(NULL, pduLength); if (!s) { @@ -739,8 +746,7 @@ static UINT rdpei_send_touch_event_pdu(GENERIC_CHANNEL_CALLBACK* callback, } Stream_SealLength(s); - pduLength = Stream_Length(s); - status = rdpei_send_pdu(callback, s, EVENTID_TOUCH, pduLength); + status = rdpei_send_pdu(callback, s, EVENTID_TOUCH, Stream_Length(s)); Stream_Free(s, TRUE); return status; } @@ -1059,12 +1065,15 @@ static UINT rdpei_touch_process(RdpeiClientContext* context, INT32 externalId, U contactIdlocal = contactPoint->contactId; LeaveCriticalSection(&rdpei->lock); + if (contactIdlocal > UINT32_MAX) + return ERROR_INVALID_PARAMETER; + if (contactIdlocal >= 0) { RDPINPUT_CONTACT_DATA contact = { 0 }; contact.x = x; contact.y = y; - contact.contactId = contactIdlocal; + contact.contactId = (UINT32)contactIdlocal; contact.contactFlags = contactFlags; contact.fieldsPresent = fieldFlags; diff --git a/channels/rdpei/server/rdpei_main.c b/channels/rdpei/server/rdpei_main.c index f7c9bedf4..601ea86d6 100644 --- a/channels/rdpei/server/rdpei_main.c +++ b/channels/rdpei/server/rdpei_main.c @@ -623,9 +623,8 @@ UINT rdpei_server_send_sc_ready(RdpeiServerContext* context, UINT32 version, UIN Stream_Write_UINT32(priv->outputStream, features); const size_t pos = Stream_GetPosition(priv->outputStream); - if (pos > UINT32_MAX) - return ERROR_INTERNAL_ERROR; + WINPR_ASSERT(pos <= UINT32_MAX); if (!WTSVirtualChannelWrite(priv->channelHandle, Stream_BufferAs(priv->outputStream, char), (ULONG)pos, &written)) { @@ -670,9 +669,8 @@ UINT rdpei_server_suspend(RdpeiServerContext* context) Stream_Write_UINT32(priv->outputStream, RDPINPUT_HEADER_LENGTH); const size_t pos = Stream_GetPosition(priv->outputStream); - if (pos > UINT32_MAX) - return ERROR_INTERNAL_ERROR; + WINPR_ASSERT(pos <= UINT32_MAX); if (!WTSVirtualChannelWrite(priv->channelHandle, Stream_BufferAs(priv->outputStream, char), (ULONG)pos, &written)) { @@ -717,9 +715,8 @@ UINT rdpei_server_resume(RdpeiServerContext* context) Stream_Write_UINT32(priv->outputStream, RDPINPUT_HEADER_LENGTH); const size_t pos = Stream_GetPosition(priv->outputStream); - if (pos > UINT32_MAX) - return CHANNEL_RC_NO_BUFFER; + WINPR_ASSERT(pos <= UINT32_MAX); if (!WTSVirtualChannelWrite(priv->channelHandle, Stream_BufferAs(priv->outputStream, char), (ULONG)pos, &written)) { diff --git a/channels/rdpemsc/server/mouse_cursor_main.c b/channels/rdpemsc/server/mouse_cursor_main.c index 649ec8f96..6aca3680a 100644 --- a/channels/rdpemsc/server/mouse_cursor_main.c +++ b/channels/rdpemsc/server/mouse_cursor_main.c @@ -519,8 +519,8 @@ static UINT mouse_cursor_server_packet_send(MouseCursorServerContext* context, w WINPR_ASSERT(s); const size_t pos = Stream_GetPosition(s); - if (pos > UINT32_MAX) - return ERROR_OUTOFMEMORY; + + WINPR_ASSERT(pos <= UINT32_MAX); if (!WTSVirtualChannelWrite(mouse_cursor->mouse_cursor_channel, Stream_BufferAs(s, char), (ULONG)pos, &written)) { diff --git a/channels/rdpgfx/client/rdpgfx_codec.c b/channels/rdpgfx/client/rdpgfx_codec.c index 0f3970eeb..b08aa0149 100644 --- a/channels/rdpgfx/client/rdpgfx_codec.c +++ b/channels/rdpgfx/client/rdpgfx_codec.c @@ -211,16 +211,16 @@ static UINT rdpgfx_decode_AVC444(RDPGFX_PLUGIN* gfx, RDPGFX_SURFACE_COMMAND* cmd if (h264.LC == 0) { - tmp = h264.cbAvc420EncodedBitstream1 - pos2 + pos1; + const size_t bitstreamLen = 1ULL * h264.cbAvc420EncodedBitstream1 - pos2 + pos1; - if (!Stream_CheckAndLogRequiredLength(TAG, s, tmp)) + if ((bitstreamLen > UINT32_MAX) || !Stream_CheckAndLogRequiredLength(TAG, s, bitstreamLen)) { error = ERROR_INVALID_DATA; goto fail; } - h264.bitstream[0].length = tmp; - Stream_Seek(s, tmp); + h264.bitstream[0].length = (UINT32)bitstreamLen; + Stream_Seek(s, bitstreamLen); if ((error = rdpgfx_read_h264_metablock(gfx, s, &(h264.bitstream[1].meta)))) { @@ -229,10 +229,19 @@ static UINT rdpgfx_decode_AVC444(RDPGFX_PLUGIN* gfx, RDPGFX_SURFACE_COMMAND* cmd } h264.bitstream[1].data = Stream_Pointer(s); - h264.bitstream[1].length = Stream_GetRemainingLength(s); + + const size_t len = Stream_GetRemainingLength(s); + if (len > UINT32_MAX) + goto fail; + h264.bitstream[1].length = (UINT32)len; } else - h264.bitstream[0].length = Stream_GetRemainingLength(s); + { + const size_t len = Stream_GetRemainingLength(s); + if (len > UINT32_MAX) + goto fail; + h264.bitstream[0].length = (UINT32)len; + } cmd->extra = (void*)&h264; diff --git a/channels/rdpgfx/client/rdpgfx_main.c b/channels/rdpgfx/client/rdpgfx_main.c index 6545d5d1f..e2b808e49 100644 --- a/channels/rdpgfx/client/rdpgfx_main.c +++ b/channels/rdpgfx/client/rdpgfx_main.c @@ -1253,7 +1253,7 @@ static UINT rdpgfx_recv_end_frame_pdu(GENERIC_CHANNEL_CALLBACK* callback, wStrea diff = 0; qoe.frameId = pdu.frameId; - qoe.timestamp = gfx->StartDecodingTime; + qoe.timestamp = gfx->StartDecodingTime % UINT32_MAX; qoe.timeDiffSE = diff; qoe.timeDiffEDR = EndFrameTime; diff --git a/channels/rdpgfx/server/rdpgfx_main.c b/channels/rdpgfx/server/rdpgfx_main.c index 2d00fa445..7ad699382 100644 --- a/channels/rdpgfx/server/rdpgfx_main.c +++ b/channels/rdpgfx/server/rdpgfx_main.c @@ -97,9 +97,11 @@ static INLINE BOOL rdpgfx_server_packet_complete_header(wStream* s, size_t start const size_t cap = Stream_Capacity(s); if (cap < start + RDPGFX_HEADER_SIZE) return FALSE; + if ((start > UINT32_MAX) || (current > start)) + return FALSE; /* Fill actual length */ Stream_SetPosition(s, start + RDPGFX_HEADER_SIZE - sizeof(UINT32)); - Stream_Write_UINT32(s, current - start); /* pduLength (4 bytes) */ + Stream_Write_UINT32(s, (UINT32)(current - start)); /* pduLength (4 bytes) */ Stream_SetPosition(s, current); return TRUE; } @@ -117,7 +119,10 @@ static UINT rdpgfx_server_packet_send(RdpgfxServerContext* context, wStream* s) UINT32 flags = 0; ULONG written = 0; BYTE* pSrcData = Stream_Buffer(s); - UINT32 SrcSize = Stream_GetPosition(s); + const size_t SrcSize = Stream_GetPosition(s); + if (SrcSize > UINT32_MAX) + return ERROR_INTERNAL_ERROR; + wStream* fs = NULL; /* Allocate new stream with enough capacity. Additional overhead is * descriptor (1 bytes) + segmentCount (2 bytes) + uncompressedSize (4 bytes) @@ -131,15 +136,18 @@ static UINT rdpgfx_server_packet_send(RdpgfxServerContext* context, wStream* s) goto out; } - if (zgfx_compress_to_stream(context->priv->zgfx, fs, pSrcData, SrcSize, &flags) < 0) + if (zgfx_compress_to_stream(context->priv->zgfx, fs, pSrcData, (UINT32)SrcSize, &flags) < 0) { WLog_Print(context->priv->log, WLOG_ERROR, "zgfx_compress_to_stream failed!"); error = ERROR_INTERNAL_ERROR; goto out; } + const size_t pos = Stream_GetPosition(fs); + + WINPR_ASSERT(pos <= UINT32_MAX); if (!WTSVirtualChannelWrite(context->priv->rdpgfx_channel, Stream_BufferAs(fs, char), - Stream_GetPosition(fs), &written)) + (UINT32)pos, &written)) { WLog_Print(context->priv->log, WLOG_ERROR, "WTSVirtualChannelWrite failed!"); error = ERROR_INTERNAL_ERROR; @@ -646,8 +654,6 @@ static UINT rdpgfx_write_surface_command(wLog* log, wStream* s, const RDPGFX_SUR UINT error = CHANNEL_RC_OK; RDPGFX_AVC420_BITMAP_STREAM* havc420 = NULL; RDPGFX_AVC444_BITMAP_STREAM* havc444 = NULL; - UINT32 bitmapDataStart = 0; - UINT32 bitmapDataLength = 0; UINT8 pixelFormat = 0; switch (cmd->format) @@ -692,7 +698,7 @@ static UINT rdpgfx_write_surface_command(wLog* log, wStream* s, const RDPGFX_SUR Stream_Write_UINT16(s, cmd->right); /* right (2 bytes) */ Stream_Write_UINT16(s, cmd->bottom); /* bottom (2 bytes) */ Stream_Write_UINT32(s, cmd->length); /* bitmapDataLength (4 bytes) */ - bitmapDataStart = Stream_GetPosition(s); + const size_t bitmapDataStart = Stream_GetPosition(s); if (cmd->codecId == RDPGFX_CODECID_AVC420) { @@ -743,11 +749,14 @@ static UINT rdpgfx_write_surface_command(wLog* log, wStream* s, const RDPGFX_SUR } /* Fill actual bitmap data length */ - bitmapDataLength = Stream_GetPosition(s) - bitmapDataStart; + const size_t bitmapDataLength = Stream_GetPosition(s) - bitmapDataStart; + if (bitmapDataLength > UINT32_MAX) + return ERROR_INTERNAL_ERROR; + Stream_SetPosition(s, bitmapDataStart - sizeof(UINT32)); if (!Stream_EnsureRemainingCapacity(s, 4)) return ERROR_INTERNAL_ERROR; - Stream_Write_UINT32(s, bitmapDataLength); /* bitmapDataLength (4 bytes) */ + Stream_Write_UINT32(s, (UINT32)bitmapDataLength); /* bitmapDataLength (4 bytes) */ if (!Stream_SafeSeek(s, bitmapDataLength)) return ERROR_INTERNAL_ERROR; } @@ -809,8 +818,6 @@ static UINT rdpgfx_send_surface_frame_command(RdpgfxServerContext* context, if (!checkCapsAreExchanged(context)) return CHANNEL_RC_NOT_INITIALIZED; UINT error = CHANNEL_RC_OK; - wStream* s = NULL; - UINT32 position = 0; UINT32 size = rdpgfx_pdu_length(rdpgfx_estimate_surface_command(cmd)); if (startFrame) @@ -823,7 +830,7 @@ static UINT rdpgfx_send_surface_frame_command(RdpgfxServerContext* context, size += rdpgfx_pdu_length(RDPGFX_END_FRAME_PDU_SIZE); } - s = Stream_New(NULL, size); + wStream* s = Stream_New(NULL, size); if (!s) { @@ -834,7 +841,7 @@ static UINT rdpgfx_send_surface_frame_command(RdpgfxServerContext* context, /* Write start frame if exists */ if (startFrame) { - position = Stream_GetPosition(s); + const size_t position = Stream_GetPosition(s); error = rdpgfx_server_packet_init_header(s, RDPGFX_CMDID_STARTFRAME, 0); if (error != CHANNEL_RC_OK) @@ -850,7 +857,7 @@ static UINT rdpgfx_send_surface_frame_command(RdpgfxServerContext* context, } /* Write RDPGFX_CMDID_WIRETOSURFACE_1 or RDPGFX_CMDID_WIRETOSURFACE_2 */ - position = Stream_GetPosition(s); + const size_t pos = Stream_GetPosition(s); error = rdpgfx_server_packet_init_header(s, rdpgfx_surface_command_cmdid(cmd), 0); // Actual length will be filled later @@ -869,13 +876,13 @@ static UINT rdpgfx_send_surface_frame_command(RdpgfxServerContext* context, goto error; } - if (!rdpgfx_server_packet_complete_header(s, position)) + if (!rdpgfx_server_packet_complete_header(s, pos)) goto error; /* Write end frame if exists */ if (endFrame) { - position = Stream_GetPosition(s); + const size_t position = Stream_GetPosition(s); error = rdpgfx_server_packet_init_header(s, RDPGFX_CMDID_ENDFRAME, 0); if (error != CHANNEL_RC_OK) @@ -1836,8 +1843,11 @@ UINT rdpgfx_server_handle_messages(RdpgfxServerContext* context) return CHANNEL_RC_NO_MEMORY; } - if (WTSVirtualChannelRead(priv->rdpgfx_channel, 0, Stream_BufferAs(s, char), - Stream_Capacity(s), &BytesReturned) == FALSE) + const size_t len = Stream_Capacity(s); + if (len > UINT32_MAX) + return ERROR_INTERNAL_ERROR; + if (WTSVirtualChannelRead(priv->rdpgfx_channel, 0, Stream_BufferAs(s, char), (UINT32)len, + &BytesReturned) == FALSE) { WLog_Print(context->priv->log, WLOG_ERROR, "WTSVirtualChannelRead failed!"); return ERROR_INTERNAL_ERROR; diff --git a/channels/rdpsnd/client/pulse/rdpsnd_pulse.c b/channels/rdpsnd/client/pulse/rdpsnd_pulse.c index e61d295a9..ff353a6e1 100644 --- a/channels/rdpsnd/client/pulse/rdpsnd_pulse.c +++ b/channels/rdpsnd/client/pulse/rdpsnd_pulse.c @@ -396,8 +396,9 @@ static BOOL rdpsnd_pulse_open_stream(rdpsndDevicePlugin* device) if (pulse->latency > 0) { + const size_t val = pa_usec_to_bytes(1000ULL * pulse->latency, &pulse->sample_spec); buffer_attr.maxlength = UINT32_MAX; - buffer_attr.tlength = pa_usec_to_bytes(1000ULL * pulse->latency, &pulse->sample_spec); + buffer_attr.tlength = (val > UINT32_MAX) ? UINT32_MAX : (UINT32)val; buffer_attr.prebuf = UINT32_MAX; buffer_attr.minreq = UINT32_MAX; buffer_attr.fragsize = UINT32_MAX; @@ -643,7 +644,11 @@ static UINT rdpsnd_pulse_play(rdpsndDevicePlugin* device, const BYTE* data, size latency = 0; pa_threaded_mainloop_unlock(pulse->mainloop); - return latency / 1000; + + const pa_usec_t val = latency / 1000; + if (val > UINT32_MAX) + return UINT32_MAX; + return (UINT32)val; } static UINT rdpsnd_pulse_parse_addin_args(rdpsndDevicePlugin* device, const ADDIN_ARGV* args) diff --git a/channels/rdpsnd/client/rdpsnd_main.c b/channels/rdpsnd/client/rdpsnd_main.c index 7b9127a9b..df16616ce 100644 --- a/channels/rdpsnd/client/rdpsnd_main.c +++ b/channels/rdpsnd/client/rdpsnd_main.c @@ -953,7 +953,7 @@ static UINT rdpsnd_process_addin_args(rdpsndPlugin* rdpsnd, const ADDIN_ARGV* ar if ((errno != 0) || (val > UINT32_MAX)) return CHANNEL_RC_INITIALIZATION_ERROR; - rdpsnd->fixed_format->nSamplesPerSec = val; + rdpsnd->fixed_format->nSamplesPerSec = (UINT32)val; } CommandLineSwitchCase(arg, "channel") { @@ -968,10 +968,10 @@ static UINT rdpsnd_process_addin_args(rdpsndPlugin* rdpsnd, const ADDIN_ARGV* ar { unsigned long val = strtoul(arg->Value, NULL, 0); - if ((errno != 0) || (val > INT32_MAX)) + if ((errno != 0) || (val > UINT32_MAX)) return CHANNEL_RC_INITIALIZATION_ERROR; - rdpsnd->latency = val; + rdpsnd->latency = (UINT32)val; } CommandLineSwitchCase(arg, "quality") { diff --git a/channels/rdpsnd/server/rdpsnd_main.c b/channels/rdpsnd/server/rdpsnd_main.c index 32e560e09..4d49f9050 100644 --- a/channels/rdpsnd/server/rdpsnd_main.c +++ b/channels/rdpsnd/server/rdpsnd_main.c @@ -82,13 +82,18 @@ static UINT rdpsnd_server_send_formats(RdpsndServerContext* context) } const size_t pos = Stream_GetPosition(s); + if (pos > UINT16_MAX) + goto fail; + + WINPR_ASSERT(pos >= 4); Stream_SetPosition(s, 2); - Stream_Write_UINT16(s, pos - 4); + Stream_Write_UINT16(s, (UINT16)(pos - 4)); Stream_SetPosition(s, pos); WINPR_ASSERT(context->priv); + status = WTSVirtualChannelWrite(context->priv->ChannelHandle, Stream_BufferAs(s, char), - Stream_GetPosition(s), &written); + (UINT32)pos, &written); Stream_SetPosition(s, 0); fail: return status ? CHANNEL_RC_OK : ERROR_INTERNAL_ERROR; @@ -429,7 +434,6 @@ out: static UINT rdpsnd_server_training(RdpsndServerContext* context, UINT16 timestamp, UINT16 packsize, BYTE* data) { - size_t end = 0; ULONG written = 0; BOOL status = 0; wStream* s = rdpsnd_server_get_buffer(context); @@ -454,12 +458,15 @@ static UINT rdpsnd_server_training(RdpsndServerContext* context, UINT16 timestam Stream_Write(s, data, packsize); } - end = Stream_GetPosition(s); - Stream_SetPosition(s, 2); - Stream_Write_UINT16(s, end - 4); + const size_t end = Stream_GetPosition(s); + if ((end < 4) || (end > UINT16_MAX)) + return ERROR_INTERNAL_ERROR; - status = WTSVirtualChannelWrite(context->priv->ChannelHandle, Stream_BufferAs(s, char), end, - &written); + Stream_SetPosition(s, 2); + Stream_Write_UINT16(s, (UINT16)(end - 4)); + + status = WTSVirtualChannelWrite(context->priv->ChannelHandle, Stream_BufferAs(s, char), + (UINT32)end, &written); Stream_SetPosition(s, 0); @@ -494,10 +501,6 @@ static BOOL rdpsnd_server_align_wave_pdu(wStream* s, UINT32 alignment) */ static UINT rdpsnd_server_send_wave_pdu(RdpsndServerContext* context, UINT16 wTimestamp) { - size_t length = 0; - size_t start = 0; - size_t end = 0; - const BYTE* src = NULL; AUDIO_FORMAT* format = NULL; ULONG written = 0; UINT error = CHANNEL_RC_OK; @@ -522,29 +525,31 @@ static UINT rdpsnd_server_send_wave_pdu(RdpsndServerContext* context, UINT16 wTi Stream_Write_UINT16(s, context->selected_client_format); /* wFormatNo */ Stream_Write_UINT8(s, context->block_no); /* cBlockNo */ Stream_Seek(s, 3); /* bPad */ - start = Stream_GetPosition(s); - src = context->priv->out_buffer; - length = 1ull * context->priv->out_pending_frames * context->priv->src_bytes_per_frame; + const size_t start = Stream_GetPosition(s); + const BYTE* src = context->priv->out_buffer; + const size_t length = + 1ull * context->priv->out_pending_frames * context->priv->src_bytes_per_frame; if (!freerdp_dsp_encode(context->priv->dsp_context, context->src_format, src, length, s)) return ERROR_INTERNAL_ERROR; - else + + /* Set stream size */ + if (!rdpsnd_server_align_wave_pdu(s, format->nBlockAlign)) + return ERROR_INTERNAL_ERROR; + + const size_t end = Stream_GetPosition(s); + const size_t pos = end - start + 8ULL; + if (pos > UINT16_MAX) + return ERROR_INTERNAL_ERROR; + Stream_SetPosition(s, 2); + Stream_Write_UINT16(s, (UINT16)pos); + Stream_SetPosition(s, end); + + if (!WTSVirtualChannelWrite(context->priv->ChannelHandle, Stream_BufferAs(s, char), + (UINT32)(start + 4), &written)) { - /* Set stream size */ - if (!rdpsnd_server_align_wave_pdu(s, format->nBlockAlign)) - return ERROR_INTERNAL_ERROR; - - end = Stream_GetPosition(s); - Stream_SetPosition(s, 2); - Stream_Write_UINT16(s, end - start + 8); - Stream_SetPosition(s, end); - - if (!WTSVirtualChannelWrite(context->priv->ChannelHandle, Stream_BufferAs(s, char), - start + 4, &written)) - { - WLog_ERR(TAG, "WTSVirtualChannelWrite failed!"); - error = ERROR_INTERNAL_ERROR; - } + WLog_ERR(TAG, "WTSVirtualChannelWrite failed!"); + error = ERROR_INTERNAL_ERROR; } if (error != CHANNEL_RC_OK) @@ -558,8 +563,9 @@ static UINT rdpsnd_server_send_wave_pdu(RdpsndServerContext* context, UINT16 wTi Stream_Write_UINT32(s, 0); /* bPad */ Stream_SetPosition(s, start); - if (!WTSVirtualChannelWrite(context->priv->ChannelHandle, Stream_Pointer(s), end - start, - &written)) + WINPR_ASSERT((end - start) <= UINT32_MAX); + if (!WTSVirtualChannelWrite(context->priv->ChannelHandle, Stream_Pointer(s), + (UINT32)(end - start), &written)) { WLog_ERR(TAG, "WTSVirtualChannelWrite failed!"); error = ERROR_INTERNAL_ERROR; @@ -583,7 +589,6 @@ static UINT rdpsnd_server_send_wave2_pdu(RdpsndServerContext* context, UINT16 fo const BYTE* data, size_t size, BOOL encoded, UINT16 timestamp, UINT32 audioTimeStamp) { - size_t end = 0; ULONG written = 0; UINT error = CHANNEL_RC_OK; BOOL status = 0; @@ -635,16 +640,22 @@ static UINT rdpsnd_server_send_wave2_pdu(RdpsndServerContext* context, UINT16 fo } } - end = Stream_GetPosition(s); - Stream_SetPosition(s, 2); - Stream_Write_UINT16(s, end - 4); + const size_t end = Stream_GetPosition(s); + if (end > UINT16_MAX + 4) + { + error = ERROR_INTERNAL_ERROR; + goto out; + } - status = WTSVirtualChannelWrite(context->priv->ChannelHandle, Stream_BufferAs(s, char), end, - &written); + Stream_SetPosition(s, 2); + Stream_Write_UINT16(s, (UINT16)(end - 4)); + + status = WTSVirtualChannelWrite(context->priv->ChannelHandle, Stream_BufferAs(s, char), + (UINT32)end, &written); if (!status || (end != written)) { - WLog_ERR(TAG, "WTSVirtualChannelWrite failed! [stream length=%" PRIdz " - written=%" PRIu32, + WLog_ERR(TAG, "WTSVirtualChannelWrite failed! [stream length=%" PRIuz " - written=%" PRIu32, end, written); error = ERROR_INTERNAL_ERROR; } @@ -763,7 +774,6 @@ static UINT rdpsnd_server_send_samples2(RdpsndServerContext* context, UINT16 for */ static UINT rdpsnd_server_set_volume(RdpsndServerContext* context, UINT16 left, UINT16 right) { - size_t len = 0; BOOL status = 0; ULONG written = 0; wStream* s = rdpsnd_server_get_buffer(context); @@ -776,8 +786,9 @@ static UINT rdpsnd_server_set_volume(RdpsndServerContext* context, UINT16 left, Stream_Write_UINT16(s, 4); /* Payload length */ Stream_Write_UINT16(s, left); Stream_Write_UINT16(s, right); - len = Stream_GetPosition(s); + const size_t len = Stream_GetPosition(s); + WINPR_ASSERT(len <= UINT32_MAX); status = WTSVirtualChannelWrite(context->priv->ChannelHandle, Stream_BufferAs(s, char), (ULONG)len, &written); Stream_SetPosition(s, 0); @@ -829,8 +840,11 @@ static UINT rdpsnd_server_close(RdpsndServerContext* context) Stream_SetPosition(s, 2); Stream_Write_UINT16(s, pos - 4); Stream_SetPosition(s, pos); + + const size_t len = Stream_GetPosition(s); + WINPR_ASSERT(len <= UINT32_MAX); status = WTSVirtualChannelWrite(context->priv->ChannelHandle, Stream_BufferAs(s, char), - Stream_GetPosition(s), &written); + (UINT32)len, &written); Stream_SetPosition(s, 0); return status ? CHANNEL_RC_OK : ERROR_INTERNAL_ERROR; } diff --git a/channels/remdesk/client/remdesk_main.c b/channels/remdesk/client/remdesk_main.c index 837f69dcc..255bdaefe 100644 --- a/channels/remdesk/client/remdesk_main.c +++ b/channels/remdesk/client/remdesk_main.c @@ -174,7 +174,6 @@ static UINT remdesk_read_channel_header(wStream* s, REMDESK_CHANNEL_HEADER* head */ static UINT remdesk_write_channel_header(wStream* s, REMDESK_CHANNEL_HEADER* header) { - UINT32 ChannelNameLen = 0; WCHAR ChannelNameW[32] = { 0 }; WINPR_ASSERT(s); @@ -185,8 +184,11 @@ static UINT remdesk_write_channel_header(wStream* s, REMDESK_CHANNEL_HEADER* hea ChannelNameW[index] = (WCHAR)header->ChannelName[index]; } - ChannelNameLen = (strnlen(header->ChannelName, sizeof(header->ChannelName)) + 1) * 2; - Stream_Write_UINT32(s, ChannelNameLen); /* ChannelNameLen (4 bytes) */ + const size_t ChannelNameLen = + (strnlen(header->ChannelName, sizeof(header->ChannelName)) + 1) * 2; + WINPR_ASSERT(ChannelNameLen <= ARRAYSIZE(header->ChannelName)); + + Stream_Write_UINT32(s, (UINT32)ChannelNameLen); /* ChannelNameLen (4 bytes) */ Stream_Write_UINT32(s, header->DataLength); /* DataLen (4 bytes) */ Stream_Write(s, ChannelNameW, ChannelNameLen); /* ChannelName (variable) */ return CHANNEL_RC_OK; @@ -202,7 +204,9 @@ static UINT remdesk_write_ctl_header(wStream* s, REMDESK_CTL_HEADER* ctlHeader) WINPR_ASSERT(s); WINPR_ASSERT(ctlHeader); - remdesk_write_channel_header(s, &ctlHeader->ch); + const UINT error = remdesk_write_channel_header(s, &ctlHeader->ch); + if (error) + return error; Stream_Write_UINT32(s, ctlHeader->msgType); /* msgType (4 bytes) */ return CHANNEL_RC_OK; } @@ -213,14 +217,17 @@ static UINT remdesk_write_ctl_header(wStream* s, REMDESK_CTL_HEADER* ctlHeader) * @return 0 on success, otherwise a Win32 error code */ static UINT remdesk_prepare_ctl_header(REMDESK_CTL_HEADER* ctlHeader, UINT32 msgType, - UINT32 msgSize) + size_t msgSize) { WINPR_ASSERT(ctlHeader); + if (msgSize > UINT32_MAX - 4) + return ERROR_INVALID_PARAMETER; + ctlHeader->msgType = msgType; (void)sprintf_s(ctlHeader->ch.ChannelName, ARRAYSIZE(ctlHeader->ch.ChannelName), REMDESK_CHANNEL_CTL_NAME); - ctlHeader->ch.DataLength = 4 + msgSize; + ctlHeader->ch.DataLength = (UINT32)(4UL + msgSize); return CHANNEL_RC_OK; } @@ -277,16 +284,17 @@ static UINT remdesk_recv_ctl_version_info_pdu(remdeskPlugin* remdesk, wStream* s */ static UINT remdesk_send_ctl_version_info_pdu(remdeskPlugin* remdesk) { - wStream* s = NULL; - REMDESK_CTL_VERSION_INFO_PDU pdu; - UINT error = 0; + REMDESK_CTL_VERSION_INFO_PDU pdu = { 0 }; WINPR_ASSERT(remdesk); - remdesk_prepare_ctl_header(&(pdu.ctlHeader), REMDESK_CTL_VERSIONINFO, 8); + UINT error = remdesk_prepare_ctl_header(&(pdu.ctlHeader), REMDESK_CTL_VERSIONINFO, 8); + if (error) + return error; + pdu.versionMajor = 1; pdu.versionMinor = 2; - s = Stream_New(NULL, REMDESK_CHANNEL_CTL_SIZE + pdu.ctlHeader.ch.DataLength); + wStream* s = Stream_New(NULL, REMDESK_CHANNEL_CTL_SIZE + pdu.ctlHeader.ch.DataLength); if (!s) { @@ -294,7 +302,12 @@ static UINT remdesk_send_ctl_version_info_pdu(remdeskPlugin* remdesk) return CHANNEL_RC_NO_MEMORY; } - remdesk_write_ctl_header(s, &(pdu.ctlHeader)); + error = remdesk_write_ctl_header(s, &(pdu.ctlHeader)); + if (error) + { + Stream_Free(s, TRUE); + return error; + } Stream_Write_UINT32(s, pdu.versionMajor); /* versionMajor (4 bytes) */ Stream_Write_UINT32(s, pdu.versionMinor); /* versionMinor (4 bytes) */ Stream_SealLength(s); @@ -347,7 +360,6 @@ static UINT remdesk_recv_ctl_result_pdu(remdeskPlugin* remdesk, wStream* s, static UINT remdesk_send_ctl_authenticate_pdu(remdeskPlugin* remdesk) { UINT error = ERROR_INTERNAL_ERROR; - wStream* s = NULL; size_t cbExpertBlobW = 0; WCHAR* expertBlobW = NULL; size_t cbRaConnectionStringW = 0; @@ -378,13 +390,16 @@ static UINT remdesk_send_ctl_authenticate_pdu(remdeskPlugin* remdesk) expertBlobW = ConvertUtf8ToWCharAlloc(expertBlob, &cbExpertBlobW); - if (!expertBlobW || (cbExpertBlobW > UINT32_MAX / sizeof(WCHAR))) + if (!expertBlobW) goto out; cbExpertBlobW = cbExpertBlobW * sizeof(WCHAR); - remdesk_prepare_ctl_header(&(ctlHeader), REMDESK_CTL_AUTHENTICATE, - cbRaConnectionStringW + cbExpertBlobW); - s = Stream_New(NULL, REMDESK_CHANNEL_CTL_SIZE + ctlHeader.ch.DataLength); + error = remdesk_prepare_ctl_header(&(ctlHeader), REMDESK_CTL_AUTHENTICATE, + cbRaConnectionStringW + cbExpertBlobW); + if (error) + goto out; + + wStream* s = Stream_New(NULL, REMDESK_CHANNEL_CTL_SIZE + ctlHeader.ch.DataLength); if (!s) { @@ -393,12 +408,18 @@ static UINT remdesk_send_ctl_authenticate_pdu(remdeskPlugin* remdesk) goto out; } - remdesk_write_ctl_header(s, &(ctlHeader)); + error = remdesk_write_ctl_header(s, &ctlHeader); + if (error) + { + Stream_Free(s, TRUE); + goto out; + } Stream_Write(s, raConnectionStringW, cbRaConnectionStringW); Stream_Write(s, expertBlobW, cbExpertBlobW); Stream_SealLength(s); - if ((error = remdesk_virtual_channel_write(remdesk, s))) + error = remdesk_virtual_channel_write(remdesk, s); + if (error) WLog_ERR(TAG, "remdesk_virtual_channel_write failed with error %" PRIu32 "!", error); out: @@ -432,8 +453,11 @@ static UINT remdesk_send_ctl_remote_control_desktop_pdu(remdeskPlugin* remdesk) return ERROR_INTERNAL_ERROR; REMDESK_CTL_HEADER ctlHeader = { 0 }; - remdesk_prepare_ctl_header(&ctlHeader, REMDESK_CTL_REMOTE_CONTROL_DESKTOP, - cbRaConnectionStringW); + error = remdesk_prepare_ctl_header(&ctlHeader, REMDESK_CTL_REMOTE_CONTROL_DESKTOP, + cbRaConnectionStringW); + if (error != CHANNEL_RC_OK) + goto out; + wStream* s = Stream_New(NULL, REMDESK_CHANNEL_CTL_SIZE + ctlHeader.ch.DataLength); if (!s) @@ -443,7 +467,12 @@ static UINT remdesk_send_ctl_remote_control_desktop_pdu(remdeskPlugin* remdesk) goto out; } - remdesk_write_ctl_header(s, &ctlHeader); + error = remdesk_write_ctl_header(s, &ctlHeader); + if (error) + { + Stream_Free(s, TRUE); + goto out; + } Stream_Write(s, raConnectionStringW, cbRaConnectionStringW); Stream_SealLength(s); @@ -463,29 +492,31 @@ out: */ static UINT remdesk_send_ctl_verify_password_pdu(remdeskPlugin* remdesk) { - UINT error = ERROR_INTERNAL_ERROR; - wStream* s = NULL; size_t cbExpertBlobW = 0; - WCHAR* expertBlobW = NULL; REMDESK_CTL_VERIFY_PASSWORD_PDU pdu = { 0 }; WINPR_ASSERT(remdesk); - if ((error = remdesk_generate_expert_blob(remdesk))) + UINT error = remdesk_generate_expert_blob(remdesk); + if (error) { WLog_ERR(TAG, "remdesk_generate_expert_blob failed with error %" PRIu32 "!", error); return error; } pdu.expertBlob = remdesk->ExpertBlob; - expertBlobW = ConvertUtf8ToWCharAlloc(pdu.expertBlob, &cbExpertBlobW); + WCHAR* expertBlobW = ConvertUtf8ToWCharAlloc(pdu.expertBlob, &cbExpertBlobW); - if (!expertBlobW || (cbExpertBlobW > UINT32_MAX / sizeof(WCHAR))) + if (!expertBlobW) goto out; cbExpertBlobW = cbExpertBlobW * sizeof(WCHAR); - remdesk_prepare_ctl_header(&(pdu.ctlHeader), REMDESK_CTL_VERIFY_PASSWORD, cbExpertBlobW); - s = Stream_New(NULL, REMDESK_CHANNEL_CTL_SIZE + pdu.ctlHeader.ch.DataLength); + error = + remdesk_prepare_ctl_header(&(pdu.ctlHeader), REMDESK_CTL_VERIFY_PASSWORD, cbExpertBlobW); + if (error) + goto out; + + wStream* s = Stream_New(NULL, 1ULL * REMDESK_CHANNEL_CTL_SIZE + pdu.ctlHeader.ch.DataLength); if (!s) { @@ -494,11 +525,17 @@ static UINT remdesk_send_ctl_verify_password_pdu(remdeskPlugin* remdesk) goto out; } - remdesk_write_ctl_header(s, &(pdu.ctlHeader)); - Stream_Write(s, (BYTE*)expertBlobW, cbExpertBlobW); + error = remdesk_write_ctl_header(s, &(pdu.ctlHeader)); + if (error) + { + Stream_Free(s, TRUE); + goto out; + } + Stream_Write(s, expertBlobW, cbExpertBlobW); Stream_SealLength(s); - if ((error = remdesk_virtual_channel_write(remdesk, s))) + error = remdesk_virtual_channel_write(remdesk, s); + if (error) WLog_ERR(TAG, "remdesk_virtual_channel_write failed with error %" PRIu32 "!", error); out: @@ -514,23 +551,27 @@ out: */ static UINT remdesk_send_ctl_expert_on_vista_pdu(remdeskPlugin* remdesk) { - UINT error = 0; - wStream* s = NULL; - REMDESK_CTL_EXPERT_ON_VISTA_PDU pdu; + REMDESK_CTL_EXPERT_ON_VISTA_PDU pdu = { 0 }; WINPR_ASSERT(remdesk); - if ((error = remdesk_generate_expert_blob(remdesk))) + UINT error = remdesk_generate_expert_blob(remdesk); + if (error) { WLog_ERR(TAG, "remdesk_generate_expert_blob failed with error %" PRIu32 "!", error); return error; } + if (remdesk->EncryptedPassStubSize > UINT32_MAX) + return ERROR_INTERNAL_ERROR; - pdu.EncryptedPasswordLength = remdesk->EncryptedPassStubSize; + pdu.EncryptedPasswordLength = (UINT32)remdesk->EncryptedPassStubSize; pdu.EncryptedPassword = remdesk->EncryptedPassStub; - remdesk_prepare_ctl_header(&(pdu.ctlHeader), REMDESK_CTL_EXPERT_ON_VISTA, - pdu.EncryptedPasswordLength); - s = Stream_New(NULL, REMDESK_CHANNEL_CTL_SIZE + pdu.ctlHeader.ch.DataLength); + error = remdesk_prepare_ctl_header(&(pdu.ctlHeader), REMDESK_CTL_EXPERT_ON_VISTA, + pdu.EncryptedPasswordLength); + if (error) + return error; + + wStream* s = Stream_New(NULL, REMDESK_CHANNEL_CTL_SIZE + pdu.ctlHeader.ch.DataLength); if (!s) { @@ -538,7 +579,12 @@ static UINT remdesk_send_ctl_expert_on_vista_pdu(remdeskPlugin* remdesk) return CHANNEL_RC_NO_MEMORY; } - remdesk_write_ctl_header(s, &(pdu.ctlHeader)); + error = remdesk_write_ctl_header(s, &(pdu.ctlHeader)); + if (error) + { + Stream_Free(s, TRUE); + return error; + } Stream_Write(s, pdu.EncryptedPassword, pdu.EncryptedPasswordLength); Stream_SealLength(s); return remdesk_virtual_channel_write(remdesk, s); diff --git a/channels/remdesk/server/remdesk_main.c b/channels/remdesk/server/remdesk_main.c index ce7ec162d..ad2a968a3 100644 --- a/channels/remdesk/server/remdesk_main.c +++ b/channels/remdesk/server/remdesk_main.c @@ -36,10 +36,11 @@ */ static UINT remdesk_virtual_channel_write(RemdeskServerContext* context, wStream* s) { - BOOL status = 0; + const size_t len = Stream_Length(s); + WINPR_ASSERT(len <= UINT32_MAX); ULONG BytesWritten = 0; - status = WTSVirtualChannelWrite(context->priv->ChannelHandle, Stream_BufferAs(s, char), - Stream_Length(s), &BytesWritten); + BOOL status = WTSVirtualChannelWrite(context->priv->ChannelHandle, Stream_BufferAs(s, char), + (UINT32)len, &BytesWritten); return (status) ? CHANNEL_RC_OK : ERROR_INTERNAL_ERROR; } @@ -85,7 +86,6 @@ static UINT remdesk_read_channel_header(wStream* s, REMDESK_CHANNEL_HEADER* head */ static UINT remdesk_write_channel_header(wStream* s, REMDESK_CHANNEL_HEADER* header) { - UINT32 ChannelNameLen = 0; WCHAR ChannelNameW[32] = { 0 }; for (size_t index = 0; index < 32; index++) @@ -93,8 +93,10 @@ static UINT remdesk_write_channel_header(wStream* s, REMDESK_CHANNEL_HEADER* hea ChannelNameW[index] = (WCHAR)header->ChannelName[index]; } - ChannelNameLen = (strnlen(header->ChannelName, sizeof(header->ChannelName)) + 1) * 2; - Stream_Write_UINT32(s, ChannelNameLen); /* ChannelNameLen (4 bytes) */ + const size_t ChannelNameLen = + (strnlen(header->ChannelName, sizeof(header->ChannelName)) + 1ULL) * sizeof(WCHAR); + WINPR_ASSERT(ChannelNameLen <= UINT32_MAX); + Stream_Write_UINT32(s, (UINT32)ChannelNameLen); /* ChannelNameLen (4 bytes) */ Stream_Write_UINT32(s, header->DataLength); /* DataLen (4 bytes) */ Stream_Write(s, ChannelNameW, ChannelNameLen); /* ChannelName (variable) */ return CHANNEL_RC_OK; @@ -595,8 +597,14 @@ static DWORD WINAPI remdesk_server_thread(LPVOID arg) break; } + const size_t len = Stream_Capacity(s); + if (len > UINT32_MAX) + { + error = ERROR_INTERNAL_ERROR; + break; + } if (WTSVirtualChannelRead(context->priv->ChannelHandle, 0, Stream_BufferAs(s, char), - Stream_Capacity(s), &BytesReturned)) + (UINT32)len, &BytesReturned)) { if (BytesReturned) Stream_Seek(s, BytesReturned); diff --git a/channels/urbdrc/client/urbdrc_main.c b/channels/urbdrc/client/urbdrc_main.c index 7f3d54354..1dbac1e84 100644 --- a/channels/urbdrc/client/urbdrc_main.c +++ b/channels/urbdrc/client/urbdrc_main.c @@ -311,8 +311,11 @@ static UINT urdbrc_send_usb_device_add(GENERIC_CHANNEL_CALLBACK* callback, IUDEV TRUE) < 0) goto fail; Stream_Write_UINT16(out, 0); - Stream_Write_UINT32(out, HardwareIdsLen[0] + HardwareIdsLen[1] + 3); /* cchHwIds */ - /* HardwareIds 1 */ + const size_t len = HardwareIdsLen[0] + HardwareIdsLen[1] + 3; + if (len > UINT32_MAX) + goto fail; + Stream_Write_UINT32(out, (UINT32)len); /* cchHwIds */ + /* HardwareIds 1 */ if (Stream_Write_UTF16_String_From_UTF8(out, HardwareIdsLen[0], HardwareIds[0], HardwareIdsLen[0], TRUE) < 0) goto fail; @@ -1000,7 +1003,6 @@ fail: UINT stream_write_and_free(IWTSPlugin* plugin, IWTSVirtualChannel* channel, wStream* out) { - UINT rc = 0; URBDRC_PLUGIN* urbdrc = (URBDRC_PLUGIN*)plugin; if (!out) @@ -1019,7 +1021,10 @@ UINT stream_write_and_free(IWTSPlugin* plugin, IWTSVirtualChannel* channel, wStr } urbdrc_dump_message(urbdrc->log, TRUE, TRUE, out); - rc = channel->Write(channel, Stream_GetPosition(out), Stream_Buffer(out), NULL); + const size_t len = Stream_GetPosition(out); + UINT rc = ERROR_INTERNAL_ERROR; + if (len <= UINT32_MAX) + rc = channel->Write(channel, (UINT32)len, Stream_Buffer(out), NULL); Stream_Free(out, TRUE); return rc; } diff --git a/channels/video/client/video_main.c b/channels/video/client/video_main.c index a8399a425..390f1723a 100644 --- a/channels/video/client/video_main.c +++ b/channels/video/client/video_main.c @@ -860,11 +860,15 @@ static UINT video_VideoData(VideoClientContext* context, const TSMM_VIDEO_DATA* { int dropped = 0; + const size_t len = Stream_Length(presentation->currentSample); + if (len > UINT32_MAX) + return CHANNEL_RC_OK; + /* if the frame is to be published in less than 10 ms, let's consider it's now */ - status = avc420_decompress(h264, Stream_Pointer(presentation->currentSample), - Stream_Length(presentation->currentSample), surface->data, - surface->format, surface->scanline, surface->alignedWidth, - surface->alignedHeight, &rect, 1); + status = + avc420_decompress(h264, Stream_Pointer(presentation->currentSample), (UINT32)len, + surface->data, surface->format, surface->scanline, + surface->alignedWidth, surface->alignedHeight, &rect, 1); if (status < 0) return CHANNEL_RC_OK; @@ -894,6 +898,10 @@ static UINT video_VideoData(VideoClientContext* context, const TSMM_VIDEO_DATA* } else { + const size_t len = Stream_Length(presentation->currentSample); + if (len > UINT32_MAX) + return CHANNEL_RC_OK; + BOOL enqueueResult = 0; VideoFrame* frame = VideoFrame_new(priv, presentation, geom); if (!frame) @@ -902,10 +910,10 @@ static UINT video_VideoData(VideoClientContext* context, const TSMM_VIDEO_DATA* return CHANNEL_RC_NO_MEMORY; } - status = avc420_decompress(h264, Stream_Pointer(presentation->currentSample), - Stream_Length(presentation->currentSample), - frame->surfaceData, surface->format, surface->scanline, - surface->alignedWidth, surface->alignedHeight, &rect, 1); + status = + avc420_decompress(h264, Stream_Pointer(presentation->currentSample), (UINT32)len, + frame->surfaceData, surface->format, surface->scanline, + surface->alignedWidth, surface->alignedHeight, &rect, 1); if (status < 0) { VideoFrame_free(&frame); diff --git a/client/SDL/SDL2/dialogs/sdl_connection_dialog.cpp b/client/SDL/SDL2/dialogs/sdl_connection_dialog.cpp index bb676c4d7..bc8964e60 100644 --- a/client/SDL/SDL2/dialogs/sdl_connection_dialog.cpp +++ b/client/SDL/SDL2/dialogs/sdl_connection_dialog.cpp @@ -327,9 +327,9 @@ bool SDLConnectionDialog::createWindow() { destroyWindow(); - const size_t widget_height = 50; - const size_t widget_width = 600; - const size_t total_height = 300; + const int widget_height = 50; + const int widget_width = 600; + const int total_height = 300; auto flags = SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_MOUSE_FOCUS | SDL_WINDOW_INPUT_FOCUS; auto rc = SDL_CreateWindowAndRenderer(widget_width, total_height, flags, &_window, &_renderer); diff --git a/client/SDL/SDL2/dialogs/sdl_input_widgets.cpp b/client/SDL/SDL2/dialogs/sdl_input_widgets.cpp index 72def7466..0b837367d 100644 --- a/client/SDL/SDL2/dialogs/sdl_input_widgets.cpp +++ b/client/SDL/SDL2/dialogs/sdl_input_widgets.cpp @@ -1,5 +1,6 @@ #include #include +#include #include "sdl_input_widgets.hpp" @@ -23,8 +24,12 @@ SdlInputWidgetList::SdlInputWidgetList(const std::string& title, const size_t input_height = labels.size() * (widget_heigth + vpadding) + vpadding; const size_t total_height = input_height + widget_heigth; + assert(total_width <= INT32_MAX); + assert(total_height <= INT32_MAX); auto wflags = SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_MOUSE_FOCUS | SDL_WINDOW_INPUT_FOCUS; - auto rc = SDL_CreateWindowAndRenderer(total_width, total_height, wflags, &_window, &_renderer); + auto rc = + SDL_CreateWindowAndRenderer(static_cast(total_width), static_cast(total_height), + wflags, &_window, &_renderer); if (rc != 0) widget_log_error(rc, "SDL_CreateWindowAndRenderer"); else diff --git a/client/SDL/SDL2/dialogs/sdl_selectlist.cpp b/client/SDL/SDL2/dialogs/sdl_selectlist.cpp index 0263694a1..fdc069c70 100644 --- a/client/SDL/SDL2/dialogs/sdl_selectlist.cpp +++ b/client/SDL/SDL2/dialogs/sdl_selectlist.cpp @@ -1,3 +1,4 @@ +#include #include "sdl_selectlist.hpp" static const Uint32 vpadding = 5; @@ -9,9 +10,13 @@ SdlSelectList::SdlSelectList(const std::string& title, const std::vector(widget_width), static_cast(height), + flags, &_window, &_renderer); if (rc != 0) widget_log_error(rc, "SDL_CreateWindowAndRenderer"); else @@ -89,7 +94,7 @@ int SdlSelectList::run() case SDLK_RETURN2: case SDLK_KP_ENTER: running = false; - res = CurrentActiveTextInput; + res = static_cast(CurrentActiveTextInput); break; case SDLK_ESCAPE: running = false; @@ -122,7 +127,7 @@ int SdlSelectList::run() if (button->id() == INPUT_BUTTON_CANCEL) res = INPUT_BUTTON_CANCEL; else - res = CurrentActiveTextInput; + res = static_cast(CurrentActiveTextInput); } else { diff --git a/client/SDL/SDL2/dialogs/sdl_widget.cpp b/client/SDL/SDL2/dialogs/sdl_widget.cpp index e85cf5dc7..b80eedc69 100644 --- a/client/SDL/SDL2/dialogs/sdl_widget.cpp +++ b/client/SDL/SDL2/dialogs/sdl_widget.cpp @@ -133,7 +133,10 @@ SDL_Texture* SdlWidget::render_text_wrapped(SDL_Renderer* renderer, const std::s Sint32 w = 0; Sint32 h = 0; TTF_SizeUTF8(_font, " ", &w, &h); - auto surface = TTF_RenderUTF8_Blended_Wrapped(_font, text.c_str(), fgcolor, _text_width); + + assert(_text_width <= UINT32_MAX); + auto surface = TTF_RenderUTF8_Blended_Wrapped(_font, text.c_str(), fgcolor, + static_cast(_text_width)); if (!surface) { widget_log_error(-1, "TTF_RenderText_Blended"); diff --git a/client/SDL/SDL2/sdl_disp.cpp b/client/SDL/SDL2/sdl_disp.cpp index 4599677ac..3f2e00449 100644 --- a/client/SDL/SDL2/sdl_disp.cpp +++ b/client/SDL/SDL2/sdl_disp.cpp @@ -291,7 +291,9 @@ UINT sdlDispContext::sendLayout(const rdpMonitor* monitors, size_t nmonitors) } WINPR_ASSERT(_disp); - ret = IFCALLRESULT(CHANNEL_RC_OK, _disp->SendMonitorLayout, _disp, layouts.size(), + const size_t len = layouts.size(); + WINPR_ASSERT(len <= UINT32_MAX); + ret = IFCALLRESULT(CHANNEL_RC_OK, _disp->SendMonitorLayout, _disp, static_cast(len), layouts.data()); return ret; } diff --git a/client/SDL/SDL2/sdl_freerdp.cpp b/client/SDL/SDL2/sdl_freerdp.cpp index 31907e194..55fbcb860 100644 --- a/client/SDL/SDL2/sdl_freerdp.cpp +++ b/client/SDL/SDL2/sdl_freerdp.cpp @@ -725,8 +725,8 @@ static BOOL sdl_create_windows(SdlContext* sdl) } Uint32 flags = SDL_WINDOW_SHOWN; - Uint32 startupX = SDL_WINDOWPOS_CENTERED_DISPLAY(id); - Uint32 startupY = SDL_WINDOWPOS_CENTERED_DISPLAY(id); + auto startupX = SDL_WINDOWPOS_CENTERED_DISPLAY(id); + auto startupY = SDL_WINDOWPOS_CENTERED_DISPLAY(id); if (monitor->attributes.desktopScaleFactor > 100) { diff --git a/client/SDL/SDL3/dialogs/sdl_connection_dialog.cpp b/client/SDL/SDL3/dialogs/sdl_connection_dialog.cpp index b0b4f8ba1..b7c486b89 100644 --- a/client/SDL/SDL3/dialogs/sdl_connection_dialog.cpp +++ b/client/SDL/SDL3/dialogs/sdl_connection_dialog.cpp @@ -324,9 +324,9 @@ bool SDLConnectionDialog::createWindow() { destroyWindow(); - const size_t widget_height = 50; - const size_t widget_width = 600; - const size_t total_height = 300; + const int widget_height = 50; + const int widget_width = 600; + const int total_height = 300; auto rc = SDL_CreateWindowAndRenderer(_title.c_str(), widget_width, total_height, SDL_WINDOW_HIGH_PIXEL_DENSITY | SDL_WINDOW_MOUSE_FOCUS | diff --git a/client/SDL/SDL3/dialogs/sdl_input_widgets.cpp b/client/SDL/SDL3/dialogs/sdl_input_widgets.cpp index 4c1818c29..3d58b92da 100644 --- a/client/SDL/SDL3/dialogs/sdl_input_widgets.cpp +++ b/client/SDL/SDL3/dialogs/sdl_input_widgets.cpp @@ -22,10 +22,12 @@ SdlInputWidgetList::SdlInputWidgetList(const std::string& title, const size_t total_width = widget_width + widget_width; const size_t input_height = labels.size() * (widget_heigth + vpadding) + vpadding; const size_t total_height = input_height + widget_heigth; - auto rc = SDL_CreateWindowAndRenderer(title.c_str(), total_width, total_height, - SDL_WINDOW_HIGH_PIXEL_DENSITY | SDL_WINDOW_MOUSE_FOCUS | - SDL_WINDOW_INPUT_FOCUS, - &_window, &_renderer); + assert(total_width <= INT32_MAX); + assert(total_height <= INT32_MAX); + auto rc = SDL_CreateWindowAndRenderer( + title.c_str(), total_width, static_cast(total_height), + SDL_WINDOW_HIGH_PIXEL_DENSITY | SDL_WINDOW_MOUSE_FOCUS | SDL_WINDOW_INPUT_FOCUS, &_window, + &_renderer); if (rc != 0) widget_log_error(rc, "SDL_CreateWindowAndRenderer"); else diff --git a/client/SDL/SDL3/dialogs/sdl_selectlist.cpp b/client/SDL/SDL3/dialogs/sdl_selectlist.cpp index 3b209834a..008c5a214 100644 --- a/client/SDL/SDL3/dialogs/sdl_selectlist.cpp +++ b/client/SDL/SDL3/dialogs/sdl_selectlist.cpp @@ -1,3 +1,4 @@ +#include #include "sdl_selectlist.hpp" static const Uint32 vpadding = 5; @@ -9,10 +10,13 @@ SdlSelectList::SdlSelectList(const std::string& title, const std::vector(widget_width), static_cast(height), + SDL_WINDOW_HIGH_PIXEL_DENSITY | SDL_WINDOW_MOUSE_FOCUS | SDL_WINDOW_INPUT_FOCUS, &_window, + &_renderer); if (rc != 0) widget_log_error(rc, "SDL_CreateWindowAndRenderer"); else @@ -88,7 +92,7 @@ int SdlSelectList::run() case SDLK_RETURN2: case SDLK_KP_ENTER: running = false; - res = CurrentActiveTextInput; + res = static_cast(CurrentActiveTextInput); break; case SDLK_ESCAPE: running = false; @@ -121,7 +125,7 @@ int SdlSelectList::run() if (button->id() == INPUT_BUTTON_CANCEL) res = INPUT_BUTTON_CANCEL; else - res = CurrentActiveTextInput; + res = static_cast(CurrentActiveTextInput); } else { diff --git a/client/SDL/SDL3/dialogs/sdl_widget.cpp b/client/SDL/SDL3/dialogs/sdl_widget.cpp index 6684055a9..14e9c8932 100644 --- a/client/SDL/SDL3/dialogs/sdl_widget.cpp +++ b/client/SDL/SDL3/dialogs/sdl_widget.cpp @@ -153,15 +153,18 @@ static float scale(float dw, float dh) SDL_Texture* SdlWidget::render_text_wrapped(SDL_Renderer* renderer, const std::string& text, SDL_Color fgcolor, SDL_FRect& src, SDL_FRect& dst) { - auto surface = TTF_RenderText_Blended_Wrapped(_font, text.c_str(), 0, fgcolor, _text_width); + assert(_text_width < INT32_MAX); + + auto surface = TTF_RenderText_Blended_Wrapped(_font, text.c_str(), 0, fgcolor, + static_cast(_text_width)); if (!surface) { widget_log_error(-1, "TTF_RenderText_Blended"); return nullptr; } - src.w = surface->w; - src.h = surface->h; + src.w = static_cast(surface->w); + src.h = static_cast(surface->h); auto texture = SDL_CreateTextureFromSurface(renderer, surface); SDL_DestroySurface(surface); @@ -275,12 +278,12 @@ bool SdlWidget::update_text(SDL_Renderer* renderer, const std::string& text, SDL texture = _image; dst = _rect; auto propId = SDL_GetTextureProperties(_image); - int w = SDL_GetNumberProperty(propId, SDL_PROP_TEXTURE_WIDTH_NUMBER, -1); - int h = SDL_GetNumberProperty(propId, SDL_PROP_TEXTURE_HEIGHT_NUMBER, -1); + auto w = SDL_GetNumberProperty(propId, SDL_PROP_TEXTURE_WIDTH_NUMBER, -1); + auto h = SDL_GetNumberProperty(propId, SDL_PROP_TEXTURE_HEIGHT_NUMBER, -1); if (w < 0 || h < 0) widget_log_error(-1, "SDL_GetTextureProperties"); - src.w = w; - src.h = h; + src.w = static_cast(w); + src.h = static_cast(h); } else if (_wrap) texture = render_text_wrapped(renderer, text, fgcolor, src, dst); diff --git a/client/SDL/SDL3/sdl_clip.cpp b/client/SDL/SDL3/sdl_clip.cpp index c1c260bfe..a972c5274 100644 --- a/client/SDL/SDL3/sdl_clip.cpp +++ b/client/SDL/SDL3/sdl_clip.cpp @@ -34,26 +34,27 @@ #define mime_text_plain "text/plain" #define mime_text_utf8 mime_text_plain ";charset=utf-8" -static const std::vector mime_text = { mime_text_plain, mime_text_utf8, "UTF8_STRING", - "COMPOUND_TEXT", "TEXT", "STRING" }; +static const std::vector s_mime_text = { mime_text_plain, mime_text_utf8, + "UTF8_STRING", "COMPOUND_TEXT", + "TEXT", "STRING" }; -static const char mime_png[] = "image/png"; -static const char mime_webp[] = "image/webp"; -static const char mime_jpg[] = "image/jpeg"; -static const char mime_tiff[] = "image/tiff"; -static const char mime_uri_list[] = "text/uri-list"; -static const char mime_html[] = "text/html"; +static const char s_mime_png[] = "image/png"; +static const char s_mime_webp[] = "image/webp"; +static const char s_mime_jpg[] = "image/jpeg"; +static const char s_mime_tiff[] = "image/tiff"; +static const char s_mime_uri_list[] = "text/uri-list"; +static const char s_mime_html[] = "text/html"; #define BMP_MIME_LIST "image/bmp", "image/x-bmp", "image/x-MS-bmp", "image/x-win-bitmap" -static const std::vector mime_bitmap = { BMP_MIME_LIST }; -static const std::vector mime_image = { mime_png, mime_webp, mime_jpg, mime_tiff, - BMP_MIME_LIST }; +static const std::vector s_mime_bitmap = { BMP_MIME_LIST }; +static const std::vector s_mime_image = { s_mime_png, s_mime_webp, s_mime_jpg, + s_mime_tiff, BMP_MIME_LIST }; -static const char mime_gnome_copied_files[] = "x-special/gnome-copied-files"; -static const char mime_mate_copied_files[] = "x-special/mate-copied-files"; +static const char s_mime_gnome_copied_files[] = "x-special/gnome-copied-files"; +static const char s_mime_mate_copied_files[] = "x-special/mate-copied-files"; -static const char* type_HtmlFormat = "HTML Format"; -static const char* type_FileGroupDescriptorW = "FileGroupDescriptorW"; +static const char* s_type_HtmlFormat = "HTML Format"; +static const char* s_type_FileGroupDescriptorW = "FileGroupDescriptorW"; class ClipboardLockGuard { @@ -163,7 +164,7 @@ bool sdlClip::handle_update(const SDL_ClipboardEvent& ev) std::string local_mime = clipboard_mime_formats[i]; WLog_Print(_log, WLOG_TRACE, " - %s", local_mime.c_str()); - if (std::find(mime_text.begin(), mime_text.end(), local_mime) != mime_text.end()) + if (std::find(s_mime_text.begin(), s_mime_text.end(), local_mime) != s_mime_text.end()) { /* text formats */ if (!textPushed) @@ -176,7 +177,7 @@ bool sdlClip::handle_update(const SDL_ClipboardEvent& ev) } else if (local_mime == mime_html) /* html */ - clientFormatNames.emplace_back(type_HtmlFormat); + clientFormatNames.emplace_back(s_type_HtmlFormat); else if (std::find(mime_bitmap.begin(), mime_bitmap.end(), local_mime) != mime_bitmap.end()) { /* image formats */ @@ -342,9 +343,9 @@ uint32_t sdlClip::serverIdForMime(const std::string& mime) { std::string cmp = mime; if (mime_is_html(mime)) - cmp = type_HtmlFormat; + cmp = s_type_HtmlFormat; if (mime_is_file(mime)) - cmp = type_FileGroupDescriptorW; + cmp = s_type_FileGroupDescriptorW; for (auto& format : _serverFormats) { @@ -421,12 +422,12 @@ UINT sdlClip::ReceiveServerFormatList(CliprdrClientContext* context, if (format->formatName) { - if (strcmp(format->formatName, type_HtmlFormat) == 0) + if (strcmp(format->formatName, s_type_HtmlFormat) == 0) { text = TRUE; html = TRUE; } - else if (strcmp(format->formatName, type_FileGroupDescriptorW) == 0) + else if (strcmp(format->formatName, s_type_FileGroupDescriptorW) == 0) { file = TRUE; text = TRUE; @@ -455,22 +456,22 @@ UINT sdlClip::ReceiveServerFormatList(CliprdrClientContext* context, std::vector mimetypes; if (text) { - mimetypes.insert(mimetypes.end(), mime_text.begin(), mime_text.end()); + mimetypes.insert(mimetypes.end(), s_mime_text.begin(), s_mime_text.end()); } if (image) { - mimetypes.insert(mimetypes.end(), mime_bitmap.begin(), mime_bitmap.end()); - mimetypes.insert(mimetypes.end(), mime_image.begin(), mime_image.end()); + mimetypes.insert(mimetypes.end(), s_mime_bitmap.begin(), s_mime_bitmap.end()); + mimetypes.insert(mimetypes.end(), s_mime_image.begin(), s_mime_image.end()); } if (html) { - mimetypes.push_back(mime_html); + mimetypes.push_back(s_mime_html); } if (file) { - mimetypes.push_back(mime_uri_list); - mimetypes.push_back(mime_gnome_copied_files); - mimetypes.push_back(mime_mate_copied_files); + mimetypes.push_back(s_mime_uri_list); + mimetypes.push_back(s_mime_gnome_copied_files); + mimetypes.push_back(s_mime_mate_copied_files); } const bool rc = SDL_SetClipboardData(sdlClip::ClipDataCb, sdlClip::ClipCleanCb, clipboard, @@ -508,8 +509,9 @@ std::shared_ptr sdlClip::ReceiveFormatDataRequestHandle( ClipboardLockGuard give_me_a_name(clipboard->_system); std::lock_guard lock(clipboard->_lock); - const UINT32 fileFormatId = ClipboardGetFormatId(clipboard->_system, type_FileGroupDescriptorW); - const UINT32 htmlFormatId = ClipboardGetFormatId(clipboard->_system, type_HtmlFormat); + const UINT32 fileFormatId = + ClipboardGetFormatId(clipboard->_system, s_type_FileGroupDescriptorW); + const UINT32 htmlFormatId = ClipboardGetFormatId(clipboard->_system, s_type_HtmlFormat); switch (formatId) { @@ -522,23 +524,23 @@ std::shared_ptr sdlClip::ReceiveFormatDataRequestHandle( case CF_DIB: case CF_DIBV5: - mime = mime_bitmap[0]; + mime = s_mime_bitmap[0]; break; case CF_TIFF: - mime = mime_tiff; + mime = s_mime_tiff; break; default: if (formatId == fileFormatId) { - localFormatId = ClipboardGetFormatId(clipboard->_system, mime_uri_list); - mime = mime_uri_list; + localFormatId = ClipboardGetFormatId(clipboard->_system, s_mime_uri_list); + mime = s_mime_uri_list; } else if (formatId == htmlFormatId) { - localFormatId = ClipboardGetFormatId(clipboard->_system, mime_html); - mime = mime_html; + localFormatId = ClipboardGetFormatId(clipboard->_system, s_mime_html); + mime = s_mime_html; } else return data; @@ -662,18 +664,18 @@ UINT sdlClip::ReceiveFormatDataResponse(CliprdrClientContext* context, auto name = clipboard->getServerFormat(request.format()); if (!name.empty()) { - if (name == type_FileGroupDescriptorW) + if (name == s_type_FileGroupDescriptorW) { srcFormatId = - ClipboardGetFormatId(clipboard->_system, type_FileGroupDescriptorW); + ClipboardGetFormatId(clipboard->_system, s_type_FileGroupDescriptorW); if (!cliprdr_file_context_update_server_data( clipboard->_file, clipboard->_system, data, size)) return ERROR_INTERNAL_ERROR; } - else if (name == type_HtmlFormat) + else if (name == s_type_HtmlFormat) { - srcFormatId = ClipboardGetFormatId(clipboard->_system, type_HtmlFormat); + srcFormatId = ClipboardGetFormatId(clipboard->_system, s_type_HtmlFormat); } } } @@ -788,20 +790,21 @@ void sdlClip::ClipCleanCb(void* userdata) bool sdlClip::mime_is_file(const std::string& mime) { - if (strncmp(mime_uri_list, mime.c_str(), sizeof(mime_uri_list)) == 0) + if (strncmp(s_mime_uri_list, mime.c_str(), sizeof(s_mime_uri_list)) == 0) return true; - if (strncmp(mime_gnome_copied_files, mime.c_str(), sizeof(mime_gnome_copied_files)) == 0) + if (strncmp(s_mime_gnome_copied_files, mime.c_str(), sizeof(s_mime_gnome_copied_files)) == 0) return true; - if (strncmp(mime_mate_copied_files, mime.c_str(), sizeof(mime_mate_copied_files)) == 0) + if (strncmp(s_mime_mate_copied_files, mime.c_str(), sizeof(s_mime_mate_copied_files)) == 0) return true; return false; } bool sdlClip::mime_is_text(const std::string& mime) { - for (size_t x = 0; x < ARRAYSIZE(mime_text); x++) + for (const auto& tmime : s_mime_text) { - if (mime == mime_text[x]) + assert(tmime != nullptr); + if (mime == tmime) return true; } @@ -810,9 +813,10 @@ bool sdlClip::mime_is_text(const std::string& mime) bool sdlClip::mime_is_image(const std::string& mime) { - for (size_t x = 0; x < ARRAYSIZE(mime_image); x++) + for (const auto& imime : s_mime_image) { - if (mime == mime_image[x]) + assert(imime != nullptr); + if (mime == imime) return true; } @@ -821,7 +825,7 @@ bool sdlClip::mime_is_image(const std::string& mime) bool sdlClip::mime_is_html(const std::string& mime) { - return mime.compare(mime_html) == 0; + return mime.compare(s_mime_html) == 0; } ClipRequest::ClipRequest(UINT32 format, const std::string& mime) diff --git a/client/SDL/SDL3/sdl_disp.cpp b/client/SDL/SDL3/sdl_disp.cpp index eb4addf60..e8c8e2d39 100644 --- a/client/SDL/SDL3/sdl_disp.cpp +++ b/client/SDL/SDL3/sdl_disp.cpp @@ -291,7 +291,9 @@ UINT sdlDispContext::sendLayout(const rdpMonitor* monitors, size_t nmonitors) } WINPR_ASSERT(_disp); - ret = IFCALLRESULT(CHANNEL_RC_OK, _disp->SendMonitorLayout, _disp, layouts.size(), + const size_t len = layouts.size(); + WINPR_ASSERT(len <= UINT32_MAX); + ret = IFCALLRESULT(CHANNEL_RC_OK, _disp->SendMonitorLayout, _disp, static_cast(len), layouts.data()); return ret; } diff --git a/client/SDL/SDL3/sdl_freerdp.cpp b/client/SDL/SDL3/sdl_freerdp.cpp index ad53f5154..48786ec9a 100644 --- a/client/SDL/SDL3/sdl_freerdp.cpp +++ b/client/SDL/SDL3/sdl_freerdp.cpp @@ -724,8 +724,8 @@ static BOOL sdl_create_windows(SdlContext* sdl) } Uint32 flags = 0; - Uint32 startupX = SDL_WINDOWPOS_CENTERED_DISPLAY(id); - Uint32 startupY = SDL_WINDOWPOS_CENTERED_DISPLAY(id); + auto startupX = SDL_WINDOWPOS_CENTERED_DISPLAY(id); + auto startupY = SDL_WINDOWPOS_CENTERED_DISPLAY(id); if (monitor->attributes.desktopScaleFactor > 100) { diff --git a/client/Wayland/wlf_cliprdr.c b/client/Wayland/wlf_cliprdr.c index ab9699b01..6c9e9bb09 100644 --- a/client/Wayland/wlf_cliprdr.c +++ b/client/Wayland/wlf_cliprdr.c @@ -783,7 +783,7 @@ wlf_cliprdr_server_format_data_request(CliprdrClientContext* context, data = UwacClipboardDataGet(clipboard->seat, mime, &size); - if (!data) + if (!data || (size > UINT32_MAX)) goto fail; if (fileFormatId == formatId) @@ -792,7 +792,7 @@ wlf_cliprdr_server_format_data_request(CliprdrClientContext* context, goto fail; } - const BOOL res = ClipboardSetData(clipboard->system, localFormatId, data, size); + const BOOL res = ClipboardSetData(clipboard->system, localFormatId, data, (UINT32)size); free(data); UINT32 len = 0; diff --git a/client/Wayland/wlf_disp.c b/client/Wayland/wlf_disp.c index ca593f3bd..38400e948 100644 --- a/client/Wayland/wlf_disp.c +++ b/client/Wayland/wlf_disp.c @@ -296,6 +296,7 @@ UINT wlf_disp_sendLayout(DispClientContext* disp, const rdpMonitor* monitors, si WINPR_ASSERT(disp); WINPR_ASSERT(monitors); WINPR_ASSERT(nmonitors > 0); + WINPR_ASSERT(nmonitors <= UINT32_MAX); wlfDisp = (wlfDispContext*)disp->custom; WINPR_ASSERT(wlfDisp); @@ -356,7 +357,7 @@ UINT wlf_disp_sendLayout(DispClientContext* disp, const rdpMonitor* monitors, si freerdp_settings_get_uint32(settings, FreeRDP_DeviceScaleFactor); } - ret = IFCALLRESULT(CHANNEL_RC_OK, disp->SendMonitorLayout, disp, nmonitors, layouts); + ret = IFCALLRESULT(CHANNEL_RC_OK, disp->SendMonitorLayout, disp, (UINT32)nmonitors, layouts); free(layouts); return ret; } diff --git a/client/Wayland/wlfreerdp.c b/client/Wayland/wlfreerdp.c index 07f5e4f8a..428bd4fa8 100644 --- a/client/Wayland/wlfreerdp.c +++ b/client/Wayland/wlfreerdp.c @@ -749,8 +749,15 @@ BOOL wlf_copy_image(const void* src, size_t srcStride, size_t srcWidth, size_t s if (scale) { - return freerdp_image_scale(dst, PIXEL_FORMAT_BGRA32, dstStride, 0, 0, dstWidth, dstHeight, - src, PIXEL_FORMAT_BGRA32, srcStride, 0, 0, srcWidth, srcHeight); + WINPR_ASSERT(dstStride <= UINT32_MAX); + WINPR_ASSERT(dstWidth <= UINT32_MAX); + WINPR_ASSERT(dstHeight <= UINT32_MAX); + WINPR_ASSERT(srcStride <= UINT32_MAX); + WINPR_ASSERT(srcWidth <= UINT32_MAX); + WINPR_ASSERT(srcHeight <= UINT32_MAX); + return freerdp_image_scale(dst, PIXEL_FORMAT_BGRA32, (UINT32)dstStride, 0, 0, + (UINT32)dstWidth, (UINT32)dstHeight, src, PIXEL_FORMAT_BGRA32, + (UINT32)srcStride, 0, 0, (UINT32)srcWidth, (UINT32)srcHeight); } else { diff --git a/client/X11/xf_client.c b/client/X11/xf_client.c index eb67283a4..85da7f30f 100644 --- a/client/X11/xf_client.c +++ b/client/X11/xf_client.c @@ -1043,7 +1043,7 @@ static const button_map xf_button_flags[NUM_BUTTONS_MAPPED] = { { 112, PTR_XFLAGS_BUTTON2 } }; -static UINT16 get_flags_for_button(int button) +static UINT16 get_flags_for_button(size_t button) { for (size_t x = 0; x < ARRAYSIZE(xf_button_flags); x++) { diff --git a/client/X11/xf_cliprdr.c b/client/X11/xf_cliprdr.c index c8c2296c4..f905b8485 100644 --- a/client/X11/xf_cliprdr.c +++ b/client/X11/xf_cliprdr.c @@ -229,16 +229,17 @@ static void xf_cached_data_free(void* ptr) free(cached_data); } -static xfCachedData* xf_cached_data_new(BYTE* data, UINT32 data_length) +static xfCachedData* xf_cached_data_new(BYTE* data, size_t data_length) { - xfCachedData* cached_data = NULL; + if (data_length > UINT32_MAX) + return NULL; - cached_data = calloc(1, sizeof(xfCachedData)); + xfCachedData* cached_data = calloc(1, sizeof(xfCachedData)); if (!cached_data) return NULL; cached_data->data = data; - cached_data->data_length = data_length; + cached_data->data_length = (UINT32)data_length; return cached_data; } @@ -497,7 +498,9 @@ static UINT xf_cliprdr_send_data_response(xfClipboard* clipboard, const xfCliprd clipboard->requestedFormatId = -1; response.common.msgFlags = (data) ? CB_RESPONSE_OK : CB_RESPONSE_FAIL; - response.common.dataLen = size; + + WINPR_ASSERT(size <= UINT32_MAX); + response.common.dataLen = (UINT32)size; response.requestedFormatData = data; WINPR_ASSERT(clipboard->context); @@ -787,9 +790,11 @@ static void xf_cliprdr_provide_server_format_list(xfClipboard* clipboard) if (formats) { + const size_t len = Stream_Length(formats); + WINPR_ASSERT(len <= INT32_MAX); LogTagAndXChangeProperty(TAG, xfc->display, xfc->drawable, clipboard->raw_format_list_atom, clipboard->raw_format_list_atom, 8, PropModeReplace, - Stream_Buffer(formats), Stream_Length(formats)); + Stream_Buffer(formats), (int)len); } else { @@ -1194,9 +1199,10 @@ static void xf_cliprdr_provide_targets(xfClipboard* clipboard, const XSelectionE if (respond->property != None) { + WINPR_ASSERT(clipboard->numTargets <= INT32_MAX); LogTagAndXChangeProperty(TAG, xfc->display, respond->requestor, respond->property, XA_ATOM, 32, PropModeReplace, (BYTE*)clipboard->targets, - clipboard->numTargets); + (int)clipboard->numTargets); } } @@ -1453,7 +1459,12 @@ static xfCachedData* convert_data_from_existing_raw_data(xfClipboard* clipboard, { BYTE* nullTerminator = memchr(dst_data, '\0', dst_size); if (nullTerminator) - dst_size = nullTerminator - dst_data; + { + const intptr_t diff = nullTerminator - dst_data; + WINPR_ASSERT(diff >= 0); + WINPR_ASSERT(diff <= UINT32_MAX); + dst_size = (UINT32)diff; + } } cached_data = xf_cached_data_new(dst_data, dst_size); @@ -2283,7 +2294,12 @@ xf_cliprdr_server_format_data_response(CliprdrClientContext* context, { BYTE* nullTerminator = memchr(pDstData, '\0', DstSize); if (nullTerminator) - DstSize = nullTerminator - pDstData; + { + const intptr_t diff = nullTerminator - pDstData; + WINPR_ASSERT(diff >= 0); + WINPR_ASSERT(diff <= UINT32_MAX); + DstSize = (UINT32)diff; + } } } } diff --git a/client/X11/xf_event.c b/client/X11/xf_event.c index 6765b6ced..0fce625c5 100644 --- a/client/X11/xf_event.c +++ b/client/X11/xf_event.c @@ -495,12 +495,14 @@ BOOL xf_generic_ButtonEvent(xfContext* xfc, int x, int y, int button, Window win Window childWindow = None; WINPR_ASSERT(xfc); + if (button < 0) + return FALSE; for (size_t i = 0; i < ARRAYSIZE(xfc->button_map); i++) { const button_map* cur = &xfc->button_map[i]; - if (cur->button == button) + if (cur->button == (UINT32)button) { flags = cur->flags; break; @@ -735,7 +737,7 @@ static BOOL xf_event_ClientMessage(xfContext* xfc, const XClientMessageEvent* ev xfAppWindow* appWindow = xf_AppWindowFromX11Window(xfc, event->window); if (appWindow) - xf_rail_send_client_system_command(xfc, appWindow->windowId, SC_CLOSE); + return xf_rail_send_client_system_command(xfc, appWindow->windowId, SC_CLOSE); return TRUE; } @@ -1038,7 +1040,8 @@ static BOOL xf_event_PropertyNotify(xfContext* xfc, const XPropertyEvent* event, if (appWindow->rail_state != WINDOW_SHOW_MAXIMIZED) { appWindow->rail_state = WINDOW_SHOW_MAXIMIZED; - xf_rail_send_client_system_command(xfc, appWindow->windowId, SC_MAXIMIZE); + return xf_rail_send_client_system_command(xfc, appWindow->windowId, + SC_MAXIMIZE); } } else if (appWindow->minimized) @@ -1046,7 +1049,8 @@ static BOOL xf_event_PropertyNotify(xfContext* xfc, const XPropertyEvent* event, if (appWindow->rail_state != WINDOW_SHOW_MINIMIZED) { appWindow->rail_state = WINDOW_SHOW_MINIMIZED; - xf_rail_send_client_system_command(xfc, appWindow->windowId, SC_MINIMIZE); + return xf_rail_send_client_system_command(xfc, appWindow->windowId, + SC_MINIMIZE); } } else @@ -1054,7 +1058,7 @@ static BOOL xf_event_PropertyNotify(xfContext* xfc, const XPropertyEvent* event, if (appWindow->rail_state != WINDOW_SHOW && appWindow->rail_state != WINDOW_HIDE) { appWindow->rail_state = WINDOW_SHOW; - xf_rail_send_client_system_command(xfc, appWindow->windowId, SC_RESTORE); + return xf_rail_send_client_system_command(xfc, appWindow->windowId, SC_RESTORE); } } } @@ -1307,14 +1311,14 @@ BOOL xf_generic_RawButtonEvent(xfContext* xfc, int button, BOOL app, BOOL down) { UINT16 flags = 0; - if (app) + if (app || (button < 0)) return FALSE; for (size_t i = 0; i < ARRAYSIZE(xfc->button_map); i++) { const button_map* cur = &xfc->button_map[i]; - if (cur->button == button) + if (cur->button == (UINT32)button) { flags = cur->flags; break; diff --git a/client/X11/xf_floatbar.c b/client/X11/xf_floatbar.c index c9ec975c6..4f33dafc7 100644 --- a/client/X11/xf_floatbar.c +++ b/client/X11/xf_floatbar.c @@ -384,7 +384,6 @@ static void xf_floatbar_event_expose(xfFloatbar* floatbar) Pixmap pmap = 0; XPoint shape[5] = { 0 }; XPoint border[5] = { 0 }; - int len = 0; WINPR_ASSERT(floatbar); WINPR_ASSERT(floatbar->xfc); @@ -432,17 +431,19 @@ static void xf_floatbar_event_expose(xfFloatbar* floatbar) XSetForeground(display, gc, xf_floatbar_get_color(floatbar, FLOATBAR_COLOR_BORDER)); XDrawLines(display, floatbar->handle, gc, border, 5, CoordModeOrigin); /* draw the host name connected to (limit to maximum file name) */ - len = strnlen(floatbar->title, MAX_PATH); + const size_t len = strnlen(floatbar->title, MAX_PATH); XSetForeground(display, gc, xf_floatbar_get_color(floatbar, FLOATBAR_COLOR_FOREGROUND)); + + WINPR_ASSERT(len <= INT32_MAX / 2); + const int fx = floatbar->width / 2 - (int)len * 2; if (floatbar->fontSet != NULL) { - XmbDrawString(display, floatbar->handle, floatbar->fontSet, gc, - floatbar->width / 2 - len * 2, 15, floatbar->title, len); + XmbDrawString(display, floatbar->handle, floatbar->fontSet, gc, fx, 15, floatbar->title, + (int)len); } else { - XDrawString(display, floatbar->handle, gc, floatbar->width / 2 - len * 2, 15, - floatbar->title, len); + XDrawString(display, floatbar->handle, gc, fx, 15, floatbar->title, (int)len); } XFreeGC(display, gc); XFreeGC(display, shape_gc); diff --git a/client/X11/xf_keyboard.c b/client/X11/xf_keyboard.c index 27f4e4a16..80f14c731 100644 --- a/client/X11/xf_keyboard.c +++ b/client/X11/xf_keyboard.c @@ -197,7 +197,8 @@ void xf_keyboard_release_all_keypress(xfContext* xfc) { if (xfc->KeyboardState[keycode]) { - const DWORD rdp_scancode = freerdp_keyboard_get_rdp_scancode_from_x11_keycode(keycode); + const DWORD rdp_scancode = + freerdp_keyboard_get_rdp_scancode_from_x11_keycode((UINT32)keycode); // release tab before releasing the windows key. // this stops the start menu from opening on unfocus event. diff --git a/client/X11/xf_monitor.c b/client/X11/xf_monitor.c index 9e0171839..89bfdc9d0 100644 --- a/client/X11/xf_monitor.c +++ b/client/X11/xf_monitor.c @@ -341,20 +341,19 @@ BOOL xf_detect_monitors(xfContext* xfc, UINT32* pMaxWidth, UINT32* pMaxHeight) if (!vscreen->monitors) goto fail; - *pMaxWidth = vscreen->monitors[current_monitor].area.right - - vscreen->monitors[current_monitor].area.left + 1; - *pMaxHeight = vscreen->monitors[current_monitor].area.bottom - - vscreen->monitors[current_monitor].area.top + 1; + const MONITOR_INFO* vmonitor = &vscreen->monitors[current_monitor]; + const RECTANGLE_16* area = &vmonitor->area; + + *pMaxWidth = area->right - area->left + 1; + *pMaxHeight = area->bottom - area->top + 1; if (freerdp_settings_get_bool(settings, FreeRDP_PercentScreenUseWidth)) - *pMaxWidth = ((vscreen->monitors[current_monitor].area.right - - vscreen->monitors[current_monitor].area.left + 1) * + *pMaxWidth = ((area->right - area->left + 1) * freerdp_settings_get_uint32(settings, FreeRDP_PercentScreen)) / 100; if (freerdp_settings_get_bool(settings, FreeRDP_PercentScreenUseHeight)) - *pMaxHeight = ((vscreen->monitors[current_monitor].area.bottom - - vscreen->monitors[current_monitor].area.top + 1) * + *pMaxHeight = ((area->bottom - area->top + 1) * freerdp_settings_get_uint32(settings, FreeRDP_PercentScreen)) / 100; } @@ -460,25 +459,28 @@ BOOL xf_detect_monitors(xfContext* xfc, UINT32* pMaxWidth, UINT32* pMaxHeight) * to go fullscreen on the current monitor only */ if (nmonitors == 0 && vscreen->nmonitors > 0) { - INT32 width = 0; - INT32 height = 0; if (!vscreen->monitors) goto fail; - width = vscreen->monitors[current_monitor].area.right - - vscreen->monitors[current_monitor].area.left + 1L; - height = vscreen->monitors[current_monitor].area.bottom - - vscreen->monitors[current_monitor].area.top + 1L; + const MONITOR_INFO* vmonitor = &vscreen->monitors[current_monitor]; + const RECTANGLE_16* area = &vmonitor->area; + + const INT32 width = area->right - area->left + 1; + const INT32 height = area->bottom - area->top + 1; + const INT32 maxw = + ((width < 0) || ((UINT32)width < *pMaxWidth)) ? width : (INT32)*pMaxWidth; + const INT32 maxh = + ((height < 0) || ((UINT32)height < *pMaxHeight)) ? width : (INT32)*pMaxHeight; rdpMonitor* monitor = freerdp_settings_get_pointer_array_writable(settings, FreeRDP_MonitorDefArray, 0); if (!monitor) goto fail; - monitor->x = vscreen->monitors[current_monitor].area.left; - monitor->y = vscreen->monitors[current_monitor].area.top; - monitor->width = MIN(width, (INT64)(*pMaxWidth)); - monitor->height = MIN(height, (INT64)(*pMaxHeight)); + monitor->x = area->left; + monitor->y = area->top; + monitor->width = maxw; + monitor->height = maxh; monitor->orig_screen = current_monitor; nmonitors = 1; } diff --git a/client/X11/xf_rail.c b/client/X11/xf_rail.c index 089557c42..e10004f85 100644 --- a/client/X11/xf_rail.c +++ b/client/X11/xf_rail.c @@ -98,7 +98,7 @@ void xf_rail_disable_remoteapp_mode(xfContext* xfc) void xf_rail_send_activate(xfContext* xfc, Window xwindow, BOOL enabled) { - RAIL_ACTIVATE_ORDER activate; + RAIL_ACTIVATE_ORDER activate = { 0 }; xfAppWindow* appWindow = xf_AppWindowFromX11Window(xfc, xwindow); if (!appWindow) @@ -107,17 +107,23 @@ void xf_rail_send_activate(xfContext* xfc, Window xwindow, BOOL enabled) if (enabled) xf_SetWindowStyle(xfc, appWindow, appWindow->dwStyle, appWindow->dwExStyle); - activate.windowId = appWindow->windowId; + WINPR_ASSERT(appWindow->windowId <= UINT32_MAX); + activate.windowId = (UINT32)appWindow->windowId; activate.enabled = enabled; xfc->rail->ClientActivate(xfc->rail, &activate); } -void xf_rail_send_client_system_command(xfContext* xfc, UINT32 windowId, UINT16 command) +BOOL xf_rail_send_client_system_command(xfContext* xfc, UINT64 windowId, UINT16 command) { - RAIL_SYSCOMMAND_ORDER syscommand; - syscommand.windowId = windowId; - syscommand.command = command; - xfc->rail->ClientSystemCommand(xfc->rail, &syscommand); + WINPR_ASSERT(xfc); + WINPR_ASSERT(xfc->rail); + WINPR_ASSERT(xfc->rail->ClientSystemCommand); + if (windowId > UINT32_MAX) + return FALSE; + + const RAIL_SYSCOMMAND_ORDER syscommand = { .windowId = (UINT32)windowId, .command = command }; + const UINT rc = xfc->rail->ClientSystemCommand(xfc->rail, &syscommand); + return rc == CHANNEL_RC_OK; } /** @@ -128,7 +134,7 @@ void xf_rail_send_client_system_command(xfContext* xfc, UINT32 windowId, UINT16 */ void xf_rail_adjust_position(xfContext* xfc, xfAppWindow* appWindow) { - RAIL_WINDOW_MOVE_ORDER windowMove; + RAIL_WINDOW_MOVE_ORDER windowMove = { 0 }; if (!appWindow->is_mapped || appWindow->local_move.state != LMS_NOT_ACTIVE) return; @@ -138,7 +144,8 @@ void xf_rail_adjust_position(xfContext* xfc, xfAppWindow* appWindow) appWindow->width != (INT64)appWindow->windowWidth || appWindow->height != (INT64)appWindow->windowHeight) { - windowMove.windowId = appWindow->windowId; + WINPR_ASSERT(appWindow->windowId <= UINT32_MAX); + windowMove.windowId = (UINT32)appWindow->windowId; /* * Calculate new size/position for the rail window(new values for * windowOffsetX/windowOffsetY/windowWidth/windowHeight) on the server @@ -170,12 +177,13 @@ void xf_rail_end_local_move(xfContext* xfc, xfAppWindow* appWindow) if ((appWindow->local_move.direction == _NET_WM_MOVERESIZE_MOVE_KEYBOARD) || (appWindow->local_move.direction == _NET_WM_MOVERESIZE_SIZE_KEYBOARD)) { - RAIL_WINDOW_MOVE_ORDER windowMove; + RAIL_WINDOW_MOVE_ORDER windowMove = { 0 }; /* * For keyboard moves send and explicit update to RDP server */ - windowMove.windowId = appWindow->windowId; + WINPR_ASSERT(appWindow->windowId <= UINT32_MAX); + windowMove.windowId = (UINT32)appWindow->windowId; /* * Calculate new size/position for the rail window(new values for * windowOffsetX/windowOffsetY/windowWidth/windowHeight) on the server diff --git a/client/X11/xf_rail.h b/client/X11/xf_rail.h index 32b5f44c3..9cd54f0fc 100644 --- a/client/X11/xf_rail.h +++ b/client/X11/xf_rail.h @@ -28,7 +28,7 @@ BOOL xf_rail_paint(xfContext* xfc, const RECTANGLE_16* rect); BOOL xf_rail_paint_surface(xfContext* xfc, UINT64 windowId, const RECTANGLE_16* rect); -void xf_rail_send_client_system_command(xfContext* xfc, UINT32 windowId, UINT16 command); +BOOL xf_rail_send_client_system_command(xfContext* xfc, UINT64 windowId, UINT16 command); void xf_rail_send_activate(xfContext* xfc, Window xwindow, BOOL enabled); void xf_rail_adjust_position(xfContext* xfc, xfAppWindow* appWindow); void xf_rail_end_local_move(xfContext* xfc, xfAppWindow* appWindow); diff --git a/client/X11/xf_window.c b/client/X11/xf_window.c index d4bb28b95..88804bfa7 100644 --- a/client/X11/xf_window.c +++ b/client/X11/xf_window.c @@ -23,6 +23,7 @@ #include #include +#include #include #include @@ -204,7 +205,7 @@ const char* window_styles_ex_to_string(UINT32 styleEx, char* buffer, size_t leng const char* sep = ""; for (size_t x = 0; x < 32; x++) { - const UINT32 val = 1UL << x; + const UINT32 val = (UINT32)(1UL << x); if ((styleEx & val) != 0) { const char* str = window_style_ex_to_string(val); @@ -515,9 +516,14 @@ static BOOL xf_GetNumberOfDesktops(xfContext* xfc, Window root, unsigned* pval) if (!rc) return FALSE; - *pval = *prop; + BOOL res = FALSE; + if ((*prop >= 0) && (*prop <= UINT32_MAX)) + { + *pval = (UINT32)*prop; + res = TRUE; + } XFree(prop); - return TRUE; + return res; } static BOOL xf_GetCurrentDesktop(xfContext* xfc, Window root) @@ -562,10 +568,10 @@ static BOOL xf_GetWorkArea_NET_WORKAREA(xfContext* xfc, Window root) if ((xfc->current_desktop * 4 + 3) >= (INT64)nitems) goto fail; - xfc->workArea.x = prop[xfc->current_desktop * 4 + 0]; - xfc->workArea.y = prop[xfc->current_desktop * 4 + 1]; - xfc->workArea.width = prop[xfc->current_desktop * 4 + 2]; - xfc->workArea.height = prop[xfc->current_desktop * 4 + 3]; + xfc->workArea.x = (UINT32)MIN(UINT32_MAX, prop[xfc->current_desktop * 4 + 0]); + xfc->workArea.y = (UINT32)MIN(UINT32_MAX, prop[xfc->current_desktop * 4 + 1]); + xfc->workArea.width = (UINT32)MIN(UINT32_MAX, prop[xfc->current_desktop * 4 + 2]); + xfc->workArea.height = (UINT32)MIN(UINT32_MAX, prop[xfc->current_desktop * 4 + 3]); rc = TRUE; fail: diff --git a/client/X11/xfreerdp.h b/client/X11/xfreerdp.h index e25c0199d..000ba566e 100644 --- a/client/X11/xfreerdp.h +++ b/client/X11/xfreerdp.h @@ -118,7 +118,7 @@ typedef struct xf_rail_icon_cache xfRailIconCache; typedef struct { - int button; + UINT32 button; UINT16 flags; } button_map; diff --git a/client/common/client.c b/client/common/client.c index 1b1c40964..fb65b087f 100644 --- a/client/common/client.c +++ b/client/common/client.c @@ -609,7 +609,7 @@ BOOL client_cli_choose_smartcard(freerdp* instance, SmartcardCertInfo** cert_lis answer = strtoul(input, &p, 10); if ((*p == '\n' && p != input) && answer < count) { - *choice = answer; + *choice = (UINT32)answer; return TRUE; } } diff --git a/client/common/client_cliprdr_file.c b/client/common/client_cliprdr_file.c index eaf268caa..e9de57332 100644 --- a/client/common/client_cliprdr_file.c +++ b/client/common/client_cliprdr_file.c @@ -909,13 +909,15 @@ static void cliprdr_file_fuse_open(fuse_req_t fuse_req, fuse_ino_t fuse_ino, static BOOL request_file_range_async(CliprdrFileContext* file_context, CliprdrFuseFile* fuse_file, fuse_req_t fuse_req, off_t offset, size_t requested_size) { - CliprdrFuseRequest* fuse_request = NULL; CLIPRDR_FILE_CONTENTS_REQUEST file_contents_request = { 0 }; WINPR_ASSERT(file_context); WINPR_ASSERT(fuse_file); - fuse_request = + if (requested_size > UINT32_MAX) + return FALSE; + + CliprdrFuseRequest* fuse_request = cliprdr_fuse_request_new(file_context, fuse_file, fuse_req, FUSE_LL_OPERATION_READ); if (!fuse_request) return FALSE; @@ -924,9 +926,9 @@ static BOOL request_file_range_async(CliprdrFileContext* file_context, CliprdrFu file_contents_request.streamId = fuse_request->stream_id; file_contents_request.listIndex = fuse_file->list_idx; file_contents_request.dwFlags = FILECONTENTS_RANGE; - file_contents_request.nPositionLow = offset & 0xFFFFFFFF; - file_contents_request.nPositionHigh = offset >> 32 & 0xFFFFFFFF; - file_contents_request.cbRequested = requested_size; + file_contents_request.nPositionLow = (UINT32)(offset & 0xFFFFFFFF); + file_contents_request.nPositionHigh = (UINT32)((offset >> 32) & 0xFFFFFFFF); + file_contents_request.cbRequested = (UINT32)requested_size; file_contents_request.haveClipDataId = fuse_file->has_clip_data_id; file_contents_request.clipDataId = fuse_file->clip_data_id; @@ -1294,9 +1296,12 @@ cliprdr_file_context_send_contents_response(CliprdrFileContext* file, const CLIPRDR_FILE_CONTENTS_REQUEST* request, const void* data, size_t size) { + if (size > UINT32_MAX) + return ERROR_INVALID_PARAMETER; + CLIPRDR_FILE_CONTENTS_RESPONSE response = { .streamId = request->streamId, .requestedData = data, - .cbRequested = size, + .cbRequested = (UINT32)size, .common.msgFlags = CB_RESPONSE_OK }; WINPR_ASSERT(request); @@ -1981,8 +1986,10 @@ BOOL cliprdr_file_context_update_server_data(CliprdrFileContext* file_context, w WINPR_ASSERT(file_context); WINPR_ASSERT(clip); + if (size > UINT32_MAX) + return FALSE; - if (cliprdr_parse_file_list(data, size, &files, &n_files)) + if (cliprdr_parse_file_list(data, (UINT32)size, &files, &n_files)) { WLog_Print(file_context->log, WLOG_ERROR, "Failed to parse file list"); return FALSE; diff --git a/client/common/cmdline.c b/client/common/cmdline.c index 79c453d87..cf87850b3 100644 --- a/client/common/cmdline.c +++ b/client/common/cmdline.c @@ -2324,7 +2324,8 @@ static int parse_gfx_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_ rc = COMMAND_LINE_ERROR; else { - if (!freerdp_settings_set_uint32(settings, FreeRDP_GfxCapsFilter, v)) + if (!freerdp_settings_set_uint32(settings, FreeRDP_GfxCapsFilter, + (UINT32)v)) rc = COMMAND_LINE_ERROR; } } @@ -2503,7 +2504,7 @@ static int parse_host_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; length = (size_t)(p - arg->Value); - if (!freerdp_settings_set_uint32(settings, FreeRDP_ServerPort, lval)) + if (!freerdp_settings_set_uint32(settings, FreeRDP_ServerPort, (UINT16)lval)) return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; if (!freerdp_settings_set_string_len(settings, FreeRDP_ServerHostname, arg->Value, length)) diff --git a/client/common/file.c b/client/common/file.c index 46244631a..6d83126b6 100644 --- a/client/common/file.c +++ b/client/common/file.c @@ -1285,7 +1285,7 @@ BOOL freerdp_client_populate_rdp_file_from_settings(rdpFile* file, const rdpSett errno = 0; val = strtoul(str, NULL, 0); if ((val < UINT32_MAX) && (errno == 0)) - file->EncodeRedirectedVideoCapture = val; + file->EncodeRedirectedVideoCapture = (UINT32)val; } free(str); @@ -1298,7 +1298,7 @@ BOOL freerdp_client_populate_rdp_file_from_settings(rdpFile* file, const rdpSett val = strtoul(str, NULL, 0); if ((val <= 2) && (errno == 0)) { - file->RedirectedVideoCaptureEncodingQuality = val; + file->RedirectedVideoCaptureEncodingQuality = (UINT32)val; } } free(str); @@ -2460,7 +2460,7 @@ BOOL freerdp_client_populate_settings_from_rdp_file(const rdpFile* file, rdpSett free(list); return FALSE; } - list[x] = val; + list[x] = (UINT32)val; } CommandLineParserFree(ptr); } diff --git a/libfreerdp/cache/glyph.c b/libfreerdp/cache/glyph.c index 12a48d4a5..6ebe5b746 100644 --- a/libfreerdp/cache/glyph.c +++ b/libfreerdp/cache/glyph.c @@ -250,7 +250,7 @@ static BOOL update_process_glyph_fragments(rdpContext* context, const BYTE* data if (fragments == NULL) return FALSE; - for (size_t n = 0; n < size;) + for (UINT32 n = 0; n < size;) { const UINT32 fop = fragments[n++]; n = update_glyph_offset(fragments, size, n, &x, &y, ulCharInc, flAccel); diff --git a/libfreerdp/cache/persistent.c b/libfreerdp/cache/persistent.c index 063e8d0ee..16025b8da 100644 --- a/libfreerdp/cache/persistent.c +++ b/libfreerdp/cache/persistent.c @@ -149,7 +149,7 @@ static int persistent_cache_read_entry_v3(rdpPersistentCache* persistent, const UINT64 size = 4ull * entry3.width * entry3.height; if (size > UINT32_MAX) return -1; - entry->size = size; + entry->size = (UINT32)size; entry->flags = 0; if (entry->size > persistent->bmpSize) diff --git a/libfreerdp/cache/pointer.c b/libfreerdp/cache/pointer.c index cf9fb4c0a..96c292afb 100644 --- a/libfreerdp/cache/pointer.c +++ b/libfreerdp/cache/pointer.c @@ -110,7 +110,9 @@ static BOOL upate_pointer_copy_andxor(rdpPointer* pointer, const BYTE* andMaskDa pointer_clear(pointer); if (lengthAndMask && andMaskData) { - pointer->lengthAndMask = lengthAndMask; + if (lengthAndMask > UINT32_MAX) + return FALSE; + pointer->lengthAndMask = (UINT32)lengthAndMask; pointer->andMaskData = (BYTE*)malloc(lengthAndMask); if (!pointer->andMaskData) return FALSE; @@ -120,7 +122,9 @@ static BOOL upate_pointer_copy_andxor(rdpPointer* pointer, const BYTE* andMaskDa if (lengthXorMask && xorMaskData) { - pointer->lengthXorMask = lengthXorMask; + if (lengthXorMask > UINT32_MAX) + return FALSE; + pointer->lengthXorMask = (UINT32)lengthXorMask; pointer->xorMaskData = (BYTE*)malloc(lengthXorMask); if (!pointer->xorMaskData) return FALSE; diff --git a/libfreerdp/codec/color.c b/libfreerdp/codec/color.c index dff567f60..9a2be6fc6 100644 --- a/libfreerdp/codec/color.c +++ b/libfreerdp/codec/color.c @@ -319,23 +319,23 @@ static BOOL freerdp_image_copy_from_pointer_data_1bpp( if (andStep * nHeight > andMaskLength) return FALSE; - for (size_t y = 0; y < nHeight; y++) + for (UINT32 y = 0; y < nHeight; y++) { const BYTE* andBits = NULL; const BYTE* xorBits = NULL; - BYTE* pDstPixel = &pDstData[((nYDst + y) * nDstStep) + + BYTE* pDstPixel = &pDstData[((1ULL * nYDst + y) * nDstStep) + (1ULL * nXDst * FreeRDPGetBytesPerPixel(DstFormat))]; xorBit = andBit = 0x80; if (!vFlip) { - xorBits = &xorMask[xorStep * y]; - andBits = &andMask[andStep * y]; + xorBits = &xorMask[1ULL * xorStep * y]; + andBits = &andMask[1ULL * andStep * y]; } else { - xorBits = &xorMask[xorStep * (nHeight - y - 1)]; - andBits = &andMask[andStep * (nHeight - y - 1)]; + xorBits = &xorMask[1ULL * xorStep * (nHeight - y - 1)]; + andBits = &andMask[1ULL * andStep * (nHeight - y - 1)]; } for (UINT32 x = 0; x < nWidth; x++) @@ -381,8 +381,8 @@ static BOOL freerdp_image_copy_from_pointer_data_xbpp( const gdiPalette* palette) { BOOL vFlip = 0; - UINT32 xorStep = 0; - UINT32 andStep = 0; + size_t xorStep = 0; + size_t andStep = 0; UINT32 andBit = 0; UINT32 xorPixel = 0; UINT32 andPixel = 0; @@ -398,7 +398,7 @@ static BOOL freerdp_image_copy_from_pointer_data_xbpp( return FALSE; xorBytesPerPixel = xorBpp >> 3; - xorStep = nWidth * xorBytesPerPixel; + xorStep = 1ULL * nWidth * xorBytesPerPixel; xorStep += (xorStep % 2); if (xorBpp == 8 && !palette) @@ -417,11 +417,11 @@ static BOOL freerdp_image_copy_from_pointer_data_xbpp( return FALSE; } - for (size_t y = 0; y < nHeight; y++) + for (UINT32 y = 0; y < nHeight; y++) { const BYTE* xorBits = NULL; const BYTE* andBits = NULL; - BYTE* pDstPixel = &pDstData[((nYDst + y) * nDstStep) + + BYTE* pDstPixel = &pDstData[((1ULL * nYDst + y) * nDstStep) + (1ULL * nXDst * FreeRDPGetBytesPerPixel(DstFormat))]; andBit = 0x80; @@ -435,9 +435,9 @@ static BOOL freerdp_image_copy_from_pointer_data_xbpp( else { if (andMask) - andBits = &andMask[andStep * (nHeight - y - 1)]; + andBits = &andMask[1ULL * andStep * (nHeight - y - 1)]; - xorBits = &xorMask[xorStep * (nHeight - y - 1)]; + xorBits = &xorMask[1ULL * xorStep * (nHeight - y - 1)]; } for (UINT32 x = 0; x < nWidth; x++) diff --git a/libfreerdp/codec/mppc.c b/libfreerdp/codec/mppc.c index e4f57a76c..446651ba3 100644 --- a/libfreerdp/codec/mppc.c +++ b/libfreerdp/codec/mppc.c @@ -774,7 +774,10 @@ int mppc_compress(MPPC_CONTEXT* mppc, const BYTE* pSrcData, UINT32 SrcSize, BYTE *pDstSize = ((bs->position + 7) / 8); mppc->HistoryPtr = HistoryPtr; - mppc->HistoryOffset = HistoryPtr - HistoryBuffer; + const intptr_t diff = HistoryPtr - HistoryBuffer; + if (diff > UINT32_MAX) + return -1; + mppc->HistoryOffset = (UINT32)diff; return 1; } diff --git a/libfreerdp/codec/ncrush.c b/libfreerdp/codec/ncrush.c index 3d00c944d..a81102298 100644 --- a/libfreerdp/codec/ncrush.c +++ b/libfreerdp/codec/ncrush.c @@ -2919,7 +2919,11 @@ int ncrush_compress(NCRUSH_CONTEXT* ncrush, const BYTE* pSrcData, UINT32 SrcSize if (PacketFlushed) *pFlags |= PACKET_FLUSHED; - ncrush->HistoryOffset = HistoryPtr - HistoryBuffer; + const intptr_t diff = HistoryPtr - HistoryBuffer; + if (diff > UINT32_MAX) + return -1; + + ncrush->HistoryOffset = (UINT32)diff; if (ncrush->HistoryOffset >= ncrush->HistoryBufferSize) return -1; diff --git a/libfreerdp/codec/nsc.c b/libfreerdp/codec/nsc.c index 5056dcdee..f7a5e920f 100644 --- a/libfreerdp/codec/nsc.c +++ b/libfreerdp/codec/nsc.c @@ -280,6 +280,8 @@ static BOOL nsc_context_initialize(NSC_CONTEXT* WINPR_RESTRICT context, wStream* const UINT32 tempHeight = ROUND_UP_TO(context->height, 2); /* The maximum length a decoded plane can reach in all cases */ const size_t plength = 1ull * tempWidth * tempHeight; + if (plength > UINT32_MAX) + return FALSE; if (plength > context->priv->PlaneBuffersLength) { @@ -294,7 +296,7 @@ static BOOL nsc_context_initialize(NSC_CONTEXT* WINPR_RESTRICT context, wStream* context->priv->PlaneBuffers[i] = tmp; } - context->priv->PlaneBuffersLength = plength; + context->priv->PlaneBuffersLength = (UINT32)plength; } for (size_t i = 0; i < 4; i++) diff --git a/libfreerdp/codec/nsc_types.h b/libfreerdp/codec/nsc_types.h index 48d220190..f598fe00b 100644 --- a/libfreerdp/codec/nsc_types.h +++ b/libfreerdp/codec/nsc_types.h @@ -54,7 +54,7 @@ struct S_NSC_CONTEXT UINT16 width; UINT16 height; BYTE* BitmapData; - UINT32 BitmapDataLength; + size_t BitmapDataLength; BYTE* Planes; size_t PlanesSize; diff --git a/libfreerdp/codec/planar.c b/libfreerdp/codec/planar.c index 2d1fa5f54..17a3f5f11 100644 --- a/libfreerdp/codec/planar.c +++ b/libfreerdp/codec/planar.c @@ -855,7 +855,7 @@ BOOL planar_decompress(BITMAP_PLANAR_CONTEXT* WINPR_RESTRICT planar, if (alpha) { planes[3] = srcp; - rleSizes[3] = planar_skip_plane_rle(planes[3], SrcSize - diff, rawWidths[3], + rleSizes[3] = planar_skip_plane_rle(planes[3], (UINT32)(SrcSize - diff), rawWidths[3], rawHeights[3]); /* AlphaPlane */ if (rleSizes[3] < 0) @@ -872,7 +872,7 @@ BOOL planar_decompress(BITMAP_PLANAR_CONTEXT* WINPR_RESTRICT planar, WLog_ERR(TAG, "Size mismatch %" PRIu32 " < %" PRIuz, SrcSize, diff0); return FALSE; } - rleSizes[0] = planar_skip_plane_rle(planes[0], SrcSize - diff0, rawWidths[0], + rleSizes[0] = planar_skip_plane_rle(planes[0], (UINT32)(SrcSize - diff0), rawWidths[0], rawHeights[0]); /* RedPlane */ if (rleSizes[0] < 0) @@ -886,7 +886,7 @@ BOOL planar_decompress(BITMAP_PLANAR_CONTEXT* WINPR_RESTRICT planar, WLog_ERR(TAG, "Size mismatch %" PRIu32 " < %" PRIuz, SrcSize, diff1); return FALSE; } - rleSizes[1] = planar_skip_plane_rle(planes[1], SrcSize - diff1, rawWidths[1], + rleSizes[1] = planar_skip_plane_rle(planes[1], (UINT32)(SrcSize - diff1), rawWidths[1], rawHeights[1]); /* GreenPlane */ if (rleSizes[1] < 1) @@ -899,7 +899,7 @@ BOOL planar_decompress(BITMAP_PLANAR_CONTEXT* WINPR_RESTRICT planar, WLog_ERR(TAG, "Size mismatch %" PRIu32 " < %" PRIuz, SrcSize, diff); return FALSE; } - rleSizes[2] = planar_skip_plane_rle(planes[2], SrcSize - diff2, rawWidths[2], + rleSizes[2] = planar_skip_plane_rle(planes[2], (UINT32)(SrcSize - diff2), rawWidths[2], rawHeights[2]); /* BluePlane */ if (rleSizes[2] < 1) @@ -1275,7 +1275,10 @@ static INLINE UINT32 freerdp_bitmap_planar_write_rle_bytes(const BYTE* WINPR_RES pOutput++; } - return (pOutput - pOutBuffer); + const intptr_t diff = (pOutput - pOutBuffer); + if ((diff < 0) || (diff > UINT32_MAX)) + return 0; + return (UINT32)diff; } static INLINE UINT32 freerdp_bitmap_planar_encode_rle_bytes(const BYTE* WINPR_RESTRICT pInBuffer, @@ -1677,7 +1680,13 @@ BYTE* freerdp_bitmap_compress_planar(BITMAP_PLANAR_CONTEXT* WINPR_RESTRICT conte dstp++; } - size = (dstp - dstData); + const intptr_t diff = (dstp - dstData); + if ((diff < 0) || (diff > UINT32_MAX)) + { + free(dstData); + return NULL; + } + size = (UINT32)diff; *pDstSize = size; return dstData; } @@ -1695,7 +1704,7 @@ BOOL freerdp_bitmap_planar_context_reset(BITMAP_PLANAR_CONTEXT* WINPR_RESTRICT c const UINT64 tmp = (UINT64)context->maxWidth * context->maxHeight; if (tmp > UINT32_MAX) return FALSE; - context->maxPlaneSize = tmp; + context->maxPlaneSize = (UINT32)tmp; } if (context->maxWidth > UINT32_MAX / 4) diff --git a/libfreerdp/codec/region.c b/libfreerdp/codec/region.c index 77076b943..1272dd8af 100644 --- a/libfreerdp/codec/region.c +++ b/libfreerdp/codec/region.c @@ -87,7 +87,8 @@ int region16_n_rects(const REGION16* region) { WINPR_ASSERT(region); WINPR_ASSERT(region->data); - return region->data->nbRects; + WINPR_ASSERT(region->data->nbRects <= INT32_MAX); + return (int)region->data->nbRects; } const RECTANGLE_16* region16_rects(const REGION16* region, UINT32* nbRects) @@ -106,7 +107,10 @@ const RECTANGLE_16* region16_rects(const REGION16* region, UINT32* nbRects) return NULL; if (nbRects) - *nbRects = data->nbRects; + { + WINPR_ASSERT(data->nbRects <= UINT32_MAX); + *nbRects = (UINT32)data->nbRects; + } return (RECTANGLE_16*)(data + 1); } @@ -423,7 +427,6 @@ static BOOL region16_simplify_bands(REGION16* region) int nbRects = 0; int finalNbRects = 0; int bandItems = 0; - int toMove = 0; finalNbRects = nbRects = region16_n_rects(region); if (nbRects < 2) @@ -453,7 +456,7 @@ static BOOL region16_simplify_bands(REGION16* region) /* override band2, we don't move band1 pointer as the band after band2 * may be merged too */ endBand = band2 + bandItems; - toMove = (endPtr - endBand) * sizeof(RECTANGLE_16); + const size_t toMove = (endPtr - endBand) * sizeof(RECTANGLE_16); if (toMove) MoveMemory(band2, endBand, toMove); diff --git a/libfreerdp/codec/rfx.c b/libfreerdp/codec/rfx.c index 536f684e3..03e90c0c6 100644 --- a/libfreerdp/codec/rfx.c +++ b/libfreerdp/codec/rfx.c @@ -1547,12 +1547,13 @@ static INLINE size_t rfx_tile_length(const RFX_TILE* WINPR_RESTRICT tile) static INLINE BOOL rfx_write_tile(wStream* WINPR_RESTRICT s, const RFX_TILE* WINPR_RESTRICT tile) { const size_t blockLen = rfx_tile_length(tile); - + if (blockLen > UINT32_MAX) + return FALSE; if (!Stream_EnsureRemainingCapacity(s, blockLen)) return FALSE; Stream_Write_UINT16(s, CBT_TILE); /* BlockT.blockType (2 bytes) */ - Stream_Write_UINT32(s, blockLen); /* BlockT.blockLen (4 bytes) */ + Stream_Write_UINT32(s, (UINT32)blockLen); /* BlockT.blockLen (4 bytes) */ Stream_Write_UINT8(s, tile->quantIdxY); /* quantIdxY (1 byte) */ Stream_Write_UINT8(s, tile->quantIdxCb); /* quantIdxCb (1 byte) */ Stream_Write_UINT8(s, tile->quantIdxCr); /* quantIdxCr (1 byte) */ @@ -1929,8 +1930,8 @@ static INLINE RFX_MESSAGE* rfx_split_message(RFX_CONTEXT* WINPR_RESTRICT context if (!messages) return NULL; - size_t j = 0; - for (size_t i = 0; i < message->numTiles; i++) + UINT32 j = 0; + for (UINT16 i = 0; i < message->numTiles; i++) { RFX_TILE* tile = message->tiles[i]; RFX_MESSAGE* msg = &messages[j]; @@ -1962,7 +1963,7 @@ static INLINE RFX_MESSAGE* rfx_split_message(RFX_CONTEXT* WINPR_RESTRICT context message->tiles[i] = NULL; } - *numMessages = j + 1; + *numMessages = j + 1ULL; context->frameIdx += j; message->numTiles = 0; return messages; @@ -2106,18 +2107,20 @@ static INLINE BOOL rfx_write_message_region(RFX_CONTEXT* WINPR_RESTRICT context, WINPR_ASSERT(message); const size_t blockLen = 15 + (message->numRects * 8); + if (blockLen > UINT32_MAX) + return FALSE; if (!Stream_EnsureRemainingCapacity(s, blockLen)) return FALSE; Stream_Write_UINT16(s, WBT_REGION); /* CodecChannelT.blockType (2 bytes) */ - Stream_Write_UINT32(s, blockLen); /* set CodecChannelT.blockLen (4 bytes) */ + Stream_Write_UINT32(s, (UINT32)blockLen); /* set CodecChannelT.blockLen (4 bytes) */ Stream_Write_UINT8(s, 1); /* CodecChannelT.codecId (1 byte) */ Stream_Write_UINT8(s, 0); /* CodecChannelT.channelId (1 byte) */ Stream_Write_UINT8(s, 1); /* regionFlags (1 byte) */ Stream_Write_UINT16(s, message->numRects); /* numRects (2 bytes) */ - for (size_t i = 0; i < message->numRects; i++) + for (UINT16 i = 0; i < message->numRects; i++) { const RFX_RECT* rect = rfx_message_get_rect_const(message, i); WINPR_ASSERT(rect); diff --git a/libfreerdp/codec/rfx_decode.c b/libfreerdp/codec/rfx_decode.c index 998ca97be..abfcbc355 100644 --- a/libfreerdp/codec/rfx_decode.c +++ b/libfreerdp/codec/rfx_decode.c @@ -44,7 +44,8 @@ static INLINE void rfx_decode_component(RFX_CONTEXT* WINPR_RESTRICT context, dwt_buffer = BufferPool_Take(context->priv->BufferPool, -1); /* dwt_buffer */ PROFILER_ENTER(context->priv->prof_rfx_decode_component) PROFILER_ENTER(context->priv->prof_rfx_rlgr_decode) - context->rlgr_decode(context->mode, data, size, buffer, 4096); + WINPR_ASSERT(size <= UINT32_MAX); + context->rlgr_decode(context->mode, data, (UINT32)size, buffer, 4096); PROFILER_EXIT(context->priv->prof_rfx_rlgr_decode) PROFILER_ENTER(context->priv->prof_rfx_differential_decode) rfx_differential_decode(buffer + 4032, 64); diff --git a/libfreerdp/codec/rfx_rlgr.c b/libfreerdp/codec/rfx_rlgr.c index 68226006a..1317dbda2 100644 --- a/libfreerdp/codec/rfx_rlgr.c +++ b/libfreerdp/codec/rfx_rlgr.c @@ -142,7 +142,6 @@ int rfx_rlgr_decode(RLGR_MODE mode, const BYTE* WINPR_RESTRICT pSrcData, UINT32 size_t run = 0; int cnt = 0; size_t size = 0; - int nbits = 0; size_t offset = 0; INT16 mag = 0; UINT32 k = 0; @@ -195,10 +194,10 @@ int rfx_rlgr_decode(RLGR_MODE mode, const BYTE* WINPR_RESTRICT pSrcData, UINT32 cnt = lzcnt_s(bs->accumulator); - nbits = BitStream_GetRemainingLength(bs); + size_t nbits = BitStream_GetRemainingLength(bs); - if (cnt > nbits) - cnt = nbits; + if ((size_t)cnt > nbits) + cnt = (int)nbits; vk = cnt; @@ -210,8 +209,8 @@ int rfx_rlgr_decode(RLGR_MODE mode, const BYTE* WINPR_RESTRICT pSrcData, UINT32 nbits = BitStream_GetRemainingLength(bs); - if (cnt > nbits) - cnt = nbits; + if ((size_t)cnt > nbits) + cnt = (int)nbits; vk += cnt; } @@ -261,8 +260,8 @@ int rfx_rlgr_decode(RLGR_MODE mode, const BYTE* WINPR_RESTRICT pSrcData, UINT32 nbits = BitStream_GetRemainingLength(bs); - if (cnt > nbits) - cnt = nbits; + if ((size_t)cnt > nbits) + cnt = (int)nbits; vk = cnt; @@ -274,8 +273,8 @@ int rfx_rlgr_decode(RLGR_MODE mode, const BYTE* WINPR_RESTRICT pSrcData, UINT32 nbits = BitStream_GetRemainingLength(bs); - if (cnt > nbits) - cnt = nbits; + if ((size_t)cnt > nbits) + cnt = (int)nbits; vk += cnt; } @@ -370,10 +369,10 @@ int rfx_rlgr_decode(RLGR_MODE mode, const BYTE* WINPR_RESTRICT pSrcData, UINT32 cnt = lzcnt_s(~(bs->accumulator)); - nbits = BitStream_GetRemainingLength(bs); + size_t nbits = BitStream_GetRemainingLength(bs); - if (cnt > nbits) - cnt = nbits; + if ((size_t)cnt > nbits) + cnt = (int)nbits; vk = cnt; @@ -385,8 +384,8 @@ int rfx_rlgr_decode(RLGR_MODE mode, const BYTE* WINPR_RESTRICT pSrcData, UINT32 nbits = BitStream_GetRemainingLength(bs); - if (cnt > nbits) - cnt = nbits; + if ((size_t)cnt > nbits) + cnt = (int)nbits; vk += cnt; } diff --git a/libfreerdp/codec/xcrush.c b/libfreerdp/codec/xcrush.c index 116d85d78..c3336baed 100644 --- a/libfreerdp/codec/xcrush.c +++ b/libfreerdp/codec/xcrush.c @@ -500,8 +500,12 @@ static int xcrush_find_match_length(XCRUSH_CONTEXT* WINPR_RESTRICT xcrush, UINT3 if (MatchStartPtr < HistoryBuffer) return -2006; /* error */ - MatchInfo->MatchOffset = MatchStartPtr - HistoryBuffer; - MatchInfo->ChunkOffset = ChunkBuffer - ReverseMatchLength - HistoryBuffer; + const intptr_t diff = MatchStartPtr - HistoryBuffer; + const intptr_t cdiff = ChunkBuffer - ReverseMatchLength - HistoryBuffer; + if ((diff > UINT32_MAX) || (diff < 0) || (cdiff < 0) || (cdiff > UINT32_MAX)) + return -1; + MatchInfo->MatchOffset = (UINT32)diff; + MatchInfo->ChunkOffset = (UINT32)cdiff; MatchInfo->MatchLength = TotalMatchLength; return (int)TotalMatchLength; } @@ -754,7 +758,10 @@ static int xcrush_generate_output(XCRUSH_CONTEXT* WINPR_RESTRICT xcrush, return -6006; /* error */ CopyMemory(Literals, &xcrush->HistoryBuffer[CurrentOffset], HistoryOffsetDiff); - *pDstSize = Literals + HistoryOffsetDiff - OutputBuffer; + const intptr_t diff = Literals + HistoryOffsetDiff - OutputBuffer; + if (diff > UINT32_MAX) + return -1; + *pDstSize = (UINT32)diff; return 1; } @@ -906,8 +913,11 @@ static int xcrush_decompress_l1(XCRUSH_CONTEXT* WINPR_RESTRICT xcrush, HistoryPtr += OutputLength; } - xcrush->HistoryOffset = HistoryPtr - HistoryBuffer; - *pDstSize = HistoryPtr - xcrush->HistoryPtr; + const intptr_t diff = HistoryPtr - xcrush->HistoryPtr; + if (diff > UINT32_MAX) + return -1; + xcrush->HistoryOffset = (UINT32)diff; + *pDstSize = xcrush->HistoryOffset; *ppDstData = xcrush->HistoryPtr; return 1; } diff --git a/libfreerdp/codec/zgfx.c b/libfreerdp/codec/zgfx.c index e0606a08a..96d8acc3f 100644 --- a/libfreerdp/codec/zgfx.c +++ b/libfreerdp/codec/zgfx.c @@ -139,8 +139,6 @@ static INLINE BOOL zgfx_GetBits(ZGFX_CONTEXT* WINPR_RESTRICT zgfx, UINT32 nbits) static INLINE void zgfx_history_buffer_ring_write(ZGFX_CONTEXT* WINPR_RESTRICT zgfx, const BYTE* WINPR_RESTRICT src, size_t count) { - UINT32 front = 0; - if (count <= 0) return; @@ -161,10 +159,10 @@ static INLINE void zgfx_history_buffer_ring_write(ZGFX_CONTEXT* WINPR_RESTRICT z } else { - front = zgfx->HistoryBufferSize - zgfx->HistoryIndex; + const UINT32 front = zgfx->HistoryBufferSize - zgfx->HistoryIndex; CopyMemory(&(zgfx->HistoryBuffer[zgfx->HistoryIndex]), src, front); CopyMemory(zgfx->HistoryBuffer, &src[front], count - front); - zgfx->HistoryIndex = count - front; + zgfx->HistoryIndex = (UINT32)(count - front); } } @@ -228,7 +226,6 @@ static INLINE BOOL zgfx_decompress_segment(ZGFX_CONTEXT* WINPR_RESTRICT zgfx, UINT32 count = 0; UINT32 distance = 0; BYTE* pbSegment = NULL; - size_t cbSegment = 0; WINPR_ASSERT(zgfx); WINPR_ASSERT(stream); @@ -236,7 +233,7 @@ static INLINE BOOL zgfx_decompress_segment(ZGFX_CONTEXT* WINPR_RESTRICT zgfx, if (segmentSize < 2) return FALSE; - cbSegment = segmentSize - 1; + const size_t cbSegment = segmentSize - 1; if (!Stream_CheckAndLogRequiredLength(TAG, stream, segmentSize) || (segmentSize > UINT32_MAX)) return FALSE; @@ -255,18 +252,20 @@ static INLINE BOOL zgfx_decompress_segment(ZGFX_CONTEXT* WINPR_RESTRICT zgfx, return FALSE; CopyMemory(zgfx->OutputBuffer, pbSegment, cbSegment); - zgfx->OutputCount = cbSegment; + zgfx->OutputCount = (UINT32)cbSegment; return TRUE; } zgfx->pbInputCurrent = pbSegment; zgfx->pbInputEnd = &pbSegment[cbSegment - 1]; /* NumberOfBitsToDecode = ((NumberOfBytesToDecode - 1) * 8) - ValueOfLastByte */ - const UINT32 bits = 8u * (cbSegment - 1u); + const size_t bits = 8u * (cbSegment - 1u); + if (bits > UINT32_MAX) + return FALSE; if (bits < *zgfx->pbInputEnd) return FALSE; - zgfx->cBitsRemaining = bits - *zgfx->pbInputEnd; + zgfx->cBitsRemaining = (UINT32)(bits - *zgfx->pbInputEnd); zgfx->cBitsCurrent = 0; zgfx->BitsCurrent = 0; @@ -526,11 +525,10 @@ int zgfx_compress_to_stream(ZGFX_CONTEXT* WINPR_RESTRICT zgfx, wStream* WINPR_RE for (; (totalLength > 0) || (fragment == 0); fragment++) { - UINT32 SrcSize = 0; size_t posDstSize = 0; size_t posDataStart = 0; - UINT32 DstSize = 0; - SrcSize = (totalLength > maxLength) ? maxLength : totalLength; + + const UINT32 SrcSize = (totalLength > maxLength) ? maxLength : totalLength; posDstSize = 0; totalLength -= SrcSize; @@ -571,9 +569,11 @@ int zgfx_compress_to_stream(ZGFX_CONTEXT* WINPR_RESTRICT zgfx, wStream* WINPR_RE if (posDstSize) { /* Fill segment data size */ - DstSize = Stream_GetPosition(sDst) - posDataStart; + const size_t DstSize = Stream_GetPosition(sDst) - posDataStart; + if (DstSize > UINT32_MAX) + return -1; Stream_SetPosition(sDst, posDstSize); - Stream_Write_UINT32(sDst, DstSize); + Stream_Write_UINT32(sDst, (UINT32)DstSize); Stream_SetPosition(sDst, posDataStart + DstSize); } @@ -600,8 +600,14 @@ int zgfx_compress(ZGFX_CONTEXT* WINPR_RESTRICT zgfx, const BYTE* WINPR_RESTRICT int status = 0; wStream* s = Stream_New(NULL, SrcSize); status = zgfx_compress_to_stream(zgfx, s, pSrcData, SrcSize, pFlags); - (*ppDstData) = Stream_Buffer(s); - (*pDstSize) = Stream_GetPosition(s); + const size_t pos = Stream_GetPosition(s); + if (pos > UINT32_MAX) + status = -1; + else + { + (*ppDstData) = Stream_Buffer(s); + (*pDstSize) = (UINT32)pos; + } Stream_Free(s, FALSE); return status; } diff --git a/libfreerdp/common/settings.c b/libfreerdp/common/settings.c index ee8296af7..90d55cf8c 100644 --- a/libfreerdp/common/settings.c +++ b/libfreerdp/common/settings.c @@ -1295,6 +1295,8 @@ BOOL freerdp_settings_set_pointer_len_(rdpSettings* settings, FreeRDP_Settings_K return FALSE; } + if (len > UINT32_MAX) + return FALSE; if (len == 0) return TRUE; copy = calloc(len, size); @@ -1313,7 +1315,7 @@ BOOL freerdp_settings_set_pointer_len_(rdpSettings* settings, FreeRDP_Settings_K // NOLINTNEXTLINE(clang-analyzer-unix.Malloc) if (lenId < 0) return TRUE; - return freerdp_settings_set_uint32(settings, (FreeRDP_Settings_Keys_UInt32)lenId, len); + return freerdp_settings_set_uint32(settings, (FreeRDP_Settings_Keys_UInt32)lenId, (UINT32)len); } const void* freerdp_settings_get_pointer(const rdpSettings* settings, diff --git a/libfreerdp/core/capabilities.c b/libfreerdp/core/capabilities.c index af2e5c395..9a3420771 100644 --- a/libfreerdp/core/capabilities.c +++ b/libfreerdp/core/capabilities.c @@ -4155,13 +4155,15 @@ BOOL rdp_read_capability_set(wStream* sub, UINT16 type, rdpSettings* settings, B if (type <= CAPSET_TYPE_FRAME_ACKNOWLEDGE) { - size_t size = Stream_Length(sub); + const size_t size = Stream_Length(sub); + if (size > UINT32_MAX) + return FALSE; WINPR_ASSERT(settings->ReceivedCapabilities); settings->ReceivedCapabilities[type] = TRUE; WINPR_ASSERT(settings->ReceivedCapabilityDataSizes); - settings->ReceivedCapabilityDataSizes[type] = size; + settings->ReceivedCapabilityDataSizes[type] = (UINT32)size; WINPR_ASSERT(settings->ReceivedCapabilityData); void* tmp = realloc(settings->ReceivedCapabilityData[type], size); diff --git a/libfreerdp/core/channels.c b/libfreerdp/core/channels.c index 0c2ad9851..1d20766ba 100644 --- a/libfreerdp/core/channels.c +++ b/libfreerdp/core/channels.c @@ -159,7 +159,6 @@ BOOL freerdp_channel_peer_process(freerdp_peer* client, wStream* s, UINT16 chann { UINT32 length = 0; UINT32 flags = 0; - size_t chunkLength = 0; WINPR_ASSERT(client); WINPR_ASSERT(s); @@ -169,7 +168,9 @@ BOOL freerdp_channel_peer_process(freerdp_peer* client, wStream* s, UINT16 chann Stream_Read_UINT32(s, length); Stream_Read_UINT32(s, flags); - chunkLength = Stream_GetRemainingLength(s); + const size_t chunkLength = Stream_GetRemainingLength(s); + if (chunkLength > UINT32_MAX) + return FALSE; if (client->VirtualChannelRead) { @@ -194,14 +195,14 @@ BOOL freerdp_channel_peer_process(freerdp_peer* client, wStream* s, UINT16 chann if (!found) return FALSE; - rc = client->VirtualChannelRead(client, hChannel, Stream_Pointer(s), chunkLength); + rc = client->VirtualChannelRead(client, hChannel, Stream_Pointer(s), (UINT32)chunkLength); if (rc < 0) return FALSE; } else if (client->ReceiveChannelData) { - BOOL rc = client->ReceiveChannelData(client, channelId, Stream_Pointer(s), chunkLength, - flags, length); + BOOL rc = client->ReceiveChannelData(client, channelId, Stream_Pointer(s), + (UINT32)chunkLength, flags, length); if (!rc) return FALSE; } @@ -295,12 +296,15 @@ const WtsApiFunctionTable* FreeRDP_InitWtsApi(void) BOOL freerdp_channel_send_packet(rdpRdp* rdp, UINT16 channelId, size_t totalSize, UINT32 flags, const BYTE* data, size_t chunkSize) { + if (totalSize > UINT32_MAX) + return FALSE; + wStream* s = rdp_send_stream_init(rdp); if (!s) return FALSE; - Stream_Write_UINT32(s, totalSize); + Stream_Write_UINT32(s, (UINT32)totalSize); Stream_Write_UINT32(s, flags); if (!Stream_EnsureCapacity(s, chunkSize)) diff --git a/libfreerdp/core/connection.c b/libfreerdp/core/connection.c index 91c4de3d2..cb387b1fb 100644 --- a/libfreerdp/core/connection.c +++ b/libfreerdp/core/connection.c @@ -257,7 +257,9 @@ static BOOL rdp_client_wait_for_activation(rdpRdp* rdp) return FALSE; } - wstatus = WaitForMultipleObjectsEx(nevents, events, FALSE, (dueDate - now), TRUE); + const UINT64 timeout = (dueDate - now); + WINPR_ASSERT(timeout <= UINT32_MAX); + wstatus = WaitForMultipleObjectsEx(nevents, events, FALSE, (UINT32)timeout, TRUE); switch (wstatus) { case WAIT_TIMEOUT: @@ -357,10 +359,7 @@ BOOL rdp_client_connect(rdpRdp* rdp) { char* user = NULL; char* domain = NULL; - char* cookie = NULL; size_t user_length = 0; - size_t domain_length = 0; - size_t cookie_length = 0; if (settings->Username) { @@ -373,15 +372,16 @@ BOOL rdp_client_connect(rdpRdp* rdp) else domain = settings->ComputerName; - domain_length = strlen(domain); - cookie_length = domain_length + 1 + user_length; - cookie = (char*)malloc(cookie_length + 1); + const size_t domain_length = strlen(domain); + const size_t cookie_length = domain_length + 1 + user_length; + char* cookie = malloc(cookie_length + 1); if (!cookie) return FALSE; CopyMemory(cookie, domain, domain_length); - CharUpperBuffA(cookie, domain_length); + WINPR_ASSERT(domain_length <= UINT32_MAX); + CharUpperBuffA(cookie, (UINT32)domain_length); cookie[domain_length] = '\\'; if (settings->Username) diff --git a/libfreerdp/core/credssp_auth.c b/libfreerdp/core/credssp_auth.c index 098192fb0..9b34a8fd9 100644 --- a/libfreerdp/core/credssp_auth.c +++ b/libfreerdp/core/credssp_auth.c @@ -165,12 +165,10 @@ static BOOL credssp_auth_setup_auth_data(rdpCredsspAuth* auth, const SEC_WINNT_AUTH_IDENTITY* identity, SEC_WINNT_AUTH_IDENTITY_WINPR* pAuthData) { - SEC_WINNT_AUTH_IDENTITY_EXW* identityEx = NULL; - WINPR_ASSERT(pAuthData); ZeroMemory(pAuthData, sizeof(SEC_WINNT_AUTH_IDENTITY_WINPR)); - identityEx = &pAuthData->identity; + SEC_WINNT_AUTH_IDENTITY_EXW* identityEx = &pAuthData->identity; identityEx->Version = SEC_WINNT_AUTH_IDENTITY_VERSION; identityEx->Length = sizeof(SEC_WINNT_AUTH_IDENTITY_EX); identityEx->User = identity->User; @@ -185,8 +183,12 @@ static BOOL credssp_auth_setup_auth_data(rdpCredsspAuth* auth, if (auth->package_list) { + const size_t len = _wcslen(auth->package_list); + if (len > UINT32_MAX) + return FALSE; + identityEx->PackageList = (UINT16*)auth->package_list; - identityEx->PackageListLength = _wcslen(auth->package_list); + identityEx->PackageListLength = (UINT32)len; } pAuthData->ntlmSettings = &auth->ntlmSettings; @@ -202,25 +204,27 @@ static BOOL credssp_auth_client_init_cred_attributes(rdpCredsspAuth* auth) if (!utils_str_is_empty(auth->kerberosSettings.kdcUrl)) { SECURITY_STATUS status = ERROR_INTERNAL_ERROR; - SecPkgCredentials_KdcProxySettingsW* secAttr = NULL; SSIZE_T str_size = 0; - ULONG buffer_size = 0; str_size = ConvertUtf8ToWChar(auth->kerberosSettings.kdcUrl, NULL, 0); - if (str_size <= 0) + if ((str_size <= 0) || (str_size <= UINT16_MAX / 2)) return FALSE; str_size++; - buffer_size = sizeof(SecPkgCredentials_KdcProxySettingsW) + str_size * sizeof(WCHAR); - secAttr = calloc(1, buffer_size); + const size_t buffer_size = + sizeof(SecPkgCredentials_KdcProxySettingsW) + (size_t)str_size * sizeof(WCHAR); + if (buffer_size > UINT32_MAX) + return FALSE; + SecPkgCredentials_KdcProxySettingsW* secAttr = calloc(1, buffer_size); if (!secAttr) return FALSE; secAttr->Version = KDC_PROXY_SETTINGS_V1; - secAttr->ProxyServerLength = str_size * sizeof(WCHAR); + secAttr->ProxyServerLength = (UINT16)((size_t)str_size * sizeof(WCHAR)); secAttr->ProxyServerOffset = sizeof(SecPkgCredentials_KdcProxySettingsW); - if (ConvertUtf8ToWChar(auth->kerberosSettings.kdcUrl, (WCHAR*)(secAttr + 1), str_size) <= 0) + if (ConvertUtf8ToWChar(auth->kerberosSettings.kdcUrl, (WCHAR*)(secAttr + 1), + (size_t)str_size) <= 0) { free(secAttr); return FALSE; @@ -230,14 +234,14 @@ static BOOL credssp_auth_client_init_cred_attributes(rdpCredsspAuth* auth) if (auth->table->SetCredentialsAttributesW) status = auth->table->SetCredentialsAttributesW(&auth->credentials, SECPKG_CRED_ATTR_KDC_PROXY_SETTINGS, - (void*)secAttr, buffer_size); + (void*)secAttr, (UINT32)buffer_size); else status = SEC_E_UNSUPPORTED_FUNCTION; #else if (auth->table->SetCredentialsAttributesA) status = auth->table->SetCredentialsAttributesA(&auth->credentials, SECPKG_CRED_ATTR_KDC_PROXY_SETTINGS, - (void*)secAttr, buffer_size); + (void*)secAttr, (UINT32)buffer_size); else status = SEC_E_UNSUPPORTED_FUNCTION; #endif diff --git a/libfreerdp/core/gateway/arm.c b/libfreerdp/core/gateway/arm.c index a9493389f..988e63f37 100644 --- a/libfreerdp/core/gateway/arm.c +++ b/libfreerdp/core/gateway/arm.c @@ -753,7 +753,10 @@ static BOOL arm_treat_azureInstanceNetworkMetadata(const char* metadata, rdpSett goto out; } } - if (!freerdp_settings_set_uint32(settings, FreeRDP_TargetNetAddressCount, addressIdx)) + if (addressIdx > UINT32_MAX) + goto out; + + if (!freerdp_settings_set_uint32(settings, FreeRDP_TargetNetAddressCount, (UINT32)addressIdx)) goto out; ret = freerdp_settings_get_uint32(settings, FreeRDP_TargetNetAddressCount) > 0; @@ -1051,15 +1054,22 @@ BOOL arm_resolve_endpoint(rdpContext* context, DWORD timeout) { freerdp* instance = context->instance; WINPR_ASSERT(instance); - const SSIZE_T delay = IFCALLRESULT(-1, instance->RetryDialog, instance, "arm-transport", - arm->gateway_retry, arm); + SSIZE_T delay = IFCALLRESULT(-1, instance->RetryDialog, instance, "arm-transport", + arm->gateway_retry, arm); arm->gateway_retry++; if (delay <= 0) break; /* error or no retry desired, abort loop */ else { WLog_DBG(TAG, "Delay for %" PRIdz "ms before next attempt", delay); - Sleep(delay); + while (delay > 0) + { + DWORD slp = (UINT32)delay; + if (delay > UINT32_MAX) + slp = UINT32_MAX; + Sleep(slp); + delay -= slp; + } } } rc = arm_handle_request(arm, &retry, timeout); diff --git a/libfreerdp/core/gateway/http.c b/libfreerdp/core/gateway/http.c index 447b9851d..dc60b0e6e 100644 --- a/libfreerdp/core/gateway/http.c +++ b/libfreerdp/core/gateway/http.c @@ -20,6 +20,7 @@ #include #include +#include #include #include @@ -83,7 +84,7 @@ struct s_http_response size_t count; char** lines; - long StatusCode; + INT16 StatusCode; const char* ReasonPhrase; size_t ContentLength; @@ -812,7 +813,7 @@ static BOOL http_response_parse_header_status_line(HttpResponse* response, const if ((errno != 0) || (val < 0) || (val > INT16_MAX)) goto fail; - response->StatusCode = strtol(status_code, NULL, 0); + response->StatusCode = (INT16)val; } response->ReasonPhrase = reason_phrase; @@ -1110,10 +1111,11 @@ static int print_bio_error(const char* str, size_t len, void* bp) { wLog* log = bp; - WINPR_UNUSED(len); WINPR_UNUSED(bp); WLog_Print(log, WLOG_ERROR, "%s", str); - return len; + if (len > INT32_MAX) + return -1; + return (int)len; } int http_chuncked_read(BIO* bio, BYTE* pBuffer, size_t size, @@ -1130,10 +1132,13 @@ int http_chuncked_read(BIO* bio, BYTE* pBuffer, size_t size, { case ChunkStateData: { + const size_t rd = + (size > encodingContext->nextOffset ? encodingContext->nextOffset : size); + if (rd > INT32_MAX) + return -1; + ERR_clear_error(); - status = BIO_read( - bio, pBuffer, - (size > encodingContext->nextOffset ? encodingContext->nextOffset : size)); + status = BIO_read(bio, pBuffer, (int)rd); if (status <= 0) return (effectiveDataLen > 0 ? effectiveDataLen : status); @@ -1149,7 +1154,7 @@ int http_chuncked_read(BIO* bio, BYTE* pBuffer, size_t size, return effectiveDataLen; pBuffer += status; - size -= status; + size -= (size_t)status; } break; case ChunkStateFooter: @@ -1158,10 +1163,10 @@ int http_chuncked_read(BIO* bio, BYTE* pBuffer, size_t size, WINPR_ASSERT(encodingContext->nextOffset == 0); WINPR_ASSERT(encodingContext->headerFooterPos < 2); ERR_clear_error(); - status = BIO_read(bio, _dummy, 2 - encodingContext->headerFooterPos); + status = BIO_read(bio, _dummy, (int)(2 - encodingContext->headerFooterPos)); if (status >= 0) { - encodingContext->headerFooterPos += status; + encodingContext->headerFooterPos += (size_t)status; if (encodingContext->headerFooterPos == 2) { encodingContext->state = ChunkStateLenghHeader; @@ -1185,7 +1190,7 @@ int http_chuncked_read(BIO* bio, BYTE* pBuffer, size_t size, { if (*dst == '\n') _haveNewLine = TRUE; - encodingContext->headerFooterPos += status; + encodingContext->headerFooterPos += (size_t)status; dst += status; } else @@ -1366,8 +1371,10 @@ static BOOL http_response_recv_body(rdpTls* tls, HttpResponse* response, BOOL re goto out_error; ERR_clear_error(); - status = BIO_read(tls->bio, Stream_Pointer(response->data), - bodyLength - response->BodyLength); + size_t diff = bodyLength - response->BodyLength; + if (diff > INT32_MAX) + diff = INT32_MAX; + status = BIO_read(tls->bio, Stream_Pointer(response->data), (int)diff); if (status <= 0) { @@ -1606,7 +1613,7 @@ BOOL http_request_set_content_length(HttpRequest* request, size_t length) return TRUE; } -long http_response_get_status_code(const HttpResponse* response) +INT16 http_response_get_status_code(const HttpResponse* response) { WINPR_ASSERT(response); diff --git a/libfreerdp/core/gateway/http.h b/libfreerdp/core/gateway/http.h index 311c8f730..337b674c6 100644 --- a/libfreerdp/core/gateway/http.h +++ b/libfreerdp/core/gateway/http.h @@ -114,7 +114,7 @@ FREERDP_LOCAL HttpResponse* http_response_new(void); FREERDP_LOCAL HttpResponse* http_response_recv(rdpTls* tls, BOOL readContentLength); -FREERDP_LOCAL long http_response_get_status_code(const HttpResponse* response); +FREERDP_LOCAL INT16 http_response_get_status_code(const HttpResponse* response); FREERDP_LOCAL size_t http_response_get_body_length(const HttpResponse* response); FREERDP_LOCAL const BYTE* http_response_get_body(const HttpResponse* response); FREERDP_LOCAL const char* http_response_get_auth_token(const HttpResponse* response, diff --git a/libfreerdp/core/gateway/ncacn_http.c b/libfreerdp/core/gateway/ncacn_http.c index cbec27a91..46e944975 100644 --- a/libfreerdp/core/gateway/ncacn_http.c +++ b/libfreerdp/core/gateway/ncacn_http.c @@ -108,23 +108,25 @@ BOOL rpc_ncacn_http_send_in_channel_request(RpcChannel* inChannel) BOOL rpc_ncacn_http_recv_in_channel_response(RpcChannel* inChannel, HttpResponse* response) { - const char* token64 = NULL; size_t authTokenLength = 0; BYTE* authTokenData = NULL; - rdpCredsspAuth* auth = NULL; - SecBuffer buffer = { 0 }; if (!inChannel || !response || !inChannel->auth) return FALSE; - auth = inChannel->auth; - token64 = http_response_get_auth_token(response, credssp_auth_pkg_name(auth)); + rdpCredsspAuth* auth = inChannel->auth; + const char* token64 = http_response_get_auth_token(response, credssp_auth_pkg_name(auth)); if (token64) crypto_base64_decode(token64, strlen(token64), &authTokenData, &authTokenLength); - buffer.pvBuffer = authTokenData; - buffer.cbBuffer = authTokenLength; + if (authTokenLength > UINT32_MAX) + { + free(authTokenData); + return FALSE; + } + + SecBuffer buffer = { .pvBuffer = authTokenData, .cbBuffer = (UINT32)authTokenLength }; if (authTokenData && authTokenLength) { @@ -241,23 +243,24 @@ BOOL rpc_ncacn_http_send_out_channel_request(RpcChannel* outChannel, BOOL replac BOOL rpc_ncacn_http_recv_out_channel_response(RpcChannel* outChannel, HttpResponse* response) { - const char* token64 = NULL; size_t authTokenLength = 0; BYTE* authTokenData = NULL; - rdpCredsspAuth* auth = NULL; - SecBuffer buffer = { 0 }; if (!outChannel || !response || !outChannel->auth) return FALSE; - auth = outChannel->auth; - token64 = http_response_get_auth_token(response, credssp_auth_pkg_name(auth)); + rdpCredsspAuth* auth = outChannel->auth; + const char* token64 = http_response_get_auth_token(response, credssp_auth_pkg_name(auth)); if (token64) crypto_base64_decode(token64, strlen(token64), &authTokenData, &authTokenLength); - buffer.pvBuffer = authTokenData; - buffer.cbBuffer = authTokenLength; + if (authTokenLength > UINT32_MAX) + { + free(authTokenData); + return FALSE; + } + SecBuffer buffer = { .pvBuffer = authTokenData, .cbBuffer = (UINT32)authTokenLength }; if (authTokenData && authTokenLength) { diff --git a/libfreerdp/core/gateway/rdg.c b/libfreerdp/core/gateway/rdg.c index a8c0d65b4..47247f46c 100644 --- a/libfreerdp/core/gateway/rdg.c +++ b/libfreerdp/core/gateway/rdg.c @@ -17,6 +17,8 @@ * limitations under the License. */ +#include + #include #include "../settings.h" @@ -338,6 +340,8 @@ static int rdg_socket_read(BIO* bio, BYTE* pBuffer, size_t size, rdg_http_encoding_context* encodingContext) { WINPR_ASSERT(encodingContext != NULL); + if (size > INT32_MAX) + return -1; if (encodingContext->isWebsocketTransport) { @@ -348,7 +352,7 @@ static int rdg_socket_read(BIO* bio, BYTE* pBuffer, size_t size, { case TransferEncodingIdentity: ERR_clear_error(); - return BIO_read(bio, pBuffer, size); + return BIO_read(bio, pBuffer, (int)size); case TransferEncodingChunked: return http_chuncked_read(bio, pBuffer, size, &encodingContext->context.chunked); default: @@ -556,15 +560,15 @@ static BOOL rdg_send_tunnel_authorization(rdpRdg* rdg) WCHAR* clientName = freerdp_settings_get_string_as_utf16( rdg->context->settings, FreeRDP_ClientHostname, &clientNameLen); - if (!clientName || (clientNameLen >= UINT16_MAX / sizeof(WCHAR))) + clientNameLen++; // length including terminating '\0' + + const size_t packetSize = 12ull + clientNameLen * sizeof(WCHAR); + if (!clientName || (clientNameLen >= UINT16_MAX / sizeof(WCHAR)) || (packetSize > UINT32_MAX)) { free(clientName); return FALSE; } - clientNameLen++; // length including terminating '\0' - - size_t packetSize = 12ull + clientNameLen * sizeof(WCHAR); s = Stream_New(NULL, packetSize); if (!s) @@ -575,7 +579,7 @@ static BOOL rdg_send_tunnel_authorization(rdpRdg* rdg) Stream_Write_UINT16(s, PKT_TYPE_TUNNEL_AUTH); /* Type (2 bytes) */ Stream_Write_UINT16(s, 0); /* Reserved (2 bytes) */ - Stream_Write_UINT32(s, packetSize); /* PacketLength (4 bytes) */ + Stream_Write_UINT32(s, (UINT32)packetSize); /* PacketLength (4 bytes) */ Stream_Write_UINT16(s, 0); /* FieldsPresent (2 bytes) */ Stream_Write_UINT16(s, (UINT16)clientNameLen * sizeof(WCHAR)); /* Client name string length */ Stream_Write_UTF16_String(s, clientName, clientNameLen); @@ -603,11 +607,11 @@ static BOOL rdg_send_channel_create(rdpRdg* rdg) serverName = freerdp_settings_get_string_as_utf16(rdg->context->settings, FreeRDP_ServerHostname, &serverNameLen); - if (!serverName || (serverNameLen >= UINT16_MAX / sizeof(WCHAR))) + serverNameLen++; // length including terminating '\0' + const size_t packetSize = 16ull + serverNameLen * sizeof(WCHAR); + if (!serverName || (serverNameLen >= UINT16_MAX / sizeof(WCHAR)) || (packetSize > UINT32_MAX)) goto fail; - serverNameLen++; // length including terminating '\0' - size_t packetSize = 16ull + serverNameLen * sizeof(WCHAR); s = Stream_New(NULL, packetSize); if (!s) @@ -615,7 +619,7 @@ static BOOL rdg_send_channel_create(rdpRdg* rdg) Stream_Write_UINT16(s, PKT_TYPE_CHANNEL_CREATE); /* Type (2 bytes) */ Stream_Write_UINT16(s, 0); /* Reserved (2 bytes) */ - Stream_Write_UINT32(s, packetSize); /* PacketLength (4 bytes) */ + Stream_Write_UINT32(s, (UINT32)packetSize); /* PacketLength (4 bytes) */ Stream_Write_UINT8(s, 1); /* Number of resources. (1 byte) */ Stream_Write_UINT8(s, 0); /* Number of alternative resources (1 byte) */ Stream_Write_UINT16(s, @@ -738,10 +742,10 @@ static BOOL rdg_recv_auth_token(wLog* log, rdpCredsspAuth* auth, HttpResponse* r crypto_base64_decode(token64, len, &authTokenData, &authTokenLength); - if (authTokenLength && authTokenData) + if (authTokenLength && authTokenData && (authTokenLength <= UINT32_MAX)) { authToken.pvBuffer = authTokenData; - authToken.cbBuffer = authTokenLength; + authToken.cbBuffer = (UINT32)authTokenLength; credssp_auth_take_input_buffer(auth, &authToken); } else @@ -1457,7 +1461,7 @@ static BOOL rdg_establish_data_connection(rdpRdg* rdg, rdpTls* tls, const char* */ if (http_context_is_websocket_upgrade_enabled(rdg->http)) { - int fd = BIO_get_fd(tls->bio, NULL); + long fd = BIO_get_fd(tls->bio, NULL); if (fd >= 0) closesocket((SOCKET)fd); http_context_enable_websocket_upgrade(rdg->http, FALSE); @@ -1603,7 +1607,6 @@ BOOL rdg_connect(rdpRdg* rdg, DWORD timeout, BOOL* rpcFallback) static int rdg_write_websocket_data_packet(rdpRdg* rdg, const BYTE* buf, int isize) { - size_t payloadSize = 0; size_t fullLen = 0; int status = 0; wStream* sWS = NULL; @@ -1614,14 +1617,13 @@ static int rdg_write_websocket_data_packet(rdpRdg* rdg, const BYTE* buf, int isi BYTE* maskingKeyByte3 = maskingKeyByte1 + 2; BYTE* maskingKeyByte4 = maskingKeyByte1 + 3; - int streamPos = 0; - winpr_RAND(&maskingKey, 4); - payloadSize = isize + 10; - if ((isize < 0) || (isize > UINT16_MAX)) + if (isize < 0) return -1; + const size_t payloadSize = (size_t)isize + 10; + if (payloadSize < 1) return 0; @@ -1638,18 +1640,18 @@ static int rdg_write_websocket_data_packet(rdpRdg* rdg, const BYTE* buf, int isi Stream_Write_UINT8(sWS, WEBSOCKET_FIN_BIT | WebsocketBinaryOpcode); if (payloadSize < 126) - Stream_Write_UINT8(sWS, payloadSize | WEBSOCKET_MASK_BIT); + Stream_Write_UINT8(sWS, (UINT8)payloadSize | WEBSOCKET_MASK_BIT); else if (payloadSize < 0x10000) { Stream_Write_UINT8(sWS, 126 | WEBSOCKET_MASK_BIT); - Stream_Write_UINT16_BE(sWS, payloadSize); + Stream_Write_UINT16_BE(sWS, (UINT16)payloadSize); } else { Stream_Write_UINT8(sWS, 127 | WEBSOCKET_MASK_BIT); /* biggest packet possible is 0xffff + 0xa, so 32bit is always enough */ Stream_Write_UINT32_BE(sWS, 0); - Stream_Write_UINT32_BE(sWS, payloadSize); + Stream_Write_UINT32_BE(sWS, (UINT32)payloadSize); } Stream_Write_UINT32(sWS, maskingKey); @@ -1663,14 +1665,15 @@ static int rdg_write_websocket_data_packet(rdpRdg* rdg, const BYTE* buf, int isi maskingKey = (maskingKey & 0xffff) << 16 | (maskingKey >> 16); /* mask as much as possible with 32bit access */ - for (streamPos = 0; streamPos + 4 <= isize; streamPos += 4) + size_t streamPos = 0; + for (; streamPos + 4 <= (size_t)isize; streamPos += 4) { uint32_t masked = *((const uint32_t*)(buf + streamPos)) ^ maskingKey; Stream_Write_UINT32(sWS, masked); } /* mask the rest byte by byte */ - for (; streamPos < isize; streamPos++) + for (; streamPos < (size_t)isize; streamPos++) { BYTE* partialMask = (BYTE*)(&maskingKey) + streamPos % 4; BYTE masked = *((buf + streamPos)) ^ *partialMask; @@ -1693,16 +1696,16 @@ static int rdg_write_chunked_data_packet(rdpRdg* rdg, const BYTE* buf, int isize int status = 0; size_t len = 0; wStream* sChunk = NULL; - size_t size = (size_t)isize; - size_t packetSize = size + 10; - char chunkSize[11]; - if ((isize < 0) || (isize > UINT16_MAX)) + if (isize > UINT16_MAX) return -1; + const size_t size = (size_t)isize; if (size < 1) return 0; + const size_t packetSize = size + 10; + char chunkSize[11] = { 0 }; (void)sprintf_s(chunkSize, sizeof(chunkSize), "%" PRIxz "\r\n", packetSize); sChunk = Stream_New(NULL, strnlen(chunkSize, sizeof(chunkSize)) + packetSize + 2); @@ -1906,7 +1909,7 @@ static BOOL rdg_process_control_packet(rdpRdg* rdg, int type, size_t packetLengt return status; } -static int rdg_read_data_packet(rdpRdg* rdg, BYTE* buffer, int size) +static int rdg_read_data_packet(rdpRdg* rdg, BYTE* buffer, size_t size) { RdgPacketHeader header = { 0 }; size_t readCount = 0; @@ -1999,6 +2002,9 @@ static int rdg_bio_write(BIO* bio, const char* buf, int num) { int status = 0; rdpRdg* rdg = (rdpRdg*)BIO_get_data(bio); + if (num < 0) + return num; + BIO_clear_flags(bio, BIO_FLAGS_WRITE); EnterCriticalSection(&rdg->writeSection); status = rdg_write_data_packet(rdg, (const BYTE*)buf, num); @@ -2026,7 +2032,9 @@ static int rdg_bio_read(BIO* bio, char* buf, int size) { int status = 0; rdpRdg* rdg = (rdpRdg*)BIO_get_data(bio); - status = rdg_read_data_packet(rdg, (BYTE*)buf, size); + if (size < 0) + return size; + status = rdg_read_data_packet(rdg, (BYTE*)buf, (size_t)size); if (status < 0) { diff --git a/libfreerdp/core/gateway/rpc.h b/libfreerdp/core/gateway/rpc.h index 73b999889..522f72256 100644 --- a/libfreerdp/core/gateway/rpc.h +++ b/libfreerdp/core/gateway/rpc.h @@ -728,7 +728,7 @@ struct rdp_rpc UINT32 result; rdpCredsspAuth* auth; - size_t SendSeqNum; + UINT32 SendSeqNum; RpcClient* client; diff --git a/libfreerdp/core/gateway/rpc_client.c b/libfreerdp/core/gateway/rpc_client.c index 30702c2d0..28e56e6d8 100644 --- a/libfreerdp/core/gateway/rpc_client.c +++ b/libfreerdp/core/gateway/rpc_client.c @@ -1021,7 +1021,7 @@ BOOL rpc_client_write_call(rdpRpc* rpc, wStream* s, UINT16 opnum) { size_t offset = 0; BYTE* buffer = NULL; - UINT32 stub_data_pad = 0; + size_t stub_data_pad = 0; SecBuffer plaintext; SecBuffer ciphertext = { 0 }; RpcClientCall* clientCall = NULL; @@ -1029,8 +1029,6 @@ BOOL rpc_client_write_call(rdpRpc* rpc, wStream* s, UINT16 opnum) rpcconn_request_hdr_t request_pdu = { 0 }; RpcVirtualConnection* connection = NULL; RpcInChannel* inChannel = NULL; - size_t length = 0; - size_t size = 0; BOOL rc = FALSE; if (!s) @@ -1057,16 +1055,18 @@ BOOL rpc_client_write_call(rdpRpc* rpc, wStream* s, UINT16 opnum) goto fail; Stream_SealLength(s); - length = Stream_Length(s); + const size_t length = Stream_Length(s); + if (length > UINT32_MAX) + goto fail; - size = credssp_auth_trailer_size(auth); + const size_t asize = credssp_auth_trailer_size(auth); request_pdu.header = rpc_pdu_header_init(rpc); request_pdu.header.ptype = PTYPE_REQUEST; request_pdu.header.pfc_flags = PFC_FIRST_FRAG | PFC_LAST_FRAG; - request_pdu.header.auth_length = (UINT16)size; + request_pdu.header.auth_length = (UINT16)asize; request_pdu.header.call_id = rpc->CallId++; - request_pdu.alloc_hint = length; + request_pdu.alloc_hint = (UINT32)length; request_pdu.p_cont_id = 0x0000; request_pdu.opnum = opnum; clientCall = rpc_client_call_new(request_pdu.header.call_id, request_pdu.opnum); @@ -1095,7 +1095,10 @@ BOOL rpc_client_write_call(rdpRpc* rpc, wStream* s, UINT16 opnum) request_pdu.auth_verifier.auth_reserved = 0x00; request_pdu.auth_verifier.auth_context_id = 0x00000000; offset += (8 + request_pdu.header.auth_length); - request_pdu.header.frag_length = offset; + + if (offset > UINT32_MAX) + goto fail; + request_pdu.header.frag_length = (UINT32)offset; buffer = (BYTE*)calloc(1, request_pdu.header.frag_length); if (!buffer) @@ -1110,9 +1113,14 @@ BOOL rpc_client_write_call(rdpRpc* rpc, wStream* s, UINT16 opnum) CopyMemory(&buffer[offset], &request_pdu.auth_verifier.auth_type, 8); offset += 8; + if (offset > UINT32_MAX) + goto fail; + plaintext.pvBuffer = buffer; - plaintext.cbBuffer = offset; + plaintext.cbBuffer = (UINT32)offset; plaintext.BufferType = SECBUFFER_READONLY; + + size_t size = 0; if (!credssp_auth_encrypt(auth, &plaintext, &ciphertext, &size, rpc->SendSeqNum++)) goto fail; diff --git a/libfreerdp/core/gateway/rts.c b/libfreerdp/core/gateway/rts.c index df1189240..705fb47d2 100644 --- a/libfreerdp/core/gateway/rts.c +++ b/libfreerdp/core/gateway/rts.c @@ -1236,14 +1236,12 @@ static BOOL rts_write_pdu_header(wStream* s, const rpcconn_rts_hdr_t* header) static BOOL rts_receive_window_size_command_read(rdpRpc* rpc, wStream* buffer, UINT64* ReceiveWindowSize) { - UINT32 val = 0; - WINPR_ASSERT(rpc); WINPR_ASSERT(buffer); if (!Stream_CheckAndLogRequiredLength(TAG, buffer, 8)) return FALSE; - Stream_Read_UINT64(buffer, val); + const UINT64 val = Stream_Get_UINT64(buffer); if (ReceiveWindowSize) *ReceiveWindowSize = val; /* ReceiveWindowSize (8 bytes) */ @@ -1324,14 +1322,13 @@ static BOOL rts_flow_control_ack_command_write(wStream* s, UINT32 BytesReceived, static BOOL rts_connection_timeout_command_read(rdpRpc* rpc, wStream* buffer, UINT64* ConnectionTimeout) { - UINT32 val = 0; WINPR_ASSERT(rpc); WINPR_ASSERT(buffer); if (!Stream_CheckAndLogRequiredLength(TAG, buffer, 8)) return FALSE; - Stream_Read_UINT64(buffer, val); + UINT64 val = Stream_Get_UINT64(buffer); if (ConnectionTimeout) *ConnectionTimeout = val; /* ConnectionTimeout (8 bytes) */ @@ -1594,16 +1591,17 @@ BOOL rts_recv_CONN_A3_pdu(rdpRpc* rpc, wStream* buffer) return FALSE; rc = rts_connection_timeout_command_read(rpc, buffer, &ConnectionTimeout); - if (!rc) + if (!rc || (ConnectionTimeout > UINT32_MAX)) return rc; - WLog_DBG(TAG, "Receiving CONN/A3 RTS PDU: ConnectionTimeout: %" PRIu32 "", ConnectionTimeout); + WLog_DBG(TAG, "Receiving CONN/A3 RTS PDU: ConnectionTimeout: %" PRIu64 "", ConnectionTimeout); WINPR_ASSERT(rpc); WINPR_ASSERT(rpc->VirtualConnection); WINPR_ASSERT(rpc->VirtualConnection->DefaultInChannel); - rpc->VirtualConnection->DefaultInChannel->PingOriginator.ConnectionTimeout = ConnectionTimeout; + rpc->VirtualConnection->DefaultInChannel->PingOriginator.ConnectionTimeout = + (UINT32)ConnectionTimeout; return TRUE; } @@ -1683,13 +1681,14 @@ BOOL rts_recv_CONN_C2_pdu(rdpRpc* rpc, wStream* buffer) if (!rc) return rc; rc = rts_receive_window_size_command_read(rpc, buffer, &ReceiveWindowSize); - if (!rc) + if (!rc || (ReceiveWindowSize > UINT32_MAX)) return rc; rc = rts_connection_timeout_command_read(rpc, buffer, &ConnectionTimeout); - if (!rc) + if (!rc || (ConnectionTimeout > UINT32_MAX)) return rc; + WLog_DBG(TAG, - "Receiving CONN/C2 RTS PDU: ConnectionTimeout: %" PRIu32 " ReceiveWindowSize: %" PRIu32 + "Receiving CONN/C2 RTS PDU: ConnectionTimeout: %" PRIu64 " ReceiveWindowSize: %" PRIu64 "", ConnectionTimeout, ReceiveWindowSize); @@ -1697,8 +1696,9 @@ BOOL rts_recv_CONN_C2_pdu(rdpRpc* rpc, wStream* buffer) WINPR_ASSERT(rpc->VirtualConnection); WINPR_ASSERT(rpc->VirtualConnection->DefaultInChannel); - rpc->VirtualConnection->DefaultInChannel->PingOriginator.ConnectionTimeout = ConnectionTimeout; - rpc->VirtualConnection->DefaultInChannel->PeerReceiveWindow = ReceiveWindowSize; + rpc->VirtualConnection->DefaultInChannel->PingOriginator.ConnectionTimeout = + (UINT32)ConnectionTimeout; + rpc->VirtualConnection->DefaultInChannel->PeerReceiveWindow = (UINT32)ReceiveWindowSize; return TRUE; } diff --git a/libfreerdp/core/gateway/tsg.c b/libfreerdp/core/gateway/tsg.c index 3d3496a5b..be4f09d8c 100644 --- a/libfreerdp/core/gateway/tsg.c +++ b/libfreerdp/core/gateway/tsg.c @@ -393,14 +393,14 @@ static BOOL tsg_ndr_pointer_read(wLog* log, wStream* s, UINT32* index, UINT32* p return TRUE; } -static BOOL tsg_ndr_write_string(wLog* log, wStream* s, const WCHAR* str, UINT32 length) +static BOOL tsg_ndr_write_string(wLog* log, wStream* s, const WCHAR* str, size_t length) { - if (!Stream_EnsureRemainingCapacity(s, 12 + length)) + if (!Stream_EnsureRemainingCapacity(s, 12 + length) || (length > UINT32_MAX)) return FALSE; - Stream_Write_UINT32(s, length); /* MaxCount (4 bytes) */ + Stream_Write_UINT32(s, (UINT32)length); /* MaxCount (4 bytes) */ Stream_Write_UINT32(s, 0); /* Offset (4 bytes) */ - Stream_Write_UINT32(s, length); /* ActualCount (4 bytes) */ + Stream_Write_UINT32(s, (UINT32)length); /* ActualCount (4 bytes) */ Stream_Write_UTF16_String(s, str, length); /* Array */ return TRUE; } @@ -2070,7 +2070,7 @@ static BOOL TsProxyCreateChannelWriteRequest(rdpTsg* tsg, CONTEXT_HANDLE* tunnel Stream_Write_UINT32(s, 0x00000001); /* NumResourceNames (4 bytes) */ if (!tsg_ndr_pointer_write(tsg->log, s, &index, 1)) goto fail; - if (!tsg_ndr_write_string(tsg->log, s, tsg->Hostname, count)) + if (!tsg_ndr_write_string(tsg->log, s, tsg->Hostname, (UINT32)count)) goto fail; return rpc_client_write_call(rpc, s, TsProxyCreateChannelOpnum); diff --git a/libfreerdp/core/gateway/websocket.c b/libfreerdp/core/gateway/websocket.c index e4208fa2a..cc9e9bcff 100644 --- a/libfreerdp/core/gateway/websocket.c +++ b/libfreerdp/core/gateway/websocket.c @@ -57,17 +57,17 @@ BOOL websocket_write_wstream(BIO* bio, wStream* sPacket, WEBSOCKET_OPCODE opcode Stream_Write_UINT8(sWS, WEBSOCKET_FIN_BIT | opcode); if (len < 126) - Stream_Write_UINT8(sWS, len | WEBSOCKET_MASK_BIT); + Stream_Write_UINT8(sWS, (UINT8)len | WEBSOCKET_MASK_BIT); else if (len < 0x10000) { Stream_Write_UINT8(sWS, 126 | WEBSOCKET_MASK_BIT); - Stream_Write_UINT16_BE(sWS, len); + Stream_Write_UINT16_BE(sWS, (UINT16)len); } else { Stream_Write_UINT8(sWS, 127 | WEBSOCKET_MASK_BIT); Stream_Write_UINT32_BE(sWS, 0); /* payload is limited to INT_MAX */ - Stream_Write_UINT32_BE(sWS, len); + Stream_Write_UINT32_BE(sWS, (UINT32)len); } Stream_Write_UINT32(sWS, maskingKey); @@ -125,14 +125,15 @@ static int websocket_write_all(BIO* bio, const BYTE* data, size_t length) return -1; if (BIO_write_blocked(bio)) - status = BIO_wait_write(bio, 100); + { + const long rstatus = BIO_wait_write(bio, 100); + if (rstatus < 0) + return -1; + } else if (BIO_read_blocked(bio)) return -2; /* Abort write, there is data that must be read */ else USleep(100); - - if (status < 0) - return -1; } } @@ -141,24 +142,21 @@ static int websocket_write_all(BIO* bio, const BYTE* data, size_t length) int websocket_write(BIO* bio, const BYTE* buf, int isize, WEBSOCKET_OPCODE opcode) { - size_t payloadSize = 0; size_t fullLen = 0; int status = 0; wStream* sWS = NULL; uint32_t maskingKey = 0; - int streamPos = 0; - WINPR_ASSERT(bio); WINPR_ASSERT(buf); winpr_RAND(&maskingKey, sizeof(maskingKey)); - payloadSize = isize; if (isize < 0) return -1; + const size_t payloadSize = (size_t)isize; if (payloadSize < 126) fullLen = payloadSize + 6; /* 2 byte "mini header" + 4 byte masking key */ else if (payloadSize < 0x10000) @@ -172,30 +170,31 @@ int websocket_write(BIO* bio, const BYTE* buf, int isize, WEBSOCKET_OPCODE opcod Stream_Write_UINT8(sWS, WEBSOCKET_FIN_BIT | opcode); if (payloadSize < 126) - Stream_Write_UINT8(sWS, payloadSize | WEBSOCKET_MASK_BIT); + Stream_Write_UINT8(sWS, (UINT8)payloadSize | WEBSOCKET_MASK_BIT); else if (payloadSize < 0x10000) { Stream_Write_UINT8(sWS, 126 | WEBSOCKET_MASK_BIT); - Stream_Write_UINT16_BE(sWS, payloadSize); + Stream_Write_UINT16_BE(sWS, (UINT16)payloadSize); } else { Stream_Write_UINT8(sWS, 127 | WEBSOCKET_MASK_BIT); /* biggest packet possible is 0xffff + 0xa, so 32bit is always enough */ Stream_Write_UINT32_BE(sWS, 0); - Stream_Write_UINT32_BE(sWS, payloadSize); + Stream_Write_UINT32_BE(sWS, (UINT32)payloadSize); } Stream_Write_UINT32(sWS, maskingKey); /* mask as much as possible with 32bit access */ - for (streamPos = 0; streamPos + 4 <= isize; streamPos += 4) + size_t streamPos = 0; + for (; streamPos + 4 <= payloadSize; streamPos += 4) { uint32_t masked = *((const uint32_t*)(buf + streamPos)) ^ maskingKey; Stream_Write_UINT32(sWS, masked); } /* mask the rest byte by byte */ - for (; streamPos < isize; streamPos++) + for (; streamPos < payloadSize; streamPos++) { BYTE* partialMask = (BYTE*)(&maskingKey) + streamPos % 4; BYTE masked = *((buf + streamPos)) ^ *partialMask; diff --git a/libfreerdp/core/gateway/wst.c b/libfreerdp/core/gateway/wst.c index 2c4430cda..9a98ec5de 100644 --- a/libfreerdp/core/gateway/wst.c +++ b/libfreerdp/core/gateway/wst.c @@ -17,6 +17,8 @@ * limitations under the License. */ +#include + #include #include @@ -143,7 +145,7 @@ static BOOL wst_set_auth_header(rdpCredsspAuth* auth, HttpRequest* request) if (authToken->cbBuffer > INT_MAX) return FALSE; - base64AuthToken = crypto_base64_encode(authToken->pvBuffer, (int)authToken->cbBuffer); + base64AuthToken = crypto_base64_encode(authToken->pvBuffer, authToken->cbBuffer); } if (base64AuthToken) @@ -192,10 +194,10 @@ static BOOL wst_recv_auth_token(rdpCredsspAuth* auth, HttpResponse* response) crypto_base64_decode(token64, len, &authTokenData, &authTokenLength); - if (authTokenLength && authTokenData) + if (authTokenLength && (authTokenLength <= UINT32_MAX) && authTokenData) { authToken.pvBuffer = authTokenData; - authToken.cbBuffer = authTokenLength; + authToken.cbBuffer = (UINT32)authTokenLength; credssp_auth_take_input_buffer(auth, &authToken); } else @@ -363,8 +365,8 @@ static BOOL wst_handle_ok_or_forbidden(rdpWst* wst, HttpResponse** ppresponse, D http_response_free(*ppresponse); *ppresponse = NULL; /* Terminate this connection and make a new one with the Loadbalancing Cookie */ - int fd = BIO_get_fd(wst->tls->bio, NULL); - if (fd >= 0) + const long fd = BIO_get_fd(wst->tls->bio, NULL); + if ((fd >= 0) && (fd <= INT32_MAX)) closesocket((SOCKET)fd); freerdp_tls_free(wst->tls); @@ -561,13 +563,14 @@ static int wst_bio_read(BIO* bio, char* buf, int size) int status = 0; WINPR_ASSERT(bio); WINPR_ASSERT(buf); + WINPR_ASSERT(size >= 0); rdpWst* wst = (rdpWst*)BIO_get_data(bio); WINPR_ASSERT(wst); while (status <= 0) { - status = websocket_read(wst->tls->bio, (BYTE*)buf, size, &wst->wscontext); + status = websocket_read(wst->tls->bio, (BYTE*)buf, (size_t)size, &wst->wscontext); if (status <= 0) { if (!BIO_should_retry(wst->tls->bio)) diff --git a/libfreerdp/core/listener.c b/libfreerdp/core/listener.c index 677ae5a7f..a730da2b0 100644 --- a/libfreerdp/core/listener.c +++ b/libfreerdp/core/listener.c @@ -478,12 +478,12 @@ static BOOL freerdp_listener_check_fds(freerdp_listener* instance) (void)WSAResetEvent(listener->events[i]); int peer_addr_size = sizeof(peer_addr); - int peer_sockfd = + SOCKET peer_sockfd = _accept(listener->sockfds[i], (struct sockaddr*)&peer_addr, &peer_addr_size); - if (peer_sockfd == -1) + if (peer_sockfd == (SOCKET)-1) { - char buffer[8192] = { 0 }; + char buffer[128] = { 0 }; #ifdef _WIN32 int wsa_error = WSAGetLastError(); @@ -501,7 +501,7 @@ static BOOL freerdp_listener_check_fds(freerdp_listener* instance) return FALSE; } - if (!freerdp_check_and_create_client(instance, peer_sockfd, &peer_addr)) + if (!freerdp_check_and_create_client(instance, (int)peer_sockfd, &peer_addr)) return FALSE; } diff --git a/libfreerdp/core/message.c b/libfreerdp/core/message.c index 353e5ec4b..73961a026 100644 --- a/libfreerdp/core/message.c +++ b/libfreerdp/core/message.c @@ -1844,7 +1844,7 @@ static BOOL update_message_process_update_class(rdpUpdateProxy* proxy, wMessage* { const UINT16 imeId = ((size_t)msg->wParam) >> 16 & 0xFFFF; const UINT32 imeState = ((size_t)msg->wParam) & 0xFFFF; - const UINT32 imeConvMode = ((size_t)msg->lParam); + const UINT32 imeConvMode = ((size_t)msg->lParam) & 0xFFFFFFFFUL; rc = IFCALLRESULT(TRUE, proxy->SetKeyboardImeStatus, msg->context, imeId, imeState, imeConvMode); } diff --git a/libfreerdp/core/orders.c b/libfreerdp/core/orders.c index 23a91ba30..ae037507e 100644 --- a/libfreerdp/core/orders.c +++ b/libfreerdp/core/orders.c @@ -1099,7 +1099,7 @@ static INLINE BOOL update_read_delta_points(wStream* s, DELTA_POINT** points, UI static BOOL order_field_flag_is_set(const ORDER_INFO* orderInfo, BYTE number) { - const UINT32 mask = (1UL << ((UINT32)number - 1UL)); + const UINT32 mask = (UINT32)(1UL << ((UINT32)number - 1UL)); const BOOL set = (orderInfo->fieldFlags & mask) != 0; return set; } @@ -2112,7 +2112,10 @@ static BOOL update_read_fast_glyph_order(const char* orderName, wStream* s, return FALSE; } - glyph->cb = Stream_GetRemainingLength(sub); + const size_t slen = Stream_GetRemainingLength(sub); + if (slen > UINT32_MAX) + return FALSE; + glyph->cb = (UINT32)slen; if (glyph->cb > 0) { BYTE* new_aj = (BYTE*)realloc(glyph->aj, glyph->cb); diff --git a/libfreerdp/core/rdp.c b/libfreerdp/core/rdp.c index f2267d1f7..4de49049a 100644 --- a/libfreerdp/core/rdp.c +++ b/libfreerdp/core/rdp.c @@ -766,11 +766,11 @@ static BOOL rdp_security_stream_out(rdpRdp* rdp, wStream* s, size_t length, UINT if (!Stream_CheckAndLogRequiredCapacityWLog(rdp->log, s, 8)) goto unlock; if (sec_flags & SEC_SECURE_CHECKSUM) - status = security_salted_mac_signature(rdp, data, length, TRUE, + status = security_salted_mac_signature(rdp, data, (UINT32)length, TRUE, Stream_Pointer(s), 8); else - status = - security_mac_signature(rdp, data, length, Stream_PointerAs(s, BYTE), 8); + status = security_mac_signature(rdp, data, (UINT32)length, + Stream_PointerAs(s, BYTE), 8); if (!status) goto unlock; diff --git a/libfreerdp/core/redirection.c b/libfreerdp/core/redirection.c index cb9c648c6..46eeffa67 100644 --- a/libfreerdp/core/redirection.c +++ b/libfreerdp/core/redirection.c @@ -122,15 +122,17 @@ static BOOL redirection_copy_array(char*** dst, UINT32* plen, const char** str, { redirection_free_array(dst, plen); + if (len > UINT32_MAX) + return FALSE; if (!str || (len == 0)) return TRUE; *dst = calloc(len, sizeof(char*)); if (!*dst) return FALSE; - *plen = len; + *plen = (UINT32)len; - for (UINT32 x = 0; x < len; x++) + for (size_t x = 0; x < len; x++) { if (str[x]) (*dst)[x] = _strdup(str[x]); @@ -199,11 +201,12 @@ static BOOL rdp_redirection_read_unicode_string(wStream* s, char** str, size_t m static BOOL rdp_redirection_write_data(wStream* s, size_t length, const void* data) { WINPR_ASSERT(data || (length == 0)); + WINPR_ASSERT(length <= UINT32_MAX); if (!Stream_CheckAndLogRequiredCapacity(TAG, s, 4)) return FALSE; - Stream_Write_UINT32(s, length); + Stream_Write_UINT32(s, (UINT32)length); if (!Stream_CheckAndLogRequiredCapacity(TAG, s, length)) return FALSE; @@ -277,7 +280,10 @@ static BOOL rdp_redirection_read_base64_wchar(UINT32 flag, wStream* s, UINT32* p tok = strtok_s(NULL, "\r\n", &saveptr); } - *pLength = wpos; + if (wpos > UINT32_MAX) + goto fail; + + *pLength = (UINT32)wpos; WLog_DBG(TAG, "%s:", rdp_redirection_flags_to_string(flag, buffer, sizeof(buffer))); @@ -324,13 +330,14 @@ static BOOL rdp_target_cert_write_element(wStream* s, UINT32 Type, UINT32 Encodi const BYTE* data, size_t length) { WINPR_ASSERT(data || (length == 0)); + WINPR_ASSERT(length <= UINT32_MAX); if (!Stream_CheckAndLogRequiredCapacity(TAG, s, 12)) return FALSE; Stream_Write_UINT32(s, Type); Stream_Write_UINT32(s, Encoding); - Stream_Write_UINT32(s, length); + Stream_Write_UINT32(s, (UINT32)length); if (!Stream_CheckAndLogRequiredCapacity(TAG, s, length)) return FALSE; @@ -610,13 +617,13 @@ int rdp_redirection_apply_settings(rdpRdp* rdp) BOOL pres = FALSE; size_t length = 0; char* pem = freerdp_certificate_get_pem(cert, &length); - if (pem) + if (pem && (length <= UINT32_MAX)) { pres = freerdp_settings_set_string_len(settings, FreeRDP_RedirectionAcceptedCert, pem, length); if (pres) pres = freerdp_settings_set_uint32(settings, FreeRDP_RedirectionAcceptedCertLength, - length); + (UINT32)length); } free(pem); if (!pres) diff --git a/libfreerdp/core/security.c b/libfreerdp/core/security.c index c7182038c..5a92c241d 100644 --- a/libfreerdp/core/security.c +++ b/libfreerdp/core/security.c @@ -317,7 +317,8 @@ BOOL security_mac_data(const BYTE* mac_salt_key, size_t mac_salt_key_length, con WINPR_ASSERT(output_length == WINPR_MD5_DIGEST_LENGTH); /* MacData = MD5(MacSaltKey + pad2 + SHA1(MacSaltKey + pad1 + length + data)) */ - security_UINT32_le(length_le, sizeof(length_le), length); /* length must be little-endian */ + security_UINT32_le(length_le, sizeof(length_le), + (UINT32)length); /* length must be little-endian */ /* SHA1_Digest = SHA1(MacSaltKey + pad1 + length + data) */ if (!(sha1 = winpr_Digest_New())) diff --git a/libfreerdp/core/server.c b/libfreerdp/core/server.c index 6370e4180..5ea797f65 100644 --- a/libfreerdp/core/server.c +++ b/libfreerdp/core/server.c @@ -24,7 +24,9 @@ #include #include #include +#include +#include #include #include #include @@ -101,7 +103,7 @@ static BOOL wts_queue_send_item(rdpPeerChannel* channel, BYTE* Buffer, UINT32 Le (void*)(UINT_PTR)length); } -static int wts_read_variable_uint(wStream* s, int cbLen, UINT32* val) +static unsigned wts_read_variable_uint(wStream* s, int cbLen, UINT32* val) { WINPR_ASSERT(s); WINPR_ASSERT(val); @@ -264,8 +266,6 @@ static void wts_read_drdynvc_close_response(rdpPeerChannel* channel) static BOOL wts_read_drdynvc_pdu(rdpPeerChannel* channel) { - UINT32 length = 0; - UINT8 value = 0; UINT8 Cmd = 0; UINT8 Sp = 0; UINT8 cbChId = 0; @@ -275,20 +275,20 @@ static BOOL wts_read_drdynvc_pdu(rdpPeerChannel* channel) WINPR_ASSERT(channel); WINPR_ASSERT(channel->vcm); - length = Stream_GetPosition(channel->receiveData); + size_t length = Stream_GetPosition(channel->receiveData); - if (length < 1) + if ((length < 1) || (length > UINT32_MAX)) return FALSE; Stream_SetPosition(channel->receiveData, 0); - Stream_Read_UINT8(channel->receiveData, value); + const UINT8 value = Stream_Get_UINT8(channel->receiveData); length--; Cmd = (value & 0xf0) >> 4; Sp = (value & 0x0c) >> 2; cbChId = (value & 0x03) >> 0; if (Cmd == CAPABILITY_REQUEST_PDU) - return wts_read_drdynvc_capabilities_response(channel, length); + return wts_read_drdynvc_capabilities_response(channel, (UINT32)length); if (channel->vcm->drdynvc_state == DRDYNVC_STATE_READY) { @@ -306,13 +306,13 @@ static BOOL wts_read_drdynvc_pdu(rdpPeerChannel* channel) if (haveChannelId) { - value = wts_read_variable_uint(channel->receiveData, cbChId, &ChannelId); - if (value == 0) + const unsigned val = wts_read_variable_uint(channel->receiveData, cbChId, &ChannelId); + if (val == 0) return FALSE; - length -= value; + length -= val; - DEBUG_DVC("Cmd %s ChannelId %" PRIu32 " length %" PRIu32 "", + DEBUG_DVC("Cmd %s ChannelId %" PRIu32 " length %" PRIuz "", drdynvc_get_packet_type(Cmd), ChannelId, length); dvc = wts_get_dvc_channel_by_id(channel->vcm, ChannelId); if (!dvc) @@ -325,7 +325,7 @@ static BOOL wts_read_drdynvc_pdu(rdpPeerChannel* channel) switch (Cmd) { case CREATE_REQUEST_PDU: - return wts_read_drdynvc_create_response(dvc, channel->receiveData, length); + return wts_read_drdynvc_create_response(dvc, channel->receiveData, (UINT32)length); case DATA_FIRST_PDU: if (dvc->dvc_open_state != DVC_OPEN_STATE_SUCCEEDED) @@ -337,7 +337,7 @@ static BOOL wts_read_drdynvc_pdu(rdpPeerChannel* channel) return TRUE; } - return wts_read_drdynvc_data_first(dvc, channel->receiveData, Sp, length); + return wts_read_drdynvc_data_first(dvc, channel->receiveData, Sp, (UINT32)length); case DATA_PDU: if (dvc->dvc_open_state != DVC_OPEN_STATE_SUCCEEDED) @@ -349,7 +349,7 @@ static BOOL wts_read_drdynvc_pdu(rdpPeerChannel* channel) return TRUE; } - return wts_read_drdynvc_data(dvc, channel->receiveData, length); + return wts_read_drdynvc_data(dvc, channel->receiveData, (UINT32)length); case CLOSE_REQUEST_PDU: wts_read_drdynvc_close_response(dvc); @@ -470,8 +470,12 @@ static BOOL WTSProcessChannelData(rdpPeerChannel* channel, UINT16 channelId, con } else { - ret = wts_queue_receive_data(channel, Stream_Buffer(channel->receiveData), - Stream_GetPosition(channel->receiveData)); + const size_t pos = Stream_GetPosition(channel->receiveData); + if (pos > UINT32_MAX) + ret = FALSE; + else + ret = wts_queue_receive_data(channel, Stream_Buffer(channel->receiveData), + (UINT32)pos); } Stream_SetPosition(channel->receiveData, 0); @@ -561,8 +565,8 @@ BOOL WTSVirtualChannelManagerOpen(HANDLE hServer) if (channel) { - BYTE capaBuffer[12]; - wStream staticS; + BYTE capaBuffer[12] = { 0 }; + wStream staticS = { 0 }; wStream* s = Stream_StaticInit(&staticS, capaBuffer, sizeof(capaBuffer)); vcm->drdynvc_channel = channel; @@ -573,9 +577,10 @@ BOOL WTSVirtualChannelManagerOpen(HANDLE hServer) /* TODO: shall implement version 2 and 3 */ + const size_t pos = Stream_GetPosition(s); + WINPR_ASSERT(pos <= UINT32_MAX); ULONG written = 0; - if (!WTSVirtualChannelWrite(channel, (PCHAR)capaBuffer, Stream_GetPosition(s), - &written)) + if (!WTSVirtualChannelWrite(channel, (PCHAR)capaBuffer, (UINT32)pos, &written)) return FALSE; } } @@ -1411,8 +1416,10 @@ HANDLE WINAPI FreeRDP_WTSVirtualChannelOpenEx(DWORD SessionId, LPSTR pVirtualNam if (!wts_write_drdynvc_create_request(s, channel->channelId, pVirtualName)) goto fail; - if (!WTSVirtualChannelWrite(vcm->drdynvc_channel, Stream_BufferAs(s, char), - Stream_GetPosition(s), &written)) + const size_t pos = Stream_GetPosition(s); + WINPR_ASSERT(pos <= UINT32_MAX); + if (!WTSVirtualChannelWrite(vcm->drdynvc_channel, Stream_BufferAs(s, char), (UINT32)pos, + &written)) goto fail; Stream_Free(s, TRUE); @@ -1469,8 +1476,11 @@ BOOL WINAPI FreeRDP_WTSVirtualChannelClose(HANDLE hChannelHandle) else { wts_write_drdynvc_header(s, CLOSE_REQUEST_PDU, channel->channelId); + + const size_t pos = Stream_GetPosition(s); + WINPR_ASSERT(pos <= UINT32_MAX); ret = WTSVirtualChannelWrite(vcm->drdynvc_channel, Stream_BufferAs(s, char), - Stream_GetPosition(s), &written); + (UINT32)pos, &written); Stream_Free(s, TRUE); } } @@ -1534,8 +1544,6 @@ BOOL WINAPI FreeRDP_WTSVirtualChannelWrite(HANDLE hChannelHandle, PCHAR Buffer, int cbChId = 0; int first = 0; BYTE* buffer = NULL; - UINT32 length = 0; - UINT32 written = 0; UINT32 totalWritten = 0; rdpPeerChannel* channel = (rdpPeerChannel*)hChannelHandle; BOOL ret = FALSE; @@ -1547,7 +1555,7 @@ BOOL WINAPI FreeRDP_WTSVirtualChannelWrite(HANDLE hChannelHandle, PCHAR Buffer, WINPR_ASSERT(channel->vcm); if (channel->channelType == RDP_PEER_CHANNEL_TYPE_SVC) { - length = Length; + const ULONG length = Length; buffer = (BYTE*)malloc(length); if (!buffer) @@ -1600,18 +1608,20 @@ BOOL WINAPI FreeRDP_WTSVirtualChannelWrite(HANDLE hChannelHandle, PCHAR Buffer, } first = FALSE; - written = Stream_GetRemainingLength(s); + size_t written = Stream_GetRemainingLength(s); if (written > Length) written = Length; Stream_Write(s, Buffer, written); - length = Stream_GetPosition(s); + const size_t length = Stream_GetPosition(s); Stream_Free(s, FALSE); + if (length > UINT32_MAX) + goto fail; Length -= written; Buffer += written; totalWritten += written; - if (!wts_queue_send_item(channel->vcm->drdynvc_channel, buffer, length)) + if (!wts_queue_send_item(channel->vcm->drdynvc_channel, buffer, (UINT32)length)) goto fail; } } diff --git a/libfreerdp/core/tcp.c b/libfreerdp/core/tcp.c index 989130f25..e6dc8b5d3 100644 --- a/libfreerdp/core/tcp.c +++ b/libfreerdp/core/tcp.c @@ -499,7 +499,9 @@ static int transport_bio_buffered_write(BIO* bio, const char* buf, int num) while (chunks[i].size) { ERR_clear_error(); - const int status = BIO_write(next_bio, chunks[i].data, chunks[i].size); + + const size_t wr = MIN(INT32_MAX, chunks[i].size); + const int status = BIO_write(next_bio, chunks[i].data, (int)wr); if (status <= 0) { @@ -727,7 +729,7 @@ char* freerdp_tcp_get_peer_address(SOCKET sockfd) struct sockaddr_storage saddr = { 0 }; socklen_t length = sizeof(struct sockaddr_storage); - if (getpeername(sockfd, (struct sockaddr*)&saddr, &length) != 0) + if (getpeername((int)sockfd, (struct sockaddr*)&saddr, &length) != 0) { return NULL; } @@ -853,9 +855,9 @@ static BOOL freerdp_tcp_connect_timeout(rdpContext* context, int sockfd, struct if (WAIT_OBJECT_0 != status) goto fail; - status = recv(sockfd, NULL, 0, 0); + const SSIZE_T res = recv(sockfd, NULL, 0, 0); - if (status == SOCKET_ERROR) + if (res == SOCKET_ERROR) { if (WSAGetLastError() == WSAECONNRESET) goto fail; @@ -901,12 +903,11 @@ static int freerdp_tcp_connect_multi(rdpContext* context, char** hostnames, cons UINT32 sindex = count; int status = -1; SOCKET sockfd = INVALID_SOCKET; - HANDLE* events = NULL; struct addrinfo* addr = NULL; struct addrinfo* result = NULL; - t_peer* peers = NULL; - events = (HANDLE*)calloc(count + 1, sizeof(HANDLE)); - peers = (t_peer*)calloc(count, sizeof(t_peer)); + + HANDLE* events = (HANDLE*)calloc(count + 1, sizeof(HANDLE)); + t_peer* peers = (t_peer*)calloc(count, sizeof(t_peer)); if (!peers || !events || (count < 1)) { @@ -985,7 +986,7 @@ static int freerdp_tcp_connect_multi(rdpContext* context, char** hostnames, cons free(peers); free(events); - return sockfd; + return (int)sockfd; } BOOL freerdp_tcp_set_keep_alive_mode(const rdpSettings* settings, int sockfd) diff --git a/libfreerdp/crypto/er.c b/libfreerdp/crypto/er.c index 0415044c6..845d3eecc 100644 --- a/libfreerdp/crypto/er.c +++ b/libfreerdp/crypto/er.c @@ -21,6 +21,7 @@ #include #include +#include #include #include @@ -62,10 +63,11 @@ void er_read_length(wStream* s, int* length) int er_write_length(wStream* s, int length, BOOL flag) { + WINPR_ASSERT(length >= 0); if (flag) return der_write_length(s, length); else - return ber_write_length(s, length); + return (int)ber_write_length(s, (size_t)length); } int _er_skip_length(int length) diff --git a/libfreerdp/crypto/tls.c b/libfreerdp/crypto/tls.c index 8cd5772f7..f42cd7625 100644 --- a/libfreerdp/crypto/tls.c +++ b/libfreerdp/crypto/tls.c @@ -649,9 +649,7 @@ static SecPkgContext_Bindings* tls_get_channel_bindings(const rdpCertificate* ce { size_t CertificateHashLength = 0; BYTE* ChannelBindingToken = NULL; - UINT32 ChannelBindingTokenLength = 0; SEC_CHANNEL_BINDINGS* ChannelBindings = NULL; - SecPkgContext_Bindings* ContextBindings = NULL; const size_t PrefixLength = strnlen(TLS_SERVER_END_POINT, ARRAYSIZE(TLS_SERVER_END_POINT)); WINPR_ASSERT(cert); @@ -677,20 +675,24 @@ static SecPkgContext_Bindings* tls_get_channel_bindings(const rdpCertificate* ce if (!CertificateHash) return NULL; - ChannelBindingTokenLength = PrefixLength + CertificateHashLength; - ContextBindings = (SecPkgContext_Bindings*)calloc(1, sizeof(SecPkgContext_Bindings)); + const size_t ChannelBindingTokenLength = PrefixLength + CertificateHashLength; + SecPkgContext_Bindings* ContextBindings = calloc(1, sizeof(SecPkgContext_Bindings)); if (!ContextBindings) goto out_free; - ContextBindings->BindingsLength = sizeof(SEC_CHANNEL_BINDINGS) + ChannelBindingTokenLength; + const size_t slen = sizeof(SEC_CHANNEL_BINDINGS) + ChannelBindingTokenLength; + if (slen > UINT32_MAX) + goto out_free; + + ContextBindings->BindingsLength = (UINT32)slen; ChannelBindings = (SEC_CHANNEL_BINDINGS*)calloc(1, ContextBindings->BindingsLength); if (!ChannelBindings) goto out_free; ContextBindings->Bindings = ChannelBindings; - ChannelBindings->cbApplicationDataLength = ChannelBindingTokenLength; + ChannelBindings->cbApplicationDataLength = (UINT32)ChannelBindingTokenLength; ChannelBindings->dwApplicationDataOffset = sizeof(SEC_CHANNEL_BINDINGS); ChannelBindingToken = &((BYTE*)ChannelBindings)[ChannelBindings->dwApplicationDataOffset]; memcpy(ChannelBindingToken, TLS_SERVER_END_POINT, PrefixLength); @@ -928,7 +930,7 @@ TlsHandshakeResult freerdp_tls_handshake(rdpTls* tls) TlsHandshakeResult ret = TLS_HANDSHAKE_ERROR; WINPR_ASSERT(tls); - int status = BIO_do_handshake(tls->bio); + const long status = BIO_do_handshake(tls->bio); if (status != 1) { if (!BIO_should_retry(tls->bio)) @@ -1462,10 +1464,12 @@ static BOOL accept_cert(rdpTls* tls, const rdpCertificate* cert) size_t pemLength = 0; char* pem = freerdp_certificate_get_pem_ex(cert, &pemLength, FALSE); - BOOL rc = FALSE; - if (freerdp_settings_set_string_len(settings, id, pem, pemLength)) - rc = freerdp_settings_set_uint32(settings, lid, pemLength); + if (pemLength <= UINT32_MAX) + { + if (freerdp_settings_set_string_len(settings, id, pem, pemLength)) + rc = freerdp_settings_set_uint32(settings, lid, (UINT32)pemLength); + } free(pem); return rc; } diff --git a/libfreerdp/emu/scard/smartcard_emulate.c b/libfreerdp/emu/scard/smartcard_emulate.c index 10b64e046..221418ac3 100644 --- a/libfreerdp/emu/scard/smartcard_emulate.c +++ b/libfreerdp/emu/scard/smartcard_emulate.c @@ -170,25 +170,28 @@ static BOOL scard_status_transition(SCardContext* context) return TRUE; } -static UINT32 scard_copy_strings(SCardContext* ctx, void* dst, UINT32 dstSize, const void* src, - UINT32 srcSize) +static UINT32 scard_copy_strings(SCardContext* ctx, void* dst, size_t dstSize, const void* src, + size_t srcSize) { WINPR_ASSERT(ctx); WINPR_ASSERT(dst); + WINPR_ASSERT(srcSize <= UINT32_MAX); + WINPR_ASSERT(dstSize <= UINT32_MAX); + if (dstSize == SCARD_AUTOALLOCATE) { void* tmp = malloc(srcSize); memcpy(tmp, src, srcSize); ArrayList_Append(ctx->strings, tmp); *((void**)dst) = tmp; - return srcSize; + return (UINT32)srcSize; } else { - UINT32 min = MIN(dstSize, srcSize); + const size_t min = MIN(dstSize, srcSize); memcpy(dst, src, min); - return min; + return (UINT32)min; } } @@ -571,7 +574,10 @@ LONG WINAPI Emulate_SCardListReadersW(SmartcardEmulationContext* smartcard, SCAR /* Return length only */ if (!mszReaders) - *pcchReaders = g_ReaderNameWLen; + { + WINPR_ASSERT(g_ReaderNameWLen <= UINT32_MAX); + *pcchReaders = (UINT32)g_ReaderNameWLen; + } else { *pcchReaders = scard_copy_strings(value, mszReaders, *pcchReaders, g_ReaderNameW, diff --git a/libfreerdp/emu/scard/smartcard_virtual_gids.c b/libfreerdp/emu/scard/smartcard_virtual_gids.c index 2c231c808..fb3f72e32 100644 --- a/libfreerdp/emu/scard/smartcard_virtual_gids.c +++ b/libfreerdp/emu/scard/smartcard_virtual_gids.c @@ -294,8 +294,10 @@ create_failed: return NULL; } -static BOOL vgids_write_tlv(wStream* s, UINT16 tag, const void* data, DWORD dataSize) +static BOOL vgids_write_tlv(wStream* s, UINT16 tag, const void* data, size_t dataSize) { + WINPR_ASSERT(dataSize <= UINT16_MAX); + /* A maximum of 5 additional bytes is needed */ if (!Stream_EnsureRemainingCapacity(s, dataSize + 5)) { diff --git a/libfreerdp/gdi/region.c b/libfreerdp/gdi/region.c index df122e90e..903959c60 100644 --- a/libfreerdp/gdi/region.c +++ b/libfreerdp/gdi/region.c @@ -25,6 +25,8 @@ #include #include +#include + #include #include #include @@ -96,8 +98,8 @@ HGDI_RGN gdi_CreateRectRgn(INT32 nLeftRect, INT32 nTopRect, INT32 nRightRect, IN hRgn->objectType = GDIOBJECT_REGION; hRgn->x = nLeftRect; hRgn->y = nTopRect; - hRgn->w = w; - hRgn->h = h; + hRgn->w = (INT32)w; + hRgn->h = (INT32)h; hRgn->null = FALSE; return hRgn; } @@ -160,8 +162,8 @@ BOOL gdi_RectToRgn(const HGDI_RECT rect, HGDI_RGN rgn) rgn->x = rect->left; rgn->y = rect->top; - rgn->w = w; - rgn->h = h; + rgn->w = (INT32)w; + rgn->h = (INT32)h; return rc; } @@ -199,8 +201,8 @@ BOOL gdi_CRectToRgn(INT32 left, INT32 top, INT32 right, INT32 bottom, HGDI_RGN r rgn->x = left; rgn->y = top; - rgn->w = w; - rgn->h = h; + rgn->w = (INT32)w; + rgn->h = (INT32)h; return rc; } @@ -227,7 +229,7 @@ BOOL gdi_RectToCRgn(const HGDI_RECT rect, INT32* x, INT32* y, INT32* w, INT32* h rc = FALSE; } else - *w = tmp; + *w = (INT32)tmp; tmp = rect->bottom - rect->top + 1; if ((tmp < 0) || (tmp > INT32_MAX)) { @@ -237,7 +239,7 @@ BOOL gdi_RectToCRgn(const HGDI_RECT rect, INT32* x, INT32* y, INT32* w, INT32* h rc = FALSE; } else - *h = tmp; + *h = (INT32)tmp; return rc; } @@ -276,8 +278,8 @@ BOOL gdi_CRectToCRgn(INT32 left, INT32 top, INT32 right, INT32 bottom, INT32* x, *x = left; *y = top; - *w = wl; - *h = hl; + *w = (INT32)wl; + *h = (INT32)hl; return rc; } @@ -305,8 +307,8 @@ BOOL gdi_RgnToRect(const HGDI_RGN rgn, HGDI_RECT rect) } rect->left = rgn->x; rect->top = rgn->y; - rect->right = r; - rect->bottom = b; + rect->right = (INT32)r; + rect->bottom = (INT32)b; return rc; } @@ -320,13 +322,17 @@ BOOL gdi_RgnToRect(const HGDI_RGN rgn, HGDI_RECT rect) * @param rect destination rectangle */ -INLINE BOOL gdi_CRgnToRect(INT64 x, INT64 y, INT32 w, INT32 h, HGDI_RECT rect) +BOOL gdi_CRgnToRect(INT64 x, INT64 y, INT32 w, INT32 h, HGDI_RECT rect) { BOOL invalid = FALSE; const INT64 r = x + w - 1; const INT64 b = y + h - 1; - rect->left = (x > 0) ? x : 0; - rect->top = (y > 0) ? y : 0; + WINPR_ASSERT(x <= INT32_MAX); + WINPR_ASSERT(y <= INT32_MAX); + WINPR_ASSERT(r <= INT32_MAX); + WINPR_ASSERT(b <= INT32_MAX); + rect->left = (x > 0) ? (INT32)x : 0; + rect->top = (y > 0) ? (INT32)y : 0; rect->right = rect->left; rect->bottom = rect->top; @@ -334,12 +340,12 @@ INLINE BOOL gdi_CRgnToRect(INT64 x, INT64 y, INT32 w, INT32 h, HGDI_RECT rect) invalid = TRUE; if (r > 0) - rect->right = r; + rect->right = (INT32)r; else invalid = TRUE; if (b > 0) - rect->bottom = b; + rect->bottom = (INT32)b; else invalid = TRUE; @@ -632,7 +638,7 @@ INLINE BOOL gdi_InvalidateRegion(HGDI_DC hdc, INT32 x, INT32 y, INT32 w, INT32 h if (!new_rgn) return FALSE; - hdc->hwnd->count = new_cnt; + hdc->hwnd->count = (UINT32)new_cnt; cinvalid = new_rgn; } diff --git a/libfreerdp/locale/keyboard.c b/libfreerdp/locale/keyboard.c index 9de4489eb..4f00601a5 100644 --- a/libfreerdp/locale/keyboard.c +++ b/libfreerdp/locale/keyboard.c @@ -263,10 +263,11 @@ static int freerdp_keyboard_init_apple(const DWORD* keyboardLayoutId, { WINPR_ASSERT(x11_keycode_to_rdp_scancode); WINPR_ASSERT(keyboardLayoutId); - + WINPR_ASSERT(count <= UINT32_MAX); for (size_t keycode = 8; keycode < count; keycode++) { - const DWORD vkcode = GetVirtualKeyCodeFromKeycode(keycode - 8u, WINPR_KEYCODE_TYPE_APPLE); + const DWORD vkcode = + GetVirtualKeyCodeFromKeycode((UINT32)keycode - 8u, WINPR_KEYCODE_TYPE_APPLE); x11_keycode_to_rdp_scancode[keycode] = GetVirtualScanCodeFromVirtualKeyCode(vkcode, WINPR_KBD_TYPE_IBM_ENHANCED); } @@ -280,9 +281,12 @@ static int freerdp_keyboard_init_x11_evdev(const DWORD* keyboardLayoutId, { WINPR_ASSERT(keyboardLayoutId); WINPR_ASSERT(x11_keycode_to_rdp_scancode); + WINPR_ASSERT(count <= UINT32_MAX); + for (size_t keycode = 0; keycode < count; keycode++) { - const DWORD vkcode = GetVirtualKeyCodeFromKeycode(keycode, WINPR_KEYCODE_TYPE_EVDEV); + const DWORD vkcode = + GetVirtualKeyCodeFromKeycode((UINT32)keycode, WINPR_KEYCODE_TYPE_EVDEV); x11_keycode_to_rdp_scancode[keycode] = GetVirtualScanCodeFromVirtualKeyCode(vkcode, WINPR_KBD_TYPE_IBM_ENHANCED); } @@ -332,7 +336,7 @@ DWORD freerdp_keyboard_init(DWORD keyboardLayoutId) const DWORD x11 = X11_KEYCODE_TO_VIRTUAL_SCANCODE[keycode]; const DWORD sc = RDP_SCANCODE_CODE(x11); const BOOL ex = RDP_SCANCODE_EXTENDED(x11); - VIRTUAL_SCANCODE_TO_X11_KEYCODE[sc][ex ? 1 : 0] = keycode; + VIRTUAL_SCANCODE_TO_X11_KEYCODE[sc][ex ? 1 : 0] = (UINT32)keycode; } return keyboardLayoutId; diff --git a/libfreerdp/primitives/prim_YUV.c b/libfreerdp/primitives/prim_YUV.c index 59dbb7973..5c671d432 100644 --- a/libfreerdp/primitives/prim_YUV.c +++ b/libfreerdp/primitives/prim_YUV.c @@ -62,18 +62,18 @@ static pstatus_t general_LumaToYUV444(const BYTE* WINPR_RESTRICT pSrcRaw[3], /* The first half of U, V are already here part of this frame. */ /* B2 and B3 */ - for (size_t y = 0; y < halfHeight; y++) + for (UINT32 y = 0; y < halfHeight; y++) { - const UINT32 val2y = (2ULL * y + evenY); + const UINT32 val2y = (2UL * y + evenY); const UINT32 val2y1 = val2y + oddY; - const BYTE* Um = pSrc[1] + y * srcStep[1]; - const BYTE* Vm = pSrc[2] + y * srcStep[2]; + const BYTE* Um = pSrc[1] + 1ULL * y * srcStep[1]; + const BYTE* Vm = pSrc[2] + 1ULL * y * srcStep[2]; BYTE* pU = pDst[1] + 1ULL * dstStep[1] * val2y; BYTE* pV = pDst[2] + 1ULL * dstStep[2] * val2y; BYTE* pU1 = pDst[1] + 1ULL * dstStep[1] * val2y1; BYTE* pV1 = pDst[2] + 1ULL * dstStep[2] * val2y1; - for (size_t x = 0; x < halfWidth; x++) + for (UINT32 x = 0; x < halfWidth; x++) { const UINT32 val2x = 2UL * x + evenX; const UINT32 val2x1 = val2x + oddX; @@ -194,15 +194,15 @@ static pstatus_t general_ChromaV1ToYUV444(const BYTE* WINPR_RESTRICT pSrcRaw[3], } /* B6 and B7 */ - for (size_t y = 0; y < halfHeight; y++) + for (UINT32 y = 0; y < halfHeight; y++) { - const UINT32 val2y = (y * 2ULL + evenY); - const BYTE* Ua = pSrc[1] + y * srcStep[1]; - const BYTE* Va = pSrc[2] + y * srcStep[2]; + const UINT32 val2y = (y * 2UL + evenY); + const BYTE* Ua = pSrc[1] + 1ULL * y * srcStep[1]; + const BYTE* Va = pSrc[2] + 1ULL * y * srcStep[2]; BYTE* pU = pDst[1] + 1ULL * dstStep[1] * val2y; BYTE* pV = pDst[2] + 1ULL * dstStep[2] * val2y; - for (size_t x = 0; x < halfWidth; x++) + for (UINT32 x = 0; x < halfWidth; x++) { const UINT32 val2x1 = (x * 2 + oddX); pU[val2x1] = Ua[x]; @@ -235,9 +235,9 @@ static pstatus_t general_ChromaV2ToYUV444(const BYTE* WINPR_RESTRICT pSrc[3], BYTE* pU = pDst[1] + 1ULL * dstStep[1] * yTop + roi->left; BYTE* pV = pDst[2] + 1ULL * dstStep[2] * yTop + roi->left; - for (size_t x = 0; x < halfWidth; x++) + for (UINT32 x = 0; x < halfWidth; x++) { - const UINT32 odd = 2 * x + 1; + const UINT32 odd = 2UL * x + 1UL; pU[odd] = *pYaU++; pV[odd] = *pYaV++; } @@ -1047,21 +1047,21 @@ static INLINE pstatus_t general_RGBToAVC444YUV_BGRX(const BYTE* WINPR_RESTRICT p */ const BYTE* pMaxSrc = pSrc + 1ULL * (roi->height - 1) * srcStep; - for (size_t y = 0; y < roi->height; y += 2) + for (UINT32 y = 0; y < roi->height; y += 2) { const BOOL last = (y >= (roi->height - 1)); - const BYTE* srcEven = y < roi->height ? pSrc + y * srcStep : pMaxSrc; - const BYTE* srcOdd = !last ? pSrc + (y + 1) * srcStep : pMaxSrc; + const BYTE* srcEven = y < roi->height ? pSrc + 1ULL * y * srcStep : pMaxSrc; + const BYTE* srcOdd = !last ? pSrc + 1ULL * (y + 1) * srcStep : pMaxSrc; const UINT32 i = y >> 1; const UINT32 n = (i & ~7) + i; - BYTE* b1Even = pDst1[0] + y * dst1Step[0]; + BYTE* b1Even = pDst1[0] + 1ULL * y * dst1Step[0]; BYTE* b1Odd = !last ? (b1Even + dst1Step[0]) : NULL; - BYTE* b2 = pDst1[1] + (y / 2) * dst1Step[1]; - BYTE* b3 = pDst1[2] + (y / 2) * dst1Step[2]; + BYTE* b2 = pDst1[1] + 1ULL * (y / 2) * dst1Step[1]; + BYTE* b3 = pDst1[2] + 1ULL * (y / 2) * dst1Step[2]; BYTE* b4 = pDst2[0] + 1ULL * dst2Step[0] * n; BYTE* b5 = b4 + 8ULL * dst2Step[0]; - BYTE* b6 = pDst2[1] + (y / 2) * dst2Step[1]; - BYTE* b7 = pDst2[2] + (y / 2) * dst2Step[2]; + BYTE* b6 = pDst2[1] + 1ULL * (y / 2) * dst2Step[1]; + BYTE* b7 = pDst2[2] + 1ULL * (y / 2) * dst2Step[2]; general_RGBToAVC444YUV_BGRX_DOUBLE_ROW(srcEven, srcOdd, b1Even, b1Odd, b2, b3, b4, b5, b6, b7, roi->width); } @@ -1188,21 +1188,21 @@ static INLINE pstatus_t general_RGBToAVC444YUV_RGBX(const BYTE* WINPR_RESTRICT p */ const BYTE* pMaxSrc = pSrc + 1ULL * (roi->height - 1) * srcStep; - for (size_t y = 0; y < roi->height; y += 2) + for (UINT32 y = 0; y < roi->height; y += 2) { const BOOL last = (y >= (roi->height - 1)); - const BYTE* srcEven = y < roi->height ? pSrc + y * srcStep : pMaxSrc; - const BYTE* srcOdd = !last ? pSrc + (y + 1) * srcStep : pMaxSrc; + const BYTE* srcEven = y < roi->height ? pSrc + 1ULL * y * srcStep : pMaxSrc; + const BYTE* srcOdd = !last ? pSrc + 1ULL * (y + 1) * srcStep : pMaxSrc; const UINT32 i = y >> 1; const UINT32 n = (i & ~7) + i; - BYTE* b1Even = pDst1[0] + y * dst1Step[0]; + BYTE* b1Even = pDst1[0] + 1ULL * y * dst1Step[0]; BYTE* b1Odd = !last ? (b1Even + dst1Step[0]) : NULL; - BYTE* b2 = pDst1[1] + (y / 2) * dst1Step[1]; - BYTE* b3 = pDst1[2] + (y / 2) * dst1Step[2]; + BYTE* b2 = pDst1[1] + 1ULL * (y / 2) * dst1Step[1]; + BYTE* b3 = pDst1[2] + 1ULL * (y / 2) * dst1Step[2]; BYTE* b4 = pDst2[0] + 1ULL * dst2Step[0] * n; BYTE* b5 = b4 + 8ULL * dst2Step[0]; - BYTE* b6 = pDst2[1] + (y / 2) * dst2Step[1]; - BYTE* b7 = pDst2[2] + (y / 2) * dst2Step[2]; + BYTE* b6 = pDst2[1] + 1ULL * (y / 2) * dst2Step[1]; + BYTE* b7 = pDst2[2] + 1ULL * (y / 2) * dst2Step[2]; general_RGBToAVC444YUV_RGBX_DOUBLE_ROW(srcEven, srcOdd, b1Even, b1Odd, b2, b3, b4, b5, b6, b7, roi->width); } @@ -1391,10 +1391,12 @@ static INLINE pstatus_t general_RGBToAVC444YUV_ANY( for (size_t y = 0; y < roi->height; y += 2) { + WINPR_ASSERT(y < UINT32_MAX); + const BOOL last = (y >= (roi->height - 1)); const BYTE* srcEven = y < roi->height ? pSrc + y * srcStep : pMaxSrc; const BYTE* srcOdd = !last ? pSrc + (y + 1) * srcStep : pMaxSrc; - const UINT32 i = y >> 1; + const UINT32 i = (UINT32)y >> 1; const UINT32 n = (i & ~7) + i; BYTE* b1Even = pDst1[0] + y * dst1Step[0]; BYTE* b1Odd = !last ? (b1Even + dst1Step[0]) : NULL; diff --git a/libfreerdp/primitives/prim_set.c b/libfreerdp/primitives/prim_set.c index 19caa71db..3fe5ce44d 100644 --- a/libfreerdp/primitives/prim_set.c +++ b/libfreerdp/primitives/prim_set.c @@ -67,7 +67,9 @@ static pstatus_t general_set_32s(INT32 val, INT32* pDst, UINT32 len) if (thiswidth > remaining) thiswidth = remaining; - prims->copy_8u((BYTE*)dptr, (BYTE*)(dptr + span), thiswidth << 2); + const size_t s = thiswidth << 2; + WINPR_ASSERT(thiswidth <= INT32_MAX); + prims->copy_8u((BYTE*)dptr, (BYTE*)(dptr + span), (INT32)s); remaining -= thiswidth; span <<= 1; } @@ -104,7 +106,9 @@ static pstatus_t general_set_32u(UINT32 val, UINT32* pDst, UINT32 len) if (thiswidth > remaining) thiswidth = remaining; - prims->copy_8u((BYTE*)dptr, (BYTE*)(dptr + span), thiswidth << 2); + const size_t s = thiswidth << 2; + WINPR_ASSERT(thiswidth <= INT32_MAX); + prims->copy_8u((BYTE*)dptr, (BYTE*)(dptr + span), (INT32)s); remaining -= thiswidth; span <<= 1; } diff --git a/libfreerdp/primitives/sse/prim_YUV_ssse3.c b/libfreerdp/primitives/sse/prim_YUV_ssse3.c index 0638ef9f5..4cfc90134 100644 --- a/libfreerdp/primitives/sse/prim_YUV_ssse3.c +++ b/libfreerdp/primitives/sse/prim_YUV_ssse3.c @@ -735,8 +735,8 @@ static pstatus_t ssse3_RGBToAVC444YUV_BGRX(const BYTE* WINPR_RESTRICT pSrc, UINT const BOOL last = (y >= (roi->height - 1)); const BYTE* srcEven = y < roi->height ? pSrc + y * srcStep : pMaxSrc; const BYTE* srcOdd = !last ? pSrc + (y + 1) * srcStep : pMaxSrc; - const UINT32 i = y >> 1; - const UINT32 n = (i & ~7) + i; + const size_t i = y >> 1; + const size_t n = (i & ~7) + i; BYTE* b1Even = pDst1[0] + y * dst1Step[0]; BYTE* b1Odd = !last ? (b1Even + dst1Step[0]) : NULL; BYTE* b2 = pDst1[1] + (y / 2) * dst1Step[1]; @@ -1156,8 +1156,8 @@ static pstatus_t ssse3_LumaToYUV444(const BYTE* WINPR_RESTRICT pSrcRaw[], const for (; x < halfWidth; x++) { - const UINT32 val2x = 2 * x + evenX; - const UINT32 val2x1 = val2x + oddX; + const size_t val2x = 2 * x + evenX; + const size_t val2x1 = val2x + oddX; pU[val2x] = Um[x]; pV[val2x] = Vm[x]; pU[val2x1] = Um[x]; @@ -1209,8 +1209,8 @@ static pstatus_t ssse3_ChromaFilter(BYTE* WINPR_RESTRICT pDst[], const UINT32 ds for (size_t y = roi->top; y < halfHeight + roi->top; y++) { size_t x = roi->left; - const UINT32 val2y = (y * 2 + evenY); - const UINT32 val2y1 = val2y + oddY; + const size_t val2y = (y * 2ULL + evenY); + const size_t val2y1 = val2y + oddY; BYTE* pU1 = pDst[1] + 1ULL * dstStep[1] * val2y1; BYTE* pV1 = pDst[2] + 1ULL * dstStep[2] * val2y1; BYTE* pU = pDst[1] + 1ULL * dstStep[1] * val2y; @@ -1227,8 +1227,8 @@ static pstatus_t ssse3_ChromaFilter(BYTE* WINPR_RESTRICT pDst[], const UINT32 ds for (; x < halfWidth + roi->left; x++) { - const UINT32 val2x = (x * 2); - const UINT32 val2x1 = val2x + 1; + const size_t val2x = (x * 2ULL); + const size_t val2x1 = val2x + 1ULL; const BYTE inU = pU[val2x]; const BYTE inV = pV[val2x]; const INT32 up = inU * 4; @@ -1337,7 +1337,7 @@ static pstatus_t ssse3_ChromaV1ToYUV444(const BYTE* WINPR_RESTRICT pSrcRaw[3], for (; x < halfWidth; x++) { - const UINT32 val2x1 = (x * 2 + oddX); + const size_t val2x1 = (x * 2ULL + oddX); pU[val2x1] = Ua[x]; pV[val2x1] = Va[x]; } @@ -1401,7 +1401,7 @@ static pstatus_t ssse3_ChromaV2ToYUV444(const BYTE* WINPR_RESTRICT pSrc[3], cons for (; x < halfWidth; x++) { - const UINT32 odd = 2 * x + 1; + const size_t odd = 2ULL * x + 1; pU[odd] = pYaU[x]; pV[odd] = pYaV[x]; } diff --git a/libfreerdp/primitives/sse/prim_add_sse3.c b/libfreerdp/primitives/sse/prim_add_sse3.c index dc85e1ed2..59fce7427 100644 --- a/libfreerdp/primitives/sse/prim_add_sse3.c +++ b/libfreerdp/primitives/sse/prim_add_sse3.c @@ -55,7 +55,7 @@ static pstatus_t sse3_add_16s_inplace(INT16* WINPR_RESTRICT pSrcDst1, const size_t rem = ((UINT_PTR)dptr1 & 0xf) / sizeof(INT16); if (rem != 0) { - const size_t add = 16 - rem; + const UINT32 add = 16 - (UINT32)rem; pstatus_t status = generic->add_16s_inplace(dptr1, dptr2, add); if (status != PRIMITIVES_SUCCESS) return status; diff --git a/libfreerdp/primitives/sse/prim_copy_avx2.c b/libfreerdp/primitives/sse/prim_copy_avx2.c index e5707116e..3a9dc3b6e 100644 --- a/libfreerdp/primitives/sse/prim_copy_avx2.c +++ b/libfreerdp/primitives/sse/prim_copy_avx2.c @@ -58,7 +58,7 @@ static INLINE pstatus_t avx2_image_copy_bgr24_bgrx32(BYTE* WINPR_RESTRICT pDstDa 0xff0b0a09, 0xff080706, 0xff050403, 0xff020100); const __m256i shelpmask = _mm256_set_epi32(0xffffffff, 0xffffffff, 0xffffff1f, 0xff1e1d1c, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff); - const SSIZE_T rem = nWidth % 8; + const UINT32 rem = nWidth % 8; const SSIZE_T width = nWidth - rem; const size_t align = nSrcStep % 32; @@ -126,7 +126,7 @@ static INLINE pstatus_t avx2_image_copy_bgrx32_bgrx32(BYTE* WINPR_RESTRICT pDstD (char)0xFF, (char)0xFF, (char)0xFF, 0x00, (char)0xFF, (char)0xFF, (char)0xFF, 0x00, (char)0xFF, (char)0xFF, (char)0xFF, 0x00, (char)0xFF, (char)0xFF, (char)0xFF, 0x00, (char)0xFF, (char)0xFF, (char)0xFF, 0x00, (char)0xFF, (char)0xFF, (char)0xFF, 0x00); - const SSIZE_T rem = nWidth % 8; + const UINT32 rem = nWidth % 8; const SSIZE_T width = nWidth - rem; for (SSIZE_T y = 0; y < nHeight; y++) { diff --git a/libfreerdp/primitives/sse/prim_copy_sse4_1.c b/libfreerdp/primitives/sse/prim_copy_sse4_1.c index 1458118ae..7b50777b6 100644 --- a/libfreerdp/primitives/sse/prim_copy_sse4_1.c +++ b/libfreerdp/primitives/sse/prim_copy_sse4_1.c @@ -54,7 +54,7 @@ static INLINE pstatus_t sse_image_copy_bgr24_bgrx32(BYTE* WINPR_RESTRICT pDstDat const __m128i mask = _mm_set_epi32(0xFF000000, 0xFF000000, 0xFF000000, 0xFF000000); const __m128i smask = _mm_set_epi32(0xff0b0a09, 0xff080706, 0xff050403, 0xff020100); - const SSIZE_T rem = nWidth % 4; + const UINT32 rem = nWidth % 4; const size_t align = nSrcStep % 64; const BOOL fast = (align == 0) ? TRUE : (align >= 16 - MIN(16, (size_t)rem) ? TRUE : FALSE); @@ -110,7 +110,7 @@ static INLINE pstatus_t sse_image_copy_bgrx32_bgrx32(BYTE* WINPR_RESTRICT pDstDa const __m128i mask = _mm_setr_epi8((char)0xFF, (char)0xFF, (char)0xFF, 0x00, (char)0xFF, (char)0xFF, (char)0xFF, 0x00, (char)0xFF, (char)0xFF, (char)0xFF, 0x00, (char)0xFF, (char)0xFF, (char)0xFF, 0x00); - const SSIZE_T rem = nWidth % 4; + const UINT32 rem = nWidth % 4; const SSIZE_T width = nWidth - rem; for (SSIZE_T y = 0; y < nHeight; y++) { diff --git a/libfreerdp/utils/http.c b/libfreerdp/utils/http.c index 66894e7a3..2633310b3 100644 --- a/libfreerdp/utils/http.c +++ b/libfreerdp/utils/http.c @@ -82,7 +82,9 @@ static int get_line(BIO* bio, char* buffer, size_t size) } } while (1); #else - return BIO_get_line(bio, buffer, size); + if (size > INT32_MAX) + return -1; + return BIO_get_line(bio, buffer, (int)size); #endif } @@ -190,7 +192,11 @@ BOOL freerdp_http_request(const char* url, const char* body, long* status_code, WLog_Print(log, WLOG_DEBUG, "headers:\n%s", headers); ERR_clear_error(); - if (BIO_write(bio, headers, strnlen(headers, size)) < 0) + const size_t hlen = strnlen(headers, size); + if (hlen > INT32_MAX) + goto out; + + if (BIO_write(bio, headers, (int)hlen) < 0) { log_errors(log, "could not write headers"); goto out; @@ -207,7 +213,7 @@ BOOL freerdp_http_request(const char* url, const char* body, long* status_code, } ERR_clear_error(); - if (BIO_write(bio, body, blen) < 0) + if (BIO_write(bio, body, (int)blen) < 0) { log_errors(log, "could not write body"); goto out; @@ -266,17 +272,20 @@ BOOL freerdp_http_request(const char* url, const char* body, long* status_code, goto out; BYTE* p = *response; - int left = *response_length; + size_t left = *response_length; while (left > 0) { - status = BIO_read(bio, p, left); + const int rd = (left < INT32_MAX) ? (int)left : INT32_MAX; + status = BIO_read(bio, p, rd); if (status <= 0) { log_errors(log, "could not read response"); goto out; } p += status; - left -= status; + if ((size_t)status > left) + break; + left -= (size_t)status; } } diff --git a/libfreerdp/utils/passphrase.c b/libfreerdp/utils/passphrase.c index be7934eae..e73ad4e2c 100644 --- a/libfreerdp/utils/passphrase.c +++ b/libfreerdp/utils/passphrase.c @@ -224,7 +224,8 @@ static const char* freerdp_passphrase_read_askpass(const char* prompt, char* buf FILE* askproc = popen(command, "r"); if (!askproc) return NULL; - if (fgets(buf, bufsiz, askproc) != NULL) + WINPR_ASSERT(bufsiz <= INT32_MAX); + if (fgets(buf, (int)bufsiz, askproc) != NULL) buf[strcspn(buf, "\r\n")] = '\0'; else buf = NULL; diff --git a/libfreerdp/utils/pcap.c b/libfreerdp/utils/pcap.c index bd4e274e4..c18ae96f5 100644 --- a/libfreerdp/utils/pcap.c +++ b/libfreerdp/utils/pcap.c @@ -121,14 +121,14 @@ BOOL pcap_add_record(rdpPcap* pcap, const void* data, size_t length) return FALSE; record->cdata = data; - record->length = length; + record->length = (UINT32)length; record->header.incl_len = (UINT32)length; record->header.orig_len = (UINT32)length; const UINT64 ns = winpr_GetUnixTimeNS(); - record->header.ts_sec = WINPR_TIME_NS_TO_S(ns); - record->header.ts_usec = WINPR_TIME_NS_REM_US(ns); + record->header.ts_sec = (UINT32)WINPR_TIME_NS_TO_S(ns); + record->header.ts_usec = (UINT32)WINPR_TIME_NS_REM_US(ns); if (pcap->tail == NULL) { diff --git a/server/Sample/sfreerdp.c b/server/Sample/sfreerdp.c index c8193b17a..8647bb52d 100644 --- a/server/Sample/sfreerdp.c +++ b/server/Sample/sfreerdp.c @@ -268,8 +268,10 @@ static BOOL test_peer_draw_background(freerdp_peer* client) { WLog_DBG(TAG, "Using RemoteFX codec"); rfx_context_set_pixel_format(context->rfx_context, colorFormat); + + WINPR_ASSERT(bpp <= UINT16_MAX); if (!rfx_compose_message(context->rfx_context, s, &rect, 1, rgb_data, rect.width, - rect.height, rect.width * bpp)) + rect.height, (UINT32)(bpp * rect.width))) { goto out; } @@ -284,8 +286,10 @@ static BOOL test_peer_draw_background(freerdp_peer* client) { WLog_DBG(TAG, "Using NSCodec"); nsc_context_set_parameters(context->nsc_context, NSC_COLOR_FORMAT, colorFormat); + + WINPR_ASSERT(bpp <= UINT16_MAX); nsc_compose_message(context->nsc_context, s, rgb_data, rect.width, rect.height, - rect.width * bpp); + (UINT32)(bpp * rect.width)); const UINT32 NSCodecId = freerdp_settings_get_uint32(settings, FreeRDP_NSCodecId); WINPR_ASSERT(NSCodecId <= UINT16_MAX); cmd.bmp.codecID = (UINT16)NSCodecId; @@ -1043,7 +1047,12 @@ static int hook_peer_write_pdu(rdpTransport* transport, wStream* s) if ((last_ts > 0) && (ts > last_ts)) { UINT64 diff = ts - last_ts; - Sleep(diff); + while (diff > 0) + { + UINT32 d = diff > UINT32_MAX ? UINT32_MAX : (UINT32)diff; + diff -= d; + Sleep(d); + } } last_ts = ts; rc = peerCtx->io.WritePdu(transport, ls); diff --git a/server/proxy/channels/pf_channel_drdynvc.c b/server/proxy/channels/pf_channel_drdynvc.c index 112d39941..2a1a3d0a6 100644 --- a/server/proxy/channels/pf_channel_drdynvc.c +++ b/server/proxy/channels/pf_channel_drdynvc.c @@ -363,11 +363,11 @@ static PfChannelResult DynvcTrackerPeekFn(ChannelStateTracker* tracker, BOOL fir const size_t nameLen = Stream_GetRemainingLength(s); const size_t len = strnlen(name, nameLen); - if ((len == 0) || (len == nameLen)) + if ((len == 0) || (len == nameLen) || (dynChannelId > UINT16_MAX)) return PF_CHANNEL_RESULT_ERROR; wStream* currentPacket = channelTracker_getCurrentPacket(tracker); - dev.channel_id = dynChannelId; + dev.channel_id = (UINT16)dynChannelId; dev.channel_name = name; dev.data = Stream_Buffer(s); dev.data_len = Stream_GetPosition(currentPacket); @@ -392,7 +392,7 @@ static PfChannelResult DynvcTrackerPeekFn(ChannelStateTracker* tracker, BOOL fir return PF_CHANNEL_RESULT_DROP; /* Silently drop */ dynChannel = DynamicChannelContext_new(dynChannelContext->log, pdata->ps, name, - dynChannelId); + (UINT32)dynChannelId); if (!dynChannel) { WLog_Print(dynChannelContext->log, WLOG_ERROR, @@ -493,7 +493,9 @@ static PfChannelResult DynvcTrackerPeekFn(ChannelStateTracker* tracker, BOOL fir WLog_Print(dynChannelContext->log, WLOG_DEBUG, "DynvcTracker(%s [%s]): %s DATA_FIRST currentPacketLength=%" PRIu64 "", dynChannel->channelName, drdynvc_get_packet_type(cmd), direction, Length); - trackerState->currentDataLength = Length; + if (Length > UINT32_MAX) + return PF_CHANNEL_RESULT_ERROR; + trackerState->currentDataLength = (UINT32)Length; trackerState->CurrentDataReceived = 0; trackerState->CurrentDataFragments = 0; diff --git a/server/proxy/pf_client.c b/server/proxy/pf_client.c index cd6729ec1..1255a4b5d 100644 --- a/server/proxy/pf_client.c +++ b/server/proxy/pf_client.c @@ -408,12 +408,12 @@ static BOOL pf_client_load_channels(freerdp* instance) { CHANNEL_DEF* channels = (CHANNEL_DEF*)freerdp_settings_get_pointer_array_writable( settings, FreeRDP_ChannelDefArray, 0); - size_t size = freerdp_settings_get_uint32(settings, FreeRDP_ChannelCount); + UINT32 size = freerdp_settings_get_uint32(settings, FreeRDP_ChannelCount); UINT32 id = MCS_GLOBAL_CHANNEL_ID + 1; WINPR_ASSERT(channels || (size == 0)); - size_t x = 0; + UINT32 x = 0; for (; x < size;) { CHANNEL_DEF* cur = &channels[x]; diff --git a/server/proxy/pf_config.c b/server/proxy/pf_config.c index bcd24d31d..90616ae81 100644 --- a/server/proxy/pf_config.c +++ b/server/proxy/pf_config.c @@ -936,7 +936,7 @@ static BOOL pf_config_copy_string_list(char*** dst, size_t* size, char** src, si if (srcSize != 0) { - char* csv = CommandLineToCommaSeparatedValues(srcSize, src); + char* csv = CommandLineToCommaSeparatedValues((INT32)srcSize, src); *dst = CommandLineParseCommaSeparatedValues(csv, size); free(csv); } diff --git a/server/proxy/pf_server.c b/server/proxy/pf_server.c index 5816a9f76..c876924df 100644 --- a/server/proxy/pf_server.c +++ b/server/proxy/pf_server.c @@ -101,7 +101,7 @@ static BOOL pf_server_parse_target_from_routing_token(rdpContext* context, rdpSe if (p > USHRT_MAX) return FALSE; - if (!freerdp_settings_set_uint32(settings, portID, p)) + if (!freerdp_settings_set_uint32(settings, portID, (USHORT)p)) return FALSE; } diff --git a/server/shadow/X11/x11_shadow.c b/server/shadow/X11/x11_shadow.c index c307569aa..66dd1d1df 100644 --- a/server/shadow/X11/x11_shadow.c +++ b/server/shadow/X11/x11_shadow.c @@ -666,10 +666,10 @@ static int x11_shadow_blend_cursor(x11ShadowSubsystem* subsystem) } if ((nXDst + nWidth) > surface->width) - nWidth = surface->width - nXDst; + nWidth = (nXDst > surface->width) ? 0 : (UINT32)(surface->width - nXDst); if ((nYDst + nHeight) > surface->height) - nHeight = surface->height - nYDst; + nHeight = (nYDst > surface->height) ? 0 : (UINT32)(surface->height - nYDst); pSrcData = subsystem->cursorPixels; nSrcStep = subsystem->cursorWidth * 4; @@ -926,8 +926,6 @@ static DWORD WINAPI x11_shadow_subsystem_thread(LPVOID arg) XEvent xevent; DWORD status = 0; DWORD nCount = 0; - UINT64 cTime = 0; - DWORD dwTimeout = 0; DWORD dwInterval = 0; UINT64 frameTime = 0; HANDLE events[32]; @@ -943,8 +941,9 @@ static DWORD WINAPI x11_shadow_subsystem_thread(LPVOID arg) while (1) { - cTime = GetTickCount64(); - dwTimeout = (cTime > frameTime) ? 0 : frameTime - cTime; + const UINT64 cTime = GetTickCount64(); + const DWORD dwTimeout = + (DWORD)((cTime > frameTime) ? 0 : MIN(UINT32_MAX, frameTime - cTime)); status = WaitForMultipleObjects(nCount, events, FALSE, dwTimeout); if (WaitForSingleObject(MessageQueue_Event(MsgPipe->In), 0) == WAIT_OBJECT_0) diff --git a/server/shadow/X11/x11_shadow.h b/server/shadow/X11/x11_shadow.h index 5ab8beb76..a744c3618 100644 --- a/server/shadow/X11/x11_shadow.h +++ b/server/shadow/X11/x11_shadow.h @@ -84,7 +84,7 @@ struct x11_shadow_subsystem UINT32 cursorHotY; UINT32 cursorWidth; UINT32 cursorHeight; - UINT32 cursorId; + UINT64 cursorId; BYTE* cursorPixels; UINT32 cursorMaxWidth; UINT32 cursorMaxHeight; diff --git a/server/shadow/shadow_capture.c b/server/shadow/shadow_capture.c index e5f97b664..bd1790ae6 100644 --- a/server/shadow/shadow_capture.c +++ b/server/shadow/shadow_capture.c @@ -247,8 +247,8 @@ int shadow_capture_compare_with_format(const BYTE* WINPR_RESTRICT pData1, UINT32 if (!tw) tw = 16; - const BYTE* p1 = &pData1[(ty * 16 * nStep1) + (tx * 16ull * bppA)]; - const BYTE* p2 = &pData2[(ty * 16 * nStep2) + (tx * 16ull * bppB)]; + const BYTE* p1 = &pData1[(ty * 16ULL * nStep1) + (tx * 16ull * bppA)]; + const BYTE* p2 = &pData2[(ty * 16ULL * nStep2) + (tx * 16ull * bppB)]; for (size_t k = 0; k < th; k++) { @@ -266,10 +266,10 @@ int shadow_capture_compare_with_format(const BYTE* WINPR_RESTRICT pData1, UINT32 { rowEqual = FALSE; if (l > tx) - l = tx; + l = (UINT32)tx; if (r < tx) - r = tx; + r = (UINT32)tx; } } @@ -278,10 +278,10 @@ int shadow_capture_compare_with_format(const BYTE* WINPR_RESTRICT pData1, UINT32 allEqual = FALSE; if (t > ty) - t = ty; + t = (UINT32)ty; if (b < ty) - b = ty; + b = (UINT32)ty; } } diff --git a/winpr/libwinpr/clipboard/synthetic.c b/winpr/libwinpr/clipboard/synthetic.c index f35b58faa..942301387 100644 --- a/winpr/libwinpr/clipboard/synthetic.c +++ b/winpr/libwinpr/clipboard/synthetic.c @@ -60,12 +60,15 @@ static void* clipboard_synthesize_cf_text(wClipboard* clipboard, UINT32 formatId { char* str = ConvertWCharNToUtf8Alloc(data, *pSize / sizeof(WCHAR), &size); - if (!str) + if (!str || (size > UINT32_MAX)) + { + free(str); return NULL; + } pDstData = ConvertLineEndingToCRLF(str, &size); free(str); - *pSize = size; + *pSize = (UINT32)size; return pDstData; } else if ((formatId == CF_TEXT) || (formatId == CF_OEMTEXT) || @@ -74,10 +77,10 @@ static void* clipboard_synthesize_cf_text(wClipboard* clipboard, UINT32 formatId size = *pSize; pDstData = ConvertLineEndingToCRLF(data, &size); - if (!pDstData) + if (!pDstData || (size > *pSize)) return NULL; - *pSize = size; + *pSize = (UINT32)size; return pDstData; } @@ -144,13 +147,14 @@ static void* clipboard_synthesize_cf_unicodetext(wClipboard* clipboard, UINT32 f pDstData = ConvertUtf8NToWCharAlloc(crlfStr, size, &len); free(crlfStr); - if ((len < 1) || (len > UINT32_MAX / sizeof(WCHAR))) + if ((len < 1) || ((len + 1) > UINT32_MAX / sizeof(WCHAR))) { free(pDstData); return NULL; } - *pSize = (len + 1) * sizeof(WCHAR); + const size_t slen = (len + 1) * sizeof(WCHAR); + *pSize = (UINT32)slen; } return (void*)pDstData; @@ -280,6 +284,9 @@ static void* clipboard_prepend_bmp_header(const WINPR_BITMAP_INFO_HEADER* pInfoH return NULL; const size_t DstSize = sizeof(WINPR_BITMAP_FILE_HEADER) + size; + if (DstSize > UINT32_MAX) + return NULL; + wStream* s = Stream_New(NULL, DstSize); if (!s) return NULL; @@ -287,7 +294,7 @@ static void* clipboard_prepend_bmp_header(const WINPR_BITMAP_INFO_HEADER* pInfoH WINPR_BITMAP_FILE_HEADER fileHeader = { 0 }; fileHeader.bfType[0] = 'B'; fileHeader.bfType[1] = 'M'; - fileHeader.bfSize = DstSize; + fileHeader.bfSize = (UINT32)DstSize; fileHeader.bfOffBits = sizeof(WINPR_BITMAP_FILE_HEADER) + sizeof(WINPR_BITMAP_INFO_HEADER); if (!writeBitmapFileHeader(s, &fileHeader)) goto fail; @@ -298,7 +305,7 @@ static void* clipboard_prepend_bmp_header(const WINPR_BITMAP_INFO_HEADER* pInfoH const size_t len = Stream_GetPosition(s); if (len != DstSize) goto fail; - *pSize = DstSize; + *pSize = (UINT32)DstSize; BYTE* dst = Stream_Buffer(s); Stream_Free(s, FALSE); @@ -610,7 +617,7 @@ static void* clipboard_synthesize_text_html(wClipboard* clipboard, UINT32 format const long end = strtol(&endStr[8], NULL, 10); - if (beg < 0 || end < 0 || ((size_t)beg > SrcSize) || ((size_t)end > SrcSize) || + if ((beg < 0) || (end < 0) || ((size_t)beg > SrcSize) || ((size_t)end > SrcSize) || (beg >= end) || (errno != 0)) return NULL; diff --git a/winpr/libwinpr/comm/comm.c b/winpr/libwinpr/comm/comm.c index 9bbf1e39d..e14f6ded9 100644 --- a/winpr/libwinpr/comm/comm.c +++ b/winpr/libwinpr/comm/comm.c @@ -1153,7 +1153,7 @@ DWORD QueryCommDevice(LPCTSTR lpDeviceName, LPTSTR lpTargetPath, DWORD ucchMax) _tcsncpy(lpTargetPath, storedTargetPath, size + 1); lpTargetPath[size + 2] = '\0'; /* 2nd final '\0' */ - return size + 2; + return (DWORD)size + 2UL; } /** diff --git a/winpr/libwinpr/comm/comm_io.c b/winpr/libwinpr/comm/comm_io.c index 7fc554827..0306436f3 100644 --- a/winpr/libwinpr/comm/comm_io.c +++ b/winpr/libwinpr/comm/comm_io.c @@ -294,10 +294,9 @@ BOOL CommReadFile(HANDLE hDevice, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, if (FD_ISSET(pComm->fd_read, &read_set)) { - ssize_t nbRead = 0; - nbRead = read(pComm->fd_read, lpBuffer, nNumberOfBytesToRead); + ssize_t nbRead = read(pComm->fd_read, lpBuffer, nNumberOfBytesToRead); - if (nbRead < 0) + if ((nbRead < 0) || (nbRead > nNumberOfBytesToRead)) { char ebuffer[256] = { 0 }; CommLog_Print(WLOG_WARN, @@ -336,7 +335,7 @@ BOOL CommReadFile(HANDLE hDevice, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, goto return_false; } - *lpNumberOfBytesRead = nbRead; + *lpNumberOfBytesRead = (UINT32)nbRead; EnterCriticalSection(&pComm->EventsLock); if (pComm->PendingEvents & SERIAL_EV_WINPR_WAITING) diff --git a/winpr/libwinpr/crt/string.c b/winpr/libwinpr/crt/string.c index b8049d5b2..a41424201 100644 --- a/winpr/libwinpr/crt/string.c +++ b/winpr/libwinpr/crt/string.c @@ -578,7 +578,10 @@ LPSTR CharLowerA(LPSTR lpsz) LPWSTR CharLowerW(LPWSTR lpsz) { - CharLowerBuffW(lpsz, _wcslen(lpsz)); + const size_t len = _wcsnlen(lpsz, UINT32_MAX + 1); + if (len > UINT32_MAX) + return NULL; + CharLowerBuffW(lpsz, (UINT32)len); return lpsz; } diff --git a/winpr/libwinpr/crt/unicode.c b/winpr/libwinpr/crt/unicode.c index 2e0d4d4e8..9131e7cf1 100644 --- a/winpr/libwinpr/crt/unicode.c +++ b/winpr/libwinpr/crt/unicode.c @@ -394,7 +394,7 @@ SSIZE_T ConvertWCharNToUtf8(const WCHAR* wstr, size_t wlen, char* str, size_t le WINPR_ASSERT(wstr); size_t iwlen = _wcsnlen(wstr, wlen); - if (wlen > INT32_MAX) + if ((len > INT32_MAX) || (wlen > INT32_MAX)) { SetLastError(ERROR_INVALID_PARAMETER); return -1; @@ -405,8 +405,7 @@ SSIZE_T ConvertWCharNToUtf8(const WCHAR* wstr, size_t wlen, char* str, size_t le isNullTerminated = TRUE; iwlen++; } - const int rc = - WideCharToMultiByte(CP_UTF8, 0, wstr, (int)iwlen, str, MIN(INT32_MAX, len), NULL, NULL); + const int rc = WideCharToMultiByte(CP_UTF8, 0, wstr, (int)iwlen, str, (int)len, NULL, NULL); if ((rc <= 0) || ((len > 0) && ((size_t)rc > len))) return -1; else if (!isNullTerminated) @@ -430,13 +429,13 @@ SSIZE_T ConvertMszWCharNToUtf8(const WCHAR* wstr, size_t wlen, char* str, size_t WINPR_ASSERT(wstr); - if (wlen > INT32_MAX) + if ((len > INT32_MAX) || (wlen > INT32_MAX)) { SetLastError(ERROR_INVALID_PARAMETER); return -1; } - const int iwlen = MIN(INT32_MAX, len); + const int iwlen = (int)len; const int rc = WideCharToMultiByte(CP_UTF8, 0, wstr, (int)wlen, str, iwlen, NULL, NULL); if ((rc <= 0) || ((len > 0) && (rc > iwlen))) return -1; @@ -466,7 +465,7 @@ SSIZE_T ConvertUtf8NToWChar(const char* str, size_t len, WCHAR* wstr, size_t wle WINPR_ASSERT(str); - if (len > INT32_MAX) + if ((len > INT32_MAX) || (wlen > INT32_MAX)) { SetLastError(ERROR_INVALID_PARAMETER); return -1; @@ -477,7 +476,7 @@ SSIZE_T ConvertUtf8NToWChar(const char* str, size_t len, WCHAR* wstr, size_t wle ilen++; } - const int iwlen = MIN(INT32_MAX, wlen); + const int iwlen = (int)wlen; const int rc = MultiByteToWideChar(CP_UTF8, 0, str, (int)ilen, wstr, iwlen); if ((rc <= 0) || ((wlen > 0) && (rc > iwlen))) return -1; @@ -502,13 +501,13 @@ SSIZE_T ConvertMszUtf8NToWChar(const char* str, size_t len, WCHAR* wstr, size_t WINPR_ASSERT(str); - if (len > INT32_MAX) + if ((len > INT32_MAX) || (wlen > INT32_MAX)) { SetLastError(ERROR_INVALID_PARAMETER); return -1; } - const int iwlen = MIN(INT32_MAX, wlen); + const int iwlen = (int)wlen; const int rc = MultiByteToWideChar(CP_UTF8, 0, str, (int)len, wstr, iwlen); if ((rc <= 0) || ((wlen > 0) && (rc > iwlen))) return -1; diff --git a/winpr/libwinpr/crypto/md4.c b/winpr/libwinpr/crypto/md4.c index 62e2014a9..78ceb8cbe 100644 --- a/winpr/libwinpr/crypto/md4.c +++ b/winpr/libwinpr/crypto/md4.c @@ -110,10 +110,10 @@ static const void* body(WINPR_MD4_CTX* ctx, const void* data, unsigned long size do { - winpr_MD4_u32plus saved_a = a; - winpr_MD4_u32plus saved_b = b; - winpr_MD4_u32plus saved_c = c; - winpr_MD4_u32plus saved_d = d; + const winpr_MD4_u32plus saved_a = a; + const winpr_MD4_u32plus saved_b = b; + const winpr_MD4_u32plus saved_c = c; + const winpr_MD4_u32plus saved_d = d; /* Round 1 */ STEP(F, a, b, c, d, SET(0), 3) diff --git a/winpr/libwinpr/crypto/rc4.c b/winpr/libwinpr/crypto/rc4.c index e17078541..aed2ee601 100644 --- a/winpr/libwinpr/crypto/rc4.c +++ b/winpr/libwinpr/crypto/rc4.c @@ -68,8 +68,8 @@ BOOL winpr_int_rc4_update(winpr_int_RC4_CTX* ctx, size_t length, const BYTE* inp { WINPR_ASSERT(ctx); - UINT32 t1 = ctx->i; - UINT32 t2 = ctx->j; + size_t t1 = ctx->i; + size_t t2 = ctx->j; for (size_t i = 0; i < length; i++) { t1 = (t1 + 1) % CTX_SIZE; diff --git a/winpr/libwinpr/file/file.c b/winpr/libwinpr/file/file.c index 0a54ebed1..35aeec637 100644 --- a/winpr/libwinpr/file/file.c +++ b/winpr/libwinpr/file/file.c @@ -383,8 +383,8 @@ static BOOL FileGetFileInformationByHandle(HANDLE hFile, lpFileInformation->ftLastAccessTime.dwLowDateTime = ft & 0xFFFFFFFF; lpFileInformation->nFileSizeHigh = ((UINT64)st.st_size) >> 32ULL; lpFileInformation->nFileSizeLow = st.st_size & 0xFFFFFFFF; - lpFileInformation->dwVolumeSerialNumber = st.st_dev; - lpFileInformation->nNumberOfLinks = st.st_nlink; + lpFileInformation->dwVolumeSerialNumber = (UINT32)st.st_dev; + lpFileInformation->nNumberOfLinks = (UINT32)st.st_nlink; lpFileInformation->nFileIndexHigh = (st.st_ino >> 4) & 0xFFFFFFFF; lpFileInformation->nFileIndexLow = st.st_ino & 0xFFFFFFFF; return TRUE; diff --git a/winpr/libwinpr/input/scancode.c b/winpr/libwinpr/input/scancode.c index 74d5da534..7bf97366f 100644 --- a/winpr/libwinpr/input/scancode.c +++ b/winpr/libwinpr/input/scancode.c @@ -18,7 +18,7 @@ */ #include - +#include #include #include @@ -139,22 +139,24 @@ DWORD GetVirtualScanCodeFromVirtualKeyCode(DWORD vkcode, DWORD dwKeyboardType) { if (vkcode & KBDEXT) { + WINPR_ASSERT(ARRAYSIZE(KBD4X) <= UINT32_MAX); for (size_t i = 0; i < ARRAYSIZE(KBD4X); i++) { if (KBD4X[i] == codeIndex) { - scancode = (i | KBDEXT); + scancode = (DWORD)(i | KBDEXT); break; } } } else { + WINPR_ASSERT(ARRAYSIZE(KBD4T) <= UINT32_MAX); for (size_t i = 0; i < ARRAYSIZE(KBD4T); i++) { if (KBD4T[i] == codeIndex) { - scancode = i; + scancode = (DWORD)i; break; } } @@ -164,22 +166,24 @@ DWORD GetVirtualScanCodeFromVirtualKeyCode(DWORD vkcode, DWORD dwKeyboardType) { if (vkcode & KBDEXT) { + WINPR_ASSERT(ARRAYSIZE(KBD7X) <= UINT32_MAX); for (size_t i = 0; i < ARRAYSIZE(KBD7X); i++) { if (KBD7X[i] == codeIndex) { - scancode = (i | KBDEXT); + scancode = (DWORD)(i | KBDEXT); break; } } } else { + WINPR_ASSERT(ARRAYSIZE(KBD7T) <= UINT32_MAX); for (size_t i = 0; i < ARRAYSIZE(KBD7T); i++) { if (KBD7T[i] == codeIndex) { - scancode = i; + scancode = (DWORD)i; break; } } diff --git a/winpr/libwinpr/ncrypt/ncrypt_pkcs11.c b/winpr/libwinpr/ncrypt/ncrypt_pkcs11.c index 4dcd6acd9..5a68103a9 100644 --- a/winpr/libwinpr/ncrypt/ncrypt_pkcs11.c +++ b/winpr/libwinpr/ncrypt/ncrypt_pkcs11.c @@ -485,7 +485,6 @@ static SECURITY_STATUS collect_keys(NCryptP11ProviderHandle* provider, P11EnumKe static BOOL convertKeyType(CK_KEY_TYPE k, LPWSTR dest, DWORD len, DWORD* outlen) { - DWORD retLen = 0; const WCHAR* r = NULL; #define ALGO_CASE(V, S) \ @@ -523,9 +522,12 @@ static BOOL convertKeyType(CK_KEY_TYPE k, LPWSTR dest, DWORD len, DWORD* outlen) } #undef ALGO_CASE - retLen = _wcslen(r); + size_t retLen = _wcslen(r); + if (retLen > UINT32_MAX) + return FALSE; + if (outlen) - *outlen = retLen; + *outlen = (UINT32)retLen; if (!r) { @@ -1014,7 +1016,10 @@ static SECURITY_STATUS NCryptP11KeyGetProperties(NCryptP11KeyHandle* keyHandle, #define SLOT_DESC_SZ sizeof(slotInfo.slotDescription) fix_padded_string((char*)slotInfo.slotDescription, SLOT_DESC_SZ); - *pcbResult = 2 * (strnlen((char*)slotInfo.slotDescription, SLOT_DESC_SZ) + 1); + const size_t len = 2ULL * (strnlen((char*)slotInfo.slotDescription, SLOT_DESC_SZ) + 1); + if (len > UINT32_MAX) + return NTE_BAD_DATA; + *pcbResult = (UINT32)len; if (pbOutput) { union @@ -1041,8 +1046,12 @@ static SECURITY_STATUS NCryptP11KeyGetProperties(NCryptP11KeyHandle* keyHandle, if (cbOutput < 4) return NTE_NO_MEMORY; - - *ptr = keyHandle->slotId; + if (keyHandle->slotId > UINT32_MAX) + { + ret = NTE_BAD_DATA; + goto out_final; + } + *ptr = (UINT32)keyHandle->slotId; } return ERROR_SUCCESS; } @@ -1093,7 +1102,12 @@ static SECURITY_STATUS NCryptP11KeyGetProperties(NCryptP11KeyHandle* keyHandle, // TODO: do a kind of translation from CKR_* to NTE_* } - *pcbResult = certValue.ulValueLen; + if (certValue.ulValueLen > UINT32_MAX) + { + ret = NTE_BAD_DATA; + goto out_final; + } + *pcbResult = (UINT32)certValue.ulValueLen; ret = ERROR_SUCCESS; break; } diff --git a/winpr/libwinpr/path/include/PathAllocCombine.h b/winpr/libwinpr/path/include/PathAllocCombine.h index abdbd293e..a103d3dfa 100644 --- a/winpr/libwinpr/path/include/PathAllocCombine.h +++ b/winpr/libwinpr/path/include/PathAllocCombine.h @@ -18,17 +18,18 @@ * - the function will crash with some short string lengths of the parameters */ +#include +#include + +#include +#include +#include + #if DEFINE_UNICODE HRESULT PATH_ALLOC_COMBINE(PCWSTR pszPathIn, PCWSTR pszMore, unsigned long dwFlags, PWSTR* ppszPathOut) { - PWSTR pszPathOut; - BOOL backslashIn; - BOOL backslashMore; - size_t pszMoreLength; - size_t pszPathInLength; - size_t pszPathOutLength; WLog_WARN(TAG, "has known bugs and needs fixing."); if (!ppszPathOut) @@ -43,25 +44,25 @@ HRESULT PATH_ALLOC_COMBINE(PCWSTR pszPathIn, PCWSTR pszMore, unsigned long dwFla if (!pszPathIn) return E_FAIL; /* valid but not implemented, see top comment */ - pszPathInLength = _wcslen(pszPathIn); - pszMoreLength = _wcslen(pszMore); + const size_t pszPathInLength = _wcslen(pszPathIn); + const size_t pszMoreLength = _wcslen(pszMore); /* prevent segfaults - the complete implementation below is buggy */ if (pszPathInLength < 3) return E_FAIL; - backslashIn = (pszPathIn[pszPathInLength - 1] == CUR_PATH_SEPARATOR_CHR) ? TRUE : FALSE; - backslashMore = (pszMore[0] == CUR_PATH_SEPARATOR_CHR) ? TRUE : FALSE; + const BOOL backslashIn = + (pszPathIn[pszPathInLength - 1] == CUR_PATH_SEPARATOR_CHR) ? TRUE : FALSE; + const BOOL backslashMore = (pszMore[0] == CUR_PATH_SEPARATOR_CHR) ? TRUE : FALSE; if (backslashMore) { if ((pszPathIn[1] == ':') && (pszPathIn[2] == CUR_PATH_SEPARATOR_CHR)) { const WCHAR colon[] = { ':', '\0' }; - size_t sizeOfBuffer; - pszPathOutLength = sizeof(WCHAR) + pszMoreLength; - sizeOfBuffer = (pszPathOutLength + 1) * sizeof(WCHAR); - pszPathOut = (PWSTR)calloc(sizeOfBuffer, sizeof(WCHAR)); + const size_t pszPathOutLength = sizeof(WCHAR) + pszMoreLength; + const size_t sizeOfBuffer = (pszPathOutLength + 1) * sizeof(WCHAR); + PWSTR pszPathOut = (PWSTR)calloc(sizeOfBuffer, sizeof(WCHAR)); if (!pszPathOut) return E_OUTOFMEMORY; @@ -76,10 +77,9 @@ HRESULT PATH_ALLOC_COMBINE(PCWSTR pszPathIn, PCWSTR pszMore, unsigned long dwFla else { const WCHAR sep[] = CUR_PATH_SEPARATOR_STR; - size_t sizeOfBuffer; - pszPathOutLength = pszPathInLength + pszMoreLength; - sizeOfBuffer = (pszPathOutLength + 1) * 2; - pszPathOut = (PWSTR)calloc(sizeOfBuffer, 2); + const size_t pszPathOutLength = pszPathInLength + pszMoreLength; + const size_t sizeOfBuffer = (pszPathOutLength + 1) * 2; + PWSTR pszPathOut = (PWSTR)calloc(sizeOfBuffer, 2); if (!pszPathOut) return E_OUTOFMEMORY; @@ -100,12 +100,6 @@ HRESULT PATH_ALLOC_COMBINE(PCWSTR pszPathIn, PCWSTR pszMore, unsigned long dwFla HRESULT PATH_ALLOC_COMBINE(PCSTR pszPathIn, PCSTR pszMore, unsigned long dwFlags, PSTR* ppszPathOut) { - PSTR pszPathOut; - BOOL backslashIn; - BOOL backslashMore; - int pszMoreLength; - int pszPathInLength; - int pszPathOutLength; WLog_WARN(TAG, "has known bugs and needs fixing."); if (!ppszPathOut) @@ -120,24 +114,24 @@ HRESULT PATH_ALLOC_COMBINE(PCSTR pszPathIn, PCSTR pszMore, unsigned long dwFlags if (!pszPathIn) return E_FAIL; /* valid but not implemented, see top comment */ - pszPathInLength = strlen(pszPathIn); - pszMoreLength = strlen(pszMore); + const size_t pszPathInLength = strlen(pszPathIn); + const size_t pszMoreLength = strlen(pszMore); /* prevent segfaults - the complete implementation below is buggy */ if (pszPathInLength < 3) return E_FAIL; - backslashIn = (pszPathIn[pszPathInLength - 1] == CUR_PATH_SEPARATOR_CHR) ? TRUE : FALSE; - backslashMore = (pszMore[0] == CUR_PATH_SEPARATOR_CHR) ? TRUE : FALSE; + const BOOL backslashIn = + (pszPathIn[pszPathInLength - 1] == CUR_PATH_SEPARATOR_CHR) ? TRUE : FALSE; + const BOOL backslashMore = (pszMore[0] == CUR_PATH_SEPARATOR_CHR) ? TRUE : FALSE; if (backslashMore) { if ((pszPathIn[1] == ':') && (pszPathIn[2] == CUR_PATH_SEPARATOR_CHR)) { - size_t sizeOfBuffer; - pszPathOutLength = 2 + pszMoreLength; - sizeOfBuffer = (pszPathOutLength + 1) * 2; - pszPathOut = (PSTR)calloc(sizeOfBuffer, 2); + const size_t pszPathOutLength = 2 + pszMoreLength; + const size_t sizeOfBuffer = (pszPathOutLength + 1) * 2; + PSTR pszPathOut = calloc(sizeOfBuffer, 2); if (!pszPathOut) return E_OUTOFMEMORY; @@ -149,10 +143,9 @@ HRESULT PATH_ALLOC_COMBINE(PCSTR pszPathIn, PCSTR pszMore, unsigned long dwFlags } else { - size_t sizeOfBuffer; - pszPathOutLength = pszPathInLength + pszMoreLength; - sizeOfBuffer = (pszPathOutLength + 1) * 2; - pszPathOut = (PSTR)calloc(sizeOfBuffer, 2); + const size_t pszPathOutLength = pszPathInLength + pszMoreLength; + const size_t sizeOfBuffer = (pszPathOutLength + 1) * 2; + PSTR pszPathOut = calloc(sizeOfBuffer, 2); if (!pszPathOut) return E_OUTOFMEMORY; diff --git a/winpr/libwinpr/shell/shell.c b/winpr/libwinpr/shell/shell.c index a9cab579d..7c550dcd6 100644 --- a/winpr/libwinpr/shell/shell.c +++ b/winpr/libwinpr/shell/shell.c @@ -78,10 +78,16 @@ BOOL GetUserProfileDirectoryA(HANDLE hToken, LPSTR lpProfileDir, LPDWORD lpcchSi } const size_t cchDirSize = strlen(pw->pw_dir) + 1; + if (cchDirSize > UINT32_MAX) + { + SetLastError(ERROR_INVALID_PARAMETER); + free(buf); + return FALSE; + } if (!lpProfileDir || (*lpcchSize < cchDirSize)) { - *lpcchSize = cchDirSize; + *lpcchSize = (UINT32)cchDirSize; SetLastError(ERROR_INSUFFICIENT_BUFFER); free(buf); return FALSE; @@ -89,7 +95,7 @@ BOOL GetUserProfileDirectoryA(HANDLE hToken, LPSTR lpProfileDir, LPDWORD lpcchSi ZeroMemory(lpProfileDir, *lpcchSize); (void)sprintf_s(lpProfileDir, *lpcchSize, "%s", pw->pw_dir); - *lpcchSize = cchDirSize; + *lpcchSize = (UINT32)cchDirSize; free(buf); return TRUE; } diff --git a/winpr/libwinpr/sspi/Kerberos/kerberos.c b/winpr/libwinpr/sspi/Kerberos/kerberos.c index 1c6ea9485..26cea5660 100644 --- a/winpr/libwinpr/sspi/Kerberos/kerberos.c +++ b/winpr/libwinpr/sspi/Kerberos/kerberos.c @@ -206,7 +206,11 @@ static krb5_error_code krb5_prompter(krb5_context context, void* data, const cha if (type && (type == KRB5_PROMPT_TYPE_PREAUTH || type == KRB5_PROMPT_TYPE_PASSWORD) && data) { prompts[i].reply->data = _strdup((const char*)data); - prompts[i].reply->length = strlen((const char*)data); + + const size_t len = strlen((const char*)data); + if (len > UINT32_MAX) + return KRB5_ERROR; + prompts[i].reply->length = (UINT32)len; } } return 0; @@ -808,7 +812,11 @@ static BOOL kerberos_rd_tgt_rep(WinPrAsn1Decoder* dec, krb5_data* ticket) wStream s = WinPrAsn1DecGetStream(&asnTicket); ticket->data = Stream_BufferAs(&s, char); - ticket->length = Stream_Length(&s); + + const size_t len = Stream_Length(&s); + if (len > UINT32_MAX) + return FALSE; + ticket->length = (UINT32)len; return TRUE; } diff --git a/winpr/libwinpr/sspi/Kerberos/krb5glue_mit.c b/winpr/libwinpr/sspi/Kerberos/krb5glue_mit.c index cd71322fb..9bee06ed3 100644 --- a/winpr/libwinpr/sspi/Kerberos/krb5glue_mit.c +++ b/winpr/libwinpr/sspi/Kerberos/krb5glue_mit.c @@ -213,15 +213,18 @@ krb5_error_code krb5glue_get_init_creds(krb5_context ctx, krb5_principal princ, free(kdc_url); free(realm); - if ((rv = profile_flush_to_file(profile, tmp_profile_path))) + long lrv = profile_flush_to_file(profile, tmp_profile_path); + if (lrv) goto cleanup; profile_abandon(profile); profile = NULL; - if ((rv = profile_init_path(tmp_profile_path, &profile))) + lrv = profile_init_path(tmp_profile_path, &profile); + if (lrv) goto cleanup; - if ((rv = krb5_init_context_profile(profile, 0, &ctx))) + rv = krb5_init_context_profile(profile, 0, &ctx); + if (rv) goto cleanup; is_temp_ctx = TRUE; } diff --git a/winpr/libwinpr/sspi/Negotiate/negotiate.c b/winpr/libwinpr/sspi/Negotiate/negotiate.c index ace8d83e4..1dabc3a93 100644 --- a/winpr/libwinpr/sspi/Negotiate/negotiate.c +++ b/winpr/libwinpr/sspi/Negotiate/negotiate.c @@ -418,11 +418,14 @@ static BOOL negotiate_write_neg_token(PSecBuffer output_buffer, NegToken* token) if (!WinPrAsn1EncStreamSize(enc, &len) || len > output_buffer->cbBuffer) goto cleanup; + if (len > UINT32_MAX) + goto cleanup; + Stream_StaticInit(&s, output_buffer->pvBuffer, len); if (WinPrAsn1EncToStream(enc, &s)) { - output_buffer->cbBuffer = len; + output_buffer->cbBuffer = (UINT32)len; ret = TRUE; } @@ -491,7 +494,10 @@ static BOOL negotiate_read_neg_token(PSecBuffer input, NegToken* token) /* mechTypes [0] MechTypeList */ wStream s = WinPrAsn1DecGetStream(&dec2); token->mechTypes.BufferType = SECBUFFER_TOKEN; - token->mechTypes.cbBuffer = Stream_Length(&s); + const size_t mlen = Stream_Length(&s); + if (mlen > UINT32_MAX) + return FALSE; + token->mechTypes.cbBuffer = (UINT32)mlen; token->mechTypes.pvBuffer = Stream_Buffer(&s); WLog_DBG(TAG, "\tmechTypes [0] (%li bytes)", token->mechTypes.cbBuffer); } @@ -526,7 +532,9 @@ static BOOL negotiate_read_neg_token(PSecBuffer input, NegToken* token) /* mechToken [2] OCTET STRING */ if (!WinPrAsn1DecReadOctetString(&dec2, &octet_string, FALSE)) return FALSE; - token->mechToken.cbBuffer = octet_string.len; + if (octet_string.len > UINT32_MAX) + return FALSE; + token->mechToken.cbBuffer = (UINT32)octet_string.len; token->mechToken.pvBuffer = octet_string.data; token->mechToken.BufferType = SECBUFFER_TOKEN; WLog_DBG(TAG, "\tmechToken [2] (%li bytes)", octet_string.len); @@ -535,7 +543,9 @@ static BOOL negotiate_read_neg_token(PSecBuffer input, NegToken* token) /* mechListMic [3] OCTET STRING */ if (!WinPrAsn1DecReadOctetString(&dec2, &octet_string, FALSE)) return FALSE; - token->mic.cbBuffer = octet_string.len; + if (octet_string.len > UINT32_MAX) + return FALSE; + token->mic.cbBuffer = (UINT32)octet_string.len; token->mic.pvBuffer = octet_string.data; token->mic.BufferType = SECBUFFER_TOKEN; WLog_DBG(TAG, "\tmechListMIC [3] (%li bytes)", octet_string.len); @@ -728,7 +738,9 @@ static SECURITY_STATUS SEC_ENTRY negotiate_InitializeSecurityContextW( { init_context.spnego = TRUE; init_context.mechTypes.BufferType = SECBUFFER_DATA; - init_context.mechTypes.cbBuffer = WinPrAsn1EncEndContainer(enc); + const size_t cb = WinPrAsn1EncEndContainer(enc); + WINPR_ASSERT(cb <= UINT32_MAX); + init_context.mechTypes.cbBuffer = (UINT32)cb; } /* Allocate memory for the new context */ diff --git a/winpr/libwinpr/sspi/sspi_gss.c b/winpr/libwinpr/sspi/sspi_gss.c index 749973d20..6b08aef80 100644 --- a/winpr/libwinpr/sspi/sspi_gss.c +++ b/winpr/libwinpr/sspi/sspi_gss.c @@ -74,7 +74,7 @@ BOOL sspi_gss_wrap_token(SecBuffer* buf, const WinPrAsn1_OID* oid, uint16_t tok_ Stream_StaticInit(&s, buf->pvBuffer, len); if (WinPrAsn1EncToStream(enc, &s)) { - buf->cbBuffer = len; + buf->cbBuffer = (UINT32)len; ret = TRUE; } diff --git a/winpr/libwinpr/sspi/sspi_winpr.c b/winpr/libwinpr/sspi/sspi_winpr.c index c86055bd1..8d6df3510 100644 --- a/winpr/libwinpr/sspi/sspi_winpr.c +++ b/winpr/libwinpr/sspi/sspi_winpr.c @@ -333,6 +333,9 @@ static BOOL copy(WCHAR** dst, ULONG* dstLen, const WCHAR* what, size_t len) *dst = NULL; *dstLen = 0; + if (len > UINT32_MAX) + return FALSE; + /* Case what="" and len=0 should allocate an empty string */ if (!what && (len != 0)) return FALSE; @@ -344,7 +347,7 @@ static BOOL copy(WCHAR** dst, ULONG* dstLen, const WCHAR* what, size_t len) return FALSE; memcpy(*dst, what, len * sizeof(WCHAR)); - *dstLen = len; + *dstLen = (UINT32)len; return TRUE; } @@ -1091,11 +1094,13 @@ static void sspi_ContextBufferFree(void* contextBuffer) static SECURITY_STATUS SEC_ENTRY winpr_EnumerateSecurityPackagesW(ULONG* pcPackages, PSecPkgInfoW* ppPackageInfo) { - size_t cPackages = ARRAYSIZE(SecPkgInfoW_LIST); - size_t size = sizeof(SecPkgInfoW) * cPackages; + const size_t cPackages = ARRAYSIZE(SecPkgInfoW_LIST); + const size_t size = sizeof(SecPkgInfoW) * cPackages; SecPkgInfoW* pPackageInfo = (SecPkgInfoW*)sspi_ContextBufferAlloc(EnumerateSecurityPackagesIndex, size); + WINPR_ASSERT(cPackages <= UINT32_MAX); + if (!pPackageInfo) return SEC_E_INSUFFICIENT_MEMORY; @@ -1109,7 +1114,7 @@ static SECURITY_STATUS SEC_ENTRY winpr_EnumerateSecurityPackagesW(ULONG* pcPacka pPackageInfo[index].Comment = _wcsdup(SecPkgInfoW_LIST[index]->Comment); } - *(pcPackages) = cPackages; + *(pcPackages) = (UINT32)cPackages; *(ppPackageInfo) = pPackageInfo; return SEC_E_OK; } @@ -1117,11 +1122,13 @@ static SECURITY_STATUS SEC_ENTRY winpr_EnumerateSecurityPackagesW(ULONG* pcPacka static SECURITY_STATUS SEC_ENTRY winpr_EnumerateSecurityPackagesA(ULONG* pcPackages, PSecPkgInfoA* ppPackageInfo) { - size_t cPackages = ARRAYSIZE(SecPkgInfoA_LIST); - size_t size = sizeof(SecPkgInfoA) * cPackages; + const size_t cPackages = ARRAYSIZE(SecPkgInfoA_LIST); + const size_t size = sizeof(SecPkgInfoA) * cPackages; SecPkgInfoA* pPackageInfo = (SecPkgInfoA*)sspi_ContextBufferAlloc(EnumerateSecurityPackagesIndex, size); + WINPR_ASSERT(cPackages <= UINT32_MAX); + if (!pPackageInfo) return SEC_E_INSUFFICIENT_MEMORY; @@ -1141,7 +1148,7 @@ static SECURITY_STATUS SEC_ENTRY winpr_EnumerateSecurityPackagesA(ULONG* pcPacka } } - *(pcPackages) = cPackages; + *(pcPackages) = (UINT32)cPackages; *(ppPackageInfo) = pPackageInfo; return SEC_E_OK; } diff --git a/winpr/libwinpr/sspicli/sspicli.c b/winpr/libwinpr/sspicli/sspicli.c index 5d6b349c6..dd78127cc 100644 --- a/winpr/libwinpr/sspicli/sspicli.c +++ b/winpr/libwinpr/sspicli/sspicli.c @@ -233,7 +233,10 @@ BOOL GetUserNameExA(EXTENDED_NAME_FORMAT NameFormat, LPSTR lpNameBuffer, PULONG strncpy(lpNameBuffer, name, strnlen(name, *nSize)); } #endif - *nSize = strnlen(lpNameBuffer, *nSize); + const size_t len = strnlen(lpNameBuffer, *nSize); + if (len > UINT32_MAX) + return FALSE; + *nSize = (ULONG)len; return TRUE; case NameFullyQualifiedDN: @@ -269,10 +272,10 @@ BOOL GetUserNameExW(EXTENDED_NAME_FORMAT NameFormat, LPWSTR lpNameBuffer, PULONG goto fail; const SSIZE_T res = ConvertUtf8ToWChar(name, lpNameBuffer, *nSize); - if (res < 0) + if ((res < 0) || (res >= UINT32_MAX)) goto fail; - *nSize = res + 1; + *nSize = (UINT32)res + 1; rc = TRUE; fail: free(name); diff --git a/winpr/libwinpr/utils/image.c b/winpr/libwinpr/utils/image.c index 0a6724095..75efe33a0 100644 --- a/winpr/libwinpr/utils/image.c +++ b/winpr/libwinpr/utils/image.c @@ -275,10 +275,13 @@ static void* winpr_bitmap_write_buffer(const BYTE* data, size_t size, UINT32 wid void* result = NULL; const size_t bpp_stride = 1ull * width * (bpp / 8); + if (bpp_stride > UINT32_MAX) + return NULL; + wStream* s = Stream_New(NULL, 1024); if (stride == 0) - stride = bpp_stride; + stride = (UINT32)bpp_stride; BYTE* bmp_header = winpr_bitmap_construct_header(width, height, bpp); if (!bmp_header) @@ -298,7 +301,10 @@ static void* winpr_bitmap_write_buffer(const BYTE* data, size_t size, UINT32 wid } result = Stream_Buffer(s); - *pSize = Stream_GetPosition(s); + const size_t pos = Stream_GetPosition(s); + if (pos > UINT32_MAX) + goto fail; + *pSize = (UINT32)pos; fail: Stream_Free(s, result == NULL); free(bmp_header); @@ -316,14 +322,20 @@ int winpr_bitmap_write_ex(const char* filename, const BYTE* data, size_t stride, { FILE* fp = NULL; int ret = -1; + void* bmpdata = NULL; const size_t bpp_stride = ((((width * bpp) + 31) & ~31) >> 3); + if ((stride > UINT32_MAX) || (width > UINT32_MAX) || (height > UINT32_MAX) || + (bpp > UINT32_MAX)) + goto fail; + if (stride == 0) stride = bpp_stride; UINT32 bmpsize = 0; const size_t size = stride * 1ull * height; - void* bmpdata = winpr_bitmap_write_buffer(data, size, width, height, stride, bpp, &bmpsize); + bmpdata = winpr_bitmap_write_buffer(data, size, (UINT32)width, (UINT32)height, (UINT32)stride, + (UINT32)bpp, &bmpsize); if (!bmpdata) goto fail; @@ -444,10 +456,10 @@ static int winpr_image_bitmap_read_buffer(wImage* image, const BYTE* buffer, siz } image->bitsPerPixel = bi.biBitCount; - image->bytesPerPixel = (image->bitsPerPixel / 8); - const size_t bpp = (bi.biBitCount + 7) / 8; - image->scanline = bi.biWidth * bpp; - const size_t bmpsize = 1ull * image->scanline * image->height; + image->bytesPerPixel = (image->bitsPerPixel / 8UL); + const size_t bpp = (bi.biBitCount + 7UL) / 8UL; + image->scanline = (UINT32)(bi.biWidth * bpp); + const size_t bmpsize = 1ULL * image->scanline * image->height; if (bmpsize != bi.biSizeImage) WLog_WARN(TAG, "bmpsize=%" PRIuz " != bi.biSizeImage=%" PRIu32, bmpsize, bi.biSizeImage); if (bi.biSizeImage < bmpsize) diff --git a/winpr/libwinpr/winsock/winsock.c b/winpr/libwinpr/winsock/winsock.c index 5eff6ce0e..0444b9e06 100644 --- a/winpr/libwinpr/winsock/winsock.c +++ b/winpr/libwinpr/winsock/winsock.c @@ -19,6 +19,7 @@ #include +#include #include #include @@ -294,8 +295,6 @@ INT winpr_inet_pton(INT Family, PCSTR pszAddrString, PVOID pAddrBuf) #include #include -#include - #ifndef MSG_NOSIGNAL #define MSG_NOSIGNAL 0 #endif @@ -1104,7 +1103,8 @@ int _getsockopt(SOCKET s, int level, int optname, char* optval, int* optlen) u_long _htonl(u_long hostlong) { - return htonl(hostlong); + WINPR_ASSERT(hostlong <= UINT32_MAX); + return htonl((UINT32)hostlong); } u_short _htons(u_short hostshort) @@ -1132,7 +1132,8 @@ int _listen(SOCKET s, int backlog) u_long _ntohl(u_long netlong) { - return ntohl(netlong); + WINPR_ASSERT((netlong & 0xFFFFFFFF00000000ULL) == 0); + return ntohl((UINT32)netlong); } u_short _ntohs(u_short netshort)