6-11
Wednesday
标签
梦涛笔记

ROS通过aliyun域名解析实现DDNS脚本

ROS 发布时间:2025-06-01 16:03:12

优化获取地址方式,以及设置地址相同时不触发解析请求,避免频繁多余请求接口。


:local id "key"
:local secret "secret"
:local domain "your.domain.com"

:global GIPV4
:global GIPV6

# 定义拨号接口名称
:local interfaceName "pppoe-out1"

# 获取接口的IP地址
:local ipAddress [/ip address get [/ip address find interface=$interfaceName] address]

# 检查是否获取到IP地址
:if ($ipAddress != "") do={
    :set ipAddress [:pick $ipAddress 0 ([len $ipAddress] -3)]
  :if ($ipAddress != $GIPV4) do={
    :global GIPV4 $ipAddress
    :log info ("IP Address of $interfaceName: " . $ipAddress)

    :local result [/tool fetch url="https://www.zhisg.com/route.php/ddns/ali/set\?id=$id&secret=$secret&domain=$domain&ip=$ipAddress" as-value output=user];
    :log info $result;

  }
} else={
    :log error ("Failed to get IP address for $interfaceName")
}


# 定义IPV6地址接口名称
:local ipv6Interface "bridge1"
# 定义IPV6前缀地址池
:local ipv6Pool "TELEv6"

:local ipv6Addr [/ipv6 address get [/ipv6 address find interface=$ipv6Interface from-pool=$ipv6Pool] address ]
:local ipv6Prefix [ /ipv6 pool get [/ipv6 pool find name=$ipv6Pool] prefix ]

# 检查是否获取到IP地址
:if ($ipv6Addr != "") do={
    :set ipv6Addr [:pick $ipv6Addr 0 ([len $ipv6Addr] -3)]
  :if ($ipv6Addr != $GIPV6) do={
    :global GIPV6 $ipv6Addr
    :log info ("IPv6 Address of $ipv6Interface: " . $ipv6Addr)
    :log info ("IPv6 Prefix of $ipv6Pool: " . $ipv6Prefix)


    :local result [/tool fetch url="https://www.zhisg.com/route.php/ddns/ali/set\?id=$id&secret=$secret&domain=$domain&ip=$ipv6Addr&type=AAAA" as-value output=user];
    :log info $result;

  }
} else={
    :log error ("Failed to get IPv6 address for $ipv6Interface")
}

:log info "DDNS FINISHED"


Centos7/Redhat7升级OpenSSL

CentOS 发布时间:2025-05-30 02:49:50

原来的OpenSSL默认版本是1.0.2k

升级到最新版的OpenSSL步骤如下

下载官网最新的软件  https://openssl-library.org/source/

wget  https://github.com/openssl/openssl/releases/download/openssl-3.5.0/openssl-3.5.0.tar.gz

解压OpenSSL,并切换至包目录

tar zxvf openssl-3.5.0.tar.gz
cd openssl-3.5.0

安装编译所需依赖

yum install perl-IPC-Cmd perl-Data-Dumper gcc gcc-c++ perl perl-devel

预编译命令

./Configure --prefix=/usr/local/openssl/

编译和编译安装命令

make && make install

备份旧的OpenSSL,链接新OpenSSL的库文件

mv /usr/bin/openssl{,.bak}

ln -s /usr/local/openssl/bin/openssl /usr/bin/openssl
ln -s /usr/local/openssl/include/openssl /usr/include/openssl

检查OpenSSL,看看依赖是否正常

ldd /usr/bin/openssl

若有缺失项,libssl.so.3 => not found  libcrypto.so.3=> not found

则/etc/ld.so.conf.d/openssl.conf 添加配置

echo "/usr/local/openssl/lib64/" > /etc/ld.so.conf.d/openssl.conf

激活路径

ldconfig -v

再次检查可以看到前面缺失的库已经装载到内存了,OpenSSL可以使用了

检查OpenSSL的版本,确认升级成功

openssl version

使用acme.sh自动化脚本自动签发Let's Encrypt 证书

CentOS 发布时间:2025-05-29 09:31:15

安装命令:

curl https://get.acme.sh | sh -s email=my@example.com

安装过程不会污染已有的系统任何功能和文件,所有的修改都限制在安装目录中: ~/.acme.sh/

注意:如果安装完成后提示 -bash: acme.sh: command not found,需要手动执行 source ~/.bashrc

升级 acme.sh 到最新版:

acme.sh --upgrade

如果你不想手动升级,可以开启自动升级:

acme.sh --upgrade --auto-upgrade

修改默认 CA

acme.sh 脚本默认 CA 服务器是 ZeroSSL,把 CA 服务器改成 Let's Encrypt:

acme.sh --set-default-ca --server letsencrypt


手动验证DNS

acme.sh --issue --dns -d example.com --yes-I-know-dns-manual-mode-enough-go-ahead-please

自动验证(DNS API)以Aliyun为例

export Ali_Key="--key--"
export Ali_Secret="--sercert--"

签发通配符证书:

acme.sh --issue --dns dns_ali -d example.com -d *.example.com
更详细的 DNS API 用法: https://github.com/acmesh-official/acme.sh/wiki/dnsapi

继签证书:

acme.sh --renew -d example.com

安装复制证书

Apache 示例:

acme.sh --install-cert -d example.com --cert-file /path/to/certfile/in/apache/cert.pem --key-file /path/to/keyfile/in/apache/key.pem --fullchain-file /path/to/fullchain/certfile/apache/fullchain.pem --reloadcmd "systemctl reload httpd"

Nginx 示例:

acme.sh --install-cert -d example.com --key-file /path/to/keyfile/in/nginx/key.pem  --fullchain-file /path/to/fullchain/nginx/cert.pem --reloadcmd  "systemctl reload nginx"

注意:reloadcmd 非常重要。证书会自动申请续签,但是如果没有正确的 reloadcmd 命令,证书可能无法被重新应用到 Apache 或者 Nginx,因为配置没有被重载。

查看已安装证书信息

acme.sh --info -d example.com

查看所有安装的证书

acme.sh --list

删除一条安装的证书

acme.sh --remove -d example.com

由ECIES加密算法引发编写了RSAIES加密方法

PHP 发布时间:2025-05-28 12:54:36

ECDSA (Elliptic Curve Digital Signature Algorithm,椭圆曲线数字签名算法)

相比RSA算法密钥更短安全性更高,验签速度也更快,使用场景也得到广泛应用。

因为ECDSA算法只能做签名,不能做加解密,所以产生了ECIES(Elliptic Curve Integrated Encryption Scheme,椭圆曲线集成加密方案)。

ECIES 其中用到的 ECDH算法生成共享密钥,因平台兼容问题一些旧系统还无法支持。

所以依照ECIES的加密思路设计了自己的RSAIES加密方法:

RSAIES 加密方式详解
  • 生成随机AES密钥,使用 RSA 加密方法对其加密
  • 生成随机AES密钥iv值
  • 用随机AES密钥对数据进行AES-128-CFB加密,参数 OPENSSL_RAW_DATA
  • 密文和iv值进行base64处理(支持HEX)
  • 使用SHA256计算哈希值(mac),用于接收者验证数据完整性
  • 把 加密的随机AES密钥 cipher 向量 iv 编码方式 code 密文哈希值 mac 加密类型 RSAIES 放入 encryption 字段
RSAIES 解密方式详解
  • 把接收到的密文使用SHA256计算哈希值,验证mac值是否相同,判定数据是否完整
  • 把接收到的 加密的随机AES密钥 cipher 编码还原 base64_decode 后,使用 RSA 解密方法对其解密得到AES密钥原文
  • 用得到的随机AES密钥和收到的向量 iv 采用 aes-128-cfb 进行解密, 参数 OPENSSL_RAW_DATA
  • 得到原文


示例代码: https://github.com/unntech/encrypt/blob/main/src/RSA.php
    /**
     * RASIES加密
     * 生成随机AES密钥,使用 RSA 加密方法对其加密
     * 使用AES-128-CFB加密文本,参数选 OPENSSL_RAW_DATA
     * @param string $plaintext 明文数据
     * @param string $code 密文编码支持 base64 | hex | bin
     * @return false | array 
     *     [ 'cipher' => '加密的AES密钥', 
     *       'iv'     => 'iv',  
     *       'code'   => 'base64', 
     *       'ciphertext' => '密文', 
     *       'mac'    => '密文SHA256哈希' 
     *     ]
     * 
     */
    public function encrypt_ies(string $plaintext, string $code = 'base64', int $padding = OPENSSL_PKCS1_PADDING )
    {
        $publicKey = $this->third_public_key;
        // 生成随机对称密钥
        $cipher_method = 'aes-128-cfb';
        $symmetricKey = openssl_random_pseudo_bytes(16); // 使用 AES-128 密钥长度
        $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher_method));
        // 使用公钥加密对称密钥(使用 RASIES 过程)
        openssl_public_encrypt( $symmetricKey, $encryptedKey, $publicKey, $padding );
        // 使用对称密钥加密消息(AES-128-CFB)
        $encryptedMessage = openssl_encrypt($plaintext, $cipher_method, $symmetricKey, OPENSSL_RAW_DATA, $iv);
        $ciphertext = Encode::encode($encryptedMessage, $code );
        //使用SHA256计算密文哈希值
        $mac = strtoupper(hash("sha256", $ciphertext));

        // AES密钥cipher、向量iv、密文及哈希值
        return [
            'cipher_method' => $cipher_method,
            'cipher'        => Encode::encode($encryptedKey, $code),
            'iv'            => Encode::encode($iv, $code),
            'code'          => $code,
            'ciphertext'    => $ciphertext,
            'mac'           => $mac,
        ];
    }

    /**
     * RASIES 解密
     * 使用RSA解密方法对 $cipher 解密,得到AES密钥
     * 使用AES-128-CFB解密密文,参数选 OPENSSL_RAW_DATA,得到明文
     * @param string $ciphertext 密文
     * @param string $cipher 加密的AES密钥
     * @param string $iv AES加密向量
     * @param string|null $mac 密文哈希值
     * @param string $code 编码
     * @param int $padding 填充方式(OPENSSL_PKCS1_PADDING / OPENSSL_NO_PADDING)
     * @return string|null
     */
    public function decrypt_ies(string $ciphertext, string $cipher = '', string $iv = '', ?string $mac = null, string $code = 'base64', int $padding = OPENSSL_PKCS1_PADDING): ?string
    {
        // 解密对称密钥
        openssl_private_decrypt(Encode::decode($cipher, $code), $symmetricKey, $this->private_key, $padding);
        if(empty($symmetricKey)){
            return null;
        }
        // 2. 验证 MAC
        if(!is_null($mac)){
            $_mac = strtoupper(hash("sha256", $ciphertext));
            if($mac != $_mac){
                return null;
            }
        }
        // 3. 解密密文
        $plaintext = openssl_decrypt(Encode::decode($ciphertext, $code), 'aes-128-cfb', $symmetricKey, OPENSSL_RAW_DATA, Encode::decode($iv, $code));

        return $plaintext;
    }


RSAIES Integrated Encryption Scheme)RSA集成加密方案,采取了RSA使用广泛及跨平台兼容性高的优点,方案中只用RSA加解密随机AES密钥。

然后用AES进行对称加密数据,相比RSA加密快,又不用处理长文本RSA加密复杂的缺点。


Libsodium 加密库

PHP 发布时间:2025-05-26 02:38:36

Libsodium 是一个现代化、易用且高度安全的密码学库,旨在简化加密操作并避免常见的安全错误。它是 NaCl(Networking and Cryptography Library)的一个分支,由 Frank Denis 和社区维护。

安全设计哲学

  • 无脑安全默认配置:所有 API 默认使用当前最安全的算法和参数组合(如 XChaCha20-Poly1305、Argon2)。
  • 防误用设计:避免开发者因组合错误算法导致漏洞(如用 ECB 模式或弱哈希)。

现代密码学算法

  • 加密:XChaCha20-Poly1305, AES-GCM
  • 密钥交换:X25519(椭圆曲线 Diffie-Hellman)
  • 签名:Ed25519(EdDSA 签名)
  • 哈希:BLAKE2b
  • 密码哈希:Argon2(抗 GPU/ASIC 攻击)

跨平台支持

   提供 C 库及多种语言绑定(如 PHP、Python、Java)。

活跃维护与审计

   代码经过多次独立安全审计,社区活跃,及时修复漏洞。

PHP 7.2+ 已内置 Sodium 扩展(无需额外安装),通过函数前缀 sodium_* 调用。

官方文档: https://www.php.net/manual/zh/book.sodium.php

Libsodium 是开发者的“密码学瑞士军刀”,强烈推荐在安全敏感项目中替代 OpenSSL 等传统库。其设计目标正是让安全变得简单,让开发者专注于业务逻辑而非密码学细节。


配置mpdf导出PDF支持中文

PHP 发布时间:2025-05-19 10:14:03

修改配置文件:vendor/mpdf/mpdf/src/Config/ConfigVariables.php

'useAdobeCJK' => true,
'autoScriptToLang' => true,
'autoLangToFont' => true,
'useSubstitutions' => true,


Composer常用配置优化

PHP 发布时间:2025-05-16 02:34:31
  • 全局配置:作用范围:对所有项目生效;
  • 文件路径:~/.composer/config.json(Linux/macOS)或%APPDATA%\Composer\config.json(Windows)
composer config --global 配置项 值
  • 项目级配置:作用范围:仅对当前项目生效;
  • 文件路径:项目根目录下的composer.json
composer config 配置项 值
  • 修改包源(国内镜像源加速)
composer config --global repo.packagist composer https://mirrors.aliyun.com/composer/
  • 恢复官方源
composer config --global --unset repos.packagist
  • 修改缓存路径:解决网络盘和下载慢,已下载的库缓存至本地
composer config --global cache-dir /本地路径/cache
  • 查看当前缓存路径
composer config cache-dir
  • 查看当前配置
composer config --list --global    # 查看全局配置
composer config --list                  
# 查看项目级配置
  • 重置配置项
composer config --global --unset 配置项   # 删除全局配置项
  • ---

ROS通过aliyun域名解析实现DDNS脚本

ROS 发布时间:2025-03-29 05:51:38
#aliyun Access Key
:local id "key"
:local secret "secret"

#domain
:local domain "your.domain.com"


#PPPoE-out
:local pppoe "pppoe-out1"

#阿里云DDNS服务器:

:local ipaddr [/ip address get [/ip address find interface=$pppoe] address]
:set ipaddr [:pick $ipaddr 0 ([len $ipaddr] -3)]
#:log info $ipaddr;
:local result [/tool fetch url="https://www.zhisg.com/route.php/ddns/ali/set\?id=$id&secret=$secret&domain=$domain&ip=$ipaddr" as-value output=user];
:log info $result;


#:global ddnspool "ipv6"
#:global ddnsinterface "bridge"
#:global ddnsinterface "6to4-henet"
#:global ddnsinterface "pppoe-out1"
#:global ddnsinterface "ether6"

# Define Global Variables
:global ddnsip
:global ddnslastip
:if ([ :typeof $ddnslastip ] = nil ) do={ :global ddnslastip "0" }


# Define Local Variables
:local int

# Loop thru interfaces and look for ones containing
# default gateways without routing-marks
:if ([ :typeof $ddnsinterface ] != "str" ) do={
  :foreach int in=[ /ipv6 address find global ] do={
    :local testip [ /ipv6 address get $int address ]
    :if ($testip in "fe80::/10" || $testip in "fc00::/7") do={
    } else={
      :global ddnsip $testip
    }
  }
} else={
  :if ([ :typeof $ddnspool ] != "str" ) do={
    # Grab the current Global IP address on that interface.
    :foreach int in=[ /ipv6 address find interface=$ddnsinterface global ] do={
      :local testip [ /ipv6 address get $int address ]
      :if ($testip in "fe80::/10" || $testip in "fc00::/7") do={
      } else={
        :global ddnsip $testip
      }
    }
  } else={
    # Grab the current Global IP address on that interface from spec ip pool.
    :global ddnsip [ /ipv6 address get [ /ipv6 address find interface=$ddnsinterface  from-pool=$ddnspool ] address ]
  }
}

# Did we get an IP address to compare?
:if ([ :typeof $ddnsip ] = nil ) do={
   :log info ("DynDNS: No ip address present on please check.")
} else={
  :log info ("DynDNS: check IPv6 UPDATE " . $ddnsip)
#  :if ($ddnsip != $ddnslastip) do={
:local result [/tool fetch url="https://www.zhisg.com/route.php/ddns/ali/set\?id=$id&secret=$secret&domain=$domain&ip=$ddnsip&type=AAAA" as-value output=user];
:log info $result;    
    :global ddnslastip $ddnsip
#  }
}


PHP OPcache 配置参数优化方案

PHP 发布时间:2025-03-19 10:45:14
vim /etc/php.d/10-opcache.ini
; Enable Zend OPcache extension module
zend_extension=opcache

; Determines if Zend OPCache is enabled
opcache.enable=1

; Determines if Zend OPCache is enabled for the CLI version of PHP
opcache.enable_cli=1

; The OPcache shared memory storage size.
opcache.memory_consumption=512

; The amount of memory for interned strings in Mbytes.
opcache.interned_strings_buffer=16

; The maximum number of keys (scripts) in the OPcache hash table.
; Only numbers between 200 and 1000000 are allowed.
opcache.max_accelerated_files=300000

; The maximum percentage of "wasted" memory until a restart is scheduled.
;opcache.max_wasted_percentage=5

; When this directive is enabled, the OPcache appends the current working
; directory to the script key, thus eliminating possible collisions between
; files with the same name (basename). Disabling the directive improves
; performance, but may break existing applications.
;opcache.use_cwd=1

; When disabled, you must reset the OPcache manually or restart the
; webserver for changes to the filesystem to take effect.
opcache.validate_timestamps=1

; How often (in seconds) to check file timestamps for changes to the shared
; memory storage allocation. ("1" means validate once per second, but only
; once per request. "0" means always validate)
opcache.revalidate_freq=10

; Enables or disables file search in include_path optimization
;opcache.revalidate_path=0

; If disabled, all PHPDoc comments are dropped from the code to reduce the
; size of the optimized code.
;opcache.save_comments=1

; If enabled, compilation warnings (including notices and deprecations) will
; be recorded and replayed each time a file is included. Otherwise, compilation
; warnings will only be emitted when the file is first cached.
;opcache.record_warnings=0

; Allow file existence override (file_exists, etc.) performance feature.
;opcache.enable_file_override=0

; A bitmask, where each bit enables or disables the appropriate OPcache
; passes
;opcache.optimization_level=0x7FFFBFFF

; This hack should only be enabled to work around "Cannot redeclare class"
; errors.
;opcache.dups_fix=0

; The location of the OPcache blacklist file (wildcards allowed).
; Each OPcache blacklist file is a text file that holds the names of files
; that should not be accelerated.
opcache.blacklist_filename=/etc/php.d/opcache*.blacklist

; Allows exclusion of large files from being cached. By default all files
; are cached.
;opcache.max_file_size=0

; Check the cache checksum each N requests.
; The default value of "0" means that the checks are disabled.
;opcache.consistency_checks=0

; How long to wait (in seconds) for a scheduled restart to begin if the cache
; is not being accessed.
;opcache.force_restart_timeout=180

; OPcache error_log file name. Empty string assumes "stderr".
;opcache.error_log=

; All OPcache errors go to the Web server log.
; By default, only fatal errors (level 0) or errors (level 1) are logged.
; You can also enable warnings (level 2), info messages (level 3) or
; debug messages (level 4).
;opcache.log_verbosity_level=1

; Preferred Shared Memory back-end. Leave empty and let the system decide.
;opcache.preferred_memory_model=

; Protect the shared memory from unexpected writing during script execution.
; Useful for internal debugging only.
;opcache.protect_memory=0

; Allows calling OPcache API functions only from PHP scripts which path is
; started from specified string. The default "" means no restriction
;opcache.restrict_api=

; Enables and sets the second level cache directory.
; It should improve performance when SHM memory is full, at server restart or
; SHM reset. The default "" disables file based caching.
; RPM note : file cache directory must be owned by process owner
;   for mod_php, see /etc/httpd/conf.d/php.conf
;   for php-fpm, see /etc/php-fpm.d/*conf
opcache.file_cache=/tmp

; Enables or disables opcode caching in shared memory.
;opcache.file_cache_only=0

; Enables or disables checksum validation when script loaded from file cache.
;opcache.file_cache_consistency_checks=1

; Implies opcache.file_cache_only=1 for a certain process that failed to
; reattach to the shared memory (for Windows only). Explicitly enabled file
; cache is required.
;opcache.file_cache_fallback=1

; Enables or disables copying of PHP code (text segment) into HUGE PAGES.
; Under certain circumstances (if only a single global PHP process is
; started from which all others fork), this can increase performance
; by a tiny amount because TLB misses are reduced.  On the other hand, this
; delays PHP startup, increases memory usage and degrades performance
; under memory pressure - use with care.
; Requires appropriate OS configuration.
opcache.huge_code_pages=1

; Validate cached file permissions.
; Leads OPcache to check file readability on each access to cached file.
; This directive should be enabled in shared hosting environment, when few
; users (PHP-FPM pools) reuse the common OPcache shared memory.
;opcache.validate_permission=0

; Prevent name collisions in chroot'ed environment.
; This directive prevents file name collisions in different "chroot"
; environments. It should be enabled for sites that may serve requests in
; different "chroot" environments.
;opcache.validate_root=0

; If specified, it produces opcode dumps for debugging different stages of
; optimizations.
;opcache.opt_debug_level=0

; Specifies a PHP script that is going to be compiled and executed at server
; start-up.
; https://php.net/opcache.preload
;opcache.preload=

; Preloading code as root is not allowed for security reasons. This directive
; facilitates to let the preloading to be run as another user.
; https://php.net/opcache.preload_user
;opcache.preload_user=

; Prevents caching files that are less than this number of seconds old. It
; protects from caching of incompletely updated files. In case all file updates
; on your site are atomic, you may increase performance by setting it to "0".
;opcache.file_update_protection=2

; Absolute path used to store shared lockfiles (for *nix only).
;opcache.lockfile_path=/tmp
;
;JIT
opcache.jit=tracing
opcache.jit_buffer_size=256M


MySQL配置优化参数

MySQL 发布时间:2025-03-19 10:31:54
vim /etc/my.cnf
# For advice on how to change settings please see
# http://dev.mysql.com/doc/refman/5.7/en/server-configuration-defaults.html

[mysqld]
#
# Remove leading # and set to the amount of RAM for the most important data
# cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%.
# innodb_buffer_pool_size = 128M
#
# Remove leading # to turn on a very important data integrity option: logging
# changes to the binary log between backups.
# log_bin
#
# Remove leading # to set options mainly useful for reporting servers.
# The server defaults are faster for transactions and fast SELECTs.
# Adjust sizes as needed, experiment to find the optimal values.
# join_buffer_size = 128M
# sort_buffer_size = 2M
# read_rnd_buffer_size = 2M

datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock

# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
event_scheduler=1
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER
max_connections=1000

skip_name_resolve

innodb_buffer_pool_size = 32000M
innodb_log_file_size = 2048M

query_cache_type=0
query_cache_size=0
query_cache_limit=1M

server-id = 112031
master-info-repository = table
relay-log-info-repository = table
relay-log-recovery=1

log-bin = mysql-bin
expire_logs_days = 7
binlog_format = mixed
#binlog-ignore-db = mysql
binlog-ignore-db = sys
binlog-ignore-db = phpmyadmin
binlog-ignore-db = information_schema
binlog-ignore-db = performance_schema

log-slave-updates
#replicate-ignore-db = mysql
#
slave-skip-errors=all

slow_query_log = 1
long_query_time = 2
#log_output = table