- Практическое руководство. Использование именованных каналов для сетевого взаимодействия между процессами How to: Use Named Pipes for Network Interprocess Communication
- Пример Example
- Пример Example
- Отказоустойчивость Robust Programming
- Named Pipes
- When to use named pipes in Windows?
- 4 Answers 4
- Not the answer you’re looking for? Browse other questions tagged windows named-pipes or ask your own question.
- Related
- Hot Network Questions
- Subscribe to RSS
- Part I: The Fundamentals of Windows Named Pipes
- What Kind of Pipes Exist?
- How Does Pipe Communication Work?
- What Are the Operational Limits Associated with Named Pipes?
- Named Pipe Permissions
- Take a Deeper Dive into Named Pipe Servers with Hands-On Examples
- VS-Labs Research Team
- What are named pipes?
- 10 Answers 10
Практическое руководство. Использование именованных каналов для сетевого взаимодействия между процессами How to: Use Named Pipes for Network Interprocess Communication
Именованные каналы обеспечивают межпроцессное взаимодействие между сервером канала и одним или несколькими клиентами канала. Named pipes provide interprocess communication between a pipe server and one or more pipe clients. Они предоставляют больше функциональных возможностей, чем анонимные каналы, которые обеспечивают межпроцессное взаимодействие на локальном компьютере. They offer more functionality than anonymous pipes, which provide interprocess communication on a local computer. Именованные каналы поддерживают полную дуплексную связь по сети и несколько экземпляров сервера, связь на основе сообщений и олицетворение клиента, позволяющее подключающимся процессам использовать собственные наборы разрешений на удаленных серверах. Named pipes support full duplex communication over a network and multiple server instances, message-based communication, and client impersonation, which enables connecting processes to use their own set of permissions on remote servers.
Для реализации именованных каналов используются классы NamedPipeServerStream и NamedPipeClientStream. To implement name pipes, use the NamedPipeServerStream and NamedPipeClientStream classes.
Пример Example
В примере ниже показано, как создать именованный канал с помощью класса NamedPipeServerStream. The following example demonstrates how to create a named pipe by using the NamedPipeServerStream class. В этом примере серверный процесс создает четыре потока. In this example, the server process creates four threads. Каждый поток может принимать подключение клиента. Each thread can accept a client connection. Процесс подключения клиента передает серверу имя файла. The connected client process then supplies the server with a file name. Если клиенту имеет необходимые разрешения, серверный процесс открывает указанный файл и отправляет клиенту его содержимое. If the client has sufficient permissions, the server process opens the file and sends its contents back to the client.
Пример Example
В примере ниже представлен клиентский процесс, основанный на классе NamedPipeClientStream. The following example shows the client process, which uses the NamedPipeClientStream class. Клиент подключается к серверному процессу и передает серверу имя файла. The client connects to the server process and sends a file name to the server. В этом примере используется олицетворение. Это означает, что у идентификатора, от имени которого выполняется клиентское приложение, должны быть разрешения на доступ к файлу. The example uses impersonation, so the identity that is running the client application must have permission to access the file. Затем сервер отправляет клиенту содержимое файла. The server then sends the contents of the file back to the client. Полученное содержимое файла выводится в консоль. The file contents are then displayed to the console.
Отказоустойчивость Robust Programming
Клиентский и серверный процессы в этом примере предназначены для выполнения на одном компьютере, поэтому объекту NamedPipeClientStream передается имя сервера «.» . The client and server processes in this example are intended to run on the same computer, so the server name provided to the NamedPipeClientStream object is «.» . Если клиентский и серверный процессы выполняются на разных компьютерах, вместо «.» должно быть указано сетевое имя компьютера, на котором осуществляется серверный процесс. If the client and server processes were on separate computers, «.» would be replaced with the network name of the computer that runs the server process.
Named Pipes
A named pipe is a named, one-way or duplex pipe for communication between the pipe server and one or more pipe clients. All instances of a named pipe share the same pipe name, but each instance has its own buffers and handles, and provides a separate conduit for client/server communication. The use of instances enables multiple pipe clients to use the same named pipe simultaneously.
Any process can access named pipes, subject to security checks, making named pipes an easy form of communication between related or unrelated processes.
Any process can act as both a server and a client, making peer-to-peer communication possible. As used here, the term pipe server refers to a process that creates a named pipe, and the term pipe client refers to a process that connects to an instance of a named pipe. The server-side function for instantiating a named pipe is CreateNamedPipe. The server-side function for accepting a connection is ConnectNamedPipe. A client process connects to a named pipe by using the CreateFile or CallNamedPipe function.
Named pipes can be used to provide communication between processes on the same computer or between processes on different computers across a network. If the server service is running, all named pipes are accessible remotely. If you intend to use a named pipe locally only, deny access to NT AUTHORITY\NETWORK or switch to local RPC.
For more information, see the following topics:
When to use named pipes in Windows?
In *nix many command line applications that accept file names as arguments accept pipes also. Example:
Also works with
And the result of the «anotherApplication» is redirected to «anApplication» as it was a file
I learned that the Windows equivalent to this is a «named pipe». I wonder if the command line application must be aware of named pipes to understand it, or if any command line application that accepts a file as argument would work with a named pipe instead.
4 Answers 4
You’ve got this quite backwards. Just to be precise:
This runs anApplication with the filename file.txt as the first command line argument.
This runs anApplication with no command line arguments. The standard out is connected to the standard in of anotherApplication which is run with arguments as the command line arguments. This is exactly the same on windows as it is on Unix versions. Named pipes are a completely different OS feature.
A named pipe is a directory entry that looks like a file, but acts like a stream of data that you can attach output and input to.
A named pipe on Windows is a very different thing than what you’re talking about. A named pipe is actually a tool for helping to build server applications on Windows, and is roughly equivalent to a «Unix domain socket».
In your situation, whether anApplication works in this situation depends on how the application reacts when executed without a file name on the command line. (I’m talking about the arrangement in your description; the command line is backwards as pointed out by another answer.) If the application reads from stdin when started without a command line, then this sort of shell pipe arrangement will work. If instead, the application prints a help message and exits when started without a file name, then this shell pipe will not work.
Note that this is the syntax of cmd.exe.
This sort of pipe redirection should work with any program, so to answer your specific question, the program needs no special code if it is a standard console application.
There is one caveat — if the program is getting input through the special keyboard monitoring forms of runtime API, then redirection won’t work.
AFAIK it works the same under Windows as in UNIX. I suppose that some more advanced Win32 Console API functions might bypass this, but you’ll have to read the documentation for that.
Not the answer you’re looking for? Browse other questions tagged windows named-pipes or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Part I: The Fundamentals of Windows Named Pipes
This shared memory is treated as a file object in the Windows operating system. Since pipes are treated as file objects , standard file object functions such as ReadFile() and WriteFile() , which are exposed via the Windows Application Programming Interface (API), are commonly used during communication.
Pipe communication utilizes First-in-First-out (FiFo) implementation.
This means that the first byte of data written to a pipe is the first byte of data that will be read from the pipe. After data is read from a pipe, it is no longer available inside the pipe’s data buffer and therefore cannot be read again.
However, a function called PeekNamedPipe() exposed via the Windows API can be used to circumvent this limitation by reading data from a pipe without removing it from the pipe’s data buffer.
What Kind of Pipes Exist?
There are two main kinds of pipes: named pipes , which have a name, and anonymous pipes , which do not have a name.
An example of a named pipe is \\.\Pipe\ExampleNamedPipeServer . While most details discussed in this blog are relevant to named pipes, some information can also be applied to anonymous pipes.
How Does Pipe Communication Work?
Microsoft Windows Pipes utilizes a client-server implementation whereby the process that creates a named pipe is known as the server and the process that communicates with the named pipe is known as the client.
By utilizing a client-server relationship, named pipe servers can support two methods of communication. These two methods are half-duplex and duplex communication. With half-duplex communication, a client opens a one-way channel which allows the client to write data to the server without the server being able to respond.
With duplex communication, a two-way communication channel is opened that allows the client to write data over the pipe to the server, and the server to write data over the pipe back to the client.
What Are the Operational Limits Associated with Named Pipes?
When evaluating the operation limitations associated with named pipes, it is important to note that each active connection associated with a named pipe server results in the creation of a new instance of the named pipe. These instances all share a common name; however, the buffers and handles to each named pipe instance are different.
Enumerating these instances can be accomplished using the tool PipeList , which is part of the SysInternals Suite . An example of how this tool can be used to enumerate the number of active pipe instances can be seen in Figure 1.
With some background info on named pipes and how they operate, it is now time to review the permissions and access control lists associated with named pipes.
Named Pipe Permissions
Permissions are a core component of operating systems and are implemented in many ways. Within Windows, permissions are assigned using Access Control Lists (ACL). ACL’s are composed of Access Control Entries (ACE’s) which hold two separate permission structures.
The first is a Discretionary Access Control List (DACL), and the second is a System Access Control List (SACL). The SACL is mostly used for logging events to the security event log and is not interesting for our purposes. The DACL on the other hand is interesting since it defines who can modify, write, read, or execute a specified resource.
To view the DACL’s of a given named pipe, one can use the tool Accesschk from the SysInternals Suite .
Accesschk is a versatile tool that allows users to enumerate various resources, such as named pipes, and the permissions associated with them.
DACL enumeration can be performed on named pipes by passing the argument \pipe\ via the command line to accesschk.exe .
This argument acts as a wild card and enumerates every existing named pipe that is currently active on the system. An example of this can be seen in Figure 2 below.
Take a Deeper Dive into Named Pipe Servers with Hands-On Examples
Now that we’ve covered some general background information in relation to named pipe usage on Windows and reviewed how to enumerate named pipe permissions, let’s take a deeper dive into identifying usage of named pipe servers within applications using a custom vulnerable application. Click here to read part II of our three-part series: Analysis of a Vulnerable Microsoft Windows Named Pipe Application .
VS-Labs Research Team
Maintain awareness regarding unknown threats to your products, technologies, and enterprise networks. Organizations that are willing to take the next step in proactively securing their flagship product or environment can leverage our zero-day vulnerability research offering. Our subscription-based capability provides your organization with immediate access to zero-day vulnerabilities affecting products and software. Learn More →
What are named pipes?
What are they and how do they work?
Context happens to be SQL Server
10 Answers 10
Both on Windows and POSIX systems, named-pipes provide a way for inter-process communication to occur among processes running on the same machine. What named pipes give you is a way to send your data without having the performance penalty of involving the network stack.
Just like you have a server listening to a IP address/port for incoming requests, a server can also set up a named pipe which can listen for requests. In either cases, the client process (or the DB access library) must know the specific address (or pipe name) to send the request. Often, a commonly used standard default exists (much like port 80 for HTTP, SQL server uses port 1433 in TCP/IP; \\.\pipe\sql\query for a named pipe).
By setting up additional named pipes, you can have multiple DB servers running, each with its own request listeners.
The advantage of named pipes is that it is usually much faster, and frees up network stack resources.
— BTW, in the Windows world, you can also have named pipes to remote machines — but in that case, the named pipe is transported over TCP/IP, so you will lose performance. Use named pipes for local machine communication.
Unix and Windows both have things called «Named pipes», but they behave differently. On Unix, a named pipe is a one-way street which typically has just one reader and one writer — the writer writes, and the reader reads, you get it?
On Windows, the thing called a «Named pipe» is an IPC object more like a TCP socket — things can flow both ways and there is some metadata (You can obtain the credentials of the thing on the other end etc).
Unix named pipes appear as a special file in the filesystem and can be accessed with normal file IO commands including the shell. Windows ones don’t, and need to be opened with a special system call (after which they behave mostly like a normal win32 handle).
Even more confusing, Unix has something called a «Unix socket» or AF_UNIX socket, which works more like (but not completely like) a win32 «named pipe», being bidirectional.
Linux Pipes
First In First Out (FIFO) interproccess communication mechanism.
Unnamed Pipes
On the command line, represented by a «|» between two commands.
Named Pipes
A FIFO special file. Once created, you can use the pipe just like a normal file(open, close, write, read, etc).
To create a named pipe, called «myPipe», from the command line (man page):
To create a named pipe from c, where «pathname» is the name you would like the pipe to have and «mode» contains the permissions you want the pipe to have (man page):
[. ] A traditional pipe is «unnamed» because it exists anonymously and persists only for as long as the process is running. A named pipe is system-persistent and exists beyond the life of the process and must be «unlinked» or deleted once it is no longer being used. Processes generally attach to the named pipe (usually appearing as a file) to perform IPC (inter-process communication).
wc will block until
Pipes are a way of streaming data between applications. Under Linux I use this all the time to stream the output of one process into another. This is anonymous because the destination app has no idea where that input-stream comes from. It doesn’t need to.
A named pipe is just a way of actively hooking onto an existing pipe and hoovering-up its data. It’s for situations where the provider doesn’t know what clients will be eating the data.
This is an exeprt from Technet (so not sure why the marked answer says named pipes are faster??):
Named Pipes vs. TCP/IP Sockets
In a fast local area network (LAN) environment, Transmission Control Protocol/Internet Protocol (TCP/IP) Sockets and Named Pipes clients are comparable with regard to performance. However, the performance difference between the TCP/IP Sockets and Named Pipes clients becomes apparent with slower networks, such as across wide area networks (WANs) or dial-up networks. This is because of the different ways the interprocess communication (IPC) mechanisms communicate between peers.
For named pipes, network communications are typically more interactive. A peer does not send data until another peer asks for it using a read command. A network read typically involves a series of peek named pipes messages before it starts to read the data. These can be very costly in a slow network and cause excessive network traffic, which in turn affects other network clients.
It is also important to clarify if you are talking about local pipes or network pipes. If the server application is running locally on the computer that is running an instance of SQL Server, the local Named Pipes protocol is an option. Local named pipes runs in kernel mode and is very fast.
For TCP/IP Sockets, data transmissions are more streamlined and have less overhead. Data transmissions can also take advantage of TCP/IP Sockets performance enhancement mechanisms such as windowing, delayed acknowledgements, and so on. This can be very helpful in a slow network. Depending on the type of applications, such performance differences can be significant.
TCP/IP Sockets also support a backlog queue. This can provide a limited smoothing effect compared to named pipes that could lead to pipe-busy errors when you are trying to connect to SQL Server.
Generally, TCP/IP is preferred in a slow LAN, WAN, or dial-up network, whereas named pipes can be a better choice when network speed is not the issue, as it offers more functionality, ease of use, and configuration options.