Difference between revisions of "OpenSSL: CLI Introduction"

From OnnoWiki
Jump to navigation Jump to search
Line 210: Line 210:
 
Dimana,
 
Dimana,
  
* -pubin is used like before when the key is the public one, which is natural as we are verifying a signature.To complete the verification, one needs to compute the digest of the input file and to compare it to the digest obtained in the verification of the digital signature.
+
* -pubin dipakai jika key yang digunakan adalah public key, ini biasa digunakan untuk memverifikasi signature. Untuk menyelesaikan proses verifikasi, kita perlu menghitung digest dari input file dan membandingkannya dengan digest yang di peroleh dari verifikasi digital signature.
  
 
==Public Key Infrastructure==
 
==Public Key Infrastructure==

Revision as of 05:48, 8 June 2017

sumber: https://users.dcc.uchile.cl/~pcamacho/tutorial/crypto/openssl/openssl_intro.html


Overview

OpenSSL adalah library C yang mengimplementasikan operasi kriptografi seperti enkripsi simetris, enkripsi kunci publik, tanda tangan digital, fungsi hash dan sebagainya. OpenSSL juga menerapkan protokol Secure Socket Layer (SSL) yang terkenal. OpenSSL tersedia untuk beragam platform.

Source Code dapat didownload dari www.openssl.org. Distribusi windows dapat ditemukan di sini. Tutorial ini menunjukkan beberapa fungsi dasar dari tool baris perintah OpenSSL.

Di Ubuntu OpenSSL sudah built-in, untuk cek versi dalam ketik di CLI,

openssl version
OpenSSL 1.0.2g  1 Mar 2016

Ada banyak perintah di OpenSSL, di CLI ketik,

openssl list-standard-commands
asn1parse
ca
ciphers
crl
crl2pkcs7
...

Beberapa perintah penting,

  • ca - untuk membuat certificate authorities.
  • dgst - untuk menghitung fungsi hash.
  • enc - untuk encrypt/decrypt menggunakan secret key algorithms. It is possible to generate using a password or directly a secret key stored in a file.
  • genrsa - untuk membuat pasangan public/private key menggunakan algoritma RSA .
  • password - membuat “hashed password”.
  • pkcs12 - untuk manajemen informasi berdasarkan standard PKCS #12 .
  • pkcs7 - untuk manajemen informasi berdasarkan standard PKCS #7 .
  • rand - membuat pseudo-random bit string.
  • rsa - RSA data management.
  • rsautl - untuk encrypt/decrypt atau sign/verify signature dengan RSA.
  • verify - untuk cek untuk X509.
  • x509 - manajemen data untuk X509.

Algorotma Enkripsi Secret key

Untuk melihat berbagai algoritma secret key yang ada, di CLI ketik

openssl list-cipher-commands
aes-128-cbc
aes-128-ecb
aes-192-cbc
aes-192-ecb
aes-256-cbc
aes-256-ecb
base64
...
	

Daftar berisi algoritma base64 yang merupakan cara untuk mengkodekan informasi biner dengan karakter alfanumerik. Ini sebenarnya bukan algoritma kunci rahasia karena tidak ada kunci rahasia! Mari kita lihat sebuah contoh:

touch number.txt
echo "123456789" > number.txt
openssl enc -base64 -in number.txt
MTIzNDU2Nzg5Cg==
	


Untuk encrypt sebuah text, kita dapat menggunakan algoritma AES dengan mode CBC dan key 256 bit, seperti contoh berikut,

touch plain.txt
echo "I love OpenSSL!" > plain.txt
openssl enc -aes-256-cbc -in plain.txt -out encrypted.bin
enter aes-256-cbc encryption password: hello
Verifying - enter aes-256-cbc encryption password: hello
	

Secret key 256 bit akan di hitung dari password. Untuk decrypt file yang dibuat, kita dapat menggunakan perintah

openssl enc -aes-256-cbc -d -in encrypted.bin -pass pass:hello
I love OpenSSL!
	

Public Key Cryptography

Berikut ini akan di gambarkan bagaimana OpenSSL melakukan manajemen untuk public key. Algoritma RSA akan digunakan. Tentunya ada juga algoritma lainnya.

Key generation

Membuat pasangan public/private key. Disini pasangan kunci dibuat dengan RSA key 1024 bit,

openssl genrsa -out key.pem 1024
Generating RSA private key, 1024 bit long modulus
.............................++++++
................................................................++++++
e is 65537 (0x10001)

File yang dibuat ada kedua public & private key. Tentunya private ket harus di simpan di tempat yang aman, dan sebagainya di enkripsi. Sebelum melakukan itu, coba lihat file key.pem yang dibuat. Private key di coded menggunakan standard Privacy Enhanced Email (PEM).

cat key.pem
-----BEGIN RSA PRIVATE KEY-----
MIICXgIBAAKBgQC7iXTZ+DVO6jzjUMzJKij53vHd0+43ksK7A/gevHpbAGpLyhTE
dpqFlcYYjIs6Vi/rFzb2rF3GbEtbOC+FQzMpmCE2ISNp2FgK2lX8nVTY6KQb9tBZ
/Nmxyd3Sle2BIe05/ETbOgH7AG7jQiPJTBLen1yfEI/qXRbZWtBj2pLnlQIDAQAB
...
IfVV1RrKWZTXFMGHXIXEAM+x1/xsvJcmcpEA9+71Tj45tA==
-----END RSA PRIVATE KEY-----

Perintah berikut memungkinkan kita untuk melihat detail dari pasangan RSA key (modulus, public dan private exponent dll).

openssl rsa -in key.pem -text -noout
Private-Key: (1024 bit)
modulus:
   00:bb:89:74:d9:f8:35:4e:ea:3c:e3:50:cc:c9:2a:
   ...
   6e:e3:42:23:c9:4c:12:de:9f:5c:9f:10:8f:ea:5d:
   16:d9:5a:d0:63:da:92:e7:95
publicExponent: 65537 (0x10001)
privateExponent:
   00:94:df:e7:ed:69:47:18:60:86:f9:85:99:2c:50:
   ...
   81:ef:b1:28:63:bb:fc:70:de:52:3a:08:69:c9:9e:
   75:d8:7e:8b:39:13:ab:24:39
prime1:
   00:f2:18:f9:0d:62:fc:af:fb:df:10:23:d9:e4:b4:
   ...
   10:f8:ca:9c:64:a1:42:ec:2f:4a:7f:7c:59:57:1c:
   be:33:09:95:d3
prime2:
   00:c6:4e:66:2a:11:2c:42:fb:69:30:9a:c3:8b:57:
   ...
   d0:fc:50:7d:da:8c:51:2d:02:53:5b:d1:e9:4d:cc:
   3b:7b:9a:a3:f7
exponent1:
   15:be:44:6f:fd:59:f0:7c:50:96:64:81:e7:56:8f:
   ...
   6e:48:d4:2e:fd:84:c3:2d:a4:25:3b:07:d3:19:13:
   c4:05:b2:5d
exponent2:
   00:94:59:63:fe:46:58:89:47:50:da:c6:7c:50:8a:
   ...
   05:18:2c:12:ea:62:9b:fb:82:c8:df:60:ba:1a:b4:
   15:2f:93:70:e3
coefficient:
   00:9f:3c:71:db:ba:2a:20:5f:8a:7a:f0:99:e7:f0:
   ...
   c4:00:cf:b1:d7:fc:6c:bc:97:26:72:91:00:f7:ee:
   f5:4e:3e:39:b4
	

Opsi -noout memungkinkan untuk tidak menayangkan key dalam format base 64. Angka dalam format hexadecimal yang dapat dilihat (kecuali public exponent secara default selalu 65537 untuk 1024 bit keys): modulus, public exponent, private, dua primes yang mengkomposisi module dan tiga angka lain yang digunakan untuk mengoptimasi algoritma.

Selanjutnya kita bisa mengenkripsi private key,

openssl rsa -in key.pem -des3 -out enc-key.pem
writing RSA key
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
	

File kunci akan dienkripsi menggunakan algoritma kunci rahasia dimana kunci rahasia dihasilkan oleh kata sandi yang diberikan oleh pengguna. Dalam contoh ini algoritma kunci rahasia yang digunakan adalah triple des (3-des). Kunci pribadi saja tidak terlalu menarik karena pengguna lain memerlukan kunci publik untuk dapat mengirim pesan terenkripsi (atau memeriksa apakah ada informasi yang ditandatangani oleh anda).

Untuk ekstrak publik dari file key.pem, adalah sebagai berikut

openssl rsa -in key.pem -pubout -out pub-key.pem

Encryption

Selanjutnya, kita bisa melakukan enkripsi dan membuat tanda tangan digital.

openssl rsautl -encrypt -in <input_file> -inkey <llave> \
       -out <output_file> 

Dimana,

  • input_file - file yang akan di enkripsi. This file must no be longer that 116 bytes =928 bits because RSA is a block cipher, and this command is low level command, i.e. it does not do the work of cutting your text in piece of 1024 bits (less indeed because a few bits are used for special purposes.)
  • key file berisi public key. Jika file ini hanya berisi public key (bukan keduanya private dan public), maka opsi -pubin harus digunakan.
  • output_file - file keluaran yang terenkripsi.

Untuk men-decrypt kita hanya perlu menukar -encrypt dengan -decrypt, dan membalikan input / output file karena input sekarang adalah file yang terenkripsi, sedang output adalah plain text.


Digital signature

Langkah selanjutnya adalah membuat tanda tangan digital dan untuk memverifikasinya. Tidak terlalu efisien untuk menandatangani file besar dengan menggunakan algoritma kunci publik secara langsung. Itulah sebabnya pertama-tama kami menghitung intisari informasi yang akan ditandatangani. Perhatikan bahwa dalam praktiknya ada sedikit hal yang lebih kompleks. Keamanan yang diberikan oleh skema ini (hashing dan kemudian masuk langsung menggunakan RSA) tidak sama (kurang sebenarnya) daripada langsung menandatangani keseluruhan dokumen dengan algoritma RSA. Skema yang digunakan dalam aplikasi real disebut RSA-PSS yang efisien dan terbukti menjaga tingkat keamanan terbaik

openssl dgst -<hash_algorithm> -out <digest> <input_file>

Dimana,

  • hash_algorithm - algoritma hash yang digunakan untuk menghitung digest. Ada beberapa algoritma yang tersedia, seperti: SHA-1 (opsi -sha1) dengan 160 bit digests output, MD5(opsi -md5) dengan 128 bit output dan RIPEMD160 (opsi -ripemd160) dengan 160 bit output.
  • digest - file yang berisi hasil hash dari aplikasi di input_file.
  • input_file - berisi file yang akan di hitung hash-nya.

Perintah ini bisa digunakan untuk mengecek nilai hash dari file / arsip. Untuk menghitung tanda tangan dari ringkasannya:

openssl rsautl -sign -in <digest> -out <signature> -inkey <key>

Untuk mencek validitas dari sebuah tanda tangan:

openssl rsautl -verify -in <signature> -out <digest> \
        -inkey <key> -pubin

Dimana,

  • -pubin dipakai jika key yang digunakan adalah public key, ini biasa digunakan untuk memverifikasi signature. Untuk menyelesaikan proses verifikasi, kita perlu menghitung digest dari input file dan membandingkannya dengan digest yang di peroleh dari verifikasi digital signature.

Public Key Infrastructure

4.1 What is a PKI? (in short)

4.1.1 The Problem: Man in the Middle Attack

One of the major breakthrough of public key cryptography is to solve the problem of key distribution. Secret key cryptography supposes the participants already agreed on a common secret. But how do they manage this in practice? Sending the key through an encrypted channel seems the more natural and practical solution but once again we need a common secret key to do this. With public key cryptography things are a lot simpler: if I want to send a message to Bob, I only need to find Bob’s public key (on his homepage, on a public key directory ...) encrypt the message using this key and send the result to Bob. Then Bob using his own private key can recover the plain text. However a big problem remains. What happens if a malicious person called The Ugly makes me believe that the public key he owns is in fact Bob’s one? Simply I will send an encrypted message using The Ugly’s public key thinking I’m communicating with Bob. The Ugly will receive the message, decrypt it, and will then encrypt the plaintext with Bob’s (real) public key. Bob will receive the encrypted message, will answer probably with another encrypted message using The Ugly’s public key (who once again managed to convince Bob, this public key belongs to me). Afterwards The Ugly will decrypt the message, reencrypt it with my public key, so I will really receive the Bob’s answer. Indeed I will be communicating with Bob, but without confidentiality. This attack is called “Man in the middle Attack”, where the man is of course The Ugly of our little story. So we need a mechanism to associate in a trustworthy way a public key to the identity of a person (name, identity card number ...). One of this mechanism is implemented in PGP. The idea is that every one builds his own net of trust, by having a list of trusted public keys, and by sharing these keys. The other solution is the use of a PKI.

4.1.2 A solution: Public Key Infrastructure

Public Key Infrastructure is a centralized solution to the problem of trust. The idea is to have a trusted entity (organization, corporation) that will do the job of certifying that a given public key belongs really to a given person. This person must be identified by his name, address and other useful information that may allow to know who this person is. Once this work his done, the PKI emits a public certificate for this person. This certificate contains between others:

   All the information needed to identify this person (name, birth date,...).
   The public key of this person.
   The date of creation of the certificate.
   The date of revocation of the certificate (a certificate is valid during 1 or 3 years in practice).
   The digital signature of all this previous information emitted by the PKI. 

So now, if I want to send a private message to Bob, I can ask for his certificate. When I received the certificate, I must check the signature of the PKI who emitted it and for the date of revocation. If verifications pass then I can safely use the public key of the certificate to communicate with Bob. Indeed, in practice the way a PKI works is much more complicated. For example sometimes a certificate may be revocated before the date of end of validity has been reached. So a kind of list of revocated certificated has to be maintained and accessed every time you want to use a certificate. The problem of certificate revocation is really difficult in practice.

4.2 My first PKI with OpenSSL

This section will show how to create your own small PKI. Obviously this is only a tutorial and you SHOULD NOT base a real application only on the information contained in this page!

4.2.1 openssl.cnf: let’s configure a few things

Before starting to create certificates it is necesarry to configure a few parameters. That can be done editing the file openssl.cnf the is usually located in the bin directory of OpenSSL. This file looks like this:

openssl.cnf


  1. OpenSSL example configuration file.
  2. This is mostly being used for generation of certificate requests.
  1. This definition stops the following lines choking if HOME isn't
  2. defined.

HOME = . RANDFILE = $ENV::HOME/.rnd

  1. Extra OBJECT IDENTIFIER info:
  2. oid_file = $ENV::HOME/.oid

oid_section = new_oids

  1. To use this configuration file with the "-extfile" option of the
  2. "openssl x509" utility, name here the section containing the
  3. X.509v3 extensions to use:
  4. extensions =
  5. (Alternatively, use a configuration file that has only
  6. X.509v3 extensions in its main [= default] section.)

[ new_oids ]

  1. We can add new OIDs in here for use by 'ca' and 'req'.
  2. Add a simple OID like this:
  3. testoid1=1.2.3.4
  4. Or use config file substitution like this:
  5. testoid2=${testoid1}.5.6

[ ca ] default_ca = CA_default # The default ca section

[ CA_default ]

dir = "/home/philippe/openssl" # Where everything is kept certs = $dir/certs # Where the issued certs are kept crl_dir = $dir/crl # Where the issued crl are kept database = $dir/index.txt # database index file.

  1. unique_subject = no # Set to 'no' to allow creation of
                 # several ctificates with same subject.

new_certs_dir = $dir/newcerts # default place for new certs.

certificate = $dir/cacert.pem # The CA certificate serial = $dir/serial # The current serial number crlnumber = $dir/crlnumber # the current crl number

                 # must be commented out to leave a V1 CRL

crl = $dir/crl.pem # The current CRL private_key = $dir/private/cakey.pem # The private key RANDFILE = $dir/private/.rnd # private random number file

x509_extensions = usr_cert # The extentions to add to the cert

  1. Comment out the following two lines for the "traditional"
  2. (and highly broken) format.

name_opt = ca_default # Subject Name options cert_opt = ca_default # Certificate field options

  1. Extension copying option: use with caution.
  2. copy_extensions = copy
  1. Extensions to add to a CRL. Note: Netscape communicator chokes on V2 CRLs
  2. so this is commented out by default to leave a V1 CRL.
  3. crlnumber must also be commented out to leave a V1 CRL.
  4. crl_extensions = crl_ext

default_days = 365 # how long to certify for default_crl_days= 30 # how long before next CRL default_md = sha1 # which md to use. preserve = no # keep passed DN ordering

  1. A few difference way of specifying how similar the request should look
  2. For type CA, the listed attributes must be the same, and the optional
  3. and supplied fields are just that :-)

policy = policy_match

  1. For the CA policy

[ policy_match ] countryName = match stateOrProvinceName = match organizationName = match organizationalUnitName = optional commonName = supplied emailAddress = optional

....



If you want to simplify your work you should use the default openssl.cnf file with the demoCA directory (also in the bin directory of OpenSSL) that contains all the necesarry files. You should ensure that all the directories are valid ones, and that the private key that will be created in the next section (cakey.pem) is well linked. Also check of the presence of a file .rand or .rnd that will bee created with cakey.pem. For the certificates database you can create an empty file index.txt. Also create a serial file serial with the text for example 011E. 011E is the serial number for the next certificate.

4.2.2 PKI creation

First we must create a certificate for the PKI that will contain a pair of public / private key. The private key will be used to sign the certificates.

openssl req -new -x509 -keyout cakey.pem -out cacert.pem
 	



The pair of keys will be in cakey.pem and the certificate (which does NOT contain the private key, only the public) is saved in cacert.pem. During the execution you will be asked for many informations about your organization (name, country, and so on ...). The private key contained in cakey.pem is encrypted with a password. This file should be put in a very secure place (although it is encrypted). -x509 refers to a standard that defines how information of the certificate is coded. It can be useful to export the certificate of the PKI in DER format as to be able to load it into your browser.

openssl x509 -in cacert.pem -outform DER -out cacert.der


4.2.3 Creation of a user certificate

Now the PKI has got its own pair of keys and certificate, let’s suppose a user wants to get a certificate from the PKI. To do so he must create a certificate request, that will contain all the information needed for the certificate (name, country, ... and the public key of the user of course). This certificate request is sent to the PKI.

openssl req -new -keyout userkey.pem -out usercert-req.pem
 	

Note this command will create the pair of keys and the certificate request. The pair of keys is saved in userkey.pem and the certificate request in usercert-req.pem. The PKI is ready for the next step: signing the certificate request to obtain the user’s certificate.


openssl ca -in usercert-req.pem -out usercert.pem

Using configuration from /usr/local/bin/openssl/openssl.cnf Loading 'screen' into random state - done Enter pass phrase for demoCA/private/cakey.pem: Check that the request matches the signature Signature ok Certificate Details:

       Serial Number: 286 (0x11e)
       Validity
           Not Before: Jan 19 12:52:37 2008 GMT
           Not After : Jan 18 12:52:37 2009 GMT
       Subject:
           countryName               = CL
           stateOrProvinceName       = RM
           organizationName          = littlecryptographer
           commonName                = John Smith
           emailAddress              = jsmith@hello.com
       X509v3 extensions:
           X509v3 Basic Constraints:
               CA:FALSE
           Netscape Comment:
               OpenSSL Generated Certificate
           X509v3 Subject Key Identifier:
               34:F0:61:38:87:68:C7:25:93:86:90:35:32:40:4F:...
           X509v3 Authority Key Identifier:
               keyid:FE:CB:56:0B:28:EB:2A:E9:C7:9C:EA:E5:3A:...

Certificate is to be certified until Jan 18 12:52:37 2009 GMT (365 days) Sign the certificate? [y/n]:y



usercert.pem is the public certificate signed by the PKI. If you want to import this certificate into your browser you need to convert it in PKCS12 format:


> openssl pkcs12 -export -in usercert.pem -inkey userkey.pem > usercert.p12



Congratulations! You have created your first home-made PKI!

Referensi