Compliance baseline / safety compliance inspection is enough! (unfinished)

xdm! I'm back! Fight the undead cockroach, fight the undead Li Qiang

Compliance baseline

Host security compliance check

This article contains 16 common safety compliance checks!

Xiao Li said:

  • Search and replace files
    Syntax: sed option's / search content / replace content / action 'file
    Where s: represents search/ Separator (can be customized); The actions are generally p printing and global replacement g
    \Represents escape^ Represents replacing the entire line

Xiao Li said:
In linux, shell and regular expression are usually used to filter characters. This paper will illustrate some usage of +, *, [: space:] with a simple example
+Match 1 or more characters
*Match 0 or more characters
[: Space:] match white space characters, including spaces, tab

Xiao Li said:
Format of each line of PAM configuration file: (see below for details)
Module-type Control-flag Module-path Arguments
Module type control character module path module parameters

Xiao Li said:
① Insert a line of text above the line containing a keyword. The command is as follows:
sed -i '/hello/i\1234' testfile
After executing the command, the content after the backslash after i will be inserted above the line containing the hello keyword
② Insert a line of text under the line containing a keyword. The command is as follows:
sed -i '/hello/a\4567' testfile
After executing the command, the content after the backslash after a is inserted under the line containing the hello keyword

  1. User account and environment - check that the minimum password length is greater than or equal to 8

     id: 92014
        title: "User account and environment - Check whether the minimum password length is set to be greater than or equal to 8"
        description: "/etc/login.defs In the file PASS_MIN_LEN The parameter is the minimum length of password. Considering the complexity of password, it is recommended to PASS_MIN_LEN The parameter is set to 8 or above."
        rationale: "The minimum length of password should be greater than or equal to 8"
        condition: all
        rules:
          - 'f:/etc/login.defs -> n:^PASS_MIN_LEN\s*\t*(\d+)$ compare >= 8'
    
  2. User account and environment - check whether the password expiration time is less than or equal to 90 days

  3. User account and environment - check whether the minimum interval between password changes is greater than or equal to 7 days

  4. User account and environment - check whether the password expiration warning time is greater than or equal to 7 days

    /etc/login.defs file

    PASS_MAX_DAYS 60      #The maximum valid period of password is PASS_MAX_DAYS is 60, which means that the password will expire in 60 days. 99999 means never expire.
    PASS_MIN_DAYS 0      #The minimum interval between two password changes. 0 means that the account password can be changed at any time
    PASS_MIN_LEN  8      #Minimum password length, invalid for root
    PASS_WARN_AGE 7      #How many days before the password expires
    
    
    
    UID_MIN                   500
    UID_MAX                 60000 
    UID_MIN    #Minimum value of user ID
    UID_MAX    #Maximum value of user ID
    
    GID_MIN                   500
    GID_MAX                 60000
    GID_MIN    #Group ID min
    GID_MAX    #Group ID Max
    
    CREATE_HOME     yes 
    CREATE_HOME  #Indicates whether to create the user home directory
    USERGROUPS_ENAB yes 
    USERGROUPS_ENAB   #When this parameter is enabled, it means that when userdel deletes a user, if no member of the user group exists, the user group will be deleted
    
    MD5_CRYPT_ENAB yes 
    ENCRYPT_METHOD MD5   
    ENCRYPT_METHOD  #Indicates the encryption method of user password. Here, it indicates that MD5 is used to encrypt password
    
  5. Configure PAM authentication - check if password reuse is restricted

    Principle: / etc / PAM D / password auth and / etc / PAM D / system auth file should contain: password sufficient pam_unix.so remember=5

    $ sudo vi /etc/pam.d/common-passwordpassword [success=1 default=ignore] pam_unix.so obscure sha512 remember=5
    

    "remember=5" means that it is forbidden to use the five recently used passwords (the used passwords will be saved under / etc/security/opasswd)

  6. SSH service configuration - check whether the SSH idle timeout interval is set

    /etc/ssh/sshd_ ClientAliveInterval in config file should be set to less than or equal to 300, and ClientAliveCountMax should be set to less than or equal to 3

    ClientAliveInterval 300
    ClientAliveCountMax 3
    #According to the above configuration, 300 * 3 = 900 seconds = 15 minutes, that is, when the client does not respond in 15 minutes, the ssh connection will exit automatically.
    
  7. SSH service configuration - check whether the HostbasedAuthentication of SSH is disabled/

    etc/ssh/sshd_ HostbasedAuthentication in config file should be set to: no

    HostbasedAuthentication yes #Specifies whether authentication is allowed
    EnableSSHKeysign yes
    StrictHostKeyChecking no
    
  8. SSH service configuration - check whether the MaxAuthTries parameter of SSH is less than four

    The MaxAuthTries parameter (with an initial value of 6) specifies the maximum number of authentication attempts allowed per connection. When the login times reach half of the setting, the error information will be written to the syslog file for recording.

    Port 22960 
    LoginGraceTime 30  #Time limit for certification
    MaxAuthTries 3   #Number of certifications
    Protocol 2 
    PermitRootLogin no
    

    **sshd: * * use ssh protocol (a protocol designed to provide security for remote login sessions and other network services) to remotely open the services of other host shell s (with the highest permission).

    Secure Shell (SSH) is a network protocol that allows data exchange between two computers through a secure connection. Encryption ensures the confidentiality and integrity of data. SSH uses public key encryption technology to authenticate the remote host and (if necessary) allows the remote host to authenticate users. SSH is usually used for remote access and command execution, but it also supports tunneling, forwarding any tcp port and X11 connection; It can also transfer files using SFTP or SCP protocols. The ssh server listens on port 22 of tcp by default. An SSH client program usually establishes a remote connection daosshd daemon.

    systemctl start sshd   #Start sshd (provided the default 22 port is used)
    

    /etc/ssh/sshd_config file:

    # This is ssh server systemwide configuration file.
    Port 22  #Set the port number of sshd listening
    
    ListenAddress 192.168.1.1  #Set the IP address bound to the sshd server
    
    HostKey /etc/ssh/ssh_host_key  #Set up a file that contains your computer's private key.
    
    ServerKeyBits 1024   #Defines the number of bits of the server key.
    
    LoginGraceTime 600  #Set the time (in seconds) that the server needs to wait before disconnecting if the user cannot log in successfully
    
    KeyRegenerationInterval 3600  #Set the number of seconds after which the server's key is automatically regenerated (if a key is used). The key regeneration is to prevent the stolen key from decrypting the intercepted information.
    
    PermitRootLogin no  #Set whether root can log in with ssh. This option must not be set to "yes".
    
    IgnoreRhosts yes  #Set whether to use "rhosts" and "shosts" files during verification. This parameter can ignore the records of previously logged hosts.
    
    IgnoreUserKnownHosts yes  #Set whether ssh daemon ignores the user's "$HOME/.ssh/known_hosts" when performing the security authentication of RhostsRSAAuthentication
    
    StrictModes yes  #Set whether ssh checks the permission and ownership of the user's home directory and rhosts file before receiving the login request. This is usually necessary because novices often set their directories and files so that everyone has write permission.
    
    X11Forwarding no  #Set whether X11 forwarding is allowed.
    PrintMotd yes  #Set whether sshd displays the information in "/ etc/motd" when the user logs in.
    
    SyslogFacility AUTH  #Set whether to give "facility code" when recording messages from sshd.
    
    LogLevel INFO    #Set the level of logging sshd log messages. INFO is a good choice. Check the man help page of sshd for more information.
    
    RhostsAuthentication no   #Set whether it is sufficient to only use rhosts or "/ etc/hosts.equiv" for security verification.
    
    RhostsRSAAuthentication no   #Set whether rhosts or "/ etc/hosts.equiv" plus RSA are allowed for security authentication.
    
    RSAAuthentication yes   #Set whether only RSA Security authentication is allowed.
    
    PasswordAuthentication yes   #Set whether password authentication is allowed.
    
    PermitEmptyPasswords no  #Set whether to allow login with an account with a blank password.
     
    AllowUsers admin   # "AllowUsers" can be followed by any number of user name matching patterns or user@host Such matching strings, which are separated by spaces. The host name can be a DNS name or an IP address.
    
    
  9. SSH service configuration - check whether PermitEmptyPasswords of SSH is disabled

  10. SSH service configuration - check the protocol version used by SSH. ssh2 should be used

    SSH1 uses symmetric encryption algorithms such as DES, 3DES, Blowfish and RC4 to protect the safe transmission of data, while the key of symmetric encryption algorithm is exchanged through asymmetric encryption algorithm (RSA). SSH1 uses cyclic redundancy check code (CRC) to ensure data integrity, but it was later found that this method has defects.

    SSH2 uses digital signature algorithm (DSA) and Diffie Hellman (DH) algorithm instead of RSA to complete the exchange of symmetric keys, and uses message confirmation code (HMAC) instead of CRC. At the same time, SSH2 adds symmetric encryption algorithms such as AES and Twofish.

  11. Configure PAM authentication - check if password creation requirements are configured

    Principle: / etc / PAM D / password auth and / etc / PAM In the D / system auth file, the password creation requirements should be set, that is, the settings of retry, minlen, dcreduce, ucreduce, ocredit and lcreduce exist

    PAM separates the service provided by the system from the authentication mode of the service by providing some dynamic link libraries and a set of unified API s, so that the system administrator can flexibly configure different authentication modes for different services according to needs without changing the service program. At the same time, it is also convenient to add new authentication means to the system. PAM module is an embedded module, which takes effect immediately after modification.

    PAM configuration file syntax format
    Each PAM configuration file contains a set of instructions for defining modules and control flags and parameters. Each instruction has a simple syntax, which is used to identify the purpose (Interface) of the module and the configuration setting of the module. The syntax format is as follows:

    module_interface control_flag module_name module_arguments
    As in / etc / PAM In the D / password auth AC configuration file (CentOS), one line of PAM module interface is defined as follows
    Multiple login failures, user locked and using Pam_Tally2 unlock

Format of each line of PAM configuration file:

Module-type:

auth: identify two aspects of user authentication. First, he confirms that the user is themselves, which prompts the user to enter a password through the application
Or other formal means. Second, such modules give membership.

Account: handle non authentication level account management. A typical usage is to restrict and allow access to a service based on different times of the day. limit
Currently available system resources (maximum number of users) or limit specific users - root can only log in from the console.

session: a series of related actions that only need to be done when the user gets / loses the service. This includes recording user login / logout, mounting necessary directories, etc.

Password: set the password.

Control-flag:

required: indicates that the module must return success to pass the authentication, but if the module returns failure, the failure result will not be immediately returned
Notify the user, but wait until all modules in the same stack are executed, and then return the failure result to the application. It can be considered a necessary condition.

Required: similar to required, the module must return success to pass the authentication, but once the module returns failure, it will not be executed again
Any module in the same stack, but directly returns control to the application. Is a necessary condition. Note: Solaris does not support.

sufficient: indicates that the successful return of this module is enough to pass the requirements of identity authentication. It is not necessary to execute other modules in the same stack, but
If this module returns a failure, it can be ignored. It can be considered as a sufficient condition.

Optional: indicates that this module is optional. Its success generally does not play a key role in identity authentication, and its return value is generally ignored.

include, literally. Contains another configuration file.

Module-path:

Debian PAM
Module is stored in / lib/security by default. In the configuration file of each module, there is no need to write the absolute path, but directly
Just write the module name under the default directory. Of course, you can also write absolute paths.

Arguments:

The parameters of each module are different. For details, please refer to the developer's man ual. Invalid parameters will not affect the results, but will be logged
Come down. First, check whether / lib/security has this module, and then: man module name

PAM common modules

| PAM modular          | Combined management type(Module type)        | explain                                                         |
| ---------------- | ----------------------------- | ------------------------------------------------------------ |
| pam_unix.so      | auth                          | Prompt user for password,And with/etc/shadow File comparison.Match return 0         |
| pam_unix.so      | account                       | Check the user's account information(Including whether it has expired, etc).When account number is available,Return 0.         |
| pam_unix.so      | password                      | Change the user's password. The password entered by the user,New password update as user shadow file |
| pam_shells.so    | auth,account                 | If the user wants to log in to the system, its shell Must be in/etc/shells One of the files shell |
| pam_deny.so      | account,auth,password,session | This module can be used to deny access                                         |
| pam_permit.so    | account,auth,password,session | The module returns success at any time.                                      |
| pam_securetty.so | auth                          | If the user wants to root When logging in,Logged in tty Must be/etc/securetty in.  |
| pam_listfile.so  | account,auth,password,session | Control switch for accessing application                                         |





**cracklib modular**It is used to check whether the password violates the password dictionary. The strength detection of the password is carried out in two times. The first time is to detect whether the password is part of the comparison dictionary provided. If the detection result is negative, some additional tests will be provided to further detect its strength, such as detecting the proportion of characters in the new password in the characters of the old password and the length of the password, The case of characters used, whether special characters are used, etc

**cracklib Module parameter supplement:**

```
  debug: take debug Information writing syslog

  type=XXX: Prompt for the text content of the password. Default is"New UNIX password: " and "Retype UNIX password: ",Customizable

  retry=N: The user can enter the password several times at most and report an error. The default is once.

  difok=N: The new password cannot have the same characters as the old password. The default is 5. In addition, if the new password has 1/2 Characters are different from the old ones and will also be accepted.

  diginore=N: By default, when the new password has 23 characters, difok Options are ignored.

  minlen=N: Minimum password length.

  dcredit=N: When N>=0 When, N Represents the maximum number of Arabic numerals a new password can have. When N<0 When, N Represents the minimum number of Arabic numerals required for a new password.

  ucredit=N: and dcredit Almost, but it's capital letters.

  lcredit=N: and dcredit Almost, but here we're talking about lowercase letters.

  ocredit=N: and dcredit Almost, but this is about special characters.

  use_authtok: Use this option after a password related authentication module, for example pam_unix.so Verification module
```

pam_cracklib Modular PAM Configure the basic module of the interface in Debian The configuration file in the system is /etc/pam.d/common-password But in Redhat The configuration file in the system is /etc/pam.d/system-auth His configuration looks like this:

```
password required pam_cracklib.so retry=3 minlen=6 difok=3
#cracklib module and its parameters

password required pam_unix.so md5 use_authtok
#pam_unix module, using MD5 encryption. Through this module, the old password of users can be stored.
```
  1. Configure PAM authentication - check login failure configuration

    Online servers sometimes need to limit the number of user logins This function can be through pam_tally2.so module.

    /etc/pam. D / password auth and / etc / PAM D / system auth file should: set login failure lock.

    format

    • pam_tally2.so [file=/path/to/counter] [onerr=[fail|succeed]] [magic_root] [even_deny_root] [deny=n] [lock_time=n] [unlock_time=n]

    • [root_unlock_time=n] [serialize] [audit] [silent] [no_log_info]

      parameter

    file:File used to specify the number of Statistics,Default is/var/log/tallylog
    
    magic_root:If user uid=0,When calling this module during account authentication, if it fails, it will not be counted in the statistics
    
    even_deny_root:root Locked like a user
    
    deny:Lock times of ordinary users
    
    lock_time:Waiting time after ordinary users lock
    
    unlock_time:Time to wait for ordinary users to unlock after locking
    

    Manual unlocking:

    Check the number of wrong login of a user:
    pam_tally –-user
     For example, view work Number of user login errors:
    pam_tally –-user work
     Clear the wrong login times of a user:
    pam_tally –-user –-reset
     For example, empty work The number of user login errors,
    pam_tally –-user work –-reset
    faillog -r Orders are also acceptable.
    pam_tally2 –u tom --reset Reset the user's counter to zero( SLES 11.2 Reset succeeded only after using this command)
    View wrong logins: pam_tally2 –u tom
    
  2. Configure PAM authentication - check if failed password attempt lock is configured

    Using PAM_ PAM of tally2 module_ Tally2 (the rest is pam_tally2.so)

  3. User and group settings - check that the SSH password field is not empty

  4. Configure PAM authentication - check whether the password hash algorithm is SHA-512

    /etc/pam. All contents of D / system auth file:

    [root@wazuh-test1 ~]# grep -v ^# /etc/pam.d/system-auth
    auth        required      pam_env.so
    auth        required      pam_faildelay.so delay=2000000
    auth        sufficient    pam_unix.so nullok try_first_pass
    auth        requisite     pam_succeed_if.so uid >= 1000 quiet_success
    auth        required      pam_deny.so
    
    account     required      pam_unix.so
    account     sufficient    pam_localuser.so
    account     sufficient    pam_succeed_if.so uid < 1000 quiet
    account     required      pam_permit.so
    
    password    requisite     pam_pwquality.so try_first_pass local_users_only retry=3 authtok_type=
    password    sufficient    pam_unix.so sha512 shadow nullok try_first_pass use_authtok
    password    required      pam_deny.so
    
    session     optional      pam_keyinit.so revoke
    session     required      pam_limits.so
    -session     optional      pam_systemd.so
    session     [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
    session     required      pam_unix.so
    auth    required                        pam_tally2.so   deny=5 unlock_time=60 even_deny_root=5 root_unlock_time=60  
    
    
    
    

Replacement script (in optimization)

#! /usr/bin/bash


#User and account environment
#1. Check whether the minimum length of password is greater than or equal to 8
#2. Check whether the password expiration time is less than or equal to 90 days
#3. User account and environment - check whether the minimum interval between password changes is greater than or equal to 7 days
#4. Check whether the password expiration warning time is greater than or equal to 7 days
sed -i 's/^PASS_MIN_LEN[[:space:]]*[0-10]*$/PASS_MIN_LEN  8/g'	 /etc/login.defs
sed -i 's/^PASS_MAX_DAYS[[:space:]]*[0-10]*$/PASS_MAX_DAYS 90/g' /etc/login.defs	
sed -i 's/^PASS_MIN_DAYS[[:space:]]*[0-10]*$/PASS_MIN_DAYS 7/g'	 /etc/login.defs
sed -i 's/^PASS_WARN_AGE[[:space:]]*[0-10]*$/PASS_WARN_AGE 7/g'	 /etc/login.defs



#Configure PAM environment
#1. Check whether password reuse is restricted
#2. Check whether the password creation requirements are configured
#3. Check login failure configuration
#4. Check whether the failed password attempt lock is configured
#5. Check whether the password hash algorithm is SHA-512
sed -i 's/^password sufficient pam_unix.so remember[[:space:]]*[0-10]*$/password sufficient pam_unix.so remember=5/'	 /etc/pam.d/password-auth
sed -i 's/^password sufficient pam_unix.so remember[[:space:]]*[0-10]*$/password sufficient pam_unix.so remember=5/'	 /etc/pam.d/system-auth
sed -i 's/^password required pam_cracklib.so retry[[:space:]]*[0-10]*$/password required pam_cracklib.so retry=3 minlen=8 dcredit=-1 ucredit=-1 lcredit=-1 ocredit=-1/'	/etc/pam.d/password-auth
sed -i 's/^password required pam_cracklib.so retry[[:space:]]*[0-10]*$/password required pam_cracklib.so retry=3 minlen=8 dcredit=-1 ucredit=-1 lcredit=-1 ocredit=-1/'	/etc/pam.d/system-auth
sed -i '/^#%PAM-1.0/a  auth required pam_tally2.so  deny=3  unlock_time=40 even_deny_root root_unlock_time=30/'  /etc/pam.d/password-auth
sed -i '/^#%PAM-1.0/a  auth required pam_tally2.so  deny=3  unlock_time=40 even_deny_root root_unlock_time=30/'  /etc/pam.d/system-auth
sed -i '/^password    sufficient    pam_unix.so[[:space:]]*[0-10]*$/a  password    sufficient    pam_unix.so sha512 shadow nullok try_first_pass use_authtok'  /etc/pam.d/system-auth



#SSH service configuration
#1. Check whether the SSH idle timeout interval is set
#2. Check whether the HostbasedAuthentication of SSH is disabled
#3. Check whether the MaxAuthTries parameter of SSH is less than four
#4. Check whether PermitEmptyPasswords of SSH is disabled / whether SSH password field is not empty
sed -i 's/^ClientAliveInterval[[:space:]]*[0-10]*$/ClientAliveInterval 300/g'	 /etc/ssh/sshd_config
sed -i 's/^ClientAliveCountMax[[:space:]]*[0-10]*$/ClientAliveCountMax 3/g'	 /etc/ssh/sshd_config
sed -i 's/^HostbasedAuthentication[[:space:]]*[0-10]*$/HostbasedAuthentication yes/g'	 /etc/ssh/sshd_config
sed -i 's/^EnableSSHKeysign[[:space:]]*[0-10]*$/EnableSSHKeysign yes/g'	 /etc/ssh/sshd_config
sed -i 's/^StrictHostKeyChecking[[:space:]]*[0-10]*$/StrictHostKeyChecking no/g'	 /etc/ssh/sshd_config
sed -i 's/^PermitEmptyPasswords[[:space:]]*[0-10]*$/PermitEmptyPasswords no/g'  /etc/ssh/sshd_config

## Port
sed -i 's/^Port[[:space:]]*[0-10]*$/Port 22960/g'	 /etc/ssh/sshd_config


sed -i 's/^MaxAuthTries[[:space:]]*[0-10]*$/MaxAuthTries 3/g'	 /etc/ssh/sshd_config
sed -i 's/^LoginGraceTime[[:space:]]*[0-10]*$/LoginGraceTime  30/g'	 /etc/ssh/sshd_config
sed -i 's/^Protocol[[:space:]]*[0-10]*$///g'	 /etc/ssh/sshd_config
sed -i 's/^PermitRootLogin[[:space:]]*[0-10]*$/PermitRootLogin no/g'	 /etc/ssh/sshd_config
sed -i 's/^PermitEmptyPasswords[[:space:]]*[0-10]*$/PermitEmptyPasswords no/g'	 /etc/ssh/sshd_config


Keywords: bash security

Added by Xurion on Fri, 28 Jan 2022 01:15:42 +0200