■ 윈도우즈 서비스에서 시스템 권한으로 프로세스를 실행하는 방법을 보여준다.
[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 } } |
▶ ProcessService.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 |
using System; using System.ServiceProcess; using TestLibrary; namespace TestService { /// <summary> /// 프로젝트 서비스 /// </summary> public partial class ProjectService : ServiceBase { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 에이전트 노드 /// </summary> private TestNode testNode; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - ProjectService() /// <summary> /// 생성자 /// </summary> public ProjectService() { this.testNode = new TestNode(); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 테스트 하기 - Test(argumentArray) /// <summary> /// 테스트 하기 /// </summary> /// <param name="argumentArray">인자 배열</param> public void Test(string[] argumentArray) { OnStart(argumentArray); Console.ReadKey(true); OnStop(); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 시작시 처리하기 - OnStart(argumentArray) /// <summary> /// 시작시 처리하기 /// </summary> /// <param name="argumentArray">인자 배열</param> protected override void OnStart(string[] argumentArray) { this.testNode.Start(); } #endregion #region 중단시 처리하기 - OnStop() /// <summary> /// 중단시 처리하기 /// </summary> protected override void OnStop() { this.testNode.Stop(); } #endregion } } |
▶ 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 |
using System; using System.ServiceProcess; namespace TestService { /// <summary> /// 프로그램 /// </summary> static class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 프로그램 시작하기 - Main(argumentArray) /// <summary> /// 프로그램 시작하기 /// </summary> /// <param name="argumentArray">인자 배열</param> private static void Main(string[] argumentArray) { if(Environment.UserInteractive) { ProjectService service = new ProjectService(); service.Test(argumentArray); } else { ServiceBase[] serviceBaseArray; serviceBaseArray = new ServiceBase[] { new ProjectService() }; ServiceBase.Run(serviceBaseArray); } } #endregion } } |