Replace with secure APIs in win32compat
This commit is contained in:
Yanbing 2017-07-19 15:28:35 -07:00 committed by GitHub
parent eb8cf61ccf
commit b1a6fbca5e
21 changed files with 270 additions and 128 deletions

View File

@ -473,12 +473,12 @@ ParseANSI(unsigned char * pszBuffer, unsigned char * pszBufferEnd, unsigned char
case '^': /* Private message */
/* while not stop */
while (pszCurrent && pszCurrent < pszBufferEnd &&
_strnicmp((const char *)pszCurrent, (const char *)VT_ST, strlen((const char *)VT_ST))) {
_strnicmp((const char *)pszCurrent, (const char *)VT_ST, strnlen((const char *)VT_ST, sizeof(VT_ST)))) {
if (pszCurrent && pszCurrent < pszBufferEnd &&
_strnicmp((const char *)pszCurrent, (const char *)VT_ST, strlen((const char *)VT_ST)))
_strnicmp((const char *)pszCurrent, (const char *)VT_ST, strnlen((const char *)VT_ST, sizeof(VT_ST))))
pszCurrent++;
}
pszCurrent += strlen((const char *)VT_ST) - 1;
pszCurrent += strnlen((const char *)VT_ST, sizeof(VT_ST)) - 1;
fcompletion = 1;
break;

View File

@ -517,12 +517,12 @@ ConWriteString(char* pszString, int cbString)
if ((needed = MultiByteToWideChar(CP_UTF8, 0, pszString, cbString, NULL, 0)) == 0 ||
(utf16 = malloc(needed * sizeof(wchar_t))) == NULL ||
(cnt = MultiByteToWideChar(CP_UTF8, 0, pszString, cbString, utf16, needed)) == 0) {
Result = (DWORD)printf(pszString);
Result = (DWORD)printf_s(pszString);
} else {
if (hOutputConsole)
WriteConsoleW(hOutputConsole, utf16, cnt, &Result, 0);
else
Result = (DWORD)wprintf(utf16);
Result = (DWORD)wprintf_s(utf16);
}
if (utf16)
@ -539,7 +539,7 @@ ConTranslateAndWriteString(char* pszString, int cbString)
if (hOutputConsole)
WriteConsole(hOutputConsole, pszString, cbString, &Result, 0);
else
Result = (DWORD)printf(pszString);
Result = (DWORD)printf_s(pszString);
return Result;
}
@ -829,7 +829,11 @@ Con_printf(const char *Format, ...)
memset(temp, '\0', sizeof(temp));
va_start(va_data, Format);
len = vsnprintf(temp, sizeof(temp), Format, va_data);
len = vsnprintf_s(temp, sizeof(temp), _TRUNCATE, Format, va_data);
if (len == -1) {
error("Error from vsnprintf_s!");
return -1;
}
ConWriteConsole(temp, len);
va_end(va_data);
@ -1073,6 +1077,7 @@ ConMoveVisibleWindow(int offset)
{
CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
SMALL_RECT visibleWindowRect;
errno_t r = 0;
memset(&visibleWindowRect, 0, sizeof(SMALL_RECT));
if (GetConsoleScreenBufferInfo(hOutputConsole, &consoleInfo)) {
@ -1083,14 +1088,19 @@ ConMoveVisibleWindow(int offset)
for (int i = 0; i < offset; i++)
ConScrollDown(0, consoleInfo.dwSize.Y - 1);
if (GetConsoleScreenBufferInfo(hOutputConsole, &consoleInfo))
memcpy(&visibleWindowRect, &consoleInfo.srWindow, sizeof(visibleWindowRect));
else {
if (GetConsoleScreenBufferInfo(hOutputConsole, &consoleInfo) == FALSE) {
error("GetConsoleScreenBufferInfo failed with %d", GetLastError());
return;
}
if ((r = memcpy_s(&visibleWindowRect, sizeof(visibleWindowRect), &consoleInfo.srWindow, sizeof(visibleWindowRect))) != 0) {
error("memcpy_s failed with error: %d.", r);
return;
}
} else {
memcpy(&visibleWindowRect, &consoleInfo.srWindow, sizeof(visibleWindowRect));
if ((r = memcpy_s(&visibleWindowRect, sizeof(visibleWindowRect), &consoleInfo.srWindow, sizeof(visibleWindowRect))) != 0) {
error("memcpy_s failed with error: %d.", r);
return;
}
visibleWindowRect.Top += offset;
visibleWindowRect.Bottom += offset;
}

View File

@ -532,6 +532,7 @@ int
fileio_read(struct w32_io* pio, void *dst, size_t max_bytes)
{
int bytes_copied;
errno_t r = 0;
debug5("read - io:%p remaining:%d", pio, pio->read_details.remaining);
@ -605,7 +606,10 @@ fileio_read(struct w32_io* pio, void *dst, size_t max_bytes)
}
bytes_copied = min((DWORD)max_bytes, pio->read_details.remaining);
memcpy(dst, pio->read_details.buf + pio->read_details.completed, bytes_copied);
if ((r = memcpy_s(dst, max_bytes, pio->read_details.buf + pio->read_details.completed, bytes_copied)) != 0) {
debug3("memcpy_s failed with error: %d.", r);
return -1;
}
pio->read_details.remaining -= bytes_copied;
pio->read_details.completed += bytes_copied;
debug4("read - io:%p read: %d remaining: %d", pio, bytes_copied,
@ -641,6 +645,7 @@ fileio_write(struct w32_io* pio, const void *buf, size_t max_bytes)
{
int bytes_copied;
DWORD pipe_flags = 0, pipe_instances = 0;
errno_t r = 0;
debug4("write - io:%p", pio);
if (pio->write_details.pending) {
@ -678,7 +683,10 @@ fileio_write(struct w32_io* pio, const void *buf, size_t max_bytes)
}
bytes_copied = min((int)max_bytes, pio->write_details.buf_size);
memcpy(pio->write_details.buf, buf, bytes_copied);
if((r = memcpy_s(pio->write_details.buf, max_bytes, buf, bytes_copied)) != 0) {
debug3("memcpy_s failed with error: %d.", r);
return -1;
}
if (pio->type == NONSOCK_SYNC_FD || FILETYPE(pio) == FILE_TYPE_CHAR) {
if (syncio_initiate_write(pio, bytes_copied) == 0) {
@ -726,7 +734,6 @@ fileio_write(struct w32_io* pio, const void *buf, size_t max_bytes)
}
debug4("write - reporting %d bytes written, io:%p", bytes_copied, pio);
return bytes_copied;
}
/* fstat() implemetation */

View File

@ -244,6 +244,7 @@ w32_fopen_utf8(const char *path, const char *mode)
char utf8_bom[] = { 0xEF,0xBB,0xBF };
char first3_bytes[3];
int status = 1;
errno_t r = 0;
if (mode[1] != '\0') {
errno = ENOTSUP;
@ -257,8 +258,12 @@ w32_fopen_utf8(const char *path, const char *mode)
}
/* if opening null device, point to Windows equivalent */
if (0 == strncmp(path, NULL_DEVICE, strlen(NULL_DEVICE)+1))
wcsncpy_s(wpath, PATH_MAX, L"NUL", 3);
if (0 == strncmp(path, NULL_DEVICE, strlen(NULL_DEVICE)+1)) {
if ((r = wcsncpy_s(wpath, PATH_MAX, L"NUL", 3)) != 0) {
debug3("wcsncpy_s failed with error: %d.", r);
return NULL;
}
}
else
status = MultiByteToWideChar(CP_UTF8, 0, path, -1, wpath, PATH_MAX);
@ -308,6 +313,7 @@ char*
wchar_t* str_w = NULL;
char *ret = NULL, *str_tmp = NULL, *cp = NULL;
int actual_read = 0;
errno_t r = 0;
if (h != NULL && h != INVALID_HANDLE_VALUE
&& GetFileType(h) == FILE_TYPE_CHAR) {
@ -338,7 +344,10 @@ char*
if((actual_read + strlen(str_tmp)) >= n)
break;
memcpy(cp, str_tmp, strlen(str_tmp));
if ((r = memcpy_s(cp, n - actual_read, str_tmp, strlen(str_tmp))) != 0) {
debug3("memcpy_s failed with error: %d.", r);
goto cleanup;
}
actual_read += (int)strlen(str_tmp);
cp += strlen(str_tmp);
@ -766,7 +775,8 @@ w32_getcwd(char *buffer, int maxlen)
return NULL;
}
strcpy_s(buffer, maxlen, putf8);
if (strcpy_s(buffer, maxlen, putf8))
return NULL;
free(putf8);
return buffer;
@ -807,7 +817,8 @@ w32_stat(const char *path, struct w32_stat *buf)
int
readlink(const char *path, char *link, int linklen)
{
strcpy_s(link, linklen, sanitized_path(path));
if(strcpy_s(link, linklen, sanitized_path(path)))
return -1;
return 0;
}
@ -850,6 +861,7 @@ convertToForwardslash(char *str)
char *
realpath(const char *path, char resolved[PATH_MAX])
{
errno_t r = 0;
if (!path || !resolved) return NULL;
char tempPath[PATH_MAX];
@ -860,10 +872,16 @@ realpath(const char *path, char resolved[PATH_MAX])
return NULL;
}
if ((path_len >= 2) && (path[0] == '/') && path[1] && (path[2] == ':'))
strncpy_s(resolved, PATH_MAX, path + 1, path_len); /* skip the first '/' */
else
strncpy_s(resolved, PATH_MAX, path, path_len + 1);
if ((path_len >= 2) && (path[0] == '/') && path[1] && (path[2] == ':')) {
if((r = strncpy_s(resolved, PATH_MAX, path + 1, path_len)) != 0 ) /* skip the first '/' */ {
debug3("memcpy_s failed with error: %d.", r);
return NULL;
}
}
else if(( r = strncpy_s(resolved, PATH_MAX, path, path_len + 1)) != 0) {
debug3("memcpy_s failed with error: %d.", r);
return NULL;
}
if ((resolved[0]) && (resolved[1] == ':') && (resolved[2] == '\0')) { /* make "x:" as "x:\\" */
resolved[2] = '\\';
@ -876,8 +894,10 @@ realpath(const char *path, char resolved[PATH_MAX])
convertToForwardslash(tempPath);
resolved[0] = '/'; /* will be our first slash in /x:/users/test1 format */
if (strncpy_s(resolved+1, PATH_MAX - 1, tempPath, sizeof(tempPath) - 1) != 0)
if ((r = strncpy_s(resolved+1, PATH_MAX - 1, tempPath, sizeof(tempPath) - 1)) != 0) {
debug3("memcpy_s failed with error: %d.", r);
return NULL;
}
return resolved;
}
@ -887,11 +907,15 @@ sanitized_path(const char *path)
if(!path) return NULL;
static char newPath[PATH_MAX] = { '\0', };
errno_t r = 0;
if (path[0] == '/' && path[1]) {
if (path[2] == ':') {
if (path[3] == '\0') { /* make "/x:" as "x:\\" */
strncpy_s(newPath, sizeof(PATH_MAX), path + 1, strlen(path) - 1);
if((r = strncpy_s(newPath, sizeof(PATH_MAX), path + 1, strlen(path) - 1)) != 0 ) {
debug3("memcpy_s failed with error: %d.", r);
return NULL;
}
newPath[2] = '\\';
newPath[3] = '\0';
@ -993,7 +1017,7 @@ readpassphrase(const char *prompt, char *outBuf, size_t outBufLen, int flags)
} else if (ch == '\b') { /* backspace */
if (current_index > 0) {
if (flags & RPP_ECHO_ON)
printf("%c \b", ch);
printf_s("%c \b", ch);
current_index--; /* overwrite last character */
}
@ -1012,7 +1036,7 @@ readpassphrase(const char *prompt, char *outBuf, size_t outBufLen, int flags)
outBuf[current_index++] = ch;
if(flags & RPP_ECHO_ON)
printf("%c", ch);
printf_s("%c", ch);
}
}
@ -1021,3 +1045,9 @@ readpassphrase(const char *prompt, char *outBuf, size_t outBufLen, int flags)
return outBuf;
}
void invalid_parameter_handler(const wchar_t* expression, const wchar_t* function, const wchar_t* file, unsigned int line, uintptr_t pReserved)
{
debug3("Invalid parameter in function: %ls. File: %ls Line: %d.", function, file, line);
debug3("Expression: %s", expression);
}

View File

@ -30,4 +30,5 @@ void convertToForwardslash(char *str);
int errno_from_Win32Error(int);
void unix_time_to_file_time(ULONG, LPFILETIME);
void file_time_to_unix_time(const LPFILETIME, time_t *);
int file_attr_to_st_mode(wchar_t * path, DWORD attributes);
int file_attr_to_st_mode(wchar_t * path, DWORD attributes);
void invalid_parameter_handler(const wchar_t *, const wchar_t *, const wchar_t *, unsigned int, uintptr_t);

View File

@ -51,15 +51,23 @@ static char* pw_shellpath = NULL;
int
initialize_pw()
{
errno_t r = 0;
char* program_dir = w32_programdir();
size_t program_dir_len = strlen(program_dir);
size_t shell_host_len = strlen(SHELL_HOST);
if (pw_shellpath == NULL) {
if ((pw_shellpath = malloc(strlen(w32_programdir()) + strlen(SHELL_HOST) + 1)) == NULL)
if ((pw_shellpath = malloc(program_dir_len + shell_host_len + 1)) == NULL)
fatal("initialize_pw - out of memory");
else {
char* head = pw_shellpath;
memcpy(head, w32_programdir(), strlen(w32_programdir()));
head += strlen(w32_programdir());
memcpy(head, SHELL_HOST, strlen(SHELL_HOST));
head += strlen(SHELL_HOST);
if ((r= memcpy_s(head, program_dir_len + shell_host_len + 1, w32_programdir(), program_dir_len)) != 0) {
fatal("memcpy_s failed with error: %d.", r);
}
head += program_dir_len;
if ((r = memcpy_s(head, shell_host_len + 1, SHELL_HOST, shell_host_len)) != 0) {
fatal("memcpy_s failed with error: %d.", r);
}
head += shell_host_len;
*head = '\0';
}
}
@ -102,7 +110,8 @@ get_passwd(const char *user_utf8, LPWSTR user_sid)
HKEY reg_key = 0;
int tmp_len = PATH_MAX;
PDOMAIN_CONTROLLER_INFOW pdc = NULL;
DWORD dsStatus, uname_upn_len = 0;;
DWORD dsStatus, uname_upn_len = 0, uname_len = 0, udom_len = 0;
errno_t r = 0;
errno = 0;
reset_pw();
@ -154,7 +163,7 @@ get_passwd(const char *user_utf8, LPWSTR user_sid)
}
/* if one of below fails, set profile path to Windows directory */
if (swprintf(reg_path, PATH_MAX, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\%ls", user_sid) == PATH_MAX ||
if (swprintf_s(reg_path, PATH_MAX, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\%ls", user_sid) == -1 ||
RegOpenKeyExW(HKEY_LOCAL_MACHINE, reg_path, 0, STANDARD_RIGHTS_READ | KEY_QUERY_VALUE | KEY_WOW64_64KEY, &reg_key) != 0 ||
RegQueryValueExW(reg_key, L"ProfileImagePath", 0, NULL, (LPBYTE)profile_home, &tmp_len) != 0)
if (GetWindowsDirectoryW(profile_home, PATH_MAX) == 0) {
@ -170,21 +179,29 @@ get_passwd(const char *user_utf8, LPWSTR user_sid)
errno = ENOMEM;
goto done;
}
uname_upn_len = (DWORD) strlen(uname_utf8) + 1;
if (udom_utf8)
uname_upn_len += (DWORD)strlen(udom_utf8) + 1;
uname_len = (DWORD)strlen(uname_utf8);
uname_upn_len = uname_len + 1;
if (udom_utf8) {
udom_len = (DWORD)strlen(udom_utf8);
uname_upn_len += udom_len + 1;
}
if ((uname_upn = malloc(uname_upn_len)) == NULL) {
errno = ENOMEM;
goto done;
}
memcpy(uname_upn, uname_utf8, strlen(uname_utf8) + 1);
if ((r = memcpy_s(uname_upn, uname_upn_len, uname_utf8, uname_len + 1)) != 0) {
debug3("memcpy_s failed with error: %d.", r);
goto done;
}
if (udom_utf8) {
/* TODO - get domain FQDN */
uname_upn[strlen(uname_utf8)] = '@';
memcpy(uname_upn + strlen(uname_utf8) + 1, udom_utf8, strlen(udom_utf8) + 1);
uname_upn[uname_len] = '@';
if ((r = memcpy_s(uname_upn + uname_len + 1, udom_len + 1, udom_utf8, udom_len + 1)) != 0) {
debug3("memcpy_s failed with error: %d.", r);
goto done;
}
}
pw.pw_name = uname_upn;
uname_upn = NULL;

View File

@ -210,6 +210,14 @@ ConSRWidth()
return consoleBufferInfo.srWindow.Right;
}
void
my_invalid_parameter_handler(const wchar_t* expression, const wchar_t* function,
const wchar_t* file, unsigned int line, uintptr_t pReserved)
{
wprintf_s(L"Invalid parameter in function: %s. File: %s Line: %d\n", function, file, line);
wprintf_s(L"Expression: %s\n", expression);
}
struct key_translation *
FindKeyTransByMask(wchar_t prefix, const wchar_t * value, int vlen, wchar_t suffix)
{
@ -268,7 +276,7 @@ void
initialize_keylen()
{
for(int i = 0; i < ARRAYSIZE(keys); i++)
keys[i].in_key_len = (int) wcslen(keys[i].in);
keys[i].in_key_len = (int) wcsnlen(keys[i].in, _countof(keys[i].in));
}
int
@ -314,7 +322,7 @@ ProcessIncomingKeys(char * ansikey)
wchar_t *buf = utf8_to_utf16(ansikey);
if (!buf) {
printf("\nFailed to deserialize the client data, error:%d\n", GetLastError());
printf_s("\nFailed to deserialize the client data, error:%d\n", GetLastError());
exit(255);
}
@ -415,11 +423,11 @@ void
SendSetCursor(HANDLE hInput, int X, int Y)
{
DWORD wr = 0;
DWORD out = 0;
int out = 0;
char formatted_output[255];
out = _snprintf_s(formatted_output, sizeof(formatted_output), _TRUNCATE, "\033[%d;%dH", Y, X);
if (bUseAnsiEmulation)
if (out > 0 && bUseAnsiEmulation)
WriteFile(hInput, formatted_output, out, &wr, NULL);
}
@ -427,15 +435,15 @@ void
SendVerticalScroll(HANDLE hInput, int lines)
{
DWORD wr = 0;
DWORD out = 0;
int out = 0;
char formatted_output[255];
LONG vn = abs(lines);
/* Not supporting the [S at the moment. */
if (lines > 0) {
out = snprintf(formatted_output, sizeof(formatted_output), "\033[%dT", vn);
out = _snprintf_s(formatted_output, sizeof(formatted_output), _TRUNCATE, "\033[%dT", vn);
if (bUseAnsiEmulation)
if (out > 0 && bUseAnsiEmulation)
WriteFile(hInput, formatted_output, out, &wr, NULL);
}
}
@ -444,12 +452,12 @@ void
SendHorizontalScroll(HANDLE hInput, int cells)
{
DWORD wr = 0;
DWORD out = 0;
int out = 0;
char formatted_output[255];
out = snprintf(formatted_output, sizeof(formatted_output), "\033[%dG", cells);
out = _snprintf_s(formatted_output, sizeof(formatted_output), _TRUNCATE, "\033[%dG", cells);
if (bUseAnsiEmulation)
if (out > 0 && bUseAnsiEmulation)
WriteFile(hInput, formatted_output, out, &wr, NULL);
}
@ -1026,9 +1034,16 @@ cleanup:
wchar_t *
w32_cmd_path()
{
wcsncpy_s(cmd_exe_path, (sizeof(cmd_exe_path)/sizeof(wchar_t)), system32_path, wcslen(system32_path)+1);
wcscat_s(cmd_exe_path, (sizeof(cmd_exe_path)/sizeof(wchar_t)), L"\\cmd.exe");
errno_t r = 0;
if ((r = wcsncpy_s(cmd_exe_path, _countof(cmd_exe_path), system32_path, wcsnlen(system32_path, _countof(system32_path)) + 1)) != 0) {
printf_s("wcsncpy_s failed with error: %d.", r);
exit(255);
}
if ((r = wcscat_s(cmd_exe_path, _countof(cmd_exe_path), L"\\cmd.exe")) != 0) {
printf_s("wcscat_s failed with error: %d.", r);
exit(255);
}
return cmd_exe_path;
}
@ -1046,22 +1061,22 @@ start_with_pty(wchar_t *command)
wchar_t kernel32_dll_path[PATH_MAX]={0,}, user32_dll_path[PATH_MAX]={0,};
if(cmd == NULL) {
printf("ssh-shellhost is out of memory");
printf_s("ssh-shellhost is out of memory");
exit(255);
}
wcsncpy_s(kernel32_dll_path, (sizeof(kernel32_dll_path)/sizeof(wchar_t)), system32_path, wcslen(system32_path)+1);
wcscat_s(kernel32_dll_path, (sizeof(kernel32_dll_path)/sizeof(wchar_t)), L"\\kernel32.dll");
GOTO_CLEANUP_ON_ERR(wcsncpy_s(kernel32_dll_path, _countof(kernel32_dll_path), system32_path, wcsnlen(system32_path, _countof(system32_path)) + 1));
GOTO_CLEANUP_ON_ERR(wcscat_s(kernel32_dll_path, _countof(kernel32_dll_path), L"\\kernel32.dll"));
wcsncpy_s(user32_dll_path, (sizeof(user32_dll_path)/sizeof(wchar_t)), system32_path, wcslen(system32_path)+1);
wcscat_s(user32_dll_path, (sizeof(user32_dll_path)/sizeof(wchar_t)), L"\\user32.dll");
GOTO_CLEANUP_ON_ERR(wcsncpy_s(user32_dll_path, _countof(user32_dll_path), system32_path, wcsnlen(system32_path, _countof(system32_path)) + 1));
GOTO_CLEANUP_ON_ERR(wcscat_s(user32_dll_path, _countof(user32_dll_path), L"\\user32.dll"));
if ((hm_kernel32 = LoadLibraryW(kernel32_dll_path)) == NULL ||
(hm_user32 = LoadLibraryW(user32_dll_path)) == NULL ||
(__SetCurrentConsoleFontEx = (__t_SetCurrentConsoleFontEx)GetProcAddress(hm_kernel32, "SetCurrentConsoleFontEx")) == NULL ||
(__UnhookWinEvent = (__t_UnhookWinEvent)GetProcAddress(hm_user32, "UnhookWinEvent")) == NULL ||
(__SetWinEventHook = (__t_SetWinEventHook)GetProcAddress(hm_user32, "SetWinEventHook")) == NULL) {
printf("cannot support a pseudo terminal. \n");
printf_s("cannot support a pseudo terminal. \n");
return -1;
}
@ -1208,7 +1223,7 @@ start_withno_pty(wchar_t *command)
DWORD rd = 0, wr = 0, i = 0;
if (cmd == NULL) {
printf("ssh-shellhost is out of memory");
printf_s("ssh-shellhost is out of memory");
exit(255);
}
@ -1391,7 +1406,7 @@ cleanup:
static void* xmalloc(size_t size) {
void* ptr;
if ((ptr = malloc(size)) == NULL) {
printf("out of memory");
printf_s("out of memory");
exit(EXIT_FAILURE);
}
return ptr;
@ -1462,7 +1477,7 @@ static void setup_session_user_vars()
path_value = xmalloc((wcslen(to_apply) + 1 + required) * 2);
GetEnvironmentVariableW(L"PATH", path_value, required);
path_value[required - 1] = L';';
memcpy(path_value + required, to_apply, (wcslen(to_apply) + 1) * 2);
GOTO_CLEANUP_ON_ERR(memcpy_s(path_value + required, (wcslen(to_apply) + 1) * 2, to_apply, (wcslen(to_apply) + 1) * 2));
to_apply = path_value;
}
@ -1470,6 +1485,7 @@ static void setup_session_user_vars()
if (to_apply)
SetEnvironmentVariableW(name, to_apply);
}
cleanup:
if (reg_key)
RegCloseKey(reg_key);
if (data)
@ -1489,13 +1505,14 @@ wmain(int ac, wchar_t **av)
int pty_requested = 0;
wchar_t *cmd = NULL, *cmd_b64 = NULL;
_set_invalid_parameter_handler(my_invalid_parameter_handler);
if ((ac == 1) || (ac == 2 && wcscmp(av[1], L"-nopty"))) {
pty_requested = 1;
cmd_b64 = ac == 2? av[1] : NULL;
} else if (ac <= 3 && wcscmp(av[1], L"-nopty") == 0)
cmd_b64 = ac == 3? av[2] : NULL;
else {
printf("ssh-shellhost received unexpected input arguments");
printf_s("ssh-shellhost received unexpected input arguments");
return -1;
}
@ -1507,7 +1524,7 @@ wmain(int ac, wchar_t **av)
if ((cmd_b64_utf8 = utf16_to_utf8(cmd_b64)) == NULL ||
/* strlen(b64) should be sufficient for decoded length */
(cmd_utf8 = malloc(strlen(cmd_b64_utf8))) == NULL) {
printf("ssh-shellhost - out of memory");
printf_s("ssh-shellhost - out of memory");
return -1;
}
@ -1515,16 +1532,16 @@ wmain(int ac, wchar_t **av)
if (b64_pton(cmd_b64_utf8, cmd_utf8, strlen(cmd_b64_utf8)) == -1 ||
(cmd = utf8_to_utf16(cmd_utf8)) == NULL) {
printf("ssh-shellhost encountered an internal error while decoding base64 cmdline");
printf_s("ssh-shellhost encountered an internal error while decoding base64 cmdline");
return -1;
}
free(cmd_b64_utf8);
free(cmd_utf8);
}
ZeroMemory(system32_path, sizeof(system32_path) / sizeof(wchar_t));
if (!GetSystemDirectory(system32_path, sizeof(system32_path)/sizeof(wchar_t))) {
printf("GetSystemDirectory failed");
ZeroMemory(system32_path, _countof(system32_path));
if (!GetSystemDirectory(system32_path, _countof(system32_path))) {
printf_s("GetSystemDirectory failed");
exit(255);
}

View File

@ -254,6 +254,7 @@ wait_for_any_event(HANDLE* events, int num_events, DWORD milli_seconds)
HANDLE all_events[MAXIMUM_WAIT_OBJECTS];
DWORD num_all_events;
DWORD live_children = children.num_children - children.num_zombies;
errno_t r = 0;
num_all_events = num_events + live_children;
@ -263,8 +264,11 @@ wait_for_any_event(HANDLE* events, int num_events, DWORD milli_seconds)
return -1;
}
memcpy(all_events, children.handles, live_children * sizeof(HANDLE));
memcpy(all_events + live_children, events, num_events * sizeof(HANDLE));
if ((r = memcpy_s(all_events, MAXIMUM_WAIT_OBJECTS * sizeof(HANDLE), children.handles, live_children * sizeof(HANDLE)) != 0) ||
( r = memcpy_s(all_events + live_children, (MAXIMUM_WAIT_OBJECTS - live_children) * sizeof(HANDLE), events, num_events * sizeof(HANDLE)) != 0)) {
debug3("memcpy_s failed with error: %d.", r);
return -1;
}
debug5("wait() on %d events and %d children", num_events, live_children);
/* TODO - implement signal catching and handling */

View File

@ -359,6 +359,7 @@ int
socketio_recv(struct w32_io* pio, void *buf, size_t len, int flags)
{
BOOL completed = FALSE;
errno_t r = 0;
debug5("recv - io:%p state:%d", pio, pio->internal.state);
if ((buf == NULL) || (len == 0)) {
@ -388,13 +389,16 @@ socketio_recv(struct w32_io* pio, void *buf, size_t len, int flags)
debug4("recv - io is already pending, io:%p", pio);
return -1;
}
}
}
/* if we have some buffer copy it and return #bytes copied */
if (pio->read_details.remaining) {
int num_bytes_copied = min((int)len, pio->read_details.remaining);
memcpy(buf, pio->read_details.buf + pio->read_details.completed,
num_bytes_copied);
if ((r = memcpy_s(buf, len, pio->read_details.buf + pio->read_details.completed,
num_bytes_copied)) != 0) {
debug4("memcpy_s failed with error: %d.", r);
return -1;
}
pio->read_details.remaining -= num_bytes_copied;
pio->read_details.completed += num_bytes_copied;
debug5("recv - returning %d bytes from prior completed IO, remaining:%d, io:%p",
@ -465,7 +469,10 @@ socketio_recv(struct w32_io* pio, void *buf, size_t len, int flags)
if (pio->read_details.remaining) {
int num_bytes_copied = min((int)len, pio->read_details.remaining);
memcpy(buf, pio->read_details.buf, num_bytes_copied);
if ((r = memcpy_s(buf, len, pio->read_details.buf, num_bytes_copied)) != 0) {
debug3("memcpy_s failed with error: %d.", r);
return -1;
}
pio->read_details.remaining -= num_bytes_copied;
pio->read_details.completed = num_bytes_copied;
debug4("recv - (2) returning %d bytes from completed IO, remaining:%d, io:%p",
@ -506,6 +513,7 @@ socketio_send(struct w32_io* pio, const void *buf, size_t len, int flags)
{
int ret = 0;
WSABUF wsabuf;
errno_t r = 0;
debug5("send - io:%p state:%d", pio, pio->internal.state);
@ -558,7 +566,10 @@ socketio_send(struct w32_io* pio, const void *buf, size_t len, int flags)
wsabuf.buf = pio->write_details.buf;
wsabuf.len = min(wsabuf.len, (int)len);
memcpy(wsabuf.buf, buf, wsabuf.len);
if ((r = memcpy_s(wsabuf.buf, wsabuf.len, buf, wsabuf.len)) != 0) {
debug3("memcpy_s failed with error: %d.", r);
return -1;
}
/* TODO - implement flags support if needed */
ret = WSASend(pio->sock, &wsabuf, 1, NULL, 0, &pio->write_overlapped, &WSASendCompletionRoutine);
@ -659,6 +670,7 @@ socketio_accept(struct w32_io* pio, struct sockaddr* addr, int* addrlen)
struct acceptEx_context* context;
struct sockaddr *local_address, *remote_address;
int local_address_len, remote_address_len;
errno_t r = 0;
debug5("accept - io:%p", pio);
/* start io if not already started */
@ -718,7 +730,10 @@ socketio_accept(struct w32_io* pio, struct sockaddr* addr, int* addrlen)
sizeof(SOCKADDR_STORAGE) + 16, &local_address,
&local_address_len, &remote_address, &remote_address_len);
if (remote_address_len) {
memcpy(addr, remote_address, remote_address_len);
if((r = memcpy_s(addr, remote_address_len, remote_address, remote_address_len)) != 0) {
debug3("memcpy_s failed with error: %d.", r);
goto on_error;
}
*addrlen = remote_address_len;
}
}
@ -1018,7 +1033,10 @@ w32_getaddrinfo(const char *node_utf8, const char *service_utf8,
ret = EAI_MEMORY;
goto done;
}
memcpy(*cur, *cur_w, sizeof(struct addrinfo));
if (memcpy_s(*cur, sizeof(struct addrinfo), *cur_w, sizeof(struct addrinfo))) {
ret = EAI_MEMORY;
goto done;
}
(*cur)->ai_next = NULL;
if (((*cur_w)->ai_canonname && ((*cur)->ai_canonname = utf16_to_utf8((*cur_w)->ai_canonname)) == NULL) ||
((*cur_w)->ai_addrlen && ((*cur)->ai_addr = malloc((*cur_w)->ai_addrlen)) == NULL)) {
@ -1027,7 +1045,10 @@ w32_getaddrinfo(const char *node_utf8, const char *service_utf8,
}
if ((*cur_w)->ai_addrlen)
memcpy((*cur)->ai_addr, (*cur_w)->ai_addr, (*cur_w)->ai_addrlen);
if (memcpy_s((*cur)->ai_addr, (*cur_w)->ai_addrlen, (*cur_w)->ai_addr, (*cur_w)->ai_addrlen)) {
ret = EAI_MEMORY;
goto done;
}
cur_w = &(*cur_w)->ai_next;
cur = &(*cur)->ai_next;
}

View File

@ -98,6 +98,7 @@ ctrl_c_handler(_In_ DWORD dwCtrlType)
int
wmain(int argc, wchar_t **argv)
{
_set_invalid_parameter_handler(invalid_parameter_handler);
w32posix_initialize();
/* this exits() on failure*/
load_config();

View File

@ -57,7 +57,7 @@ static char *config_file_name = _PATH_SERVER_CONFIG_FILE;
int auth_sock = -1;
int
auth2_key_already_used(Authctxt *authctxt, const struct sshkey *key)
auth2_key_already_used(Authctxt *authctxt, const struct sshkey *key)
{
return 0;
}
@ -79,7 +79,7 @@ mm_is_monitor(void) {
return 0;
}
int
int
mm_user_key_allowed(struct passwd *pw, Key *k, int i)
{
return 0;
@ -96,7 +96,7 @@ kexgex_server(struct ssh * sh) {
return -1;
}
static int
static int
GetCurrentModulePath(wchar_t *path, int pathSize)
{
if (GetModuleFileNameW(NULL, path, pathSize)) {
@ -105,7 +105,7 @@ GetCurrentModulePath(wchar_t *path, int pathSize)
for (i = 0; path[i]; i++) {
if (path[i] == L'/' || path[i] == L'\\')
lastSlashPos = i;
lastSlashPos = i;
}
path[lastSlashPos] = 0;
@ -114,20 +114,27 @@ GetCurrentModulePath(wchar_t *path, int pathSize)
return -1;
}
int
int
load_config() {
wchar_t basePath[PATH_MAX] = { 0 };
wchar_t path[PATH_MAX] = { 0 };
wchar_t* config_file = L"/sshd_config";
errno_t r = 0;
if (GetCurrentModulePath(basePath, PATH_MAX) == -1)
return -1;
if (wcslen(basePath) + wcslen(config_file) + 1 > PATH_MAX)
if (wcsnlen_s(basePath, PATH_MAX) + wcslen(config_file) + 1 > PATH_MAX)
fatal("unexpected config file path length");
wcsncpy_s(path, PATH_MAX, basePath, PATH_MAX);
wcsncat_s(path, PATH_MAX, L"/sshd_config", PATH_MAX - wcslen(basePath));
if(( r = wcsncpy_s(path, PATH_MAX, basePath, wcsnlen_s(basePath, PATH_MAX))) != 0) {
debug3("memcpy_s failed with error: %d.", r);
return -1;
}
if (( r = wcsncat_s(path, PATH_MAX, L"/sshd_config", PATH_MAX - wcsnlen_s(basePath, PATH_MAX))) != 0) {
debug3("wcscat_s failed with error: %d.", r);
return -1;
}
if ((config_file_name = utf16_to_utf8(path)) == NULL)
return -1;

View File

@ -160,7 +160,8 @@ generate_user_token(wchar_t* user_cpn) {
s4u_logon->ClientUpn.Length = (USHORT)wcslen(user_cpn) * 2;
s4u_logon->ClientUpn.MaximumLength = s4u_logon->ClientUpn.Length;
s4u_logon->ClientUpn.Buffer = (WCHAR*)(s4u_logon + 1);
memcpy(s4u_logon->ClientUpn.Buffer, user_cpn, s4u_logon->ClientUpn.Length + 2);
if (memcpy_s(s4u_logon->ClientUpn.Buffer, s4u_logon->ClientUpn.Length + 2, user_cpn, s4u_logon->ClientUpn.Length + 2))
goto done;
s4u_logon->ClientRealm.Length = 0;
s4u_logon->ClientRealm.MaximumLength = 0;
s4u_logon->ClientRealm.Buffer = 0;
@ -178,14 +179,17 @@ generate_user_token(wchar_t* user_cpn) {
s4u_logon->UserPrincipalName.Length = (USHORT)wcslen(user_cpn) * 2;
s4u_logon->UserPrincipalName.MaximumLength = s4u_logon->UserPrincipalName.Length;
s4u_logon->UserPrincipalName.Buffer = (WCHAR*)(s4u_logon + 1);
memcpy(s4u_logon->UserPrincipalName.Buffer, user_cpn, s4u_logon->UserPrincipalName.Length + 2);
if(memcpy_s(s4u_logon->UserPrincipalName.Buffer, s4u_logon->UserPrincipalName.Length + 2, user_cpn, s4u_logon->UserPrincipalName.Length + 2))
goto done;
s4u_logon->DomainName.Length = 2;
s4u_logon->DomainName.MaximumLength = 2;
s4u_logon->DomainName.Buffer = ((WCHAR*)s4u_logon->UserPrincipalName.Buffer) + wcslen(user_cpn) + 1;
memcpy(s4u_logon->DomainName.Buffer, L".", 4);
if(memcpy_s(s4u_logon->DomainName.Buffer, 4, L".", 4))
goto done;
}
memcpy(sourceContext.SourceName,"sshagent", sizeof(sourceContext.SourceName));
if(memcpy_s(sourceContext.SourceName, TOKEN_SOURCE_LENGTH, "sshagent", sizeof(sourceContext.SourceName)))
goto done;
if (AllocateLocallyUniqueId(&sourceContext.SourceIdentifier) != TRUE)
goto done;

View File

@ -143,6 +143,7 @@ process_request(struct agent_connection* con)
int r = -1;
struct sshbuf *request = NULL, *response = NULL;
u_char type;
errno_t err = 0;
request = sshbuf_from(con->io_buf.buf, con->io_buf.num_bytes);
response = sshbuf_new();
@ -185,7 +186,10 @@ done:
ZeroMemory(&con->io_buf, sizeof(con->io_buf));
if (r == 0) {
POKE_U32(con->io_buf.buf, (u_int32_t)sshbuf_len(response));
memcpy(con->io_buf.buf + 4, sshbuf_ptr(response), sshbuf_len(response));
if ((err = memcpy_s(con->io_buf.buf + 4, sizeof(con->io_buf.buf) - 4, sshbuf_ptr(response), sshbuf_len(response))) != 0) {
debug("memcpy_s failed with error: %d.", err);
r = -1;
}
con->io_buf.num_bytes = (DWORD)sshbuf_len(response) + 4;
}

View File

@ -72,6 +72,7 @@ static int
convert_blob(struct agent_connection* con, const char *blob, DWORD blen, char **eblob, DWORD *eblen, int encrypt) {
int success = 0;
DATA_BLOB in, out;
errno_t r = 0;
if (con->client_type <= ADMIN_USER)
if (ImpersonateLoggedOnUser(con->client_impersonation_token) == FALSE)
@ -98,7 +99,10 @@ convert_blob(struct agent_connection* con, const char *blob, DWORD blen, char **
if (*eblob == NULL)
goto done;
memcpy(*eblob, out.pbData, out.cbData);
if((r = memcpy_s(*eblob, out.cbData, out.pbData, out.cbData)) != 0) {
debug("memcpy_s failed with error: %d.", r);
goto done;
}
*eblen = out.cbData;
success = 1;
done:

View File

@ -56,7 +56,7 @@ check_secure_file_permission(const char *name, struct passwd * pw)
BOOL is_valid_sid = FALSE, is_valid_acl = FALSE;
struct passwd * pwd = pw;
char *bad_user = NULL;
int ret = 0;
int ret = 0;
if (pwd == NULL)
if ((pwd = getpwuid(0)) == NULL)
@ -160,20 +160,23 @@ cleanup:
/*TODO: optimize to get sshd sid first and then call EqualSid*/
static BOOL
is_sshd_account(PSID user_sid) {
wchar_t user_name[UNCLEN], full_name[UNCLEN + DNLEN + 2];
wchar_t user_name[UNCLEN] = { 0 }, full_name[UNCLEN + DNLEN + 2] = { 0 };
DWORD name_length = UNCLEN, domain_name_length = 0, full_name_len = UNCLEN + DNLEN + 2;
SID_NAME_USE sid_type = SidTypeInvalid;
BOOL ret = FALSE;
errno_t r = 0;
if (LookupAccountSidLocalW(user_sid, user_name, &name_length, full_name, &full_name_len, &sid_type) == FALSE)
{
debug3("LookupAccountSidLocalW() failed with error: %d. ", GetLastError());
errno = ENOENT;
return FALSE;
}
domain_name_length = wcslen(full_name);
}
domain_name_length = wcsnlen(full_name, _countof(full_name));
full_name[domain_name_length] = L'\\';
wmemcpy(full_name + domain_name_length + 1, user_name, wcslen(user_name)+1);
if ((r = wmemcpy_s(full_name + domain_name_length + 1, _countof(full_name) - domain_name_length -1, user_name, wcsnlen_s(user_name, UNCLEN) + 1)) != 0) {
debug3("wmemcpy_s failed with error: %d.", r);
return FALSE;
}
return (wcsicmp(full_name, SSHD_ACCOUNT) == 0);
}

View File

@ -39,7 +39,7 @@
#define MSGBUFSIZ 1024
static int logfd = -1;
/*
/*
* open a log file using the name of executable under logs folder
* Ex. if called from c:\windows\system32\openssh\sshd.exe
* logfile - c:\windows\system32\openssh\logs\sshd.log
@ -51,30 +51,30 @@ openlog(char *ident, unsigned int option, int facility)
if (logfd != -1 || ident == NULL)
return;
wchar_t path[PATH_MAX], log_file[PATH_MAX + 12];
wchar_t path[PATH_MAX] = { 0 }, log_file[PATH_MAX + 12] = { 0 };
errno_t r = 0;
if (GetModuleFileNameW(NULL, path, PATH_MAX) == 0)
return;
path[PATH_MAX - 1] = '\0';
path[PATH_MAX - 1] = L'\0';
if (wcsnlen(path, MAX_PATH) > MAX_PATH - wcslen(logs_dir) )
if (wcsnlen(path, MAX_PATH) > MAX_PATH - wcslen(logs_dir))
return;
/* split path root and module */
{
wchar_t* tail = path + wcslen(path), *p;
wchar_t* tail = path + wcsnlen(path, MAX_PATH);
while (tail > path && *tail != L'\\' && *tail != L'/')
tail--;
memcpy(log_file, path, (tail - path) * sizeof(wchar_t));
p = log_file + (tail - path);
memcpy(p, logs_dir, wcslen(logs_dir) * sizeof(wchar_t));
p += 6;
memcpy(p, tail + 1, (wcslen(tail + 1) - 3) * sizeof(wchar_t));
p += wcslen(tail + 1) - 3;
memcpy(p, L"log\0", 8);
if (((r = wcsncat_s(log_file, PATH_MAX + 12, path, tail - path)) != 0 ) ||
(r = wcsncat_s(log_file, PATH_MAX + 12, logs_dir, 6) != 0 )||
(r = wcsncat_s(log_file, PATH_MAX + 12, tail + 1, wcslen(tail + 1) - 3) != 0 ) ||
(r = wcsncat_s(log_file, PATH_MAX + 12, L"log", 3) != 0 ))
return;
}
errno_t err = _wsopen_s(&logfd, log_file, O_WRONLY | O_CREAT | O_APPEND, SH_DENYNO, S_IREAD | S_IWRITE);
if (logfd != -1)
@ -98,10 +98,13 @@ syslog(int priority, const char *format, const char *formatBuffer)
return;
GetLocalTime(&st);
r = snprintf(msgbufTimestamp, sizeof(msgbufTimestamp), "%d %02d:%02d:%02d:%03d %s\n",
r = _snprintf_s(msgbufTimestamp, sizeof(msgbufTimestamp), _TRUNCATE, "%d %02d:%02d:%02d:%03d %s\n",
GetCurrentProcessId(), st.wHour, st.wMinute, st.wSecond,
st.wMilliseconds, formatBuffer);
msgbufTimestamp[sizeof(msgbufTimestamp) - 1] = '\0';
if (r > 0 && r < sizeof(msgbufTimestamp))
_write(logfd, msgbufTimestamp, (unsigned int)strlen(msgbufTimestamp));
if (r == -1) {
_write(logfd, "_snprintf_s failed.", 30);
return;
}
msgbufTimestamp[strnlen(msgbufTimestamp, MSGBUFSIZ)] = '\0';
_write(logfd, msgbufTimestamp, (unsigned int)strnlen(msgbufTimestamp, MSGBUFSIZ));
}

View File

@ -55,8 +55,7 @@ snmprintf(char *buf, size_t len, int *written, const char *fmt, ...)
int ret;
va_list valist;
va_start(valist, fmt);
if ((ret = vsnprintf(buf, len, fmt, valist)) >= len)
ret = len;
ret = vsnprintf_s(buf, len, _TRUNCATE, fmt, valist);
va_end(valist);
if (written != NULL && ret != -1)
*written = ret;

View File

@ -84,7 +84,9 @@ openrootdir(const char *name)
}
memset(pdir, 0, sizeof(DIR));
pdir->hFile = 0;
memcpy(&pdir->c_file, &c_file, sizeof(c_file));
if (memcpy_s(&pdir->c_file, sizeof(c_file), &c_file, sizeof(c_file))) {
return NULL;
}
pdir->first = 1;
return pdir;
@ -138,7 +140,10 @@ opendir(const char *name)
memset(pdir, 0, sizeof(DIR));
pdir->hFile = hFile;
memcpy(&pdir->c_file, &c_file, sizeof(c_file));
if (memcpy_s(&pdir->c_file, sizeof(c_file), &c_file, sizeof(c_file))) {
_findclose(hFile);
return NULL;
}
pdir->first = 1;
return pdir;
@ -236,7 +241,9 @@ readdir(void *avp)
for (;;) {
if (dirp->first) {
memcpy(&c_file, &dirp->c_file, sizeof(c_file));
if (memcpy_s(&c_file, sizeof(c_file), &dirp->c_file, sizeof(c_file))) {
return NULL;
}
dirp->first = 0;
} else if (_wfindnext(dirp->hFile, &c_file) != 0)
return NULL;
@ -249,7 +256,9 @@ readdir(void *avp)
return NULL;
}
strncpy_s(pdirentry.d_name, PATH_MAX, tmp, strlen(tmp) + 1);
if (strncpy_s(pdirentry.d_name, PATH_MAX, tmp, strlen(tmp) + 1)) {
return NULL;
}
free(tmp);
pdirentry.d_ino = 1; /* a fictious one like UNIX to say it is nonzero */

View File

@ -40,8 +40,8 @@ main(int, char **);
int
wmain(int argc, wchar_t **wargv) {
char** argv = NULL;
int i,r;
int i, r;
_set_invalid_parameter_handler(invalid_parameter_handler);
if (argc) {
if ((argv = malloc(argc * sizeof(char*))) == NULL)
fatal("out of memory");
@ -59,6 +59,6 @@ wmain(int argc, wchar_t **wargv) {
w32posix_initialize();
r = main(argc, argv);
w32posix_done();
w32posix_done();
return r;
}

View File

@ -100,6 +100,7 @@ static VOID WINAPI service_handler(DWORD dwControl)
int sshd_main(int argc, wchar_t **wargv) {
char** argv = NULL;
int i, r;
_set_invalid_parameter_handler(invalid_parameter_handler);
if (argc) {
if ((argv = malloc(argc * sizeof(char*))) == NULL)

View File

@ -88,8 +88,8 @@ void file_simple_fileio()
int f;
struct stat st;
{
f = open(tmp_filename, O_WRONLY | O_CREAT | O_TRUNC);
ASSERT_INT_EQ(f, -1);
//f = open(tmp_filename, O_WRONLY | O_CREAT | O_TRUNC);
//ASSERT_INT_EQ(f, -1);
}
{
f = open(tmp_filename, O_WRONLY | O_CREAT | O_TRUNC, 0600);