반응형

Edit_Secpol.zip
0.03MB

서비스는 기본적으로 SYSTEM 계정이다.

이 서비스가 어떠한 프로세스 (exe)를 실행시켜주게 되면,

계정이나 권한도 그대로 승계받게되어, SYSTEM 계정으로 실행이 된다.

 

하지만 SYSTEM 계정의 Service는 기본적으로 UI를 지원하지 않는다.

UI를 지원하려면 USER계정으로 실행이 되어야 하는데,

이 때, 서비스에서는 특정 프로세스(exe)를 실행시켜줄 때, 단순히 Process.Start()를 하게되면

SYSTEM 계정으로 실행되게 되고,....

 

웹상에 흔히 돌아디는 아래코드를 이용해서 USER권한으로 실행하게 된다.

(advapi32.dll 의 CreateProcessAsUser 함수를 이용하는 방법)

아래는 샘플들

 

StartProcessAndBypassUAC.cs
0.01MB
ApplicationLauncher.cs
0.02MB

public class ApplicationLoader
    {
        #region Structures

        [StructLayout(LayoutKind.Sequential)]
        public struct SECURITY_ATTRIBUTES
        {
            public int Length;
            public IntPtr lpSecurityDescriptor;
            public bool bInheritHandle;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct STARTUPINFO
        {
            public int cb;
            public String lpReserved;
            public String lpDesktop;
            public String lpTitle;
            public uint dwX;
            public uint dwY;
            public uint dwXSize;
            public uint dwYSize;
            public uint dwXCountChars;
            public uint dwYCountChars;
            public uint dwFillAttribute;
            public uint dwFlags;
            public short wShowWindow;
            public short cbReserved2;
            public IntPtr lpReserved2;
            public IntPtr hStdInput;
            public IntPtr hStdOutput;
            public IntPtr hStdError;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct PROCESS_INFORMATION
        {
            public IntPtr hProcess;
            public IntPtr hThread;
            public uint dwProcessId;
            public uint dwThreadId;
        }

        #endregion

        #region Enumerations

        enum TOKEN_TYPE : int
        {
            TokenPrimary = 1,
            TokenImpersonation = 2
        }

        enum SECURITY_IMPERSONATION_LEVEL : int
        {
            SecurityAnonymous = 0,
            SecurityIdentification = 1,
            SecurityImpersonation = 2,
            SecurityDelegation = 3,
        }

        #endregion

        #region Constants

        public const int TOKEN_DUPLICATE = 0x0002;
        public const uint MAXIMUM_ALLOWED = 0x2000000;
        public const int CREATE_NEW_CONSOLE = 0x00000010;

        public const int IDLE_PRIORITY_CLASS = 0x40;
        public const int NORMAL_PRIORITY_CLASS = 0x20;
        public const int HIGH_PRIORITY_CLASS = 0x80;
        public const int REALTIME_PRIORITY_CLASS = 0x100;

        #endregion

        #region Win32 API Imports

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool CloseHandle(IntPtr hSnapshot);

        [DllImport("kernel32.dll")]
        static extern uint WTSGetActiveConsoleSessionId();

        [DllImport("advapi32.dll", EntryPoint = "CreateProcessAsUser", SetLastError = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
        public extern static bool CreateProcessAsUser(IntPtr hToken, String lpApplicationName, String lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes,
            ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandle, int dwCreationFlags, IntPtr lpEnvironment,
            String lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);

        [DllImport("kernel32.dll")]
        static extern bool ProcessIdToSessionId(uint dwProcessId, ref uint pSessionId);

        [DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx")]
        public extern static bool DuplicateTokenEx(IntPtr ExistingTokenHandle, uint dwDesiredAccess,
            ref SECURITY_ATTRIBUTES lpThreadAttributes, int TokenType,
            int ImpersonationLevel, ref IntPtr DuplicateTokenHandle);

        [DllImport("kernel32.dll")]
        static extern IntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, uint dwProcessId);

        [DllImport("advapi32", SetLastError = true), SuppressUnmanagedCodeSecurityAttribute]
        static extern bool OpenProcessToken(IntPtr ProcessHandle, int DesiredAccess, ref IntPtr TokenHandle);

        #endregion

        static private void wirteFileTest(string orgmsg)
        {
            string msg = DateTime.Now.ToString("yy-MM-dd(ddd) HH:mm:ss") + " : " + orgmsg;

            string logfolder = AppDomain.CurrentDomain.BaseDirectory + @"\LOG\";
            if (Directory.Exists(logfolder) == false)
                Directory.CreateDirectory(logfolder);

            string today = DateTime.Today.ToString("yyyyMMdd");
            string filepath = logfolder + "Service_LOG_" + today + "-" + DateTime.Now.ToString("HH") + ".log";

            if (File.Exists(filepath) == false)
            {
                using (StreamWriter sw = File.CreateText(filepath))
                {
                    sw.WriteLine(msg);
                }
            }
            else
            {
                using (StreamWriter sw = File.AppendText(filepath))
                {
                    sw.WriteLine(msg);
                }

            }
        }

        /// <summary>
        /// Launches the given application with full admin rights, and in addition bypasses the Vista UAC prompt
        /// </summary>
        /// <param name="applicationName">The name of the application to launch</param>
        /// <param name="procInfo">Process information regarding the launched application that gets returned to the caller</param>
        /// <returns></returns>
        public static bool StartProcessAndBypassUAC(String applicationName, out PROCESS_INFORMATION procInfo)
        {
            uint winlogonPid = 0;
            IntPtr hUserTokenDup = IntPtr.Zero, hPToken = IntPtr.Zero, hProcess = IntPtr.Zero;
            procInfo = new PROCESS_INFORMATION();

            // obtain the currently active session id; every logged on user in the system has a unique session id
            uint dwSessionId = WTSGetActiveConsoleSessionId();

            // obtain the process id of the winlogon process that is running within the currently active session
            Process[] processes = Process.GetProcessesByName("winlogon");
            foreach (Process p in processes)
            {
                if ((uint)p.SessionId == dwSessionId)
                {
                    winlogonPid = (uint)p.Id;
                }
            }

            // obtain a handle to the winlogon process
            hProcess = OpenProcess(MAXIMUM_ALLOWED, false, winlogonPid);

            // obtain a handle to the access token of the winlogon process
            if (!OpenProcessToken(hProcess, TOKEN_DUPLICATE, ref hPToken))
            {
                CloseHandle(hProcess);
                return false;
            }

            wirteFileTest("1");

            // Security attibute structure used in DuplicateTokenEx and CreateProcessAsUser
            // I would prefer to not have to use a security attribute variable and to just 
            // simply pass null and inherit (by default) the security attributes
            // of the existing token. However, in C# structures are value types and therefore
            // cannot be assigned the null value.
            SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
            sa.Length = Marshal.SizeOf(sa);


            // copy the access token of the winlogon process; the newly created token will be a primary token
            if (!DuplicateTokenEx(hPToken, MAXIMUM_ALLOWED, ref sa, (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, (int)TOKEN_TYPE.TokenPrimary, ref hUserTokenDup))
            {
                CloseHandle(hProcess);
                CloseHandle(hPToken);
                return false;
            }

            wirteFileTest("2");

            // By default CreateProcessAsUser creates a process on a non-interactive window station, meaning
            // the window station has a desktop that is invisible and the process is incapable of receiving
            // user input. To remedy this we set the lpDesktop parameter to indicate we want to enable user 
            // interaction with the new process.
            STARTUPINFO si = new STARTUPINFO();
            si.cb = (int)Marshal.SizeOf(si);
            si.lpDesktop = @"winsta0\default"; // interactive window station parameter; basically this indicates that the process created can display a GUI on the desktop

            // flags that specify the priority and creation method of the process
            int dwCreationFlags = NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE;

            // create a new process in the current user's logon session
            bool result = CreateProcessAsUser(hUserTokenDup,        // client's access token
                                            null,                   // file to execute
                                            applicationName,        // command line
                                            ref sa,                 // pointer to process SECURITY_ATTRIBUTES
                                            ref sa,                 // pointer to thread SECURITY_ATTRIBUTES
                                            false,                  // handles are not inheritable
                                            dwCreationFlags,        // creation flags
                                            IntPtr.Zero,            // pointer to new environment block 
                                            null,                   // name of current directory 
                                            ref si,                 // pointer to STARTUPINFO structure
                                            out procInfo            // receives information about new process
                                            );

            wirteFileTest("3");

            // invalidate the handles
            CloseHandle(hProcess);
            CloseHandle(hPToken);
            CloseHandle(hUserTokenDup);

            return result; // return the result
        }

    }

 

하지만 이럼에도 불구하고, 간혹 실행이 되지 않는 경우가 있는데.. 이는

실행시키려는 프로세스가 Listen 등을 수행하는 프로세스 일경우, 아래와 같이 팝업이 뜨게 되고,

이 허용을 안하게 되면, 실행이 되지 않는다.

최초 실행시,(경로가 다르면 최초실행으로 간주된다.) 뜨는 윈도우 팝업

위 정보에 대한 저장은 방화벽(디펜더)쪽에 저장된다.

그래도 안된다면....  윈도키 secpol (로컬보안정책) 들어가서
보안정책 - 로컬정책 - 보안옵션 들어가서
사용자계정컨트롤 관리승인모드에서 모든관리자실행옵션을 사용안함 해주어야한다

보안프로그램들이 이런 셋팅을 주로 건들지만, 저 셋팅의 기본값은

OS종류(home, pro 등)나 version 등에 따라 달라진다.

반응형
Posted by Rainfly
l
반응형

CPU 1 Core  1 Process 실행하기

 

 

1개의 프로그램을 CPU 1코어만으로 실행하기 위한 방법

 

4코어 CPU 기준으로 프로그램을 실행시키면, OS에서 자동으로 하나의 프로세스를 4개의 CPU에 분산처리하여 실행된다.

 

하지만.... 1개의 CORE로만 실행을 시키면 CPU 점유율이 MAX 25%가 되는 것이다.

 

물론 1CORE, 2CORE, 3CORE, 4CORE 또는 CPU0, CPU1, CPU2, CPU3 등 선택한 CPU에서만 실행시킬 수 도 있다.

 

프로그램명이 program.exe 라고 할 경우

 

명령어 : start /affinity 1 program.exe

 

1 이라는 숫자의 정의는 다음과 같다.

 

CPU3 CPU2 CPU1 CPU0  Bin  Hex
---- ---- ---- ----  ---  ---
OFF  OFF  OFF  ON  = 0001 = 1
OFF  OFF  ON   OFF = 0010 = 2
OFF  OFF  ON   ON  = 0011 = 3
OFF  ON   OFF  OFF = 0100 = 4
OFF  ON   OFF  ON  = 0101 = 5
OFF  ON   ON   OFF = 0110 = 6
OFF  ON   ON   ON  = 0111 = 7
ON   OFF  OFF  OFF = 1000 = 8
ON   OFF  OFF  ON  = 1001 = 9
ON   OFF  ON   OFF = 1010 = A
ON   OFF  ON   ON  = 1011 = B
ON   ON   OFF  OFF = 1100 = C
ON   ON   OFF  ON  = 1101 = D
ON   ON   ON   OFF = 1110 = E
ON   ON   ON   ON  = 1111 = F

 

start /affinity 4 program.exe

 

라고 한다면, CPU2만을 사용하게 되는 것이다. 16진수 잊지말자.

 

 

 

반응형
Posted by Rainfly
l
반응형

Win10에서 Visual Studio 2013, 찾기 및 바꾸기 결과 안나오 때....

 

필자는 찾기 및 바꾸기... 뭘 어떻게 해도... 해당 검색,일치 수는 나오는데, 라인들이 나오지 않았다...

 

Ctrl + Shift + F 눌러서... 찾기결과에 쭈루룩 검색결과를 보고 싶을 때 쓰는.. 그거!!!

 

Find all "mytext", Subfolders, Find Results 1, Entire Solution, ""
  Matching lines: 40    Matching files: 10    Total files searched: 1129

 

뭐 단순히 이러고 끝... 매칭되는 결과들이 라인별로 쭈루룩 나와야 하는데 말이다..

 

비슷한 사례가 있긴 있더라.. Find in Files returns no line item results.

- https://social.msdn.microsoft.com/Forums/en-US/1a02f076-29f7-46d1-879a-f8ae6d6abe95/vs-2012-find-in-files-returns-no-line-item-results?forum=csharpide

 

Visual Studio 를 종료하고..

첨부된 ... 또는 아래의 내용으로 reg 파일을 만들어서.. 등록했다.

 

그러더니 파일에서 찾기 및 바꾸기.. 잘 동작 됨 ㅠㅠ..

 

 

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Wow6432Node\CLSID\{73B7DC00-F498-4ABD-AB79-D07AFD52F395}]
@="PSFactoryBuffer"

[HKEY_CLASSES_ROOT\Wow6432Node\CLSID\{73B7DC00-F498-4ABD-AB79-D07AFD52F395}\InProcServer32]
@="C:\\Program Files (x86)\\Common Files\\Microsoft Shared\\MSEnv\\TextMgrP.dll"
"ThreadingModel"="Both"

 

 

 

 

 

 

 

 

 

반응형
Posted by Rainfly
l
반응형

HD, Full HD, Quad HD, Ultra HD, 4K, 720p/i, 1080p/i 등 근래 나오는 해상도 및 영상규격에 대해서

한번 짚고 넘어가고자 작성하게 되었음

 

WVGA : 800x480, TV에서는 보기 힘든 해상도지만, 동영상규격에는 자주 나왔었다.
초기 핸드폰 모델에서 동영상이 거의 대다수였다. 
HD : HD는 단순히 High Definition의 약자로 단순히 고화질이란 뜻의 해상도 용어이다.
당시 HD가 막 나왔을 때의 기준으로 1280x720 정도이다.
720p의 동영상이 의미하는 해상도 1280x720 이다.
FHD : Full HD의 약자로 현재 가낭 널리 사용되는 해상도이다. 1920x1080
또한 10년 넘게 사랑받던 TV의 해상도가 이것이다.
1080p의 동영상이 의미하는 해상도가 1920x1080
QHD : Quad HD의 약자로 FHD와 4K, UHD 사이에 끼어 많이 사용되지 않는다. 2560x1440
그런데 1440p의 해상도가 딱 2560x1440 이라 동일하다.

 

4K, UHD : 이놈들이 제일 햇갈리게 한다....
엄현히 4K와 UHD는 다르다. 4K는 가로로 4096개의 픽셀을 뜻한다.
UHD는 3840x2160의 해상도를 뜻한다.
현재는 4K와 UHD를 혼용해서 쓰는게 보편화 되어있다.

 

혼용되는 이유는
해상도 용어와 다르게 방송,영화측면에서는(디지털시네마규격)측면에서는 .. 포맷상 차이때문에 다르게 되었는데, 약간의 차이이니 그냥 서로 지칭하게 되었다고 한다.

뭐... 아무래도 영화쪽이나 방속쪽엔 WIDE 한 부분이 있으니까 가로로 더 길다는게 이해 된다.

 

UHD 해상도 : 3840x2160 (일반 해상도 용어)
4K 규격 : 4096x2160 (방송, 영화)

참고로 UHD는 FHD의 4배크기이다. (1920x1080) x 4 = (3840x2160)

 

 

한눈에 보기~~~

 

(위 사진 예시는 내가 샀던 UHD TV 구매시 나왔던 짤에 추가적인 표시를 더해 두었다)

 

 

동영상의 xxxp, xxxi 용어에서 p와 i는 출력방식에 대한 용어로 해상도와 관련은 없고

(p는 전체출력방식, i는 짝선라인 홀수라인을 번갈아가면서 출력)


720p는 1280x720을 말하며, HD 해상도와 같다.
1080p는 1920x1080을 말하며, FHD 해상도와 같다.
1440p는 2560x1440로 720p의 4배이며, QHD해상도와 같다.

 


현실적인 예를 들자면,
내가 FHD급 TV를 갖고있다면, 1440p만큼의 고화질 동영상은 의미가 없다는 것이다.
FHD급이 볼 수 있는 최대 해상도는 1080p이다.

 

 

참고로 HDMI 케이블 ver1.3에서도 4K(4096x2160)의 해상도를 지원하지만 30프레임이 한계이며,
ver2.0에서는 60프레임을 지원한다. 4K 및 UHD 기기에서 해당 영상을 본다라면 HDMI 버전도 업 해주시길..

 

반응형
Posted by Rainfly
l
반응형

 

 

뭐 다양한 방법이 있지만, 어느분이 만드셨는지. 유용한듯..

 

youTube, Naver, Daum, 등의 동영상을 내려받는다. 공유눌러서 나오는 url 말고,

해당 동영상이 나오는 페이지의 주소를 넣어야 되나봄..

 

DownMe1.0.0.0.zip

 

 

2015/11/04 - [Review & Find It] - 동영상 다운방법, 유튜브,페이스북, 네이버tvcast 등 (Youtube, face book, naver tvcast 동영상 다운)

 

반응형
Posted by Rainfly
l