net-acct & NAT

aleks

Старожил
Тут возникла небольшая проблема: поставил на машинку с Linux(kernel-2.4.26) и 2-я сетевыми интерфейсами(eth0 внутрь, eth1 наружу+SNAT) PPTPd (MSChap_V2,MPPE,MPPC, но не суть). Подключаюсь, поднимаются ppp0, ppp1 и т.д. Для SNAT прописал
Код:
$IPTABLES -A FORWARD -i $EXTIF -o ppp+ -m state --state ESTABLISHED,RELATED \
 -j ACCEPT
$IPTABLES -A FORWARD -i ppp+ -o $EXTIF -j ACCEPT
$IPTABLES -t nat -A POSTROUTING -o $EXTIF -j MASQUERADE
Туда же netacct-mysql-0.73. Конфиг naccttab:

Код:
database file                   # "mysql" or "file"
                                # choose to write in mysql or in
                                # /var/log/net-acct
                                # now it works :)

mysql_user acct                 # usually you don't need to change this

mysql_password acct_password    # change this to your password

mysql_host localhost            # sometimes you need to change this to
                                # 127.0.0.1 instead of localhost

mysql_database netacct          # usually you don't need to change this

mysql_table accounting          # table name

pidfile  /var/run/nacctd.pid    # set pid file
                                # tis will help if you want to
                                # two (or more) nacctd on same machine

#compactnet 172.18.3.0  255.255.255.0

                                # log only summary day trafic for this network
                                # patch by Boril

flush 180                       # flush every 5 minutes
                                # this gives the interval in seconds
                                # when the accumulated data is flushed
                                # to the output file

fdelay 60                       # this defines after how many seconds
                                # of inactivity a certain record of
                                # traffic information may be written out
                                # this helps making the logfiles smaller
                                # since only one output record will be
                                # generated for related traffic

file /var/log/net-acct          # defines output file
                                # this is the regular output file of
                                # the daemon

dumpfile /var/log/net-acct-dump # defines dump file
                                # this is used to dump the not yet
                                # written information so this is not
                                # lost should the machine crash
                                # on startup an eventuelly existing
                                # file of this name will be moved
                                # to *.o

notdev eth0                     # Dont log entries for this device
                                # Use this on routers that you dont
                                # log forwarded packets twice.

device eth1                     # device to put into promiscous mode
                                # you can specify as many as you want
                                # and you don't have to specify one
                                # (e.g. if this runs on your router)
                                #
                                # if you plan to use it on some *BSD
                                # system put here apropriate device
                                # i.e. - device ep0

#iflimit eth1                   # on machines with multiple interfaces,
                                # log only packets on this interface
                                # mutually exclusive with hostlimit

#ignoremask 255.255.255.0        # Ignore traffic on same class C net
                                # This means traffic that is on
                                # your local LAN is not counted.
                                # This is useful for NFS etc.
                                # Not giving this option causes everything
                                # to be counted.
                                # This can degrade performance seriously!

ignorenet 127.0.0.0 255.0.0.0   # ignore loopback net
                                # You can define as many ignorenets as
                                # you want. Ignoring a net with
                                # ignorenet is not as efficient as
                                # ignoremask. Thus you should exclude
                                # your local network with ignoremask,
                                # not with ignorenet (although this is
                                # is possible).

#ignorenet 172.18.3.0 255.255.255.0

#masqif  10.2.12.** # if compiled with -DREMAP_MASQUERADE:
 # ipnumber you are masquerading as,
 # this remaps ip/port for incoming
 # connections (e.g. ftp-data) to ip/port
 # of the masqueraded destination

debug 4                         # set debugging level
debugfile /tmp/nacctd.debug     # where to put debugging info

# Device configuration
# Defines where the real data starts for each type of interface
# First give the name prefix, then the offset in bytes to the start
# of the real data, then the offset of the type field in bytes. If
# there is no type field, just give a 0.
# Don't specify SLIP or PPP devices here, otherwise association of
# dynamic ip-addresses with usernames won't work
# Put device types with more traffic last.

#headers        tr      40      38
headers lo      14      12
#headers        isdn    4       0
# headers isdn  14      0       # for hdlc/trans/cisco and hdlc/trans/raw
headers eth     14      12
#headers        plip    14      12

# For dynamic slip/ppp

#dynamicip /var/run             # where files for dynamic ip are stored
#dynamicnet 202.36.94.0 255.255.255.0   # on which network are all the
                                        # dynamically assigned adresses

#exclude-name-lookup    202.36.94.1     255.255.255.255
#exclude-name-lookup    202.36.94.253   255.255.255.255

# hostlimit 12.34.56.78         # log only packets to/from this host
# hostlimit 34.56.78.12         # and this one too
                                # this option is mutually exclusive with iflimit

# For disabling certain fields
# This is commented out by default
# Field 7 is disabled by default so we match the old (pre 0.5) output format
# Now everything is disableb by default and it works ... if you disable
# src_ip address it will write empty cell in mysql or data_size it will
# write 0 in mysql
#
# disable 2                     # disable output of protocol
# disable 3                     # disable output of source address
# disable 4                     # disable output of source port
# disable 5                     # disable output of destination address
# disable 6                     # disable output of destination port
disable 7                       # disable output of packets count
# disable 8                     # disable output of byte count
# disable 9                     # disable output of device name
# disable 10                    # disable output of user name
# disable 11                    # disable output of duration
# disable 12                    # disable output of peering flag

# For excluding certain hosts from ignoring
# This can be useful for a kludgy way to account for proxy traffic, you'd then
# add your proxy server here.
# I guess I should consider using some filter language...
# This is commented out by default
# This does not affect addresses excluded by ignoremask,
# as this would impose too much of a performance penalty
# dontignore 127.3.4.5 255.255.255.255  # Don't ignore host 127.3.4.5,
                                        # although it would be excluded by
                                        # above ignorenet statement

# line sl0 ttyS0                # One way to
                                # assign traffic to a user is if both
                                # of the following conditions meet:
                                # a) nacctd runs on the ppp/slip server
                                # b) the relation between network interface
                                # (e.g. sl0, ppp1) and serial line (e.g.
                                # ttyS1) is fixed.
                                # You can give as many line statements
                                # as you want
                                # There is a better way now, so this is
                                # commented out

Так вот проблема: в логе данные только о трафике с внешнего интерфейса машины.
Пробовал указать параметр masqif, так при старте ругается, что не знает такого и в интернете про это параметр ничего нет..
 

LKr

Старожил
комментарий читал?

Код:
#masqif  10.2.12.** # if compiled with -DREMAP_MASQUERADE:
 

aleks

Старожил
LKr":6zpgqlvc сказал(а):
комментарий читал?
Код:
#masqif  10.2.12.** # if compiled with -DREMAP_MASQUERADE:
извини, потом дописал
Пробовал указать параметр masqif, так при старте ругается, что не знает такого и в интернете про это параметр ничего нет..
 

LKr

Старожил
Да, в общем считалка конечно не лучший выбор...
Давно не обновляется.
При большом траффике может пропускать мимо...
При потере коннекта с mysql тоже беда случается.
Что-то еще очень неприятное было, не помню уже, дааавно игрался.
А, еще она детальный траф перестала писать в базу с версии 0.71 вроде...
 

LKr

Старожил
aleks":339usrzq сказал(а):
Пробовал указать параметр masqif, так при старте ругается, что не знает такого и в интернете про это параметр ничего нет..

тоже потом дописал:
Код:
if compiled with -DREMAP_MASQUERADE:
при компиляции-то указал?

Во, вспомнил, под старинными 2.4 она не собиралась с маскарадом, хотела какие-то заголовки от 2.2...
 

aleks

Старожил
да у меня как видишь в файл...
и большого трафика тут не должно быть.
детально не пишется как раз после 0.73 вроде как.
И чем тогда её можно заменить?
 

aleks

Старожил
LKr":2waa18zk сказал(а):
aleks":2waa18zk сказал(а):
Пробовал указать параметр masqif, так при старте ругается, что не знает такого и в интернете про это параметр ничего нет..
тоже потом дописал:
Код:
if compiled with -DREMAP_MASQUERADE:
при компиляции-то указал? Во, вспомнил, под старинными 2.4 она не собиралась с маскарадом, хотела какие-то заголовки от 2.2...

Код:
 ./configure --enable-DREMAP_MASQUERADE=yes
так указывать?
 

LKr

Старожил
aleks":l701aa6y сказал(а):
да у меня как видишь в файл... и большого трафика тут не должно быть. детально не пишется как раз после 0.73 вроде как. И чем тогда её можно заменить?

ну... под 2.4 самое простое поискать что-нть считающее через ULOG (тож терять будет, но приблуд много) или через QUEUE (с точностью до байта, но если обсчитывать не успевает - скорость падает)
все это ессно про NetFilter AKA iptalbes
у нас самописное, хотя в последнее время уже появляются проекты в инете...
 

LKr

Старожил
aleks":128le20e сказал(а):
Код:
 ./configure --enable-DREMAP_MASQUERADE=yes
так указывать?

а у configure --help есть такая опция?
в обычном netacct вроде прям в Makefile эта строчка была, её просто раскомментировать надо было.
 

aleks

Старожил
./configure --help Usage: configure [options] [host] Options: [defaults in brackets after descriptions] Configuration: --cache-file=FILE cache test results in FILE --help print this message --no-create do not create output files --quiet, --silent do not print `checking...' messages --version print the version of autoconf that created configure Directory and file names: --prefix=PREFIX install architecture-independent files in PREFIX [/usr/local] --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX [same as prefix] --bindir=DIR user executables in DIR [EPREFIX/bin] --sbindir=DIR system admin executables in DIR [EPREFIX/sbin] --libexecdir=DIR program executables in DIR [EPREFIX/libexec] --datadir=DIR read-only architecture-independent data in DIR [PREFIX/share] --sysconfdir=DIR read-only single-machine data in DIR [PREFIX/etc] --sharedstatedir=DIR modifiable architecture-independent data in DIR [PREFIX/com] --localstatedir=DIR modifiable single-machine data in DIR [PREFIX/var] --libdir=DIR object code libraries in DIR [EPREFIX/lib] --includedir=DIR C header files in DIR [PREFIX/include] --oldincludedir=DIR C header files for non-gcc in DIR [/usr/include] --infodir=DIR info documentation in DIR [PREFIX/info] --mandir=DIR man documentation in DIR [PREFIX/man] --srcdir=DIR find the sources in DIR [configure dir or ..] --program-prefix=PREFIX prepend PREFIX to installed program names --program-suffix=SUFFIX append SUFFIX to installed program names --program-transform-name=PROGRAM run sed PROGRAM on installed program names Host type: --build=BUILD configure for building on BUILD [BUILD=HOST] --host=HOST configure for HOST [guessed] --target=TARGET configure for TARGET [TARGET=HOST] Features and packages: --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) --enable-FEATURE[=ARG] include FEATURE [ARG=yes] --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) --x-includes=DIR X include files are in DIR --x-libraries=DIR X library files are in DIR --enable and --with options recognized: --with-libpcap-includes=DIR libcap include directory --with-libpcap-libraries=DIR libcap library directory --with-hashsize=number set custom HASH_SIZE --with-mysql=DIR mysql install directory
в Makefile тоже чего-то не нашёл про DREMAP_MASQUERADE
в net-acct-0.71 есть!
 

LKr

Старожил
нашел в старинных backup'ах :)
netacct-0.71-glibc2 (кста, если в файл - нафига тебе -mysql версия?)
именно в Makefile:
Код:
# Uncomment for IP masquerade support
MASQ=-DREMAP_MASQUERADE

именно эта версия в свое время стабильно работала у нас... но давно... и на 2.2.19 еще :)
потом выкинули т.к. не устраивала.
 

LKr

Старожил
aleks":3amzkq3r сказал(а):
ок, сейчас его скомпилю.

неа...
получишь то же самое
Код:
process.c:242: `PORT_MASQ_BEGIN' undeclared (first use in this function)
process.c:242: (Each undeclared identifier is reported only once
process.c:242: for each function it appears in.)
process.c:243: `PORT_MASQ_END' undeclared (first use in this function)

в 2.4 маскарад совсем по-другому делается, нежели чем в 2.2
 

LKr

Старожил
aleks":3laz3ia8 сказал(а):
в последнее время уже появляются проекты в инете...
хм... ты про http://oobilling.ru/ ? Что-то всё там слишком мудрёно, NetBilling как-то попроще... и вообще заработает ли?...

Да не, я про считалки...
Просто раньше все через pcap работали, потом появились через ULOG, а в последнее время попадаются и на IPQ (QUEUE)
Названий не скажу, т.к. не актуально совсем стало :)
 

aleks

Старожил
Да не, я про считалки...
на такущём этапе меня это мало интересует.
Сейчас главное чтобы там не было бесконтрольности.
На самом деле только Web трафик хватит считать, но через SQUID бывает слишком не точно, а детишек как известно обманывать нехорошо :)
PPTP тоже не на 100% не решает проблему, т.к. есть двупользовательские машины с обобщёнными сетевыми интерфейсами (в доках написано что это есть хорошо :( )...
Короче тут специфика сильная(учёт по пользователям, не привязанным к IP) и для полного решения следует SQUID как следует перепахать.
 

LKr

Старожил
Не надо его пахать, настрой на нем самом авторизацию и парси логи, там будет имя пользователя/че скачал AFAIR
 

aleks

Старожил
LKr":3rpfsptu сказал(а):
Не надо его пахать, настрой на нем самом авторизацию и парси логи, там будет имя пользователя/че скачал AFAIR
Да SAMS ( http://linux.perm.ru/projects/sams/ ) поставлю, только вот что пишут(не только они, везде об этом):
Если у пользователя лимит трафика составляет 100Мб, он скачал 98Мб и поставил на закачку фильм (700Мб), то фильм он скачает - это особенность работы SQUID, после чего, во время обработки логов SQUID он будет отключен. Чтобы избежать этого - SQUID надо пропатчить (вроде бы патч лежит здесь: http://bspu.secna.ru/~swp/local-patches/squid). Патч заставляет SQUID писать в логи информацию о закачке файла порциями, например по 100Кб. Сам этот патч я не пробовал и судить о его работе не берусь. Если пользователь начал закачку файла из броузера и увидев, что файл слишком большой, прервал ее, файл будет скачан SQUIDом и занесен в статистику пользователю.
patch-aa, который упоминается почему-то ни у кого не работает :)
 
Верх