How to use the public, private key-pair and certificate?



I can meet lots of SSL certification to protect web server host. I am not the security engineer. Therefore, It is difficult to understand the relationship private-public key pair and the certification. I have recently found the answer from here. Now I will follow these if it works or not. In this post, I will use "openssl" to handle.


1. Install the "openssl" on ubuntu


Basically, this openssl has been installed on ubuntu, therfore, I do not need to install again.


# apt-get install openssl 


2. Generate the private keys


In this post, I create private key of 2048 size with RSA algorithm at first. 


# openssl genrsa -out myprivate.pem 2048

Generating RSA private key, 2048 bit long modulus

......+++

...............................................+++

e is 65537 (0x10001)


# cat myprivate.pem

-----BEGIN RSA PRIVATE KEY-----

something............xxxxxxxxxxxxxxxxxxxxxxxxx

-----END RSA PRIVATE KEY----- 


3. Generate the public keys


With the private key, I can generate the public key with RSA key management command.


# openssl rsa -in myprivate.pem -outform PEM -pubout -out public.pem

writing RSA key


# cat public.pem

-----BEGIN PUBLIC KEY-----

something............xxxxxxxxxxxxxxxxxxxxxxxxx

-----END PUBLIC KEY-----


4. Create a CSR (Certificate Signing Request)


To create a CSR, "req" command is for PKCS#10 X.509 Certificate Signing Request (CSR) Management. CSR should be created with the private key which is created. During creation, some information are required to insert.


# openssl req -new -key myprivate.pem -out mycert.csr

You are about to be asked to enter information that will be incorporated

into your certificate request.

What you are about to enter is what is called a Distinguished Name or a DN.

There are quite a few fields but you can leave some blank

For some fields there will be a default value,

If you enter '.', the field will be left blank.

-----

Country Name (2 letter code) [AU]:KR

State or Province Name (full name) [Some-State]:SEOUL

Locality Name (eg, city) []:

Organization Name (eg, company) [Internet Widgits Pty Ltd]:

Organizational Unit Name (eg, section) []:

Common Name (e.g. server FQDN or YOUR name) []:

Email Address []:


Please enter the following 'extra' attributes

to be sent with your certificate request

A challenge password []:

An optional company name []:


After above status, I will get csr file.


5. Create a Self-signed Certificate 


With the create CSR file and Private key, I can create the Self-signed Certificate (CRT) file, which I can share

# openssl x509 -req -days 365 -in mycert.csr -signkey myprivate.pem -out cert.crt

Signature ok

subject=/C=KR/ST=SEOUL/O=Internet Widgits Pty Ltd

Getting Private key


I create the CRT file with expiration. (-days option define the date to expire). This is important because CRT file can be shared.


6. How to Use these Keys and Certifications


Now, I have four files (Public-Private Key Pairs, CSR and CRT files). At first, I create sample documentation. 


# cat this_sample.txt

Hi, I am doing some test now


Before I encrypt file above. I want to see the command option of "openssl rsautl". In this command, I will use -encrypt and -decrypt options. Please note that -encrypt require "public key" not "private key" and reverse versa. "-pkcs" option is default pandding option.


# openssl rsautl --help

Usage: rsautl [options]

-in file        input file

-out file       output file

-inkey file     input key

-keyform arg    private key format - default PEM

-pubin          input is an RSA public

-certin         input is a certificate carrying an RSA public key

-ssl            use SSL v2 padding

-raw            use no padding

-pkcs           use PKCS#1 v1.5 padding (default)

-oaep           use PKCS#1 OAEP

-sign           sign with private key

-verify         verify with public key

-encrypt        encrypt with public key

-decrypt        decrypt with private key

-hexdump        hex dump output

-engine e       use engine e, possibly a hardware device.

-passin arg    pass phrase source


Now, I encrypt this file with Public key with RSA utility command which are used for signing, verification, encryption and decryption. Please, note "-pubin" option is important factor to encrypt file.


# openssl rsautl -encrypt -inkey public.pem -pubin -in this_sample.txt -out encrypted_sample


Now, I have encrypted file. At this time, I have some question. How can I recover this file. 


# openssl rsautl -decrypt -inkey myprivate.pem -keyform PEM -in encrypted_sample -out decrypted_sample


# cat decrypted_sample

Hi, I am doing some test now


It's works. However, I have something left. What is the CRT file for?. CRT file can be shared. Someone can get the public key from this CRT file.


# openssl x509 -pubkey -in cert.crt -out certpubkey.pem

-----BEGIN PUBLIC KEY-----

something......... xxxxxxxxxxxxxxxxxxx

-----END PUBLIC KEY-----


With this public key, I can send some file with encryption.


7. Encrypt with Private Key and Decrypt with Public Key


So far, I encrypt with Public key and I decrypt with Private key. However, I have question if it is do with reverse. The answer is "yes". However, it is not possible with "openssl" command line. Therefore, I can not handle this anymore at this time in this post.


Reference


[ 1 ] https://security.stackexchange.com/questions/108508/how-do-i-produce-a-ca-signed-public-key

[ 2 ] https://unix.stackexchange.com/questions/296697/how-to-encrypt-a-file-with-private-key

What to use WMI(Windows Management Instrumentation) from remote Linux server?



Usually, I can access and run some command with SSH. In this case, I used "Paramiko" module. This is sample code which I create. However, I have some questions from here. It is if is possible to access and run some command with RDP. At this time. I can not found any solution for this. But I have found about "WMI (Windows Management Instrucmentation)". It make I can get some information which is offered by Window OS with WMI.


1. Install python-wmi-client-wrapper.


In this "Git", there is the way how to installation for this


pip install wmi-client-wrapper 


2. Install WMI


"WMI" is the package for Window OS. Therefore, the wrapper is necessary. The first step is to obtain these wrapper. Thus, I still need "WMI" main module. In my case, I used Ubuntu 16.04 LTS, and I will install WMI 1.3.16.


ulimit -n 100000

cd /tmp

mkdir wmic

cd wmic


apt install autoconf gcc libdatetime-perl make build-essential g++ python-dev

wget http://www.opsview.com/sites/default/files/wmi-1.3.16.tar_.bz2

bunzip2 wmi-1.3.16.tar_.bz2

tar -xvf wmi-1.3.16.tar_

cd wmi-1.3.16/


After above, I need edit some line of file to make and build this WMI.


vim Samba/source/pidl/pidl

:583 (to jump to line 583)

remove the word defined before @$pidl

:wq

========= Look here =============
$pidl = Parse::Pidl::IDL::parse_file($idl_file, \@opt_incdirs);
defined @$pidl || die "Failed to parse $idl_file";  >>>> @$pidl || die "Failed to parse $idl_file";
require Parse::Pidl::Typelist;
=============================


And I need export some values also.


export ZENHOME=/usr

make "CPP=gcc -E -ffreestanding"

cp Samba/source/bin/wmic /bin


Now, I can use WMI and WMI-wrapper. From now, I will do some sample code. 


3. Create the sample code.


I will create some sample code to obtain the Window Processor Information.


import wmi_client_wrapper as wmi


wmic = wmi.WmiClientWrapper(

    username="Administrator",

    password="password",

    host="172.22.0.123",

)


output = wmic.query("SELECT * FROM Win32_Processor")


After run this command, I will get some result with JSON format.


# ./sample.py

[{'L2CacheSize': '0', 'VMMonitorModeExtensions': False, 'ConfigManagerErrorCode': '0', 'VoltageCaps': '0', 'PowerManagementSupported': False, 'LoadPercentage': '12', 'SerialNumber': '', 'ThreadCount': '0', 'Version': '', 'MaxClockSpeed': '2400', 'CpuStatus': '1', 'PartNumber': '', 'SecondLevelAddressTranslationExtensions': False, 'Revision': '16130', 'Status': 'OK', 'PNPDeviceID': None, 'L2CacheSpeed': '0', 'AddressWidth': '64', 'ConfigManagerUserConfig': False, 'ErrorCleared': False, 'ProcessorId': '1789FBFF000306F2', 'ProcessorType': '3', 'DeviceID': 'CPU0', 'CurrentVoltage': '0', 'CurrentClockSpeed': '2400', 'Manufacturer': 'GenuineIntel', 'Name': 'Intel(R) Xeon(R) CPU E5-2676 v3 @ 2.40GHz', 'InstallDate': None, 'Level': '6', 'AssetTag': '', 'SocketDesignation': 'CPU 1', 'NumberOfCores': '1', 'Caption': 'Intel64 Family 6 Model 63 Stepping 2', 'StatusInfo': '3', 'Architecture': '9', 'UniqueId': None, 'PowerManagementCapabilities': 'NULL', 'OtherFamilyDescription': None, 'Description': 'Intel64 Family 6 Model 63 Stepping 2', 'CreationClassName': 'Win32_Processor', 'NumberOfLogicalProcessors': '1', 'Family': '5', 'ErrorDescription': None, 'Characteristics': '2816', 'UpgradeMethod': '1', 'SystemName': 'EC2AMAZ-JC32MSV', 'NumberOfEnabledCore': '108', 'LastErrorCode': '0', 'ExtClock': '0', 'Stepping': None, 'VirtualizationFirmwareEnabled': False, 'Role': 'CPU', 'L3CacheSize': '0', 'L3CacheSpeed': '0', 'Availability': '3', 'SystemCreationClassName': 'Win32_ComputerSystem', 'DataWidth': '64'}]


4. Troubleshooting


During I try this, I do not open any security rule for this. I am question for this. I want to know if what port is used for this running. I dump the packet on my host. "135" Port are used. This port is RPC for Window. It is default opened.


04:19:44.298786 IP 172.22.0.216.46372 > 172.22.0.123.135: Flags [S], seq 2010311507, win 26883, options [mss 8961,sackOK,TS val 2762852 ecr 0,nop,wscale 7], length 0

04:19:44.299089 IP 172.22.0.123.135 > 172.22.0.216.46372: Flags [S.], seq 1265146297, ack 2010311508, win 8192, options [mss 8961,nop,w cale 8,sackOK,TS val 1122704139 ecr 2762852], length 0

04:19:44.299098 IP 172.22.0.216.46372 > 172.22.0.123.135: Flags [.], ack 1, win 211, options [nop,nop,TS val 2762853 ecr 1122704139], length 0


I run "netstat -an" on Window. The result is look like below.


  TCP    172.22.0.123:59796     52.23.123.168:443      ESTABLISHED

  TCP    172.22.0.123:60018     198.252.206.25:443     ESTABLISHED

  TCP    [::]:135               [::]:0                 LISTENING

  TCP    [::]:445               [::]:0                 LISTENING 


Reference 


[ 1 ] https://www.shellandco.net/wmic-command-ubuntu-16-04-lts/

[ 2 ] https://askubuntu.com/questions/885407/installing-wmic-on-ubuntu-16-04-lts

[ 3 ] https://github.com/kanzure/python-wmi-client-wrapper



+ Recent posts