Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Openssl and encryption and decryption (2) openssl

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/03 Report--

Openssl is a conditional implementation of hundreds of algorithms, the implementation of one-way encryption tools and other set of suites, the amount of code is very small but powerful. It consists of three parts:

Libcrypto: an encryption library for general functions, which can be called directly during software development.

Libssl: implement the function of TLS/SSL

Openssl: multi-functional command line tools for encryption, decryption, creation of CA, certificates, a pair of keys, etc.

Openssl enc encryption and decryption command:

Parameter description-des3 is the specified encryption algorithm-an is the output file output according to base64 content, otherwise it is binary-in

File to be encrypted-out

Encrypted file-salt

Add salt-d to decrypt

We set up a file to encrypt, and the source file is

Openssl enc-des3-a-salt-in / work/aaa.txt-out / work/aaa.enc

Enter the password twice

Decrypt the file just now

Openssl enc-d-des3-a-salt-in / work/aaa.enc-out / work/aaa.out

Openssl one-way encryption:

The common ones are md5, sha1, sha256 and so on. The system itself has these tools as shown below:

We now use the openssl dest command to do this.

Openssl dgst-md5 FILE

Openssl asymmetric encryption:

Generally, the private key is used to encrypt the public key for decryption, but if you want to make an electronic signature, you need to use the private key for encryption and the public key for decryption. The most commonly used is RSA. Again, the public key will not be used for data encryption because it is too slow and is usually used for key exchange and authentication.

Digital signature:

Public key encryption and private key decryption, we know that the digital signature will not encrypt the data itself with the public key, but the signature of the encrypted data. Commonly used algorithms RSA, DSA (can only be used for signature, not encryption). The signature itself is still encrypted, so this means that DSA can only be encrypted with a public key and decrypted with a private key, not vice versa. And RSA can.

Digital Certificate:

In order to ensure the reliability of the public key source. A has the public key of CA, and B applies for a certificate from CA and the certificate (including the public key of B and the information of B) contains the electronic signature of CA (encrypted by CA private key). B sends the certificate to A Magi An and uses the public key of CA to decrypt the electronic signature to verify its validity. Certificate format includes: x509 and so on. The contents of the certificate include the applicant's public key, certificate expiration time, applicant's legal identity information (address, country, institution name, etc.), certificate usage, CA information, CA digital signature (summary information of the first four items of the certificate encrypted by CA private key)

We know that you enter a domain name when you visit an e-commerce website or a bank website. how do you know that the website you visit is the real one and not forged by others? This is the use of ssl, this site is bound to a certificate, and the domain name you enter is included in the legal identity information of the applicant in the certificate. Because the client trusts the major international CA institutions, in order to make the client trust the website he wants to visit, the company to which the website belongs has to apply for a certificate from CA. Who generated the private key and public key? Obviously, the private key and public key are generated by the applicant (you can't ask CA to generate it for you, because if CA is generated, it means that CA has your private key), and then send the public key and other necessary information to CA,CA for approval and issue a certificate. So what you need to do to apply for a certificate is:

Generate a pair of private and public keys by yourself

Fill in the public key, domain name and other necessary information in a fixed format and submit it to CA

In the future communication, the client will obtain the certificate of the website when he visits the website, then verify the validity, then check the validity period, and finally go to CA to see if the certificate has been revoked.

We know that openssl can generate public and private keys and can also build CA, so we will demonstrate from these two aspects. Two machines

Linux01 is the server side-- CA server

Linux02 for client-apply for certificate

Demo: set up a CA

If you are using it on a small scale within an enterprise, you can use this tool to build your own CA and then issue certificates to your servers and manage revocation lists and other operations.

The configuration file for building a private CA is in / etc/pki/tls/openssl.cnf, which generally does not need to be modified, but some configurations need to be understood.

Parameter indicates where the working directory of the openssl is if dir wants to make openssl into CA.

The certificates issued by certsCA are put here, and the list of certificates revoked by crl_dirCA relative to CA's working directory is put there by default.

Database index file database, automatically generate this file, through this file you can quickly see which certificates new_certs_dir

Where is the certificate just signed? where is certificateCA's own certificate? here is the public key serial.

Current serial number, the serial number crlnumber of the certificate issued by CA

Revoke the serial number of the certificate crl

CRL currently in use, certificate revocation list file private_key

CA's own private key RANDFILE

Random data file

Enter the working directory / etc/pki/CA to generate a private key pair

The private key is generated by this command, and the public key is extracted from the private key. The name of the private key should be the same as in the configuration file

Openssl genrsa-out. / private/cakey.pem 204modify permissions are not required, just for security purposes. Chmod 600. / private/cakey.pem

Generate certificates. Openssl req is a certificate request tool, and you can also sign your own certificates.

Parameter description

-in FILENAME

Input file, but usually we use-key-key FILENAME to specify the private key file, it will extract the public key from the private key file-days N validity period-x509 self-signed certificate format, only use-out FILENAMEA for self-signed certificates

Where do you put the certificate? use-new only for self-signed certificates.

For a new application openssl req-new-x509-key. / private/cakey.pem-out cacert.pem-days 3655

Cacert.pem this is also defined in the configuration file above. Executing the command starts a wizard and enters the necessary information. This information can also be defined in the second half of the above file so that you don't have to enter it every time.

Generate three missing basic files serial, index.txt, crlnumber, and create three files

Touche. / index.txt serial crlnumber# may need the file index.txt.attr, which has been encountered before, so you also set up one.

Initialize the serial file, you can also write 00, because the issuance of certificates must always have a serial number mark.

Echo 01 > serial

At this point, the CA is built.

Demo: generate public and private key pairs

Here we demonstrate to the site on Nginx to apply for a certificate as an example, this certificate should be placed in the Nginx directory, I will set up a certs directory here, and then apply for the certificate. This name I call nginx.pri, actually the name does not matter, the length I use 1024.

Openssl genrsa-out. / nginx.pri 1024

Generate a certificate request

Openssl req-new-key. / nginx.pri-out new_cacert.req

We copy the generated request file to the CA server, and I put it under / tmp here, but it's the same everywhere. Finally, you have to use the command to sign the request.

Scp new_cacert.req 172.16.100.29:/tmp/

Issue the certificate (executed on the CA server), and then copy the certificate to the client server

Openssl ca-in / tmp/new_cacert.req-out / tmp/nginx.crt-days 3655

SSL/TLS:

Https actually introduces ssl or tls. How does it work? TCP/IP protocol has four layers, none of which is encrypted, so how to realize the secure communication of http? Is to add a half layer between the application layer and the transport layer, it is not a whole layer, because not all applications need to be encrypted, if you add a whole layer, then everything is encrypted.

SSL is developed by Netscape to achieve secure communication between its browser and WEB server. It is called secure socket sublayer. The socket itself is registered in the kernel by the application layer program, so a half layer is added between the application layer and the transport layer, including the SSL library. If the program calls this library, it can achieve secure communication.

TLS is modelled on SSL and is called transport layer security, and its mechanism is very similar to that of SSL, except that something has changed. TLSv1 and SSLv3 are very close, and these two versions are commonly used in practical applications.

So the application layer protocol calls SSL or TLS is the secure communication, for example, after the http call becomes https and so on. Here's how the most commonly used https is implemented:

The premise of the scenario is that you visit Taobao for the first time, you want to make sure that you visit the real Taobao, not fake, and that the communication is encrypted and secure.

The client opens a browser to enter the Taobao website

DNS domain name resolution, when you get the IP address, communicate with the IP

Communicate with the given IP, and the TCP three-way handshake is performed to establish the session. Let's start the SSL handshake.

After the TCP connection is established, the browser initiates a HTTPS request and sends the encryption rules that it supports to the website, which selects a set of encryption methods and HASH algorithms, and then sends the website certificate (which contains the public key, digital signature and other information) to the browser.

The browser inquires whether the certificate authority is a trusted CA authority. If the certificate is decrypted with CA's public key to obtain the digital signature of the certificate, if the certificate is decrypted successfully, the source of the certificate is reliable, then check the validity period of the certificate, and then go to the CA on the Internet to query whether the certificate is revoked. If any of the above fails, you will get a prompt. If passed in the address bar, a green lock sign will appear. (authentication)

If trusted or the user actively chooses trust, the browser generates a random password and encrypts it with the public key in the website certificate (the key is passed, and the password generated by the browser is symmetrically encrypted to encrypt communication data)

The browser uses the previously agreed HASH information to calculate the handshake information to get the information summary, then encrypts the handshake information with the generated random password, and then sends the summary + encrypted handshake information + the encrypted password of the website public key to the website (information encryption, data consistency)

The website receives the encrypted information, decrypts it with its own private key and gets the password. Then use the password to decrypt the handshake information, and then compare the Hash value sent by the browser with the Hash value calculated according to the handshake information to see if it is the same, if the same proof has not been tampered with.

The website uses the same way to encrypt handshake information and send it to the browser

The SSL handshake ends and the SSL data transfer begins. After that, all the transferred data is encrypted by the password generated by the browser.

Note: the server generally does not verify the client certificate, because except in special cases, the client has to install the client certificate for the server to verify. In addition, in order to avoid being cracked by violence, the SSL session has a duration. If there is no request beyond this time, it will be disconnected automatically. If you want to connect again, repeat the above process.

Telnet and SSH:

The early implementation of remote login uses Telnet, and the server supports the client to establish a remote connection session locally, extending the virtual terminal that should have been displayed on the server to the client to display. In the early days, they were all physical terminals, and a physical terminal corresponds to a graphics card interface and a corresponding keyboard. Multiple users need to use multiple physical terminals to connect, and then there are virtual terminals. That is, there is only one monitor and graphics card, but multiple login interfaces can be displayed, but when it is impossible for the server to log in, they all go to the server to open the terminal, so they can log in remotely and run a software on the server. monitor on a certain port, used to wait for the client to log in to connect If you want a user to see the login interface to enter a user name and password, it must be related to the terminal used by the user. We know that the login interface is a login program, which must be associated with the user interface before it can be completed. The user interface is usually a device, and this device is a terminal device. If it is a physical terminal, it is easy to solve, but what about the remote host? The mouse, keyboard and monitor of the remote host are associated to the server and resolved by the server to the local login device. All have Telnet, but its transmission is clear text, very insecure. So there's ssh, an abbreviation called Secure Shell, which listens on port 22.

In the scenario of using SSH, you usually need to use a certificate, but it is not necessary. If you do not have a certificate, how can you ensure that the server you log in to is the server you want to log in to? when you log in with SSH, you will get a prompt for the first time, which contains the fingerprint information of the server, and then ask whether you trust the computer, if you enter YES. Then the fingerprint information of this server will be recorded in a list on your local machine (know_hosts file) and there will be no prompt next time. This is equivalent to manually trusting the host, all without a certificate. If you have a certificate, you don't need to trust it manually. But after this stage, you have to enter a user name and password to verify, how to encrypt this information? In fact, before you see the login information entered, the ssh client and the server negotiate the encryption method. The client generates an one-time symmetric encryption key, then encrypts and sends it to the server with the server's public key, and completes the secret key exchange. Then the client uses the encryption key to encrypt the user name and password information to send to the server, and the server uses the private key to decrypt the information and verify it. And then use this password to communicate with each other. But ssh is different from https, https communication will be broken without a request for a period of time, but ssh will not be online all the time, but there is a problem, because it is not automatically disconnected, so if someone else captures your communication for brute force cracking, once successful, then it can use this password. So how to solve this problem? It is very simple to change the password at any time, that is, to negotiate to change the password at regular intervals, but the connection keeps opening. The software implemented on Linux based on ssh is openssh.

Ssh authentication mechanism: password-based and key-based, usually based on secret key. What it needs is also very simple.

The client generates a pair of keys locally, which is actually a private key. The public key is extracted from the private key, but ssh will automatically extract it for you.

The client copies the public key to the authorized_keys or authorized_keys2 file in the .ssh directory under the home directory of the user to be logged in on the server

# generate a key pair, save it in the .ssh directory in the user's home directory, and generate two files: id_rsa is the private key id_rsa.pub is the public key ssh-key-t rsa

Description: should the above password be set to empty? This password is set for the private key, in order to protect the private key file, so set the password, but if you set the password here, you have to enter the password every time you use this private key, for example, when you ssh to the target host, you will use your private key, and then you have to enter the password. So either not encrypt, or let the process remember the password, such as ssh-add or ssh-agent, it will record these passwords and then a common sense.

Copy the key to the remote host

Ssh-copy-id-I public key file user @ host IP

Note: the user here is which user you want to log in with. In fact, this command is to write the contents of the public key file to the authorized_keys file in the .ssh directory of the root user's home directory of the target host.

The server-side program for openssh is sshd, so let's talk about its configuration files and scripts:

Configuration file: / etc/ssh/sshd_config

Service script: / etc/rc.d/init.d/sshd

Script configuration file: / etc/sysconfig/sshd

Parameter indicates that Port defaults to 22ListenAddress listening address, defaults to all Protocal protocol versions, and defaults to 2HostKey

It is the secret key of the host. What is stored in the local know_host is the public key that logged in to the host, such as A login B, then B's public key will be stored in the know_host of A, and the public key will be stored in / etc/ssh/ssh_host_rsa_key. This will be used by default.

KeyRegenerationInterval We know that the communication between the two hosts will generate a temporary secret key for symmetric encryption. The validity period of this password is defined by this parameter. By default, the length of the ServerKeyBits host key is the LoginGraceTime login grace period, how long to wait for the password prompt, and if no password is entered during this period, the connection will be disconnected. Whether the default 2-minute PermitRootLogin allows administrators to log in, the default is to allow StrictModes strict mode, in addition to verifying the user name and password, but also depends on whether you want to log in to the server you use the user's home directory and the permissions inside. The maximum number of MaxAuthTries authentication attempts is 6 MaxSessions sessions. The default is whether 10 RSAAuthentication use RSA authentication, the default is whether YESPubkeyAuthentication uses public key authentication, the default is the file used for YESAuthorizedKeysFile verification, and the default is .ssh / authorized_keys, which is the file where the other party's public key is stored. Whether RhostsRSAAuthentication no allows authentication based on remote hosts, that is, whether hosts An and B trust each other, then users of B can log in to host A, default is whether NOPasswordAuthentication allows input password for authentication, default is whether YESChallengeResponseAuthentication enables challenge handshake authentication, default is whether NOGSSAPIAuthentication allows GSSAPI authentication, default is whether YESGSSAPICleanupCredentials clears authentication process, default is whether YESUsePAM uses PAM authentication, default is YESAllowUsers

User whitelist, that is, only those users are allowed to log in to DenyUsers

User blacklist ClientAliveInterval client activity interval, that is, the timeout (in seconds).

ClientAliveCountMax

The number of client active messages, and the client can send multiple commands to the server before receiving a response from the server.

Best practices for using SSH:

Use only the SSH2 version

Restrict user login and use blacklist and whitelist

Configure the idle session timeout, that is, how long it takes to automatically disconnect without entering a command. ClientAliveInterval 、 ClientAliveCountMax

Use iptables to set the ssh service security access policy, that is, only which IP segments are allowed to access

Change the ssh default port number

Use strong passwords, long enough and complex

Use public key-based authentication

It is forbidden to log in with an empty password. It is prohibited by default.

Use the brute force cracking tool to crack it yourself first.

Limit the frequency of ssh method

Check the log often to see if anyone is trying to crack it.

Generate a strong password:

#! / bin/bashgenpasswd () {local len=$1 [$len= = "] & & len=20 # reads random numbers from / dev/urandom, then sends them to tr, deletes the characters through the-dc parameter, then sends them to # head-c, deletes the special characters, takes the first 20 digits, and processes tr-dc A-Za-z0-9 _ < / dev/urandom with xargs | head-c $len | xargs} genpasswd

Display user login information

# display the last successful login information of each user account on the current system, which host you logged in from, and which terminal lastloglastlog-u was used to display the specified user # display the current login user whoami# to display the recent failed login information on the current system, in fact, it is to search / var/log/btmp file lastb# to display the most recent successful login information on the current system, in fact, to search / var/log/wtmp file last

After compiling and installing openssl, you are prompted that the shared library file cannot be found.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report