Permitir o SELINUX para algum programa em específico

Neste exemplo, vamos liberar as permissões que o nGinx precisa para funcionar.

Primeiramente, vamos listar as linhas negadas pelo selinux.

sudo cat /var/log/audit/audit.log | grep nginx | grep denied

Agora, vamos criar um arquivo .pp para ser carregado pelo SELINUX.

sudo cat /var/log/audit/audit.log | grep nginx | grep denied | audit2allow -M mynginx 

sudo semodule -i mynginx.pp

Adicionar certificado TLS no Postfix

Create tls directory, set correct ownership/permissions and create a certificate file:

# mkdir /etc/postfix/tls
# chown root:postfix /etc/postfix/tls
# chmod u=rwx,go= /etc/postfix/tls
# cd /etc/postfix/tls
# openssl req -new -x509 -nodes -out smtpd.pem -keyout smtpd.pem -days 3650

Change /etc/postfix/main.cf accordingly:

# grep _tls /etc/postfix/main.cf
smtpd_tls_CAfile = /etc/postfix/tls/smtpd.pem
smtpd_tls_cert_file = /etc/postfix/tls/smtpd.pem
smtpd_tls_key_file = /etc/postfix/tls/smtpd.pem
smtpd_tls_session_cache_database = btree:${queue_directory}/smtpd_scache
smtpd_tls_security_level = may
smtpd_use_tls = yes
smtp_tls_security_level = may
smtp_tls_CAfile = /etc/postfix/tls/smtpd.pem
smtp_tls_cert_file = /etc/postfix/tls/smtpd.pem
smtp_tls_key_file = /etc/postfix/tls/smtpd.pem
smtp_tls_session_cache_database = btree:${queue_directory}/smtp_scache
smtp_use_tls = yes
smtpd_tls_received_header = yes
smtpd_tls_ask_ccert = yes
smtpd_tls_loglevel = 1
tls_random_source = dev:/dev/urandom

If smtpd_sasl_auth_enable = yes option is set in /etc/postfix/main.cf, make sure that saslauthd service is started.

Reload Postfix configuration:

# service postfix reload

Script para criar um swap de 2GB em arquivo

sudo install -o root -g root -m 0600 /dev/null /swapfile
dd if=/dev/zero of=/swapfile bs=1k count=2048k
mkswap /swapfile
swapon /swapfile
echo "/swapfile swap swap auto 0 0" | sudo tee -a /etc/fstab
sudo sysctl -w vm.swappiness=10
echo vm.swappiness = 10 | sudo tee -a /etc/sysctl.conf

godep: command not found

Se encontrar o erro

godep: command not found

Simplesmente faça isso:

step 1: $ export GOBIN=$GOPATH/bin

step 2: $ export PATH=$GOPATH:$GOBIN:$PATH

step 3: go get github.com/tools/godep

step 4: godep save -r

Como identificar tabelas e índices inchados no PostgreSQL?

Como? Com essa query:

SELECT
  current_database(), schemaname, tablename, /*reltuples::bigint, relpages::bigint, otta,*/
  ROUND((CASE WHEN otta=0 THEN 0.0 ELSE sml.relpages::FLOAT/otta END)::NUMERIC,1) AS tbloat,
  CASE WHEN relpages < otta THEN 0 ELSE bs*(sml.relpages-otta)::BIGINT END AS wastedbytes,
  iname, /*ituples::bigint, ipages::bigint, iotta,*/
  ROUND((CASE WHEN iotta=0 OR ipages=0 THEN 0.0 ELSE ipages::FLOAT/iotta END)::NUMERIC,1) AS ibloat,
  CASE WHEN ipages < iotta THEN 0 ELSE bs*(ipages-iotta) END AS wastedibytes
FROM (
  SELECT
    schemaname, tablename, cc.reltuples, cc.relpages, bs,
    CEIL((cc.reltuples*((datahdr+ma-
      (CASE WHEN datahdr%ma=0 THEN ma ELSE datahdr%ma END))+nullhdr2+4))/(bs-20::FLOAT)) AS otta,
    COALESCE(c2.relname,'?') AS iname, COALESCE(c2.reltuples,0) AS ituples, COALESCE(c2.relpages,0) AS ipages,
    COALESCE(CEIL((c2.reltuples*(datahdr-12))/(bs-20::FLOAT)),0) AS iotta -- very rough approximation, assumes all cols
  FROM (
    SELECT
      ma,bs,schemaname,tablename,
      (datawidth+(hdr+ma-(CASE WHEN hdr%ma=0 THEN ma ELSE hdr%ma END)))::NUMERIC AS datahdr,
      (maxfracsum*(nullhdr+ma-(CASE WHEN nullhdr%ma=0 THEN ma ELSE nullhdr%ma END))) AS nullhdr2
    FROM (
      SELECT
        schemaname, tablename, hdr, ma, bs,
        SUM((1-null_frac)*avg_width) AS datawidth,
        MAX(null_frac) AS maxfracsum,
        hdr+(
          SELECT 1+COUNT(*)/8
          FROM pg_stats s2
          WHERE null_frac<>0 AND s2.schemaname = s.schemaname AND s2.tablename = s.tablename
        ) AS nullhdr
      FROM pg_stats s, (
        SELECT
          (SELECT current_setting('block_size')::NUMERIC) AS bs,
          CASE WHEN SUBSTRING(v,12,3) IN ('8.0','8.1','8.2') THEN 27 ELSE 23 END AS hdr,
          CASE WHEN v ~ 'mingw32' THEN 8 ELSE 4 END AS ma
        FROM (SELECT version() AS v) AS foo
      ) AS constants
      GROUP BY 1,2,3,4,5
    ) AS foo
  ) AS rs
  JOIN pg_class cc ON cc.relname = rs.tablename
  JOIN pg_namespace nn ON cc.relnamespace = nn.oid AND nn.nspname = rs.schemaname AND nn.nspname <> 'information_schema'
  LEFT JOIN pg_index i ON indrelid = cc.oid
  LEFT JOIN pg_class c2 ON c2.oid = i.indexrelid
) AS sml
ORDER BY wastedbytes DESC

Converter vídeo x265/HEVC para x264

X265_CodecPorque converter um vídeo encodado em x265/HEVC para x264? O x265 é mais novo, o arquivo fica bem menor praticamente metade do tamanho de um x264. Bom, se você pretende assistir o vídeo em um Raspberry PI você vai precisar fazer isso, pois a CPU/GPU do Raspberry Pi não dá conta de tocar o x265.

Este simples script converte todos os x265 com extensão .mkv no diretório para x264. Enjoy!

INPUT="$1"
for i in *.mkv ; do
    ffmpeg -i "$i" -bsf:v h264_mp4toannexb -sn -map 0:0 -map 0:1 -vcodec libx264 "$i.ts"
    mv "$i.ts" "$i.mpg"
    sleep 3
done

Fonte: http://askubuntu.com/questions/707397/batch-convert-h-265-mkv-to-h-264-with-ffmpeg-to-make-files-compatible-for-re-enc

Como instalar o ffmpeg no Centos7

Neste post irei explicar como instalar o ffmpeg (e mais algumas coisas) no Centos7, usando repositórios não oficiais. Não garanto que eles estejam atualizados, use por conta e risco.

yum -y install epel-release
 yum -y install http://li.nux.ro/download/nux/dextop/el7/x86_64/nux-dextop-release-0-5.el7.nux.noarch.rpm
 yum -y install http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el7.rf.x86_64.rpm

yum install -y gstreamer gstreamer1 gstreamer-ffmpeg gstreamer-plugins-good gstreamer-plugins-ugly
 yum install -y vlc smplayer ffmpeg HandBrake-{gui,cli}
 yum install -y libdvdcss gstreamer{,1}-plugins-ugly gstreamer-plugins-bad-nonfree gstreamer1-plugins-bad-freeworld

yum install -y http://linuxdownload.adobe.com/linux/x86_64/adobe-release-x86_64-1.0-1.noarch.rpm
 yum install -y flash-plugin
 yum install -y icedtea-web

Pronto.

Como limpar o filtro de ar da Yamaha DT 180

IMG_20150723_192343 IMG_20150723_192437 IMG_20150723_192455IMG_20150723_192510IMG_20150723_192522

É bem simples. Basta remover os 4 parafusos da tampa para ter acesso ao filtro. Depois remova os outros 4 parafusos que seguram o suporte da espuma, que faz o papel de filtrar o ar. Pronto, agora limpe todas as peças e a parte interna da cavidade do filtro de ar. A espuma você deve limpá-la com tinner/aguarrás, que toda a sujeira misturada com óleo sai facilmente. Depois monte tudo no lugar. As fotos abaixo detalham todo o processo.

 

Howto VPN L2TP Pre-Shared Key

Tested on: CentOS 6.6
Tools used: Strongswan (https://www.strongswan.org/) for IPSec tunnel, Xl2tpd (https://www.xelerance.com/services/software/xl2tpd/) for Layer 2 Tunneling Protocol (L2TP) daemon and ppp.

Pre-requisites:

[root@centos02 ~]# yum install epel-release
 [root@centos02 ~]# yum install strongswan ppp xl2tpd

Part 1: Configure Strongswan

Edit the following files:

[root@centos02 ~]# vi /etc/strongswan/ipsec.conf
# ipsec.conf – strongSwan IPsec configuration file
config setup
        strictcrlpolicy=no
        #charondebug=”ike 4, knl 4, cfg 2″    #useful debugs
conn %default
        ikelifetime=1440m
        keylife=60m
        rekeymargin=3m
        keyingtries=1
        keyexchange=ikev1
        authby=xauthpsk
conn L2TP-PSK-CLIENT
        keyexchange=ikev1
        type=transport
        authby=secret
        ike=3des-sha1-modp1024
        rekey=no
        left=%defaultroute
        leftprotoport=udp/l2tp
        right=134.142.135.72        # IP of your VPN Server
        rightprotoport=udp/l2tp
        auto=add

Add your pre-shared key here:

[root@centos02 ~]# vi /etc/strongswan/ipsec.secrets
# /etc/ipsec.secrets – strongSwan IPsec secrets file
: PSK “minhapresharedkey”                 # Pre-Shared Key

Set strongswan to start on boot:
[root@centos02 ~]# chkconfig strongswan on

Start strongswan service:
[root@centos02 ~]# /etc/init.d/strongswan start

Try the ipsec:
[root@centos02 ~]# strongswan up L2TP-PSK-CLIENT

If you get the line below, your IPSec tunnel is working:
connection ‘L2TP-PSK-CLIENT’ established successfully

To shutdown the IPSec tunnel, run:
[root@centos02 ~]# strongswan down L2TP-PSK-CLIENT

Part 2: Configure Xl2tpd

Edite the config file:

[root@centos02 ~]# vi /etc/xl2tpd/xl2tpd.conf
[global]
force userspace = yes
;debug tunnel = yes
; Connect as a client to a server at 134.142.135.72
[lac L2TPserver]
lns = 134.142.135.72
require chap = yes
refuse pap = yes
require authentication = yes
; Name should be the same as the username in the PPP authentication!
name = gustfn
;ppp debug = yes
pppoptfile = /etc/ppp/options.l2tpd.client
length bit = yes

And this one:

[root@centos02 ~]# vi /etc/ppp/options.l2tpd.client
ipcp-accept-local
ipcp-accept-remote
refuse-eap
noccp
noauth
crtscts
idle 1800
mtu 1200
mru 1200
nodefaultroute
lock
connect-delay 5000
require-mppe

name gustfn
password MinhaSenhaDaVpn

Add here your user and password for VPN:

[root@centos01 ~]# vi /etc/ppp/chap-secrets
# Secrets for authentication using CHAP
# client    server    secret            IP addresses
gustfn        *        MinhaSenhaDaVpn

To make things easier, let’s create two scripts: one for up the VPN and other for down the VPN:

[root@centos02 ~]# vi vpn_up.sh
#!/bin/sh
# Create a tunnel IPSec with Pre-Shared Key
strongswan up L2TP-PSK-CLIENT | grep “established successfully”
# start the ppp connection and autenticate with your user/pass
echo “c L2TPserver” > /var/run/xl2tpd/l2tp-control
sleep 5
# Important: You need to add here the routes of your VPN network
route add -net 10.24.48.0 netmask 255.255.255.0 dev ppp0
# And delete this one manually
route del 134.142.135.72

[root@centos02 ~]# vi vpn_down.sh
#!/bin/sh
echo “d L2TPserver” > /var/run/xl2tpd/l2tp-control
strongswan down L2TP-PSK-CLIENT

And make both scripts executable:
root@centos02 ~]# chmod +x vpn_up.sh
root@centos02 ~]# chmod +x vpn_down.sh

Set xl2tpd to start on boot:
[root@centos02 ~]# chkconfig xl2tpd on

Start the Xl2tpd daemon:
[root@centos02 ~]# /etc/init.d/xl2tpd start

Done! Now let’s try to check if the VPN is working!
[root@centos02 ~]# ./vpn_up.sh
connection ‘L2TP-PSK-CLIENT’ established successfully

Great!! Now I’m just trying to ping an IP from the other side:
[root@centos02 ~]# ping 10.24.48.52
PING 10.24.48.52 (10.24.48.52) 56(84) bytes of data.
64 bytes from 10.24.48.52: icmp_seq=1 ttl=63 time=232 ms
64 bytes from 10.24.48.52: icmp_seq=2 ttl=63 time=181 ms
64 bytes from 10.24.48.52: icmp_seq=3 ttl=63 time=197 ms

The VPN L2TP is working, good job! To shutdown the VPN, just run:
[root@centos02 ~]# ./vpn_down.sh

How to build a simple affiliate API using OpenResty

Hello,

In this post I’ll discuss about how to create a simple API to provide simple access to a common affiliate partner program. The idea is to have a URL that accepts a few arguments (in our case, we will take the args called partner, subid, gender and route.

To do that, we’ll use the powerful nGinx-with-steroids called OpenResty. My compliments to Yichun Zhang (agentzh), the head of the project.

First of all, download and unpack the OpenResty. (I’ll suppress some simple steps in this doc.)

 

wget http://openresty.org/download/ngx_openresty-1.7.10.1.tar.gz
tar zxvfp ngx_openresty-1.7.10.1.tar.gz
cd ngx_openresty-1.7.10.1
 ./configure --prefix=/usr/local/openresty --with-http_postgres_module
gmake -j4
gmake install
vi /usr/local/openresty/nginx/conf/nginx.conf

# Content of file nginx.conf
worker_processes 4;
events {}
error_log logs/error.log debug;

http {
 upstream database {
 postgres_server 192.168.0.10:5432 dbname=mydatabase user=postgres password=mypassword123;
 }
 
 server {
 listen 192.168.0.11:8080;
 server_name localhost;
 root /usr/local/openresty/nginx/html;

 location /postgresquery {
 internal;
 postgres_pass database;
 set_unescape_uri $id $arg_id;
 set_unescape_uri $subid $arg_subid;
 postgres_escape $id;
 postgres_escape $subid;
 postgres_escape $referencia $http_referer;

 postgres_query
 GET "INSERT INTO mytable01 (id, subid, referer) VALUES ($id, $subid, $referencia) 
RETURNING clickid";
 postgres_output value;
 postgres_rewrite changes 200;
 }

 location /campaign {
 content_by_lua ' 
 local res = ngx.location.capture("/postgresquery", { args = { id = ngx.var.arg_id, 
subid = ngx.var.arg_subid, http_referer = ngx.var.http_referer } } )
 if res.status == 200 and res.body then

 local cookie_name_click = "COOKIE_CLICK="
 local cookie_value_click = res.body
 local cookie_click = cookie_name_click .. cookie_value_click

 local cookie_name_id = "COOKIE_ID="
 local cookie_value_id = ngx.var.arg_id
 local cookie_id = cookie_name_id .. cookie_value_id

 if ngx.var.arg_subid then

 local cookie_name_subid = "COOKIE_SUBID="
 local cookie_value_subid = ngx.var.arg_subid
 local cookie_subid = cookie_name_subid .. cookie_value_subid

 if ngx.var.arg_gender then

 local cookie_name_gender = "COOKIE_GENDER=" 
 local cookie_value_gender = ngx.var.arg_gender
 local cookie_gender = cookie_name_gender .. cookie_value_gender

 ngx.header["Set-Cookie"] = {cookie_click, cookie_id, cookie_subid, cookie_gender}
 else
 ngx.header["Set-Cookie"] = {cookie_click, cookie_id, cookie_subid}
 end
 else
 if ngx.var.arg_gender then

 local cookie_name_gender = "COOKIE_GENDER="
 local cookie_value_gender = ngx.var.arg_gender
 local cookie_gender = cookie_name_gender .. cookie_value_gender

 ngx.header["Set-Cookie"] = {cookie_click, cookie_id, cookie_gender}
 else
 ngx.header["Set-Cookie"] = {cookie_click, cookie_id}
 end
 end

 if ngx.var.arg_route == "photos" then
 return ngx.redirect("http://mywebsite.priv/photos")
 elseif ngx.var.arg_route == "videos" then
 return ngx.redirect("http://mywebsite.priv/videos")
 else
 return ngx.redirect("http://mywebsite.priv/")
 end
 end
 ';
 }

 }
}
# End of file nginx.conf

I’ll explain what this webservice does. It accept an URL of this kind:

http://192.168.0.11:8080/campaign?id=123&subid=5&gender=3&route=videos
http://192.168.0.11:8080/campaign?id=123&subid=5&gender=3
http://192.168.0.11:8080/campaign?id=123&subid=5
http://192.168.0.11:8080/campaign?id=123

Where 192.168.0.11 is the IP of my OpenResty server running on port 8080.

When this URL reaches the server, the nGinx Lua capture the request and make an internal request, to /postgresquery, passing the arguments id, subid and http_referer. The location /postgresquery, that can be accessed only internally, treats the arguments and makes the insert in the database. And return as output the result of column named clickid.

Next step is to check if the response of the request to /postgresquery has returned 200 (if res.status == 200) and if there is any value returned by the request (res.value). So the program creates two cookies, called COOKIE_CLICK and COOKIE_ID, which contains the number of the click of the origin request, inserted on our table called mytable01, and the ID of the partner, that was given by query string argument $id.

Following we check if there are two opcional arguments called subid and gender and if exists, create the proper cookies.

At last the check if there is an argument called route and redirect the user to the proper location on our website, after processed the origin click from a partner website.

The next image shows the whole process.

Screen Shot 2015-03-10 at 16.44.59

Why the choose to do that on OpenResty? Because this process is very fast and this is important when you are dealing with a high number of requests concurrently. The user will not be noticed of this process and your server will be grateful for little-used resources.

←Older