Thursday, August 30, 2007

API hooking revealed - The Code Project - System

API hooking revealed - The Code Project - System

Introduction

Intercepting Win32 API calls has always been a challenging subject among most of the Windows developers and I have to admit, it's been one of my favorite topics. The term Hooking represents a fundamental technique of getting control over a particular piece of code execution. It provides an straightforward mechanism that can easily alter the operating system's behavior as well as 3rd party products, without having their source code available.

Many modern systems draw the attention to their ability to utilize existing Windows applications by employing spying techniques. A key motivation for hooking, is not only to contribute to advanced functionalities, but also to inject user-supplied code for debugging purposes.

Unlike some relatively "old" operating systems like DOS and Windows 3.xx, the present Windows OS as NT/2K and 9x provide sophisticated mechanisms to separate address spaces of each process. This architecture offers a real memory protection, thus no application is able to corrupt the address space of another process or in the worse case even to crash the operating system itself. This fact makes a lot harder the development of system-aware hooks.

My motivation for writing this article was the need for a really simple hooking framework, that will offer an easy to use interface and ability to capture different APIs. It intends to reveal some of the tricks that can help you to write your own spying system. It suggests a single solution how to build a set for hooking Win32 API functions on NT/2K as well as 98/Me (shortly named in the article 9x) family Windows. For the sake of simplicity I decided not to add a support do UNICODE. However, with some minor modifications of the code you could easily accomplish this task.

Spying of applications provides many advantages:

  1. API function's monitoring
    The ability to control API function calls is extremely helpful and enables developers to track down specific "invisible" actions that occur during the API call. It contributes to comprehensive validation of parameters as well as reports problems that usually remain overlooked behind the scene. For instance sometimes, it might be very helpful to monitor memory related API functions for catching resource leaks.
  2. Debugging and reverse engineering
    Besides the standard methods for debugging API hooking has a deserved reputation for being one of the most popular debugging mechanisms. Many developers employ the API hooking technique in order to identify different component implementations and their relationships. API interception is very powerful way of getting information about a binary executable.
  3. Peering inside operating system
    Often developers are keen to know operating system in dept and are inspired by the role of being a "debugger". Hooking is also quite useful technique for decoding undocumented or poorly documented APIs.
  4. Extending originally offered functionalities by embedding custom modules into external Windows applications Re-routing the normal code execution by injecting hooks can provide an easy way to change and extend existing module functionalities. For example many 3rd party products sometimes don't meet specific security requirements and have to be adjusted to your specific needs. Spying of applications allows developers to add sophisticated pre- and post-processing around the original API functions. This ability is an extremely useful for altering the behavior of the already compiled code.

Functional requirements of a hooking system

There are few important decisions that have to be made, before you start implementing any kind of API hooking system. First of all, you should determine whether to hook a single application or to install a system-aware engine. For instance if you would like to monitor just one application, you don't need to install a system-wide hook but if your job is to track down all calls to TerminateProcess() or WriteProcessMemory() the only way to do so is to have a system-aware hook. What approach you will choose depends on the particular situation and addresses specific problems.

General design of an API spying framework

Usually a Hook system is composed of at least two parts - a Hook Server and a Driver. The Hook Server is responsible for injecting the Driver into targeted processes at the appropriate moment. It also administers the driver and optionally can receive information from the Driver about its activities whereas the Driver module that performs the actual interception.
This design is rough and beyond doubt doesn't cover all possible implementations. However it outlines the boundaries of a hook framework.

Once you have the requirement specification of a hook framework, there are few design points you should take into account:

  • What applications do you need to hook
  • How to inject the DLL into targeted processes or which implanting technique to follow
  • Which interception mechanism to use

I hope next the few sections will provide answers to those issues.

Injecting techniques

  1. Registry
    In order to inject a DLL into processes that link with USER32.DLL, you simply can add the DLL name to the value of the following registry key:

    HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Windows\AppInit_DLLs

    Its value contains a single DLL name or group of DLLs separated either by comma or spaces. According to MSDN documentation [7], all DLLs specified by the value of that key are loaded by each Windows-based application running within the current logon session. It is interesting that the actual loading of these DLLs occurs as a part of USER32's initialization. USER32 reads the value of mentioned registry key and calls LoadLibrary() for these DLLs in its DllMain code. However this trick applies only to applications that use USER32.DLL. Another restriction is that this built-in mechanism is supported only by NT and 2K operating systems. Although it is a harmless way to inject a DLL into a Windows processes there are few shortcomings:

    • In order to activate/deactivate the injection process you have to reboot Windows.
    • The DLL you want to inject will be mapped only into these processes that use USER32.DLL, thus you cannot expect to get your hook injected into console applications, since they usually don't import functions from USER32.DLL.
    • On the other hand you don't have any control over the injection process. It means that it is implanted into every single GUI application, regardless you want it or not. It is a redundant overhead especially if you intend to hook few applications only. For more details see [2] "Injecting a DLL Using the Registry"

  2. System-wide Windows Hooks
    Certainly a very popular technique for injecting DLL into a targeted process relies on provided by Windows Hooks. As pointed out in MSDN a hook is a trap in the system message-handling mechanism. An application can install a custom filter function to monitor the message traffic in the system and process certain types of messages before they reach the target window procedure.

    A hook is normally implemented in a DLL in order to meet the basic requirement for system-wide hooks. The basic concept of that sort of hooks is that the hook callback procedure is executed in the address spaces of each hooked up process in the system. To install a hook you call SetWindowsHookEx() with the appropriate parameters. Once the application installs a system-wide hook, the operating system maps the DLL into the address space in each of its client processes. Therefore global variables within the DLL will be "per-process" and cannot be shared among the processes that have loaded the hook DLL. All variables that contain shared data must be placed in a shared data section. The diagram bellow shows an example of a hook registered by Hook Server and injected into the address spaces named "Application one" and "Application two".

    Figure 1

    A system-wide hook is registered just ones when SetWindowsHookEx() is executed. If no error occurs a handle to the hook is returned. The returned value is required at the end of the custom hook function when a call to CallNextHookEx() has to be made. After a successful call to SetWindowsHookEx() , the operating system injects the DLL automatically (but not necessary immediately) into all processes that meet the requirements for this particular hook filter. Let's have a closer look at the following dummy WH_GETMESSAGE filter function:

    //---------------------------------------------------------------------------
    // GetMsgProc
    //
    // Filter function for the WH_GETMESSAGE - it's just a dummy function
    //---------------------------------------------------------------------------
    LRESULT CALLBACK GetMsgProc(
    int code, // hook code
    WPARAM wParam, // removal option
    LPARAM lParam // message
    )
    {
    // We must pass the all messages on to CallNextHookEx.
    return ::CallNextHookEx(sg_hGetMsgHook, code, wParam, lParam);
    }

    A system-wide hook is loaded by multiple processes that don't share the same address space.

    For instance hook handle sg_hGetMsgHook, that is obtained by SetWindowsHookEx() and is used as parameter in CallNextHookEx() must be used virtually in all address spaces. It means that its value must be shared among hooked processes as well as the Hook Server application. In order to make this variable "visible" to all processes we should store it in the shared data section.

    The following is an example of employing #pragma data_seg(). Here I would like to mention that the data within the shared section must be initialized, otherwise the variables will be assigned to the default data segment and #pragma data_seg() will have no effect.

    //---------------------------------------------------------------------------
    // Shared by all processes variables
    //---------------------------------------------------------------------------
    #pragma data_seg(".HKT")
    HHOOK sg_hGetMsgHook = NULL;
    BOOL sg_bHookInstalled = FALSE;
    // We get this from the application who calls SetWindowsHookEx()'s wrapper
    HWND sg_hwndServer = NULL;
    #pragma data_seg()
    You should add a SECTIONS statement to the DLL's DEF file as well
    SECTIONS
    .HKT Read Write Shared
    or use
    #pragma comment(linker, "/section:.HKT, rws")

    Once a hook DLL is loaded into the address space of the targeted process, there is no way to unload it unless the Hook Server calls UnhookWindowsHookEx() or the hooked application shuts down. When the Hook Server calls UnhookWindowsHookEx() the operating system loops through an internal list with all processes which have been forced to load the hook DLL. The operating system decrements the DLL's lock count and when it becomes 0, the DLL is automatically unmapped from the process's address space.

    Here are some of the advantages of this approach:

    • This mechanism is supported by NT/2K and 9x Windows family and hopefully will be maintained by future Windows versions as well.
    • Unlike the registry mechanism of injecting DLLs this method allows DLL to be unloaded when Hook Server decides that DLL is no longer needed and makes a call to UnhookWindowsHookEx()

    Although I consider Windows Hooks as very handy injection technique, it comes with its own disadvantages:

    • Windows Hooks can degrade significantly the entire performance of the system, because they increase the amount of processing the system must perform for each message.
    • It requires lot of efforts to debug system-wide Windows Hooks. However if you use more than one instance of VC++ running in the same time, it would simplify the debugging process for more complex scenarios.
    • Last but not least, this kind of hooks affect the processing of the whole system and under certain circumstances (say a bug) you must reboot your machine in order to recover it.
  3. Injecting DLL by using CreateRemoteThread() API function
    Well, this is my favorite one. Unfortunately it is supported only by NT and Windows 2K operating systems. It is bizarre, that you are allowed to call (link with) this API on Win 9x as well, but it just returns NULL without doing anything.

    Injecting DLLs by remote threads is Jeffrey Ritcher's idea and is well documented in his article [9] "Load Your 32-bit DLL into Another Process's Address Space Using INJLIB".

    The basic concept is quite simple, but very elegant. Any process can load a DLL dynamically using LoadLibrary() API. The issue is how do we force an external process to call LoadLibrary() on our behalf, if we don't have any access to process's threads? Well, there is a function, called CreateRemoteThread() that addresses creating a remote thread. Here comes the trick - have a look at the signature of thread function, whose pointer is passed as parameter (i.e. LPTHREAD_START_ROUTINE) to the CreateRemoteThread():

    DWORD WINAPI ThreadProc(LPVOID lpParameter);
    And here is the prototype of LoadLibrary API
    HMODULE WINAPI LoadLibrary(LPCTSTR lpFileName);
    Yes, they do have "identical" pattern. They use the same calling convention WINAPI, they both accept one parameter and the size of returned value is the same. This match gives us a hint that we can use LoadLibrary() as thread function, which will be executed after the remote thread has been created. Let's have a look at the following sample code:
    hThread = ::CreateRemoteThread(
    hProcessForHooking,
    NULL,
    0,
    pfnLoadLibrary,
    "C:\\HookTool.dll",
    0,
    NULL);
    By using GetProcAddress() API we get the address of the LoadLibrary() API. The dodgy thing here is that Kernel32.DLL is mapped always to the same address space of each process, thus the address of LoadLibrary() function has the same value in address space of any running process. This ensures that we pass a valid pointer (i.e. pfnLoadLibrary) as parameter of CreateRemoteThread().

    As parameter of the thread function we use the full path name of the DLL, casting it to LPVOID. When the remote thread is resumed, it passes the name of the DLL to the ThreadFunction (i.e. LoadLibrary). That's the whole trick with regard to using remote threads for injection purposes.

    There is an important thing we should consider, if implanting through CreateRemoteThread() API. Every time before the injector application operate on the virtual memory of the targeted process and makes a call to CreateRemoteThread(), it first opens the process using OpenProcess() API and passes PROCESS_ALL_ACCESS flag as parameter. This flag is used when we want to get maximum access rights to this process. In this scenario OpenProcess() will return NULL for some of the processes with low ID number. This error (although we use a valid process ID) is caused by not running under security context that has enough permissions. If you think for a moment about it, you will realize that it makes perfect sense. All those restricted processes are part of the operating system and a normal application shouldn't be allowed to operate on them. What would happen if some application has a bug and accidentally attempts to terminate an operating system's process? To prevent the operating system from that kind of eventual crashes, it is required that a given application must have sufficient privileges to execute APIs that might alter operating system behavior. To get access to the system resources (e.g. smss.exe, winlogon.exe, services.exe, etc) through OpenProcess() invocation, you must be granted the debug privilege. This ability is extremely powerful and offers a way to access the system resources, that are normally restricted. Adjusting the process privileges is a trivial task and can be described with the following logical operations:

    • Open the process token with permissions needed to adjust privileges
    • Given a privilege's name "SeDebugPrivilege", we should locate its local LUID mapping. The privileges are specified by name and can be found in Platform SDK file winnt.h
    • Adjust the token in order to enable the "SeDebugPrivilege" privilege by calling AdjustTokenPrivileges() API
    • Close obtained by OpenProcessToken() process token handle
    For more details about changing privileges see [10] "Using privilege".
  4. Implanting through BHO add-ins
    Sometimes you will need to inject a custom code inside Internet Explorer only. Fortunately Microsoft provides an easy and well documented way for this purpose - Browser Helper Objects. A BHO is implemented as COM DLL and once it is properly registered, each time when IE is launched it loads all COM components that have implemented IObjectWithSite interface.
  5. MS Office add-ins
    Similarly, to the BHOs, if you need to implant in MS Office applications code of your own, you can take the advantage of provided standard mechanism by implementing MS Office add-ins. There are many available samples that show how to implement this kind of add-ins.

Interception mechanisms

Injecting a DLL into the address space of an external process is a key element of a spying system. It provides an excellent opportunity to have a control over process's thread activities. However it is not sufficient to have the DLL injected if you want to intercept API function calls within the process.

This part of the article intends to make a brief review of several available real-world hooking aspects. It focuses on the basic outline for each one of them, exposing their advantages and disadvantages.

In terms of the level where the hook is applied, there are two mechanisms for API spying - Kernel level and User level spying. To get better understanding of these two levels you must be aware of the relationship between the Win32 subsystem API and the Native API. Following figure demonstrates where the different hooks are set and illustrates the module relationships and their dependencies on Windows 2K:

Figure 2

The major implementation difference between them is that interceptor engine for kernel-level hooking is wrapped up as a kernel-mode driver, whereas user-level hooking usually employs user-mode DLL.

  1. NT Kernel level hooking
    There are several methods for achieving hooking of NT system services in kernel mode. The most popular interception mechanism was originally demonstrated by Mark Russinovich and Bryce Cogswell in their article [3] "Windows NT System-Call Hooking". Their basic idea is to inject an interception mechanism for monitoring NT system calls just bellow the user mode. This technique is very powerful and provides an extremely flexible method for hooking the point that all user-mode threads pass through before they are serviced by the OS kernel.

    You can find an excellent design and implementation in "Undocumented Windows 2000 Secrets" as well. In his great book Sven Schreiber explains how to build a kernel-level hooking framework from scratch [5].

    Another comprehensive analysis and brilliant implementation has been provided by Prasad Dabak in his book "Undocumented Windows NT" [17].

    However, all these hooking strategies, remain out of the scope of this article.

  2. Win32 User level hooking
    1. Windows subclassing.
      This method is suitable for situations where the application's behavior might be changed by new implementation of the window procedure. To accomplish this task you simply call SetWindowLongPtr() with GWLP_WNDPROC parameter and pass the pointer to your own window procedure. Once you have the new subclass procedure set up, every time when Windows dispatches a message to a specified window, it looks for the address of the window's procedure associated with the particular window and calls your procedure instead of the original one.

      The drawback of this mechanism is that subclassing is available only within the boundaries of a specific process. In other words an application should not subclass a window class created by another process.

      Usually this approach is applicable when you hook an application through add-in (i.e. DLL / In-Proc COM component) and you can obtain the handle to the window whose procedure you would like to replace.

      For example, some time ago I wrote a simple add-in for IE (Browser Helper Object) that replaces the original pop-up menu provided by IE using subclassing.

    2. Proxy DLL (Trojan DLL)
      An easy way for hacking API is just to replace a DLL with one that has the same name and exports all the symbols of the original one. This technique can be effortlessly implemented using function forwarders. A function forwarder basically is an entry in the DLL's export section that delegates a function call to another DLL's function.

      You can accomplish this task by simply using #pragma comment:

      #pragma comment(linker, "/export:DoSomething=DllImpl.ActuallyDoSomething")

      However, if you decide to employ this method, you should take the responsibility of providing compatibilities with newer versions of the original library. For more details see [13a] section "Export forwarding" and [2] "Function Forwarders".

    3. Code overwriting
      There are several methods that are based on code overwriting. One of them changes the address of the function used by CALL instruction. This method is difficult, and error prone. The basic idea beneath is to track down all CALL instructions in the memory and replace the addresses of the original function with user supplied one.

      Another method of code overwriting requires a more complicated implementation. Briefly, the concept of this approach is to locate the address of the original API function and to change first few bytes of this function with a JMP instruction that redirects the call to the custom supplied API function. This method is extremely tricky and involves a sequence of restoring and hooking operations for each individual call. It's important to point out that if the function is in unhooked mode and another call is made during that stage, the system won't be able to capture that second call.
      The major problem is that it contradicts with the rules of a multithreaded environment.

      However, there is a smart solution that solves some of the issues and provides a sophisticated way for achieving most of the goals of an API interceptor. In case you are interested you might peek at [12] Detours implementation.

    4. Spying by a debugger
      An alternative to hooking API functions is to place a debugging breakpoint into the target function. However there are several drawbacks for this method. The major issue with this approach is that debugging exceptions suspend all application threads. It requires also a debugger process that will handle this exception. Another problem is caused by the fact that when the debugger terminates, the debugger is automatically shut down by Windows.
    5. Spying by altering of the Import Address Table
      This technique was originally published by Matt Pietrek and than elaborated by Jeffrey Ritcher ([2] "API Hooking by Manipulating a Module's Import Section") and John Robbins ([4] "Hooking Imported Functions"). It is very robust, simple and quite easy to implement. It also meets most of the requirements of a hooking framework that targets Windows NT/2K and 9x operating systems. The concept of this technique relies on the elegant structure of the Portable Executable (PE) Windows file format. To understand how this method works, you should be familiar with some of the basics behind PE file format, which is an extension of Common Object File Format (COFF). Matt Pietrek reveals the PE format in details in his wonderful articles - [6] "Peering Inside the PE.", and [13a/b] "An In-Depth Look into the Win32 PE file format". I will give you a brief overview of the PE specification, just enough to get the idea of hooking by manipulation of the Import Address Table.

      In general an PE binary file is organized, so that it has all code and data sections in a layout that conform to the virtual memory representation of an executable. PE file format is composed of several logical sections. Each of them maintains specific type of data and addresses particular needs of the OS loader.

      The section .idata, I would like to focus your attention on, contains information about Import Address Table. This part of the PE structure is particularly very crucial for building a spy program based on altering IAT.
      Each executable that conforms with PE format has layout roughly described by the figure below.

      Figure 3

      The program loader is responsible for loading an application along with all its linked DLLs into the memory. Since the address where each DLL is loaded into, cannot be known in advance, the loader is not able to determine the actual address of each imported function. The loader must perform some extra work to ensure that the program will call successfully each imported function. But going through each executable image in the memory and fixing up the addresses of all imported functions one by one would take unreasonable amount of processing time and cause huge performance degradation. So, how does the loader resolves this challenge? The key point is that each call to an imported function must be dispatched to the same address, where the function code resides into the memory. Each call to an imported function is in fact an indirect call, routed through IAT by an indirect JMP instruction. The benefit of this design is that the loader doesn't have to search through the whole image of the file. The solution appears to be quite simple - it just fixes-up the addresses of all imports inside the IAT. Here is an example of a snapshot PE File structure of a simple Win32 Application, taken with the help of the [8] PEView utility. As you can see TestApp import table contains two imported by GDI32.DLL function - TextOutA() and GetStockObject().

      Figure 4

      Actually the hooking process of an imported function is not that complex as it looks at first sight. In a nutshell an interception system that uses IAT patching has to discover the location that holds the address of imported function and replace it with the address of an user supplied function by overwriting it. An important requirement is that the newly provided function must have exactly the same signature as the original one. Here are the logical steps of a replacing cycle:
      • Locate the import section from the IAT of each loaded by the process DLL module as well as the process itself
      • Find the IMAGE_IMPORT_DESCRIPTOR chunk of the DLL that exports that function. Practically speaking, usually we search this entry by the name of the DLL
      • Locate the IMAGE_THUNK_DATA which holds the original address of the imported function
      • Replace the function address with the user supplied one

      By changing the address of the imported function inside the IAT, we ensure that all calls to the hooked function will be re-routed to the function interceptor.

      Replacing the pointer inside the IAT is that .idata section doesn't necessarily have to be a writable section. This requires that we must ensure that .idata section can be modified. This task can be accomplished by using VirtualProtect() API.

      Another issue that deserves attention is related to the GetProcAddress() API behavior on Windows 9x system. When an application calls this API outside the debugger it returns a pointer to the function. However if you call this function within from the debugger it actually returns different address than it would when the call is made outside the debugger. It is caused by the fact that that inside the debugger each call to GetProcAddress() returns a wrapper to the real pointer. Returned by GetProcAddress() value points to PUSH instruction followed by the actual address. This means that on Windows 9x when we loop through the thunks, we must check whether the address of examined function is a PUSH instruction (0x68 on x86 platforms) and accordingly get the proper value of the address function.

      Windows 9x doesn't implement copy-on-write, thus operating system attempts to keep away the debuggers from stepping into functions above the 2-GB frontier. That is the reason why GetProcAddress() returns a debug thunk instead of the actual address. John Robbins discusses this problem in [4] "Hooking Imported Functions".

Figuring out when to inject the hook DLL

That section reveals some challenges that are faced by developers when the selected injection mechanism is not part of the operating system's functionality. For example, performing the injection is not your concern when you use built-in Windows Hooks in order to implant a DLL. It is an OS's responsibility to force each of those running processes that meet the requirements for this particular hook, to load the DLL [18]. In fact Windows keeps track of all newly launched processes and forces them to load the hook DLL. Managing injection through registry is quite similar to Windows Hooks. The biggest advantage of all those "built-in" methods is that they come as part of the OS.

Unlike the discussed above implanting techniques, to inject by CreateRemoteThread() requires maintenance of all currently running processes. If the injecting is made not on time, this can cause the Hook System to miss some of the calls it claims as intercepted. It is crucial that the Hook Server application implements a smart mechanism for receiving notifications each time when a new process starts or shuts down. One of the suggested methods in this case, is to intercept CreateProcess() API family functions and monitor all their invocations. Thus when an user supplied function is called, it can call the original CreateProcess() with dwCreationFlags OR-ed with CREATE_SUSPENDED flag. This means that the primary thread of the targeted application will be in suspended state, and the Hook Server will have the opportunity to inject the DLL by hand-coded machine instructions and resume the application using ResumeThread() API. For more details you might refer to [2] "Injecting Code with CreateProcess()".

The second method of detecting process execution, is based on implementing a simple device driver. It offers the greatest flexibility and deserves even more attention. Windows NT/2K provides a special function PsSetCreateProcessNotifyRoutine() exported by NTOSKRNL. This function allows adding a callback function, that is called whenever a process is created or deleted. For more details see [11] and [15] from the reference section.

Enumerating processes and modules

Sometimes we would prefer to use injecting of the DLL by CreateRemoteThread() API, especially when the system runs under NT/2K. In this case when the Hook Server is started it must enumerate all active processes and inject the DLL into their address spaces. Windows 9x and Windows 2K provide a built-in implementation (i.e. implemented by Kernel32.dll) of Tool Help Library. On the other hand Windows NT uses for the same purpose PSAPI library. We need a way to allow the Hook Server to run and then to detect dynamically which process "helper" is available. Thus the system can determine which the supported library is, and accordingly to use the appropriate APIs.

I will present an object-oriented architecture that implements a simple framework for retrieving processes and modules under NT/2K and 9x [16]. The design of my classes allows extending the framework according to your specific needs. The implementation itself is pretty straightforward.

CTaskManager implements the system's processor. It is responsible for creating an instance of a specific library handler (i.e. CPsapiHandler or CToolhelpHandler) that is able to employ the correct process information provider library (i.e. PSAPI or ToolHelp32 respectively). CTaskManager is in charge of creating and marinating a container object that keeps a list with all currently active processes. After instantiating of the CTaskManager object the application calls Populate() method. It forces enumerating of all processes and DLL libraries and storing them into a hierarchy kept by CTaskManager's member m_pProcesses.

Following UML diagram shows the class relationships of this subsystem:

Figure 5

It is important to highlight the fact that NT's Kernel32.dll doesn't implement any of the ToolHelp32 functions. Therefore we must link them explicitly, using runtime dynamic linking. If we use static linking the code will fail to load on NT, regardless whether or not the application has attempted to execute any of those functions. For more details see my article "Single interface for enumerating processes and modules under NT and Win9x/2K.".

Requirements of the Hook Tool System

Now that I've made a brief introduction to the various concepts of the hooking process it's time to determine the basic requirements and explore the design of a particular hooking system. These are some of the issues addressed by the Hook Tool System:

  • Provide a user-level hooking system for spying any Win32 API functions imported by name
  • Provide the abilities to inject hook driver into all running processes by Windows hooks as well as CreateRemoteThread() API. The framework should offer an ability to set this up by an INI file
  • Employ an interception mechanism based on the altering Import Address Table
  • Present an object-oriented reusable and extensible layered architecture
  • Offer an efficient and scalable mechanism for hooking API functions
  • Meet performance requirements
  • Provide a reliable communication mechanism for transferring data between the driver and the server
  • Implement custom supplied versions of TextOutA/W() and ExitProcess() API functions
  • Log events to a file
  • The system is implemented for x86 machines running Windows 9x, Me, NT or Windows 2K operating system

Design and implementation

This part of the article discusses the key components of the framework and how do they interact each other. This outfit is capable to capture any kind of WINAPI imported by name functions.

Before I outline the system's design, I would like to focus your attention on several methods for injecting and hooking.

First and foremost, it is necessary to select an implanting method that will meet the requirements for injecting the DLL driver into all processes. So I designed an abstract approach with two injecting techniques, each of them applied accordingly to the settings in the INI file and the type of the operating system (i.e. NT/2K or 9x). They are - System-wide Windows Hooks and CreateRemoteThread() method. The sample framework offers the ability to inject the DLL on NT/2K by Windows Hooks as well as to implant by CreateRemoteThread() means. This can be determined by an option in the INI file that holds all settings of the system.

Another crucial moment is the choice of the hooking mechanism. Not surprisingly, I decided to apply altering IAT as an extremely robust method for Win32 API spying.

To achieve desired goals I designed a simple framework composed of the following components and files:

  • TestApp.exe - a simple Win32 test application that just outputs a text using TextOut() API. The purpose of this app is to show how it gets hooked up.
  • HookSrv.exe - control program
  • HookTool .DLL - spy library implemented as Win32 DLL
  • HookTool.ini - a configuration file
  • NTProcDrv.sys - a tiny Windows NT/2K kernel-mode driver for monitoring process creation and termination. This component is optional and addresses the problem with detection of process execution under NT based systems only.

HookSrv is a simple control program. Its main role is to load the HookTool.DLL and then to activate the spying engine. After loading the DLL, the Hook Server calls InstallHook() function and passes a handle to a hidden windows where the DLL should post all messages to.

HookTool.DLL is the hook driver and the heart of presented spying system. It implements the actual interceptor and provides three user supplied functions TextOutA/W() and ExitProcess() functions.

Although the article emphasizes on Windows internals and there is no need for it to be object-oriented, I decided to encapsulate related activities in reusable C++ classes. This approach provides more flexibility and enables the system to be extended. It also benefits developers with the ability to use individual classes outside this project.

Following UML class diagram illustrates the relationships between set of classes used in HookTool.DLL's implementation.

Figure 6

In this section of the article I would like to draw your attention to the class design of the HookTool.DLL. Assigning responsibilities to the classes is an important part of the development process. Each of the presented classes wraps up a specific functionality and represents a particular logical entity.

CModuleScope is the main doorway of the system. It is implemented using "Singleton" pattern and works in a thread-safe manner. Its constructor accepts 3 pointers to the data declared in the shared segment, that will be used by all processes. By this means the values of those system-wide variables can be maintained very easily inside the class, keeping the rule for encapsulation.

When an application loads the HookTool library, the DLL creates one instance of CModuleScope on receiving DLL_PROCESS_ATTACH notification. This step just initializes the only instance of CModuleScope. An important piece of the CModuleScope object construction is the creation of an appropriate injector object. The decision which injector to use will be made after parsing the HookTool.ini file and determining the value of UseWindowsHook parameter under [Scope] section. In case that the system is running under Windows 9x, the value of this parameter won't be examined by the system, because Window 9x doesn't support injecting by remote threads.

After instantiating of the main processor object, a call to ManageModuleEnlistment() method will be made. Here is a simplified version of its implementation:

// Called on DLL_PROCESS_ATTACH DLL notification
BOOL CModuleScope::ManageModuleEnlistment()
{
BOOL bResult = FALSE;
// Check if it is the hook server
if (FALSE == *m_pbHookInstalled)
{
// Set the flag, thus we will know that the server has been installed
*m_pbHookInstalled = TRUE;
// and return success error code
bResult = TRUE;
}
// and any other process should be examined whether it should be
// hooked up by the DLL
else
{
bResult = m_pInjector->IsProcessForHooking(m_szProcessName);
if (bResult)
InitializeHookManagement();
}
return bResult;
}

The implementation of the method ManageModuleEnlistment() is straightforward and examines whether the call has been made by the Hook Server, inspecting the value m_pbHookInstalled points to. If an invocation has been initiated by the Hook Server, it just sets up indirectly the flag sg_bHookInstalled to TRUE. It tells that the Hook Server has been started.

The next action taken by the Hook Server is to activate the engine through a single call to InstallHook() DLL exported function. Actually its call is delegated to a method of CModuleScope - InstallHookMethod(). The main purpose of this function is to force targeted for hooking processes to load or unload the HookTool.DLL.

 // Activate/Deactivate hooking
engine BOOL CModuleScope::InstallHookMethod(BOOL bActivate, HWND hWndServer)
{
BOOL bResult;
if (bActivate)
{
*m_phwndServer = hWndServer;
bResult = m_pInjector->InjectModuleIntoAllProcesses();
}
else
{
m_pInjector->EjectModuleFromAllProcesses();
*m_phwndServer = NULL;
bResult = TRUE;
}
return bResult;
}

HookTool.DLL provides two mechanisms for self injecting into the address space of an external process - one that uses Windows Hooks and another that employs injecting of DLL by CreateRemoteThread() API. The architecture of the system defines an abstract class CInjector that exposes pure virtual functions for injecting and ejecting DLL. The classes CWinHookInjector and CRemThreadInjector inherit from the same base - CInjector class. However they provide different realization of the pure virtual methods InjectModuleIntoAllProcesses() and EjectModuleFromAllProcesses(), defined in CInjector interface.

CWinHookInjector class implements Windows Hooks injecting mechanism. It installs a filter function by the following call

// Inject the DLL into all running processes
BOOL CWinHookInjector::InjectModuleIntoAllProcesses()
{
*sm_pHook = ::SetWindowsHookEx(
WH_GETMESSAGE,
(HOOKPROC)(GetMsgProc),
ModuleFromAddress(GetMsgProc),
0
);
return (NULL != *sm_pHook);
}

As you can see it makes a request to the system for registering WH_GETMESSAGE hook. The server executes this method only once. The last parameter of SetWindowsHookEx() is 0, because GetMsgProc() is designed to operate as a system-wide hook. The callback function will be invoked by the system each time when a window is about to process a particular message. It is interesting that we have to provide a nearly dummy implementation of the GetMsgProc() callback, since we don't intend to monitor the message processing. We supply this implementation only in order to get free injection mechanism provided by the operating system.

After making the call to SetWindowsHookEx(), OS checks whether the DLL (i.e. HookTool.DLL) that exports GetMsgProc() has been already mapped in all GUI processes. If the DLL hasn't been loaded yet, Windows forces those GUI processes to map it. An interesting fact is, that a system-wide hook DLL should not return FALSE in its DllMain(). That's because the operating system validates DllMain()'s return value and keeps trying to load this DLL until its DllMain() finally returns TRUE.

A quite different approach is demonstrated by the CRemThreadInjector class. Here the implementation is based on injecting the DLL using remote threads. CRemThreadInjector extends the maintenance of the Windows processes by providing means for receiving notifications of process creation and termination. It holds an instance of CNtInjectorThread class that observes the process execution. CNtInjectorThread object takes care for getting notifications from the kernel-mode driver. Thus each time when a process is created a call to CNtInjectorThread ::OnCreateProcess() is issued, accordingly when the process exits CNtInjectorThread ::OnTerminateProcess() is automatically called. Unlike the Windows Hooks, the method that relies on remote thread, requires manual injection each time when a new process is created. Monitoring process activities will provide us with a simple technique for alerting when a new process starts.

CNtDriverController class implements a wrapper around API functions for administering services and drivers. It is designed to handle the loading and unloading of the kernel-mode driver NTProcDrv.sys. Its implementation will be discussed later.

After a successful injection of HookTool.DLL into a particular process, a call to ManageModuleEnlistment() method is issued inside the DllMain(). Recall the method's implementation that I described earlier. It examines the shared variable sg_bHookInstalled through the CModuleScope 's member m_pbHookInstalled. Since the server's initialization had already set the value of sg_bHookInstalled to TRUE, the system checks whether this application must be hooked up and if so, it actually activates the spy engine for this particular process.

Turning the hacking engine on, takes place in the CModuleScope::InitializeHookManagement()'s implementation. The idea of this method is to install hooks for some vital functions as LoadLibrary() API family as well as GetProcAddress(). By this means we can monitor loading of DLLs after the initialization process. Each time when a new DLL is about to be mapped it is necessary to fix-up its import table, thus we ensure that the system won't miss any call to the captured function.

At the end of the InitializeHookManagement() method we provide initializations for the function we actually want to spy on.

Since the sample code demonstrates capturing of more than one user supplied functions, we must provide a single implementation for each individual hooked function. This means that using this approach you cannot just change the addresses inside IAT of the different imported functions to point to a single "generic" interception function. The spying function needs to know which function this call comes to. It is also crucial that the signature of the interception routine must be exactly the same as the original WINAPI function prototype, otherwise the stack will be corrupted. For example CModuleScope implements three static methods MyTextOutA(),MyTextOutW() and MyExitProcess(). Once the HookTool.DLL is loaded into the address space of a process and the spying engine is activated, each time when a call to the original TextOutA() is issued, CModuleScope:: MyTextOutA() gets called instead.

Proposed design of the spying engine itself is quite efficient and offers great flexibility. However, it is suitable mostly for scenarios where the set of functions for interception is known in advance and their number is limited.

If you want to add new hooks to the system you simply declare and implement the interception function as I did with MyTextOutA/W() and MyExitProcess(). Then you have to register it in the way shown by InitializeHookManagement() implementation.

Intercepting and tracing process execution is a very useful mechanism for implementing systems that require manipulations of external processes. Notifying interested parties upon starting of a new processes is a classic problem of developing process monitoring systems and system-wide hooks. The Win32 API provides a set of great libraries (PSAPI and ToolHelp [16]) that allow you to enumerate processes currently running in the system. Although these APIs are extremely powerful they don't permit you to get notifications when a new process starts or ends up. Luckily, NT/2K provides a set of APIs, documented in Windows DDK documentation as "Process Structure Routines" exported by NTOSKRNL. One of these APIs PsSetCreateProcessNotifyRoutine() offers the ability to register system-wide callback function which is called by OS each time when a new process starts, exits or has been terminated. The mentioned API can be employed as a simple way to for tracking down processes simply by implementing a NT kernel-mode driver and a user mode Win32 control application. The role of the driver is to detect process execution and notify the control program about these events. The implementation of the Windows process's observer NTProcDrv provides a minimal set of functionalities required for process monitoring under NT based systems. For more details see articles [11] and [15]. The code of the driver can be located in the NTProcDrv.c file. Since the user mode implementation installs and uninstalls the driver dynamically the currently logged-on user must have administrator privileges. Otherwise you won't be able to install the driver and it will disturb the process of monitoring. A way around is to manually install the driver as an administrator or run HookSrv.exe using offered by Windows 2K "Run as different user" option.

Last but not least, the provided tools can be administered by simply changing the settings of an INI file (i.e. HookTool.ini). This file determines whether to use Windows hooks (for 9x and NT/2K) or CreateRemoteThread() (only under NT/2K) for injecting. It also offers a way to specify which process must be hooked up and which shouldn't be intercepted. If you would like to monitor the process there is an option (Enabled) under section [Trace] that allows to log system activities. This option allows you to report rich error information using the methods exposed by CLogFile class. In fact ClogFile provides thread-safe implementation and you don't have to take care about synchronization issues related to accessing shared system resources (i.e. the log file). For more details see CLogFile and content of HookTool.ini file.

Sample code

The project compiles with VC6++ SP4 and requires Platform SDK. In a production Windows NT environment you need to provide PSAPI.DLL in order to use provided CTaskManager implementation.

Before you run the sample code make sure that all the settings in HookTool.ini file have been set according to your specific needs.

For those that will like the lower-level stuff and are interested in further development of the kernel-mode driver NTProcDrv code, they must install Windows DDK.

Out of the scope

For the sake of simplicity these are some of the subjects I intentionally left out of the scope of this article:

  • Monitoring Native API calls
  • A driver for monitoring process execution on Windows 9x systems.
  • UNICODE support, although you can still hook UNICODE imported APIs

Conclusion

This article by far doesn't provide a complete guide for the unlimited API hooking subject and without any doubt it misses some details. However I tried to fit in this few pages just enough important information that might help those who are interested in user mode Win32 API spying.

References

[1] "Windows 95 System Programming Secrets", Matt Pietrek
[2] "Programming Application for MS Windows" , Jeffrey Richter
[3] "Windows NT System-Call Hooking" , Mark Russinovich and Bryce Cogswell, Dr.Dobb's Journal January 1997
[4] "Debugging applications" , John Robbins
[5] "Undocumented Windows 2000 Secrets" , Sven Schreiber
[6] "Peering Inside the PE: A Tour of the Win32 Portable Executable File Format" by Matt Pietrek, March 1994
[7] MSDN Knowledge base Q197571
[8] PEview Version 0.67 , Wayne J. Radburn
[9] "Load Your 32-bit DLL into Another Process's Address Space Using INJLIB" MSJ May 1994
[10] "Programming Windows Security" , Keith Brown
[11] "Detecting Windows NT/2K process execution" Ivo Ivanov, 2002
[12] "Detours" Galen Hunt and Doug Brubacher
[13a] "An In-Depth Look into the Win32 PE file format" , part 1, Matt Pietrek, MSJ February 2002
[13b] "An In-Depth Look into the Win32 PE file format" , part 2, Matt Pietrek, MSJ March 2002
[14] "Inside MS Windows 2000 Third Edition" , David Solomon and Mark Russinovich
[15] "Nerditorium", James Finnegan, MSJ January 1999
[16] "Single interface for enumerating processes and modules under NT and Win9x/2K." , Ivo Ivanov, 2001
[17] "Undocumented Windows NT" , Prasad Dabak, Sandeep Phadke and Milind Borate
[18] Platform SDK: Windows User Interface, Hooks

History

21 Apr 2002 - updated source code

12 May 2002 - updated source code

4 Sep 2002 - updated source code

3 Dec 2002 - updated source code and demo

About Ivo Ivanov


Ivo works as an independent consultant building advanced .NET solutions. He is also a co-founder and CTO of InfoProcess Pty Ltd. – an Australian company developing Host Intrusion Prevention Systems (HIPS) for Windows.
Ivo has helped build applications for leading software solution providers such as Pacom Ltd., Citect Ltd.,Professional Advantage Pty Ltd. and NICE Ltd.. He combines in-depth knowledge of Windows Operating Systems, Object Oriented Design, and strong development skills in C/C++ and C#. Ivo applies his core skills to ensure alignment to the key components: business strategy, sperations, organisation and technology.
He is MCP.NET and Brainbench C++/OOD certified.

Click here to view Ivo Ivanov's online profile.


Other popular System articles:

Tuesday, August 28, 2007

操作Linux系统 必学的60个命令 - 文学城: 热点论坛 web.wenxuecity.com

操作Linux系统 必学的60个命令
Linux提供了大量的命令,利用它可以有效地完成大量的工作,如磁盘操作、文件存取、目录操作、进程管理、文件权限设定等。所以,在Linux系统上工 作离不开使用系统提供的命令。要想真正理解Linux系统,就必须从Linux命令学起,通过基础的命令学习可以进一步理解Linux系统。

不同Linux发行版的命令数量不一样,但Linux发行版本最少的命令也有200多个。这里笔者把比较重要和使用频率最多的命令,按照它们在系统中的作用分成下面六个部分一一介绍。

◆ 安装和登录命令:
login、shutdown、halt、reboot、install、mount、umount、chsh、exit、last;

◆ 文件处理命令:
file、mkdir、grep、dd、find、mv、ls、diff、cat、ln;

◆ 系统管理相关命令:
df、top、free、quota、at、lp、adduser、groupadd、kill、crontab;

◆ 网络操作命令:
ifconfig、ip、ping、netstat、telnet、ftp、route、rlogin、rcp、finger、mail、 nslookup;

◆ 系统安全相关命令:
passwd、su、umask、chgrp、chmod、chown、chattr、sudo ps、who;

◆ 其它命令:
tar、unzip、gunzip、unarj、mtools、man、unendcode、uudecode。

本文以Mandrake Linux 9.1(Kenrel 2.4.21)为例,介绍Linux下的安装和登录命令。

login

1.作用

login的作用是登录系统,它的使用权限是所有用户。

2.格式

login [name][-p ][-h 主机名称]

3.主要参数

-p:通知login保持现在的环境参数。

-h:用来向远程登录的之间传输用户名。

如果选择用命令行模式登录Linux的话,那么看到的第一个Linux命令就是login:。

一般界面是这样的:

Manddrake Linux release 9.1(Bamboo) for i586
renrel 2.4.21-0.13mdk on i686 / tty1
localhost login:root
password:

上面代码中,第一行是Linux发行版本号,第二行是内核版本号和登录的虚拟控制台,我们在第三行输入登录名,按“Enter”键在Password后输入账户密码,即可登录系统。出于安全考虑,输入账户密码时字符不会在屏幕上回显,光标也不移动。

登录后会看到下面这个界面(以超级用户为例):

[root@localhost root]#
last login:Tue ,Nov 18 10:00:55 on vc/1

上面显示的是登录星期、月、日、时间和使用的虚拟控制台。

4.应用技巧

Linux 是一个真正的多用户操作系统,可以同时接受多个用户登录,还允许一个用户进行多次登录。这是因为Linux和许多版本的Unix一样,提供了虚拟控制台的 访问方式,允许用户在同一时间从控制台(系统的控制台是与系统直接相连的监视器和键盘)进行多次登录。每个虚拟控制台可以看作是一个独立的工作站,工作台 之间可以切换。虚拟控制台的切换可以通过按下Alt键和一个功能键来实现,通常使用F1-F6 。

例如,用户登录后,按一下“Alt+ F2”键,用户就可以看到上面出现的“login:”提示符,说明用户看到了第二个虚拟控制台。然后只需按“Alt+ F1”键,就可以回到第一个虚拟控制台。一个新安装的Linux系统允许用户使用“Alt+F1”到“Alt+F6”键来访问前六个虚拟控制台。虚拟控制 台最有用的是,当一个程序出错造成系统死锁时,可以切换到其它虚拟控制台工作,关闭这个程序。

shutdown

1.作用

shutdown命令的作用是关闭计算机,它的使用权限是超级用户。

2.格式

shutdown [-h][-i][-k][-m][-t]

3.重要参数

-t:在改变到其它运行级别之前,告诉init程序多久以后关机。

-k:并不真正关机,只是送警告信号给每位登录者。

-h:关机后关闭电源。

-c:cancel current process取消目前正在执行的关机程序。所以这个选项当然没有时间参数,但是可以输入一个用来解释的讯息,而这信息将会送到每位使用者。

-F:在重启计算机时强迫fsck。

-time:设定关机前的时间。

-m: 将系统改为单用户模式。

-i:关机时显示系统信息。

4.命令说明

shutdown 命令可以安全地将系统关机。有些用户会使用直接断掉电源的方式来关闭Linux系统,这是十分危险的。因为Linux与Windows不同,其后台运行着 许多进程,所以强制关机可能会导致进程的数据丢失,使系统处于不稳定的状态,甚至在有的系统中会损坏硬件设备(硬盘)。在系统关机前使用 shutdown命令,系统管理员会通知所有登录的用户系统将要关闭,并且login指令会被冻结,即新的用户不能再登录。

halt

1.作用

halt命令的作用是关闭系统,它的使用权限是超级用户。

2.格式

halt [-n] [-w] [-d] [-f] [-i] [-p]

3.主要参数说明

-n:防止sync系统调用,它用在用fsck修补根分区之后,以阻止内核用老版本的超级块覆盖修补过的超级块。

-w:并不是真正的重启或关机,只是写wtmp(/var/log/wtmp)纪录。

-f:没有调用shutdown,而强制关机或重启。

-i:关机(或重启)前,关掉所有的网络接口。

-f:强迫关机,不呼叫shutdown这个指令。

-p: 当关机的时候顺便做关闭电源的动作。

-d:关闭系统,但不留下纪录。 

4.命令说明

halt 就是调用shutdown -h。halt执行时,杀死应用进程,执行sync(将存于buffer中的资料强制写入硬盘中)系统调用,文件系统写操作完成后就会停止内核。若系统的 运行级别为0或6,则关闭系统;否则以shutdown指令(加上-h参数)来取代。 

reboot

1.作用

reboot命令的作用是重新启动计算机,它的使用权限是系统管理者。

2.格式

reboot [-n] [-w] [-d] [-f] [-i]

3.主要参数

-n: 在重开机前不做将记忆体资料写回硬盘的动作。

-w: 并不会真的重开机,只是把记录写到/var/log/wtmp文件里。

-d: 不把记录写到/var/log/wtmp文件里(-n这个参数包含了-d)。

-i: 在重开机之前先把所有与网络相关的装置停止。

install

1.作用

install命令的作用是安装或升级软件或备份数据,它的使用权限是所有用户。

2.格式

(1)install [选项]... 来源 目的地

(2)install [选项]... 来源... 目录

(3)install -d [选项]... 目录...

在前两种格式中,会将<来源>复制至<目的地>或将多个<来源>文件复制至已存在的<目录>,同时设定 权限模式及所有者/所属组。在第三种格式中,会创建所有指定的目录及它们的主目录。长选项必须用的参数在使用短选项时也是必须的。

3.主要参数

--backup[=CONTROL]:为每个已存在的目的地文件进行备份。

-b:类似 --backup,但不接受任何参数。

-c:(此选项不作处理)。

-d,--directory:所有参数都作为目录处理,而且会创建指定目录的所有主目录。

-D:创建<目的地>前的所有主目录,然后将<来源>复制至 <目的地>;在第一种使用格式中有用。

-g,--group=组:自行设定所属组,而不是进程目前的所属组。

-m,--mode=模式:自行设定权限模式 (像chmod),而不是rwxr-xr-x。

-o,--owner=所有者:自行设定所有者 (只适用于超级用户)。

-p,--preserve-timestamps:以<来源>文件的访问/修改时间作为相应的目的地文件的时间属性。

-s,--strip:用strip命令删除symbol table,只适用于第一及第二种使用格式。

-S,--suffix=后缀:自行指定备份文件的<后缀>。

-v,--verbose:处理每个文件/目录时印出名称。

--help:显示此帮助信息并离开。

--version:显示版本信息并离开。

mount

1.作用

mount命令的作用是加载文件系统,它的用权限是超级用户或/etc/fstab中允许的使用者。

2.格式

mount -a [-fv] [-t vfstype] [-n] [-rw] [-F] device dir

3.主要参数

-h:显示辅助信息。

-v:显示信息,通常和-f用来除错。

-a:将/etc/fstab中定义的所有文件系统挂上。

-F:这个命令通常和-a一起使用,它会为每一个mount的动作产生一个行程负责执行。在系统需要挂上大量NFS文件系统时可以加快加载的速度。

-f:通常用于除错。它会使mount不执行实际挂上的动作,而是模拟整个挂上的过程,通常会和-v一起使用。

-t vfstype:显示被加载文件系统的类型。

-n:一般而言,mount挂上后会在/etc/mtab中写入一笔资料,在系统中没有可写入文件系统的情况下,可以用这个选项取消这个动作。

4.应用技巧

在Linux 和Unix系统上,所有文件都是作为一个大型树(以/为根)的一部分访问的。要访问CD-ROM上的文件,需要将CD-ROM设备挂装在文件树中的某个挂 装点。如果发行版安装了自动挂装包,那么这个步骤可自动进行。在Linux中,如果要使用硬盘、光驱等储存设备,就得先将它加载,当储存设备挂上了之后, 就可以把它当成一个目录来访问。挂上一个设备使用mount命令。在使用mount这个指令时,至少要先知道下列三种信息:要加载对象的文件系统类型、要 加载对象的设备名称及要将设备加载到哪个目录下。


(1)Linux可以识别的文件系统

◆ Windows 95/98常用的FAT 32文件系统:vfat ;

◆ Win NT/2000 的文件系统:ntfs ;

◆ OS/2用的文件系统:hpfs;

◆ Linux用的文件系统:ext2、ext3;

◆ CD-ROM光盘用的文件系统:iso9660。

虽然vfat是指FAT 32系统,但事实上它也兼容FAT 16的文件系统类型。

(2)确定设备的名称

在Linux 中,设备名称通常都存在/dev里。这些设备名称的命名都是有规则的,可以用“推理”的方式把设备名称找出来。例如,/dev/hda1这个 IDE设备,hd是Hard Disk(硬盘)的,sd是SCSI Device,fd是Floppy Device(或是Floppy Disk?)。a代表第一个设备,通常IDE接口可以接上4个IDE设备(比如4块硬盘)。所以要识别IDE硬盘的方法分别就是hda、hdb、hdc、 hdd。hda1中的“1”代表hda的第一个硬盘分区 (partition),hda2代表hda的第二主分区,第一个逻辑分区从hda5开始,依此类推。此外,可以直接检查 /var/log/messages文件,在该文件中可以找到计算机开机后系统已辨认出来的设备代号。

(3)查找挂接点

在决定将设备挂接之前,先要查看一下计算机是不是有个/mnt的空目录,该目录就是专门用来当作挂载点(Mount Point)的目录。建议在/mnt里建几个/mnt/cdrom、/mnt/floppy、/mnt/mo等目录,当作目录的专用挂载点。举例而言,如 要挂载下列5个设备,其执行指令可能如下 (假设都是Linux的ext2系统,如果是Windows XX请将ext2改成vfat):

软盘 ===>mount -t ext2 /dev/fd0 /mnt/floppy
cdrom ===>mount -t iso9660 /dev/hdc /mnt/cdrom
SCSI cdrom ===>mount -t iso9660 /dev/sdb /mnt/scdrom
SCSI cdr ===>mount -t iso9660 /dev/sdc /mnt/scdr

不过目前大多数较新的Linux发行版本(包括红旗 Linux、中软Linux、Mandrake Linux等)都可以自动挂装文件系统,但Red Hat Linux除外。

umount

1.作用

umount命令的作用是卸载一个文件系统,它的使用权限是超级用户或/etc/fstab中允许的使用者。

2.格式

unmount -a [-fFnrsvw] [-t vfstype] [-n] [-rw] [-F] device dir

3.使用说明

umount 命令是mount命令的逆操作,它的参数和使用方法和mount命令是一样的。Linux挂装CD-ROM后,会锁定CD—ROM,这样就不能用CD- ROM面板上的Eject按钮弹出它。但是,当不再需要光盘时,如果已将/cdrom作为符号链接,请使用umount/cdrom来卸装它。仅当无用户 正在使用光盘时,该命令才会成功。该命令包括了将带有当前工作目录当作该光盘中的目录的终端窗口。


chsh

1.作用

chsh命令的作用是更改使用者shell设定,它的使用权限是所有使用者。

2.格式

chsh [ -s ] [ -list] [ --help ] [ -v ] [ username ]

3.主要参数

-l:显示系统所有Shell类型。

-v:显示Shell版本号。

4.应用技巧

前面介绍了Linux下有多种Shell,一般缺省的是Bash,如果想更换Shell类型可以使用chsh命令。先输入账户密码,然后输入新Shell类型,如果操作正确系统会显示“Shell change”。其界面一般如下:

Changing fihanging shell for **
Password:
New shell [/bin/bash]: /bin/tcsh

上面代码中,[ ]内是目前使用的Shell。普通用户只能修改自己的Shell,超级用户可以修改全体用户的Shell。要想查询系统提供哪些Shell,可以使用chsh -l 命令,见图1所示。

图1 系统可以使用的Shell类型

从图1中可以看到,笔者系统中可以使用的Shell有bash(缺省)、csh、sh、tcsh四种。


exit

1.作用

exit命令的作用是退出系统,它的使用权限是所有用户。

2.格式

exit

3.参数

exit命令没有参数,运行后退出系统进入登录界面。


last

1.作用

last命令的作用是显示近期用户或终端的登录情况,它的使用权限是所有用户。通过last命令查看该程序的log,管理员可以获知谁曾经或企图连接系统。

2.格式

1ast[—n][-f file][-t tty] [—h 节点][-I —IP][—1][-y][1D]

3.主要参数

-n:指定输出记录的条数。

-f file:指定用文件file作为查询用的log文件。

-t tty:只显示指定的虚拟控制台上登录情况。

-h 节点:只显示指定的节点上的登录情况。

-i IP:只显示指定的IP上登录的情况。

-1:用IP来显示远端地址。

-y:显示记录的年、月、日。

-ID:知道查询的用户名。

-x:显示系统关闭、用户登录和退出的历史。

动手练习

上面介绍了Linux安装和登录命令,下面介绍几个实例,动手练习一下刚才讲过的命令。

1.一次运行多个命令

在一个命令行中可以执行多个命令,用分号将各个命令隔开即可,例如:

#last -x;halt

上面代码表示在显示系统关闭、用户登录和退出的历史后关闭计算机。

2.利用mount挂装文件系统访问Windows系统

许多Linux发行版本现在都可以自动加载Vfat分区来访问Windows系统,而Red Hat各个版本都没有自动加载Vfat分区,因此还需要进行手工操作。

mount 可以将Windows分区作为Linux的一个“文件”挂接到Linux的一个空文件夹下,从而将Windows的分区和/mnt这个目录联系起来。因 此,只要访问这个文件夹就相当于访问该分区了。首先要在/mnt下建立winc文件夹,在命令提示符下输入下面命令:

#mount -t vfat /dev/hda1 /mnt/winc

即表示将Windows的C分区挂到Liunx的/mnt/winc目录下。这时,在/mnt/winc目录下就可以看到Windows中C盘的内容了。 使用类似的方法可以访问Windows系统的D、E盘。在Linux系统显示Windows的分区一般顺序这样的:hda1为C盘、hda5为D盘、 hda6为E盘……以此类推。上述方法可以查看Windows系统有一个很大的问题,就是Windows中的所有中文文件名或文件夹名全部显示为问号 “?”,而英文却可以正常显示。我们可以通过加入一些参数让它显示中文。还以上面的操作为例,此时输入命令:

#mount -t vfat -o iocharset=cp936 /dev/hda1 /mnt/winc

现在它就可以正常显示中文了。

3.使用mount加挂闪盘上的文件系统

在Linux下使用闪盘非常简单。Linux对USB设备有很好的支持,当插入闪盘后,闪盘被识别为一个SCSI盘,通常输入以下命令:

# mount /dev/sda1 /usb

就能够加挂闪盘上的文件系统。

小知识

Linux命令与Shell

所谓Shell,就是命令解释程序,它提供了程序设计接口,可以使用程序来编程。学习Shell对于Linux初学者理解Linux系统是非常重要的。 Linux系统的Shell作为操作系统的外壳,为用户提供了使用操作系统的接口。Shell是命令语言、命令解释程序及程序设计语言的统称,是用户和 Linux内核之间的接口程序。如果把Linux内核想象成一个球体的中心,Shell就是围绕内核的外层。当从Shell或其它程序向Linux传递命 令时,内核会做出相应的反应。Shell在Linux系统的作用和MS DOS下的COMMAND.COM和Windows 95/98 的 explorer.exe相似。Shell虽然不是系统核心的一部分,只是系统核心的一个外延,但它能够调用系统内核的大部分功能。因此,可以说 Shell是Unux/Linux最重要的实用程序。

Linux中的Shell有多种类型,其中最常用的是Bourne Shell(sh)、C Shell(csh)和Korn Shell(ksh)。大多数Linux发行版本缺省的Shell是Bourne Again Shell,它是Bourne Shell的扩展,简称bash,与Bourne Shell完全向后兼容,并且在Bourne Shell的基础上增加了很多特性。bash放在/bin/bash中,可以提供如命令补全、命令编辑和命令历史表等功能。它还包含了很多C Shell和Korn Shell中的优点,有灵活和强大的编程接口,同时又有很友好的用户界面。Linux系统中200多个命令中有40个是bash的内部命令,主要包括 exit、less、lp、kill、 cd、pwd、fc、fg等。

以色列《国土报》时事评论:关于中国的大谎言

以色列《国土报》时事评论:关于中国的大谎言 - 新闻直通车

从美国开始的呼吁抵制北京奥运的波浪涌到欧洲,最近还抵达了以色列。所有人都对中国感到愤怒:右派怒,因为它是由共产党执政的;左派怒,因为中国资本主义 改革的成功;“西方世界(及其弟子以色列)”怒,因为中国如此不同,黄皮肤的、有威胁力的。西方有时恨日本,有时恨中国(常常取决于两者谁更强一点),他 们不能接受那些大多数居民从来没听说过“十戒”以及耶稣在耶路撒冷受难的国家的成功。

  所有这些混合在一起激起反中国浪潮:有道理的和纯属虚构的,还有数不清的半真半假的、一知半解的、未经验证的陈词滥调。一切发生在中国的邪恶——腐 败、造假以及环境污染——都肯定是“共产主义政府”和“政权制度”的错(只有在开明的西方,我们才有能力区分罪行和一个作为整体的国家之间的差别)。

  每一种陈词滥调都是可接受的,甚至不需要最起码的事实检验。在任何情况下,那些“黄种人”没有润滑良好的公关机器,因此我们可以畅所欲言而无须承担诽谤诉讼的风险。

  批评家并不理解中国社会的复杂性。中国社会正经历巨变,其变化是人类已知的最迅速和最广泛的。中国的环境污染可能令人震惊,但别忘了发达工业化国家把它们的污染工厂搬到中国的土地上。而且和欧美公民相比,一个中国公民的污染有多少呢?

  中国的低工资可能令人哀叹,但我们也要注意到最近几年的迅速提高,以及工人权利的改善,包括那些在城市的“临时工”权利的改善,这些都发生在我们眼 前。中国巨大的经济差距可能引起暴怒,但我们也有必要想想这个政权付出巨大努力改善村民的生活,而且近年来它已经在农村基础设施投入巨资,并取消农业税。

  关于来自中国的假冒伪劣商品的报道可能是可信的,但值得指出的是,中国专利和发明数量的增长,以及对版权保护力度加大。要成为一个繁荣社会,中国显然 还有很长的路要走,但它在最近几十年极大地改善了千百万人的生活,这是没有哪个国家可比拟的。多点了解中国不会伤害到任何想写中国的人。

  有时候,这是无知、单纯的问题;有时候,这是愤世嫉俗的偏见。当法伦(Mia Farrow)和斯皮尔伯格(Steven Spielberg)呼吁中国不要援助达尔福尔的大屠杀,人们也许会问:你自己的国家又怎样做?那伟大的美利坚合众国,它的武器扩散犹如中东的瘟疫,它摧 毁了巴格达,它的机枪轻易地流入什叶派和逊尼派民兵之手。美国和它的公民有权对别人进行道德说教吗?

  哦,我忘了。毕竟,美国人是白种人,因此他们有资格以民主和基督的同情之名发言。真遗憾,中国人太不相同了,因此总是有罪的

Friday, August 24, 2007

How to Make Great Photographs

How to Make Great Photographs

INTRODUCTION

"Photography is the power of observation, not the application of technology." Ken Rockwell.

How have I made all my best shots? By noticing something cool and taking a picture. The important part is noticing something cool. Taking the picture is easy.

Your camera has NOTHING to do with making great photos. You have to master technique of course, but that's just a burden to get out of the way to free yourself to tackle the really hard part. The hard part is saying something with your images.

Photography is art. It's abstract. Therefore it's difficult for many people to grasp. It's easy and lazy to think a camera makes the photos. It's easy to blame bad photos on a camera. When you get better you'll realize you would have been better off to pay more attention to your images and less to your camera.

All cameras, especially digital ones, offer about the same image quality in real use. The real difference is how easy or possible it is to make the needed adjustments to get decent photos in each different kind of real-world condition. Test charts shot under controlled conditions completely ignore the real world and thus only compare performance for one limited aspect of performance under only one combination of conditions, which is why those tests have nothing to do with how your photos look. That's why I ignore lab test reports and just try for myself. Lab work is useful for sorting out minutiae otherwise invisible between similar cameras in real photography and that's it.

Photography is like golf. They are both fun, popular and require some equipment. Very few people can get others to pay them to do either one for the same reason. Each takes a lifetime of constant practice, getting better and better little by little. Most golfers play for decades and never hit a hole-in-one. Photography is more complex than golf. Why does anyone expect ever to make a perfect photograph?

PATIENCE

You can't be on a schedule. You have to go out, look around and wait for the light and inspiration.

Many great shots are made only after years of observing a subject, learning when it looks best, and returning to photograph it at its most spectacular. This is how real photographers make anything look extraordinary.

If you're traveling with non-photographers you're going to have to get your schedules straight, since you'll be out shooting while normal people are eating dinner or still sleeping in the morning.

I find it difficult if anyone is expecting me to return on any sort of schedule. You are out in, and at the whim of, nature and your own brilliant crazy ideas and realizations. Sometimes you'll be back in 10 minutes, other times you might be out all night if you get excited about something.

You cripple yourself if you have someone expecting you to be back at a certain time. I've made my best work when I let the group go ahead and I continued to work at something that excited me.

Brilliance doesn't work on a schedule.

KEEP YOUR EYES OPEN

You see more if you're looking. The more you look, the more you see worth photographing. If you're not thinking and not looking you'll walk right past some of the most extraordinary opportunities.

For instance, I lived in the real Beverly Hills from 1995 - 1998. I was on Maple Drive, the same street as George Burns. I never saw any stars. I would see them listed as having lived in Beverly Hills when reading an obituary, and remark "how about that!," having never seen them even if they lived a block away. I would rarely notice them when I was in at the studios all day, every day. Why? I didn't care, and I wasn't looking for them. If I was a tourist or a housewife that reads People magazine and found actors interesting I'm sure I would have seen stars a few times every day. When I had guests in they saw actors all over the place.

The actors were all over the place, but I never saw them. Others did. If you care about something, you'll see it. If you don't, you won't. The best photos aren't obvious. Great photo opportunities don't stand out if you're not looking. That's why they're called opportunities: just like any other opportunity, you have to be paying attention to recognize them.

Photo opportunities are everywhere. Pay attention, keep your eyes open, and look for them.

PRIVACY

Creation is a solitary act. I can't create photos if I'm being distracted, watched or asked questions. I need to get out on my own and concentrate.

It's OK to go out and photograph as a group. You do have to split up and shoot on your own once you get there. Otherwise everyone in the group winds up with identical mediocre shots. Split up and see what you see, then meet up at the end for some socializing.

PASSION

Photography is communicating passion and sparking excitement in the mind and body of another person. If you don't care about the subject then the results won't get beyond the basics. Care deeply and incredible things happen. Don't care and you are quickly forgotten.

"If I feel something strongly, I make a photograph. I do not attempt to explain the feeling." Ansel Adams.

Photography is the art of communicating passion. You need to be passionate about whatever it is that you photograph. If you are passionate you'll get great results, if you don't care, you won't.

A photograph is not about technique. A photograph is communicating something, be it an idea, concept, feeling, thought or whatever, to a total stranger. For a photograph to be effective you have to be clear with what you're communicating. Ansel Adams said "There is nothing worse than a sharp photograph of a fuzzy idea." It is paramount that your idea, thought or feeling be crystal clear in the image. Merely pointing an expensive and masterfully adjusted camera at something doesn't make a good photo. Knowing what you're saying and saying it loud and clear is what makes a strong image people will remember. If it says nothing to you it will say even less to others.

"The proof of the pudding is in the eating." Cervantes, Don Quixote, 1605. Cervantes is observing that it's the end result, not the process, that matters.

Likewise, hardware has absolutely nothing to do with any of this. Craft is just a way to free your ability to communicate, not the communication itself. Many men blame their inadequacies on their hardware and think that simply buying more will solve the problem, excusing them from having to expend any precious mental effort in anything other than shopping for more hardware. You'd double over laughing if you saw the email I get from this site: 99% is from men who think all they have to do is spend some money and that great images will just pour forth. You need to get involved deeply and take your feelings seriously. You don't need money or any more equipment than you already have. Heck, I use crummy point-and-shoots and get great images, too.

Likewise you need to spend time at it just about every time. You usually cannot do it for just 5 minutes and do a decent job. It's odd how many times I'm someplace popular that I'll see a dozen different tourists get out, make a snap, and disappear while I'm still trying to concentrate, feel and understand the shot I'm going to make. You usually shouldn't rush these things!

It's all in your mind and imagination.

One cannot just keep doing the same thing. One needs constantly to innovate and discover new ways of doing what you've been doing. See and feel things from different angles and in different ways.

Not last nor least, you need to keep doing it with the same subject. The better you know your subject the better your results will be.

Sculptor Henry Moore said it best: "Art is the expression of imagination, not the reproduction of reality."

Photographer Elliot Porter said: "True art is but the expression of our love of nature" and "A true work of art is the creation of love, love for the subject first and for the medium second."

Charles Sheeler said: "Photography is nature seen from the eyes outward, painting from the eyes inward. Photography records inalterably the single image, while painting records a plurality of images willfully directed by the artist."

And even Albert Einstein offers: "Imagination is more important than knowledge."

A good photographer makes great images with a disposable camera because she knows its limits and how to use it. On the other hand, plenty of poor photographs are made every day using very expensive cameras by people lacking passion and vision, regardless of how much technical skill they have and how sharp their lenses are.

People write novels, not typewriters. So why do some people think buying a different camera or learning all about shutter speeds will help them make better images? People make photographs, not cameras. Your choice of camera has NOTHING to do with anything. NOTHING.

"Photography is bringing order out of chaos." Ansel Adams.

Painting is the art of inclusion. Photography is an art of exclusion. Trying to "get it all in" guarantees a poor photo. Anything that does not contribute to a photo distracts from it. Keep your images clean and simple.

Less is more; the less in the frame the stronger the image. Simplicity is a strong virtue.

I'm going to spend a few sections explaining what's not important. If you already understand this then skip down to the important sections starting at "curiosity."

INTIMACY

It's critical to be familiar with every nuance of your equipment. You need to know exactly how it responds in every situation. You need to foresee the final results when you look at a natural scene. You need to know exactly how your equipment ill interpret reality.

When you know this you can ensure that each photo you make will look as you intend. You'll know exactly how the photos render (look) and be able to make changes in the scene accordingly.

You can't use five cameras and know all of them well. Use one camera and one lens and one film and learn it's every nuance. Don't waste time chasing every new camera: if you do, you'll never learn it well enough to create great images, except by chance.

1.) GETTING STARTED

Don't buy anything yet. You can create magnificent images with ANY camera. Too many people think camera shopping is the first thing to do on a quest for great images. I need to explain that it's really the last. Some of us own fancy cameras because we are rich and these fancy cameras make photography more convenient. They have nothing to do with the final quality of the images.

Whatever you have is all you need, even point-and-shoot or disposable cameras. Thinking you need more makes you skip things today since you're worrying that "if you only had a..."

"Necessity is not a fact, it's an interpretation." Friedrich Nietzsche.

Go take art, painting, drawing, and design classes at your local community college. Learn to see. You may want to start by reading the books I suggest about art and composition. I never took any photo classes. Everyone learns differently; I learn by reading and doing and seeing.

The photographers whose work I admire most often are former painters or at least people who majored in art; not people with computer, engineering, science or technical photography degrees.

Ask artists for help when you are starting. Ask them how to see and show them your images and ask for suggestions. They will see things that you haven't yet, and will help open your eyes to making better images.

Avoid the friend, neighbor or co-worker who works in computers, science or engineering and always talks about cameras. These people's passion is usually just for the cameras or computers themselves, not about photography itself or art or expressing their imagination visually. Watch out for people who prefer to talk about tools instead of actually making photos. There are thousands of people who watch sports on TV and can talk endlessly about sports stats for every one athlete who actually plays professional sports. You want to talk to the rare guy who actually does it.

Likewise, forget the Internet. Starting out you need far more depth than the cursory treatments shared over the Internet and shared on my website. I'd love to help you out in person since this is all too deep to grasp over email. Learning is a two-way process, not a series of one-way emails or web reading.

Also be warned: the internet is still overloaded with the technical people who invented it. These are the last people from whom you'd want to learn, since they are usually equipment fetishists, not artists. They happen to be the ones most likely to post websites or waste their time in photo chat rooms and user groups. Beware.

Talk to professional photographers, not amateurs and hobbyists. If you don't know any pros, go look in the Yellow Pages or ask around at a professional photo lab. Some professional photographers actually enjoy their work and will talk your ear off for hours if you ask nicely.

Find people whose photos you admire and ask them. Find people whose art you admire and ask them, too. Avoid camera collectors and people who own a lot of expensive cameras. Don't talk to someone who can talk endlessly about film technology, but who never has made a photograph you admire. Talk to these engineers and you'll get so flustered worrying about your camera that you'll never get out and make good photos.

Try The Nikon School, which is a day-long slide show that costs $100 when I took it in 2001. It covers more in the very first hour than most photo courses teach in a semester. Pay attention!

You know the best classes to take? Forget fancy schools. Just look up your local community college or adult education program. There you'll find teachers who really enjoy what they do and will share the world with you if you just ask. Even better, these classes are never more than $100, if not free, depending on your location.

Don't waste too much time studying "photography." Most "photo" classes simply waste your creative time fumbling with obsolete concepts of f/stops and film speeds. Rarely do they teach you how to go create the images you really want. It's important to be fluent with the technical concepts, but those are only a starting point. Too many people spend so much time grappling with technique that they completely forget that technique and equipment is nothing more than a small step in a very long journey in creating great images.

I teach photography very differently from the old farts. In the first 150 years, which were from about 1835 through about 1985 with the introduction of the first real Matrix exposure meters (as opposed to ordinary light meters), one needed to bridle oneself with many clumsy technical inconveniences before one could produce any photograph at all. Since it's only been about ten years now that many cameras know how to set themselves properly over a wide range of conditions, many old timers still haven't learned that for most people one may completely ignore camera settings. That's right, I usually shoot on autofocus and program auto exposure any time I can!

It's sad when people ask me to suggest a camera that fits the pathetic requirements for beginning photo classes, which usually require a totally obsolete manual camera. Good gosh, run away from those classes and learn to love your point and shoot. Automation is good: the camera is not thinking for you, it's just setting the rudiments of focus and exposure which rarely require creative thought. The auto cameras free your creative juices to concentrate on what is important, which is heat, passion, fire, composition, expression and lighting.

I suggest going out and trying to express your feelings carefully and see what you get. Once you get familiar with things you may want to seek out technical advice from someone who really knows. It's more important to go find things about which you are passionate and attempt to convey that fire through images first.

2.) FORGET TECHNIQUE WHEN STARTING

"I am not a scientist. I consider myself an artist who employs certain techniques to free my vision." Ansel Adams in his Autobiography, page 254

Worrying about manual exposure settings and technique distracts you from your passion, just as if your lover were to stop to answer the phone in the middle of a steamy one-on-one.

Many people still mistakenly think that mastering simple issues like shutter speeds and depth of field is all there is to know about photography. Those have as little to do with photography as typewriter repair has to do with composing a novel. They are necessary evils, and by no means the central point.

For larger format cameras like 120 and 4x5 you probably will have to learn technique because those cameras are not made in enough quantity for their manufacturers to justify the efforts in automating them, but for 35mm and digital almost all cameras can do this themselves better than most of the people who would insist you set the camera manually. Don't fret the technique unless you have to. Most of what you see in my galleries was shot in program automatic mode. Tell that to your photo teacher.

Watch out, I know people who actually enjoy having to fool with the settings on their view cameras. This is OK, but don't let that mislead you to worrying too much about it. Start with an automatic camera so you learn the important points of how to express your feelings first. You can learn f/stops later.

Old farts like to make themselves feel important by making you think that you need them to teach you the secrets of fiddling with your camera. They will try to get you to believe that all this crap is required to make photographs. They will insist you waste your time with manual exposure settings, and if you are stupid enough to believe this you'll also spend all your time worrying about which lens is sharper instead of having your own solo show at The Whitney.

There are 150 years of photo technology programmed into your 35mm camera. Use it.

My suggestion is to start off with your 35mm SLR set to matrix metering, program auto exposure and autofocus! Your images will actually be better than dispassionate people who waste their time with manual methods because most cameras have better programming inside them than most photographers do! Your modern SLR camera probably uses the Zone System to figure exposure, which very few photographers understand.

Like what you see on this site? Most of my photos are made in these automatic modes unless conditions dictate something else. I used to use all the manual settings and my photos were boring because I missed the magic moments.

I'll explain what you really need to know about the technical side at the very bottom of this page.

You need to worry about seeing, feeling, composition and lighting, NOT about f/stops as you start out.

Yes, technical ability, in fact, virtuosity, is absolutely required for successful photography, however, this ability is nothing more than a mandatory prerequisite with which one might then be able make great photos. Luckily much of this fluency today is incorporated into automated cameras, making mastery much easier. Technical mastery alone does not make good photos, it's just one of the necessary parts.

3.) YOUR CAMERA DOES NOT MATTER

Honest. If you believe me, just skip to the next section. If you don't then read the rest of this mandatory page here.

If you insist on going out today and buying a camera, see my page here for inexpensive 35mm cameras and here for digital cameras.

4.) CURIOSITY

Photograph subjects for which you have a true curiosity. You have to find them interesting if you want the people who see your work to find them interesting, too.

5.) FOLLOW YOUR OWN VISION

Don't follow gurus, teachers, me or anyone else.

You'll never be better than anyone else at being them. No one will be better at what Ansel did than Ansel, and likewise, no one will ever be better at doing what you do than you.

Be yourself. Show your passions. Don't try to duplicate someone else's.

You have to go out, be yourself, and your own style will develop. Never, ever think that because you like something done by someone else that you have to do the same.

Find something about which you are passionate and explore that. If you get off on figurines or wastebaskets or old people or beautiful naked girls or hubcaps or patterns left by tires in the snow or sewage processing plants or cute little animals, go photograph them.

There is no right or wrong thing to photograph. Just show us what excites you.

If nothing excites you, your photos will suck. Find what you like, and the heck with everyone else.

6.) SEE, DON'T JUST LOOK

7.) CONVEY WHAT YOU FEEL. ASK HOW YOU WOULD DESCRIBE WHAT YOU ARE FEELING TO A BLIND PERSON.

8.) THERE ARE NO RULES

There is no right and no wrong. The rule of thirds is not a rule and rules are for idiots. Just go make good photos. A good photo is one you or someone else likes. There are no formulas or grades or scores.

9.) ASK NOT WHY SOMETHING IS HERE, BUT HOW TO MAKE IT MEANINGFUL

10.) CREATIVITY

Creativity is nice, but all because something is creative does not make it art. When a baby reaches into his diaper and paints the wall with what he finds there, it is a very creative act, but it is not art.

TECHNICAL STUFF

Now that you've read this far let me give you some tips.

1.) LIGHTING

Lighting is absolutely the most important technical issue there is. Learn composition as well and you'll have just about everything you need to worry about solved.

First and foremost you need to develop a sensitivity to the way light feels while you are outdoors, and learn through experience how that will look on film. As you develop this sensitivity you will be able to understand when the light looks right to capture the look you want, and when to put away the camera and grab lunch. With this ability you also will learn to be able to modify light with simple reflectors and scrims to help create your look.

The smaller your subject, the easier it is to modify light. Portrait, bug and flower photographers do this all the time; landscape photographers usually have to wait for the right light.

A simple sheet of 8-1/2 x 11" paper can reflect enough sunlight to fill in shadows on a face.

To get the right light on a mountain you may need to wait for the right season, the right weather and the right time of day. This is how Ansel Adams was able to create such masterful works: he lived in Yosemite and only showed his works from when the lighting was fantastic. If you show up on vacation and snap away in whatever light is there you'll not likely get anything extraordinary.

Everyone has different tastes. This is art.

You either need to create your own lighting in a studio (or with ten tons of gear and generators as we do on movie sets), or you need to have the patience to wait for nature to supply the correct lighting.

2.) PATIENCE

As explained above, when photographing landscapes one needs patience to get the right light. Since you can't light up the whole outdoors, you just have to wait for the right light.

This is really important!

You may have to wait for hours or days or months or years to get the right light. You cannot have people waiting for you. If you rush you'll miss the good light.

3.) EXPERIENCE

With practice you'll learn what looks good in photographs.

No photograph is an exact reproduction. All photographs distort reality. As you become familiar with how your materials interpret reality you will learn to recognize under what conditions you get the results you want. Knowing that, you will start to photograph more under the right conditions, and also seek out those conditions.

You will learn what things need to look like to your eye to get the results you want in a photograph.

One hint is that the contrast needs to look very low to your eye to look OK in a photograph. Photographs pick up contrast.

4.) PRACTICE

You need to photograph often enough to see your results while you can still remember what the scene felt like when you were there. Polaroids are handy for this: you can see the results while you still are there!

Ideally you should develop your film and see the results the very next day while your memory is still fresh. If you wait around for months you'll never be able to correlate your results with what you were feeling when you made the image.

You need to know what results you are going to get when you are feeling something.

5.) EDITING

Only show your very strongest images.

Throw away most of what you shoot. I do. Most of my photos are awful!

Go through the few photos you save out of a roll, and then throw away all but the one strongest image.

Next time, go through the few you've saved from a few rolls, and throw more away.

This isn't painting. In photography it is a requirement to throw away most of what you do.

You'll see that if you only save or show your strongest images that your body of work will seem to improve. Guess what: as you show only the better images, your body of work as seen by others has improved!

Do you think I shoot a roll of film and get a roll loaded with the images you see in my galleries? Of course not. Most of what I shoot is crap. I'm just good enough to throw most of it away and only show the good stuff.

Ansel Adams said that if you can produce one strong image in a year that you are doing very well. Don't expect to turn out miracles every roll, or even every month. Ansel didn't, I don't, and I don't think anyone does.

6.) FILM

I wrote a whole page here. Your choice of film is very important to your look.

Avoid print film, which is what 95% of amateur photographers shoot and gives inconsistent results. I shoot slides, which is what you see on this site.

Go read the film page for much more on this.

7.) EXPOSURE COMPENSATION: your Lighten/Darken control

Forget this if you are shooting print film since no matter how hard you try to get the correct exposure it's usually messed up at the photo lab when your negatives are made into the prints you see. This is why I strongly suggest digital or slide film on my film page.

If you shoot slides or digital or do your own printing then pay attention.

Shoot enough to learn under what conditions your images look too light or too dark. If you find some things always come out too light or too dark (or if the shot you just made on your digital just came out too light or dark) then here are the amounts to compensate.

Don't be bashful. No camera is perfect and one almost always needs to adjust the compensation for some shots. It took me a long time to learn this; I thought my camera was always smarter than I was. It usually is, but not always. It is these times when you need to adjust the exposure compensation.

There are no rules here, just guides. Do whatever looks right to you.

Ideally you should learn the Zone System, since when you do you'll get perfect exposures every time with no guessing or bracketing. Knowing the zone system will make this exposure compensation much clearer.

Here is what each setting does. This is not a replacement for the Zone System:

0: If your photos look fine, then no compensation is required.

+1 Stop: This is a good start for things that usually turn out too dark, like white things on a overcast day. +1 stop will lighten a medium gray to a medium light gray. This is a common setting I'd often use on older cameras without modern matrix or evaluative meters. Use this setting if the subject is mostly light granite or California stucco, for instance. A subject that is completely yellow and fills your screen might need +2/3.

+2 Stops: This is a severe correction for something that would come out way too dark. If something came out a medium gray and you added +2 stops you will get white. On old cameras or with manual light meters you would use this much compensation to make sand or snow look white.

-1 Stop: I don't usually use this. This will take a medium gray and make it a dark gray.

-2 Stops: never used except with a broken camera. This will take a medium gray and lower everything to a very dark, almost black, gray. You'd only use this with a spot meter to set shadows here as part of the Zone System, not as a setting on a camera's exposure compensation dial.

8.) ALL ABOUT USING FLASH

WHEN TO USE FLASH

Most amateur photographers and all snapshooters use flash exactly at the wrong times, ensuring amateur-looking images. Proper use of flash is far more important than what kind of camera you have. Any point-and-shoot used properly will give far better results than any Leica, Canon or Nikon used the way most amateurs do.

Most people incorrectly leave the flash OFF in daylight which leads to harsh, ugly sunlight on their friends' faces. Turning the flash ON in bright sunlight will help lighten the shadows to make them look much more natural. On a P/S camera just push the flash button a few times until the little flash icon appears, on a Nikon just turn on the flash. Also in backlit photos you'll be able to see your friends instead of just getting silhouettes.

SYNC MODES

Most people incorrectly use flash indoors or in low light at night. Using the flash with the usual default sync mode indoors leads to the nasty black backgrounds and washed out people indoors. What's worse, those nasty black backgrounds confuse printing machines into making the prints too light, and then these poor photographers blame the camera for over exposing their flash shots!

If you are doing studio strobe work or macro photography lit only by the flash of course it's OK to use fast sync. This just isn't what most ordinary people photograph.

With disposable cameras this is your only choice. With most point-and-shoots and all Nikons you should either turn the flash OFF and shoot by available light if your subject is reasonably still, or for photographing people or moving objects use the flash in the SLOW REAR or SLOW sync mode.

These SLOW sync modes are also in many P/S cameras. In a P/S camera one typically pushes the flash button until a little moon and city icon ("Night Mode" in Japanese) appears.

The SLOW sync modes allow the camera to make a long enough exposure of the background (ambient) light for it to look natural. Otherwise it always looks way too dark at the usual 1/60 sync speed people use. Really stupid photographers use the 1/250 sync speed for indoor photos and make the effect even worse. Best to try the slowest speed you can, like 1/30, if you're setting the shutter manually.

Both SLOW and SLOW REAR give the same exposure and f/stops. SLOW pops the flash at the beginning of the exposure, and SLOW REAR pops it at the end.

This matters if you have an exposure long enough to blur anything. If you do, the effect of the flash popping at the start of the exposure makes the subject appear to streak backwards from the ghost image frozen by the flash. You see the ghost and the streak moves forwards from it, showing the ghost at the back of the streak. Bad. SLOW REAR reverses this effect and gives the illusion of the subject moving forward from the ghost. This is because you see a streak, and then the flash pops at the end (front) of the streak. It might make more sense to rename SLOW REAR to "front" sync, but that's another story.

Since SLOW REAR mode fires the flash at the end of the long exposure it serves another purpose: people think the photo is taken when the flash fires, so having the flash fire at the end (rear) of the exposure keeps them still and smiling the whole time the shutter is open waiting for your camera to go off. This trick goes away for digital and newer SLR cameras since most of them fire very visible preflashes before the exposure. (The camera companies lie about them being invisible.) Thus you'll get a double flash effect.

Of course if you are trying to freeze moving things you won't with SLOW sync. You'll get the blurry streaks behind people that you see all the time in National Geographic Magazine. These streaks convey a sense of motion and I like them.

FLASH DIFFUSION

Flash on the camera is the nastiest looking light you can get. For use as fill this is usually fine, however you'll get more natural results by using a cheap diffuser if your subject is close enough. Even many professionals don't realize this, and you'll often see famous photographers suggest turning the flash fill level down a stop or two. They have to do this because the harsh on-camera fill flash may look unnatural. If you diffuse the flash (as simple as bouncing it off a big white card) then you can let the camera use the normal amount of fill flash and it will both look natural due to the diffusion, and be more effective because it can be at the correct level and not turned down a stop or two.

I prefer the $20 Lumiquest reflector gizmo that folds flat in my case and attaches with Velcro. Note that the area of the reflector is much bigger than the lens of the flash itself, giving a much softer quality to the light.

GREAT FILL FLASH INDOORS

Here's how to get great, natural looking fill indoors with most SLR cameras:

a.) Set the camera to SLOW sync

b.) Point camera-mounted flash up at the ceiling

c.) Pull out a built-in little white card or rubber-band one behind the flash so a little bit of light will bounce forward off the card. This light from the card will give a nice catchlight to their eyes while most of the light goes up to the ceiling to fill the room with soft, natural fill light. (Hint: if the room light is too dark to give a reasonably short exposure time in SLOW sync you can try the regular sync mode, in which case the entire shot is lit only by the flash bouncing off the ceiling and the little off the little white card. In this case forget bothering with color compensation filters mentioned in e.) below.)

d.) Set flash to TTL exposure mode. This will vary with camera brand. You want the mode that will blend the levels of ambient and flash light automatically.

e.) Filter or gel the flash to match the color of the existing room light, and filter your camera to match it. This way both the ambient room light and flash fill match. With a digital camera of course you set the camera's white balance to match room lighting and then get a colored gel to put over the flash for tungsten or fluorescent. You can get these gel filters in sheets for a few dollars at theatrical stage and lighting stores found in every decent sized city.

9.) TIME EXPOSURES FOR WATER

1/500 shutter speed freezes anything. This does not look as it does to our eyes. This is usually what you see in surfing magazines where every wonderful drop of spray is frozen.

1/30 makes moving water look about natural, if that's the effect you seek.

1/8 gives a nice blur.

1 second starts to get really smooth like this.

Several seconds or minutes starts to make all the whitewater flow into what looks like a fog. Here's an example.

In these examples the usual waves continuously came in and crashed on the rocks.

10.) TRICKS FOR GREAT B/W PHOTOS

A yellow filter (K2, #8, Y48 etc.) is REQUIRED outdoors for B/W film, otherwise blue skies will be completely washed out. See also the filter page. A yellow filter is required to give natural results outdoors, since film has much more sensitivity to blue than our eyes do. The yellow filter makes film's response to color match our eyes, and thus prevents the darker blue sky from looking as bright as the clouds as it would without the filter.

Go read the tips about b/w film, exposure and processing and printing about halfway down my film page here. If you don't want to take the time for great results as explained on the film page, here are some basic suggestions:

1.) Set your camera for one stop more exposure than the film is rated. Most film ratings lead to a stop of underexposure and dull shadows. In other words, either set the camera manually to an ISO speed one-half of what the box says, or set the exposure compensation to +1.

2.) If you are finishing in digital, instead just shoot color film normally (no filters) and convert to B/W in Photoshop because A.) ICE (the dust and scratch removal feature of better scanners) works with color film but not b/w and B.) you can choose the mixing of the color channels in Photoshop to select filter effects after the fact without having to use a filter for the original photograph! In the old days you had to shoot b/w film through a filter, today color film effectively shoots the color layers with various filters and you may pick and choose (and even mix) later in your computer instead. In the old days I would sometimes shoot several images with different filters; today I just shoot it once on color film if my output is to be B/W digital.

如何发掘出更多退休的钱?

如何发掘出更多退休的钱? http://bbs.wenxuecity.com/bbs/tzlc/1328415.html 按照常规的说法,退休的收入必须得有退休前的80%,或者是4% withdrawal rule,而且每年还得要加2-3%对付通胀,这是一个很大...