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

Problem with BGP Session

Problem
You want to figure out why the BGP session is not being established.

Solution
Start by looking at the current state of the TCP sessions on the router:

aviva@RouterF> show system connections extensive



Also look at the information in the system logging files:

aviva@RouterF> show log messages



Check that the TCP session can pass Internet control packets:

aviva@RouterF> ping tos 0xc0 RouterD



Discussion
When two BGP peers have a problem establishing a BGP session, one of the first indications is that you see BGP hold-time expired error messages on the routers in the router's system logging files. You also see that the State field in the show bgp neighbor command output is not Established and that the State field in the show bgp summary command is Active or Connect, indicating that the BGP session is not established.

The hold-time expired errors usually occur because the TCP session between a pair of peers cannot effectively transmit data between the routers, not because of a problem with BGP itself. When the TCP session doesn't work properly, the BGP session times out, and BGP signals the problem by sending hold-time expired messages and generating a BGP Notification message to the remote peer. Notification messages are logged at the system logging severity level warning.

Some of the most frequent causes of hold-time expired errors are MTU issues on a directly connected link, issues related to forwarding of Internet control packets, and IGP failures on IBGP sessions.

Looking at the TCP MTU path behavior, first let's look at the TCP session. By default, a TCP session transmits 576 bytes in a single packet to minimize the chances that the packet will be fragmented at a device along the path to the destination. Most links use an MTU of at least 1,500 bytes. Path MTU discovery, which is disabled by default in the JUNOS BGP, allows BGP to dynamically determine how large the packets can be in a TCP session without being fragmented. This means that BGP tries to use 576-byte packets for the TCP sessions. However, on directly connected EBGP sessions, TCP uses MTU-sized packets. If there is an MTU mismatch between the two sides of the TCP connection, the BGP session cannot be established. One workaround is to enable path MTU discovery within the BGP group:

[edit protocols bgp group external ]
aviva@RouterF# set mtu-discovery



When path MTU discovery is enabled, the don't fragment ( DF) bit is set on all TCP packets sent by the BGP session.

When you are testing session connectivity, in addition to the standard ping command, send packets in which the Internet control CoS bit is set:

aviva@RouterF> ping tos 0xc0 RouterD



If the QoS parameters are misconfigured on a transit router, TCP connectivity can work for regular best-effort traffic but will break for Internet control traffic. The same behavior can happen when you are testing new software or new PICs.

Another way to get information about the TCP session and what might be malfunctioning is to look at the current state of TCP sessions:

aviva@RouterF> show system connections extensive | find tcp
tcp4 0 2 192.168.70.143.23 172.17.28.108.3350 ESTABLISHED
sndsbcc: 2 sndsbmbcnt: 256 sndsbmbmax: 266432
sndsblowat: 2048 sndsbhiwat: 33304
rcvsbcc: 0 rcvsbmbcnt: 0 rcvsbmbmax: 463360
rcvsblowat: 1 rcvsbhiwat: 57920
iss: 2677798142 sndup: 2677853922 sndcc: 0
snduna: 2677853922 sndnxt: 2677853924 sndwnd: 57920
sndmax: 2677853924 sndcwnd: 65535 sndssthresh: 1073725440
irs: 1577022682 rcvup: 1577023284 rcvcc: 0
rcvnxt: 1577023292 rcvadv: 1577081212 rcvwnd: 57920
rtt: 200130618 srtt: 301 rttv: 12
rttmin: 100 duration: 0 mss: 1448
flags: REQ_SCALE RCVD_SCALE REQ_TSTMP RCVD_TSTMP [0x1e0]



Also, use the information in the system logging files, which is very extensive and is similar to the output of the show system connections extensive command:

Aug 24 13:15:46 RouterF rpd[2797]: bgp_traffic_timeout: NOTIFICATION sent to 192.168.
14.1 (Internal AS 3356): code 4 (Hold Timer Expired Error), Reason: holdtime expired
for 192.168.14.1 (Internal AS 3356), socket buffer
sndcc: 0
rcvcc: 0 TCP state: 4,

snd_una: 1404695285
snd_nxt: 1404695285
snd_wnd: 16384
rcv_nxt: 4086106368
rcv_adv:
4086157473, keepalive timer 0



You can learn a lot of information about the TCP connection from the socket buffer information in the system logging message, which is a subset of BSD transmission control block ( TCB) parameters:



sndcc

Bytes on send buffer. A full send buffer typically means that packets from this host are not being acknowledged.



rcvcc

Bytes on receive buffer. Expect 0 bytes here because RPD should not declared a hold time expired if information is available about the buffer.



snd_una



snd_nxt

The difference between these two (snd_nxtsnd_una) is the amount of unacknowledged data on the TCP session.



snd_wnd

Size of the window advertised by the peer.



rcv_adv



rcv_nxt

The difference between these two (rcv_advrcv_nxt) is the size of the window advertised by the local TCP stack.

It is important to try to collect the information on both sides of the session. This gives an indication about whether the data path failure is unidirectional, bidirectional, or dependent on packet size.

If you are seeing hold-time expired errors between IBGP peers, check the IGP logs. If this correlates to a link failure in your IGP, this should probably be your starting point for diagnostics.

See Also
For information about BSD TCBs, see TCP/IP Illustrated (Addison-Wesley).

понедельник, 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. Готово.

пятница, 28 мая 2010 г.

SSH tunnelling

Сначала своими словами. Простой пример. Необходимо зайти на веб сервер по шифрованому соединению... ну или воспользоваться любой другой службой этого сервера секьюрно. Там стоит sshd.



На машине клиенте ssh -L 1234:localhost:80 om@192.168.1.1. Это означает, что с 1234 порта ip адреса 127.0.0.1 пакет будет перенаправлен на адрес 192.168.1.1 порт 80 внутри SSH трубы. Для проверки вбейте в адресной строке браузера http://localhost:1234.

Далее оригинал статьи. http://www.brandonhutchinson.com/ssh_tunnelling.html



ssh tunnelling is an excellent way to tunnel insecure protocols through a secure communication channel. In this example, I'll tunnel POP3 traffic using ssh. Traditional POP3 traffic, including username and password information, travels clear-text across the network.

OpenSSH is used in the following examples.

To tunnel POP3 traffic using ssh:

1. Make sure an ssh client is installed on your machine and an ssh server is installed on the POP3 server.

2. Create a local ssh tunnel on your machine (port 1234 for this example) to the POP3 server's port 110. You will need to be the root user to bind to "privileged" ports (< 1024).
# ssh -f -N -L 1234:localhost:110 user@POP3_server

3. Test the tunnel.
$ telnet localhost 1234
You should see the POP3 server's banner information.

4. Configure your mail client to access your mail via POP3 using mail server localhost and port 1234.

"Reverse" ssh tunnel
It is possible to create a "reverse" ssh tunnel. The reverse tunnel will allow you to create an ssh tunnel from your work computer to your home computer, for example, and then login to your work machine from your home machine even if your work firewall does not permit ssh traffic initiated from your home machine!

For this to work, an ssh server must be installed on your work and home computer, and ssh (TCP port 22) must be allowed outbound from your work computer to your home computer.

$ ssh -R remote_port:localhost:22 your_home_computer

ex. $ ssh -R 2048:localhost:22 home.computer.com

At home, you would then run ssh -p 2048 localhost to log into your work computer via ssh.

Маршрутизация в Solaris 10 без reboot.

Enable/Disable IP Forwarding in Solaris 10 without reboot
April 24, 2008 · Filed Under Networking, Solaris 10


IP packet forwarding is the process of routing packets between network interfaces on one system. A packet arriving on one network interface and addressed to a host on a different network is forwarded to the appropriate interface.

In Solaris 10, IP Forwarding can be enabled or disabled using the routeadm & ifconfig commands as against the ndd commands in Solaris 9 and earlier. The advantage is the change dynamic and real-time and the change persist across reboot unlike the ndd command.

Enable/Disable IP Forwarding globally

To globally enable IP Forwarding in Solaris 10 use the routeadm command as follows:

In IPv4

solaris10# routeadm -e ipv4-forwarding

In IPv6

solaris10# routeadm -e ipv6-forwarding

The switches “-e” enables IP Forwarding.

To disable IP Forwarding

In IPv4

solaris10# routeadm -d ipv4-forwarding

In IPv6

solaris10# routeadm -d ipv6-forwarding

The switches “-d” enables IP Forwarding.

After the change run the following command for the changes to take effect.

solaris10# routeadm -u

Enable/Disable IP Forwarding per interface

To enable IP Forwarding on a specific interface (say ce0) using the ifconfig command

In IPv4

solaris10# ifconfig ce0 router

In IPv6

solaris10# ifconfig ce0 inet6 router

To disable IP Forwarding for an interface (say ce0)

In IPv4

solaris10# ifconfig ce0 -router

In IPv6

solaris10# ifconfig ce0 inet6 -router

Взял тут
http://www.sunsolarisadmin.com/solaris-10/enabledisable-ip-forwarding-in-solaris-10-without-reboot/

среда, 28 апреля 2010 г.

Serial Console on Sun Servers

Есть у меня кластер. В нём стоят два v445. К каждому подключен Storage. От serial B сервера до serial A storage идёт консольный кабель. Я задался вопросом "Как из под солярки выйти на СериалБ". Нагуглил классную статейеку.

http://www.softpanorama.org/Solaris/Startup_and_shutdown/serial_console_on_solaris.shtml

First of all you need null model cable. Specialists of old school can solder their own but this art is essentially lost :-).

Sun server usually come with one crossover 9-pin connector (silver colored -- Sun Part No. 530-3100-01). Don't throw it out when you get with the server ;-). This connector can be used with a regular Ethernet cable. That's the most convenient solution for server rooms as you can use cable of any necessary length to position your laptop conveniently or get to the desktop or workstation (if connecting to a Sun workstation or server, use 25 pin connector --- Sun Part No. 530-2889-03 or equivalent). You can also create you own or buy equivalent or use ready made cable used for managing network devices like Cisco.

V210 and V240 have two management port: one serial management (marked SER MGT) and one Net management ( marked NET MGT). You need to use serial management port. Net management port is used to connect to ALOM and you need to configure it before that.

There are two typical way to use serial console for connecting to Sun servers, for example, V210 and V240.

* Use Windows laptop with some Windows emulator (Hyperterminal, Teraterm, etc).
* Use Sun terminal emulator (tip), in Windows SFU or nearby Sun machine or if you have a laptop with Solaris installed.

No keyboard should be connected to the server/workstation on which you plan to use serial console. Sun machines on power-up check the presence of the keyboard. If something is plugged in, they assume the console input device is the keyboard. If it doesn't see any keyboard, it redirects console input/output to serial port "A".

Whether or not the Sun server has a videocard ("framebuffer" card) installed is irrelevant. Some Sun workstations have a framebuffer built in. That's why the test is always done for the keyboard presence.

Do not connect a keyboard to the Sun machine if you want to use serial console

If you SHUT OFF YOUR TERMINAL, while it is connected to a running Sun machine, you send a "break" signal via the serial line and the Sun will jump back into the OK prompt, halting the OS. This can cause considerable confusion.
Using Window Hyperterminal

Note: you can upgrade to free version 6.3 (non-commercial use)

Try these COM1 port settings:

* Bits per second: 9600
* Data bits: 8
* Parity: None
* Stop bits: 1
* Flow Control: None

I'm going to use a Dell C600 laptop an an example. The laptop has a 9pin serial port at the back that corresponds to Serial port 1 (SER 1). In other cases you need first to verify that you're "speaking" to the correct port (you can do this using for example serial mouse and disconnecting your current mouse).

Using windows terminal you can use VT-100 or better.

You can connect to Sun server that has no keyboard or display attached anytime. sometimes you need to press enter one of two times to see the output. You can disconnect anytime by disconnecting cable (do not close you terminal).
Using Tip

Note: tip is available in SFU and Solaris /etc/remote can be used with it. Connect the appropriate serial cable from serial port on laptop (usually serial port 1) to serial port A on target Sun system.

Use "tip hardwire" (not "hardware") to open a connection to the headless box before booting it: From a Solaris shell prompt on the local system, issue the command:

tip hardwire

OR

tip ser1

Notes

* This is "tip hardwire" (not "tip hardware").
* ser1 should be defined in /etc/remote (see below)

hardwire is defined on Solaris in the /etc/remote to use port B (for laptop you need to correct this or add another line, see below):

cuab:dv=/dev/cua/b:br#2400
dialup1|Dial-up system:\
:pn=2015551212:tc=UNIX-2400:
hardwire:\
:dv=/dev/term/b:br#9600:el=^C^S^Q^U^D:ie=%$:oe=^D:
tip300:tc=UNIX-300:
tip1200:tc=UNIX-1200:
tip0|tip2400:tc=UNIX-2400:
tip9600:tc=UNIX-9600:
tip19200:tc=UNIX-19200:
UNIX-300:\

If you need to connect from serial port A you need to modify this entry in /etc/remote or better add another entry, for example ser1 :

ser1:\
:dv=/dev/term/a:br#9600:el=^C^S^Q^U^D:ie=%$:oe=^D:

After tip session established you can boot the server. This tip session should be kept active as long as server remains online.
You should be connected. Press enter a few times to see if you are getting a response. If you are not, check your connections and make sure you have the right cable.

From within tip, you can access a tip menu by pressing ~? after a carriage return. To quit the tip session, press ~. and to send a break character, type ~#

To send a break character, type ~#


The hardwire parameter in the tip command refers to an entry in the file /etc/remote which describes the serial port connections. By default, hardwire specifies port B with 9600 baud, 8 data bits, no stop bits, and 1 parity bit. Connect, via a null modem, serial port "A" of the Sun to your terminal's serial port. Your terminal settings should be 9600 8N1, which are the default serial settings of the Sun.

If you use tip, if possible, emulate a SUNTERM.


Behavior of the Serial Console

Now, depending upon the machine you have, and the revision of your PROM, you'll either be greeted by a ">" prompt or an "ok" prompt. Machines that have everything configured properly and a working OS will of course, begin to boot by themselves rather than displaying a prompt.

If you want to stop the boot from happening so you can wipe out the OS to install something else (or just perform maintenence) or make changes to the NVRAM, then, before the OS starts to load from the HD, (essentially, right after it tells you the hardware ethernet address, but before it says "boot device"), you need to send a "break" signal.

* On a PC, this is done by holding down the CTRL key and tapping the "Break" key (Pause/Break on most PC keyboards).
*

tip sends break via "~#"

Once you've sent a break, as above, you'll be greeted by "OK" prompt (FORTH interpreter prompt).

вторник, 20 апреля 2010 г.

SUN Solaris ALOM

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

Hello colleagues,

Please see the steps that needs to be done in order to arrange remote access to SASN from MM. IP addresses used below are the fake ones. Please update instruction for each region.

1. Connect SASN Ethernet ALOM port to the switch where VLAN serving MM is available. Alternatively if there is a lack of ports on the switch but there is spare interface on MM you can connect SASN Ethernet ALOM and MM directly. In the latter case you can just use IP addresses from example...
2. Connect PC RS-232 port with Serial DB9-RJ45 cable to the SASN Serial ALOM port. Start Terminal program on PC with standard settings (9600, 8N1)
3. Connect power cables to the SASN. After that ALOM will be started. You should see login prompt in a while.
4. Login to the SASN ALOM. User: root. Password: changeme
5. Configure SASN ALOM Remote management via network:
-> cd /SP/network
-> set pendingipaddress=10.10.10.10
-> set pendingipnetmask=255.255.255.0
-> set pendingipgateway=10.10.10.1
-> set pendingipdiscovery=static
-> set commitpending=true
6. Verify network configuration:
-> show /SP/network
7. Login to MM and try ssh to SASN ALOM IP
ssh root@10.10.10.10 (password changeme)

Please let me know if you have any questions regarding this procedure.

BR/ Nickolay

Прочитал я в очередной раз. Эх, думаю, "освежу ка я в памяти процедуру". Зашел на терминальник, в порт, куда подключена, ещё не нагруженная, двести сороковая netra последовательным портом. Консоль. Набираю заветные "#." (решетка-точка) для входа в ALOM.

Copyright 2007 Sun Microsystems, Inc. All rights reserved.
Use is subject to license terms.


Sun(tm) Advanced Lights Out Manager 1.6.7 (radius2-rnd)

Please login:

Набираю указанные выше заветные default login/password и.. не пускает. Перебрал всё что помнил - нет. И вот вопрос. Что делать дальше? Вот об этом я и решил написать. Есть замечательная команда scadm.

USAGE: scadm [options]
For a list of commands, type "scadm help"

scadm - COMMANDS SUPPORTED
help, date, set, show, resetrsc, download, send_event, modem_setup,
useradd, userdel, usershow, userpassword, userperm, shownetwork,
loghistory, version

scadm - COMMAND DETAILS
scadm help => this message
scadm date [-s] | [[mmdd]HHMM | mmddHHMM[cc]yy][.SS] => print or set date
scadm set => set variable to value
scadm show [variable] => show variable(s)
scadm resetrsc [-s] => reset SC (-s soft reset)
scadm download [boot] => program firmware or [boot] monitor
scadm send_event [-c] "message" => send message as event (-c CRITICAL)
scadm modem_setup => connect to modem port
scadm useradd => add SC user account
scadm userdel => delete SC user account
scadm usershow [username] => show user details
scadm userpassword => set user password
scadm userperm [cuar] => set user permissions
scadm shownetwork => show network configuration
scadm loghistory => show SC event log
scadm version [-v] => show SC version (-v verbose)

Вот, собственно, и всё.

root@radius2-rnd # scadm usershow

username permissions password
-------- ----------- --------
admin cuar Assigned

И следующая команда, конечно же, scadm userpassword => set user password.

Просмотрим, что вообще настроено.

root@radius2-rnd # scadm show
if_network="true"
if_modem="false"
if_connection="telnet"
if_emailalerts="false"
sys_autorestart="xir"
sys_bootrestart="none"
sys_bootfailrecovery="none"
sys_maxbootfail="3"
sys_xirtimeout="900"
sys_boottimeout="120"
sys_wdttimeout="60"
netsc_tpelinktest="true"
netsc_dhcp="false"
netsc_ipaddr="0.0.0.0"
netsc_ipnetmask="255.255.255.0"
netsc_ipgateway="0.0.0.0"
mgt_mailhost=""
mgt_mailalert=""
sc_customerinfo=""
sc_escapechars="#."
sc_powerondelay="false"
sc_powerstatememory="false"
sc_clipasswdecho="true"
sc_cliprompt="sc"
sc_clitimeout="0"
sc_clieventlevel="2"
sc_backupuserdata="true"
sys_eventlevel="2"

Все эти параметры можно поменять из консоли и из терминала (из под root).

вторник, 16 марта 2010 г.

java script redirect

Уже постил в блоге php redirect. Вот тоже самое на java script.


script language=javascript window.location="http://172.26.18.179/cgi-bin/sgsn2_eqtrunk.pl";

script

вторник, 9 марта 2010 г.

MYSQL user management

Нашёл в своих доках две полезные заметки по MYSQL.

Сброс пароля пользователя root в mysql.

Наша память, к сожалению, нас иногда подводит. И мы никак не можем вспомнить железно, как нам кажется, отпечатанный в памяти пароль. Вы можете сказать, что нужно иметь записную книжку а лучше две, и конечно будете правы. Но… Тем не менее иногда все-таки возникает необходимость восстановления забытого, либо утраченного пароля. Сегодня я опишу простой метод восстановления пароля суперпользователя root для базы данных mysql.

Для этого необходимо выполнить всего несколько шагов.
1. Останавливаем mysql.
service mysqld stop
2. Запускаем mysql следующей командой:

/usr/bin/mysqld_safe --skip-grant-tables --user=root &

3. Запускаем клиента mysql
mysql -u root
4. Выполняем sql запрос
UPDATE mysql.user SET Password=PASSWORD(’newpwd’) WHERE User=’root’;
где newpwd – новый пароль.
5. Применяем изменения
FLUSH PRIVILEGES;
6. Выходим из mysql клиента выполнив в нем команду exit
7. Перегружаем mysql сервер.
service mysqld restart

Ну и все на этом. Пароль суперпользователя root для базы данных mysql изменен. Добавлю, что конечно же этот метод описан в официальном руководстве по mysql, но может кому пригодится.

Оригинал: http://dedicatesupport.com/archives/30

И вторая:

Как создать пользователя mysql через cli

Небольшой пост о том, как создавать из командной строки mysql новую базу данных и нового пользователя mysql с полными правами на только что созданную базу.
mysql -uroot -p CREATE DATABASE ; GRANT ALL PRIVILEGES ON .* TO 'my_user'@'localhost' IDENTIFIED BY 'my_password' WITH GRANT OPTION;

Для того чтобы выставить новому пользователю полные права на все базы данных используем следующую команду:
GRANT ALL PRIVILEGES ON *.* TO 'my_user'@'localhost' IDENTIFIED BY 'my_password' WITH GRANT OPTION;

Доступ к базе для данного пользователя возможен только с localhost. Если вы хотите дать ему доступ к базе с любого хоста, используете % вместо localhost:
GRANT ALL PRIVILEGES ON .* TO 'my_user'@'%' IDENTIFIED BY 'my_password' WITH GRANT OPTION;

четверг, 25 февраля 2010 г.

ssh deny user

Полезная вещь.

Allow only some users to login
Ok, you now have disabled root login, but any user account on your system will be authorized to remote login. This brings a lot of issues, because more users, means more distributed logins, more chances to security issues (imagine one of your users being kidnapped by a alien, you never know). So authorize one user (you), and if needed, other users, but only if needed. I hope you never left sshd_config, because now we have to search for the line “AllowUsers”. If this line doesn’t exist, add it, in the “#Authentication” part of the file, and specify the users you want to allow login. Example: “AllowUsers user1 user2“. Easy right? Let’s continue.

Оригинал: http://blog.dbugs.org/2007/08/29/ssh-security/

среда, 10 февраля 2010 г.

Postgesql опять

Я уже писал, что поставил себе на Солярку посгри. Мне очень интересно сравнить эту базу с mysql. Есть у меня скрипт для набивки базы данными из лог файлов.. вот и решил протестить, но столкнулся с небольшой трудностью. Нужно объяснить perl как работать с postgre.
Устанавливаю модуль DBI:Pg, до этого установив DBI соответственно. Он ругнуося на версию модуля Version :) Поставил самую последнюю. Пишу тестовый скрипт.

#! /usr/bin/perl

use DBI;
my $dbh = DBI->connect("DBI:Pg:dbname=test;host=localhost", "admin", "admin", {'RaiseError' => 1});

Запускаю.

install_driver(Pg) failed: Can't load '/usr/local/lib/perl5/site_perl/5.8.8/sun4-solaris/auto/DBD/Pg/Pg.so' for module DBD::Pg: ld.so.1: /usr/bin/perl: fatal: libpq.so.5: open failed: No such file or directory at /usr/local/lib/perl5/5.8.8/sun4-solaris/DynaLoader.pm line 230.
at (eval 3) line 3
Compilation failed in require at (eval 3) line 3.

Ну я почему-то сразу решил, что у меня нет DynaLoader.pm :) Полез на CPAN, но понял.. что-то не то :) Запустил поиск, нашёл файл. Открываю его стоку номер 230.

my $libref = dl_load_file($file, $module->dl_load_flags) or
croak("Can't load '$file' for module $module: ".dl_error());

Открыл файлик README в исходниках. Читаю.

* PostgreSQL library issues:

DBD::Pg uses the libpq library that comes with Postgres. If the shared libpq
library is not available, DBD::Pg will error with a message that
usually mentions a file names libpq.so, like this:

Can't load './blib/arch/auto/DBD/Pg/Pg.so' for module DBD::Pg: libpq.so.5: cannot open
shared object file: No such file or directory at .../DynaLoader.pm line 230.

This means that the libraries are not installed in a place where the system
can find them when it tries to load the Pg.so file. On some systems, you
can run /sbin/ldconfig -v to see a list of shared modules, or just search
the system for the file with "locate libpq.so". If it exists but is not being
loaded, you may need to add the directory it is in to /etc/ld.so.conf file
and run the ldconfig command. Otherwise, you may need to add the path to

Ищу файл libpq.so.5. Нашёл его тут - /usr/local/pgsql/lib/.
Смотрю что у меня в env.

-bash-3.00$ env
TERM=xterm
SHELL=/usr/bin/bash
SSH_CLIENT=172.26.17.101 3482 22
SSH_TTY=/dev/pts/4
USER=om
LD_LIBRARY_PATH=/usr/openwin/lib
MAIL=/var/mail//om
PATH=/usr/sbin:/usr/bin:/usr/ccs/bin:/usr/openwin/bin:/usr/dt/bin:/usr/platform/SUNW,Netra-240/sbin:/opt/sun/bin:/opt/SUNWvts/bin:/usr/local/pgsql/bin/
PWD=/var/om/perl_script_poly
TZ=Europe/Moscow
SHLVL=1
HOME=/var/om
LOGNAME=om
SSH_CONNECTION=172.26.17.101 3482 172.26.18.179 22
DISPLAY=localhost:11.0
_=/usr/bin/env
OLDPWD=/var/om

Добавляю в файл .profile следующие строки:
LD_LIBRARY_PATH=/usr/openwin/lib:/usr/local/pgsql/lib/
export LD_LIBRARY_PATH

Перелогинюсь. Всё ок, путь появился.

Запускаю скрипт всё - всё ок.

Поймал себя на мысли, что мануалы я читаю в последнюю очередь в моменты отчаяния. :)

четверг, 4 февраля 2010 г.

Sed

Открыл для себя программку sed. Очень удобная штука. Смысл в том, что она находит по содержание, соответствующее шаблону в файле и меняет на также определенный шаблон, после чего результать выводит в STDOUT.

sed 's/чтоискать/начтозаменить/' имяфайла

Для наглядности я создал файл file1.

-bash-3.00$ cat file1
file
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve

Что нужно сделать для того, чтобы заменить искомое выражение на шаблон и записать это в файл. Сразу хочется сделать так - "sed 's/six/HelloHello/' < file1 > file1". Отрываем file1, а там пусто :)

Сработает следующая конструкция.

-bash-3.00$ sed 's/six/HelloHello/' file1 > /tmp/1 ; cat 1 > file1 ; rm /tmp/1 ; cat file1

file
one
two
three
four
five
HelloHello
seven
eight
nine
ten
eleven
twelve

Я думаю, что найдется масса случаев, где можно применять эту программу.

вторник, 2 февраля 2010 г.

Process management in Solaris

В Solaris вместо команды top принято использовать похожую по функциональности команду prstat.

Кроме этого, в Solaris для удобства получения информации о процессах с определенными именами есть команда

pgrep имя

Она является эквивалентом команды

ps –ef | grep имя

С помощью pargs можно посмотреть, какие аргументы переданы конкретному процессу и какая у него среда окружения:

pargs 2793
2793: dtterm -name Run -xrm *menuBar: False -iconic -map -e /usr/dt/
bin/dtexec -open
argv[0]: dtterm
argv[1]: -e
argv[2]: /usr/dt/bin/dtexec
argv[3]: -open
argv[4]: -1
argv[5]: -ttprocid
argv[6]: 2.10fX-r 01 648 1289637086 1 1 0 192.168.5.33 5 sunny_105_1
argv[7]: /export/home/mozilla_bin/sfw/bin/mozilla
argv[8]:
argv[9]: -open
argv[10]: -1
argv[11]: -ttprocid
argv[12]: 2.10fX-r 01 648 1289637086 1 1 0 192.168.5.33 5 sunny_105_1
argv[13]: /export/home/mozilla_bin/sfw/bin/mozilla

pargs -e 2793
2793: dtterm -name Run -xrm *menuBar: False -iconic -map -e /usr/dt/
bin/dtexec -open
envp[0]: AB_CARDCATALOG=/usr/dt/share/answerbooks/ru_RU.UTF-8/
ab_cardcatalog
envp[1]: DISPLAY=:0.0
envp[2]: DTAPPSEARCHPATH=//.dt/appmanager:/etc/dt/appconfig/
appmanager/%L:/etc/dt/appconfig/appmanager/C:/usr/dt/appconfig/
appmanager/%L:/usr/dt/appconfig/appmanager/C
envp[3]: DTDATABASESEARCHPATH=//.dt/types,/etc/dt/appconfig/types/%L,/
etc/dt/appconfig/types/C,/usr/dt/appconfig/types/%L,/usr/dt/appconfig/
types/C

Вывод команды pargs значительно сокращен, ключ –e требует вывести все содержимое среды окружения, а для графических программ типа dtterm, как в нашем примере, среда окружения весьма велика.

Команда prstat позволяет в динамике, подобно команде top, отслеживать состояние процессов:

prstat

PID USERNAME SIZE RSS STATE PRI NICE TIME CPU PROCESS/NLWP
3576 root 3412K 868K run 13 0 0:00:02 6,3% find/1
353 root 45M 19M sleep 59 0 0:02:30 0,2% Xsun/1
753 root 15M 3620K run 49 0 0:00:02 0,1% dtterm/1
3577 root 6640K 4108K cpu0 49 0 0:00:00 0,1% prstat/1
205 root 2872K 624K sleep 59 0 0:00:00 0,0% nscd/18
895 root 123M 21M sleep 49 0 0:00:49 0,0% soffice.bin/4
667 root 1844K 488K sleep 59 0 0:00:00 0,0% rpc.rstatd/1
217 root 5364K 536K sleep 59 0 0:00:00 0,0% lpsched/1
324 root 4360K 196K sleep 59 0 0:00:00 0,0% snmpdx/1
240 root 1100K 288K sleep 59 0 0:00:00 0,0% utmpd/1
343 root 4892K 0K sleep 59 0 0:00:00 0,0% vold/3
276 root 3240K 0K sleep 59 0 0:00:00 0,0% htt/1
633 root 3784K 0K sleep 59 0 0:00:00 0,0% sdt_shell/1
657 root 16M 2496K sleep 49 0 0:00:00 0,0% dtfile/1
203 root 4484K 568K sleep 59 0 0:00:00 0,0% cron/1
189 root 5636K 1092K sleep 59 0 0:00:00 0,0% syslogd/13
168 daemon 2444K 820K sleep 59 0 0:00:00 0,0% statd/1
156 root 2412K 688K sleep 59 0 0:00:00 0,0% inetd/1
172 root 2160K 748K sleep 59 0 0:00:00 0,0% lockd/2
229 root 1348K 0K sleep 59 0 0:00:00 0,0% powerd/2
133 root 2212K 604K sleep 59 0 0:00:00 0,0% rpcbind/1
Total: 61 processes, 161 lwps, load averages: 0,25, 0,17, 0,27

Вы можете получить информацию только о тех процессах, которые запущены вами. Пользователь root может получть информацию о любых процессах.

среда, 13 января 2010 г.

Cacti backup script

Много времени прошло с момента поднятия cacti на серваке. Написал скрипт для бэкапа, который рекурсивно копирует папку cacti со всеми скриптами и файлами графиков, сливает mysql базу и всё это заворачивает в tar и gzip. Можт кому будет интересно.

Собственно листинг:

#/usr/bin/bash

TMPDIR=/space/cacti_bkp
CACTIDIR=/usr/local/apache2/htdocs/cacti
BKPDIR=/space/
BKP=cacti_bkp

if test -d $TMPDIR
then rm -r $TMPDIR; mkdir $TMPDIR
else mkdir $TMPDIR
fi

echo "Copying files.."
(cp -R $CACTIDIR $TMPDIR)
wait

echo "Making SQL dump.."
/usr/local/mysql/bin/mysqldump -ucactiuser -pcactiuser --opt cacti > $TMPDIR/cacti_base.sql

echo "TARing files.."
tar cf $BKPDIR/$BKP.tar $TMPDIR

rm -r $TMPDIR
echo "GZIPing files.."

gzip -9 $BKPDIR/$BKP.tar
chown cacti:cacti $BKPDIR/$BKP.tar.gz
mv $BKPDIR/$BKP.tar.gz $BKPDIR/$BKP`date '+_%Y%m%d_%H%M%S'`.tar.gz

Результат работы скрипта:

-rw-r--r-- 1 cacti cacti 178235269 Jan 10 08:17 cacti_bkp_20100110_082232.tar.gz
-rw-r--r-- 1 cacti cacti 178720071 Jan 13 07:46 cacti_bkp_20100113_075147.tar.gz


В cron:
15 8 * * 0 sh /space/cacti_bkp.sh 1>/dev/null &
20 8 * * * find /space/*.gz -mtime 28 -exec rm {} \;

Первая строка собственно бэкап, вторая ищет старые бэкапы и трёт их.