18 Aralık 2019 Çarşamba

zip komutu

Giriş
gzip ve zip farklı şeyler. zip her dosyayı tek başına sıkıştırır ve arşive ekler. Arşivden tek bir dosyayı çıkartmak daha kolay. Açıklaması şöyle
In ZIP files, the individual files are compressed and then added to the archive. When you want to pull a single file from a ZIP, it is simply extracted, then decompressed. With GZIP, the whole file needs to be decompressed before you can extract the file you want from the archive. When pulling a 1MB file from a 10GB archive, it is quite clear that it would take a lot longer in GZIP, than in ZIP.
Buna karşılık gzip dosyalarının nihai boyutu daha küçük oluyor. Açıklaması şöyle
GZIP’s disadvantage in how it operates, is also responsible for GZIP’s advantage. Since the compression algorithm in GZIP compresses one large file instead of multiple smaller ones, it can take advantage of the redundancy in the files to reduce the file size even further. If you archive and compress 10 identical files with ZIP and GZIP, the ZIP file would be over 10 times bigger than the resulting GZIP file.
Kullanım
Kısaca şöyle yaparız
zip Compressed.zip File1.txt File2.txt File3.txt MyFolder
-A seçeneği - adjust suffix
Eğer zip dosyasına uzantı vermezsek .zip uzantısı otomatik verilir. Bunu engellemek için kullanılır.
Örnek
Şöyle yaparız.
zip -Ar archive directory/
-d seçeneği
delete anlamına gelir. Şöyle yaparız. log4j ise başlayan tüm jar dosyalarından belirtilen dosyayı siler.
zip -q -d log4j-*.jar org/apache/log4j/net/JMSAppender.class
-j seçeneği
Açıklaması şöyle.
Store just the name of a saved file (junk the path), and do not store directory names. By default, zip will store the full path (relative to the current directory).
Elimizde şöyle bir yapı olsun.
.
├── d0
├── f0
├── f1
│   └── d1
└── f2
    └── f3
        ├── d2
        ├── d3
        └── d4
Dizin yapısını almadan sadece dosyaları zipkemek için şöyle yaparız.
zip -j myfiles d0 f1/d1 f2/f3/d4 
Çıktı olarak şunu alırız.
.
├── d0
├── d1
└── d4
-r seçeneği - Dizin için kullanılır
Örnek
Şöyle yaparız
zip -r archive.zip directory/
Örnek
Şöyle yaparız.
zip -r myfiles.zip *
-u seçeneği - update zip file
update anlamına gelir. Açıklaması şöyle
update (-u)
    Update existing entries if newer on the file system and add new files. 
    If the archive does not exist issue warning then create a new archive.
Örnek
zip dosyasına yeni bir şey eklemek için şöyle yaparız.
zip -u existing.zip file.txt
Örnek
Şöyle yaparız.
for z in *.zip; do
    zip -u "$z" file.txt
done

17 Aralık 2019 Salı

iptables INPUT Modülü

Giriş
Akış şöyledir.
prerouting -> input -> local process
iptables tarafından drop edilmesini beklediğimiz bir broadcast paketi wireshark ile görmeye devam edebiliriz. Açıklaması şöyle
Wireshark uses libpcap to fetch data from the NIC before it is handled by the OS.
-A - add işlemi
Add anlamına gelir.

-D - delete işlemi
Add ile eklenen kuralı siler

-j seçeneği
Kurala uyan pakete ne işlem yapılacağını belirtir. ACCEPT, REJECT, DROP, LOG olabilir.

Örnek
Loglama için şöyle yaparız.
$ iptables -A INPUT -p ICMP --icmp-type 8 -j LOG --log-prefix "Iptables: Ping detected: "
Açıklaması şöyle
That command asks the kernel to log ICMP type 8 packets. The target file will consist of the following records for every packet received:

kernel: [122972.300408] Iptables: Ping detected: IN=eth0 OUT= 
MAC=00:64:d9:36:7b:d7:00:24:2d:a6:e2:43:08:91 SRC=xxx.xxx.xxx.xxx 
DST=xxx.xxx.xxx.xxx LEN=60 TOS=0x00 PREC=0x00 TTL=124 ID=23020 PROTO=ICMP
TYPE=8 CODE=0 ID=33602 SEQ=2462

A technique such as this is resource-heavy as it dumps all packet metadata to a file.
Örnek
Şöyle yaparız.
# iptables -I INPUT -p tcp --dport 3001 -j REJECT
# iptables -I INPUT -p tcp --dport 3002 -j DROP

$ nc -v 127.0.0.1 3000
nc: connect to 127.0.0.1 port 3000 (tcp) failed: Connection refused

$ nc -v 127.0.0.1 3001
nc: connect to 127.0.0.1 port 3001 (tcp) failed: Connection refused

$ nc -v 127.0.0.1 3002
-i seçeneği - interface
Açıklaması şöyle.
iptables doesn't use the interface's index but is doing a string comparison with the current interface's name when evaluating the -i/--in-interface parameter.
Örnek
Şöyle yaparız.
iptables -A INPUT -i ovpn -p tcp --dport 3306 -j ACCEPT
-I - insert işlemi
Insert anlamına gelir. Şöyle yaparız.
iptables -I INPUT 1 -p tcp --dport 8443 -j ACCEPT
iptables -I INPUT 1 -p tcp --dport 8080 -j ACCEPT
iptables -I INPUT 1 -p tcp --dport 443 -j ACCEPT
iptables -I INPUT 1 -p tcp --dport 80 -j ACCEPT
--dport seçeneği - destination port
Şöyle yaparız.
iptables -A INPUT -s SOMEIP -p tcp --dport 32400 -j DROP
-p seçeneği - protocol
Örnek
Şöyle yaparız.
iptables -A INPUT -p tcp --dport 445 -j DROP
-s seçeneği - source
Örnek
Şöyle yaparız.
iptabşes -A INPUT -s <remote_ip_addresses_range> -j DROP
Örnek
Şöyle yaparız.
## Block every IP address in ~/blocking.txt
## DROP incoming packets to avoid information leak about your hosts firewall
## (HT to Conor Mancone) REJECT outgoing packets to avoid browser wait
for i in $(cat ~/blocking.txt); do
  echo "Blocking all traffic to and from $i"    
  /sbin/iptables -I INPUT -s $i -j DROP
  /sbin/iptables -I OUTPUT -d $i -j REJECT
done
--state seçeneği
Örnek - rate limiting
Şöyle yaparız. 4 dakikada 4 taneye ssh bağlantısına izin verir.
iptables -A INPUT -p tcp -m tcp --dport 22 -m state --state NEW -m recent --update
--seconds 240 --hitcount 4 --name ssh-v4 --mask 255.255.255.255 --rsource -j REJECT
--reject-with tcp-reset

iptables -A INPUT -p tcp -m tcp --dport 22 -m state --state NEW -m recent --set
--name ssh-v4 --mask 255.255.255.255 --rsource -j ACCEPT

16 Aralık 2019 Pazartesi

chmod suid Biti - Dosya Sahibinin Hakları İle Çalıştırılır

Giriş
Genellikle bir uygulamayı root olarak çalıştırmak için kullanılır

suid Yerine Diğer Seçenekler

1. Capability Kullanımı
Açıklaması şöyle.
From my understanding the trend these last years has been to remove setuid binaries and replaced them with capabilities.
Örneğin ping için raw socket açmak gerekir. Bunun için de ya root access ya da cap_net_raw capability gerekir. setcap komutu yazısına bakabilirsiniz.

2. Kernel Ayarları 
/etc/sysctl.conf Dosyası yazısına bakabilirsiniz
sysctl komutu yazısına bakabilirsiniz.

suid Nedir
suid - Set User ID - anlamına gelir. suid biti dosyalarda kullanılır, dizinlerde bir etkisi yoktur. Açıklaması şöyle.
So if the file is owned by root and the SUID bit is turned on, the program will run as root. Even if you execute it as a regular user. The same thing applies to the GUID bit.
SUID Zararlı Mıdır ?
Açıklaması şöyle.
A SUID binary is not inherently exploitable for privilege escalation. The problem is when there is a vulnerability in the software or an administrator sets the SUID bit on a binary that should not have it set. An extreme example of the latter would be an admin setting vim to SUID with owner root, allowing users to execute bash commands as root within a vim session (:![shell command]).
Ping suid bitine ihityaç duyar. Açıklaması şöyle.
The ping utility requires the binary to be owned by root and the SUID bit set because it sends/receives ICMP requests using "raw sockets" which only root can do.
Nasıl Yaparız
rwx bitlerindeki x'in yerine s veya S gelir. Açıklaması şöyle.
chmod preserves a directory's set-user-ID and set-group-ID bits unless you explicitly specify otherwise. You can set or clear the bits with symbolic modes like u+s and g-s, and you can set (but not clear) the bits with a numeric mode.
Örnek - Etkinleştirmek
Şöyle yaparız. 4 sayısı u+s anlamına gelir.
chmod 4755 file
Örnek - Kaldırmak
Şöyle yaparız. En başa 0 konulur
chmod 0554 /bin/passwd

10 Aralık 2019 Salı

runlevel komutu

Giriş
Seviyelerin anlamı şöyle.
Runlevel 0 shuts down the system.

Runlevel 1 is a single-user mode, which is used for maintenance or administrative tasks. You may also see this mode referred to as runlevel S (the S stands for single-user).

Runlevel 2 is a multi-user mode. This runlevel does not use any networking services.

Runlevel 3 is a multi-user mode with networking. This is the normal runlevel you are used to if you use a system that doesn't boot into a GUI (graphical user interface).

Runlevel 4 is not used. The user can customize this runlevel for their own purposes (which we will cover how to do later in the article).

Runlevel 5 is the same as runlevel 3, but it also starts a display manager. This is the runlevel you are used to if you use a system that boots into a GUI.

Runlevel 6 reboots the system.

8 Aralık 2019 Pazar

tput komutu - Portable Terminal Control İçindir

Giriş
Terminali kontrol etmek için bazen şöyle şeyler yapılıyor.
PS1='...'
Ancak bu tür şeyler portable değil. tcup komutu bize daha kolay anlaşılabilir bir yol sunuyor.

cup seçeneği
İmleci belirtilen konuma getirir.  Böylece döngü içinde çalışan uygulamalar ekranda hep aynı yere yazdıkları için göze rahatsızlık veren titreme olmaz.

Örnek
Şöyle yaparız.
#!/bin/bash
clear
while sleep 1; do
    tput cup 0 0
    printf "%21s %6d    \n" \
      "Célula calibrada: "   $(npe ?AI1) \
      "Anemómetro: "         $(npe ?AI2) \
      "Célula temperatura: " $(npe ?AI3) \
      "Célula temperatura: " $(npe ?AI4)
done
cscr seçeneği
Açıklaması şöyle.
changes your terminal's scroll region
Örnek
Şöyle yaparız.
tput csr 1 $((LINES/2))

~/.ssh/config Dosyası - Kullanıcı Konfigürasyon Dosyası

Giriş
Bu dosya şu dizinindedir.
~/.ssh/config
Açıklaması şöyle. Yani kendi bilgisayarımızda ssh komutunu çalıştırınca bu dosya okunur ve buradaki konfigürasyon verisi kullanılır.
ssh obtains configuration data from the following sources in the following order:
 1. command-line options
 2. user's configuration file (~/.ssh/config)
 3. system-wide configuration file (/etc/ssh/ssh_config)
Dosya Hakları
Dosya kullanıcı için okunabilir olmalı. Açıklaması şöyle
Ssh requires the file ~/.ssh/config to be readable only by the user it affects and noone else. File-permission of 664 or 644 is default on most systems (rw-rw-r-- or rw-r--r--).
Örnek
Dosya hakkı şöyle olabilir. Burada dosyanın grup yazma hakkı var.
-rw-rw-r--  1 dev dev   75 Oct 26 20:13 config
Burada ilginç bir problem şöyle. Bir kullanıcı şöyle yapmış
After creating a new user (test) with the same primary group (dev) as the existing user (dev), I am no longer able to git clone when logged in as dev
ssh ise bu durumu istemiyor ve hata veriyor. Açıklaması şöyle. Yani dosya group write ise, grupta tek bir kişi olmalı diyor.
If the file is group-writable, the group in question must have exactly one member, namely the file's owner.
(Zero-member groups are typically used by setgid  binaries, and are unlikely to be suitable.)
Çözümü ise sadece kullanıcıya rw hakkı vermek. Açıklaması şöyle.
Googling around seems to suggest that I can fix the ssh problem by running chmod 600 ~/.ssh/config
Sebebi ise şöyle. Yani güvenlik açığı olmaması
SSH is explicitly made to check the file permissions, and to complain loudly, if another user could modify the configuration because that would be huge gaping security hole. It probably checks the number of users in the group instead of complaining about group-writability as such, since many systems have per-user groups, and umasks allowing write access for the group and false positives there would just annoy people unnecessarily.
Parametrelerin Tekrar Tanımlanması
Açıklaması şöyle
For each parameter, the first obtained value will be used. The configuration files contain sections separated by Host specifications, and that section is only applied for hosts that match one of the patterns given in the specification. ...
Since the first obtained value for each parameter is used, more host-specific declarations should be given near the beginning of the file, and general defaults at the end.
Örnek
Elimizde şöyle bir kod olsun
ServerAliveInterval 1

Host work
  ConnectTimeout 2

Host *
  ConnectTimeout 3
  ServerAliveInterval 4
  ServerAliveCountMax 5

Host work
  ServerAliveCountMax 6
  ServerAliveInterval 7
Açıklaması şöyle
- For all hosts, ServerAliveInterval 1 is always used, 4 and 7 are never used, not even for work.
- ConnectTimeout is 2 for work, for other hosts it's 3.
- For all hosts, the ServerAliveCountMax is 5, the work-specific value 6 is never used, not even for work.

Host Alanı
alias tanımlamak içindir. Eğer bu dosyada alias tanımlamak istemiyorsak daha kolay bir yolu .bashrc dosyasında kendi alias'larımızı tanımlamak. Şöyle yaparız
alias go='ssh url1'
alias go2='ssh url2'
Örnek
Uzaktaki bir bilgisayara alias ve ayar tanımlamak istersek şöyle yaparız.
Host myhost
  Port 12345
  User my_user
  HostName 123.123.123.1
Şöyle yaparız.
ssh myhost
Örnek
Eğer şifre girmek istemezsek şöyle yaparız.
Host 1
  Hostname bastion.example.me
  User said
  Port 22
  IdentityFile ~/.ssh/id_rsa
  ForwardAgent yes
Örnek
Şöyle yaparız
Host meh
    HostName meh.example.com
    User admin
    Port 1234
    IdentityFile ~/.ssh/id_rsa
Bağlanmak için şöyle yaparız.
ssh meh
Host/Port Alanı
Şöyle yaparız.
Host myremotehost
  Hostname      555.555.555.555
  User          user
  Port          20002
  IdentityFile  /Users/myuser/.ssh/vpsssh
Böylece ssh -p ... şeklinde kullanmak zorunda kalmayız.

Host/ControlPersist Alanı
Açıklaması şöyle.
When used in conjunction with ControlMaster, specifies that the master connection should remain open in the background (waiting for future client connections) after the initial client connection has been closed. If set to no, then the master connection will not be placed into the background, and will close as soon as the initial client connection is closed. If set to yes or 0, then the master connection will remain in the background indefinitely (until killed or closed via a mechanism such as the "ssh -O exist"). If set to a time in seconds, or a time in any of the formats documented in sshd_config(5), then the backgrounded master connection will automatically terminate after it has remained idle (with no client connections) for the specified time.
Şöyle yaparız.
Host host
    User root
    ControlMaster auto
    ControlPath /tmp/ssh-control-%C
    ControlPersist 30   # or some safe timeout
Host/HashKnownHosts Alanı
Örnek
~/.ssh/known_hosts dosyasında bağlanılan hostiçin hash üretilmesini engellemek için şöyle yaparız
Host *
  HashKnownHosts no
Host/KnownHosts Alanı
Açıklaması şöyle
SSH has a KnownHostsCommand configuration parameter which allows you to specify a command that outputs host key lines in the same format as the known hosts file. This command will be called after SSH has read the known hosts files and allows you to add additional entries on the fly, based on the information of the current connection attempt.
Örnek
Şöyle yaparız
Host 10.0.0.*
  KnownHostsCommand /usr/bin/env printf "%H ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILUT12.."

Host/ProxyJump Alanı
Örnek
Şöyle yaparız. Böylece "conclusions.initech.biz" hariç diğer tüm "*.initech.biz" bağlantıları bir proxy üzerinden gider.
Host *.initech.biz !conclusions.initech.biz
    ProxyJump conclusions.initech.biz
IdentityFile Alanı
Eğer şifre girmek istemezsek kullanılır.
Örnek
İdentity dosyasını belirtmek için şöyle yaparız.
Host            somename
Hostname        192.168.1.3
User            user
IdentityFile    /home/user/ssh/keys/server1key
Örnek
Kullanılacak şifre yöntemini belirtmek için şöyle yaparız.
Host 10.255.252.1
    Cipher 3des-cbc
    KexAlgorithms +diffie-hellman-group1-sha1
    User foo
Host *
    Port 9922
X11
Açıklaması şöyle.
disabling X11 forwarding does not prevent users from forwarding X11 traffic, as users can always install their own forwarders.