5 Kasım 2019 Salı

dlopen metodu

Giriş
Bir shared object kütüphanesini yüklemek için kullanır. İmzası şöyle.
void * dlopen (const char *file, int mode)
mode olarak RTDL_LAZY, RTDL_NOW, RTDL_GLOBAL, RTDL_LOCAL seçeneklerinden birisi kullanılabilir. RTLD_NOAUTODEFER bayrağı Linux'ta mevcut değil.

Bu method dosyayı open() ile açar ve mmap() ile uygulamanın adres alanına dahil eder. Bu metod ile birlitek dlsym() kullanılır.

RTDL_GLOBAL Seçeneği
Açıklaması şöyle.
RTLD_GLOBAL makes the symbols of the loaded library available for use in resolving symbols for future dlopen calls, or dlsym calls on the global namespace (as opposed to a particular library). It does not redefine existing symbols or magically make unresolved ones in already-relocated code/data now resolve to the new definitions.
Örnek - RTDL_LAZY + RTDL_GLOBAL 
Şöyle yaparız. Burada C uygulaması olduğu için değişkenler en üstte tanımlı.
int main(void) {
  void *lib;
  zip_t *p_open(const char *, int, int *);
  void *p_close(zip_t*);
  int err;
  zip_t *myzip;

  lib = dlopen("libzip.so", RTLD_LAZY | RTLD_GLOBAL);
  if (lib == NULL)
    return 1;

  p_open = (zip_t(*)(const char *, int, int *))dlsym(lib, "zip_open");
  if (p_open == NULL)
    return 1;
  p_close = (void(*)(zip_t*))dlsym(lib, "zip_close");
  if (p_close == NULL)
    return 1;

  myzip = p_open("myzip.zip", ZIP_CREATE | ZIP_TRUNCATE, &err);
  if (myzip == NULL)
    return 1;

  p_close(myzip);
  return 0;
}
Örnek - RTDL_LAZY
Belirtilen .so dosyasının bağımlı olduğu diğer .so dosyaları lazy olarak yüklemek ve bağımlılıkları global sembol tablosuna eklemek için şöyle yaparız.
void* handle = ::dlopen("mylib.so", RTLD_LAZY);
Örnek - RTDL_LOCAL + RTDL_LAZY
Belirtilen .so dosyasının bağımlı olduğu diğer .so dosyaları lazy olarak yüklemek ve bağımlılıkları local sembol tablosuna eklemek için şöyle yaparız.
void *handle = dlopen("mylib.so", RTLD_LOCAL | RTLD_LAZY);
Örnek
Yükleyeceğimiz .so dosyasının bağımlılığı  pthread.so olsun. Ancak kütüphanemiz bu bağımlılığı belirtecek şekilde linklenmemiş olsun. Bu durumda .so dosyasını yüklemeye çalışırsak şu hatayı alırız.
dlopen failed: /usr/lib/libTextSearch.so: undefined symbol: pthread_create
RUN FINISHED; exit value 1; real time: 0ms; user: 0ms; system: 0ms
Önce bağımlılığı yüklemek için şöyle yaparız.
void* handlePthread = dlopen("libpthread.so.0", RTLD_GLOBAL | RTLD_LAZY);
if(!handlePthread ){
    fprintf(stderr, "dlopen failed: %s\n", dlerror());
}
Örnek
Kendi uygulamamızı elde etmek için şöyle yaparız. Aynı şey dlsym (RTDL_MAIN_ONLY,...) ile de yapılabilir.
void* handle = dlopen (NULL, RTLD_LAZY);
Hata Kontrolü
Örnek
Şöyle yaparız.
void* handle = dlopen("libTextSearch.so", RTLD_LAZY);
if(!handle){
  fprintf(stderr, "dlopen failed: %s\n", dlerror());
}
Örnek
Eğer hata varsa şöyle yaparız.
if (!handle) {
  throw std::runtime_error(::dlerror());
}

/etc/ssh/sshd_config Dosyası - Sunucu Tarafındaki Dosya

Giriş
Bu dosya şu dizinindedir. Bu dosyadaki ayarlar ssh ve sftp'nin çalışmasını değiştirir.
/etc/ssh/sshd_config
Açıklaması şöyle
The SSH server has a configuration file, usually /etc/sshd/sshd_config. The configuration file specifies encryption options, authentication options, file locations, logging, and various other parameters.
KexAlgorithms Alanı
Bir  zamanlar eski bir ssh istemcini taklit etmek için şöyle yaptım
$ ssh -oKexAlgorithms=diffie-hellman-group14-sha1 jboss@127.0.0.1

Unable to negotiate with 127.0.0.1 port 22: no matching key exchange method found. 
Their offer: curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,
ecdh-sha2-nistp384,ecdh-sha2-nistp521,sntrup761x25519-sha512@openssh.com,
diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,
diffie-hellman-group18-sha512,diffie-hellman-group14-sha256
Örnek
Şöyle yaparız
Ciphers ...
MACs ...
KexAlgorithms ...
AuthorizedKeysFile Alanı
Açıklaması şöyle. Client public key'lerin fingerprint değerini gönderir.
SSH authentication with the "publickey" method works by having the client send each potential public key to the server, then the server responds telling the client which key is allowed. If one of the keys is allowed, then the client must decrypt the private key to sign a message, proving ownership of the private key.
Örnek
Şöyle yaparız
Protocol                                     2
Ciphers                                      aes256-ctr
MACs                                         hmac-sha2-512,hmac-sha2-256
# MACs                                       hmac-sha1
PermitRootLogin                              no
AuthorizedKeysFile                           .ssh/authorized_keys  {set this up}
IgnoreRhosts                                 yes
IgnoreUserKnownHosts                         yes
StrictModes                                  yes
UsePAM                                       yes
Örnek
Şöyle yaparız
apiVersion: v1
kind: ConfigMap
metadata:
  name: ssh-config
data:
  sshd_config: |
    PasswordAuthentication no
    ChallengeResponseAuthentication no
    UsePAM no
  authorized_keys: |
    ssh-rsa AAAAB3NzaC1y... 
Match Group Alanı
Belirtilen grubun nasıl login olacağını belirtir.

Örnek
Elimizde allowssh ve sftponly grupları olsun. Açıklaması şöyle.
-It only allows (pubkey) login for users in the allowssh group.
-Users in the sftponly group cannot get a shell over SSH, only SFTP.
Şöyle yaparız.
Match Group allowssh
    PubkeyAuthentication yes

Match Group sftponly
    ChrootDirectory %h
    X11Forwarding no
    AllowTcpForwarding no
    ForceCommand internal-sftp
Match Host Alanı
Belirtilen host'un nasıl login olacağını belirtir.
Örnek
Şöyle yaparız
Match Host server1,server1.internalnet.local,1.2.3.4
    PasswordAuthentication yes
Match User Alanı
Belirtilen kullanıcının nasıl login olacağını belirtir.
Örnek
 gitlab-ci isimli kullanıcının şifre ile login olması için şöyle yaparız
printf 'Match User gitlab-ci\n\tPasswordAuthentication yes\n' >> /etc/ssh/sshd_config
Örnek
test isimli kullanıcıyı bir chroot jail içinde çalıştırmak için şöyle yaparız
Match User test
ChrootDirectory /home/foo/
X11Forwarding no
AllowTcpForwarding no
MaxSessions Alanı
Açıklaması şöyle.
MaxSessions
         Specifies the maximum number of open shell, login or subsystem
         (e.g. sftp) sessions permitted per network connection.  Multiple
         sessions may be established by clients that support connection
         multiplexing.  Setting MaxSessions to 1 will effectively disable
         session multiplexing, whereas setting it to 0 will prevent all
         shell, login and subsystem sessions while still permitting for-
         warding.  The default is 10.
Normalde bu alanın değeri şöyledir. Yani login olacak kullanıcı sayısına kısıtlama getirilmez.
#MaxSessions 10
Örnek
Sisteme giren kullanıcı sayısın kısıtlamak için şöyle yaparız.
MaxSessions 20
PasswordAuthentication Alanı
Açıklaması şöyle.
It's best to use public keys for SSH. So my sshd_config has PasswordAuthentication no.
Örnek - Password ile Giriş
Şifre ile giriş için şöyle yaparız.
PasswordAuthentication yes 
PermitEmptyPasswords no
PermitRootLogin Alanı
prohibit-password veya no değerini verirsek root login olamaz.
Örnek
Şöyle yaparız.
PermitRootLogin no
PubkeyAuthentication no
PasswordAuthentication no
RequiredAuthentications Alanı
Açıklaması şöyle
In newer versions of OpenSSH you can set the RequiredAuthentications2 pubkey,password parameter in /etc/ssh/sshd_config. This will force the user to use both public key AND password authentication, effectively giving you two-factor authentication
UsePAM Alanı
Açıklaması şöyle. "yes" ise ChallengeResponseAuthentication  ve PasswordAuthentication  etkindir
UsePAM
Enables the Pluggable Authentication Module interface. If set to “yes” this will enable PAM authentication using ChallengeResponseAuthentication and PasswordAuthentication in addition to PAM account and session module processing for all authentication types.

Because PAM challenge-response authentication usually serves an equivalent role to password authentication, you should disable either PasswordAuthentication or ChallengeResponseAuthentication.

If UsePAM is enabled, you will not be able to run sshd(8) as a non-root user. The default is “no”.
Sadece private key ile login için şöyle yaparız.
PermitRootLogin no
PasswordAuthentication no
UsePAM no

23 Ekim 2019 Çarşamba

iconv komutu

-f seçeneği
Kaynak dosyanın kullandığı encoding belirtilir.

-t seçeneği
Hedef dosyanın kullanmasını istediğimiz encoding belirtilir.

Örnek
UTF-8'de Latin 1'e çevirmek için şöyle yaparız.
iconv -f utf-8 -t iso-8859-1 < mwe.txt
Örnek
UTF-16'dan UTF-8' çevirmek için şöyle yaparız
iconv -f utf-16 -t utf-8 batchfile.bat > filename_new.txt
Örnek
cp1252'den UTF-8'e çevirmek için şöyle yaparız.
iconv -f cp1252 -t utf-8
Örnek
ISO-8859-1'den UTF-8'e çevirmek için şöyle yaparız.
iconv -f ISO-8859-1 -t UTF-8 u.item > movie_def.txt
Örnek
Elimizde şöyle bir dosya olsun. Bu dosyada fonetik işaretlere (diacritic) sahip karakterler var.
>  ~ cat file
ë
ê
Ý,text
Ò
É
file isimli kaynak dosyayı ASCII yapmak için şöyle yaparız. ASCII//TRANSLIT seçeneğiyle aynı zamanda fonetik işaretleri (diacritic) silmek mümkün.
$ iconv -t ASCII//TRANSLIT file
e
e
Y,text
O
E

bash kodlama - associative array

Giriş
declare -A ile map tanımlanır. Şöyle yaparız.
declare -A obj
obj["key1"]="val1"
obj["key2"]="val2"

for item in ${!obj[@]}; do
  echo "${obj[${item}]} ${item}"
done
Tüm Map'i Dolaşmak
Örnek
array isimli bir map olsun. !assoc[@] ile key'lere erişiriz. $i ile key değerine göre arama yaparız. Şöyle yaparız.
declare -A assoc=([foo]="123" [bar]="456")
for i in "${!assoc[@]}" ; do 
    echo "${assoc[$i]}"
done 
Örnek
Şöyle yaparız.
declare -a ratings

for movid in ...
do
  countLines=...
  sumRatings=...
  avgRating=...
  if [ $countLines -gt 100 ]
  then
    ratings[$movid]=$avgRating
  fi
done

for k in "${!ratings[@]}"
do
  echo $k'|'${ratings["$k"]}'
done
Map'te Arama Yapmak
Örnek
done isimli bir map tanımlayıp içinde arama yapmak için şöyle yaparız.
#!/bin/bash
# Keep an associative array of which names you have already processed
# Requires Bash 4
declare -A done
for file in 1/* 2/*; do
  base=${file#*/}  # trim directory prefix from value
  test "${done[$base]}" && continue
  : do things ...
  done["$base"]="$file"
done

22 Ekim 2019 Salı

chmod ve sticky bit - Dizinde Herkes Dosya Oluşturabilir Ancak Sadece Dizin Sahibi Silebilir

sticky bit
sticky biti genellikle dizinlerde kullanılır. ls komutu ile bakılınca dizin t veya T ile gösteriliyorsa sticky biti atanmış anlamına gelir.

Dizine Uygulamak
Açıklaması şöyle. Bir dizinde herkes dosya oluşturabilir ancak sadece dosyanın sahibi silebilir.
That is, the sticky bit's presence on a directory only allows contained files to be renamed or deleted if the user is either the file's owner or the containing directory's owner (or the user is root).
Bu bit genellikle /tmp dizininde kullanılır. Böylece bu dizinde herkes kendi dosyasını oluşturabilir ancak başkasının dosyasını silemez. Açıklaması şöyle.
For directories, it prevents unprivileged users from removing or renaming a file in the directory unless they own the file or the directory; this is called the restricted deletion flag for the directory, and is commonly found on world-writable directories like /tmp.
Örnek
Şöyle yaparız. ls komutunun çıktısında t harfi görülebilir.
# chmod 1777 directory
# ls -ld directory
drwxrwxrwt  2 root  wheel  2 Oct 21 17:06 directory/
Örnek
Şöyle yaparız. user ve group ve owner'a yazma hakkı verir. Ayrıca sticky bit'i de atar.
# chmod ugo+w,+t directory
Dosyaya Uygulamak
Dosyalarda da uygulanabilir. Açıklaması şöyle. Ancak günümüzde bir işlevi olup olmadığını bilmiyorum.
The sticky bit was originally used for a completely different purpose: if it was set on an executable file, it told the operating system to retain the text segment in swap. Thus the name "Sticky Bit".