Sunday, January 25, 2015

python: web scraping with BeautifulSoup

BeautifulSoup html, xml parse işlemleri için kullanabileceğiniz bir modül. iterating, searching, ve modifying işlemleri gerçekleştirebilirsiniz.

https://pypi.python.org/pypi/beautifulsoup4/4.3.2 adresinden temin edilebilir.

Xubuntu ortamında kurulumu pip ile aşağıdaki şekilde gerçekleştirdim.
Testlerimde Python 2.7.6 (default, Mar 22 2014, 22:59:56) sürümü kullandım.


Kurulum:

aokan$ sudo pip install beautifulsoup4

Örnekler:
#!/usr/bin/python
from bs4 import BeautifulSoup, NavigableString
import urllib2

url="http://www.siyahsapka.org"
soup=BeautifulSoup(urllib2.urlopen(url).read())
# style tanimi olan span'ların style'larini temizle
for span in soup('span',style=True):
    del span['style']


# tekrar eden break tag'larini (<br> veya <br />) teke indir. arada strong olsa dahi calis.
for br in soup('br'):
    sibling = br.next_sibling
    while sibling:
        if isinstance(sibling, NavigableString):
            sibling = sibling.next_sibling
            continue
        if sibling.name == 'br':
            sibling.decompose()
        elif sibling.name != 'strong':
            break
        sibling = sibling.next_sibling

# strong tag'i arasinda bulunan break (<br> veya <br />) ifadelerini temizle.
for strong in soup('strong'):
    for br in strong('br'):
        br.decompose()


# <a tag'i ile belirtilen link'leri  sadece icerisindeki text kalacak sekilde temizle.
for a in soup('a'):
    a.unwrap()

# gelen html'de yer alan <iframe tag ve içeriğini temizle.
for iframe in soup('iframe'):
    iframe.decompose()

# formatlama isleminden sonra istedigim div icindeki veriyi al
content=unicode(soup.find('div',attrs={'class':'txtIn'}))

Detaylar için http://www.crummy.com/software/BeautifulSoup/bs4/doc/



Eğer biçimlendireceğiniz html veya url sayısı 1000 üzerinde ise bu işlemleri multithread yapmanıza imkan sağlayan scrapy ile gerçekleştirmek daha doğru olacaktır.

Tuesday, January 20, 2015

bash one line: create linux system user without prompt

# useradd -d /home/usernameim -s /bin/bash -p $(echo "sifrem" | openssl passwd -1 -stdin) usernameim

Monday, January 19, 2015

oracle 11gr2 memory_target boyutunu artırma işlemi

database i kapat
su - oracle
sqlplus
sys as sysdba
shutdown immediate;

tmpfs boyutunu artır

[root@localhost:~]# cat /etc/fstab | egrep "^tmpfs"
tmpfs                   /dev/shm                tmpfs   size=8000m      0 0
umount /dev/shm && mount /dev/shm

[root@localhost:~]# df -kh | grep tmpfs
tmpfs             7,9G  3,6G  4,3G  46% /dev/shm   

database i aç
su - oracle
sqlplus
sys as sysdba
startup

database ayarlarını gerçekleştir.
su - oracle
sqlplus
sys as sysdba
create pfile='/tmp/calisan_pfile_backup.ora' from spfile;
alter system set memory_target=6G SCOPE=SPFILE;
alter system set memory_max_target=6G SCOPE=SPFILE;

database i kapat ve tekrar aç
su - oracle
sqlplus
sys as sysdba
shutdown immediate; 
startup


freeradius: allow all external ip connections

Platform: FreeBSD  8.x

add to /usr/local/etc/raddb/clients.conf
client 0.0.0.0/0 {
  secret = 12345
  shortname = name
}

Saturday, January 17, 2015

httperf ile http performance testing

httperf - HTTP performance measurement tool

manual:
http://www.hpl.hp.com/research/linux/httperf/httperf-man-0.9.txt

Örnekler:

httperf --hog --server <server_ip_address> --port 80 --uri /index.php --rate 150 --num-conn 10 --num-call 500


       httperf --hog --server www
          This  command causes httperf to create a connection to host www,
          send a request for the root document (http://www/), receive  the
          reply,  close  the  connection,  and then print some performance
          statistics.

       httperf --hog --server www --num-conn 100 --ra 10 --timeout 5
          Like above, except that a total of 100 connections  are  created
          and  that connections are created at a fixed rate of 10 per sec‐
          ond.  Note  that    option    ``--rate''  has     been  abbreviated  to
          ``--ra''.

       httperf --hog --server=www --wsess=10,5,2 --rate 1 --timeout 5
          Causes httperf to generate a total of 10 sessions at a rate of 1
          session per second.  Each session consists of 5 calls  that  are
          spaced out by 2 seconds.

       httperf --hog --server=www --wsess=10,5,2 --rate=1 --timeout=5 --ssl
          Like  above,  except that httperf contacts server www via SSL at
          port 443 (the default port for SSL connections).

       httperf --hog --server www --wsess=10,5,2  --rate=1  --timeout=5     --ssl
       --ssl-ciphers=EXP-RC4-MD5:EXP-RC2-CBC-MD5   --ssl-no-reuse  --http-ver‐
       sion=1.0
          Like above, except that httperf will inform the server  that  it
          can   only   select  from     two  cipher  suites  (EXP-RC4-MD5  or
          EXP-RC2-CBC-MD5); furthermore, httperf will use HTTP version 1.0
          which requires a new TCP connection for each request.  Also, SSL
          session ids  are    not  reused,  so  the  entire  SSL  connection
          establishment  process  (known  as the SSL handshake) occurs for
          each connection.

HTTP for Great Good


 https://speakerdeck.com/mattrobenolt/http-for-great-good


https://speakerdeck.com/mattrobenolt/cheating-your-way-to-webscale


Developing & Deploying "Large" Scale Web Applications

https://speakerdeck.com/mattrobenolt/developing-deploying-large-scale-web-applications 

How to Deploy Python WSGI Applications Using a CherryPy Web Server Behind Nginx

https://www.digitalocean.com/community/tutorials/how-to-deploy-python-wsgi-applications-using-a-cherrypy-web-server-behind-nginx

Faker: a Python package that generates data for you.

Faker is a Python package that generates fake data for you. Whether you need to bootstrap your database, create good-looking XML documents, fill-in your persistence to stress test it, or anonymize data taken from a production service, Faker is for you.

https://github.com/joke2k/faker

Basic Usage

    from faker import Factory
    fake = Factory.create()

    # OR
    from faker import Faker
    fake = Faker()

    fake.name()
    # 'Lucy Cechtelar'

    fake.address()
    # "426 Jordy Lodge
    #  Cartwrightshire, SC 88120-6700"

    fake.text()
    # Sint velit eveniet. Rerum atque repellat voluptatem quia rerum. Numquam excepturi
    # beatae sint laudantium consequatur. Magni occaecati itaque sint et sit tempore. Nesciunt
    # amet quidem. Iusto deleniti cum autem ad quia aperiam.
    # A consectetur quos aliquam. In iste aliquid et aut similique suscipit. Consequatur qui
    # quaerat iste minus hic expedita. Consequuntur error magni et laboriosam. Aut aspernatur
    # voluptatem sit aliquam. Dolores voluptatum est.
    # Aut molestias et maxime. Fugit autem facilis quos vero. Eius quibusdam possimus est.
    # Ea quaerat et quisquam. Deleniti sunt quam. Adipisci consequatur id in occaecati.
    # Et sint et. Ut ducimus quod nemo ab voluptatum.

Full Stack Python

This guide branches out on topic because your learning needs depend on what you're currently trying to do.

http://www.fullstackpython.com/introduction.html

Inject arbitrary code into a running Python process

$ pyrasite-shell $(pgrep -f "ipython")
Pyrasite Shell 2.0beta9
Connected to 'ipython'
Python 2.7.2 (default, Oct 27 2011, 01:40:22)
[GCC 4.6.1 20111003 (Red Hat 4.6.1-10)] on linux2
>>> print(x)
foo

>>> globals()['x'] = 'bar'


https://pyrasite.readthedocs.org/en/latest/index.html

random string generation with python

#!/usr/bin/python2.7

import random, string, sys
length=10
if len(sys.argv)>1:
        length=sys.argv[1]
rand_str = ''.join(random.choice(
                    string.ascii_lowercase
                    + string.ascii_uppercase
                    + string.digits)
               for i in range(int(length)))
print rand_str

Tuesday, January 13, 2015

Tools to Capture Signals

Software Defined Radio (SDR)  

Hardware Options  
– TV Tuner: $20    (capture only)  
– HackRF: $300  
– USRP2: $2000



RFCat + Hardware Radio

Hardware Options
- IM-Me    dongle: $35   
– CC1111EMK dongle: $49   
– TI EZ430 Chronos CC1111 Access Point:    $58   

screen komutu kullanımı

Yeni oturum açma:
# screen

Çalışılan oturumu arka plana atma:
<CTRL> + a + d
tuş kombinasyonu ile arka plana atılmalı. bu işlem sonrası ekranda
[detached]
şeklinde bir mesaj görürsünüz.


Mevcut oturumları listeleme:
# screen -list

ile ekran listesi alınır ve

# screen -a -r 20458
çağrısı yapılır. (Yukarıda 20458 "screen -list" ile öğrenilen tekrar erişilmek istenilen screen numarası)

add a certificate authority (CA) to Ubuntu

# cp /home/user/workspace/SecureCommunication/certs/valid3/cacert.pem /usr/local/share/ca-certificates/custom-cacert.crt
# update-ca-certificates
Updating certificates in /etc/ssl/certs... WARNING: Skipping duplicate certificate UbuntuOne-ValiCert_Class_2_VA.pem
WARNING: Skipping duplicate certificate UbuntuOne-ValiCert_Class_2_VA.pem
WARNING: Skipping duplicate certificate UbuntuOne-Go_Daddy_Class_2_CA.pem
WARNING: Skipping duplicate certificate UbuntuOne-Go_Daddy_Class_2_CA.pem
1 added, 0 removed; done.
Running hooks in /etc/ca-certificates/update.d....
Adding debian:custom-cacert.pem
done.
done.

Wednesday, January 7, 2015

ZFS arc size (ram kullanımı) sınırlandırılması

Platform

ZFSonlinux - OEL 6.5 x86_64

Konfigurasyon

ZFS ayar değişiklikleri için düzenlemeler /etc/modprobe.d/zfs.conf dosyası üzerinde yapılmalıdır.

vi /etc/modprobe.d/zfs.conf

options zfs zfs_arc_max=8589934592

Değişikliğin aktif olması için sistem yeniden başlatılmalıdır.
# reboot

Mevcut ARC size kullanımının gözlemlenmesi

arcstat.py zfsonlinux kurulu sistemlerde bulunmaktadır.
[root@localhost ~]# arcstat.py 1 5
    time  read  miss  miss%  dmis  dm%  pmis  pm%  mmis  mm%  arcsz     c
10:46:52     0     0      0     0    0     0    0     0    0      0  100M
10:46:53     0     0      0     0    0     0    0     0    0      0  100M
10:46:54     0     0      0     0    0     0    0     0    0      0  100M
10:46:55     0     0      0     0    0     0    0     0    0      0  100M
10:46:56     0     0      0     0    0     0    0     0    0      0  100M


Konfigurasyonda kullanılabilecek tüm parametreler

Kullanılabilecek parametreler aşağıda sıralanmıştır. Ayarlarla ilgili değişiklik yapılmadan önce http://docs.oracle.com/cd/E26502_01/html/E29022/chapterzfs-1.html#scrolltoc dökümanından faydalanılmalıdır.
cd /sys/module/zfs/parameters
[root@bursa parameters]# ls -1
l2arc_feed_again
l2arc_feed_min_ms
l2arc_feed_secs
l2arc_headroom
l2arc_headroom_boost
l2arc_nocompress
l2arc_noprefetch
l2arc_norw
l2arc_write_boost
l2arc_write_max
metaslab_debug_load
metaslab_debug_unload
spa_asize_inflation
spa_config_path
zfetch_array_rd_sz
zfetch_block_cap
zfetch_max_streams
zfetch_min_sec_reap
zfs_arc_grow_retry
zfs_arc_max
zfs_arc_memory_throttle_disable
zfs_arc_meta_limit
zfs_arc_meta_prune
zfs_arc_min
zfs_arc_min_prefetch_lifespan
zfs_arc_p_aggressive_disable
zfs_arc_p_dampener_disable
zfs_arc_shrink_shift
zfs_autoimport_disable
zfs_dbuf_state_index
zfs_deadman_enabled
zfs_deadman_synctime_ms
zfs_dedup_prefetch
zfs_delay_min_dirty_percent
zfs_delay_scale
zfs_dirty_data_max
zfs_dirty_data_max_max
zfs_dirty_data_max_max_percent
zfs_dirty_data_max_percent
zfs_dirty_data_sync
zfs_disable_dup_eviction
zfs_expire_snapshot
zfs_flags
zfs_free_min_time_ms
zfs_immediate_write_sz
zfs_mdcomp_disable
zfs_nocacheflush
zfs_nopwrite_enabled
zfs_no_scrub_io
zfs_no_scrub_prefetch
zfs_pd_blks_max
zfs_prefetch_disable
zfs_read_chunk_size
zfs_read_history
zfs_read_history_hits
zfs_recover
zfs_resilver_delay
zfs_resilver_min_time_ms
zfs_scan_idle
zfs_scan_min_time_ms
zfs_scrub_delay
zfs_send_corrupt_data
zfs_sync_pass_deferred_free
zfs_sync_pass_dont_compress
zfs_sync_pass_rewrite
zfs_top_maxinflight
zfs_txg_history
zfs_txg_timeout
zfs_vdev_aggregation_limit
zfs_vdev_async_read_max_active
zfs_vdev_async_read_min_active
zfs_vdev_async_write_active_max_dirty_percent
zfs_vdev_async_write_active_min_dirty_percent
zfs_vdev_async_write_max_active
zfs_vdev_async_write_min_active
zfs_vdev_cache_bshift
zfs_vdev_cache_max
zfs_vdev_cache_size
zfs_vdev_max_active
zfs_vdev_mirror_switch_us
zfs_vdev_read_gap_limit
zfs_vdev_scheduler
zfs_vdev_scrub_max_active
zfs_vdev_scrub_min_active
zfs_vdev_sync_read_max_active
zfs_vdev_sync_read_min_active
zfs_vdev_sync_write_max_active
zfs_vdev_sync_write_min_active
zfs_vdev_write_gap_limit
zfs_zevent_cols
zfs_zevent_console
zfs_zevent_len_max
zil_replay_disable
zil_slog_limit
zio_bulk_flags
zio_delay_max
zio_injection_enabled
zio_requeue_io_start_cut_in_line
zvol_inhibit_dev
zvol_major
zvol_max_discard_blocks
zvol_threads

delimited data file ve json data file size kıyaslaması


Docs:
http://tools.ietf.org/html/rfc4627
http://www.ecma-international.org/publications/standards/Ecma-404.htm

Aşağıda detaylandırılan örnek; sıkıştırılmış delimited data file ve json data file dosya büyüklüğünü kıyaslamak,  format seçimi konusunda fikir edinmek amacı ile yapılmıştır.

 generator code:
<?php
$x=0;
$code=0;
$key=0;
for($i=0; $i<9000000; $i++) {
        $x++;
        $code++;
        $key++;
//      echo chr($i)."|";
//      echo $i."|";
        echo "{'key$key': '$i'},";
        if($x%10==0) echo "\n";
        if($key%10==0) $key=0;
        if($code=="255") $code=0;
}
?>




[root@okantest ~]# du -sh delimited.file.1
69M     delimited.file.1
[root@okantest ~]# wc -l delimited.file.1
900000 delimited.file.1
[root@okantest ~]# gzip delimited.file.1
[root@okantest ~]# du -sh delimited.file.1.gz
19M     delimited.file.1.gz


[root@okantest ~]# du -sh json.file.1
173M    json.file.1
[root@okantest ~]# wc -l json.file.1
900000 json.file.1
[root@okantest ~]# gzip json.file.1
[root@okantest ~]# du -sh json.file.1.gz
23M     json.file.1.gz

Saturday, December 20, 2014

SNMP - Komut satırından snmptrap ile örnek event gönderme işlemleri

snmptrap -v2c -c public 172.16.42.3 "" .1.3.6.1.6.3.1.1.5.1.0 0 s "This is a 172.16.42.3 coldStart trap"
snmptrap -v2c -c public 172.16.42.3 "" .1.3.6.1.6.3.1.1.5.2.0 0 s "This is a 172.16.42.3 warmStart trap"
snmptrap -v2c -c public 172.16.42.3 "" .1.3.6.1.6.3.1.1.5.3.0 0 s "This is a 172.16.42.3 linkDown trap"
snmptrap -v2c -c public 172.16.42.3 "" .1.3.6.1.6.3.1.1.5.4.0 0 s "This is a 172.16.42.3 linkUp trap"
snmptrap -v2c -c public 172.16.42.3 "" .1.3.6.1.6.3.1.1.5.5.0 0 s "This is a 172.16.42.3 authenticationFailure trap"
snmptrap -v2c -c public 172.16.42.3 "" .1.3.6.1.4.1.207.8.4.4.4.77.0.1 0 s "Firewall attack trap"



Router'lar icin ornek on tanimli liste:  http://www.allied-telesis.co.jp/support/list/router/ar415s/trap.html

FreeBSD'de ek swap alanı oluşturma işlemleri

Aşağıdaki komut ile 10gb büyüklüğünde dosya oluşturulur.
dd if=/dev/zero of=/opt/swap0 bs=1024k count=10240

ile dosya oluşturulur.

mdconfig -a -t vnode -f /opt/swap0 -u 0 && swapon /dev/md0

ile aktif hale getirilir.

Aktifleme sonrası çıktı:

atakoy:/opt# server>  swapinfo -h
Device          1K-blocks     Used    Avail Capacity
/dev/label/swap0   1023996       0B       1G     0%
/dev/md0         10485760       0B      10G     0%
Total            11509756       0B      11G     0%

Açılışta aktif olması için /etc/rc.conf'a aşağıdaki satır eklenir.
swapfile="/opt/swap0"

MySQL command line sql statements

Aşağıdaki komut select output 'unu konsol ekranına döküyor. Aynı şekilde insert, update işlemleride yapılabiliyor.

$ mysql -u root -p$MYSQLPASSWORD imc -e "select * from NAMED_LIST"

Adım adım ZFS operasyonları

zpool komutu ile yeni disk için pool oluşturma

Yeni takılan diski zfs ile kullanmak için pool oluşturulmalıdır.

işlem 1
zpool create tank1 /dev/da3


zfs komutu ile pool içinde mountpoint özelliğini ayarlayarak yeni filesystem oluşturma işlemi aşağıdaki şekilde gerçekleşti.

işlem 2
zfs create -o mountpoint=/opt/output tank1/opt_output
zfs filesystem properties

zfs tercih etmemin en önemli iki nedeni filesystem ekle/çıkar işlemlerini ve ek olarak yarattığınız farklı filesystem'lere ait farklı özellikleri kolayca yönetebilmek.

Örnek olarak mountpoint özelliği ile dosya sistemimizin hangi yola bağlanacağı bilgisini aşağıdaki şekilde değiştirebiliyoruz.

Varsayılan olarak mountpoint /tank1 olarak ayarlandı. Değiştirmek için:

okantest:~# test>  zfs get mountpoint tank1
NAME   PROPERTY    VALUE       SOURCE
tank1  mountpoint  /tank1      default


işlem 3
okantest:~# test>  zfs set mountpoint=/opt/tank1 tank1

filesystem e özel değiştirebileceğiniz özellik listesini
zfs get all tank1

komutu ile alabilirsiniz.

Sık olarak değiştirdiğim zfs dosya sistemi özellikler (zfs filesystem properties ) şunlar:

  •     compression  (on | gzip | gzip-[1-9] | zle | lzjb | off)
  •     mountpoint
  •     quota
  •     recordsize bu değer optimize edilmeli default: 128k


zfs compression test results
Strength&Type    Time    Size    Comments
off/assorted    56.157s    660M   
zle/assorted    58.859s    608M    some gain, small cost
lzjb/assorted    56.919s    490M    fair gain, small cost
on/assorted    58.168s    496M    =lzjb
gzip-1/assorted    69.715s    376M    Significant gains, increased cost
gzip-2/assorted    69.416s    383M   
gzip-3/assorted    71.724s    361M   
gzip-4/assorted    76.042s    367M   
gzip-5/assorted    77.492s    367M   
gzip/assorted    81.487s    359M   
gzip-7/assorted    84.402s    365M   
gzip-8/assorted    88.709s    357M    Not much better than gzip-1, and progressively more expensive, timewise
gzip-9/assorted    93.229s    364M   
              
off/avi    18.700s    344M   
zle/avi    16.497s    324M    Best time, best compression, not sure why
lzjb/avi    18.414s    331M    “free”, with some space savings
on/avi    18.135s    325M    =lzjb
gzip-1/avi    30.593s    336M   
gzip-2/avi    30.714s    335M   
gzip-3/avi    30.043s    335M   
gzip-4/avi    32.278s    344M   
gzip-5/avi    31.652s    338M   
gzip/avi    32.148s    337M   
gzip-7/avi    33.087s    337M   
gzip-8/avi    32.642s    336M   
gzip-9/avi    30.125s    341M   
              
off/mp3    0.280s    7.29M    You can't win if you don't play.
zle/mp3    0.140s    7.20M   
lzjb/mp3    0.139s    7.20M   
on/mp3    0.137s    7.20M   
gzip-1/mp3    0.158s    7.20M   
gzip-2/mp3    0.137s    7.20M   
gzip-3/mp3    0.138s    7.20M   
gzip-4/mp3    0.150s    7.20M   
gzip-5/mp3    0.139s    7.20M   
gzip/mp3    0.141s    7.20M   
gzip-7/mp3    0.150s    7.20M   
gzip-8/mp3    0.139s    7.20M   
gzip-9/mp3    0.164s    7.20M   
              
off/programs    13.422s    240M   
zle/programs    11.731s    245M   
lzjb/programs    08.398s    231M    Second best on time, not bad on compression
on/programs    05.823s    173M    Best time and compression… should equal lzjb
gzip-1/programs    12.386s    207M   
gzip-2/programs    13.223s    214M   
gzip-3/programs    14.091s    222M   
gzip-4/programs    14.833s    219M   
gzip-5/programs    15.788s    222M   
gzip/programs    15.394s    223M   
gzip-7/programs    15.915s    220M   
gzip-8/programs    15.736s    222M   
gzip-9/programs    16.119s    222M   
              
off/text    0.257s    5.31M   
zle/text    0.120s    4.81M   
lzjb/text    0.114s    4.67M   
on/text    0.118s    4.67M   
gzip-1/text    0.137s    4.27M   
gzip-2/text    0.114s    4.25M   
gzip-3/text    0.114s    4.25M   
gzip-4/text    0.125s    4.23M   
gzip-5/text    0.114s    4.23M   
gzip/text    0.125s    4.22M   
gzip-7/text    0.115s    4.22M   
gzip-8/text    0.118s    4.22M   
gzip-9/text    0.124s    4.22M    Best compression, no surprise

Download installed rpm packages on rhel based distos

Aşağıda rhel tabanlı işletim sistemlerinde kurulu rpm'lerin bağımlılıkları ile beraber indirilmesi örneklendirilmiştir.

# yum install yum-utils

# for package in `rpm -qa` ; do /usr/bin/yumdownloader --resolve $package; done





















netmap - high speed packet I/O

project home: http://info.iet.unipi.it/~luigi/netmap/


netmap / VALE is a framework for high speed packet I/O. Implemented as a kernel module for FreeBSD and Linux, it supports access to network cards (NICs), host stack, virtual ports (the "VALE" switch), and "netmap pipes". netmap can easily do line rate on 10G NICs (14.88 Mpps), moves over 20 Mpps on VALE ports, and over 100 Mpps on netmap pipes.

ctypesgen - convert header files written in C to python code

ctypesgen generates ctypes wrappers for header files written in C
project home: https://code.google.com/p/ctypesgen/

Örnek çağrı:
sudo ctypesgen.py -o pylibapi.py -l lib/libapi.so /usr/include/stdint.h include/ntapi/api.h

GnuPG (gpg) kurulum, konfigurasyon ve örnek dosya şifreleme senaryosu

GnuPG cryptographic işlemler için kullanılan bir yazılımdır. Linux, FreeBSD, Macos veya Windows'da kullanabilirsiniz. Gizliliği sağlanan, bütünlüğü doğrulanabilen güvenli veri saklama için kullanılabilir bir araçtır.

Aşağıda bulabileceğiniz örnekte dosya şifreleme işleminin nasıl yapılması gerektiği detaylandırılmıştır. Daha fazla bilgi için GnuPG sitesini ziyaret edebilirsiniz. ( https://www.gnupg.org/ )

Installation:

Platform: Oracle Enterprise Linux 6.5 x86_64
rngd donanım kaynaklı rasgele veri oluşturma için kullanılan bir uygulamamdır. pinentry paketi ise bağımlılık olduğu için kuruyoruz.
yum install rng-tools pinentry-gtk.x86_64 gpg
then edit /etc/sysconfig/rngd and add EXTRAOPTIONS="-r /dev/urandom":
sed -r -i 's#(^EXTRAOPTIONS=).*$#\1"-r /dev/urandom"#' /etc/sysconfig/rngd


Start the service:

chkconfig rngd on
service rngd start
edit: /root/.bash_profile add these lines:

gpg-agent --daemon --enable-ssh-support --write-env-file "${HOME}/.gpg-agent-info"
if [ -f "${HOME}/.gpg-agent-info" ]; then
. "${HOME}/.gpg-agent-info"
export GPG_AGENT_INFO
export SSH_AUTH_SOCK
export SSH_AGENT_PID
fi


Generate keys:

[root@keyserver~]# gpg --gen-key
gpg (GnuPG) 2.0.14; Copyright (C) 2009 Free Software Foundation, Inc.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
gpg: keyring `/root/.gnupg/secring.gpg' created
gpg: keyring `/root/.gnupg/pubring.gpg' created
Please select what kind of key you want:
(1) RSA and RSA (default)
(2) DSA and Elgamal
(3) DSA (sign only)
(4) RSA (sign only)
Your selection?
RSA keys may be between 1024 and 4096 bits long.
What keysize do you want? (2048)
Requested keysize is 2048 bits
Please specify how long the key should be valid.
0 = key does not expire
<n> = key expires in n days
<n>w = key expires in n weeks
<n>m = key expires in n months
<n>y = key expires in n years
Key is valid for? (0)
Key does not expire at all
Is this correct? (y/N) y
GnuPG needs to construct a user ID to identify your key.
Real name: okantest
Email address:
Comment:
You selected this USER-ID:
"okantest"
Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? O
You need a Passphrase to protect your secret key.
You don't want a passphrase - this is probably a *bad* idea!
I will do it anyway. You can change your passphrase at any time,
using this program with the option "--edit-key".
We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
gpg: /root/.gnupg/trustdb.gpg: trustdb created
gpg: key 37048976 marked as ultimately trusted
public and secret key created and signed.
gpg: checking the trustdb
gpg: 3 marginal(s) needed, 1 complete(s) needed, PGP trust model
gpg: depth: 0 valid: 1 signed: 0 trust: 0-, 0q, 0n, 0m, 0f, 1u
pub 2048R/37048976 2014-12-03
Key fingerprint = 42AE 65B4 5307 A17F D562 F2F0 179B 43C0 3704 8976
uid okantest
sub 2048R/ED8D052F 2014-12-03


List your Keys (now with my key details)

[root@keyserver~]# gpg --list-keys
/root/.gnupg/pubring.gpg
------------------------
pub 2048R/37048976 2014-12-03
uid okantest
sub 2048R/ED8D052F 2014-12-03


Sign the Repo:

gpg --detach-sign --armor repodata/repomd.xml


Export the key for clients:

gpg -a --export 80A79AD1 > Swissunix.gpg


Symmetric encryption (simetrik şifreleme):

Bu yöntemde passphrase belirtmeniz zorunludur. Passphrase'i extraction için kullanıyoruz. Belirtmezseniz aşağıdaki şekilde hata alırsınız.
[root@keyserver~]# gpg -c test.file
gpg: error creating passphrase: Invalid passphrase
gpg: symmetric encryption of `test.file' failed: Invalid passphrase

Çözüm:

Aşağıdaki ifadede sifre dosyası içinde saklı şifre kullanılarak simetrik şifreleme yapılmıştır.

[root@pacenode1 ~]# time gpg --batch --yes --passphrase-fd 0 -c test-0-187.el6.x86_64.rpm < sifre
real 0m16.519s
user 0m9.462s
sys 0m0.189s

[root@pacenode1 ~]# ls -alh test-0-187.el6.x86_64.rpm*
-rw-rw-r-- 1 1000 1000 106M Eyl 1 10:30 test-0-187.el6.x86_64.rpm
-rw-r--r-- 1 root root 107M Ara 3 21:47 test-0-187.el6.x86_64.rpm.gpg


Örnek dosya şifreleme senaryosu:

Amaç dosyanın A makinasında sadece B makinasında (has secret key) okunabilecek şekilde şifrelenerek A makinasında saklanmasının sağlanması. Böylece A makinasına erişim sağlayan herhangi bir kişi dosya bu makina da şifrelenip saklansa dahi secret key'e sahip değil ise bu dosyayı okuyamayacak.
Aşağıda detaylarını bulabileceğiniz örnek işlemde özetle; key türettiğimiz makinadaki (keyserver) sadece public key'i export edip ayrı bir makinaya taşıdık ve ayrı makinada import işlemi yaptık. Sonrasında bu makinada test.file dosyasını şifreledik. ve test.file.gpg dosyası oluştu. public_key ile şifrelediğimiz bu dosyayı şifreleme yaptığımız makinada açamadık. (Çünkü private key'e sahip değil)
Bu dosyayı private key'i içeren key türetme işlemi yaptığımız makinaya (keyserver) taşıdık ve sorunsuz şekilde açıldığını gördük. Örnekde asimetrik şifreleme yöntemi kullanılmıştır.


Key export işlemi
:
[root@keyserver~]# gpg --armor --export "okantest" > public_key.asc
[root@keyserver~]# cat public_key.asc
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v2.0.14 (GNU/Linux)
mQENBFR/AisBCADEPmYrhXVRO0Ze7Abokrr4kg5iwXvHnh4ImH193LiUvs+YmRYk
1DK/pywzA4N9kLXF75rmRdCrZJpCwqqInv8zfd0aYA25a8ouSAfWBFDTmVHKHubR
2YW2CpTqTUaedSEgryAyepw/Pi3R3xcl5WMkVQqZCUoVzA0fFMKU+p0Z69GqsB/h
OqS/RjfvSXvcCT5buEGC+oWOPgz0ObX0Nb5qo25wUhNshYrBDK2qdjWapy4Dtawt
VD2zuahTKybYVKd6jvgUHzqo0aykBXRkL4Me2acW4P2fmwnTEMF5iPCxQUuEgwAe
B9J1sFNhfSxY3544f6q1I5Q2Z+mCNlkmf8WdABEBAAG0EEluc2VwdHJhIFN5c3Rl
bXOJATgEEwECACIFAlR/AisCGwMGCwkIBwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJ
EBebQ8A3BIl2cu0H/Rubnd/sBHezgmevX6diE7C+m2RhgcBuVggdWxbMpCUpYqL3
xKzv43vK6Liq1lWSwVKrlIzKHw+BiTe+PdR0aLEQAFzhi4iG4lXmZspctjAvbu6B
M/zNHoHYIDnTqKuBIn0UVep7tx1gMEMlWz0dqNAitTyHLYX/mEEcom/xFu4LDysI
7LmFfnprJAKULIdTEOFjDoF0DA2/UB4sKJYEZ+WCCVrexo6A/69ozvjEUJCx05ZL
S5YgAjHkYxKAFCPp712rFQVuXVeyf/hFe/mO8NmSFOBfgpim/3oJn1O1Amai/SqD
qNYs54OP4NNaEZgl7Hj99+pXVwO9sBWTLrs6l2u5AQ0EVH8CKwEIAKYOqnZnV+tN
8SqQmfz8BQViKwUQuYwMmkz+flNWE0ljFFw9keOas6end7jrbcs5c4JQ/lOWtU/i
xy3mrlErmp1GnnFaPlgPuaNYeG4RV9Wr4f1teJfwS2KRcRobJg3pq9PlFQ25kaqG
xt1SvljjCBpBIvFRSxnQQu3Gphr4FPvbTQas4Q+MtzVGcZQVNdPuLUm5wcphb/8O
f3TdjTOMfBRaRJcip6HjoEZTws2awwqT2GiJtLtOvntd5nUDvNhWzLgvow0hO3JJ
qZNbszJjmfANtgdKEvCO0P36do+xuJAvFndtpCuVRIJ+VFc4HJ33Pm2vuJAzu930
ACxr2m6JIhUAEQEAAYkBHwQYAQIACQUCVH8CKwIbDAAKCRAXm0PANwSJdpRwB/9G
WjkvC5lJuQuKPlTAdRAjG9zvFdNKHfxWqf04GfZJ6T8q1z0wWh5N9ogr/MM3P5uA
nF7pZD1MglgGDMvhlNjiq9MkYE9SHXIX8ikgZKTwML9pgIL2Dk1LhcZesZ+0qMHQ
U7aCFINIV189JRCEncCd2FcgRttwKKgoOi+5aD9uPVrPIQXgzuoU8SrWZrERRSkN
N7KRv89QOKDrsemE7248TtLz/bDVc3+k7Ir7KGhpqEVE3zrSlW/DppOSOyC2PfcN
pzrMOfEA2g5X7Y80c46lwMCzvGzLKNDPhl3hSpjdbn+cE8fWKxy60JAWnvE1pIzJ
5L/+YNmnYtffngHhtVU1
=H57Y
-----END PGP PUBLIC KEY BLOCK-----


Key import işlemi:

Bu işlem keyserver makinasında değil tamamen ayrı bir makinada gerçekleşti. Amacımız keyserver'da oluşturup export'unu aldığımız public_key.asc sertifika dosyasını bu makinaya yüklemek. Böylece şifrelerken bu public_key'i kullanabileceğiz.

[root@A~]# gpg --import public_key.asc


Key silme işlemi

Key silme işlemini yapmanıza gerek yok, bu kısım sadece örneklendirme için paylaşıldı.
[root@A ~]# gpg --list-keys
gpg: checking the trustdb
gpg: 3 marginal(s) needed, 1 complete(s) needed, PGP trust model
gpg: depth: 0 valid: 3 signed: 0 trust: 0-, 0q, 0n, 0m, 0f, 3u
/root/.gnupg/pubring.gpg
------------------------
pub 2048R/4D0A0CEC 2014-12-03
uid okantest
sub 2048R/89AD3BFA 2014-12-03
pub 2048R/7BFD8F15 2014-12-03
uid okantest
sub 2048R/98436A06 2014-12-03
pub 2048R/3C2FF0FB 2014-12-03
uid okantest
sub 2048R/3EC03EB3 2014-12-03

[root@A ~]# gpg --delete-secret-keys 4D0A0CEC && gpg --delete-keys 4D0A0CEC
gpg (GnuPG) 2.0.14; Copyright (C) 2009 Free Software Foundation, Inc.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
sec 2048R/4D0A0CEC 2014-12-03 okantest
Delete this key from the keyring? (y/N) y
This is a secret key! - really delete? (y/N) y
gpg (GnuPG) 2.0.14; Copyright (C) 2009 Free Software Foundation, Inc.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
pub 2048R/4D0A0CEC 2014-12-03 okantest
Delete this key from the keyring? (y/N) y

[root@A ~]# gpg --list-keys
gpg: checking the trustdb
gpg: 3 marginal(s) needed, 1 complete(s) needed, PGP trust model
gpg: depth: 0 valid: 2 signed: 0 trust: 0-, 0q, 0n, 0m, 0f, 2u
/root/.gnupg/pubring.gpg
------------------------
pub 2048R/7BFD8F15 2014-12-03
uid okantest
sub 2048R/98436A06 2014-12-03
pub 2048R/3C2FF0FB 2014-12-03
uid okantest
sub 2048R/3EC03EB3 2014-12-03


Dosya şifreleme işlemi:

-r ifadesi kullanılacak şfireleme profilini ifade eder. Aşağıda private key e sahip olmayan A makina üzerinde şifreleme işlemi yapılıyor.
[root@A~]# cat test.file
1234456

[root@hassecretkey~]# gpg -e -r "okantest" test.file
gpg: ED8D052F: There is no assurance this key belongs to the named user
pub 2048R/ED8D052F 2014-12-03 okantest
Primary key fingerprint: 42AE 65B4 5307 A17F D562 F2F0 179B 43C0 3704 8976
Subkey fingerprint: 0192 FE0A BEF6 5C72 B404 6F94 AB0D 479D ED8D 052F
It is NOT certain that the key belongs to the person named
in the user ID. If you *really* know what you are doing,
you may answer the next question with yes.
Use this key anyway? (y/N) y

Dosya boyutlarını kontrol edelim.

[root@A~]# ls -al test.file*
-rw-r--r-- 1 root root 8 Dec 3 15:52 test.file
-rw-r--r-- 1 root root 349 Dec 3 15:52 test.file.gpg

Şifreli dosyayı açma (decryption) işlemi
secret key'e sahip olmayan makinada başarısız işlem:
( Bu makinada sadece public key import işlemi yapıldı. Private key yüklü değil )

[root@A~]# gpg -o test.file -d test.file.gpg
gpg: encrypted with 2048-bit RSA key, ID ED8D052F, created 2014-12-03
"okantest"
gpg: decryption failed: No secret key

secret key'e sahip olan makinada başarılı işlem:

[root@keyserver ~]# gpg -o test.file -d test.file.gpg
gpg: encrypted with 2048-bit RSA key, ID ED8D052F, created 2014-12-03
"okantest"

[root@keyserver ~]# cat test.file
1234456

[root@keyserver ~]# ls -al test.file*
-rw-r--r-- 1 root root 8 Dec 3 15:56 test.file
-rw-r--r-- 1 root root 349 Dec 3 15:56 test.file.gpg


Onay mesajlarından kurtulma (bypass prompts):

...
It is NOT certain that the key belongs to the person named
in the user ID. If you *really* know what you are doing,
you may answer the next question with yes.
Use this key anyway? (y/N)
Çözüm:
[root@A ~]# gpg --edit-key "okantest" trust
...
1 = I don't know or won't say
2 = I do NOT trust
3 = I trust marginally
4 = I trust fully
5 = I trust ultimately
m = back to the main menu
Your decision? 5
Do you really want to set this key to ultimate trust? (y/N) y


gpg ile symmetric ve asymmetric file encryption süre kıyaslaması:

symmetric file encryption test:
( -c, --symmetric encryption only with symmetric cipher)

[root@hassecretkey ~]# time gpg --batch --yes --passphrase-fd 0 -c --cipher-algo aes128 test-0-187.el6.x86_64.rpm < sifre
real 0m8.987s
user 0m4.767s
sys 0m0.168s

[root@hassecretkey ~]# ls -alh test-0-187.el6.x86_64.rpm*
-rw-rw-r-- 1 1000 1000 106M Sep 1 10:30 test-0-187.el6.x86_64.rpm
-rw-r--r-- 1 root root 107M Dec 4 12:53 test-0-187.el6.x86_64.rpm.gpg
asymmetric file encryption test:
( -r ifadesi kullanılacak profili belirtir. )

[root@hassecretkey ~]# time gpg -e --cipher-algo aes128 -r "okantest" test-0-187.el6.x86_64.rpm
real 0m9.208s
user 0m5.298s
sys 0m0.200s

[root@hassecretkey ~]# ls -alh test-0-187.el6.x86_64.rpm*
-rw-rw-r-- 1 1000 1000 106M Sep 1 10:30 test-0-187.el6.x86_64.rpm
-rw-r--r-- 1 root root 107M Dec 4 12:52 test-0-187.el6.x86_64.rpm.gpg
[root@pacenode1 ~]# rm test-0-187.el6.x86_64.rpm.gpg
rm: remove regular file `test-0-187.el6.x86_64.rpm.gpg'? y

Sonuç:

symmetric 0m8.987s
asymmetric 0m9.208s
gpg ile asymmetric file encryption methodunu kullansanız dahi arka planda symmetric cipher ile şifreleme yapılmaktadır. Büyük dosyaların asymmetric encryption methodu ile şifrelenmesi oldukça maliyetli bir işlemdir.

2014-12-20, İstanbul  - Ali Okan YÜKSEL