понедельник, 16 августа 2010 г.

CISCO IOS Basic NAT/PAT

Между прочим ;)

Configuring Basic NAT Functionality
Problem
You want to set up Network Address Translation on your router.

Solution
In the simplest NAT configuration, all of your internal devices use the same external global address as the router's external interface:

Router#configure terminal
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#access-list 15 permit 192.168.0.0 0.0.255.255
Router(config)#ip nat inside source list 15 interface FastEthernet0/0 overload
Router(config)#interface FastEthernet0/2
Router(config-if)#ip address 192.168.1.1 255.255.255.0
Router(config-if)#ip nat inside
Router(config-if)#exit
Router(config)#interface FastEthernet0/1
Router(config-if)#ip address 192.168.2.1 255.255.255.0
Router(config-if)#ip nat inside
Router(config-if)#exit
Router(config)#interface Ethernet0/0
Router(config-if)#ip address 172.16.1.5 255.255.255.252
Router(config-if)#ip nat outside
Router(config-if)#exit
Router(config)#end
Router#


Discussion
In this example, the router will rewrite that address of all of the internal devices whose IP addresses are in the range 192.168.0.0/16. When these internal devices connect to devices on the outside of the network, they will all appear to have the same source address as the external interface of the router, 172.16.1.5.

This example actually includes two internal interfaces and one external. You designate the internal interfaces with the ip nat inside command. You can have as many inside interfaces as you like:

Router(config)#interface FastEthernet0/1
Router(config-if)#ip nat inside

You also need to designate at least one outside interface using the command ip nat outside. There can be several outside interfaces, but this can be very difficult to control, so it is usually not recommended:

Router(config-if)#interface Ethernet0/0
Router(config-if)#ip nat outside

You configure the actual translation action with the line:

Router(config)#ip nat inside source list 15 interface FastEthernet0/0 overload

This tells the router to translate the source addresses of any internal devices that match access-list number 15. The router will translate the source addresses of all of these devices to the address that is configured on the interface FastEthernet0/0, which is the outside interface.

The overload keyword is actually assumed here, so if you leave it off, the router will automatically put it in. This option tells the router that many internal devices can use the same global address simultaneously. Since the router itself uses this address, if even a single internal address translates to this address, it is already overloaded. We will explain this option in more detail in Recipe 21.2.

To help explain what the access-list on this command does, we will change it so that it includes every address in the range except one:

Router(config)#access-list 15 deny 192.168.1.101
Router(config)#access-list 15 permit 192.168.0.0 0.0.255.255

Now if you make a connection from the excluded address, 192.168.1.101, the only difference is that the router will not rewrite this internal address. Instead, this address will appear unchanged on the outside.

NAT can be quite confusing because people usually think that there is some firewall function associated with it. There is not. If you exclude one device from your NAT access-list, as we just discussed, anybody on the outside of the network will be able to connect to this internal device by its real address. But there is nothing to prevent an inbound packet from reaching a particular internal device if the person on the outside knows the real internal address and can route to it. Further, NAT by itself doesn't do any firewall functions, such as UDP or TCP port filtering.

DNAT

Пример:

ip nat inside source static tcp 192.168.10.1 25 171.69.232.209 25

В этом примере внешне инициируемое соединение для порта SMTP (25)
будет посылаться на внутренний хост 192.168.10.1.

четверг, 12 августа 2010 г.

BGP attributes

Плотно занялся изучением BGP. Достаточно понятно написано про атрибуты. Из JunOS Cookbook.


Introduction
The IGPs OSPF, IS-IS, and RIP maintain the mapping for the topology within a single administrative domain or AS, along with the set of best paths between systems within the domain. Each AS uses one or more common IGPs and common metrics to determine how to route packets within the AS. The administration of an AS appears to other ASs to have a single coherent interior routing scheme and presents a consistent picture of what destinations are reachable through it.

To handle inter-AS routing, IGPs use an EGP. EGPs keep track of how routing domains are connected to each other and the sequence of domains that must be traversed to reach a particular destination. Although a number of EGPs were developed in the late 1980s, the Border Gateway Protocol (BGP) is the only one currently being used on IP networks and the Internet. Version 1 of BGP was introduced in 1989, and the current iteration, Version 4, is defined in RFC 1771 and has been in use since 1995. A number of additional RFCs define extensions to the base BGP protocol (see http://www.bgp4.as/rfc).

BGP is the routing protocol that holds the Internet together, providing the mesh-like connectivity of Internet service provider (ISP) networks that forms what we call the Internet. ISPs use BGP to connect to each other, forming the virtual backbone of the Internet. Large enterprises also sometimes use BGP to connect to their ISPs, as well as to connect portions of their internal corporate network.

BGP uses a path vector algorithm to determine network topology and paths to destinations. This algorithm defines a route as a pairing between a destination and the attributes of the path to that destination. It considers multiple attributes of the path in order to choose the best route to the destination. In comparison, a distance-vector protocol uses a single distance metric to choose the best route. BGP routing updates carry path information, which is a full list of the transit ASs that must be traversed between the AS receiving the update and the AS that can deliver the packet using its IGP. BGP uses this list to eliminate loops in the path because a router can check the list of ASs to see whether a route has already passed through it. BGP treats each AS equally when considering the path, no matter how big or small it is. BGP does not know how many routers or what type of links are in an AS.

BGP uses TCP port 179 for transport. BGP relies on basic TCP connections to reach its peers, using the fragmentation, retransmission, acknowledgment, and sequencing functions in TCP. If two routers cannot establish a TCP connection between them, they will not be able to establish BGP peering.

BGP requires that all peering sessions be configured explicitly between BGP neighbors. There are two types of BGP peerings, external BGP (EBGP) and internal BGP (IBGP). The basic distinction between them is that an EBGP peering is between two ASs that have different AS numbers and an IBGP peering is within a single AS so the peers have the same AS number. An EBGP peering is between two BGP routers that are directly connected to each other. IBGP peerings can be among multiple routers within an AS. IBGP routers must create a full mesh of IBGP peering sessions to communicate BGP routing information with each other. This full mesh can be physical connections, where all IBGP routers are directly connected and adjacent to each other. Typically, though, the full mesh is virtual, created in the router software configuration, and the connectivity is provided by an IGP. A third type of BGP peering, called multihop or EBGP multihop, allows BGP to set up sessions with neighbors in other ASs that are not directly connected.

BGP requires that each AS have a 16-bit AS number. AS numbers range from 0 tHRough 65535 and are globally unique across the Internet. BGP uses the AS number to prevent routing loops. AS numbers are doled out in blocks to each of the regional Internet registries ( ARIN, APNIC, RIPE, AfriNIC, and LatNIC), and the regional registries assign AS numbers to individual organizations. The AS numbers 64512 tHRough 65534 are reserved for private use, but you can use these on internal enterprise networks as long as the numbers are unique within your network. The examples in this chapter use private AS numbers as well as RFC 1918 private IP addresses. This is purely for demonstration purposesyou should never allow private AS numbers or private IP addresses to reach the public Internet.

By default, BGP routers accept all BGP information from EBGP peers and advertise all BGP information to all EBGP peers. BGP routers advertise all BGP information to IBGP peers if it comes from an EBGP peer and advertise paths learned from IBGP peers only to external peers. BGP does not advertise its internal paths to IBGP peers. This is done instead by IGP. To prevent routing loops, a BGP router does not, by default, accept routes that contain its own AS number.

BGP makes extensive use of routing policy to allow ISPs to enforce administrative policies. The JUNOS software provides both inbound and outbound policy controls at different levels: for all BGP peers, for groups of peers, and for individual peers. A policy with a narrower scope overrides one with a broader scope. Stated another way, a policy applied to a group overrides a BGP-wide policy, and a policy applied to a peer overrides both a group and BGP-wide policy.

Multiprotocol BGP ( MBGP), defined in RFC 2858, is an extension to BGP that supports other protocols, including IPv6, MPLS, and VPNs.

In choosing routes toward a destination, if there is more than one route to the same destination, BGP uses an algorithm to select a single route to use (see the Introduction to Chapter 8). Note that other router vendors may follow a slightly different set of rules to determine the active route.

For more information about BGP, see BGP4: Inter-Domain Routing in the Internet (Addison-Wesley).

BGP Attributes
BGP routers exchange routes, or NLRI, with their neighbors. An NLRI consists of a route prefix and the BGP attributes associated with the route. Attributes contain information about a route, such as where it came from and how to reach it, that BGP uses to choose the best path to a destination. A number of attributes were defined in the original BGP specification, and, over time, attributes have been added to extend the functionality of BGP. Compared to IGP routes, which generally just carry the route, a next hop, metric, and an optional tag, BGP routes typically have about a dozen attributes associated with them.

There are several types of attributes. Well-known attributes are supported by all BGP implementations. Mandatory attributes are included with every prefix. If they are missing, the receiving BGP router will generate an error message. Discretionary attributes are those that BGP routers must recognize and support but don't have to be included with every prefix. When a BGP router passes a prefix to its peers, it includes all well-known, mandatory, and discretionary attributes associated with the prefix, either in the state they were received or in the state after they were modified when they passed through the local AS.

BGP routers can also include optional attributes with prefixes, or those that are not necessarily supported by all BGP routers. Optional attributes can be transitive, which means that BGP must include the information when sending the prefix to another router even if the sending router doesn't understand the option, or nontransitive, which allows a router that doesn't understand the option to silently drop it when advertising the prefix.

The following are some of the common BGP attributes. Most BGP implementations understand these attributes.



ORIGIN (well-known, mandatory)

Designates how BGP learned about the route. It can be one of the following:



I

Route was originally learned from an IGP in the originating AS.



E

Route was originally learned from an EGP.



Incomplete

Route's source is unknown or BGP doesn't have complete knowledge of its origin.



AS_PATH (well-known, mandatory)

Contains a list of AS numbers that form the path to a destination network. There are two types of AS path attributes. The AS_SEQUENCE attribute indicates the networks that the route has transited from the originating AS to the local AS. When advertising a prefix to an EBGP peer, a BGP router modifies the AS path, prepending its AS by adding it to the beginning of the list. The last AS in the path sequence is the originator of the route. For example, in the AS path 65500 65505 65100, the route originated at AS 65100 and the last AS it passed through was 65500. BGP uses the AS path for loop avoidance among ASs. The second type of AS path attribute is AS_SET, which is an unordered list of AS numbers along the path to the destination.



NEXT_HOP (well-known, mandatory)

Contains the IP address of the BGP router that is the next hop toward the destination. The BGP router selects the next hop based on its local routing table. For routes learned from a different AS, the next hop is the IP address of the physical interface to a remote router. If the advertising and receiving routers are in the same AS and the route is in the same AS, the BGP next hop is the IP address of the advertising router. If the route is in a different AS, the BGP next hop is the IP address of a remote BGP router.



LOCAL_PREF (well-known, optional)

Indicates the degree of preference for routes learned by IBGP within an AS. BGP uses this information to choose or favor an exit point from the AS. The higher the preference, the more preferred a route is. This attribute is distributed only in IBGP routing updates.



MED or MULTI_EXIT_DESC (optional, nontransitive)

The multiple exit discriminator is used to determine the exit point from one AS to another AS when there are multiple equivalent paths between the ASs and when all other factors in determining the exit point are equal. The MED is effectively the BGP metric and is a common way for one ISP to make another ISP use the desired link between the two ISPs. Because the MED is nontransitive, it is sent only to adjacent ASs.



ATOMIC_AGGREGATE (well-known, optional)

Indicates that the route is an aggregate of several route prefixes. BGP sets this attribute to indicate that some route information has been lost in the aggregation process.



AGGREGATOR (optional, transitive)

Indicates that the BGP router has summarized a range of prefixes.



COMMUNITY (optional, transitive)

Identifies an administrative or logical grouping of routes that share routing policies. Communities are represented by an identifier that includes the 16-bit AS number and a 16-bit community number. For example, in 65500:1001, the AS number is 65500 and the community number is 1001. BGP has three well-known communities:



NO_EXPORT

Routes cannot be advertised to EBGP peers but can be advertised within a BGP confederation.



NO_ADVERTISE

Routes cannot be advertised at all.



LOCAL_AS

Routes cannot be advertised to EBGP peers, even if the peers are in the same confederation.



MP_REACH_NLRI and MP_UNREACH_NLRI (optional, nontransitive)

Carry IPv6 NLRI information in MBGP.



ORIGINATOR_ID (optional, nontransitive)

Identifies a route reflector for IBGP. It is a 32-bit value that indicates the originator of the route within an AS.



CLUSTER_LIST (optional, nontransitive)

Lists route reflection identifiers of the clusters through which the route has passed. If a cluster sees its own identifier in the list, a loop has occurred and the route is ignored.

понедельник, 9 августа 2010 г.

Perl view my IP

Есть сервер, подключенный к модему с динамическим public ip. Решил обойтись без dynamic dns. На сервере пишу скрипт на Perl, который выходит на сайт whatismyipaddress.com, узнает там свой айпишник, записывает его в файл ip.htm и выкладывает на ftp.


#!/usr/bin/perl
# Script by k4

open DB, "ip.htm";
$pth="/home/user";
chdir $pth;

$lastip=;
chomp $lastip;
#print $lastip;

my $url = 'http://whatismyipaddress.com/';

use LWP::Simple;
my $content = get $url;
die "Couldn't get $url" unless defined $content;

if($content =~ m/(IP\sInformation:\s\)(\d+\.\d+\.\d+\.\d+)(\<\!\-\-\s)/) {

if ($lastip eq $2) { } else { $a=1; print `echo $2 > ip.htm`; }
} else {
print "IP is unknown\n";
}

if ($a) {

use Net::FTP;

$ftp = Net::FTP->new('ftp.host.net', Debug => 0)
or die "Cannot connect to sgsn1: $@";


$ftp->login('login', 'password')
or die "Cannot login", $ftp->message;

#$ftp->cwd("/")
#or die "Cannot change working directory ", $ftp->message;

$ftp->put("ip.htm")
or die "send failed ", $ftp->message;

$ftp->quit;
}

четверг, 29 июля 2010 г.

Firewall на Juniper M20/M120

Всё просто. Достаточно понять структуру конфига и иметь под рукой руководство :)

В разделе firewall создаем фильтр gtp, в нем term'ы. В данном примере создаем терм ospf, в нем разрешаем ospf пакеты из сети 0.33.10.0/28. В терме icmp разрешаем запрос и ответ echo от всех к двум подсетям. Терм gtp. Разрешаем udp порты на определенные хосты. В последнем разрешаем фрагментированные udp пакеты.

firewall {
    family inet {
        filter gtp {
            term ospf {
                from {
                    source-address {
                        10.33.10.0/28;
                    }
                    protocol ospf;
                }
                then accept;
            }
            term icmp {
                from {
                    source-address {
                        0.0.0.0/0;
                    }
                    destination-address {
                        10.33.10.0/28;
                        213.11.43.128/27;
                    }
                    protocol icmp;
                    icmp-type [ echo-reply echo-request ];
                }
                then accept;
            }
            term gtp {
                from {
                    source-address {
                        0.0.0.0/0;
                    }
                    destination-address {
                        213.11.43.128/27;
                    }
                    protocol udp;
                    destination-port [ 2123 2152 3386 ];
                }
                then accept;
            }
            term frag {
                from {
                    is-fragment;
                    protocol udp;
                }
                then accept;
            }
        }
 }
}

четверг, 22 июля 2010 г.

RADIUS settings on Juniper M20

Вот небольшая конструкция из коонфига GGSN juniper m20. Указано 3 Ip radius серверов. Основной сервер 10.10.17.2. На него отправляются запросы, и абонетов выпускаем в инет при получении acct response. Что примечательно, на первые два ip отправляются копии запросов, не ожидающие подтверждений. Об этом говорит строчка multicast-servers 2 т.е. 2 первых сервера - multicast servers.

radius {
server {
acct {
address [ 10.10.60.4 10.10.60.5 10.10.17.2 ];
routing-instance gi-sasn;
gi-address-range 10.10.30.136/29;
timeout 3;
retry 3;
secret "SECRET"; ## SECRET-DATA
serverdown-timeout 0;
multicast-servers 2;
}
}
}

И ещё один финт.

radius {
retry-method multiple-server;
load-balancing;
accounting {
message-attributes {
ggsn-address;
gprs-qos;
msisdn;
pdp-type;
signaling-sgsn;
sgsn-plmn-id;
charging-identifier;
session-stop;
}
shared-server acct;
un-acknowledge;
}
accept-disconnect;
}

Здесь ggsn тоже не дожидается ответа от radius. Об этом говорит строчка un-acknowledge. На этом наш небольшой экскурс в мир ggsn пока завершен. :)

среда, 21 июля 2010 г.

OpenVPN + ipfilter + nat на Solaris 10




OpenVPN



Мне нужно было сделать шлюз с vpn сервером, который бы выпускал авторизованных клиентов через определенный интерфейс дальше в сеть под ip адресом исходящего интерфейса. Другими словами - NAT, а ещё конкретнее - PAT. Я делал такое на Linux с использованием pptpd и iptables, включая ip_forwarding на уровне ядра системы. PPTPD я выбрал потому, что для подключения к серверу не нужно устанавливать на WinXP клиента никакого дополнительного софта. В случае с OpenVPN необходимо поставить клиентскую часть + драйвера для tun/tap интерфейсов. Ниже я опишу, как я это делал на Solaris, использую OpenVPN и стандартный для этой системы ipfilter.

Сервер Sun Netra 240, OS Solaris 5.10 x64, клиент Windows XP. Будем считать, что OpenVPN и OpenSSL уже стоит. OVPN я собирал из исходников, доступных на его сайте. Много зависимостей можно найти тут - http://www.sunfreeware.com/

Займемся настройкой OpenVPN.



Итак, план такой^
1. Создаем ROOT CERTIFICATE AUTHORITY (CA).
2. Создаем ключ Диффи Хельман.
3. Создаем сертификат для сервера, подписываем его сертификатом CA.
4. Повторяем для клиентов. Размещаем необходимые файлы на клиентских хостах.

Как всё было



root@netra # pwd
/etc/openvpn/cert
root@netra # openssl req -days 3650 -nodes -new -x509 -keyout /etc/openvpn/cert/ca.key -out /etc/openvpn/cert/ca.crt -config /usr/local/share/easy-rsa/openssl.cnf
Generating a 1024 bit RSA private key
............................................................................................................++++++
..........++++++
writing new private key to '/etc/openvpn/cert/ca.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [RU]:
State or Province Name (full name) [RO]:
Locality Name (eg, city) [ROSTOV]:
Organization Name (eg, company) [ORG]:
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []:vpn_server
Email Address [email@mail.com]:root@localhost
root@netra # ls -l
total 6
-rw-r--r-- 1 root root 1159 Jul 20 16:23 ca.crt
-rw-r--r-- 1 root root 891 Jul 20 16:23 ca.key
root@netra # more ca.crt
-----BEGIN CERTIFICATE-----
MIIDKzCCApSgAwIBAgIJANyjv36yiT4TMA0GCSqGSIb3DQEBBQUAMG0xCzAJBgNV
...
2Vio3tsLzIke9dWdlSEztZfeKihV4xzUs/48Javez2lku4k4nx6f327KRGtXFLs=
-----END CERTIFICATE-----
root@netra # more ca.key
-----BEGIN RSA PRIVATE KEY-----
MIICXgIBAAKBgQC1LYCTM4GH03uueXwAO5gDHzi2nVCw6tM9e+d85NRpzplhFkXh
...
/tnYCSRyOzYqLnzdxddKbru/0SDIlFp1q9k49R/29jv4Rg==
-----END RSA PRIVATE KEY-----
root@netra # openssl dhparam -out /etc/openvpn/cert/dh1024.pem 1024
Generating DH parameters, 1024 bit long safe prime, generator 2
This is going to take a long time
...........................+..............................................++*++*++*
root@netra #
root@netra # ls -lt

total 8
-rw-r--r-- 1 root root 245 Jul 20 16:30 dh1024.pem
-rw-r--r-- 1 root root 1159 Jul 20 16:23 ca.crt
-rw-r--r-- 1 root root 891 Jul 20 16:23 ca.key
root@netra # more dh1024.pem
-----BEGIN DH PARAMETERS-----
MIGHAoGBAPMdnAaERljNhxa7w01UKEt/62ucSnQhGgLGAIQ5wWHvM/r3ZSxV+coX
...
ier9ndCIBUZhFB7MT23BD0bNRBJuzq38n9gcecuDiLubCB6vGTA7AgEC
-----END DH PARAMETERS-----
root@netra # ls
ca.crt ca.key dh1024.pem
root@netra # openssl req -days 3650 -nodes -new -keyout /etc/openvpn/cert/netra.key -out /etc/openvpn/cert/netra.csr -config /usr/local/share/easy-rsa/openssl.cnf
Generating a 1024 bit RSA private key
.....................................................++++++
.......++++++
writing new private key to '/etc/openvpn/cert/netra.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [RU]:
State or Province Name (full name) [RO]:
Locality Name (eg, city) [ROSTOV]:
Organization Name (eg, company) [ORG]:
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []:netra
Email Address [email@mail.com]:root@localhost

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
root@netra # ls -l
total 12
-rw-r--r-- 1 root root 1159 Jul 20 16:23 ca.crt
-rw-r--r-- 1 root root 891 Jul 20 16:23 ca.key
-rw-r--r-- 1 root root 245 Jul 20 16:30 dh1024.pem
-rw-r--r-- 1 root root 651 Jul 20 16:38 netra.csr
-rw-r--r-- 1 root root 887 Jul 20 16:38 netra.key
root@netra # openssl ca -days 3650 -out /etc/openvpn/cert/netra.crt -in /etc/openvpn/cert/netra.csr -extensions server -config /usr/local/share/easy-rsa/openssl.cnf
Using configuration from /usr/local/share/easy-rsa/openssl.cnf
/etc/openvpn/cert/index.txt: No such file or directory
unable to open '/etc/openvpn/cert/index.txt'
2002:error:02001002:system library:fopen:No such file or directory:bss_file.c:356:fopen('/etc/openvpn/cert/index.txt','r')
2002:error:20074002:BIO routines:FILE_CTRL:system lib:bss_file.c:358:
root@netra # touch /etc/openvpn/cert/index.txt
root@netra # openssl ca -days 3650 -out /etc/openvpn/cert/netra.crt -in /etc/openvpn/cert/netra.csr -extensions server -config /usr/local/share/easy-rsa/openssl.cnf
Using configuration from /usr/local/share/easy-rsa/openssl.cnf
/etc/openvpn/cert/serial: No such file or directory
error while loading serial number
2089:error:02001002:system library:fopen:No such file or directory:bss_file.c:356:fopen('/etc/openvpn/cert/serial','r')
2089:error:20074002:BIO routines:FILE_CTRL:system lib:bss_file.c:358:
root@netra # touch /etc/openvpn/cert/serial
root@netra # openssl ca -days 3650 -out /etc/openvpn/cert/netra.crt -in /etc/openvpn/cert/netra.csr -extensions server -config /usr/local/share/easy-rsa/openssl.cnf

Using configuration from /usr/local/share/easy-rsa/openssl.cnf
unable to load number from /etc/openvpn/cert/serial
error while loading serial number
2092:error:0D066096:asn1 encoding routines:a2i_ASN1_INTEGER:short line:f_int.c:215:
root@netra # echo 01 > /etc/openvpn/cert/serial
root@netra # openssl ca -days 3650 -out /etc/openvpn/cert/netra.crt -in /etc/openvpn/cert/netra.csr -extensions server -config /usr/local/share/easy-rsa/openssl.cnf

Using configuration from /usr/local/share/easy-rsa/openssl.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName :PRINTABLE:'RU'
stateOrProvinceName :PRINTABLE:'RO'
localityName :PRINTABLE:'ROSTOV'
organizationName :PRINTABLE:'ORG'
commonName :PRINTABLE:'netra'
emailAddress :IA5STRING:'root@localhost'
Certificate is to be certified until Jul 17 12:43:55 2020 GMT (3650 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated
root@netra # ls -lt
total 36
-rw-r--r-- 1 root root 3520 Jul 20 16:44 netra.crt
-rw-r--r-- 1 root root 3520 Jul 20 16:44 01.pem
-rw-r--r-- 1 root root 21 Jul 20 16:44 index.txt.attr
-rw-r--r-- 1 root root 83 Jul 20 16:44 index.txt
-rw-r--r-- 1 root root 3 Jul 20 16:44 serial
-rw-r--r-- 1 root root 3 Jul 20 16:43 serial.old
-rw-r--r-- 1 root root 0 Jul 20 16:42 index.txt.old
-rw-r--r-- 1 root root 651 Jul 20 16:38 netra.csr
-rw-r--r-- 1 root root 887 Jul 20 16:38 netra.key
-rw-r--r-- 1 root root 245 Jul 20 16:30 dh1024.pem
-rw-r--r-- 1 root root 1159 Jul 20 16:23 ca.crt
-rw-r--r-- 1 root root 891 Jul 20 16:23 ca.key
root@netra # more index.txt
V 200717124355Z 01 unknown /C=RU/ST=RO/O=ORG/CN=netra/emailAddress=root@localhost
root@netra # more serial
02
root@netra # openssl req -days 3650 -nodes -new -keyout /etc/openvpn/cert/laptop.key -out /etc/openvpn/cert/laptop.csr -config /usr/local/share/easy-rsa/openssl.cnf
Generating a 1024 bit RSA private key
...........++++++
..................++++++
writing new private key to '/etc/openvpn/cert/laptop.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [RU]:
State or Province Name (full name) [RO]:
Locality Name (eg, city) [ROSTOV]:
Organization Name (eg, company) [ORG]:
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []:k4laptop
Email Address [email@mail.com]:k4route@gmail.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
root@netra # ls -lt
total 40
-rw-r--r-- 1 root root 660 Jul 20 16:50 laptop.csr
-rw-r--r-- 1 root root 887 Jul 20 16:50 laptop.key
-rw------- 1 root root 0 Jul 20 16:46 ipp.txt
-rw-r--r-- 1 root root 3520 Jul 20 16:44 netra.crt
-rw-r--r-- 1 root root 3520 Jul 20 16:44 01.pem
-rw-r--r-- 1 root root 21 Jul 20 16:44 index.txt.attr
-rw-r--r-- 1 root root 83 Jul 20 16:44 index.txt
-rw-r--r-- 1 root root 3 Jul 20 16:44 serial
-rw-r--r-- 1 root root 3 Jul 20 16:43 serial.old
-rw-r--r-- 1 root root 0 Jul 20 16:42 index.txt.old
-rw-r--r-- 1 root root 651 Jul 20 16:38 netra.csr
-rw-r--r-- 1 root root 887 Jul 20 16:38 netra.key
-rw-r--r-- 1 root root 245 Jul 20 16:30 dh1024.pem
-rw-r--r-- 1 root root 1159 Jul 20 16:23 ca.crt
-rw-r--r-- 1 root root 891 Jul 20 16:23 ca.key
root@netra # openssl ca -days 3650 -out /etc/openvpn/cert/laptop.crt -in /etc/openvpn/cert/laptop.csr -config /usr/local/share/easy-rsa/openssl.cnf
Using configuration from /usr/local/share/easy-rsa/openssl.cnf

Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName :PRINTABLE:'RU'
stateOrProvinceName :PRINTABLE:'RO'
localityName :PRINTABLE:'ROSTOV'
organizationName :PRINTABLE:'ORG'
commonName :PRINTABLE:'k4laptop'
emailAddress :IA5STRING:'k4route@gmail.com'
Certificate is to be certified until Jul 17 12:51:48 2020 GMT (3650 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated
root@netra # ls -lt
total 60
-rw-r--r-- 1 root root 3427 Jul 20 16:51 laptop.crt
-rw-r--r-- 1 root root 3427 Jul 20 16:51 02.pem
-rw-r--r-- 1 root root 21 Jul 20 16:51 index.txt.attr
-rw-r--r-- 1 root root 172 Jul 20 16:51 index.txt
-rw-r--r-- 1 root root 3 Jul 20 16:51 serial
-rw-r--r-- 1 root root 660 Jul 20 16:50 laptop.csr
-rw-r--r-- 1 root root 887 Jul 20 16:50 laptop.key
-rw------- 1 root root 0 Jul 20 16:46 ipp.txt
-rw-r--r-- 1 root root 3520 Jul 20 16:44 netra.crt
-rw-r--r-- 1 root root 3520 Jul 20 16:44 01.pem
-rw-r--r-- 1 root root 21 Jul 20 16:44 index.txt.attr.old
-rw-r--r-- 1 root root 83 Jul 20 16:44 index.txt.old
-rw-r--r-- 1 root root 3 Jul 20 16:44 serial.old
-rw-r--r-- 1 root root 651 Jul 20 16:38 netra.csr
-rw-r--r-- 1 root root 887 Jul 20 16:38 netra.key
-rw-r--r-- 1 root root 245 Jul 20 16:30 dh1024.pem
-rw-r--r-- 1 root root 1159 Jul 20 16:23 ca.crt
-rw-r--r-- 1 root root 891 Jul 20 16:23 ca.key
root@netra # more index.txt
V 200717124355Z 01 unknown /C=RU/ST=RO/O=ORG/CN=netra/emailAddress=root@localhost
V 200717125148Z 02 unknown /C=RU/ST=RO/O=ORG/CN=k4laptop/emailAddress=k4route@gmail.com
root@netra # more serial
03

Запускаем openvpn в режиме демона
openvpn --daemon --config /etc/openvpn/openvpn.conf

В логе сервера:

Tue Jul 20 17:27:51 2010 us=722787 Current Parameter Settings:
Tue Jul 20 17:27:51 2010 us=723074 config = '/etc/openvpn/openvpn.conf'
Tue Jul 20 17:27:51 2010 us=723103 mode = 1
Tue Jul 20 17:27:51 2010 us=723121 show_ciphers = DISABLED
Tue Jul 20 17:27:51 2010 us=723138 show_digests = DISABLED
Tue Jul 20 17:27:51 2010 us=723154 show_engines = DISABLED
Tue Jul 20 17:27:51 2010 us=723171 genkey = DISABLED
Tue Jul 20 17:27:51 2010 us=723187 key_pass_file = '[UNDEF]'
Tue Jul 20 17:27:51 2010 us=723203 show_tls_ciphers = DISABLED
Tue Jul 20 17:27:51 2010 us=723219 proto = 0
Tue Jul 20 17:27:51 2010 us=723237 local = '10.10.60.4'
Tue Jul 20 17:27:51 2010 us=723251 remote_list = NULL
Tue Jul 20 17:27:51 2010 us=723284 remote_random = DISABLED
Tue Jul 20 17:27:51 2010 us=723301 local_port = 1194
Tue Jul 20 17:27:51 2010 us=723316 remote_port = 1194
Tue Jul 20 17:27:51 2010 us=723330 remote_float = DISABLED
Tue Jul 20 17:27:51 2010 us=723344 ipchange = '[UNDEF]'
Tue Jul 20 17:27:51 2010 us=723358 bind_local = ENABLED
Tue Jul 20 17:27:51 2010 us=723372 dev = 'tun'
Tue Jul 20 17:27:51 2010 us=723388 dev_type = '[UNDEF]'
Tue Jul 20 17:27:51 2010 us=723401 NOTE: --mute triggered...
Tue Jul 20 17:27:51 2010 us=723442 155 variation(s) on previous 20 message(s) suppressed by --mute
Tue Jul 20 17:27:51 2010 us=723461 OpenVPN 2.0.9 sparc-sun-solaris2.10 [SSL] [LZO] built on Apr 9 2009
Tue Jul 20 17:27:51 2010 us=756859 Diffie-Hellman initialized with 1024 bit key
Tue Jul 20 17:27:51 2010 us=757757 WARNING: file '/etc/openvpn/cert/netra.key' is group or others accessible
Tue Jul 20 17:27:51 2010 us=759123 TLS-Auth MTU parms [ L:1542 D:138 EF:38 EB:0 ET:0 EL:0 ]
Tue Jul 20 17:27:51 2010 us=760058 TUN/TAP device tun0 opened
Tue Jul 20 17:27:51 2010 us=760230 /usr/sbin/ifconfig tun0 10.10.0.1 10.10.0.2 mtu 1500 up
Tue Jul 20 17:27:51 2010 us=772217 /usr/sbin/ifconfig tun0 netmask 255.255.255.255
Tue Jul 20 17:27:51 2010 us=781995 /usr/sbin/route add 10.10.0.0 -netmask 255.255.255.0 10.10.0.2
add net 10.10.0.0: gateway 10.10.0.2: entry exists
Tue Jul 20 17:27:51 2010 us=789684 ERROR: Solaris route add command failed: shell command exited with error status: 17
Tue Jul 20 17:27:51 2010 us=789859 Data Channel MTU parms [ L:1542 D:1450 EF:42 EB:135 ET:0 EL:0 AF:3/1 ]
Tue Jul 20 17:27:51 2010 us=790404 GID set to nobody
Tue Jul 20 17:27:51 2010 us=790599 UID set to nobody
Tue Jul 20 17:27:51 2010 us=790837 Socket Buffers: R=[57344->65536] S=[57344->65536]
Tue Jul 20 17:27:51 2010 us=790963 UDPv4 link local (bound): 10.10.60.4:1194
Tue Jul 20 17:27:51 2010 us=791067 UDPv4 link remote: [undef]
Tue Jul 20 17:27:51 2010 us=791204 MULTI: multi_init called, r=256 v=256
Tue Jul 20 17:27:51 2010 us=791376 IFCONFIG POOL: base=10.10.0.4 size=62
Tue Jul 20 17:27:51 2010 us=791539 IFCONFIG POOL LIST
Tue Jul 20 17:27:51 2010 us=791672 k4laptop,10.10.0.4
Tue Jul 20 17:27:51 2010 us=791832 Initialization Sequence Completed

Переписываем файлы ca.crt laptop.crt laptop.key на лаптоп. Ставим клиент OpenVPN. Для него есть GUI под WinXP. Создаем конфиг.
dev tun
client
proto udp
remote 10.10.60.4 1194 # real IP of Solaris
tls-client
ns-cert-type server
ca /openvpn/ca.crt
cert /openvpn/laptop.crt
key /openvpn/laptop.key
comp-lzo

Запускаем клиента:

Tue Jul 20 17:06:46 2010 OpenVPN 2.0.9 Win32-MinGW [SSL] [LZO] built on Oct 1 2006
Tue Jul 20 17:06:46 2010 IMPORTANT: OpenVPN's default port number is now 1194, based on an official port number assignment by IANA. OpenVPN 2.0-beta16 and earlier used 5000 as the default port.
Tue Jul 20 17:06:46 2010 LZO compression initialized
Tue Jul 20 17:06:46 2010 UDPv4 link local (bound): [undef]:1194
Tue Jul 20 17:06:46 2010 UDPv4 link remote: 10.10.60.4:1194
Tue Jul 20 17:06:48 2010 [netra] Peer Connection Initiated with 10.10.60.4:1194
Tue Jul 20 17:06:50 2010 TAP-WIN32 device [Подключение по локальной сети 12] opened: \\.\Global\{8D12FDF2-7DD6-423F-91FB-A995649F0FE5}.tap
Tue Jul 20 17:06:50 2010 Notified TAP-Win32 driver to set a DHCP IP/netmask of 10.10.0.6/255.255.255.252 on interface {8D12FDF2-7DD6-423F-91FB-A995649F0FE5} [DHCP-serv: 10.10.0.5, lease-time: 31536000]
Tue Jul 20 17:06:50 2010 NOTE: FlushIpNetTable failed on interface [2] {8D12FDF2-7DD6-423F-91FB-A995649F0FE5} (status=1413) : Неверный индекс.
Tue Jul 20 17:06:53 2010 Initialization Sequence Completed

На сервере в этот момент видим:
Tue Jul 20 17:29:17 2010 us=455156 MULTI: multi_create_instance called
Tue Jul 20 17:29:17 2010 us=455376 10.208.251.225:1194 Re-using SSL/TLS context
Tue Jul 20 17:29:17 2010 us=455472 10.208.251.225:1194 LZO compression initialized
Tue Jul 20 17:29:17 2010 us=455953 10.208.251.225:1194 Control Channel MTU parms [ L:1542 D:138 EF:38 EB:0 ET:0 EL:0 ]
Tue Jul 20 17:29:17 2010 us=455989 10.208.251.225:1194 Data Channel MTU parms [ L:1542 D:1450 EF:42 EB:135 ET:0 EL:0 AF:3/1 ]
Tue Jul 20 17:29:17 2010 us=456062 10.208.251.225:1194 Local Options String: 'V4,dev-type tun,link-mtu 1542,tun-mtu 1500,proto UDPv4,comp-lzo,cipher BF-CBC,auth SHA1,keysize 128,key-method 2,tls-server'
Tue Jul 20 17:29:17 2010 us=456088 10.208.251.225:1194 Expected Remote Options String: 'V4,dev-type tun,link-mtu 1542,tun-mtu 1500,proto UDPv4,comp-lzo,cipher BF-CBC,auth SHA1,keysize 128,key-method 2,tls-client'
Tue Jul 20 17:29:17 2010 us=456175 10.208.251.225:1194 Local Options hash (VER=V4): '530fdded'
Tue Jul 20 17:29:17 2010 us=456209 10.208.251.225:1194 Expected Remote Options hash (VER=V4): '41690919'
Tue Jul 20 17:29:17 2010 us=456311 10.208.251.225:1194 TLS: Initial packet from 10.208.251.225:1194, sid=41cd4946 92fa470b
Tue Jul 20 17:29:18 2010 us=556925 10.208.251.225:1194 VERIFY OK: depth=1, /C=RU/ST=RO/L=ROSTOV/O=ORG/CN=vpn_server/emailAddress=root@localhost
Tue Jul 20 17:29:18 2010 us=558013 10.208.251.225:1194 VERIFY OK: depth=0, /C=RU/ST=RO/O=ORG/CN=k4laptop/emailAddress=k4route@gmail.com
Tue Jul 20 17:29:18 2010 us=795106 10.208.251.225:1194 Data Channel Encrypt: Cipher 'BF-CBC' initialized with 128 bit key
Tue Jul 20 17:29:18 2010 us=795336 10.208.251.225:1194 Data Channel Encrypt: Using 160 bit message hash 'SHA1' for HMAC authentication
Tue Jul 20 17:29:18 2010 us=795525 10.208.251.225:1194 Data Channel Decrypt: Cipher 'BF-CBC' initialized with 128 bit key
Tue Jul 20 17:29:18 2010 us=795640 10.208.251.225:1194 Data Channel Decrypt: Using 160 bit message hash 'SHA1' for HMAC authentication
Tue Jul 20 17:29:18 2010 us=875477 10.208.251.225:1194 Control Channel: TLSv1, cipher TLSv1/SSLv3 EDH-RSA-DES-CBC3-SHA, 1024 bit RSA
Tue Jul 20 17:29:18 2010 us=875664 10.208.251.225:1194 [k4laptop] Peer Connection Initiated with 10.208.251.225:1194
Tue Jul 20 17:29:18 2010 us=875864 k4laptop/10.208.251.225:1194 MULTI: Learn: 10.10.0.6 -> k4laptop/10.208.251.225:1194
Tue Jul 20 17:29:18 2010 us=875983 k4laptop/10.208.251.225:1194 MULTI: primary virtual IP for k4laptop/10.208.251.225:1194: 10.10.0.6
Tue Jul 20 17:29:19 2010 us=974500 k4laptop/10.208.251.225:1194 PUSH: Received control message: 'PUSH_REQUEST'
Tue Jul 20 17:29:19 2010 us=974701 k4laptop/10.208.251.225:1194 SENT CONTROL [k4laptop]: 'PUSH_REPLY,route 10.10.0.0 255.255.255.0,route 172.26.18.160 255.255.255.224,route 172.26.17.0 255.255.255.0,route 10.142.3.128 255.255.255.192,route 172.26.18.130 255.255.255.255,route 172.26.18.132 255.255.255.255,route 172.26.18.134 255.255.255.255,route 10.142.4.16 255.255.255.240,route 10.10.0.0 255.255.255.0,ping 10,ping-restart 120,ifconfig 10.10.0.6 10.10.0.5' (status=1)

OpenVPN настроен и к бою готов :)
Осталось запустить NAT, ip_forwarding и создать правила для ipfilter т.к. мы не хотим, чтобы на ip адрес, где крутится сервер заходили кто-либо, кроме клиентов VPN.

Включаем forwarding.
root@netra # routeadm -e ipv4-forwarding
root@netra # routeadm

Configuration Current Current
Option Configuration System State
---------------------------------------------------------------
IPv4 forwarding enabled enabled
IPv4 routing enabled disabled
IPv6 forwarding disabled disabled
IPv6 routing disabled disabled

Проверяем наличие нужных нам пакетов
root@netra # svcs | grep pf
online 16:07:02 svc:/network/pfil:default
online 17:52:58 svc:/network/ipfilter:default

На данный момент службы уже работают. Включить/выключить/рестартануть их можно с помощью утилиты svcadm.
root@netra # ifconfig -a
lo0: flags=2001000849 mtu 8232 index 1
inet 127.0.0.1 netmask ff000000
bge0: flags=1100843 mtu 1500 index 2
inet 10.10.60.4 netmask fffffff0 broadcast 10.10.60.15
ether 0:14:4f:d6:48:ae
bge2: flags=1100843 mtu 1500 index 4
inet 172.26.18.179 netmask ffffffe0 broadcast 172.26.18.191
ether 0:14:4f:d6:48:b0
tun0: flags=10011008d1 mtu 1500 index 19
inet 10.10.0.1 --> 10.10.0.2 netmask ffffffff


bge0 - интерфейс для входа vpn клиентов, bge2 - для выхода под его адресом (nat), tun0 - драйвер vpn.
В данной конфигурации OpenVPN настроен так, что все клиенты будут соединяться с именно этим интерфейсом, а не создавать при каждом подключении новый, как в случае с pptpd. Но, следует помнить, что каждое соединение - это пара ip адресов.
Собственно, ipfilter. Создаем файл /etc/ipf/ipf.conf
root@netra # cat /etc/ipf/ipf.conf
block in on bge0 from any
pass in on bge0 proto tcp/udp to port = 1194

pass in on bge0 proto icmp from any to any icmp-type 8 code 0
pass out on bge0 proto icmp from any to any icmp-type 0 code 0

pass in on bge0 proto icmp from any to any icmp-type 0 code 0
pass out on bge0 proto icmp from any to any icmp-type 8 code 0

Закрываем всё, кроме порта OpenVPN для bge0. Теперь Nat. Нужно 2 файла.

root@netra # cat pfil.ap
#le -1 0 pfil
#qe -1 0 pfil
#hme -1 0 pfil
#qfe -1 0 pfil
#eri -1 0 pfil
#ce -1 0 pfil
bge -1 0 pfil
#be -1 0 pfil
#vge -1 0 pfil
#ge -1 0 pfil
#nf -1 0 pfil
#fa -1 0 pfil
#ci -1 0 pfil
#el -1 0 pfil
#ipdptp -1 0 pfil
#lane -1 0 pfil
#dmfe -1 0 pfil

Убираем комментарий, с драйвера интерфейса, где будет работать NAT. И, непосредственно, правила для NAT.
root@netra # cat ipnat.conf
map bge2 10.10.0.0/24 -> 172.26.18.179/32 portmap tcp/udp auto
map bge2 10.10.0.0/24 -> 172.26.18.179/32


Даем рестарт службам pfil, ipfilter. Готово.