четверг, 17 ноября 2016 г.

Boot Multiple ISO from USB via Grub2 using Linux

Boot ISO Files directly from USB using Grub2 from Linux. Here is one way to create a Multiboot USB Flash Drive from a running Ubuntu (I used the Live CD). You may eventually need a large Flash Drive or USB Hard Drive in order to include every bootable ISO entry. I will add more Bootable ISO files to the grub.cfg file as I find time to test them. Contact me to submit working Bootable Linux ISO grub.cfg entries for inclusion.
I. Format your USB Flash Drive to use a Single Partition:
  1. Open a terminal and type sudo su
  2. Type fdisk -l (and note which device is your USB Drive)
  3. Type fdisk /dev/sdx (replacing x with your actual usb device)
  4. Type d (to delete the existing partition)
  5. Type n (to create a new partition)
  6. Type p (for primary partition)
  7. Type 1 (to create the first partition)
  8. Press Enter (to use the first cylinder)
  9. Press Enter again (to use the default value as the last cylinder)
  10. Type a (for active)
  11. Type 1 (to mark the first partition active "bootable")
  12. Type t (for partition type)
  13. Type c (to use fat32 partition)
  14. Type w (to write the changes and close fdisk)
II. Create a Fat32 Filesystem on the USB Flash Drive:
  1. Type umount /dev/sdx1 (to unmount the mounted partition)
  2. Type mkfs.vfat -F 32 -n MULTIBOOT /dev/sdx1 (to format the partition as fat32)
III. Install Grub2 on the USB Flash Drive:
Important Note:
Old versions of grub used --root-directory=/mnt/USB
while current versions use --boot-directory=/mnt/USB/boot
If you use the wrong syntax, you will receive an error stating "Installation is impossible. Aborting"
  1. Type mkdir /mnt/USB && mount /dev/sdx1 /mnt/USB (replacing x with your actual usb device)
  2. Type grub-install --force --no-floppy --boot-directory=/mnt/USB/boot /dev/sdx(replacing x with your actual USB device)
  3. Type cd /mnt/USB/boot/grub (to change directory)
  4. Type wget pendrivelinux.com/downloads/multibootlinux/grub.cfg (to get the grub.cfg file)
IV. Adding the Bootable ISO files:
  1. Type cd /mnt/USB (assuming USB is still mounted… else repeat section III. (part 1))
  2. Simply click a tab below, and follow the instructions for each ISO Distro you would like to add.
Adding an Unlisted ISO: To try ISO Files that are not yet listed, use the existing menuentry examples in /boot/grub/grub.cfg and append any options normally found in the distributions syslinux.cfg file on the "append" line to the "linux" line of the menu entry.
Please inform me of entries you get to work and I will add them to the list, so that others may benefit as well.
V. Last Step… Test to ensure your USB Device Boots into Grub2:
Reboot your Computer, and enter your BIOS or Boot Menu. Set the Boot Order to boot from the USB Device. Save your changes and Reboot. If all goes well, you should be presented with a Grub2 Boot Menu.

понедельник, 18 июля 2016 г.

NAT64 + DNS64

1. Общая схема процесса:

2. Настройка DNS64(пример для debian):
root@sneaky-work:/home/kim# cat /etc/bind/named.conf.options 
acl "ipv6net1" { 2A02:x:x:x::/40; ::1;};

options {
        directory "/var/cache/bind";

        // If there is a firewall between you and nameservers you want
        // to talk to, you may need to fix the firewall to allow multiple
        // ports to talk.  See http://www.kb.cert.org/vuls/id/800113

        // If your ISP provided one or more IP addresses for stable 
        // nameservers, you probably want to use them as forwarders.  
        // Uncomment the following block, and insert the addresses replacing 
        // the all-0's placeholder.

        dns64 2A02:x:x:x::/64 {
                recursive-only yes;
                clients { any; };
                mapped { any; };
                exclude { 2A02:x:x:x:1::/64; 64:ff9b::/96; };
        };

        forwarders {
                 2A02:x:x:x::116;
                 2001:4860:4860::8844;
                 2001:4860:4860::8888;
        };

//      allow-query { "ipv6net1"; };

        //========================================================================
        // If BIND logs error messages about the root key being expired,
        // you will need to update your keys.  See https://www.isc.org/bind-keys
        //========================================================================
        dnssec-validation auto;

        auth-nxdomain no;    # conform to RFC1035
        listen-on-v6 { any; };
};


Где:
2A02:x:x:x::/40 - весь ipv6 префикс, который будет пользоваться натом.
2A02:x:x:x::/64 - префикс для ната, dns будет преобразовывать AAA ответ в AAAA, и пользоваться этим префиксом.
2A02:x:x:x:1::/64

3.Сам NAT64:

ipv6 unicast-routing
ipv6 dhcp pool ipv6dhcp
 address prefix 2A02:x:x:x:1::/64
 dns-server 2A02:x:x:x:1::2
interface TenGigabitEthernet0/1/0
 ip address x.x.x.3 255.255.255.248
 ipv6 address 2A02:y:y:y::y:34/125
 ipv6 enable
 nat64 enable
interface BDI1110
 no ip address
 ipv6 address 2A02:x:x:x:1::1/64
 ipv6 enable
 ipv6 nd na glean
 ipv6 nd managed-config-flag
 ipv6 nd other-config-flag
 ipv6 nd router-preference High
 ipv6 dhcp server ipv6dhcp
 nat64 enable
ip route 0.0.0.0 0.0.0.0 x.x.x.1
!
ipv6 route ::/0 2A02:y:y:y::y:33 unicast
!
!
!         
ipv6 access-list ACLv6
 sequence 20 permit ipv6 2A02:x:x:x:1::/64 any
!

nat64 prefix stateful 2A02:x:x:x::/64
nat64 v4 pool pool1 111.111.111.111 111.111.111.113
nat64 v6v4 list ACLv6 pool pool1 overload


Запись микропрограммы в линейную карту ALC на Zyxel IES5000

Замену микропрограммы нужно производить по приведенной ниже схеме. Откройте терминальную программу HyperTerminal из состава Windows, установив работу через COM-порт (например, прямое соединение COM1). Скорость последовательного порта установите равной 9600 бит/с и отключите управление потоком. 


Перед заменой микропрограммы нужно вытащить плату управления (MSC-1000), иначе линейные карты в режиме отладки (в Debug Mode) будут находиться не более 30 сек.


- При загрузке линейной карты, в терминальной программе вы увидите сообщение:

Press any key to enter Debug Mode within 3 seconds
- нажмите любую клавишу, чтобы перейти в режим отладки (Debug Mode);
- дайте команду ATBA5, чтобы установить скорость консольного порта 115200;
- поменяйте скорость порта в терминальной программе;
- дайте команду ATUR и подождите, пока линейная карта ответит "Starting XMODEM upload", чтобы начать передачу файла с микропрограммным обеспечением (*.bin);
- в программе HyperTerminal обратитесь к меню "Передача" (Transfer) и выберите "Отправить файл" (Send file). В открывшемся окне выберите протокол передачи файлов X-модем и укажите программе, в каком месте на жестком диске находится требуемый файл. Затем нажмите кнопку "Отправить" (Send);  
- после успешной загрузки микропрограммы линейная карта должна автоматически перезагрузиться;
- измените скорость порта в коммуникационной программе снова на 9600 бит/с и зайдите в режим отладки (Debug Mode);
- дайте команду ATLC и подождите, пока линейная карта ответит "Starting XMODEM upload", чтобы начать передачу файла с заводскими настройками (*.rom). Обращаем ваше внимание, что все установки линейной карты будут сброшены на настройки по умолчанию;
 - после успешной загрузки файла конфигурации линейная карта должна автоматически перезагрузиться. Если этого не произошло, дайте команду ATGO, чтобы перезагрузить ее.


оригинал: https://zyxel.ru/kb/1511/

Аппаратный сброс линейной карты xDSL-коммутатора Zyxel IES5000

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

Попытайтесь выполнить следующие действия:
  1. Управляющий контроллер MSC может автоматически выполнить рестарт линейной карты. Если линейная карта не отвечает, используйте команду lcman reset, которая выполнит аппаратный сброс (hardware reset) линейной карты.
  2. Попытайтесь переставить линейную карту в другой слот коммутатора.
  3. Если указанные шаги не привели к рабочему состоянию карты, используйте команду lcman disable. Затем подключитесь к консольному порту карты и восстановите (запишите) микропрограмму.
  4. После восстановления микропрограммы в линейной карте используйте команду lcman enable, которая включает управление линейными картами.
Процедура записи микропрограммного обеспечения для линейной карты описана в следуюшей статье - БЗ-1511

Оригинал: https://zyxel.ru/kb/1555/

понедельник, 30 мая 2016 г.

Забираем список хостов для Rancid из Zabbix

Простой скрипт на Pythonвыполняющий выгрузку через Zabbix API (из нужной группы) списка хостов для Rancid


Предварительно нужно установить PyZabbix
pip install pyzabbix

Сам скрипт:
#!/usr/bin/python
from zabbix_api import ZabbixAPI

zapi = ZabbixAPI(server="https://zabbix.local")
zapi.login("login", "password")

f = open('/var/lib/rancid/network/router.db', 'w')

rows = zapi.host.get({'output': ['hostids', 'name', 'status'], 'groupids': ['8']})

if (rows != 0) and (len(rows) != 0):
 for h in rows:
  hid = h['hostid']
  
  if h['status'] == '0':
   rstatus = "up"
  else: rstatus = "down" 
  
  ipadr = zapi.hostinterface.get({'output': ['ip'], 'hostids' : hid, 'filter':{'main':1}})
  line = (ipadr[0]['ip'] + ":cisco:" + rstatus + ':"' + h['name'] + '"').encode('utf-8')
  f.write (line + '\n')
f.close()

Дальше запускаем скрипт кроном: 
* /6 * * *  rancid  python /home/zabbix/scripts/rancid-zb-api.py > /dev/null 2>&1

вторник, 19 апреля 2016 г.

Script for block tor exit node for iptables

#!/bin/bash

# A simple bash script to block IP traffic from TOR exit nodes.
# written by Andrew Vetlugin (antrew at gmail com)

wget='/usr/bin/wget'
iptables='/sbin/iptables'
url='https://torstatus.blutmagie.de/ip_list_exit.php/Tor_ip_list_EXIT.csv'

iptables_target='DROP'
#iptables_target='REJECT'

# Quick guide:

# 1. add a separate chain for a list of TOR exit nodes
# (this should be done by hand once)
# iptables -N TOR_BLOCK

# 2. add a rule to INPUT chain
# Note: if you want to be able to connect to any TOR exit node yourself
# (e.g., if $url is a exit node you should be able to fetch a list of exit
# nodes from it) then you should add this rule AFTER accepting established
# and related connections)
# iptables -A INPUT -j TOR_BLOCK

# 3. add this script to crontab (I think 10-20 minutes interval should be OK)

# flush chain
$iptables -F TOR_BLOCK

# return to parent chain if the source is not TOR exit node
$iptables -I TOR_BLOCK -j RETURN

# add TOR exit nodes to TOR_BLOCK chain with $iptables_target rule
for node in `$wget -q --no-check-certificate -O - $url | sort | uniq`; do
        $iptables -I TOR_BLOCK -s $node -j $iptables_target
done


оришинал - http://doc.norang.ca/iptables.html#sec-4-4-1

среда, 2 марта 2016 г.

Архивация содержимого папки с последующим удалением

#!/bin/bash
#Purpose = Backup of Important Data
#Run this script on cron
#START
TIME=`date +%d%m%y`             # This Command will add date in Backup File Name.
FILENAME=configs_$TIME.tar.gz   # Here i define Backup file name format.
SRCDIR=/srv/ftp/cfg             # Location of Important Data Directory (Source of backup).
DESDIR=/srv/ftp                 # Destination of backup file.
/bin/tar -cpzf $DESDIR/$FILENAME $SRCDIR
if [ -f $DESDIR/$FILENAME ]; then
  /usr/bin/find $SRCDIR/* -delete
else
 echo "Archive whith name $FILENAME in folder $DESDIR not found!"
fi

#END

вторник, 23 февраля 2016 г.

Поиск сбежавшей памяти

RAM: ps -eo size,pid,user,command | awk '{ hr=$1/1024 ; printf("%13.6f Mb ",hr) } { for ( x=4 ; x<=NF ; x++ ) { printf("%s ",$x) } print "" }' | sort

SWAP:
root@sneaky-work:/home/kim# cat ./swap.sh SUM=0 OVERALL=0 for DIR in `find /proc/ -maxdepth 1 -type d -regex "^/proc/[0-9]+"` do PID=`echo $DIR | cut -d / -f 3` PROGNAME=`ps -p $PID -o comm --no-headers` for SWAP in `grep VmSwap $DIR/status 2>/dev/null | awk '{ print $2 }'` do let SUM=$SUM+$SWAP done if (( $SUM > 0 )); then echo "PID=$PID swapped $SUM KB ($PROGNAME)" fi let OVERALL=$OVERALL+$SUM SUM=0 done echo "Overall swap used: $OVERALL KB"

среда, 3 февраля 2016 г.

Instructions on how to monitor onions w/ Nagios

Requirements

Working Nagios setup and the following packages.
  • tor / torsocks
    • For Debian, follow Tor Project Debian Instructions summarized here:
      • echo deb http://deb.torproject.org/torproject.org jessie main > /etc/apt/sources.list.d/tor.list
      • echo deb-src http://deb.torproject.org/torproject.org jessie main >> /etc/apt/sources.list.d/tor.list
      • gpg --keyserver keys.gnupg.net --recv 886DDD89
      • gpg --export A3C4F0F979CAA22CDBA8F512EE8CBC9E886DDD89 | apt-key add -
      • apt-get update
      • apt-get install tor torsocks deb.torproject.org-keyring

Nagios setup

  • Add the following new command to your Nagios configuration to monitor various types of onions:
define command {
    command_name        check_http_tor
    command_line        /usr/bin/torsocks /usr/lib/nagios/plugins/check_http -H '$HOSTADDRESS$' -I  '$HOSTADDRESS$' '$ARG1$'
    }
define command {
    command_name        check_ssh_tor
    command_line        /usr/bin/torsocks /usr/lib/nagios/plugins/check_ssh -H '$HOSTADDRESS$' '$ARG1$'
    }

define command {
    command_name        check_tcp_tor
    command_line        /usr/bin/torsocks /usr/lib/nagios/plugins/check_tcp -H '$HOSTADDRESS$' '$ARG1$'
    }
  • Apply the service check to a host:
define host {
    use                 generic-host            ; Name of host template to use
    host_name           samplea8s7df23jh7.onion
    alias               Sample Fake Onion
    address             samplea8s7df23jh7.onion
    check_command       check_http_tor!-p 8080
}


define service {
    use                 generic-service     ; name of template to use
    host_name           samplea8s7df23jh7.onion
    service_description SSH
    check_command       check_ssh_tor!-p 8492
}

define service {
    use                 generic-service     ; name of template to use
    host_name           samplea8s7df23jh7.onion
    service_description XMPP
    check_command       check_tcp_tor!-p 5222
}

Источник https://github.com/coldhakca/monion

суббота, 30 января 2016 г.

SSH as a Hidden Service

SSH as a Hidden Service

It is relatively easy to make your SSH server available as a hidden service accessible only through the Tor network. There are several reasons you might want to do this.
  1. You can access your server anonymously.
  2. You can access your server from the open internet even if it is hidden behind a firewall and it has a dynamically assigned IP address.
The downside to using the Tor network to access your server is that the network is not particularly fast.

Tor

On a server, you can run tor as a always-on service. Typically tor acts as a socks proxy, allowing you anonymous access to the tor network from your server. Running it as an always-on service means that it is always available as an anonymous proxy. In this case, it will also be configured to provide access to your SSH server as a hidden service as well. In this case, your hidden service is always available.
Alternatively, you can run tor on demand. You typically do this on a workstation. In this case you would run tor whenever you want to hidden service to be available.

Tor as Service

To install tor on a Fedora system, as root run:
yum install tor
You would configure it by editing the file /etc/tor/torrc, but for now it can be left as is. Start tor with:
systemctl start tor
You should not be able to use it as a socks proxy. The default proxy port is 9050, so you should be able to configure your browser to use a socks5 proxy with address localhost:9050 to test it.
If you would like a GUI tool to monitor and control your tor server, install vidalia:
yum install vidalia
Normally vidalia will start and control its own copy of tor. If you want to use it to control the system tor, you will need to configure vidalia and tor accordingly (in /etc/tor/torrc you will need to set HashedControlPassword, and in ~/.vidalia/vidalia.conf you need to set ControlPassword).

Tor on Demand

If you instead plan to run tor on demand, install both tor and vidalia as root:
yum install tor vidalia
Once you do this, you no longer need be root, you can run vidalia and tor as a normal user.
You would start tor by running vidalia. When you do so, vidalia will open a window that shows the status of tor, but you can close it. You would reopen it as needed by clicking on the onion in your status bar.
You should not be able to use tor as a socks proxy now. The default proxy port is 9050, so you should be able to configure your browser to use a socks5 proxy with address localhost:9050 to test it.
In this situation, the tor configuration file, torrc, is found in ~/.vidalia.

Configuring Your Hidden Service

To configure SSH as a hidden service, simply add the following to your torrc file and restart tor:
HiddenServiceDir <directory>
HiddenServicePort 22 127.0.0.1:22
where <directory> should be set to something like /var/lib/tor/ssh if you are running tor as a service and should be set to something like .vidalia/ssh if you are running tor on demand.
Once you restart tor, you should visit the directory you specified. In it will find the file hostname and private_key. Keep private_key secure. If a bad guy got a hold of this file, they could spoof your hidden service. The address of your hidden service is contained in hostname.
Once you create a hidden service, it will be listed in a directory that is publicly available. If you want to keep it really hidden, so nobody else could possibly find or use it, add the following to you hidden service description:
HiddenServiceDir <directory>
HiddenServicePort 22 127.0.0.1:22
HiddenServiceAuthorizeClient stealth clientname1,clientname2,clientname3
In this case, you can specify as many clients as you wish. Each client will get its own address and a password that allows access from that client. These addresses are not published in to directory. They can be found in <directory>/hostname.

Using Your Hidden Service

Accessing your hidden service requires two things. First, you must be running tor on your client machine as well. Then, you must tell your ssh client to proxy through tor. Starting tor is as simple as running vidalia. To tell your ssh client to use tor as a proxy requires that you specify that it use:
ncat --proxy 127.0.0.1:9050 --proxy-type socks5 %h %p
as the proxy command. The easiest was of doing that is to configure a host entry in ~/.ssh/config for you hidden service. To do so, add something like the following:
# Media host as Tor hidden service
host hidden
   hostname 7ei66g5djlymzxqb.onion
   proxyCommand ncat --proxy 127.0.0.1:9050 --proxy-type socks5 %h %p
Then simply running:
ssh hidden
should get you access to your server.
If you took the extra step of hiding your hidden service using HiddenServiceAuthorizeClient, you will need to add an entry to your torrc file before you will allowed access:
HidServAuth 7ei66g5djlymzxqb.onion op6npnLTq2NtpQVZqLJilB
This line contains the address of your hidden service, and the authorization string that was found in <directory>/hostname.


Оригинал - http://www.nurdletech.com/linux-notes/ssh/hidden-service.html

четверг, 28 января 2016 г.

LTE E392 & linux cli

root@RPi2-mobile:/etc/ppp# cat /etc/ppp/peers/4g
connect "/usr/sbin/chat -f /etc/ppp/4g"
/dev/ttyUSB0
115200
crtscts
noauth
novj
novjccomp
nobsdcomp
nopcomp
noaccomp
noccp
receive-all
#debug

usepeerdns
defaultroute

user ""
password ""
root@RPi2-mobile:/etc/ppp# cat /etc/ppp/4g
TIMEOUT 35
ECHO ON
ABORT '\nBUSY\r'
ABORT '\nERROR\r'
ABORT '\nNO ANSWER\r'
ABORT '\nNO CARRIER\r'
ABORT '\nNO DIALTONE\r'
ABORT '\nRINGING\r\n\rRINGING\r'
ABORT '\nUsername/Password Incorrect\r'
'' \rAT
OK 'AT+CGDCONT=1,"IP","internet.mts.ru"'
OK ATD*99#
CONNECT ""

вторник, 12 января 2016 г.

проверка и автоматическая установка туннеля VPNC

root@RPi2-mobile:~# crontab -l
# Edit this file to introduce tasks to be run by cron.
* * * * *  /usr/local/sbin/vpnc-keepalive 10.X.X.1 10.Y.Y.1 &

root@RPi2-mobile:~# cat /usr/local/sbin/vpnc-keepalive
#!/bin/sh
#
# Restart VPNC if both of the specified hosts on the command line are unavailable

if ! [ $(ping -q -c 1 ${1} 2>&1 | grep "1 packets received" | sed "s/.*\(1\) packets received.*/\1/") ] ||
   ! [ $(ping -q -c 1 ${2} 2>&1 | grep "1 packets received" | sed "s/.*\(1\) packets received.*/\1/") ]; then
    echo Not alive $1 or $2, restarting VPNC
    /etc/init.d/vpnc restart
else
echo Alive $1 or $2
fi