[Asterisk] Asterisk Manager Interface(AMI)

AMI

Asterisk Manager Interface(AMI)는 Asterisk 에서 제공하는 System monitoring/Management interface 이다. 즉, 이벤트 모니터링과 명령 전달을 위한 Interface 란 뜻이다.

AMI 간단 설정

기본적으로 AMI는 disable 로 되어 있다.
AMI를 활성화 하기 위해서는 /etc/asterisk/manager.conf 파일 수정이 필요하다.
/etc/asterisk/manager.conf 파일을 통해서 AMI 접속에 관한 설정을 해주고, /etc/asterisk/manager.d 디렉토리 밑에 각각의 접속에 대한 계정을 설정해준다.

예제로 hello 라는 계정에 world 라는 패스워드를 가진 계정을 추가해보자.

;
; Turn on the AMI and ask it to only accept connections from localhost
;
; By default asterisk will listen on localhost only.
[general]
enabled = yes
webenabled = yes
port = 5038
bindaddr = 192.168.200.10

; No access is allowed by default.
; To set a password, create a file in /etc/asterisk/manager.d
; use creative permission games to allow other serivces to create their own
; files
#include "manager.d/*.conf"

그리고 /etc/asterisk/manager.d 디렉토리 밑에 hello.conf 라는 파일을 하나 추가하자.

pchero@MyDebian:/etc/asterisk/manager.d$ cat hello.conf

; ami configure file for [hello]
[hello]
secret = world
read = all
write = all

이로써, AMI 로 접근이 가능한 hello 라는 계정이 생성되었다. 주의할 점은 아직 TLS/SSL 설정이 안되어있기 때문에 보안에 매우 취약하다는 점이다.

 

AMI 접속 테스트

이제 AMI에 접속해보자. Asterisk는 여러가지 AMI 접속 방법을 제공하는데… 먼저 telnet 부터 접속해보자.

pchero@MyGalaxy:~$ telnet 192.168.200.10 5038
Trying 192.168.200.10...
Connected to 192.168.200.10.
Escape character is '^]'.
Asterisk Call Manager/1.1
Action: Login
Username: hello
Secret: world

Response: Success
Message: Authentication accepted

Event: FullyBooted
Privilege: system,all
Status: Fully Booted

Action: Ping

Response: Success
Ping: Pong
Timestamp: 1395059659.619558

Action: Logoff

Response: Goodbye
Message: Thanks for all the fish.

Connection closed by foreign host.
pchero@MyGalaxy:~$

이번에는 HTTP 를 통한 접속을 해보자.

pchero@MyGalaxy:~$ wget "http://192.168.200.10:8088/rawman?action=login&username=hello&secret=world" --save-cookies cookies.txt -O -
--2014-03-17 13:36:55--  http://192.168.200.10:8088/rawman?action=login&username=hello&secret=world
Connecting to 192.168.200.10:8088... connected.
HTTP request sent, awaiting response... 200 OK
Length: 55 [text/plain]
Saving to: ‘STDOUT’

0% [                                                                                                                                              ] 0           --.-K/s              Response: Success
Message: Authentication accepted

100%[=============================================================================================================================================>] 55          --.-K/s   in 0s

2014-03-17 13:36:55 (6.75 MB/s) - written to stdout [55/55]

pchero@MyGalaxy:~$ wget "http://192.168.200.10:8088/rawman?action=ping" --load-cookies cookies.txt -O -
--2014-03-17 13:37:35--  http://192.168.200.10:8088/rawman?action=ping
Connecting to 192.168.200.10:8088... connected.
HTTP request sent, awaiting response... 200 OK
Length: 63 [text/plain]
Saving to: ‘STDOUT’

0% [                                                                                                                                              ] 0           --.-K/s              Response: Success
Ping: Pong
Timestamp: 1395059855.098176

100%[=============================================================================================================================================>] 63          --.-K/s   in 0s

2014-03-17 13:37:35 (6.22 MB/s) - written to stdout [63/63]

pchero@MyGalaxy:~$ wget "http://192.168.200.10:8088/rawman?action=logoff" --lo
--load-cookies=    --local-encoding=
pchero@MyGalaxy:~$ wget "http://192.168.200.10:8088/rawman?action=logoff" --load-cookies cookies.txt -O -
--2014-03-17 13:38:07--  http://192.168.200.10:8088/rawman?action=logoff
Connecting to 192.168.200.10:8088... connected.
HTTP request sent, awaiting response... 200 OK
Length: 56 [text/plain]
Saving to: ‘STDOUT’

0% [                                                                                                                                              ] 0           --.-K/s              Response: Goodbye
Message: Thanks for all the fish.

100%[=============================================================================================================================================>] 56          --.-K/s   in 0s

2014-03-17 13:38:07 (6.51 MB/s) - written to stdout [56/56]

 

AMI Protocol

AMI 에는 두가지 종류의 메시지가 있다. Manager event 와 manager Action 이다.

Manager Event는 단방향 메시지 전송이며, 메시지는 Asterisk 에서 AMI client로 전송된다. 주로 Asterisk에서 일어난 내용을 접속중인 AMI client로 Notice 하기 위해 사용한다.

Manager Action은 양방향 메시지 전송이며, AMI client 에서 Asterisk로 요청 메시지를 보내고, Asterisk는 처리 결과와 응답메시지를 보내는 방식으로 통신한다.

 

Message Encoding

모든 AMI message들(manager event, manager action, manager action response)은 같은 방식으로 인코딩된다. 모든 메시지들은 text-based 이고, Carriage return 과 Line-feed 기호로 끝맺음된다. 메시지 마지막은 공백 라인으로 끝이난다.

Header1: This is the first header<CR><LF>
Header2: This is the second header<CR><LF>
Header3: This is the last header of this message<CR><LF>
<CR><LF>

Events

모든 Manager event 는 항상 Event header 와 Privilege header 를 포함한다. Event header 에는 해당 event의 이름이, Privilege header 에는 해당 event 의 권한 레벨정보가 표시된다. 다른 헤더들은 해당 event 의 내용에맞는  내용들이 표시된다.

Event: Hangup
Privilege: call,all
Channel: SIP/0004F2060EB4-00000000
Uniqueid: 1283174108.0
CallerIDNum: 2565551212
CallerIDName: Russell Bryant
Cause: 16
Cause-txt: Normal Clearing

Action

모든 manager action 메시지들은 반드시 Action header 를 포함해야 한다. Action header 는 이 메시지가 어떤 명령에 대한 메시지인지를 나타낸다. 그 외 다른 header 들은 Action header 실행을 위한 인자값들로 구성된다. 상세 header 내용들을 확인하고자 한다면 Asterisk CLI 창에서 manager show command <Action> 을 입력하면 확인이 가능하다. 전체 Action list 확인은 manager show commands 명령으로 확인이 가능하다.

MyFBSD*CLI> manager show command ping
[Syntax]
Action: Ping
[ActionID:] <value>

[Synopsis]
Keepalive command.

[Description]
A 'Ping' action will ellicit a 'Pong' response. Used to keep the manager
connection open.

[Arguments]
ActionID
ActionID for this transaction. Will be returned.

[See Also]
Not available

Manager action 메시지에 대한 응답 중 제일 마지막에 오는 메시지는 Response header 를 가지고 있다. 이 Response header 를 통해서 manager action 명령의 성공 여부와 실패했을 경우 실패한 사유등을 확인할 수 있다.

Action: Login
Username: russell
Secret: russell

Response: Success
Message: Authentication accepted

Call originating

AMI 를 통해서 콜을 생성해보자.

Action: Originate
Channel: Sip/0000FFFF0001
Application: Playback
Data: demo-congrats

Response: Success
Message: Originate successfully queued

 

How to make wifi ap in gentoo

집에서 사용하는 무선랜이 벽과 벽을 통과하면서 정작 내방에서는 거의 잡히지 않게 되었다.

그동안 유선으로만 쓰고 있었는데.. 이번에 새롭게 태블릿과 휴대폰을 구입하면서 너무나 불편하게 되었다.
그래서 젠투에 Wifi 공유기 설정을 하게 되었다.

AP 지원 모드 확인
먼저 현재 사용중인 무선랜 카드가 AP 모드를 지원하는지를 확인해야 한다.

$ sudo emerge iw
$ iw list
Wiphy phy0
	max # scan SSIDs: 4
	max scan IEs length: 2257 bytes
	RTS threshold: 2347
	Coverage class: 0 (up to 0m)
	Device supports RSN-IBSS.
	Supported Ciphers:
		* WEP40 (00-0f-ac:1)
		* WEP104 (00-0f-ac:5)
		* TKIP (00-0f-ac:2)
		* CCMP (00-0f-ac:4)
		* CMAC (00-0f-ac:6)
	Available Antennas: TX 0 RX 0
	Supported interface modes:
		 * IBSS
		 * managed
		 * AP
		 * AP/VLAN
		 * monitor
		 * mesh point
		 * P2P-client
		 * P2P-GO

위와 같이 iw list 명령어로 확인했을 때, Supported interface modes: 항목에 AP 항목이 표시가 되어야한다. 꼭 확인하도록 하자.

필요 패키지
다음의 패키지들을 설치해주자.

$ sudo emerge hostapd
$ sudo emerge dhcp

dhcp 설정

생성된(곧 생성할..) 무선 AP에 Client가 접속했을 때, 자동으로 사용가능한 IP 를 할당해주어야 한다. 그러기 위해서는 dhcp 설정이 필요하다. 이 예제에서는 임의로 10.10.0.0/24 대역의 IP 주소를 사용하기로 한다.

dhcp 설정을 위해서 다음의 내용을 /etc/dhcp/dhcpd.conf 파일에 입력한다.

subnet 10.10.0.0 netmask 255.255.255.0 {
        range 10.10.0.25 10.10.0.50;
        option domain-name-servers 8.8.8.8;
        option routers 10.10.0.1;
}

hostapd 설정

hostapd 는 실제로 wifi ap를 생성해주는 유틸이다. /etc/hostapd/hostapd.conf 파일에 아래의 내용을 입력하도록 하자.

interface=wlan0
driver=nl80211
ssid=pchero_gentoo
hw_mode=g
channel=1
macaddr_acl=0
auth_algs=3

wpa=3
wpa_passphrase=yourpassword
wpa_psk_radius=0
wpa_key_mgmt=WPA-PSK WPA-EAP
wpa_pairwise=CCMP
wpa_ptk_rekey=600

간혹 설정 내용이 잘 안 맞아서 안되는 인증이 경우가 있다. 이런 경우, 어느 부분에서 문제가 생기는지 알기 어려울 수 있다. 때문에 처음에는 가급적 암호화 없는 Open 으로 설정한 뒤, 정상작동하는 것을 확인하고 하나씩 수정하는 것을 권한다. 아래 내용은 암호화를 하지 않은 Open 방식 설정 예제이다.

interface=wlan0
driver=nl80211
ssid=pchero_gentoo
hw_mode=g
channel=11

Ip masquerade

wifi ap 생성 후, 패킷을 포워딩해주어야 하기 때문에 masquerade 설정을 해야한다. 아래 명령은 root 로 su 한 다음에 진행해야 한다.

$ sudo su -
$ echo "1" > /proc/sys/net/ipv4/ip_forward
$ iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

NetworkManager

고생했던 부분이다….. 여기까지 진행하면서 문제가 없었는데, 이상하게 hostapd 를 시작하면 이상한 오류를 내면서 죽는 현상이 나타났다. 아래는 그 오류 내용이다.

pchero@localhost ~ $ sudo hostapd -dd /etc/hostapd/hostapd.conf
random: Trying to read entropy from /dev/random
Configuration file: /etc/hostapd/hostapd.conf
ctrl_interface_group=10 (from group name 'wheel')
nl80211: Could not add multicast membership for vendor events: -2 (No such file or directory)
rfkill: initial event: idx=0 type=1 op=0 soft=0 hard=0
nl80211: Supported cipher 00-0f-ac:1
nl80211: Supported cipher 00-0f-ac:5
nl80211: Supported cipher 00-0f-ac:2
nl80211: Supported cipher 00-0f-ac:4
nl80211: Supported cipher 00-0f-ac:6
nl80211: Using driver-based off-channel TX
nl80211: interface wlan0 in phy phy0
nl80211: Set mode ifindex 6 iftype 3 (AP)
nl80211: Setup AP(wlan0) - device_ap_sme=0 use_monitor=0
nl80211: Subscribe to mgmt frames with AP handle 0x1c6d390
nl80211: Register frame type=0xb0 nl_handle=0x1c6d390 match=
nl80211: Register frame type=0x0 nl_handle=0x1c6d390 match=
nl80211: Register frame type=0x20 nl_handle=0x1c6d390 match=
nl80211: Register frame type=0xa0 nl_handle=0x1c6d390 match=
nl80211: Register frame type=0xc0 nl_handle=0x1c6d390 match=
nl80211: Register frame type=0xd0 nl_handle=0x1c6d390 match=
nl80211: Register frame command failed (type=208): ret=-114 (Operation already in progress)
nl80211: Register frame match - hexdump(len=0): [NULL]
nl80211: Could not configure driver mode
nl80211: Remove monitor interface: refcount=0
nl80211: Remove beacon (ifindex=6)
netlink: Operstate: ifindex=6 linkmode=0 (kernel-control), operstate=6 (IF_OPER_UP)
nl80211: Set mode ifindex 6 iftype 2 (STATION)
nl80211: Teardown AP(wlan0) - device_ap_sme=0 use_monitor=0
nl80211 driver initialization failed.
hostapd_interface_deinit_free(0x1c6c990)
hostapd_interface_deinit_free: num_bss=1 conf->num_bss=1
hostapd_interface_deinit(0x1c6c990)
hostapd_bss_deinit: deinit bss wlan0
hostapd_cleanup(hapd=0x1c70370 (wlan0))
hostapd_free_hapd_data: Interface wlan0 wasn't started
hostapd_interface_deinit_free: driver=(nil) drv_priv=(nil) -> hapd_deinit
hostapd_interface_free(0x1c6c990)
hostapd_interface_free: free hapd 0x1c70370
hostapd_cleanup_iface(0x1c6c990)
hostapd_cleanup_iface_partial(0x1c6c990)
hostapd_cleanup_iface: free iface=0x1c6c990

결론은 NetworkManager 때문이었다. hostapd 와 NetworkManager 는 같이 실행시킬 수 없다. 즉, hostapd 를 실행시키기 위해서는 NetworkManager 를 종료 시켜야 한다.

sudo /etc/init.d/NetworkManager stop

Set wlan0

이제 wlan0 의 IP 를 설정해주자. 기본적으로 dhcpd.conf 의 설정 내용과 맞춰야 하므로 10.10.0.1 로 설정하도록 하자.

ifconfig wlan0 10.10.0.1 netmask 255.255.255.0

Start hostapd

다 끝났다. dhcp 와 hostapd 를 시작하도록 하자. dhcp 시작시, wlan0 에 대해서만 dhcp 서비스를 하도록 명시해 주어야 한다. 주의하자.
만약 interface를 명시하지 않을 경우, eth0 까지도 dhcp 서비스를 하려고 한다. 그렇게 되면 eth0에 설정되어 있는 IP 정보가 날아가게 되고, 결론적으로는 AP 로써 정상작동하지 않게 된다.

# dhcp
$ sudo dhcpd -cf /etc/dhcp/dhcpd.conf wlan0 start

# hostapd
$ sudo hostapd -dd /etc/hostapd/hostapd.conf

Miscellaneous

매번 ap 를 구동하기 위해 위의 명령어를 입력할 수는 없다. 간단히 스크립트를 만들도록 하자.

#!/bin/bash

# stop Network Manager
#service NetworkManager stop
/etc/init.d/NetworkManager stop

# Set wlan0 IP
ifconfig wlan0 10.10.0.1 netmask 255.255.255.0

# Ip forwarding
echo "1" > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

# dhcp
dhcpd -cf /etc/dhcp/dhcpd.conf wlan0 start

# hostapd
hostapd -B /etc/hostapd/hostapd.conf

참고
http://exain.wordpress.com/2011/03/31/making-a-wifi-hotspot-access-point-using-linux-wifi-lan-cardusb-adapter
http://www.sentabi.com/how-to-fix-hostapd-nl80211driver-initialization

 

Manual printer installing in linux

리눅스 사용시 간혹 수동으로 printer 설치를 해야할 경우가 있다. 이럴 경우, 다음의 순서대로 진행하면 된다.

파폭 창을 열고 localhost:631 에 접속한다.

Administration > Printers > Add Printer

이후, 설치하고자 하는 프린터의 이름과 프린터 드라이버를 지정해주면 끝!

 

Show wireshark interface lists in Ubuntu

ubuntu 에서 wireshark 설치시, 실제로 패킷 캡처를 하기 위해서 interface 리스트 목록을 확인할 때, interface 목록이 안나타나는 경우가 있다.
이는 wireshark 를 실행하는 유저의 권한 때문에 발생하는 문제이다.

간단하게 터미널에 $ sudo wireshark 를 입력하면 되지만 뭔가 깔끔하지 못하다…
이럴 경우, 터미널에 다음의 명령어를 입력하면 깔끔하게 wirewhark 를 실행할 수 있다.

$ sudo apt-get install wireshark
$ sudo dpkg-reconfigure wireshark-common 
$ sudo usermod -a -G wireshark $USER
$ sudo rebot

출처 : http://ask.wireshark.org/questions/7523/ubuntu-machine-no-interfaces-listed