Share or add to bookmark

AddThis Social Bookmark Button

Latest comments

Authorization



  
Home Data transfer protocols overview FCIP TCP/IP technology overview
Протоколы
Обзор протоколов передачи данных

TCP/IP technology overview
TCP/IP technology overview
The Transmission Control Protocol (TCP) is a connection-oriented transport protocol that guarantees reliable in-order delivery of a stream of bytes between the endpoints of a connection. TCP achieves this by assigning each byte of data a unique sequence number by maintaining timers, acknowledging received data through the use of acknowledgements (ACKs), and retransmitting data if necessary.
Data can be transferred after a connection is established between the endpoints. The data stream that passes across the connection is considered a single sequence of eight-bit bytes, each of which is given a sequence number. This overview section contains the following information:
◆ “IPv6 ,” next
◆ “TCP terminology
◆ “TCP error recovery
◆ “Network congestion
◆ “Internet Protocol security (IPsec)

IPv6
Internet Protocol version 6 (IPv6) is a Glossary Link network layer protocol for packet-switched internets. It is designated as the successor of IPv4.

Note: For the most up-to-date support information, please refer to the EMC Support Matrix > PDF and Guides > Miscellaneous> Internet Protocol.
Note: The information in this section was acquired from Wikipedia.org, August 2007, which provides further details on many of these topics.
The main improvement of IPv6 is the increase in the number of addresses available for networked devices. IPv4 supports 232 (about 4.3 billion) addresses. In comparison, IPv6 supports 2128 (about 34.1037) addresses, or approximately 5.1028 addresses for each of roughly 6.5 billion people. However, that’s not the intention of the designers.
The extended address length simplifies operational considerations, including dynamic address assignment and router decision-making. It also avoids many complex workarounds that were necessary in IPv4, such as Classless Inter-Domain Routing (CIDR). Its simplified packet header format improves the efficiency of forwarding in routers. More information on this topic is provided in “Larger address space ” and “Addressing ”.
This section contains the following information:
◆ “Features of IPv6 ,” next
◆ “Deployment status
◆ “Addressing
◆ “IPv6 packet
◆ “Transition mechanisms

Features of IPv6
To a great extent, IPv6 is a conservative extension of IPv4. Most transport- and application-layer protocols need little or no change to work over IPv6. The few exceptions are applications protocols that embed network-layer addresses (such as FTP or NTPv3).
Applications, however, usually need small changes and a recompile in order to run over IPv6. The following features of IPv6 will be further discussed in this section:
◆ “Larger address space ,” next
◆ “Stateless autoconfiguration of hosts
◆ “Multicast
◆ “Jumbograms
◆ “Network-layer security
◆ “Mobility

Larger address space
The main feature of IPv6 is the larger address space: 128 bits long (versus 32 bits in IPv4). The larger address space avoids the potential exhaustion of the IPv4 address space without the need for network address translation (NAT) and other devices that break the end-to-end nature of Internet traffic.
Note: In rare cases, NAT may still be necessary, but it will be difficult in IPv6 so should be avoided whenever possible.
It also makes administration of medium and large networks simpler, by avoiding the need for complex subnetting schemes. Ideally, subnetting will revert to its original purpose of logical segmentation of an IP network for optimal routing and access.
There are a few drawbacks to larger addresses. For instance, in regions where Glossary Link bandwidth is limited, IPv6 carries some bandwidth overhead over IPv4. However, header compression can sometimes be used to alleviate this problem. IPv6 addresses are also harder to memorize than IPv4 addresses, which are, in turn, harder to memorize than Domain Name System (DNS) names. DNS protocols have been modified to support IPv6 as well as IPv4.
For more information, refer to “Addressing

Stateless autoconfiguration of hosts
IPv6 hosts can be automatically configured when connected to a routed IPv6 network. When first connected to a network, a host sends a link-local (automatic configuration of IP addresses) multicast (broadcast) request for its configuration parameters. If configured suitably, routers respond to such a request with a router advertisement packet that contains network-layer configuration parameters.
If IPv6 autoconfiguration is not suitable, a host can use stateful autoconfiguration (DHCPv6) or be configured manually.
Note: Stateless autoconfiguration is suitable only for hosts. Routers must be configured manually or by other means.

Multicast
Network infrastructures, in most environments, are not configured to route multicast. The link-scoped aspect of multicast (that is, on a single subnet) will work but the site-scope, organization-scope, and global-scope multicast will not be routed. IPv6 does not have a link-local broadcast facility. The same effect can be achieved by multicasting to the all-hosts group (FF02::1). The m6bone is catering for deployment of a global IPv6 multicast network.

Jumbograms
IPv6 has optional support for packets over the IPv4 limit of 64 KB when used between capable communication partners and on communication links with a maximum transmission unit larger than 65,576 octets. These are referred to as jumbograms and can be as large as 4 GB. The use of jumbograms may improve performance over high-MTU (Maximum Transmission Unit) networks.
An optional feature of IPv6, the jumbo payload option, allows the exchange of packets larger than this size between cooperating hosts.

Network-layer security
IPsec (IP security), the protocol for IP network-layer encryption and Glossary Link authentication, is an integral part of the base protocol suite in IPv6. In IPv4, this is optional (although usually implemented). IPsec is not widely deployed except for securing traffic between IPv6 Border Gateway Protocol (BGP) routers (the core routing protocol of the Internet).

Mobility
Mobile IPv6 (MIPv6) avoids triangular routing and is as efficient as normal IPv6. This advantage is mostly hypothetical, since neither MIP nor MIPv6 are widely deployed.

Deployment status
As of December 2005, IPv6 accounts for only a small percentage of the live addresses in the Internet, which is still dominated by IPv4. Many of the features of IPv6 have been ported to IPv4, with the exception of stateless autoconfiguration, more flexible addressing, and Secure Neighbor Discovery (SEND).
IPv6 deployment is primarily driven by IPv4 address space exhaustion, which has been slowed by the introduction of classless inter-domain routing (CIDR) and the extensive use of network address translation (NAT).
Estimates as to when the pool of available IPv4 addresses will be exhausted vary widely, ranging from around 2011 (2005 report by Cisco Systems) to Paul Wilson’s (director of APNIC) prediction of 2023.
To prepare for the inevitable, a number of governments are starting to require support for IPv6 in new equipment. The U.S. Government, for example, has specified that the network backbones of all federal agencies must deploy IPv6 by 2008 and bought 247 billion IPv6 addresses to begin the deployment. The People’s Republic of China has a 5-year plan for deployment of IPv6, called the “China Next Generation Internet”.

Addressing
The following subjects are briefly discussed in this section:
◆ “128-bit length
◆ “Notation
◆ “Literal IPv6 addresses in URLs
◆ “Network notation
◆ “Types of IPv6 addresses
◆ “Special addresses
◆ “Zone indices

128-bit length
The primary change from IPv4 to IPv6, as discussed in “Larger address space ”, is the length of network addresses. IPv6 addresses are 128 bits long (as defined by RFC 4291), compared to IPv4 addresses, which are 32 bits. IPv6 has enough room for 3.4.1038 unique addresses, while the IPv4 address space contains about 4 billion addresses.
IPv6 addresses are typically composed of two logical parts: a 64-bit (sub-)network prefix and a 64-bit host part, which is either automatically generated from the interface's MAC (Media Glossary Link Access Control) address or assigned sequentially. Globally unique MAC addresses offer an opportunity to track user equipment (and thus users) across time and IPv6 address changes. In order to restore some of the anonymity existing in the IPv4, RFC 3041 was developed to reduce the prospect of user identity being permanently tied to an IPv6 address. RFC 3041 specifies a mechanism by which time-varying random bit strings can be used as interface circuit identifiers, replacing unchanging and traceable MAC addresses.

Notation
IPv6 addresses are normally written as eight groups of four hexadecimal digits. For example, the following is a valid IPv6 address:
2001:0db8:85a3:08d3:1319:8a2e:0370:7334
If one or more four-digit group(s) is 0000, the zeros may be omitted and replaced with two colons(::). For example, 2001:0db8:0000:0000:0000:0000:1428:57ab can be shortened to 2001:0db8::1428:57ab. Following this rule, any number of consecutive 0000 groups may be reduced to two colons, as long as there is only one double colon used in an address. Leading zeros in a group can also be omitted (as in ::1 for localhost). For example, the addresses below are all valid and equivalent:
2001:0db8:0000:0000:0000:0000:1428:57ab
2001:0db8:0000:0000:0000::1428:57ab
2001:0db8:0:0:0:0:1428:57ab
2001:0db8:0:0::1428:57ab
2001:0db8::1428:57ab
2001:db8::1428:57ab

Note: Having more than one double-colon abbreviation in an address is invalid, as it would make the notation ambiguous. A sequence of 4 bytes at the end of an IPv6 address can also be written in decimal, using dots as separators. This notation is often used with compatibility addresses. For example, the following two addresses are the same:
::ffff:1.2.3.4
::ffff:0102:0304 and 0:0:0:0:0:ffff:0102:0304.
Additional information can be found in RFC 4291 — IP Version 6 Addressing Architecture.

Literal IPv6 addresses in URLs
In a URL the IPv6-Address is enclosed in brackets. For example:
http://[2001:0db8:85a3:08d3:1319:8a2e:0370:7344]/
This notation allows parsing a URL without confusing the IPv6 address and port number:
https://[2001:0db8:85a3:08d3:1319:8a2e:0370:7344]:443/
Additional information can be found in "RFC 2732 — Format for Literal IPv6 Addresses in URLs" and "RFC 3986 — Uniform Resource Identifier (URI): Generic Syntax."

Network notation
IPv6 networks are written using CIDR (Classless Inter-Domain Routing) notation.
An IPv6 network (or subnet) is a contiguous group of IPv6 addresses, the size of which must be a power of two. The initial bits of addresses, identical for all hosts in the network, are called the network's prefix. A network is denoted by the first address in the network and the size in bits of the prefix (in decimal), separated with a slash. For example:
2001:0db8:1234::/48
stands for the network with addresses:
2001:0db8:1234:0000:0000:0000:0000:0000 through 2001:0db8:1234:FFFF:FFFF:FFFF:FFFF:FFFF
Because a single host can be seen as a network with a 128-bit prefix, you will sometimes see host addresses written followed with: /128.

Types of IPv6 addresses
IPv6 addresses are divided into the following three categories:
Unicast Addresses — Identifies a single network interface. A packet sent to a unicast address is delivered to that specific computer.
Multicast Addresses — Used to define a set of interfaces that typically belong to different nodes instead of just one. When a packet is sent to a multicast address, the protocol delivers the packet to all interfaces identified by that address. Multicast addresses begin with the prefix FF00::/8. Their second octet identifies the addresses scope, that is, the range over which the multicast address is propagated. Commonly used scopes include link-local (2), site-local (5), and global (E).
Anycast Addresses — Also assigned to more than one interface, belonging to different nodes. However, a packet sent to an anycast address is delivered to just one of the member interfaces, typically the “nearest” according to the routing protocol’s idea of distance. Anycast addresses cannot be easily identified. They have the structure of normal unicast addresses, and differ only by being injected into the routing protocol at multiple points in the network.

Special addresses
There are a number of addresses with special meaning in IPv6:
◆ ::/128 — The address with all zeros is an unspecified address, and is to be used only in software.
◆ ::1/128 — The loopback address is a localhost address. If an application in a host sends packets to this address, the IPv6 stack will loop these packets back to the same host (corresponding to 127.0.0.1 in IPv4).
◆ ::/96 — The zero prefix was used for IPv4-compatible addresses. It is now obsolete.
◆ ::ffff:0:0/96 — This prefix is used for IPv4 mapped addresses (see “Transition mechanisms”).
◆ 2001:db8::/32 — This prefix is used in documentation (RFC 3849). Addresses from this prefix should be used anywhere an example IPv6 address is given.
◆ 2002::/16 — This prefix is used for 6to4 addressing.
◆ fc00::/7 — Unique Local Addresses (ULA) are routable only within a set of cooperating sites. They were defined in RFC 4193 as a replacement for site-local addresses. The addresses include a 40-bit pseudorandom number that minimizes the risk of conflicts if sites merge or packets somehow leak out. This address space is split into two parts:
• fc00::/8 — ULA Central, currently not used as the draft is expired.
• fd00::/8 — ULA, as per RFC 4193, Generator and unofficial registry.
◆ fe80::/64 — The link-local prefix specifies that the address is valid only in the local physical link. This is analogous to the Autoconfiguration IP address 169.254.0.0/16 in IPv4.
◆ fec0::/10 — The site-local prefix specifies that the address is valid only inside the local organization.
Note: Its use has been deprecated in September 2004 by RFC 3879 and systems must not support this special type of address.
◆ ff00::/8 — The multicast prefix is used for multicast addresses[10] as defined by in "IP Version 6 Addressing Architecture" (RFC 4291).
There are no address ranges reserved for broadcast in IPv6. Instead, applications use multicast to the all-hosts group. IANA maintains the official list of the IPv6 address space. Global unicast assignments can be found at the various RIRs or at the GRH (Ghost Route Hunter) DFP pages.

Zone indices
Link-local addresses present a particular problem for systems with multiple interfaces. Because each interface may be connected to different networks and the addresses all appear to be on the same subnet, an ambiguity arises that cannot be solved by routing tables.
For example, host A has two interfaces that automatically receive link-local addresses when activated (per RFC 2462): fe80::1/64 and fe80::2/64), only one of which is connected to the same physical network as host B which has address fe80::3/64. If host A attempts to contact fe80::3, how does it know which interface (fe80::1 or fe80::2) to use?
The solution, defined by RFC 4007, is the addition of a unique zone index for the local interface, represented textually in the form <address>%<zone_id>. For example:
http://[fe80::1122:33ff:fe11:2233%eth0]:80/
However, this may cause the following problems due to clashing with the percent-encoding used with URIs.
◆ Microsoft Windows IPv6 stack uses numeric zone IDs: fe80::3%1
◆ BSD applications typically use the interface name as a zone ID: fe80::3%pcn0
◆ Linux applications also typically use the interface name as a zone ID: fe80::3%eth0, although Linux ifconfig as of version 1.42 (part of net-tools 1.60) does not display zone IDs.
Relatively few IPv6-capable applications understand zone ID syntax (with the notable exception of OpenSSH), rendering link-local addresses unusable within them if multiple interfaces use link-local addresses.

IPv6 packet
A packet is a formatted Glossary Link block of data carried by a computer network.
Figure 1 shows the structure of an IPv6 packet header.

 Figure 1 IPv6 packet header structure
Figure 1 IPv6 packet header structure

The IPv6 packet is composed of two main parts:
◆ Header
The header is in the first 40 octets (320 bits) of the packet and contains:
• Both source and destination addresses (128 bits each)
• Version (4-bit IP version)
• Traffic class (8 bits, Packet Priority)
• Flow label (20 bits, QoS management)
• Payload length in bytes (16 bits)
• Next header (8 bits)
• Hop limit (8 bits, time to live)
◆ Payload
The payload can be up to 64 KB in size in standard mode, or larger with a jumbo payload option (refer to “Jumbograms ”).
Fragmentation is handled only in the sending host in IPv6. Routers never fragment a packet, and hosts are expected to use PMTU (Path MTU) discovery.
The protocol field of IPv4 is replaced with a Next Header field. This field usually specifies the transport layer protocol used by a packet's payload. In the presence of options, however, the Next Header field specifies the presence of an Extra Options header, which then follows the IPv6 header. The payload's protocol itself is specified in a field of the Options header. This insertion of an extra header to carry options is analogous to the handling of AH and ESP (Encapsulating Security Payload) in IPsec for both IPv4 and IPv6.

Transition mechanisms
Until IPv6 completely supplants IPv4, which is not likely to happen in the near future, a number of so-called transition mechanisms are needed to enable IPv6-only hosts to reach IPv4 services and to allow isolated IPv6 hosts and networks to reach the IPv6 Internet over the IPv4 infrastructure. The following transition mechanisms are briefly discussed in this section.
◆ “Dual stack ,” next
◆ “Tunneling
◆ “Automatic tunneling
◆ “Configured tunneling
◆ “Proxying and translation

Dual stack

Since IPv6 is a conservative extension of IPv4, it is relatively easy to write a network stack that supports both IPv4 and IPv6 while sharing most of the code. Such an implementation is called a dual stack. A host implementing a dual stack is called a dual-stack host. This approach is described in RFC 4213.
Most current implementations of IPv6 use a dual stack. Some early experimental implementations used independent IPv4 and IPv6 stacks. There are no known implementations that implement IPv6 only.

Tunneling
In order to reach the IPv6 Internet, an isolated host or network must be able to use the existing IPv4 infrastructure to carry IPv6 packets. This is done using a technique somewhat misleadingly known as tunnelling that consists of encapsulating IPv6 packets within IPv4, in effect using IPv4 as a link layer for IPv6.
IPv6 packets can be directly encapsulated within IPv4 packets using protocol number 41. They can also be encapsulated within UDP packets, for example, in order to cross a router or NAT device that blocks protocol 41 traffic. They can also use generic encapsulation schemes, such as AYIYA (Anything In Anything) or GRE (Generic Routing Encapsulation).

Automatic tunneling

Automatic tunneling refers to a technique where the tunnel endpoints are automatically determined by the routing infrastructure. The recommended technique for automatic tunneling is 6to4 tunneling, which uses protocol 41 encapsulation. Tunnel endpoints are determined by using a well-known IPv4 anycast address on the remote side, and embedding IPv4 address information within IPv6 addresses on the local side. 6to4 tunneling is widely deployed today.
Another automatic tunneling mechanism is Intra-Site Automatic Tunnel Addressing Protocol (ISATAP). This protocol treats the IPv4 network as a virtual IPv6 local link, with mappings from each IPv4 address to a link-local IPv6 address. Teredo is an automatic tunneling technique that uses UDP encapsulation and is claimed to be able to cross multiple NAT boxes.
Teredo is not widely deployed today, but an experimental version of Teredo is installed with the Windows XP SP2 IPv6 stack.
Note: IPv6, 6to4, and Teredo are enabled by default in Windows Vista.

Configured tunneling
Configured tunneling is a technique where the tunnel endpoints are configured explicitly, either by a human operator or by an automatic service known as a Tunnel Broker. Configured tunneling is usually more deterministic and easier to debug than automatic tunneling, and is therefore recommended for large, well-administered networks. Configured tunneling typically uses either protocol 41 (recommended) or raw UDP encapsulation.

Proxying and translation
When an IPv6-only host needs to access an IPv4-only service (for example, a web server), some form of translation is necessary. The one form of translation that actually works is the use of a dual-stack application-layer proxy (for example, a web proxy).
Techniques for application-agnostic translation at the lower layers have also been proposed, but they have been found to be too unreliable due to the wide range of functionality required by common application-layer protocols. As such, they are commonly considered to be obsolete.

TCP terminology
This section provides information for TCP terminology.

Acknowledgements (ACKs)
The TCP acknowledgement scheme is cumulative as it acknowledges all the data received up until the time the ACK was generated. As TCP segments are not of uniform size and a TCP sender may retransmit more data than what was in a missing segment, ACKs do not acknowledge the received segment, rather they mark the position of the acknowledged data in the stream. The policy of cumulative acknowledgement makes the generation of ACKs easy and any loss of ACKs do not force the sender to retransmit data. The disadvantage is the sender does not receive any detailed information about the data received except the position in the stream of the last byte that has been received.

Delayed ACKs
Delayed ACKs allow a TCP receiver to refrain from sending an ACK for each incoming segment. However, a receiver should send an ACK for every second full-sized segment that arrives. Furthermore, the standard mandates a receiver must not withhold an ACK for more than 500 ms. The receivers should not delay ACKs that acknowledge out-of-order segments.

Maximum segment size (MSS)
The maximum segment size (MSS) is the maximum amount of data, specified in bytes, that can transmitted in a segment between the two TCP endpoints. The MSS is decided by the endpoints, as they need to agree on the maximum segment they can handle. Deciding on a good MSS is important in a general inter-networking environment because this decision greatly affects performance. It is difficult to choose a good MSS value since a very small MSS means an underutilized network, whereas a very large MSS means large IP datagrams that may lead to IP fragmentation, greatly hampering the performance.
An ideal MSS size would be when the IP datagrams are as large as possible without any fragmentation anywhere along the path from the source to the destination. When TCP sends a segment with the SYN bit set during connection establishment, it can send an optional MSS value up to the outgoing interface’s MTU minus the size of the fixed TCP and IP headers. For example, if the MTU is 1500 (Ethernet standard), the sender can advertise a MSS of 1460 (1500 minus 40).

Maximum transmission unit (MTU)
Each network interface has its own MTU that defines the largest packet that it can transmit. The MTU of the media determines the maximum size of the packets that can be transmitted without IP fragmentation.

Retransmission
A TCP sender starts a timer when it sends a segment and expects an acknowledgement for the data it sent. If the sender does not receive an acknowledgement for the data before the timer expires, it assumes that the data was lost or corrupted and retransmits the segment. Since the time required for the data to reach the receiver and the acknowledgement to reach the sender is not constant (because of the varying Internet delays), an adaptive retransmission algorithm is used to monitor performance of each connection and conclude a reasonable value for timeout based on the round trip time.

Selective Acknowledgement (SACK)
TCP may experience poor performance when multiple packets are lost from one window of data. With the limited information available from cumulative acknowledgements, a TCP sender can only learn about a single lost packet per round trip time. An aggressive sender could choose to retransmit packets early, but such retransmitted segments may have already been successfully received. The Selective Acknowledgement (SACK) mechanism, combined with a selective repeat retransmission policy, helps to overcome these limitations. The receiving TCP sends back SACK packets to the sender confirming receipt of data and specifies the holes in the data that has been received. The sender can then retransmit only the missing data segments. The selective acknowledgment extension uses two TCP options. The first is an enabling option, SACKpermitted, which may be sent in a SYN segment to indicate that the SACK option can be used once the connection is established. The other is the SACK option itself, which may be sent over an established connection once permission has been given by SACKpermitted.

TCP segment

The TCP segments are units of transfer for TCP and used to establish a connection, transfer data, send ACKs, advertise window size and close a connection. Each segment is divided into three parts:
◆ Fixed header of 20 bytes
◆ Optional variable length header, padded out to a multiple of 4 bytes
◆ Data
The maximum possible header size is 60 bytes. The TCP header carries the control information. SOURCE PORT and DESTINATION PORT contain TCP port numbers that identify the application programs at the endpoints. The SEQUENCE NUMBER field identifies the position in the sender’s byte stream of the first byte of attached data, if any, and the ACKNOWLEDGEMENT NUMBER field identifies the number of the byte the source expects to receive next. The ACKNOWLEDGEMENT NUMBER field is valid only if the ACK bit in the CODE BITS field is set. The 6-bit CODE BITS field is used to determine the purpose and contents of the segment. The HLEN field specifies the total length of the fixed plus variable headers of the segment as a number of 32-bit words. TCP software advertises how much data it is willing to receive by specifying its buffer size in the WINDOW field. The CHECKSUM field contains a 16-bit integer checksum used to verify the integrity of the data as well as the TCP header and the header options. The TCP header padding is used to ensure that the TCP header ends and data begins on a 32-bit boundary. The padding is composed of zeros.

TCP window
A TCP window is the amount of data a sender can send without waiting for an ACK from the receiver. The TCP window is a flow control mechanism and ensures that no congestion occurs in the network. For example, if a pair of hosts are talking over a TCP connection that has a TCP window size of 64 KB, the sender can only send 64 KB of data and it must stop and wait for an acknowledgement from the receiver that some or all of the data has been received. If the receiver acknowledges that all the data has been received. The sender is free to send another 64 KB. If the sender gets back an acknowledgement from the receiver that it received the first 32 KB (which is likely if the second 32 KB was still in transit or it is lost), then the sender could only send another 32 KB since it cannot have more than 64 KB of unacknowledged data outstanding (the second 32 KB of data plus the third).
The primary reason for the window is congestion control. The whole network connection, which consists of the hosts at both ends, the routers in between, and the actual connections themselves, might have a bottleneck somewhere that can only handle so much data so fast. The TCP window throttles the transmission speed down to a level where congestion and data loss do not occur.
The factors affecting the window size are as follows:

Receiver’s advertised window
The time taken by the receiver to process the received data and send ACKs may be greater than the sender’s processing time, so it is necessary to control the transmission rate of the sender to prevent it from sending more data than the receiver can handle, thus causing packet loss. TCP introduces flow control by declaring a receive window in each segment header.

Sender’s congestion window

The congestion window controls the number of packets a TCP flow has in the network at any time. The congestion window is set using an Additive-Increase, Multiplicative-Decrease (AIMD) mechanism that probes for available bandwidth, dynamically adapting to changing network conditions.

Usable window
This is the minimum of the receiver’s advertised window and the sender’s congestion window. It is the actual amount of data the sender is able to transmit. The TCP header uses a 16 bit field to report the receive window size to the sender. Therefore, the largest window that can be used is 2**16 = 65K bytes.

Window scaling
The ordinary TCP header allocates only 16 bits for window advertisement. This limits the maximum window that can be advertised to 64 KB, limiting the throughput. RFC 1323 provides the window scaling option, to be able to advertise windows greater than 64 KB. Both the endpoints must agree to use window scaling during connection establishment.
The window scale extension expands the definition of the TCP window to 32 bits and then uses a scale factor to carry this 32- bit value in the 16-bit Window field of the TCP header (SEG.WND in RFC-793). The scale factor is carried in a new TCP option — Window Scale. This option is sent only in a SYN segment (a segment with the SYN bit on), hence the window scale is fixed in each direction when a connection is opened.

TCP error recovery
In TCP, each source determines how much capacity is available in the network so it knows how many packets it can safely have in transit. Once a given source has this many packets in transit, it uses the arrival of an ACK as a signal that some of its packets have left the network and it is therefore safe to insert new packets into the network without adding to the level of congestion. TCP uses congestion control algorithms to determine the network capacity. From the congestion control point of view, a TCP connection is in one of the following states.
Slow start: After a connection is established and after a loss is detected by a timeout or by duplicate ACKs.
Fast recovery: After a loss is detected by fast retransmit.
Congestion avoidance: In all other cases. Congestion avoidance and slow start work hand-in-hand. The congestion avoidance algorithm assumes that the chance of a packet being lost due to damage is very small. Therefore, the loss of a packet means there is congestion somewhere in the network between the source and destination. Occurrence of a timeout and the receipt of duplicate ACKs indicates packet loss.
When congestion is detected in the network it is necessary to slow things down, so the slow start algorithm is invoked. Two parameters, the congestion window (cwnd) and a slow start threshold (ssthresh), are maintained for each connection. When a connection is established, both of these parameters are initialized. The cwnd is initialized to one MSS. The ssthresh is used to determine whether the slow start or congestion avoidance algorithm is to be used to control data transmission. The initial value of ssthresh may be arbitrarily high (usually ssthresh is initialized to 65535 bytes), but it may be reduced in response to congestion.
The slow start algorithm is used when cwnd is less than ssthresh, while the congestion avoidance algorithm is used when cwnd is greater than ssthresh. When cwnd and ssthresh are equal, the sender may use either slow start or congestion avoidance.
TCP never transmits more than the minimum of cwnd and the receiver’s advertised window. When a connection is established, or if congestion is detected in the network, TCP is in slow start and the congestion window is initialized to one MSS. Each time an ACK is received, the congestion window is increased by one MSS. The sender starts by transmitting one segment and waiting for its ACK. When that ACK is received, the congestion window is incremented from one to two, and two segments can be sent. When each of those two segments is acknowledged, the congestion window is increased to four, and so on. The window size increases exponentially during slow start as shown in Figure 2. When a time-out occurs or a duplicate ACK is received, ssthresh is reset to one half of the current window (that is, the minimum of cwnd and the receiver's advertised window). If the congestion was detected by an occurrence of a timeout the cwnd is set to one MSS. When an ACK is received for data transmitted the cwnd is increased, but the way it is increased depends on whether TCP is performing slow start or congestion avoidance. If the cwnd is less than or equal to the ssthresh, TCP is in slow start and slow start continues until TCP is halfway to where it was when congestion occurred, then congestion avoidance takes over. Congestion avoidance increments the cwnd by MSS squared divided by cwnd (in bytes) each time an ACK is received, increasing the cwnd linearly as shown in Figure 2. This provides a close approximation to increasing cwnd by, at most, one MSS per RTT.

 Figure 2 Slow start and congestion avoidance
Figure 2 Slow start and congestion avoidance

A TCP receiver generates ACKs on receipt of data segments. The ACK contains the highest contiguous sequence number the receiver expects to receive next. This informs the sender of the in-order data that was received by the receiver. When the receiver receives a segment with a sequence number greater than the sequence number it expected to receive, it detects the out-of-order segment and generates an immediate ACK with the last sequence number it has received in-order (that is, a duplicate ACK). This duplicate ACK is not delayed. Since the sender does not know if this duplicate ACK is a result of a lost packet or an out-of-order delivery, it waits for a small number of duplicate ACKs, assuming that if the packets are only reordered there will be only one or two duplicate ACKs before the reordered segment is received and processed and a new ACK is generated. If three or more duplicate ACKs are received in a row, it implies there has been a packet loss. At that point, the TCP sender retransmits this segment without waiting for the retransmission timer to expire. This is known as fast retransmit (Figure 3).
After fast retransmit has sent the supposedly missing segment, the congestion avoidance algorithm is invoked instead of the slow start; this is called fast recovery. Receipt of a duplicate ACK implies that not only is a packet lost, but that there is data still flowing between the two ends of TCP, as the receiver will only generate a duplicate ACK on receipt of another segment. Hence, fast recovery allows high throughput under moderate congestion.
 
Figure 3 Fast retransmit
Figure 3 Fast retransmit

Network congestion

A network link is said to be congested if contention for it causes queues to build up and packets start getting dropped. The TCP protocol detects these dropped packets and starts retransmitting them, but using aggressive retransmissions to compensate for packet loss tends to keep systems in a state of network congestion even after the initial load has been reduced to a level which would not normally have induced network congestion. In this situation, demand for link bandwidth (and eventually queue space), outstrips what is available. When congestion occurs, all the flows that detect it must reduce their transmission rate. If they do not do so, the network will remain in an unstable state with queues continuing to build up.

Internet Protocol security (IPsec)
Internet Protocol security (IPsec) is a set of protocols developed by the IETF to support secure exchange of packets in the IP layer. IP Security has been deployed widely to implement Virtual Private Networks (VPNs).
IP security supports two encryption modes:
◆ Transport
◆ Tunnel
Transport mode encrypts only the payload of each packet, but leaves the header untouched. The more secure Tunnel mode encrypts both the header and the payload.
On the receiving side, an IP Security compliant device decrypts each packet. For IP security to work, the sending and receiving devices must share a public key. This is accomplished through a protocol known as Internet Security Association and Key Management Protocol/Oakley (ISAKMP/Oakley), which allows the receiver to obtain a public key and authenticate the sender using digital certificates.

Tunneling and IPsec
Internet Protocol security (IPsec) uses cryptographic security to ensure private, secure communications over Internet Protocol networks. IPsec supports network-level data integrity, data confidentiality, data origin authentication and replay protection. It helps secure your SAN against network-based attacks from untrusted computers, attacks that can result in the denial-of-service of applications, services, or the network, data corruption, and data and user credential theft.
By default, when creating an FCIP tunnel, IPsec is disabled. FCIP tunneling with IPsec enabled will support maximum throughput as follows:
◆ Unidirectional: approximately 104 MB/sec
◆ Bidirectional: approximately 90 MB/sec
Used to provide greater security in tunneling on an FR4-18i blade or a Brocade SilkWorm 7500 switch, the IPsec feature does not require you to configure separate security for each application that uses TCP/IP.
When configuring for IPsec, however, you must ensure that there is an FR4-18i blade or a Brocade SilkWorm 7500 switch in each end of the FCIP tunnel. IPsec works on FCIP tunnels with or without IP compression (IPComp).
IPsec requires an IPsec license in addition to the FCIP license.

IPsec terminology:

AES
Advanced Encryption Standard. FIPS 197 endorses the Rijndael encryption algorithm as the approved AES for use by US government organizations and others to protect sensitive information. It replaces DES as the encryption standard.

AES-XCBC
Cipher Block Chaining. A key-dependent one-way hash function (MAC) used with AES in conjunction with the Cipher-Block-Chaining mode of operation, suitable for securing messages of varying lengths, such as IP datagrams.

AH
Authentication Header. Like ESP, AH provides data integrity, data source authentication, and protection against replay attacks but does not provide confidentiality.

DES
Data Encryption Standard is the older encryption algorithm that uses a 56-bit key to encrypt blocks of 64-bit plain text. Because of the relatively shorter key length, it is not a secured algorithm and no longer approved for Federal use.

3DES
Triple DES is a more secure variant of DES. It uses three different 56-bit keys to encrypt blocks of 64-bit plain text. The algorithm is FIPS-approved for use by Federal agencies.

ESP
Encapsulating Security Payload is the IPsec protocol that provides confidentiality, data integrity, and data source authentication of IP packets, as well as protection against replay attacks.

MD5
Message Digest 5, like SHA-1, is a popular one-way hash function used for authentication and data integrity.

SHA
Secure Hash Algorithm, like MD5, is a popular one-way hash function used for authentication and data integrity.

MAC
Message Authentication Code is a key-dependent, one-way hash function used for generating and verifying authentication data.

HMAC
A stronger MAC because it is a keyed hash inside a keyed hash. SA Security association is the collection of security parameters and authenticated keys that are negotiated between IPsec peers.

Данные передаются, после установления соединения между конечными точками. Поток передаваемых данных, состоит из восьмибитной последовательности, каждый бит из которой несет свое значение. В данной главе будут рассмотрены следующие темы:
◆ “IPv6
◆ “Терминология TCP
◆ “Восстановление ошибок в TCP
◆ “Перегрузка сети
◆ “Безопасный интернет протокол (IPsec)

IPv6
Интернет протокол версии 6 (IPv6), является протоколом передачи данных, предназначенный для работы в сетях с коммутаторами, пришедший на замену IPv4.  
Основным преимуществом  IPv6, является расширение адресного пространства подключаемых устройств. В отличие от 32-х битного IPv4,  IPv6, является 128 битным.
Расширение адресного пространства, упрощает передачу данных, например, не требует динамического роутинга, а также упрощает работу коммутаторов. Он также обходит ограничения IPv4, при работе с Classless Inter-Domain Routing (CIDR). Упрощенный формат заголовка пакета упрощает пересылку пакетов и роутинг. Более подробно об этом ознакомиться, можно в разделах “Расширенное адресное пространство ” и “Адресация ”.
В разделе будут рассмотрены:
◆ “Особенности IPv6
◆ “Состояние внедрения
◆ “Адресация
◆ “Пакет IPv6
◆ “Механизмы преобразования


Особенности IPv6
Большинство транспортных уровней и уровней приложений, протокола IPv6, требуют небольших изменений (или вообще не требуют), для работы с IPv6. За исключением некоторых сетевых протоколов, которые используют адресацию сети (таких, как FTP и NTPv3).
Обычно, приложения требуют небольших изменений, для работы через IPv6. В данном разделе, будут рассмотрены следующие особенности протокола:
◆ “Расширенное адресное пространство
◆ “Автоконфигурация узлов
◆ “Многоадресный пакет
◆ “Большие пакеты
◆ “Безопасность сетевого уровня

Расширенное адресное пространство
Основной особенностью IPv6, является расширенное адресное пространство, 128 бит, к примеру, IPv4 имеет адресное пространство длинной в 32 бита. Использование расширенного адресного пространства, решает проблемы с исчерпанием адресного пространства IPv4, и как следствие, не требует использования транслирования сетевых адресов (NAT) и различных маршрутизирующих устройств.
В некоторых случаях, NAT может быть нужен, но нет острой необходимости для функционирования IPv6.
Это упрощает администрирование больших и средних сетей, исключая необходимость использования множества подсетей. Подсети будут использоваться для разбиения сетей на логические сегменты, с целью контроля доступа и маршрутизации.
Есть несколько проблем, связанных с большим адресным пространством. К примеру, на участках сетей, где пропускная способность ограничена, IPv6 будет использовать больше ресурсов, чем IPv4. Для решения данной проблемы, может быть использована компрессия заголовка пакета. Адреса IPv6, требуют больше памяти, чем адреса IPv4 и имена Domain Name System (DNS). Протокол DNS, также был изменен для поддержки IPv6.
Дополнительная информация в разделе “Адресация

Автоконфигурация узлов
Узлы, работающие с IPv6, могут автоматически настраиваться при подключении к маршрутизатору  IPv6. Когда узел подключается в сеть, он отправляет многоадресный пакет с запросом конфигурационных параметров. Если маршрутизатор настроен на прием таких пакетов, он отправляет пригласительный пакет, содержащий конфигурационные параметры сети IPv6.
Если  IPv6 автоконфигурация не настроена, узел может использовать автоконфигурацию сети (DHCPv6), или быть настроен в ручную.
Автоконфигурация может быть настроена не только на узлах, маршрутизаторы и другие устройства, могут использовать автоматическую настройку параметров сети.

Многоадресный пакет
В большинстве случаев, сетевая инфраструктура не настроена для роутинга многоадресных пакетов. По этому, многоадресный пакет, получат устройства одной подсети, и он не перейдет в другую подсеть. Многоадресные пакеты IPv6 (FF02::1), не содержат подсеть, которая ограничивала бы их прием.

Большие пакеты
IPv6 может опционально поддерживать передачу пакетов, большей длинны, чем IPv4 (64 KB).  Коммутаторы, также должны поддерживать данный режим. Размер пакетов, поддерживаемых для передачи через IPv6, ограничен размером в 4 GB. Использование больших пакетов, может увеличить производительность сети, через большие MTU (Maximum Transmission Unit).

Безопасность сетевого уровня
IPsec (IP security), предназначен для шифрования и аутентификации на сетевом уровне IP и входит в базовый функционал IPv6. В IPv4, это опциональная честь. IPsec используется для шифрования трафика между маршрутизаторами IPv6 Border Gateway Protocol (BGP) (основной протокол маршрутизации в Internet).

Состояние внедрения
Начиная с декабря 2005, адреса IPv6 занимают доли процентов адресов в Internet, основная часть адресов, используется IPv4. Большинство функционала IPv6 были перенесены на IPv4, за исключением автоконфигурирования, более гибкой адресации и Secure Neighbor Discovery (SEND).
Предполагается, что IPv4 исчерпает свое адресное пространство в промежутке времени с 2011 (из отчета специалистов Cisco Systems за 2005 г) по 2023 (по прогнозу Paul Wilson директора APNIC).
Чтобы подготовиться к неизбежному, ряд государств стали активно внедрять поддержку IPv6. Например, правительство США дало ряд указаний по переводу внутренних сетей федеральных агентств на IPv6 в 2008, а также купило 247 биллионов адресов IPv6. Китай имеет 5-ти летний план по переходу на IPv6, он называется “China Next Generation Internet”.



Адресация
В этом разделе будут расмотренны следующие темы:
◆ “128 битная адресация
◆ “Обозначения
◆ “Буквенные IPv6 адреса в URL
◆ “Обозначение сетей
◆ “Типы адресов IPv6
◆ “Специальные адреса
◆ “Индексы зон

128 битная адресация
Основным изменением в IPv6, по сравнению с IPv4, как говорилось “Расширенное адресное пространство ”, является расширенное адресное пространство. Адреса в IPv6, имеют длину в 128 (как определено в RFC 4291), в отличие от адресов IPv4 в 32 бита.
Арес IPv6, обычно состоит из двух логических частей: 64 битной маски сети и 64-х битного префикса узла, который автоматически генерируется на основе MAC (Media Access Control) адреса интерфейса, либо назначается вручную. Зная MAC адрес, можно отслеживать сетевое оборудование и пользователя по изменению адреса IPv6. Для обеспечения анонимности, присущей в сетях IPv4, разработано правило RFC 3041, которое препятствует отслеживанию пользователя в IPv6 сетях, при помощи адреса. RFC 3041 определяет механизм, по которому, время от времени, в произвольном порядке меняется часть MAC адреса.

Обозначения
Адреса IPv6 обычно пишутся, как восемь групп по четыре шестнадцатеричных числа. Для примера, рассмотрим следующий адрес IPv6:
2001:0db8:85a3:08d3:1319:8a2e:0370:7334
Одну, или более группу из четырех цифр 0000, содержащих нулевые значения, можно заменить двумя двоеточиями (::). К примеру, 2001:0db8:0000:0000:0000:0000:1428:57ab можно сократить до 2001:0db8::1428:57ab. Следуя правилу, любой адрес, содержащий группу 0000, можно сократить двумя двоеточиями, т.к. всего одна такая последовательность может присутствовать в адресе. Ведущие нули в адресе, также могут быть пропущены (::1 обозначение для localhost). Например, вот список адресов, которые эквиваленты:
2001:0db8:0000:0000:0000:0000:1428:57ab
2001:0db8:0000:0000:0000::1428:57ab
2001:0db8:0:0:0:0:1428:57ab
2001:0db8:0:0::1428:57ab
2001:0db8::1428:57ab
2001:db8::1428:57ab

Адрес, который имеет более одной последовательности, содержащей четыре нуля в разных частях, считается неправильным, т.к. он будет иметь неоднозначную трактовку. Последовательность из 4-х бит, в конце адреса IPv6, может быть записана в десятеричной системе, с использованием, в качестве разделителей точки. Это обозначение, обычно используется для совместимости адресов. Для примера, эти адреса одинаковы:
::ffff:1.2.3.4
::ffff:0102:0304 и 0:0:0:0:0:ffff:0102:0304.
Дополнительную информацию можно найти в RFC 4291 — IP Version 6 Addressing Architecture.

Буквенные IPv6 адреса в URL
Ареса IPv6 в URL, обозначаются в квадратных скобках. К примеру:
http://[2001:0db8:85a3:08d3:1319:8a2e:0370:7344]/
Также можно указывать номер порта в строке адреса:
https://[2001:0db8:85a3:08d3:1319:8a2e:0370:7344]:443/
Дополнительную информацию можно найти в "RFC 2732 — Format for Literal IPv6 Addresses in URLs", а также "RFC 3986 — Uniform Resource Identifier (URI): Generic Syntax."

Обозначение сетей
Запись сетевых обозначений, строится при помощи IPv6 CIDR (Classless Inter-Domain Routing).
Сеть, либо подсеть IPv6, содержит группу адресов IPv6, размер сегмента, должен быть кратен двум. Первый бит адреса, является основным для всех узлов сети, и называется префиксом сети. Сеть обозначается первым адресом в сети и количеством бит в префиксе (в десятеричной системе счисления), от адреса отделяется слэшом. Пример:
2001:0db8:1234::/48
Данный адрес принадлежит сетям с адресами:
от 2001:0db8:1234:0000:0000:0000:0000:0000 до 2001:0db8:1234:FFFF:FFFF:FFFF:FFFF:FFFF
Если узел должен быть виден в сетях с 128 битным префиксом, то его адрес будет указан с префиксом /128.

Типы адресов IPv6
Адреса IPv6, разделяют на следующие категории:
Unicast Addresses — Указывает на конкретный адрес в сети. Пакет отправляется, строго по адресу и приходит получателю.
Multicast Addresses — Используется для обозначения набора адресов узлов получателей. Если пакет многоадресный, протокол доставляет пакет всем адресам, соответствующим маске получателей. Многоадресный пакет, начинается с префикса FF00::/8. Вторые восемь цифр в поле адреса, указывает диапазон значений адресов получателей. Часто используются диапазоны: link-local (2), site-local (5) и global (E).
Anycast Addresses — Также предназначается более чем одному сетевому интерфейсу. Такой пакет доставляется только до первого получателя, обычно ближайшего. Такой адрес не просто выявить. Такие пакеты имеют структуру обычного unicast адреса, различие, лишь в том, что в нем указывается путь маршрутизации пакета.

Специальные адреса
There are a number of addresses with special meaning in IPv6:
◆ ::/128 — Адрес, состоящий из всех нулей, является неопределенным и может быть использован, только в софте.
◆ ::1/128 — Адрес возврата (localhost). Если приложение на узле, отправляет пакет на данный адрес, стэк IPv6, вернет данный пакет обратно узелу-отправителю. (соответсвует адресу 127.0.0.1 в IPv4).
◆ ::/96 — Данный префикс использовался, для IPv4 совместимых адресов, на данный момент, устарел.
◆ ::ffff:0:0/96 — Данный префикс, используется для задания соответствия с адресом IPv4 (см. “Механизмы передачи”).
◆ 2001:db8::/32 — Данный префикс используется в документации (RFC 3849). Адреса с таким префиксом могут быть использованы, где угодно.
◆ 2002::/16 — Данный префикс используется для адресации IPv4 и IPv6.
◆ fc00::/7 — Unique Local Addresses (ULA) маршрутизируется только между набором сайтов. Определен в RFC 4193 в замещение адресации локальных адресов. Данные адреса, включают в себя псевдослучайный 40 битный номер, который минимизирует риски, связанные с конфликтами адресов, при объединении сетей. Данное адресное пространство разделяют на две части:
• fc00::/8 — ULA Central, в настоящее время не.
• fd00::/8 — ULA, как генератор точки RFC 4193, официально не зарезервирован.
◆ fe80::/64 — Данный префикс используется, только для локальных физических соединений. Это аналог Автоконфигурируемому адресу 169.254.0.0/16 в IPv4.
◆ fec0::/10 — Префикс, используемый, для определения локальной сети.
Использование данного префикса не рекомендуется RFC 3879 с Сентября 2004, и системы не должны поддерживать данный вид адресации.
◆ ff00::/8 — Многоадресный префикс, используется для обозначения множества адресов, как определено в "IP Version 6 Addressing Architecture" (RFC 4291).
Для broadcast сигналов, нет ограничения в адресации IPv6. Приложения часто используют многоадресные пакеты для рассылки по группе узлов. Организация IANA ведет официальный лист адресного пространства IPv6. Глобальные адреса, могут, быть найдены в различных RIR, или на страницах (Ghost Route Hunter) DFP.

Индексы зон
Локальные адреса, представляют потенциальную проблему для систем с большим количеством сетевых интерфейсов. Каждый интерфейс, может быть подключен к различным сетям, и эти адреса могут появиться в одной подсети и это вызовет проблемы с таблицами маршрутизации.
К примеру, узел A имеет два интерфейса, которые автоматически получили адреса локальной сети (fe80::1/64 и fe80::2/64), только один из интерфейсов подключен в одну физическую сеть с узлом B, который имеет адрес fe80::3/64. Если узел A попытается передать данные на адрес fe80::3, как он узнает, через какой интерфейс их отправлять (fe80::1 или fe80::2)?
Решение данной проблемы определено в RFC 4007, как уникальный индекс зоны для локального интерфейса, и представляется в текстовом виде в форме <адрес>%<индекс зоны>. Пример:
http://[fe80::1122:33ff:fe11:2233%eth0]:80/
Однако, такое представление, может вызвать проблемы с кодировкой адресов, используемых в URI.
◆ Стэк IPv6 в Microsoft Windows, использует метрику зон: fe80::3%1
◆ Приложения в BSD, обычно используют имена интерфейсов в качестве идентификатора зон: fe80::3%pcn0
◆ Приложения под Linux, также  applications обычно используют имена интерфейсов в качестве идентификатора зон: fe80::3%eth0. Хотя Linux ifconfig version 1.42 (часть пакета net-tools 1.60) не показывает идентификатора зон.
Относительно не многие приложения, работающие через IPv6, воспринимают идентификаторы зон (за исключением OpenSSH), Использование локальных адресов сети на нескольких интерфейсах, обычно не приносит желаемой пользы.



Пакет IPv6
Пакет представляет собой сформированный блок данных, передаваемых по сети.
Рисунок 1 показывает структуру заголовка пакета IPv6.

 Активное изображение
Рисунок 1 Структура заголовка пакета IPv6

Пакет IPv6 состоит из двух основных частей:
◆ Заголовок
Заголовок представляет собой 40 байт (320 бит), он содержит:
• Адрес отправителя и получателя (128 бит каждый)
• Версию (4 бита версия IP)
• Класс трафика (8 бит, приоритет пакета)
• Метку потока (20 бит, управление QoS)
• Длину сегмента переносимых данных в байтах (16 бит)
• Следующий заголовок (8 бит)
• Максимальное количество переходов по сети (8 бит, время жизни пакета)

◆ Переносимые данные
Рабочая нагрузка пакета может быть до 64 Кб, в стандартном режиме, либо больше (описание содержится в “Большие пакеты”)
Данные разбиваются на фрагменты во время отправки пакета. Маршрутизаторы никогда не дробят пакет на части, узел-получатель, самостоятельно определяет PMTU (Path MTU).
Поле протокола IPv4, заменяется на поле Next Header. Это поле, обычно указывает на транспортный уровень протокола для передачи данных. Если присутствуют опции, поле Next Header содержит дополнительный заголовок Extra Options, который следует, сразу за заголовком пакета IPv6. Рабочая нагрузка самого протокола, указывается в заголовке  Options. Добавление дополнительного заголовка, содержащего опции, аналогично технологиям AH и ESP (Encapsulating Security Payload) в IPsec, для IPv4 и IPv6.



Механизмы передачи
До тех пор, пока IPv6 полностью не вытеснил IPv4, чего не ожидается в ближайшем будущем, механизмы передачи требуются для узлов, которые работают только с IPv6, передавать данные через сети IPv4. В данном разделе будут описаны следующие механизмы передачи:
◆ “Двойной стэк
◆ “Туннелирование
◆ “Автоматическое туннелирование
◆ “Настроенное туннелирование
◆ “Проксирование и преобразования

Двойной стэк
Т.к. IPv6, является расширением протокола IPv4, достаточно просто формируется сетевой стэк, который поддерживает IPv4 и IPv6, разделяя часть кода. Такая технология, называется двойным стэком. Данная технология описана в RFC 4213.
Большинство текущих реализаций протокола IPv6, используют технологию двойного стэка. Негода ранее, в экспериментальных целях, реализовывали независимые стэки IPv4 и IPv6. Стэк IPv6 в одиночку, никогда не реализовывался в сетях.

Туннелирование
Для подключения узлов, работающих через IPv6 в Internet, узлы должны уметь использовать существующие сети IPv4, для передачи пакетов IPv6. Такую возможность обеспечивает технология туннелирования, которая инкапсулирует пакета IPv6 в IPv4.
Пакеты IPv6, могут напрямую инкапсулироваться в пакеты IPv4, при использовании протокола номер 41. Также, они могут инкапсулироваться в пакеты UDP, например для того, чтобы проходить, через NAT, который может блокировать протокол 41. Также поддерживаются схемы инкапсуляции, такие, как AYIYA (Anything In Anything), либо GRE (Generic Routing Encapsulation).

Автоматическое туннелирование
Автоматическое туннелирование, относится к технологии, по которой конечные точки автоматически определяются маршрутизацией. Для автоматического туннелирования, рекомендуется использовать технологию 6to4, которая базируется на протоколе 41.
Существует и другой механизм автоматического туннелирования: Intra-Site Automatic Tunnel Addressing Protocol (ISATAP). Данный протокол создает в сети IPv4 виртуальное локальное соединение IPv6, которое переадресует адреса IPv4 в IPv6.
Teredo это технология автоматического туннелирования, которая использует инкапсуляцию UDP, и используется для туннелирования IPv6, между многими NAT устройствами.
Технология Teredo, не широко распространена в настоящее время, экспериментальная версия Teredo, включена в стек IPv6 в Windows XP SP2.
IPv6, 6to4, и Teredo «по умолчанию» включены в Windows Vista.

Настроенное туннелирование
Настроенное туннелирование, это технология, по которой конечные точки туннелируются прозрачно. Оно может быть настроено вручную, либо при помощи автоматического сервиса Tunnel Broker. В настроенном туннелировании проще выявить проблемы, чем в автоматическом туннелировании, его рекомендуется использовать при построении больших сетей, для обеспечения простоты администрирования. Настроенное туннелирование обычно использует протокол 41, либо сырую инкапсуляцию UDP.

Проксирование и преобразования
Если узлу, работающему только по IPv6, нужно обратиться к сервису IPv4 (к примеру, web серверу), необходимо произвести преобразования протокола. Одной из форм такого преобразования, может служить использование двойного стэка на уровне приложения прокси сервера (например, web прокси).
В одно время были предложены технологии аппаратного преобразования протокола на более низком уровне, однако они не смогли обеспечить широкой функциональности, которая требовалась основным протоколам приложений. В основном такие технологии считаются устаревшими.



Терминология TCP
В данном разделе представлена информация по терминологии TCP.

Уведомления о получении (ACK)
Схема подтверждений в TCP, представляет собой совокупность подтверждений получения всех данных, перед генерацией ACK. Т.к. пакеты в TCP могут иметь разную длину, и отправитель может повторно отправить больше данных, чем в потерянном сегменте,  получатель, отправляя пакет ACK, может не подтвердить получение сегмента, пометив его позицию в потоке данных. Политика накопления подтверждений, делает генерацию ACK проще и потеря одного ACK, не заставляет отправителя повторно отправлять данные.  Недостатком является тот факт, что отправитель не получает точной информации о переданных данных, за исключением позиции последнего байта в потоке, который был получен.

Задержанные ACK
Задержка в передаче ACK, позволяет узлу получателю TCP не отправлять ACK с каждым полученным сегментом данных. ACK, отправляется каждый раз, когда получатель получает полный сегмент данных. Получатель, не должен задерживать отправку ACK, более чем на 500 миллисекунд. Также, получатель не должен задерживать отправку пакетов ACK, содержащих информацию о битых сегментах.

Максимальный размер сегмента (MSS)
Максимальный размер сегмента (MSS), является максимальным объемом данных, указанным в байтах, который может быть передан сегментом, между конечными точками через TCP. Размер MSS выбирается самими конечными точками сети, чтобы определить максимальный размер сегмента, который они в состоянии передать. От выбора правильного размера MSS, зависит скорость передачи данных. Маленький размер MSS, вызывает низкую загрузку сети, в тоже время, большой MSS, вызывает фрагментацию IP и затрудняет передачу данных.
Идеальным размером MSS, будет максимальный объем данных, который может быть передан, между отправителем и получателем, без фрагментации сегмента. Размер MSS, выбирается во время отправки пакета с битом SYN, во время осуществления соединения. Такой пакет, содержит значение MSS, оно вычисляется из MTU, передающего интерфейса, минус размер заголовков TCP и IP. Например, если MTU равен 1500 (стандартное значение для Ethernet), отправитель выберет значение MSS в 1460 (1500 минус 40).

Максимальный размер передаваемого блока (MTU)
Каждый сетевой интерфейс имеет собственное значение MTU, которое определяет размер максимального пакета, который он может передать. MTU в сетях, определяет максимальный размер пакета, который может быть предан без фрагментации IP.

Повторная передача
Узел, который передает данные в сетях TCP, отсчитывает время, с момента отправки сегмента, до получения подтверждения о получении. Если он не получает подтверждения о получении отправленных данных, за определенный период времени, он считает, что данные были потеряны во время передачи и повторно отправляет сегмент. Т.к. время, требуемое для доставки сегмента до получателя и получения подтверждения, в сетях не постоянное (могут существовать различные задержки в сетях Internet), используется адаптивный алгоритм повторной передачи данных, который следит за производительностью каждого соединения и выбирает оптимальное время повторной передачи сегмента, основываясь на среднем времени прохождения данных.

Выборочное подтверждение получения данных (SACK)
TCP может отслеживать низкую производительность сети, если теряется большое количество пакетов из сегмента. Т.к. мало информации доступно из накопленных подтверждений о передаче, отправитель TCP, может знать о единичных потерях пакетов за период времени. Отправитель, может повторно передать сегмент данных, не дожидаясь подтверждения о получении, но эти данные уже могли успешно быть доставлены. Механизм выборочного подтверждения получения данных, совмещен с политикой повторной передачи выборочных пакетов. Получатель TCP, отправляет отправителю пакет SACK, для подтверждения получения данных и указывая в нем пропущенные участки в полученных данных. В таком случае, отправитель, повторно перешлет только пропущенные сегменты данных. SACK использует две опции TCP. Первая опция активации, SACKpermitted, которая может быть отправлена в пакете SYN, и означает, что опция SACK, может быть использована, когда будет установлено соединение. Другая опция, активирует SACK отправителя, и может быть отправлена в пакете, через установившееся соединение.

Сегмент TCP
Сегментами TCP, являются пакеты, передаваемые через TCP, и используются для установки соединений, передачи данных, отправки ACK, и закрытия соединений. Сегмент состоит из трех частей:
◆ Заголовка 20 байт
◆ Опционального заголовка переменной длинны, кратного 4-м байтам
◆ Данных
Максимальный размер заголовка 60 байт. Заголовок TCP, передает управляющую информацию. Поля SOURCE PORT и DESTINATION PORT, содержат номера портов TCP, идентифицирующих приложения на конечных точках. Поле SEQUENCE NUMBER определяет позицию первого байта прикрепленных данных. В поле ACKNOWLEDGEMENT NUMBER указывается байт, содержащий номер последовательности, которую должен получить получатель. Поле ACKNOWLEDGEMENT NUMBER используется, только когда в поле CODE BITS выставлен бит ACK. 6-ти битное поле CODE BITS определяет цель и назначение сегмента. Поле HLEN указывает на суммарную длину заголовков, состоит из 32-х бит. В поле WINDOW указывается количество данных, которое будет передано далее. Данное поле используется для резервирования буфера в приложении получателе. Поле CHECKSUM содержит 16-ти битное целочисленное значение контрольной суммы, и используется для подтверждения целостности заголовков и опций, указанных в них. Далее идут нулевые значения, для того, чтобы отделить заголовок и начало сегмента данных.

TCP window
TCP window, определяет количество данных, которое будет отправлено без ожидания подтверждения ACK от получателя. TCP window представляет собой механизм контроля потока данных и гарантирует, что не возникнет пробка в сети. Например, если пара узлов передает данные через соединение TCP, которое использует TCP window размером 64 KB, отправитель может передать 64 KB данных и потом должен ждать подтверждения получения данных. Если отправитель, получает подтверждение о том, что все данные получены, он может передавать следующий фрагмент данных в 64 KB. В случае, если отправитель получает подтверждение о получении первых 32 KB (если второй сегмент в 32 KB еще передается, или потерян), отправитель может отправить, только оставшийся кусок в 32 KB.
Основной задачей TCP window, является предотвращение возникновения пробок в сети.  Соединение узлов в сети может проходить через коммутаторы, роутеры, соединения между ними, и может иметь эффект «узкого горлышка», на участках медленными соединениями. Так TCP window, замедляет передачу данных, там, где образуется скопление пакетов данных и потери данных не происходит.
Следующие факторы оказывают влияние на размер TCP window:

Окно получателя данных
Время, требуемое получателю для обработки полученных данных и отправки ACK, может быть большим. Необходимо контролировать объем передаваемых данных, чтобы избежать отправки объема, который получатель не сможет обработать, т.к. это может привести к потере пакетов. TCP использует контроль потока данных, устанавливая окно получения данных для каждого узла сети.

Окно отправки данных
Окно для отправления данных зависит от количества проходящих по TCP пакетов данных. Для этого используется механизм Additive-Increase, Multiplicative-Decrease (AIMD), который проверяет пропускную способность сети и динамически адаптируется в случае возникновения очередей пакетов.

Используемое окно передачи данных
Это минимальное значение из окна получателя данных и окна отправки данных. Оно определяет актуальное количество данных, которое отправитель может отсылать. Заголовок TCP пакета содержит 16 битное поле, для записи размера TCP window. Поэтому, максимальное значение будет 2**16 = 65Kb.

Масштабирование окна передачи данных
Заголовок пакета TCP может содержать 16 бит, для определения размера окна. Таким образом, максимальный размер окна ограничен 64 KB. RFC 1323 предоставляет возможность масштабирования окна, чтобы преодолеть ограничение в 64 KB. Получатель и отправитель, должны согласовать опцию масштабирования во время установки соединения.
Масштабирование окна, позволяет определять размер TCP window 32-мя битами, используя фактор масштабируемости, помещает адрес в стандартное 16-ти битное поле заголовка пакета TCP (SEG.WND в RFC-793). Фактор масштабирования содержится в новой опции TCP — Window Scale. Данная опция посылается только с пакетом SYN (пакет с выставленном битом в поле SYN), одинаковый масштаб окна выставляется у получателя и отправителя, в момент установки соединения.


Восстановление ошибок в TCP
С сетях TCP, каждый узел определяет доступность сетевых ресурсов, так узлу узнают максимальное количество пакетов, которое может быть передано без потерь. Когда источнику нужно отправить большое количество пакетов, он использует получения ACK, как сигнал о том, что пакеты освободили сеть и можно продолжать отправку новых пакетов. TCP использует алгоритм обнаружения скоплений пакетов, для определения вместительности сети. С точки зрения данного алгоритма, сеть TCP может находиться в следующих состояниях:
Slow start: данный статус может появиться после осуществления соединения, и были потери пакетов, либо пришло несколько дублирующих подтверждений ACK.
Fast recovery: после обнаружения ошибки доставки пакетов, после осуществления повторной отправки потерянных пакетов.
Congestion avoidance: в любых других случаях. Перегруженность сети избегнута, и устройства начинают медленно передавать данные. Алгоритм обнаружения скоплений пакетов полагает, что вероятность потери пакетов от физических нарушений сети, очень мала. Потерю пакетов в сети алгоритм воспринимает, как перегруженность участка сети между отправителем и получателем данных. Также алгоритм реагирует на таймаут получения пакетов подтверждения и получение дубликатов пакетов ACK, как на потерю пакетов.
Когда обнаруживается перегрузка сети, возникает необходимость в понижении скорости передачи данных и запускается алгоритм slow start. Два параметра, окно перегрузки (cwnd) и ограничение скорости (ssthresh), выставляются для всех соединений. Когда соединение установлено, оба эти параметра инициализируются. Сwnd инициализируется для одного MSS. Ssthresh используется для определения slow start или использует алгоритм обнаружения скоплений пакетов контролирует передачу данных. Изначально значение ssthresh может быть произвольно высоким (обычно ssthresh инициализируется со значением 65535 байт), но значение может быть уменьшено в связи с перегрузками.
Алгоритм slow start, используется, когда значение cwnd, меньше, чем ssthresh, если используется алгоритм обнаружения скоплений пакетов, cwnd больне ssthresh. Если значения cwnd и ssthresh одинаковы, то отправитель выбирает алгоритм самостоятельно.
TCP никогда не передает пакетов больше, чем минимум cwnd и значения окна передачи данных. Когда устанавливается соединение, либо обнаружена перегрузка сети, TCP работает в режиме slow start и cwnd выставляются до одной MSS. Каждый раз, когда приходят пакеты ACK, cwnd увеличивается на одну MSS. Отправитель начинает с отправки одного пакета и ожидает пакет с ACK. Когда пакет ACK получен, cwnd увеличивается на единицу, и можно отправлять два пакета. Когда подтверждения о получениях пакетов получены, cwnd увеличивается до четырех, и так далее. Сwnd увеличивается экспоненциально на протяжении slow start (см Рис.2). Если обнаруживается таймаут получения пакетов подтверждения или получение дубликатов пакетов ACK, ssthresh сбрасывается до половины текущего окна (это минимум cwnd и окна получателя данных). Если фиксируется перегрузка сети, через таймаут, cwnd выставляется до одного MSS. Если приходит пакет ACK, подтверждающий получение данных, cwnd увеличивается, но значение, на которое увеличивается cwnd, зависит от режима работы TCP (slow start, либо в режиме обнаружения скоплений пакетов). Если cwnd меньше, либо равно значению ssthresh и TCP находится в режиме slow start, то он продолжит работать в режиме slow start, до тех пор, пока TCP не достигнет половины скорости, на которой произошла перегрузка, только тогда закончит работу режим обнаружения скоплений пакетов. Алгоритм обнаружения скоплений пакетов, увеличивает значение cwnd на MSS, деля на квадрат cwnd (в байтах), каждый раз, когда приходит пакет ACK, он увеличивает cwnd линейно, на рисунке 2 изображена схема увеличения значения  cwnd. Этот рисунок отображает, ближайшее приближение роста значения cwnd, с как минимум одним MSS на RTT.

 Активное изображение
Рисунок 2 Slow start и Congestion avoidance

При получении сегментов данных, сетевой интерфейс генерирует пакеты ACK. Пакет ACK содержит требуемые интерфейсом номера последовательностей данных. Получение отправителем пакета ACK, подтверждает, что все, либо часть, отправленных данных были доставлены до получателя. Когда получатель получает сегмент с номером последовательности, большим, чем он ожидал, он определяет внеочередной сегмент и немедленно генерирует пакет ACK, содержащий номер последовательности, которую он получал в последний раз (такой пакет называется дубликатом ACK). Данный дубликат ACK незамедлительно отправляется. Т.к. отправитель не знает, получил ли он дубликат ACK либо запрос на внеочередную последовательность данных, он ожидает еще несколько дубликатов данного ACK, пологая, что пакеты были получены не по порядку. В случае, когда получатель получает сегменты не по порядку, он генерирует несколько дублирующих ACK. Если отправитель получает три или более дубликатов ACK подряд, он определяет, что произошла потеря пакета и отправляет запрашиваемый сегмент вне очереди. Механизм изображен на рисунке 3.
После того, как прошла повторная пересылка запрашиваемого пакета, алгоритм  обнаружения скоплений пакетов запускает вместо slow start, fast recovery. Получение дубликата ACK подразумевает, не только потерю пакета, т.к. данные все еще успешно передаются через соединение TCP, получатель мог сгенерировать дубликат ACK, при сбое в порядке получения последовательности сегментов. Таким образом, fast recovery позволяет повысить пропускную способность сети, не вызывая скопления пакетов в сети.
 
Активное изображение
Рисунок 3 Fast retransmit

Перегрузка сети
Скопление пакетов в сети вызывает создание очередей, и переполнение очередей вызывает потери пакетов. Протокол TCP обнаруживает потери пакетов и начинает передавать их повторно, но использование активной передачи потерянных пакетов будет создавать еще большее скопление пакетов на участках сети. Возникновение очередей зависит от пропускной способности сети (и размера поддерживаемых очередей на коммутаторах). Когда образуется скопление пакетов, все потоки, которые это обнаружили, должны снизить скорость передачи, если они этого не сделают, сеть будет находиться в перегруженном состоянии, и пакеты будут теряться.

Безопасный интернет протокол (IPsec)
IPsec представляет собой набор протоколов, разработанных IETF для поддержки шифрования при обмене пакетами на уровне протокола IP. Шифрование пакетов IP, широко распространено в Virtual Private Network (VPN).
IPsec поддерживает два режима шифрования:
◆ Транспортный
◆ Туннелирования
Транспортный режим шифрует только данные, переносимые пакетом, оставляя заголовок пакета не тронутым. Режим туннелирования, предоставляет большую безопасность, т.к. он шифрует весть пакет, включая и заголовок.
Для получения зашифрованных пакетов, должно быть установлено устройство, совместимое с IPsec, для расшифровки пакетов. Для работы шифрования пакетов IPsec, получатель и отправитель, должны иметь одинаковый public key. Данный обмен обеспечивают протоколы Internet Security Association и Key Management Protocol/Oakley (ISAKMP/Oakley), которые позволяют получателю получить public key, авторизовав его, с использованием электронного сертификата.

Туннелирование и IPsec
IPsec использует криптографическое шифрование, для обеспечения безопасной передачи данных по сетям, использующим Internet Protocol. IPsec поддерживает сохранение целостности данных на сетевом уровне, конфиденциальность передаваемых данных и аутентификацию. Он помогает защитить сети SAN от сетевых атак, несанкционированного доступа к данным, приложениям, сервисам.
По умолчанию,  шифрование IPsec отключено в туннелях FCIP. Туннелирование FCIP, с использованием IPsec, поддерживает следующие максимальные пропускные способности:
◆ Однонаправленный: приблизительно 104 MB/sec
◆ Двунаправленный: приблизительно 90 MB/sec
Используя блэйд лезвия FR4-18i, либо коммутаторы Brocade SilkWorm 7500, можно достичь наибольшую безопасность передаваемых данных при туннелировании протокола SAN. Опция IPsec, не требует настроек каждого приложения, которое работает через TCP/IP.
IPsec может работать в туннелях FCIP как без компрессии, так и с компрессией IP (IPComp).
Использование IPsec, требует дополнительной лицензии IPsec license, в дополнение к FCIP license.

Терминология IPsec:

AES
Advanced Encryption Standard. Одобрено FIPS 197, использует алгоритм шифрования Rijndael. AES одобрен правительством США для защиты конфиденциальной информации в правительственных учреждениях.  Он заменяе стандарт шифрования DES.

AES-XCBC
Cipher Block Chaining. Односторонняя функция замещения (MAC) с использованием ключа, используется с AES в режиме Cipher-Block-Chaining. Подходящий вариант для шифрования сообщений различной длинны, например IP дейтаграмм.

AH
Authentication Header. Также, как ESP, AH обеспечивает целостность данных, аутентификацию источника и предоставляет защиту от компьютерных атак, но не предоставляет конфиденциальности.

DES
Data Encryption Standard. Представляет собой алгоритм шифрования, использующий 56-битный ключ для шифрования 64-х битных блоков. Из-за сравнительно короткого ключа используется редко.

3DES
Тройной DES, более безопасный вариант DES. Он использует три различных 56-битных ключа, для шифрования блоков данных в 64-бита. Алгоритм одобрен FIPS для использования в федеральных агентствах.

ESP
Encapsulating Security Payload. Представляет собой протокол IPsec, который обеспечивает целостность данных, аутентификацию источника IP пакетов, предоставляет защиту от атак.

MD5
Message Digest 5. Также, как SHA-1, является популярной функцией замещения, используется для аутентификации и хранения данных.

SHA
Secure Hash Algorithm. Также, как MD5, является популярной функцией замещения, используется для аутентификации и хранения данных.

MAC
Message Authentication Code. Односторонняя функция замещения с использованием ключа, используется для генерации ключей аутентификации.

HMAC
Более мощный алгоритм, чем MAC, т.к. использует замещение с ключом,  замещения с ключом.
 
 

Add comment


Security code
Refresh