[OS/UBUNTU] chmod 명령 : 파일에 실행 권한 설정하기
■ chmod 명령을 사용해 파일에 실행 권한을 설정하는 방법을 보여준다. 1. CTRL + ALT + T 키를 눌러서 [터미널]을 실행한다. 2. [터미널]에서
■ chmod 명령을 사용해 파일에 실행 권한을 설정하는 방법을 보여준다. 1. CTRL + ALT + T 키를 눌러서 [터미널]을 실행한다. 2. [터미널]에서
■ GRANT ALL PRIVILEGES ON DATABASE … TO … 명령을 사용해 해당 데이터베이스에 사용자 접근 권한을 설정하는 방법을 보여준다. ▶ 예제 코드
■ 사용자 권한을 조회하는 방법을 보여준다. (PGSQL) ▶ 실행 명령
1 2 3 |
postgres=# \du |
▶ 실행 결과
1 2 3 4 5 6 7 8 |
List of roles Role name | Attributes | Member of -----------+------------------------------------------------------------+----------- postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {} testuser1 | Superuser, Create DB | {} testuser2 | | {} |
■ 사용자 권한을 조회하는 방법을 보여준다. (테이블 수준) ▶ 예제 코드 (SQL)
1 2 3 4 5 6 7 8 9 |
SELECT TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, PRIVILEGE_TYPE FROM information_schema.role_table_grants WHERE GRANTEE = 'testuser1'; |
※ 해당 뷰 명칭은 소문자로 입력한다. ※ testuser1 :
■ 사용자 권한 조회하기 (스키마 수준) ▶ 예제 코드 (SQL)
1 2 3 4 5 6 7 8 9 10 |
SELECT N.NSPNAME AS SCHEMA, U.USENAME AS USER, HAS_SCHEMA_PRIVILEGE(U.USENAME, N.NSPNAME, 'USAGE' ) AS CAN_USE, HAS_SCHEMA_PRIVILEGE(U.USENAME, N.NSPNAME, 'CREATE') AS CAN_CREATE FROM PG_NAMESPACE N CROSS JOIN PG_USER U WHERE U.USENAME = 'testuser1'; |
▶ 실행 결과
1 2 3 4 5 6 7 8 9 10 11 |
schema | user | can_use | can_create --------------------+-----------+---------+------------ pg_toast | testuser1 | t | t pg_temp_1 | testuser1 | t | t pg_toast_temp_1 | testuser1 | t | t pg_catalog | testuser1 | t | t public | testuser1 | t | t information_schema | testuser1 | t | t (6 rows) |
■ 사용자 권한을 조회하는 방법을 보여준다. (데이터베이스 수준) ▶ 예제 코드 (SQL)
1 2 3 4 5 6 7 8 9 10 |
SELECT D.DATNAME AS DATABASE, U.USENAME AS USER, HAS_DATABASE_PRIVILEGE(U.USENAME, D.DATNAME, 'CONNECT') AS CAN_CONNECT, HAS_DATABASE_PRIVILEGE(U.USENAME, D.DATNAME, 'CREATE' ) AS CAN_CREATE FROM PG_DATABASE D CROSS JOIN PG_USER U WHERE U.USENAME = 'testuser1'; |
※ testuser1 : 사용자명, 대소문자 구분한다. ▶ 실행 결과
■ CodeAccessPermission 클래스의 Demand 메소드를 사용해 권한을 감지하는 방법을 보여준다. ▶ 예제 코드 (C#)
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 |
using System; using System.IO; using System.Security; using System.Security.Permissions; namespace TestProject { /// <summary> /// 파일 헬퍼 /// </summary> public class FileHelper { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 저장하기 - Save(filePath) /// <summary> /// 저장하기 /// </summary> /// <param name="filePath">파일 경로</param> public static void Save(string filePath) { if(IsPermissionGranted(new FileIOPermission(FileIOPermissionAccess.Write, filePath))) { using(FileStream stream = File.Create(filePath)) { using(StreamWriter writer = new StreamWriter(stream)) { writer.WriteLine("I can write to local disk."); } } } else { Console.WriteLine("I can't write to local disk."); } } #endregion //////////////////////////////////////////////////////////////////////////////// Private #region 권한 부여 여부 구하기 - IsPermissionGranted(permission) /// <summary> /// 권한 부여 여부 구하기 /// </summary> /// <param name="permission">권한</param> /// <returns>권한 부여 여부</returns> private static bool IsPermissionGranted(CodeAccessPermission permission) { try { permission.Demand(); return true; } catch { return false; } } #endregion } } |
■ sudo 명령 사용시 패스워드 입력없이 사용하는 방법을 보여준다. 1. CTRL + ALT + T 키를 눌러서 [터미널]을 실행한다. 2. [터미널]에서 아래
■ chmod 명령을 사용해 사용자에게 폴더 쓰기 권한을 부여하는 방법을 보여준다. 1. CTRL + ALT + T 키를 눌러서 [터미널]을 실행한다. 2.
■ Directory 클래스의 GetAccessControl 정적 메소드를 사용해 디렉토리 쓰기 권한을 체크하는 방법을 보여준다. ▶ Directory 클래스 : GetAccessControl 정적 메소드를 사용해 디렉토리
■ File 클래스의 Create 정적 메소드를 사용해 디렉토리 쓰기 가능 여부를 구하는 방법을 보여준다. ▶ 예제 코드 (C#)
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 |
#region 디렉토리 쓰기 가능 여부 구하기 - IsDirectoryWritable(directoryPath, throwIfFails) /// <summary> /// 디렉토리 쓰기 가능 여부 구하기 /// </summary> /// <param name="directoryPath">디렉토리 경로</param> /// <param name="throwIfFails">실패시 예외 발생 여부</param> /// <returns>디렉토리 쓰기 가능 여부</returns> public bool IsDirectoryWritable(string directoryPath, bool throwIfFails = false) { try { using(FileStream fileStream = File.Create(Path.Combine(directoryPath, Path.GetRandomFileName()), 1, FileOptions.DeleteOnClose)) { } return true; } catch { if(throwIfFails) { throw; } else { return false; } } } #endregion |
■ Directory 클래스의 GetAccessControl 정적 메소드를 사용해 디렉토리 권한을 체크하는 방법을 보여준다. ▶ Directory 클래스 : GetAccessControl 정적 메소드를 사용해 디렉토리 권한
■ PrincipalPermission 클래스의 Demand 메소드를 사용해 관리자 권한을 요구하는 방법을 보여준다. [비관리자 권한으로 실행한 경우] [관리자 권한으로 실행한 경우] ▥▥▥IMAGE0▥▥▥ ▥▥▥IMAGE1▥▥▥ ▶
■ iOS에서 복수 윈도우 권한을 설정하는 방법을 보여준다. ▶ Platforms/iOS/Info.plist (XML)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> ... <key>UIApplicationSupportsMultipleScenes</key> <true /> <key>UISceneConfigurations</key> <dict> <key>UIWindowSceneSessionRoleApplication</key> <array> <dict> <key>UISceneConfigurationName</key> <string>__MAUI_DEFAULT_SCENE_CONFIGURATION__</string> <key>UISceneDelegateClassName</key> <string>SceneDelegate</string> </dict> </array> </dict> ... </dict> </plist> |
■ BasePlatformPermission 클래스를 사용해 권한을 확장하는 방법을 보여준다. ▶ Platforms/Android/AndroidManifest.xml
1 2 3 4 5 6 7 8 9 10 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"> <application android:allowBackup="true" android:icon="@mipmap/appicon" android:roundIcon="@mipmap/appicon_round" android:supportsRtl="true"></application> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> </manifest> |
▶ ReadWriteStoragePermission.cs
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 |
namespace TestProject; /// <summary> /// 저장소 읽기/쓰기 권한 /// </summary> public class ReadWriteStoragePermission : Permissions.BasePlatformPermission { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 요청 권한 배열 - RequiredPermissions /// <summary> /// 요청 권한 배열 /// </summary> public override (string androidPermission, bool isRuntime)[] RequiredPermissions => new List<(string androidPermission, bool isRuntime)> { (global::Android.Manifest.Permission.ReadExternalStorage , true), (global::Android.Manifest.Permission.WriteExternalStorage, true) }.ToArray(); #endregion } |
▶ MainPage.xaml
1 2 3 4 5 6 7 8 9 10 11 |
<?xml version="1.0" encoding="utf-8" ?> <ContentPage x:Class="TestProject.MainPage" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"> <Button x:Name="requireButton" HorizontalOptions="Center" VerticalOptions="Center" Text="권한 요청" /> </ContentPage> |
▶ MainPage.xaml.cs
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 |
namespace TestProject; /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : ContentPage { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainPage() /// <summary> /// 생성자 /// </summary> public MainPage() { InitializeComponent(); this.requireButton.Clicked += requireButton_Clicked; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private #region 권한 요청 버튼 클릭시 처리하기 - requireButton_Clicked(sender, e) /// <summary> /// 권한 요청 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private async void requireButton_Clicked(object sender, EventArgs e) { PermissionStatus status = await Permissions.RequestAsync<ReadWriteStoragePermission>(); await DisplayAlert("INFORMATION", status.ToString(), "확인"); } #endregion } |
TestProject.zip
■ Permissions 클래스의 RequestAsync 정적 메소드를 사용해 권한을 요청하는 방법을 보여준다. ▶ 예제 코드 (C#)
1 2 3 |
PermissionStatus status = await Permissions.RequestAsync<Permissions.LocationWhenInUse>(); |
■ Permissions 클래스의 CheckStatusAsync 정적 메소드를 사용해 권한을 체크하는 방법을 보여준다. ▶ 예제 코드 (C#)
1 2 3 |
PermissionStatus status = await Permissions.CheckStatusAsync<Permissions.LocationWhenInUse>(); |
■ File 클래스의 GetAccessControl 정적 메소드를 사용해 파일 소유자를 구하는 방법을 보여준다. ▶ 예제 코드 (C#)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.IO; using System.Security.AccessControl; using System.Security.Principal; FileSecurity fileSecurity = File.GetAccessControl(@"d:\arca.bat"); IdentityReference identityReference = fileSecurity.GetOwner(typeof(SecurityIdentifier)); NTAccount ntAccount = identityReference.Translate(typeof(NTAccount)) as NTAccount; Console.WriteLine(ntAccount.Value); |
■ Button 클래스에서 권한 상승 필요 표시 버튼을 사용하는 방법을 보여준다. ▶ CustomButton.cs
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 |
using System; using System.Runtime.InteropServices; using System.Security.Principal; using System.Windows.Forms; namespace TestProject { /// <summary> /// 커스텀 버튼 /// </summary> public class CustomButton : Button { //////////////////////////////////////////////////////////////////////////////////////////////////// Import ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 메시지 보내기 - SendMessage(windowHandle, message, wordParameter, longParameter) /// <summary> /// 메시지 보내기 /// </summary> /// <param name="windowHandleRef">윈도우 핸들 참조</param> /// <param name="message">메시지</param> /// <param name="wordParameter">WORD 매개 변수</param> /// <param name="longParameter">LONG 매개 변수</param> /// <returns>처리 결과</returns> [DllImport("user32")] private static extern IntPtr SendMessage(HandleRef windowHandleRef, uint message, IntPtr wordParameter, IntPtr longParameter); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// BCM_SETSHIELD /// </summary> private uint BCM_SETSHIELD = 0x0000160c; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - CustomButton() /// <summary> /// 생성자 /// </summary> public CustomButton() { FlatStyle = FlatStyle.System; if(!IsAdministratorRole()) { ShowShield(); } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private #region 관리자 역할 여부 구하기 - IsAdministratorRole() /// <summary> /// 관리자 역할 여부 구하기 /// </summary> /// <returns>관리자 역할 여부</returns> private bool IsAdministratorRole() { WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent(); WindowsPrincipal windowsPrincipal = new WindowsPrincipal(windowsIdentity); return windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator); } #endregion #region 방패 표시하기 - ShowShield() /// <summary> /// 방패 표시하기 /// </summary> private void ShowShield() { IntPtr wordParameter = new IntPtr(0); IntPtr longParamerer = new IntPtr(1); SendMessage(new HandleRef(this, Handle), BCM_SETSHIELD, wordParameter, longParamerer); } #endregion } } |
▶ MainForm.cs
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 |
using System.Windows.Forms; namespace TestProject { /// <summary> /// 메인 폼 /// </summary> public partial class MainForm : Form { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainForm() /// <summary> /// 생성자 /// </summary> public MainForm() { InitializeComponent(); } #endregion } } |
TestProject.zip
■ FileIOPermission 클래스를 사용해 파일 및 디렉토리 읽기 권한을 구하는 방법을 보여준다. ▶ 예제 코드 (C#)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Security; using System.Security.Permissions; FileIOPermission fileIOPermission = new FileIOPermission(PermissionState.None); fileIOPermission.AllLocalFiles = FileIOPermissionAccess.Read; try { fileIOPermission.Demand(); } catch(SecurityException exception) { Console.WriteLine(exception.Message); } |
■ FileIOPermission 클래스를 사용해 파일 및 디렉토리 읽기/쓰기 권한을 구하는 방법을 보여준다. ▶ 예제 코드 (C#)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Security; using System.Security.Permissions; FileIOPermission fileIOPermission = new FileIOPermission(FileIOPermissionAccess.Read, "D:\\test"); fileIOPermission.AddPathList(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, "D:\\sample.txt"); try { fileIOPermission.Demand(); } catch(SecurityException exception) { Console.WriteLine(exception.Message); } |
■ Thread 클래스를 사용해 특정 사용자 권한으로 스레드를 실행하는 방법을 보여준다. ▶ SECURITY_IMPERSONATION_LEVEL.cs
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 |
namespace TestProject { /// <summary> /// 보안 가장 레벨 /// </summary> public enum SECURITY_IMPERSONATION_LEVEL { /// <summary> /// SecurityAnonymous /// </summary> SecurityAnonymous = 0, /// <summary> /// SecurityIdentification /// </summary> SecurityIdentification = 1, /// <summary> /// SecurityImpersonation /// </summary> SecurityImpersonation = 2, /// <summary> /// SecurityDelegation /// </summary> SecurityDelegation = 3 } } |
▶ TOKEN_TYPE.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
namespace TestProject { /// <summary> /// 토큰 타입 /// </summary> public enum TOKEN_TYPE { /// <summary> /// TokenPrimary /// </summary> TokenPrimary = 1, /// <summary> /// TokenImpersonation /// </summary> TokenImpersonation = 2 } } |
▶ Program.cs
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 |
using System; using System.Runtime.InteropServices; using System.Security.Principal; using System.Threading; namespace TestProject { /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Import ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 사용자 로그온하기 - LogonUser(userName, domain, password, logonType, logonProvider, userToken) /// <summary> /// 사용자 로그온하기 /// </summary> /// <param name="userName">사용자명</param> /// <param name="domain">도메인</param> /// <param name="password">패스워드</param> /// <param name="logonType">로그온 타입</param> /// <param name="logonProvider">로그온 공급자</param> /// <param name="userToken">사용자 토큰</param> /// <returns>처리 결과</returns> [DllImport("advapi32", EntryPoint = "LogonUser", SetLastError = true)] private static extern bool LogonUser(string userName, string domain, string password, int logonType, int logonProvider, out IntPtr userToken); #endregion #region 토큰 복제하기 (확장) - DuplicateTokenEx(existingTokenHandle, desiredAccess, threadAttributeHandle, tokenType, impersonationLevel, duplicateTokenHandle) /// <summary> /// 토큰 복제하기 (확장) /// </summary> /// <param name="existingTokenHandle">기존 토클 핸들</param> /// <param name="desiredAccess">희망 액세스</param> /// <param name="threadAttributeHandle">스레드 어트리뷰트 핸들</param> /// <param name="tokenType">토큰 타입</param> /// <param name="impersonationLevel">가장 레벨</param> /// <param name="duplicateTokenHandle">복제 토큰 핸들</param> /// <returns>처리 결과</returns> [DllImport("advapi32", EntryPoint = "DuplicateTokenEx")] private static extern bool DuplicateTokenEx ( IntPtr existingTokenHandle, uint desiredAccess, IntPtr threadAttributeHandle, int tokenType, int impersonationLevel, ref IntPtr duplicateTokenHandle ); #endregion #region 스레드 토큰 설정하기 - SetThreadToken(threadHandle, tokenHandle) /// <summary> /// 스레드 토큰 설정하기 /// </summary> /// <param name="threadHandle">스레드 핸들</param> /// <param name="tokenHandle">토큰 핸들</param> /// <returns>처리 결과</returns> [DllImport("advapi32", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool SetThreadToken(IntPtr threadHandle, IntPtr tokenHandle); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> private static void Main() { Console.WriteLine($"Main 함수 : {WindowsIdentity.GetCurrent().Name}"); IntPtr userTokenHandle; LogonUser("user2", ".", "password2", 8, 0, out userTokenHandle); IntPtr copyUserTokenHandle = IntPtr.Zero; DuplicateTokenEx ( userTokenHandle, 0, IntPtr.Zero, (int)SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, (int)TOKEN_TYPE.TokenImpersonation, ref copyUserTokenHandle ); Thread thread = new Thread(new ParameterizedThreadStart(ExecuteThread)); thread.Start(copyUserTokenHandle); } #endregion #region 스레드 실행하기 - ExecuteThread(parameter) /// <summary> /// 스레드 실행하기 /// </summary> /// <param name="parameter">매개 변수</param> private static void ExecuteThread(object parameter) { IntPtr userTokenHandle = (IntPtr)parameter; SetThreadToken(IntPtr.Zero, userTokenHandle); WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent(); Console.WriteLine($"ProcessThread 함수 : {WindowsIdentity.GetCurrent().Name}"); } #endregion } } |
TestProject.zip
■ 스푸핑(spoofing) 기법을 사용해 시스템 권한으로 프로세스를 실행하는 방법을 보여준다. ▶ HANDLE_FLAG.cs
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 |
using System; namespace TestProject { /// <summary> /// 핸들 플래그 /// </summary> [Flags] public enum HANDLE_FLAG : uint { /// <summary> /// NONE /// </summary> NONE = 0, /// <summary> /// INHERIT /// </summary> INHERIT = 1, /// <summary> /// PROTECT_FROM_CLOSE /// </summary> PROTECT_FROM_CLOSE = 2 } } |
▶ PROCESS_INFORMATION.cs
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 |
using System; using System.Runtime.InteropServices; namespace TestProject { /// <summary> /// 프로세스 정보 /// </summary> [StructLayout(LayoutKind.Sequential)] public struct PROCESS_INFORMATION { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Public #region Field /// <summary> /// 프로세스 핸들 /// </summary> public IntPtr ProcessHandle; /// <summary> /// 스레드 핸들 /// </summary> public IntPtr ThreadHandle; /// <summary> /// 프로세스 ID /// </summary> public int ProcessID; /// <summary> /// 스레드 ID /// </summary> public int ThreadID; #endregion } } |
▶ ProcessAccessFlag.cs
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 |
using System; namespace TestProject { /// <summary> /// 프로세스 액세스 플래그 /// </summary> [Flags] public enum ProcessAccessFlag : uint { /// <summary> /// All /// </summary> All = 0x001f0fff, /// <summary> /// Terminate /// </summary> Terminate = 0x00000001, /// <summary> /// CreateThread /// </summary> CreateThread = 0x00000002, /// <summary> /// VirtualMemoryOperation /// </summary> VirtualMemoryOperation = 0x00000008, /// <summary> /// VirtualMemoryRead /// </summary> VirtualMemoryRead = 0x00000010, /// <summary> /// VirtualMemoryWrite /// </summary> VirtualMemoryWrite = 0x00000020, /// <summary> /// DuplicateHandle /// </summary> DuplicateHandle = 0x00000040, /// <summary> /// CreateProcess /// </summary> CreateProcess = 0x000000080, /// <summary> /// SetQuota /// </summary> SetQuota = 0x00000100, /// <summary> /// SetInformation /// </summary> SetInformation = 0x00000200, /// <summary> /// QueryInformation /// </summary> QueryInformation = 0x00000400, /// <summary> /// QueryLimitedInformation /// </summary> QueryLimitedInformation = 0x00001000, /// <summary> /// Synchronize /// </summary> Synchronize = 0x00100000 } } |
▶ SECURITY_ATTRIBUTES.cs
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 |
using System; using System.Runtime.InteropServices; namespace TestProject { /// <summary> /// 보안 어트리뷰트 /// </summary> [StructLayout(LayoutKind.Sequential)] public struct SECURITY_ATTRIBUTES { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Public #region Field /// <summary> /// 길이 /// </summary> public int Length; /// <summary> /// 보안 설명자 /// </summary> public IntPtr SecurityDescriptor; /// <summary> /// 핸들 상속 여부 /// </summary> [MarshalAs(UnmanagedType.Bool)] public bool InheritHandle; #endregion } } |
■ 윈도우즈 서비스에서 시스템 권한으로 프로세스를 실행하는 방법을 보여준다. [TestLibrary 프로젝트] ▶ ProcessHelper.cs
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 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 |
using System; using System.Runtime.InteropServices; using System.Security.Principal; namespace TestLibrary { /// <summary> /// 프로세스 헬퍼 /// </summary> public static class ProcessHelper { //////////////////////////////////////////////////////////////////////////////////////////////////// Enumeration ////////////////////////////////////////////////////////////////////////////////////////// Private #region 윈도우 표시 타입 - ShowWindowType /// <summary> /// 윈도우 표시 타입 /// </summary> private enum ShowWindowType { /// <summary> /// SW_HIDE /// </summary> SW_HIDE = 1, /// <summary> /// SW_SHOWNORMAL /// </summary> SW_SHOWNORMAL = 1, /// <summary> /// SW_NORMAL /// </summary> SW_NORMAL = 1, /// <summary> /// SW_SHOWMINIMIZED /// </summary> SW_SHOWMINIMIZED = 2, /// <summary> /// SW_SHOWMAXIMIZED /// </summary> SW_SHOWMAXIMIZED = 3, /// <summary> /// SW_MAXIMIZE /// </summary> SW_MAXIMIZE = 3, /// <summary> /// SW_SHOWNOACTIVATE /// </summary> SW_SHOWNOACTIVATE = 4, /// <summary> /// SW_SHOW /// </summary> SW_SHOW = 5, /// <summary> /// SW_MINIMIZE /// </summary> SW_MINIMIZE = 6, /// <summary> /// SW_SHOWMINNOACTIVE /// </summary> SW_SHOWMINNOACTIVE = 7, /// <summary> /// SW_SHOWN /// </summary> SW_SHOWN = 8, /// <summary> /// SW_RESTORE /// </summary> SW_RESTORE = 9, /// <summary> /// SW_SHOWDEFAULT /// </summary> SW_SHOWDEFAULT = 10, /// <summary> /// SW_MAX /// </summary> SW_MAX = 10 } #endregion #region WTS 연결 상태 클래스 - WTS_CONNECTSTATE_CLASS /// <summary> /// WTS 연결 상태 클래스 /// </summary> private enum WTS_CONNECTSTATE_CLASS { /// <summary> /// WTSActive /// </summary> WTSActive, /// <summary> /// WTSConnected /// </summary> WTSConnected, /// <summary> /// WTSConnectQuery /// </summary> WTSConnectQuery, /// <summary> /// WTSShadow /// </summary> WTSShadow, /// <summary> /// WTSDisconnected /// </summary> WTSDisconnected, /// <summary> /// WTSIdle /// </summary> WTSIdle, /// <summary> /// WTSListen /// </summary> WTSListen, /// <summary> /// WTSReset /// </summary> WTSReset, /// <summary> /// WTSDown /// </summary> WTSDown, /// <summary> /// WTSInit /// </summary> WTSInit } #endregion #region 보안 가장 레벨 - SECURITY_IMPERSONATION_LEVEL /// <summary> /// 보안 가장 레벨 /// </summary> private enum SECURITY_IMPERSONATION_LEVEL { /// <summary> /// SecurityAnonymous /// </summary> SecurityAnonymous = 0, /// <summary> /// SecurityIdentification /// </summary> SecurityIdentification = 1, /// <summary> /// SecurityImpersonation /// </summary> SecurityImpersonation = 2, /// <summary> /// SecurityDelegation /// </summary> SecurityDelegation = 3 } #endregion #region 토큰 타입 - TOKEN_TYPE /// <summary> /// 토큰 타입 /// </summary> private enum TOKEN_TYPE { /// <summary> /// TokenPrimary /// </summary> TokenPrimary = 1, /// <summary> /// TokenImpersonation /// </summary> TokenImpersonation = 2 } #endregion #region 토큰 정보 클래스 - TOKEN_INFORMATION_CLASS /// <summary> /// 토큰 정보 클래스 /// </summary> private enum TOKEN_INFORMATION_CLASS { /// <summary> /// TokenUser /// </summary> TokenUser = 1, /// <summary> /// TokenGroups /// </summary> TokenGroups, /// <summary> /// TokenPrivileges /// </summary> TokenPrivileges, /// <summary> /// TokenOwner /// </summary> TokenOwner, /// <summary> /// TokenPrimaryGroup /// </summary> TokenPrimaryGroup, /// <summary> /// TokenDefaultDACL /// </summary> TokenDefaultDACL, /// <summary> /// TokenSource /// </summary> TokenSource, /// <summary> /// TokenType /// </summary> TokenType, /// <summary> /// TokenImpersonationLevel /// </summary> TokenImpersonationLevel, /// <summary> /// TokenStatistics /// </summary> TokenStatistics, /// <summary> /// TokenRestrictedSIDs /// </summary> TokenRestrictedSIDs, /// <summary> /// TokenSessionID /// </summary> TokenSessionID, /// <summary> /// TokenGroupsAndPrivileges /// </summary> TokenGroupsAndPrivileges, /// <summary> /// TokenSessionReference /// </summary> TokenSessionReference, /// <summary> /// TokenSandBoxInert /// </summary> TokenSandBoxInert, /// <summary> /// TokenAuditPolicy /// </summary> TokenAuditPolicy, /// <summary> /// TokenOrigin /// </summary> TokenOrigin, /// <summary> /// TokenElevationType /// </summary> TokenElevationType, /// <summary> /// TokenLinkedToken /// </summary> TokenLinkedToken, /// <summary> /// TokenElevation /// </summary> TokenElevation, /// <summary> /// TokenHasRestrictions /// </summary> TokenHasRestrictions, /// <summary> /// TokenAccessInformation /// </summary> TokenAccessInformation, /// <summary> /// TokenVirtualizationAllowed /// </summary> TokenVirtualizationAllowed, /// <summary> /// TokenVirtualizationEnabled /// </summary> TokenVirtualizationEnabled, /// <summary> /// TokenIntegrityLevel /// </summary> TokenIntegrityLevel, /// <summary> /// TokenUIAccess /// </summary> TokenUIAccess, /// <summary> /// TokenMandatoryPolicy /// </summary> TokenMandatoryPolicy, /// <summary> /// TokenLogonSid /// </summary> TokenLogonSID, /// <summary> /// MaxTokenInfoClass /// </summary> MaxTokenInfoClass } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Structure ////////////////////////////////////////////////////////////////////////////////////////// Private #region 프로세스 정보 - PROCESS_INFORMATION /// <summary> /// 프로세스 정보 /// </summary> [StructLayout(LayoutKind.Sequential)] public struct PROCESS_INFORMATION { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Public #region Field /// <summary> /// 프로세스 핸들 /// </summary> public IntPtr ProcessHandle; /// <summary> /// 스레드 핸들 /// </summary> public IntPtr ThreadHandle; /// <summary> /// 프로세스 ID /// </summary> public uint ProcessID; /// <summary> /// 스레드 ID /// </summary> public uint ThreadID; #endregion } #endregion #region 시작 정보 - STARTUPINFO /// <summary> /// 시작 정보 /// </summary> [StructLayout(LayoutKind.Sequential)] private struct STARTUPINFO { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Public #region Field /// <summary> /// 바이트 카운트 /// </summary> public int ByteCount; /// <summary> /// 예약 문자열 /// </summary> public string ReservedString; /// <summary> /// 데스크톱 /// </summary> public string Desktop; /// <summary> /// 제목 /// </summary> public string Title; /// <summary> /// X /// </summary> public uint X; /// <summary> /// ㅛ /// </summary> public uint Y; /// <summary> /// X 크기 /// </summary> public uint XSize; /// <summary> /// Y 크기 /// </summary> public uint YSize; /// <summary> /// X 카운트 (문자 단위) /// </summary> public uint XCountCharacter; /// <summary> /// Y 카운트 (문자 단위) /// </summary> public uint YCountCharacter; /// <summary> /// 채우기 어트리뷰트 /// </summary> public uint FillAttribute; /// <summary> /// 플래그 /// </summary> public uint Flag; /// <summary> /// 윈도우 표시 /// </summary> public short ShowWindow; /// <summary> /// 예약 핸들 바이트 카운트 /// </summary> public short ByteCountReservedHandle; /// <summary> /// 예약 핸들 /// </summary> public IntPtr ReservedHandle; /// <summary> /// 표준 입력 핸들 /// </summary> public IntPtr StandardInputHandle; /// <summary> /// 표준 출력 핸들 /// </summary> public IntPtr StandardOutputHandle; /// <summary> /// 표준 에러 핸들 /// </summary> public IntPtr StandardErrorHandle; #endregion } #endregion #region WTS 세션 정보 - WTS_SESSION_INFO /// <summary> /// WTS 세션 정보 /// </summary> [StructLayout(LayoutKind.Sequential)] private struct WTS_SESSION_INFO { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Public #region Field /// <summary> /// 세션 ID /// </summary> public readonly uint SessionID; /// <summary> /// WIN 스테이션명 /// </summary> [MarshalAs(UnmanagedType.LPStr)] public readonly string WinStationName; /// <summary> /// 상태 /// </summary> public readonly WTS_CONNECTSTATE_CLASS State; #endregion } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Import ////////////////////////////////////////////////////////////////////////////////////////// Static #region 사용자로 프로세스 생성하기 - CreateProcessAsUser(tokenHandle, applicationName, commandLine, processAttributeHandle, threadAttributeHandle, inheritHandle, creationFlag, environmentHandle, currentDirectoryPath, startupInfo, processInformation) /// <summary> /// 사용자로 프로세스 생성하기 /// </summary> /// <param name="tokenHandle">토큰 핸들</param> /// <param name="applicationName">애플리케이션명</param> /// <param name="commandLine">명령줄</param> /// <param name="processAttributeHandle">프로세스 어트리뷰트 핸들</param> /// <param name="threadAttributeHandle">스레드 어트리뷰트 핸들</param> /// <param name="inheritHandle">상속 핸들</param> /// <param name="creationFlag">생성 플래그</param> /// <param name="environmentHandle">환경 핸들</param> /// <param name="currentDirectoryPath">현재 디렉토리 경로</param> /// <param name="startupInfo">시작 정보</param> /// <param name="processInformation">프로세스 정보</param> /// <returns>처리 결과</returns> [DllImport("advapi32", EntryPoint = "CreateProcessAsUser", SetLastError = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)] private static extern bool CreateProcessAsUser ( IntPtr tokenHandle, string applicationName, string commandLine, IntPtr processAttributeHandle, IntPtr threadAttributeHandle, bool inheritHandle, uint creationFlag, IntPtr environmentHandle, string currentDirectoryPath, ref STARTUPINFO startupInfo, out PROCESS_INFORMATION processInformation ); #endregion #region 토큰 복제하기 (확장) - DuplicateTokenEx(existingTokenHandle, desiredAccess, threadAttributeHandle, tokenType, impersonationLevel, duplicateTokenHandle) /// <summary> /// 토큰 복제하기 (확장) /// </summary> /// <param name="existingTokenHandle">기존 토클 핸들</param> /// <param name="desiredAccess">희망 액세스</param> /// <param name="threadAttributeHandle">스레드 어트리뷰트 핸들</param> /// <param name="tokenType">토큰 타입</param> /// <param name="impersonationLevel">가장 레벨</param> /// <param name="duplicateTokenHandle">복제 토큰 핸들</param> /// <returns>처리 결과</returns> [DllImport("advapi32", EntryPoint = "DuplicateTokenEx")] private static extern bool DuplicateTokenEx ( IntPtr existingTokenHandle, uint desiredAccess, IntPtr threadAttributeHandle, int tokenType, int impersonationLevel, ref IntPtr duplicateTokenHandle ); #endregion #region 환경 블럭 생성하기 - CreateEnvironmentBlock(environmentHandle, tokenHandle, inherit) /// <summary> /// 환경 블럭 생성하기 /// </summary> /// <param name="environmentHandle">환경 핸들</param> /// <param name="tokenHandle">토큰 핸들</param> /// <param name="inherit">상속 여부</param> /// <returns>처리 결과</returns> [DllImport("userenv", SetLastError = true)] private static extern bool CreateEnvironmentBlock(ref IntPtr environmentHandle, IntPtr tokenHandle, bool inherit); #endregion #region 환경 블럭 제거하기 - DestroyEnvironmentBlock(environmentHandle) /// <summary> /// 환경 블럭 제거하기 /// </summary> /// <param name="environmentHandle">환경 핸들</param> /// <returns>처리 결과</returns> [DllImport("userenv", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool DestroyEnvironmentBlock(IntPtr environmentHandle); #endregion #region 핸들 닫기 - CloseHandle(snapshotHandle) /// <summary> /// 핸들 닫기 /// </summary> /// <param name="snapshotHandle">스냅샷 핸들</param> /// <returns>처리 결과</returns> [DllImport("kernel32", SetLastError = true)] private static extern bool CloseHandle(IntPtr snapshotHandle); #endregion #region WTS 활성 콘솔 세션 ID 구하기 - WTSGetActiveConsoleSessionId() /// <summary> /// WTS 활성 콘솔 세션 ID 구하기 /// </summary> /// <returns>활성 콘솔 세션 ID</returns> [DllImport("kernel32")] private static extern uint WTSGetActiveConsoleSessionId(); #endregion #region WTS 사용자 토큰 질의하기 - WTSQueryUserToken(sessionID, tokenHandle) /// <summary> /// WTS 사용자 토큰 질의하기 /// </summary> /// <param name="sessionID">세션 ID</param> /// <param name="tokenHandle">토큰 핸들</param> /// <returns>처리 결과</returns> [DllImport("wtsapi32")] private static extern uint WTSQueryUserToken(uint sessionID, ref IntPtr tokenHandle); #endregion #region WTS 세션 열거하기 - WTSEnumerateSessions(serverHandle, reserved, version, sessionInfoHandle, count) /// <summary> /// WTS 세션 열거하기 /// </summary> /// <param name="serverHandle">서버 핸들</param> /// <param name="reserved">예약</param> /// <param name="version">버전</param> /// <param name="sessionInfoHandle">세션 정보 핸들</param> /// <param name="count">카운트</param> /// <returns>처리 결과</returns> [DllImport("wtsapi32", SetLastError = true)] private static extern int WTSEnumerateSessions ( IntPtr serverHandle, int reserved, int version, ref IntPtr sessionInfoHandle, ref int count ); #endregion #region WTF 메모리 해제하기 - WTSFreeMemory(memoryHandle) /// <summary> /// WTF 메모리 해제하기 /// </summary> /// <param name="memoryHandle">메모리 핸들</param> [DllImport("wtsapi32")] private static extern void WTSFreeMemory(IntPtr memoryHandle); #endregion #region 토큰 정보 설정하기 - SetTokenInformation(tokenHandle, tokenInformationClass, tokenInformation, tokenInformationLenth) /// <summary> /// 토큰 정보 설정하기 /// </summary> /// <param name="tokenHandle">토큰 핸들</param> /// <param name="tokenInformationClass">토큰 정보 클래스</param> /// <param name="tokenInformation">토큰 정보</param> /// <param name="tokenInformationLenth">토큰 정보 길이</param> /// <returns>처리 결과</returns> [DllImport("advapi32", SetLastError = true)] private static extern bool SetTokenInformation(IntPtr tokenHandle, TOKEN_INFORMATION_CLASS tokenInformationClass, ref uint tokenInformation, uint tokenInformationLenth); #endregion #region 프로세스 토큰 열기 - OpenProcessToken(processHandle, desiredAccess, tokenHandle) /// <summary> /// 프로세스 토큰 열기 /// </summary> /// <param name="processHandle">프로세스 핸들</param> /// <param name="desiredAccess">희망 액세스</param> /// <param name="tokenHandle">토큰 핸들</param> /// <returns>처리 결과</returns> [DllImport("advapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool OpenProcessToken(IntPtr processHandle, uint desiredAccess, out IntPtr tokenHandle); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// WTS_CURRENT_SERVER_HANDLE /// </summary> private static readonly IntPtr WTS_CURRENT_SERVER_HANDLE = IntPtr.Zero; #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// CREATE_UNICODE_ENVIRONMENT /// </summary> private const int CREATE_UNICODE_ENVIRONMENT = 0x00000400; /// <summary> /// CREATE_NO_WINDOW /// </summary> private const int CREATE_NO_WINDOW = 0x08000000; /// <summary> /// CREATE_NEW_CONSOLE /// </summary> private const int CREATE_NEW_CONSOLE = 0x00000010; /// <summary> /// INVALID_SESSION_ID /// </summary> private const uint INVALID_SESSION_ID = 0xffffffff; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 현재 사용자로 프로세스 실행하기 - ExecuteProcessAsCurrentUser(applicationFilePath, processInformation, commandLine, workingDirectoryPath, visible) /// <summary> /// 현재 사용자로 프로세스 실행하기 /// </summary> /// <param name="applicationFilePath">애플리케이션 경로</param> /// <param name="processInformation">프로세스 정보</param> /// <param name="commandLine">명령줄</param> /// <param name="workingDirectoryPath">작업 디렉토리 경로</param> /// <param name="visible">표시 여부</param> /// <returns>처리 결과</returns> public static bool ExecuteProcessAsCurrentUser ( string applicationFilePath, out PROCESS_INFORMATION processInformation, string commandLine = null, string workingDirectoryPath = null, bool visible = true ) { IntPtr userTokenHandle = IntPtr.Zero; IntPtr systemTokenHandle = IntPtr.Zero; IntPtr environmentHandle = IntPtr.Zero; processInformation = new PROCESS_INFORMATION(); try { uint activeSessionID = GetActiveConsoleSessionID(); if(activeSessionID == INVALID_SESSION_ID) { return false; } if(!GetSessionUserToken(activeSessionID, ref userTokenHandle)) { throw new Exception("ExecuteProcessAsCurrentUser : GetSessionUserToken failed."); } if(!GetSystemToken(activeSessionID, ref systemTokenHandle)) { throw new Exception("ExecuteProcessAsCurrentUser : GetSystemToken failed."); } if(!CreateEnvironmentBlock(ref environmentHandle, userTokenHandle, false)) { throw new Exception("ExecuteProcessAsCurrentUser : CreateEnvironmentBlock failed."); } uint creationFlag = CREATE_UNICODE_ENVIRONMENT | (uint)(visible ? CREATE_NEW_CONSOLE : CREATE_NO_WINDOW); STARTUPINFO startupInfo = new STARTUPINFO(); startupInfo.ByteCount = Marshal.SizeOf(typeof(STARTUPINFO)); startupInfo.ShowWindow = (short)(visible ? ShowWindowType.SW_SHOW : ShowWindowType.SW_HIDE); startupInfo.Desktop = "winsta0\\default"; if ( !CreateProcessAsUser ( systemTokenHandle, applicationFilePath, commandLine, IntPtr.Zero, IntPtr.Zero, false, creationFlag, environmentHandle, workingDirectoryPath, ref startupInfo, out processInformation ) ) { int errorCode = Marshal.GetLastWin32Error(); string errorMessage = $"ExecuteProcessAsCurrentUser: CreateProcessAsUser failed."; throw new Exception(errorMessage); } } finally { CloseHandle(userTokenHandle); CloseHandle(systemTokenHandle); if(environmentHandle != IntPtr.Zero) { DestroyEnvironmentBlock(environmentHandle); } CloseHandle(processInformation.ThreadHandle); CloseHandle(processInformation.ProcessHandle); } return true; } #endregion //////////////////////////////////////////////////////////////////////////////// Private #region 세션 사용자 토큰 구하기 - GetSessionUserToken(activeSessionID, userTokenHandle) /// <summary> /// 세션 사용자 토큰 구하기 /// </summary> /// <param name="activeSessionID">활성 세션 ID</param> /// <param name="userTokenHandle">사용자 토큰 핸들</param> /// <returns>처리 결과</returns> private static bool GetSessionUserToken(uint activeSessionID, ref IntPtr userTokenHandle) { bool result = false; IntPtr impersonationTokenHandle = IntPtr.Zero; if(WTSQueryUserToken(activeSessionID, ref impersonationTokenHandle) != 0) { result = DuplicateTokenEx ( impersonationTokenHandle, 0, IntPtr.Zero, (int)SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, (int)TOKEN_TYPE.TokenPrimary, ref userTokenHandle ); CloseHandle(impersonationTokenHandle); } return result; } #endregion #region 시스템 토큰 구하기 - GetSystemToken(activeSessionID, systemTokenHandle) /// <summary> /// 시스템 토큰 구하기 /// </summary> /// <param name="activeSessionID">활성 세션 ID</param> /// <param name="systemTokenHandle">시스템 토큰 핸들</param> /// <returns>처리 결과</returns> private static bool GetSystemToken(uint activeSessionID, ref IntPtr systemTokenHandle) { using ( WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent ( TokenAccessLevels.AssignPrimary | TokenAccessLevels.Duplicate | TokenAccessLevels.Impersonate | TokenAccessLevels.AdjustDefault | TokenAccessLevels.AdjustSessionId | TokenAccessLevels.Read ) ) { IntPtr impersonationTokenHandle = windowsIdentity.Token; if(impersonationTokenHandle == IntPtr.Zero) { return false; } if ( DuplicateTokenEx ( impersonationTokenHandle, 0, IntPtr.Zero, (int)SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, (int)TOKEN_TYPE.TokenPrimary, ref systemTokenHandle ) ) { if(SetTokenInformation(systemTokenHandle, TOKEN_INFORMATION_CLASS.TokenSessionID, ref activeSessionID, (uint)Marshal.SizeOf(activeSessionID))) { return true; } else { CloseHandle(systemTokenHandle); } } } return false; } #endregion #region 활성 콘솔 세션 ID 구하기 - GetActiveConsoleSessionID() /// <summary> /// 활성 콘솔 세션 ID 구하기 /// </summary> /// <returns>활성 콘솔 세션 ID</returns> private static uint GetActiveConsoleSessionID() { uint activeSessionID = INVALID_SESSION_ID; IntPtr sessionInfoHandle = IntPtr.Zero; int sessionCount = 0; if(WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, ref sessionInfoHandle, ref sessionCount) != 0) { int arrayElementSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO)); IntPtr currentSessionHandle = sessionInfoHandle; for(int i = 0; i < sessionCount; i++) { WTS_SESSION_INFO sessionInfo = (WTS_SESSION_INFO)Marshal.PtrToStructure(currentSessionHandle, typeof(WTS_SESSION_INFO)); currentSessionHandle += arrayElementSize; if(sessionInfo.State == WTS_CONNECTSTATE_CLASS.WTSActive) { activeSessionID = sessionInfo.SessionID; break; } } WTSFreeMemory(sessionInfoHandle); if(activeSessionID == INVALID_SESSION_ID) { activeSessionID = WTSGetActiveConsoleSessionId(); } } return activeSessionID; } #endregion } } |
▶ TestNode.cs
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 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 |
using System; using System.Diagnostics; using System.IO; namespace TestLibrary { /// <summary> /// 테스트 노드 /// </summary> public class TestNode { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field #region 로그 /// <summary> /// 로그 헬퍼 /// </summary> private ILogHelper logHelper; #endregion #region 실행 작업자 /// <summary> /// 실행 작업자 주기 (단위 : 밀리초) /// </summary> private int executeWorkerInterval = 1000; // 1초 /// <summary> /// 실행 작업자 /// </summary> private RepeatWorker executeWorker = null; #endregion /// <summary> /// 실행 여부 /// </summary> private bool isRunning = false; /// <summary> /// 틱 카운트 /// </summary> private int tickCount = 0; /// <summary> /// 첫번째 여부 /// </summary> private bool isFirst = true; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 실행 여부 - IsRunning /// <summary> /// 실행 여부 /// </summary> public bool IsRunning { get { return this.isRunning; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - TestNode() /// <summary> /// 생성자 /// </summary> public TestNode() { #region 로그 헬퍼를 설정한다. this.logHelper = new FileLogHelper("d:\\", "TestNode.log"); #endregion } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 시작하기 - Start() /// <summary> /// 시작하기 /// </summary> public void Start() { try { File.Delete(@"D:\TestNode.log"); this.logHelper?.WriteLog("BEGIN START FUNCTION"); if(this.isRunning) { this.logHelper?.WriteLog("STOP START FUNCTION : AlreadyRunning"); return; } this.isRunning = true; #region 실행 작업자를 설정한다. if(this.executeWorker != null) { if(this.executeWorker.IsRunning) { this.executeWorker.Stop(); } this.executeWorker = null; } this.executeWorker = new RepeatWorker(new Action<object>(ProcessExecute), null, this.executeWorkerInterval); #endregion this.executeWorker.Start(); this.logHelper?.WriteLog("END START FUNCTION"); } catch(Exception exception) { this.isRunning = false; this.logHelper?.WriteErrorLog(exception, "ERROR START FUNCTION"); throw exception; } } #endregion #region 중단하기 - Stop() /// <summary> /// 중단하기 /// </summary> public void Stop() { try { this.logHelper?.WriteLog("BEGIN STOP FUNCTION"); if(!this.isRunning) { this.logHelper?.WriteLog("STOP STOP FUNCTION : AlreadyStopped"); return; } this.isRunning = false; #region 실행 작업자를 중단한다. this.executeWorker.Stop(); this.executeWorker = null; #endregion this.logHelper?.WriteLog("END STOP FUNCTION"); } catch(Exception exception) { this.isRunning = false; this.logHelper?.WriteErrorLog(exception, "ERROR STOP FUNCTION"); } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 프로세스 죽이기 - KillProcess(string filePath) /// <summary> /// 프로세스 죽이기 /// </summary> /// <param name="filePath">파일 경로</param> /// <returns>처리 결과</returns> private bool KillProcess(string filePath) { if(string.IsNullOrWhiteSpace(filePath)) { return false; } bool result = false; try { string processName = Path.GetFileNameWithoutExtension(filePath); foreach(Process process in Process.GetProcessesByName(processName)) { try { if ( process.MainModule != null && process.MainModule.FileName != null && string.Compare(process.MainModule.FileName, filePath, true) == 0 ) { process.Kill(); result = true; } } catch { } } } catch { } return result; } #endregion #region 메모장 실행하기 - ExecuteNotepad() /// <summary> /// 메모장 실행하기 /// </summary> private void ExecuteNotepad() { string filePath = @"C:\Windows\System32\notepad.exe"; string workingDirectoryPath = Path.GetDirectoryName(filePath); KillProcess(filePath); try { ProcessHelper.ExecuteProcessAsCurrentUser(filePath, out ProcessHelper.PROCESS_INFORMATION processInformation, "", workingDirectoryPath); this.logHelper?.WriteLog("EXECUTE PROCESS AS CURRENT USER"); } catch(Exception exception) { this.logHelper?.WriteErrorLog(exception, "ERROR EXECUTE PROCESS AS CURRENT USER"); } } #endregion #region 실행 처리하기 - ProcessExecute(parameter) /// <summary> /// 실행 처리하기 /// </summary> /// <param name="parameter">매개 변수</param> private void ProcessExecute(object parameter) { try { this.logHelper?.WriteLog("테스트 메시지"); if(this.isFirst) { this.tickCount++; if(this.tickCount == 30) { this.isFirst = false; ExecuteNotepad(); } } } catch(Exception exception) { this.logHelper?.WriteErrorLog(exception, "ERROR PROCESS EXECUTE FUNCTION"); } } #endregion } } |
[TestService 프로젝트] ▶ ProcessInstaller.cs
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 |
using System.ComponentModel; using System.Configuration.Install; using System.ServiceProcess; namespace TestService { /// <summary> /// 프로젝트 설치자 /// </summary> [RunInstaller(true)] public partial class ProjectInstaller : Installer { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 서비스 프로세스 설치자 /// </summary> private ServiceProcessInstaller serviceProcessInstaller; /// <summary> /// 서비스 설치자 /// </summary> private ServiceInstaller serviceInstaller; /// <summary> /// 서비스명 /// </summary> private const string SERVICE_NAME = "TestNode"; /// <summary> /// 서비스 설명 /// </summary> private const string SERVICE_DESCRIPTION = "테스트 노드"; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - ProjectInstaller() /// <summary> /// 생성자 /// </summary> public ProjectInstaller() { this.serviceProcessInstaller = new ServiceProcessInstaller(); serviceProcessInstaller.Account = ServiceAccount.LocalSystem; serviceProcessInstaller.Password = null; serviceProcessInstaller.Username = null; this.serviceInstaller = new ServiceInstaller(); serviceInstaller.ServiceName = SERVICE_NAME; serviceInstaller.DisplayName = SERVICE_NAME; serviceInstaller.Description = SERVICE_DESCRIPTION; serviceInstaller.StartType = ServiceStartMode.Automatic; Installers.AddRange(new Installer[] { this.serviceProcessInstaller, this.serviceInstaller }); } #endregion } } |
■ icacls 명령을 사용해 파일/폴더 권한을 설정하는 방법을 보여준다. 1. [명령 프롬프트]를 관리자 권한으로 실행한다. 2. [명령 프롬프트]에서 아래 명령을 실행한다. ▶