精华内容
下载资源
问答
  • docker-nginx-auto-ssl:使用Let's Encrypt和Open Resty自动生成SSL证书的Docker映像
  • 自动生成SSL证书的脚本

    千次阅读 2018-10-30 18:56:28
    生成https证书脚本 基于Lnux系统下的openssl和jdkkeytool工具 1. 生成https证书脚本 #! /bin/bash FILE_PREFIX=tls RSA_BITS_NUM=2048 VALID_DAYS=3650 PASS_RSA=jeasoon PASS_P12=jeasoon PASS_JKS=jeasoon CRT_...

    自动生成SSL证书的脚本


    基于Lnux系统下的openssl和jdkkeytool工具

    1. 脚本和配置

    1.1 生成https证书脚本

    #! /bin/bash
    
    FILE_PREFIX=tls
    RSA_BITS_NUM=2048
    VALID_DAYS=3650
    
    PASS_RSA=jeasoon
    PASS_P12=jeasoon
    PASS_JKS=jeasoon
    
    CRT_ALIAS=jeasoon
    CRT_COUNTRY_NAME=CN
    CRT_PROVINCE_NAME=Beijing
    CRT_CITY_NAME=Beijing
    CRT_ORGANIZATION_NAME=jeasoon
    CRT_ORGANIZATION_UNIT_NAME=jeasoon
    CRT_DOMAIN=*.jeasoon.com
    CRT_EMAIL=jeasoon@jeasoon.com
    CRT_EXTRA_CHALLENGE_PASSWD=jeasoon
    CRT_EXTRA_OPTINAL_COMPANY_NAME=Jeasoon
    
    # 2.1 生成私钥
    echo -e "\n----------------------------------------------------------\n生成私钥\n"
    openssl genrsa -des3 -passout pass:$PASS_RSA -out $FILE_PREFIX.pem $RSA_BITS_NUM
    
    # 2.2 除去密码口令
    echo -e "\n----------------------------------------------------------\n除去密码口令\n"
    openssl rsa -in $FILE_PREFIX.pem -out $FILE_PREFIX.key -passin pass:$PASS_RSA
    
    # 2.3 生成证书请求
    echo -e "\n----------------------------------------------------------\n生成证书请求\n"
    openssl req -new -days $VALID_DAYS -key $FILE_PREFIX.key -out $FILE_PREFIX.csr << EOF
    $CRT_COUNTRY_NAME
    $CRT_PROVINCE_NAME
    $CRT_CITY_NAME
    $CRT_ORGANIZATION_NAME
    $CRT_ORGANIZATION_UNIT_NAME
    $CRT_DOMAIN
    $CRT_EMAIL
    $CRT_EXTRA_CHALLENGE_PASSWD
    $CRT_EXTRA_OPTINAL_COMPANY_NAME
    EOF
    
    # 2.4 生成证书
    echo -e "\n\n----------------------------------------------------------\n生成证书\n"
    openssl x509 -req -days $VALID_DAYS -signkey $FILE_PREFIX.key -in $FILE_PREFIX.csr -out $FILE_PREFIX.crt
    
    # 2.5 crt转为p12证书
    echo -e "\n----------------------------------------------------------\ncrt转为p12证书\n"
    openssl pkcs12 -export -in $FILE_PREFIX.crt -inkey $FILE_PREFIX.key -name $CRT_ALIAS -passout pass:$PASS_P12 -out $FILE_PREFIX.p12
    
    # 2.6 p12和jks证书互转
    echo -e "\n----------------------------------------------------------\np12和jks证书互转\n"
    keytool -importkeystore -srckeystore $FILE_PREFIX.p12 -srcstoretype PKCS12 -deststoretype JKS -srcstorepass $PASS_P12 -deststorepass $PASS_JKS -destkeystore $FILE_PREFIX.jks
    
    # 2.7 证书查看
    echo -e "\n----------------------------------------------------------\n证书查看\n"
    keytool -list -v -storepass $PASS_JKS -keystore $FILE_PREFIX.jks
    echo
    
    

    1.2 Tomcat配置

    修改tomcat根目录/conf/server.xml

    <Connector port="443" protocol="org.apache.coyote.http11.Http11NioProtocol"
               maxThreads="150" SSLEnabled="true" >
        <SSLHostConfig>
            <Certificate certificateKeystoreFile="tls/tls.jks"
                         certificateKeystorePassword="jeasoon"
                         certificateKeyPassword="jeasoon"
                         certificateKeyAlias="jeasoon"
                         type="RSA" />
        </SSLHostConfig>
    </Connector>
    

    2. 脚本步骤详解

    2.1 生成私钥

    openssl genrsa -des3 -passout pass:密码口令 -out tls.pem 2048
    

    选项:

    • genrsa: genrsa相关命令
    • -des3: 加密方式, encrypt the generated key with DES in ede cbc mode (168 bit key)
    • -passout: 输出密码口令, 后接 pass:密码口令, 如果省略, 需要手动输入密码口令
    • -out: 输出文件路径, 后接文件路径; 生成的tls.pem内容为文本
    • 1024/2048: 1024/2048位私钥, numbits

    2.2 除去密码口令

    openssl rsa -in tls.pem -out tls.key -passin pass:密码口令
    

    选项:

    • rsa: rsa相关命令
    • -in: 第一步生成的pem私钥, 后接私钥文件路径
    • -out: 输出文件路径, 后接文件路径; 生成的tls.key内容为文本
    • -passin: 输入密码口令, 后接 pass:密码口令, 如果省略, 需要手动输入密码口令

    2.3 生成证书请求

    openssl req -new -days 3650 -key tls.key -out tls.csr
    

    选项:

    • req: req相关命令
    • -new: 生成新的证书签名请求
    • -days: 有效天数, 后接数字, 天数
    • -key: 私钥key路径, 后接第二步生成的key路径
    • -out: 输出文件路径, 后接文件路径; 生成的tls.csr内容为文本

    交互输入:

    国家代码(可空): Country Name (2 letter code) [AU]:
    CN
    省份代码(可空): State or Province Name (full name) [Some-State]:
    Beijing
    城市代码(可空): Locality Name (eg, city) []:
    Beijing
    公司名称(可空): Organization Name (eg, company) [Internet Widgits Pty Ltd]:
    Jeasoon
    部门名称(可空): Organizational Unit Name (eg, section) []:
    Jeasoon
    授权域名: Common Name (e.g. server FQDN or YOUR name) []:
    *.jeasoon.com
    邮件地址(可空): Email Address []:
    jeasoon@jeasoon.com
    Extra信息(可空): A challenge password []:
    jeasoon
    Extra信息(可空): An optional company name []:
    jeasoon
    

    2.4 生成证书

    openssl x509 -req -days 3650 -signkey tls.key -in tls.csr -out tls.crt
    

    选项:

    • x509: x509相关命令
    • -req: 输入一个证书请求, 签名并输出
    • -days: 有效天数, 后接数字, 天数
    • -signkey: 输入私钥, 后接第二步生成的key文件路径
    • -in: 输入csr证书, 后接第三步生成的csr证书请求路径
    • -out: 输出文件路径, 后接文件路径; 生成的tls.crt内容为文本

    2.5 crt转为p12证书

    openssl pkcs12 -export -in tls.crt -inkey tls.key -name vixtel -passout pass:密码口令 -out tls.p12
    

    选项:

    • pkcs12: pkcs12相关命令
    • -export: 导出操作
    • -in: 输入证书, 后接第四步生成的crt证书路径
    • -days: 有效天数, 后接数字, 天数
    • -signkey: 输入私钥, 后接第二步生成的key文件路径
    • -name: 别名
    • -passout: 输出密码口令, 后接 pass:密码口令, 如果省略, 需要手动输入密码口令
    • -out: 输出文件路径, 后接文件路径; 生成的tls.p12内容为二进制

    2.6 p12和jks证书互转

    keytool为jdk工具

    p12 转为 jks:

    keytool -importkeystore -srckeystore tls.p12 -srcstoretype PKCS12 -deststoretype JKS -srcstorepass 输入密码口令 -deststorepass 输出密码口令 -destkeystore tls.jks
    

    jks 转为 p12:

    keytool -importkeystore -srckeystore tls.jks -srcstoretype JKS -deststoretype PKCS12 -srcstorepass 输入密码口令 -deststorepass 输出密码口令 -destkeystore tls.p12
    

    选项:

    • -importkeystore: 导入证书并输出指定证书
    • -srckeystore: 输入证书路径, 后跟输入证书路径
    • -destkeystore: 输出证书路径, 后跟输出证书路径
    • -srcstoretype: 输入证书类型, 后跟输入证书类型, PKCS12/JKS
    • -deststoretype: 输出证书类型, 后跟输出证书类型, JKS/PKCS12
    • -srcstorepass: 输入密码口令, 后接输入证书的密码口令
    • -deststorepass: 输出密码口令, 后接输出证书的密码口令

    2.7 证书查看

    keytool -list -v -storepass 密码口令 -keystore tls.jks
    

    选项:

    • -list: 证书更改或查看操作
    • -v: 详细输出
    • -storepass: 证书密码口令
    • -keystore: 证书路径, 后跟要查看的证书路径

    交互输出:

    Keystore type: jks
    Keystore provider: SUN
    
    Your keystore contains 1 entry
    
    Alias name: jeasoon
    Creation date: Oct 30, 2018
    Entry type: PrivateKeyEntry
    Certificate chain length: 1
    Certificate[1]:
    Owner: EMAILADDRESS=jeasoon@jeasoon.com, CN=*.jeasoon.com, O=Vixtel, L=Beijing, ST=Beijing, C=CN
    Issuer: EMAILADDRESS=jeasoon@jeasoon.com, CN=*.jeasoon.com, O=Vixtel, L=Beijing, ST=Beijing, C=CN
    Serial number: d561956d9762442a
    Valid from: Tue Oct 30 17:18:37 CST 2018 until: Fri Oct 27 17:18:37 CST 2028
    Certificate fingerprints:
             MD5:  28:82:FC:F2:05:DB:BD:7F:9A:30:3B:DC:92:0A:AF:BE
             SHA1: 62:EC:7A:D5:7A:4B:1C:67:A9:04:FD:8B:B7:4C:5E:9F:D4:7B:0A:8F
             SHA256: 15:20:DA:E2:0D:07:05:99:4F:5F:9C:AA:CF:8F:B3:68:E2:79:27:52:2E:34:52:7C:D5:F6:0E:5E:55:A6:5B:0F
    Signature algorithm name: SHA256withRSA
    Subject Public Key Algorithm: 2048-bit RSA key
    Version: 1
    
    
    *******************************************
    *******************************************
    
    
    
    展开全文
  • linux下,私有ssl证书生成器,通过提示的方式,自动根据域名生成私有ssl证书,包括crt,key
  • ssl证书自动生成脚本竞争对手松懈 。 那样令人尴尬,将来肯定会发生在其他人身上。 在现代网络上,过期的证书可能会给网站造成严重的问题,从无法连接到网站的不满意用户到恶意利用更新证书失败行为的安全威胁。 ...

    ssl证书自动生成脚本

    竞争对手松懈 那样令人尴尬,将来肯定会发生在其他人身上。

    在现代网络上,过期的证书可能会给网站造成严重的问题,从无法连接到网站的不满意用户到恶意利用更新证书失败行为的安全威胁。

    按需Ssl是一组SSL脚本,可帮助网站所有者管理证书。 它用于按需证书生成和验证,并且可以创建证书签名请求( CSR )并预测现有证书的到期时间。

    自动执行SSL到期检查

     USAGE: SSLexpiryPredictions.sh -[cdewh]

      DESCRIPTION: This script predicts the expiring SSL certificates based on the end date.

      OPTIONS:

      -c|   sets the value for configuration file which has server:port or host:port details.
           
      -d|   sets the value of directory containing the certificate files in crt or pem format.

      -e|   sets the value of certificate extention, e.g crt, pem, cert.
            crt: default [to be used with -d, if certificate file extention is other than .crt]

      -w|   sets the value for writing the script output to a file.

      -h|   prints this help and exit.

    例子:

    要创建包含所有服务器及其端口号列表的文件以进行SSL握手,请使用:

    cat > servers.list
             server1:port1
             server2:port2
             server3:port3
            (ctrl+d)
           
    $ ./SSLexpiryPredictions.sh -c server.list

    通过提供证书位置和扩展名(如果不是.crt)运行脚本:

     $ ./SSLexpiryPredictions.sh -d /path/to/certificates/dir -e pem 
    

    自动化CSR和私钥创建

    Usage:  genSSLcsr.sh [options] -[cdmshx]
      [-c (common name)]
      [-d (domain name)]
      [-s (SSL certificate subject)]
      [-p (password)]
      [-m (email address)] *(Experimental)
      [-r (remove pasphrase) default:true]
      [-h (help)]
      [-x (optional)]

    [OPTIONS]
      -c|   Sets the value for common name.
            A valid common name is something that ends with 'xyz.com'

      -d|   Sets the domain name.

      -s|   Sets the subject to be applied to the certificates.
            '/C=country/ST=state/L=locality/O=organization/OU=organizationalunit/emailAddress=email'

      -p|   Sets the password for private key.

      -r|   Sets the value of remove passphrase.
            true:[default] passphrase will be removed from key.
            false: passphrase will not be removed and key wont get printed.

      -m|   Sets the mailing capability to the script.
            (Experimental at this time and requires a lot of work)

      -x|   Creates the certificate request and key but do not print on screen.
            To be used when script is used just to create the key and CSR with no need
            + to generate the certficate on the go.

      -h|   Displays the usage. No further functions are performed.

      Example: genSSLcsr.sh -c mywebsite.xyz.com -m myemail@mydomain.com

    脚本

    1. SSLexpiryPredictions.sh

    #!/bin/bash
    ##############################################
    #
    #       PURPOSE: The script to predict expiring SSL certificates.
    #
    #       AUTHOR: 'Abhishek.Tamrakar'
    #
    #       VERSION: 0.0.1
    #
    #       COMPANY: Self
    #
    #       EMAIL: abhishek.tamrakar08@gmail.com
    #
    #       GENERATED: on 2018-05-20
    #
    #       LICENSE: Copyright (C) 2018 Abhishek Tamrakar
    #
    #  Licensed under the Apache License, Version 2.0 (the "License");
    #  you may not use this file except in compliance with the License.
    #  You may obtain a copy of the License at
    #
    #       http://www.apache.org/licenses/LICENSE-2.0
    #
    #   Unless required by applicable law or agreed to in writing, software
    #   distributed under the License is distributed on an "AS IS" BASIS,
    #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    #   See the License for the specific language governing permissions and
    #   limitations under the License.
    ##############################################

    #your Variables go here
    script=${0##/}
    exitcode=''
    WRITEFILE=0
    CONFIG=0
    DIR=0
    # functions here
    usage()
    {
    cat <<EOF

      USAGE: $script -[cdewh]"

      DESCRIPTION: This script predicts the expiring SSL certificates based on the end date.

      OPTIONS:

      -c|   sets the value for configuration file which has server:port or host:port details.

      -d|   sets the value of directory containing the certificate files in crt or pem format.

      -e|   sets the value of certificate extention, e.g crt, pem, cert.
            crt: default

      -w|   sets the value for writing the script output to a file.

      -h|   prints this help and exit.

    EOF
    exit 1
    }
    # print info messages
    info()
    {
      printf '\n%s: %6s\n' "INFO" "$@"
    }
    # print error messages
    error()
    {
      printf '\n%s: %6s\n' "ERROR" "$@"
      exit 1
    }
    # print warning messages
    warn()
    {
      printf '\n%s: %6s\n' "WARN" "$@"
    }
    # get expiry for the certificates
    getExpiry()
    {
      local expdate=$1
      local certname=$2
      today=$(date +%s)
      timetoexpire=$(( ($expdate - $today)/(60*60*24) ))

      expcerts=( ${expcerts[@]} "${certname}:$timetoexpire" )
    }

    # print all expiry that was found, typically if there is any.
    printExpiry()
    {
      local args=$#
      i=0
      if [[ $args -ne 0 ]]; then
        #statements
        printf '%s\n' "---------------------------------------------"
        printf '%s\n' "List of expiring SSL certificates"
        printf '%s\n' "---------------------------------------------"
        printf '%s\n' "$@"  | \
          sort -t':' -g -k2 | \
          column -s: -t     | \
          awk '{printf "%d.\t%s\n", NR, $0}'
        printf '%s\n' "---------------------------------------------"
      fi
    }

    # calculate the end date for the certificates first, finally to compare and predict when they are going to expire.
    calcEndDate()
    {
      sslcmd=$(which openssl)
      if [[ x$sslcmd = x ]]; then
        #statements
        error "$sslcmd command not found!"
      fi
      # when cert dir is given
      if [[ $DIR -eq 1 ]]; then
        #statements
        checkcertexists=$(ls -A $TARGETDIR| egrep "*.$EXT$")
        if [[ -z ${checkcertexists} ]]; then
          #statements
          error "no certificate files at $TARGETDIR with extention $EXT"
        fi
        for file in $TARGETDIR/*.${EXT:-crt}
        do
          expdate=$($sslcmd x509 -in $file -noout -enddate)
          expepoch=$(date -d "${expdate##*=}" +%s)
          certificatename=${file##*/}
          getExpiry $expepoch ${certificatename%.*}
        done
      elif [[ $CONFIG -eq 1 ]]; then
        #statements
        while read line
        do
          if echo "$line" | \
          egrep -q '^[a-zA-Z0-9.]+:[0-9]+|^[a-zA-Z0-9]+_.*:[0-9]+';
          then
            expdate=$(echo | \
            openssl s_client -connect $line 2>/dev/null | \
            openssl x509 -noout -enddate 2>/dev/null);
            if [[ $expdate = '' ]]; then
              #statements
              warn "[error:0906D06C] Cannot fetch certificates for $line"
            else
              expepoch=$(date -d "${expdate##*=}" +%s);
              certificatename=${line%:*};
              getExpiry $expepoch ${certificatename};
            fi
          else
            warn "[format error] $line is not in required format!"
          fi
        done < $CONFIGFILE
      fi
    }
    # your script goes here
    while getopts ":c:d:w:e:h" options
    do
    case $options in
    c )
      CONFIG=1
      CONFIGFILE="$OPTARG"
      if [[ ! -e $CONFIGFILE ]] || [[ ! -s $CONFIGFILE ]]; then
        #statements
        error "$CONFIGFILE does not exist or empty!"
      fi
            ;;
    e )
      EXT="$OPTARG"
      case $EXT in
        crt|pem|cert )
        info "Extention check complete."
        ;;
        * )
        error "invalid certificate extention $EXT!"
        ;;
      esac
      ;;
    d )
      DIR=1
      TARGETDIR="$OPTARG"
      [ $TARGETDIR = '' ] && error "$TARGETDIR empty variable!"
      ;;
    w )
      WRITEFILE=1
      OUTFILE="$OPTARG"
      ;;
    h )
            usage
            ;;
    \? )
            usage
            ;;
    : )
            fatal "Argument required !!! see \'-h\' for help"
            ;;
    esac
    done
    shift $(($OPTIND - 1))
    #
    calcEndDate
    #finally print the list
    if [[ $WRITEFILE -eq 0 ]]; then
      #statements
      printExpiry ${expcerts[@]}
    else
      printExpiry ${expcerts[@]} > $OUTFILE
    fi

    2. genSSLcsr.sh

    #!/bin/bash -
    #===============================================================================
    #
    #          FILE: genSSLcsr.sh
    #
    #         USAGE: ./genSSLcsr.sh [options]
    #
    #   DESCRIPTION: ++++version 1.0.2
    #               Fixed few bugs from previous script
    #               +Removing passphrase after CSR generation
    #               Extended use of functions
    #               Checks for valid common name
    #               ++++1.0.3
    #               Fixed line breaks
    #               Work directory to be created at the start
    #               Used getopts for better code arrangements
    #   ++++1.0.4
    #     Added mail feature (experimental at this time and needs
    #     a mail server running locally.)
    #     Added domain input and certificate subject inputs
    #
    #       OPTIONS: ---
    #  REQUIREMENTS: openssl, mailx
    #          BUGS: ---
    #         NOTES: ---
    #        AUTHOR: Abhishek Tamrakar (), abhishek.tamrakar08@gmail.com
    #  ORGANIZATION: Self
    #       CREATED: 6/24/2016
    #      REVISION: 4
    # COPYRIGHT AND
    #       LICENSE: Copyright (C) 2016 Abhishek Tamrakar
    #
    #  Licensed under the Apache License, Version 2.0 (the "License");
    #  you may not use this file except in compliance with the License.
    #  You may obtain a copy of the License at
    #
    #       http://www.apache.org/licenses/LICENSE-2.0
    #
    #   Unless required by applicable law or agreed to in writing, software
    #   distributed under the License is distributed on an "AS IS" BASIS,
    #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    #   See the License for the specific language governing permissions and
    #   limitations under the License.
    #===============================================================================

    #variables ges here
    #set basename to scriptname
    SCRIPT=${0##*/}

    #set flags
    TFOUND=0
    CFOUND=0
    MFOUND=0
    XFOUND=0
    SFOUND=0
    logdir=/var/log
    # edit these below values to replace with yours
    homedir=''
    yourdomain=''
    country=IN
    state=Maharashtra
    locality=Pune
    organization="your_organization"
    organizationalunit="your_organizational_unit"
    email=your_email@your_domain
    password=your_ssl_password
    # OS is declared and will be used in its next version
    OS=$(egrep -io 'Redhat|centos|fedora|ubuntu' /etc/issue)

    ### function declarations ###

    info()
    {
      printf '\n%s\t%s\t' "INFO" "$@"
    }

    #exit on error with a custom error message
    #the extra function was removed and replaced withonly one.
    #using FAILED\n\e<message> is a way but not necessarily required.
    #

    fatal()
    {
     printf '\n%s\t%s\n' "ERROR" "$@"
     exit 1
    }

    checkperms()
    {
    if [[ -z ${homedir} ]]; then
    homedir=$(pwd)
    fi
    if [[ -w ${homedir} ]]; then
    info "Permissions acquired for ${SCRIPT} on ${homedir}."
    else
    fatal "InSufficient permissions to run the ${SCRIPT}."
    fi
    }

    checkDomain()
    {
    info "Initializing Domain ${cn} check ? "
    if [[ ! -z ${yourdomain} ]]; then
    workdir=${homedir}/${yourdomain}
    echo -e "${cn}"|grep -E -i -q "${yourdomain}$" && echo -n "[OK]" || fatal "InValid domain in ${cn}"
    else
    workdir=${homedir}/${cn#*.}
    echo -n "[NULL]"
    info "WARNING: No domain declared to check."
    confirmUserAction
    fi
    }       # end function checkDomain

    usage()
    {
    cat << EOF

    Usage:  $SCRIPT [options] -[cdmshx]
      [-c (common name)]
      [-d (domain name)]
      [-s (SSL certificate subject)]
      [-p (password)]
      [-m (email address)] *(Experimental)
      [-r (remove pasphrase) default:true]
      [-h (help)]
      [-x (optional)]

    [OPTIONS]
      -c|   Sets the value for common name.
            A valid common name is something that ends with 'xyz.com'

      -d|   Sets the domain name.

      -s|   Sets the subject to be applied to the certificates.
            '/C=country/ST=state/L=locality/O=organization/OU=organizationalunit/emailAddress=email'

      -p|   Sets the password for private key.

      -r|   Sets the value of remove passphrase.
            true:[default] passphrase will be removed from key.
            false: passphrase will not be removed and key wont get printed.

      -m|   Sets the mailing capability to the script.
            (Experimental at this time and requires a lot of work)

      -x|   Creates the certificate request and key but do not print on screen.
            To be used when script is used just to create the key and CSR with no need
            + to generate the certficate on the go.

      -h|   Displays the usage. No further functions are performed.

      Example: $SCRIPT -c mywebsite.xyz.com -m myemail@mydomain.com

    EOF
    exit 1
    }       # end usage

    confirmUserAction() {
    while true; do
    read -p "Do you wish to continue? ans: " yn
    case $yn in
    [Yy]* ) info "Initiating the process";
    break;;
    [Nn]* ) exit 1;;
    * ) info "Please answer yes or no.";;
    esac
    done
    }       # end function confirmUserAction

    parseSubject()
    {
      local subject="$1"
      parsedsubject=$(echo $subject|sed 's/\// /g;s/^ //g')
      for i in ${parsedsubject}; do
          case ${i%=*} in
            'C' )
            country=${i##*=}
            ;;
            'ST' )
            state=${i##*=}
            ;;
            'L' )
            locality=${i##*=}
            ;;
            'O' )
            organization=${i##*=}
            ;;
            'OU' )
            organizationalunit=${i##*=}
            ;;
            'emailAddress' )
            email=${i##*=}
          ;;
        esac
      done
    }

    sendMail()
    {
     mailcmd=$(which mailx)
     if [[ x"$mailcmd" = "x" ]]; then
       fatal "Cannot send email! please install mailutils for linux"
     else
       echo "SSL CSR attached." | $mailcmd -s "SSL certificate request" \
       -t $email $ccemail -A ${workdir}/${cn}.csr \
       && info "mail sent" \
       || fatal "error in sending mail."
     fi
    }

    genCSRfile()
    {
    info "Creating signed key request for ${cn}"
    #Generate a key
    openssl genrsa -des3 -passout pass:$password -out ${workdir}/${cn}.key 4096 -noout 2>/dev/null && echo -n "[DONE]" || fatal "unable to generate key"

    #Create the request
    info "Creating Certificate request for ${cn}"
    openssl req -new -key ${workdir}/${cn}.key -passin pass:$password -sha1 -nodes \
            -subj "/C=$country/ST=$state/L=$locality/O=$organization/OU=$organizationalunit/CN=$cn/emailAddress=$email" \
            -out ${workdir}/${cn}.csr && echo -n "[DONE]" || fatal "unable to create request"

    if [[ "${REMOVEPASSPHRASE:-true}" = 'true' ]]; then
      #statements
      #Remove passphrase from the key. Comment the line out to keep the passphrase
      info "Removing passphrase from ${cn}.key"
      openssl rsa -in ${workdir}/${cn}.key \
      -passin pass:$password \
      -out ${workdir}/${cn}.insecure 2>/dev/null \
      && echo -n "[DONE]" || fatal "unable to remove passphrase"
      #swap the filenames
      info "Swapping the ${cn}.key to secure"
      mv ${workdir}/${cn}.key ${workdir}/${cn}.secure \
      && echo -n "[DONE]" || fatal "unable to perfom move"
      info "Swapping insecure key to ${cn}.key"
      mv ${workdir}/${cn}.insecure ${workdir}/${cn}.key \
      && echo -n "[DONE]" || fatal "unable to perform move"
    else
      info "Flag '-r' is set, passphrase will not be removed."
    fi
    }

    printCSR()
    {
    if [[ -e ${workdir}/${cn}.csr ]] && [[ -e ${workdir}/${cn}.key ]]
    then
    echo -e "\n\n----------------------------CSR-----------------------------"
    cat ${workdir}/${cn}.csr
    echo -e "\n----------------------------KEY-----------------------------"
    cat ${workdir}/${cn}.key
    echo -e "------------------------------------------------------------\n"
    else
    fatal "CSR or KEY generation failed !!"
    fi
    }

    ### END Functions ###

    #Check the number of arguments. If none are passed, print help and exit.
    NUMARGS=$#
    if [ $NUMARGS -eq 0 ]; then
    fatal "$NUMARGS Arguments provided !!!! See usage with '-h'"
    fi

    #Organisational details

    while getopts ":c:d:s:m:p:rhx" atype
    do
    case $atype in
    c )
            CFOUND=1
            cn="$OPTARG"
            ;;
    d )
      yourdomain="$OPTARG"
      ;;
    s )
      SFOUND=1
      subj="$OPTARG"
      ;;
    p )
      password="$OPTARG"
      ;;
    r )
      REMOVEPASSPHRASE='false'
      ;;
    m )
      MFOUND=1
      ccemail="$OPTARG"
      ;;
    x )
            XFOUND=1
      ;;
    h )
            usage
            ;;
    \? )
            usage
            ;;
    : )
            fatal "Argument required !!! see \'-h\' for help"
            ;;
    esac
    done
    shift $(($OPTIND - 1))

    #### END CASE #### START MAIN ####

    if [ $CFOUND -eq 1 ]
    then
    # take current dir as homedir by default.
    checkperms ${homedir}
    checkDomain

      if [[ ! -d ${workdir} ]]
      then
        mkdir ${workdir:-${cn#*.}} 2>/dev/null && info "${workdir} created."
      else
        info "${workdir} exists."
      fi # end workdir check
      parseSubject "$subj"
      genCSRfile
      if [ $XFOUND -eq 0 ]
      then
        sleep 2
        printCSR
      fi    # end x check
      if [[ $MFOUND -eq 1 ]]; then
        sendMail
      fi
    else
            fatal "Nothing to do!"
    fi      # end common name check

    ##### END MAIN #####

    它最初以README的形式发布在ssl-on-demand的GitHub存储库中,并在获得许可的情况下可重复使用。

    翻译自: https://opensource.com/article/20/2/ssl-demand

    ssl证书自动生成脚本

    展开全文
  • ssl-proxy通过单个命令自动生成SSL证书和代理HTTPS流量到现有HTTP服务器。 用法 带有自动自签名证书 ssl-proxy -from 0.0.0.0:4430 -to 127.0.0.1:8000 这将立即生成自签名证书,并开始将HTTPS流量从代理到 。 ...
  • acme生成通配符ssl证书

    2020-12-15 13:14:40
    2.生成SSL证书 这里我们是用 DNS 验证方式。DNS 方式,需要手动在域名上添加一条 txt 解析记录,验证域名所有权。为了避免每次都需要手动解析验证域名所有权,我们使用域名解析商提供的 api 自动添加 txt 记录完成...

    acme生成通配符ssl证书

    1.安装acme

    wget https://get.acme.sh | sh
    安装完成后的目录在/root/.acme.sh/下面.
    直接使用 cd /root/.acme.sh 命令 进入.acme.sh目录.

    2.生成SSL证书

    这里我们是用 DNS 验证方式。DNS 方式,需要手动在域名上添加一条 txt 解析记录,验证域名所有权。为了避免每次都需要手动解析验证域名所有权,我们使用域名解析商提供的 api 自动添加 txt 记录完成验证,acme.sh 目前支持数十种解析商的自动集成,其中包含阿里云。以阿里云为例,你需要先登录到阿里云账号,生成你自己的 api idapi key,它是免费的 (建议开启阿里云【RAM 访问控制】,只给 AliyunDNSFullAccess 权限策略,这样做更安全)。然后执行下面的命令:

    export Ali_Key="xxx" && export Ali_Secret="xxx"
    
    # 因为生成的通配符域名证书中并不包含根域名证书,所以我们要指定根域名。
    acme.sh --issue --dns dns_ali -d example.com -d *.example.com
    

    注意:请将 example.com 改为你自己的域名。

    3.安装到nginx

    ./acme.sh --installcert -d example.com \
              --keypath /etc/nginx/ssl/example.com.key \
              --fullchainpath /etc/nginx/ssl/example.com.cer
    

    4.nginx配置

    server {
            listen       443 ssl;
            server_name  example.com;
    
            ssl on;
            
            ssl_certificate      ssl/abc.domain.com.cer;
            ssl_certificate_key  ssl/abc.domain.com.key;
    
            location / {
                proxy_pass   http://127.0.0.1:8001;
            }
        }
     # 80端口直接转到443
     server {
            listen      80;
            server_name    example.com;
            return      301 https://$server_name$request_uri;
     } 
    

    5.更新证书

    生成的证书只有30天有效期,所以需要自行更新

    5.1手动更新

    acme.sh --renew -d example.com --force

    5.2自动更新

    安装 acme.sh 时会自动创建一个 cronjob,每天定期检查所有证书,如果证书需要更新会自动更新证书。
    通过 crontab -l 查看 crontab 任务:
    25 0 * * * "/root/.acme.sh"/acme.sh --cron --home "/root/.acme.sh" > /dev/null

    如果有该定时任务,则不需要额外配置。

    展开全文
  • 本文首发:开发指南:如何在 CentOS 7 上安装 Nginx Let’s Encrypt 是由 Internet Security Research Group (ISRG) 开发的一个...这个教程,将会一步一步的教你如何在 CentOS 7 上通过 Certbot 来生成 SSL ...

    SSL Nginx

    本文首发:开发指南:如何在 CentOS 7 上安装 Nginx


    Let’s Encrypt 是由 Internet Security Research Group (ISRG) 开发的一个自由、自动化和开放的证书颁发机构。目前几乎所有的现代浏览器都信任由 Let’s Encrypt 颁发的证书。

    这个教程,将会一步一步的教你如何在 CentOS 7 上通过 Certbot 来生成 SSL 安全证书,并配置到 Nginx 上。

    开始前的准备

    在继续此教程之前,请确保你已经满足了以下两个条件:

    • 请确保你已经拥有了一个属于你的域名,并且已经解析到了你的服务器 IP 上,在接下来的教程中,我将会用 kaifazhinan.com 作为本教程的域名。
    • 请确保你已经启用了 EPEL 仓库,并且已经安装了 Nginx,如果你还没有安装 Nginx,你可以先阅读 如何在 CentOS 7 上安装 Nginx 这篇文章来安装 Nginx。

    安装 Certbot

    Certbot 是一个非常简单方便的工具,它可以帮助我们生成 SSL 证书,自动更新 SSL 证书,并且将证书配置到 Web 服务上。

    可以运行以下命令,从 EPEL 仓库中安装 Certbot:

    sudo yum install certbot
    

    生成 Dh (Diffie-Hellman) 组

    Diffie–Hellman 密匙交换是一种可以在不安全的通信信道上安全交换密钥的方法。

    现在运行以下命令,可以来生成一个新的 2048 位的 DH 参数:

    sudo openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048
    

    2048 位,生成时间大概 3-5 分钟左右。当然,如果您愿意也可以将大小改为 4096 位,但是这样的话,可能生成的时间至少需要花费 30 分钟,此操作具体时长取决于系统熵。

    生成 SSL 证书

    要生成域名的 SSL 证书,我们将使用 Webroot 插件在 ${webroot-path}/.well-known/acme-challenge 目录中创建临时文件来验证请求的域名。Let’s Encrypt 服务器会向临时文件发出 HTTP 请求,以验证请求的域名是否被正确的解析到了正在运行 Certbot 的服务器。

    为了简便,我们将把所有访问 .well-known/acme-challenge 的 HTTP 请求都映射到 /var/lib/letsencrypt 这个目录中。

    下面的命令将会创建这个目录,并且使 Nginx 对它拥有读写的权限。

    sudo mkdir -p /var/lib/letsencrypt/.well-known
    sudo chgrp nginx /var/lib/letsencrypt
    sudo chmod g+s /var/lib/letsencrypt
    

    创建代码片段

    为了避免 Nginx 配置文件中存在重复的代码,请创建以下两个代码片段(里面是 Nginx 的配置代码),我们将在相关的 Nginx 配置文件中包含这些片段:

    1、首先,创建一个目录,用于存放 Nginx 配置的代码片段文件:

    sudo mkdir /etc/nginx/snippets
    

    2、创建第一个片段文件, letsencrypt.conf,其全路径为: /etc/nginx/snippets/letsencrypt.conf

    location ^~ /.well-known/acme-challenge/ {
      allow all;
      root /var/lib/letsencrypt/;
      default_type "text/plain";
      try_files $uri =404;
    }
    

    3、创建第二个片段文件,ssl.conf,其全路径为: /etc/nginx/snippets/ssl.conf

    ssl_dhparam /etc/ssl/certs/dhparam.pem;
    
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_session_tickets off;
    
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers 'ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS';
    ssl_prefer_server_ciphers on;
    
    ssl_stapling on;
    ssl_stapling_verify on;
    resolver 8.8.8.8 8.8.4.4 valid=300s;
    resolver_timeout 30s;
    
    add_header Strict-Transport-Security "max-age=15768000; includeSubdomains; preload";
    add_header X-Frame-Options SAMEORIGIN;
    add_header X-Content-Type-Options nosniff;
    

    上面的代码中包含 Mozilla 的推荐部分。 支持 OCSP Stapling,HTTP 严格传输安全(HSTS)并强制执行几个以安全为中心的 HTTP 头。

    加载 letsencrypt.conf

    代码片段创建完成之后,就可以打开 Nginx 的域名独立配置文件,将 letsencrypt.conf 文件引入。

    在这里,我们的域名是 kaifazhinan.com ,所以我们的配置文件为 kaifazhinan.com.conf, 文件的全路径为 /etc/nginx/conf.d/kaifazhinan.com.conf

    server {
      listen 80;
      server_name kaifazhinan.com www.kaifazhinan.com;
    
      include snippets/letsencrypt.conf;
    }
    

    注意: 我们建议针对不同的域名,创建不同的独立配置文件。这样会比较清晰,便于管理和查找对应的配置。

    Nginx 的主配置文件中有一行代码是 include /etc/nginx/conf.d/*.conf,这行代码的意思就是加载 /etc/nginx/conf.d/ 目录下所有以 .conf 结尾的配置文件,所以我们直接将独立的配置文件保存在 /etc/nginx/conf.d/ 目录下就会自动引入。

    生成证书

    重新加载 Nginx 配置使更改生效:

    sudo systemctl reload nginx
    

    你现在可以运行 Certbot 使用 Webroot 插件,为你的域名生成 SSL 证书:

    sudo certbot certonly --agree-tos --email admin@kaifazhinan.com --webroot -w /var/lib/letsencrypt/ -d kaifazhinan.com -d www.kaifazhinan.com
    

    注意: 记得将 admin@kaifazhinan.com 换成你自己的邮箱,还有 kaifazhinan.comwww.kaifazhinan.com 换成你的域名。

    如果成功的生成了 SSL 证书,那么 Certbot 将打印类似以下的内容:

    IMPORTANT NOTES:
     - Congratulations! Your certificate and chain have been saved at:
       /etc/letsencrypt/live/kaifazhinan.com/fullchain.pem
       Your key file has been saved at:
       /etc/letsencrypt/live/kaifazhinan.com/privkey.pem
       Your cert will expire on 2019-02-11. To obtain a new or tweaked
       version of this certificate in the future, simply run certbot
       again. To non-interactively renew *all* of your certificates, run
       "certbot renew"
     - If you like Certbot, please consider supporting our work by:
    
       Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
       Donating to EFF:                    https://eff.org/donate-le
    

    配置 Nginx

    现在你已经成功生成了 SSL 证书,现在可以修改 Nginx 的域名配置了,这里我们的域名是配置文件是 kaifazhinan.com.conf,文件的全路径是 /etc/nginx/conf.d/kaifazhinan.com.conf

    server {
        listen 80;
        server_name www.kaifazhinan.com kaifazhinan.com;
    
        include snippets/letsencrypt.conf;
        return 301 https://$host$request_uri;
    }
    
    server {
        listen 443 ssl http2;
        server_name www.kaifazhinan.com;
    
        ssl_certificate /etc/letsencrypt/live/kaifazhinan.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/kaifazhinan.com/privkey.pem;
        ssl_trusted_certificate /etc/letsencrypt/live/kaifazhinan.com/chain.pem;
        include snippets/ssl.conf;
        include snippets/letsencrypt.conf;
    
        return 301 https://kaifazhinan.com$request_uri;
    }
    
    server {
        listen 443 ssl http2;
        server_name kaifazhinan.com;
    
        ssl_certificate /etc/letsencrypt/live/kaifazhinan.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/kaifazhinan.com/privkey.pem;
        ssl_trusted_certificate /etc/letsencrypt/live/kaifazhinan.com/chain.pem;
        include snippets/ssl.conf;
        include snippets/letsencrypt.conf;
    
        # 如果有补充的配置,可以写在这里
    }
    

    上面的代码,我们将 HTTP 的请求重定向到了 HTTPS,将 www.kaifazhinan.com 重定向到了 kaifazhinan.com 上。

    最后,通过下面的命令,重新加载 Nginx,使上面的配置生效:

    sudo systemctl reload nginx
    

    自动更新 Let’s Encrypt SSL 证书

    Let’s Encrypt 颁发的 SSL 证书有效时间是 90 天。我们需要在证书过期之前自动续订证书,这里将创建一个每天运行两次的定时任务 ,并在证书到期前 30 天自动续订。

    通过运行 crontab 命令,来创建一个定时任务:

    sudo crontab -e
    

    上面的命令,会自动创建一个文件,并自动进入编辑状态,所以直接复制下面的内容粘贴到里面即可:

    0 */12 * * * root test -x /usr/bin/certbot -a \! -d /run/systemd/system && perl -e 'sleep int(rand(3600))' && certbot -q renew --renew-hook "systemctl reload nginx"
    

    保存并关闭文件。

    如果要测试是否能够正常更新证书,你可以在 certbot 命令后面添加 --dry-run 这个参数来主动触发更新命令。

    sudo certbot renew --dry-run
    

    如果没有输出错误,则表示 SSL 证书更新成功。

    总结

    通过此教程,你学会了:

    • 如何使用 Let’s Encrypt 客户端 Certbot 为你的域名创建了 SSL 证书;
    • 也通过创建 Nginx 的代码片段,来避免 Nginx 配置文件中的代码冗余,并且将 SSL 证书配置到了 Nginx 服务中;
    • 最后,你还创建了一个定时任务,来自动更新你的 SSL 证书,保证它不会过期。

    如果你想了解 Certbot 的更多信息,可以参考它的官方文档

    期待下次与你相见 : )

    本文首发:开发指南:如何在 CentOS 7 上安装 Nginx

    关注我

    大家好,这里是 FEHub,每天早上 9 点更新,为你分享优质精选文章,与你一起进步。

    如果喜欢这篇文章,希望大家点赞,评论,转发。你的支持,是我最大的动力,咱们明天见 😃

    长按关注 「FEHub」,每天进步一点点长按关注 「FEHub」,每天进步一点点

    展开全文
  • 低门槛跨入Https大门!网站ssl证书自动生成工具(http到https的转变)
  • 的邮件提示证书即将过期, 少于7天,但是acme.sh应该是60天自动renew的。于是查看下安装的证书列表: acme.sh --list 结果如下(已排版): Main_Domain:*.lovemiku.info "" KeyLength:lovemiku.info...
  • Spring Boot模块旨在缓解使用自动证书管理环境(ACME)协议生成有效SSL证书的麻烦。 该项目取决于库。 依存关系 该模块取决于在PATH上具有openssl来将证书转换为PKCS12格式。 Maven <groupId>...
  • Let’s Encrypt是一个 CA 机构,但这个 CA 机构是免费的!!!签发证书不需要任何费用, 为了实现通配符证书,Let’s Encrypt 对 ACME 协议的实现进行了升级,只有 ...我们通过certbot-auto自动生成工具来操作。 ...
  • 为服务器配置自动更新SSL证书

    千次阅读 2019-03-14 09:53:42
    然后生成证书,将证书拷贝到相应的目录。 因为我的 nginx 的配置只有 root 有权限,所以为图方便,acme.sh 也是安装在 root 的...nginx 是从 一个普通用户目录里读取 ssl 证书文件 生成多个证书 acme.sh --issue...

空空如也

空空如也

1 2 3 4 5 ... 17
收藏数 324
精华内容 129
关键字:

自动生成ssl证书