一 簡介
License,即版權許可證,一般用於收費軟件給付費用戶提供的訪問許可證明。根據應用部署位置的不同,一般可以分為以下兩種情況討論:
- 應用部署在開發者自己的雲服務器上。這種情況下用戶通過賬號登錄的形式遠程訪問,因此只需要在賬號登錄的時候校驗目標賬號的有效期、訪問權限等信息即可。
- 應用部署在客戶的內網環境。因為這種情況開發者無法控制客戶的網絡環境,也不能保證應用所在服務器可以訪問外網,因此通常的做法是使用服務器許可文件,在應用啟動的時候加載證書,然后在登錄或者其他關鍵操作的地方校驗證書的有效性。
注:限於文章篇幅,這里只討論代碼層面的許可限制,暫不考慮逆向破解等問題。此外,在下面我只講解關鍵代碼實現,完整代碼可以參考:gitee.com/zifangsky/L…
二 使用 TrueLicense 生成License
(1)使用Spring Boot構建測試項目ServerDemo,用於為客戶生成License許可文件:
注:這個完整的Demo項目可以參考:gitee.com/zifangsky/L…
i)在pom.xml中添加關鍵依賴:
<dependency> <groupId>de.schlichtherle.truelicense</groupId> <artifactId>truelicense-core</artifactId> <version>1.33</version> <scope>provided</scope> </dependency> 復制代碼
ii)校驗自定義的License參數:
TrueLicense的 de.schlichtherle.license.LicenseManager 類自帶的verify方法只校驗了我們后面頒發的許可文件的生效和過期時間,然而在實際項目中我們可能需要額外校驗應用部署的服務器的IP地址、MAC地址、CPU序列號、主板序列號等信息,因此我們需要復寫框架的部分方法以實現校驗自定義參數的目的。
首先需要添加一個自定義的可被允許的服務器硬件信息的實體類(如果校驗其他參數,可自行補充):
package cn.zifangsky.license; import java.io.Serializable; import java.util.List; /** * 自定義需要校驗的License參數 * * @author zifangsky * @date 2018/4/23 * @since 1.0.0 */ public class LicenseCheckModel implements Serializable{ private static final long serialVersionUID = 8600137500316662317L; /** * 可被允許的IP地址 */ private List<String> ipAddress; /** * 可被允許的MAC地址 */ private List<String> macAddress; /** * 可被允許的CPU序列號 */ private String cpuSerial; /** * 可被允許的主板序列號 */ private String mainBoardSerial; //省略setter和getter方法 @Override public String toString() { return "LicenseCheckModel{" + "ipAddress=" + ipAddress + ", macAddress=" + macAddress + ", cpuSerial='" + cpuSerial + '\'' + ", mainBoardSerial='" + mainBoardSerial + '\'' + '}'; } } 復制代碼
其次,添加一個License生成類需要的參數:
package cn.zifangsky.license; import com.fasterxml.jackson.annotation.JsonFormat; import java.io.Serializable; import java.util.Date; /** * License生成類需要的參數 * * @author zifangsky * @date 2018/4/19 * @since 1.0.0 */ public class LicenseCreatorParam implements Serializable { private static final long serialVersionUID = -7793154252684580872L; /** * 證書subject */ private String subject; /** * 密鑰別稱 */ private String privateAlias; /** * 密鑰密碼(需要妥善保管,不能讓使用者知道) */ private String keyPass; /** * 訪問秘鑰庫的密碼 */ private String storePass; /** * 證書生成路徑 */ private String licensePath; /** * 密鑰庫存儲路徑 */ private String privateKeysStorePath; /** * 證書生效時間 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date issuedTime = new Date(); /** * 證書失效時間 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date expiryTime; /** * 用戶類型 */ private String consumerType = "user"; /** * 用戶數量 */ private Integer consumerAmount = 1; /** * 描述信息 */ private String description = ""; /** * 額外的服務器硬件校驗信息 */ private LicenseCheckModel licenseCheckModel; //省略setter和getter方法 @Override public String toString() { return "LicenseCreatorParam{" + "subject='" + subject + '\'' + ", privateAlias='" + privateAlias + '\'' + ", keyPass='" + keyPass + '\'' + ", storePass='" + storePass + '\'' + ", licensePath='" + licensePath + '\'' + ", privateKeysStorePath='" + privateKeysStorePath + '\'' + ", issuedTime=" + issuedTime + ", expiryTime=" + expiryTime + ", consumerType='" + consumerType + '\'' + ", consumerAmount=" + consumerAmount + ", description='" + description + '\'' + ", licenseCheckModel=" + licenseCheckModel + '}'; } } 復制代碼
添加抽象類AbstractServerInfos,用戶獲取服務器的硬件信息:
package cn.zifangsky.license; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; /** * 用於獲取客戶服務器的基本信息,如:IP、Mac地址、CPU序列號、主板序列號等 * * @author zifangsky * @date 2018/4/23 * @since 1.0.0 */ public abstract class AbstractServerInfos { private static Logger logger = LogManager.getLogger(AbstractServerInfos.class); /** * 組裝需要額外校驗的License參數 * @author zifangsky * @date 2018/4/23 14:23 * @since 1.0.0 * @return demo.LicenseCheckModel */ public LicenseCheckModel getServerInfos(){ LicenseCheckModel result = new LicenseCheckModel(); try { result.setIpAddress(this.getIpAddress()); result.setMacAddress(this.getMacAddress()); result.setCpuSerial(this.getCPUSerial()); result.setMainBoardSerial(this.getMainBoardSerial()); }catch (Exception e){ logger.error("獲取服務器硬件信息失敗",e); } return result; } /** * 獲取IP地址 * @author zifangsky * @date 2018/4/23 11:32 * @since 1.0.0 * @return java.util.List<java.lang.String> */ protected abstract List<String> getIpAddress() throws Exception; /** * 獲取Mac地址 * @author zifangsky * @date 2018/4/23 11:32 * @since 1.0.0 * @return java.util.List<java.lang.String> */ protected abstract List<String> getMacAddress() throws Exception; /** * 獲取CPU序列號 * @author zifangsky * @date 2018/4/23 11:35 * @since 1.0.0 * @return java.lang.String */ protected abstract String getCPUSerial() throws Exception; /** * 獲取主板序列號 * @author zifangsky * @date 2018/4/23 11:35 * @since 1.0.0 * @return java.lang.String */ protected abstract String getMainBoardSerial() throws Exception; /** * 獲取當前服務器所有符合條件的InetAddress * @author zifangsky * @date 2018/4/23 17:38 * @since 1.0.0 * @return java.util.List<java.net.InetAddress> */ protected List<InetAddress> getLocalAllInetAddress() throws Exception { List<InetAddress> result = new ArrayList<>(4); // 遍歷所有的網絡接口 for (Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces(); networkInterfaces.hasMoreElements(); ) { NetworkInterface iface = (NetworkInterface) networkInterfaces.nextElement(); // 在所有的接口下再遍歷IP for (Enumeration inetAddresses = iface.getInetAddresses(); inetAddresses.hasMoreElements(); ) { InetAddress inetAddr = (InetAddress) inetAddresses.nextElement(); //排除LoopbackAddress、SiteLocalAddress、LinkLocalAddress、MulticastAddress類型的IP地址 if(!inetAddr.isLoopbackAddress() /*&& !inetAddr.isSiteLocalAddress()*/ && !inetAddr.isLinkLocalAddress() && !inetAddr.isMulticastAddress()){ result.add(inetAddr); } } } return result; } /** * 獲取某個網絡接口的Mac地址 * @author zifangsky * @date 2018/4/23 18:08 * @since 1.0.0 * @param * @return void */ protected String getMacByInetAddress(InetAddress inetAddr){ try { byte[] mac = NetworkInterface.getByInetAddress(inetAddr).getHardwareAddress(); StringBuffer stringBuffer = new StringBuffer(); for(int i=0;i<mac.length;i++){ if(i != 0) { stringBuffer.append("-"); } //將十六進制byte轉化為字符串 String temp = Integer.toHexString(mac[i] & 0xff); if(temp.length() == 1){ stringBuffer.append("0" + temp); }else{ stringBuffer.append(temp); } } return stringBuffer.toString().toUpperCase(); } catch (SocketException e) { e.printStackTrace(); } return null; } } 復制代碼
獲取客戶Linux服務器的基本信息:
package cn.zifangsky.license; import org.apache.commons.lang3.StringUtils; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.InetAddress; import java.util.List; import java.util.stream.Collectors; /** * 用於獲取客戶Linux服務器的基本信息 * * @author zifangsky * @date 2018/4/23 * @since 1.0.0 */ public class LinuxServerInfos extends AbstractServerInfos { @Override protected List<String> getIpAddress() throws Exception { List<String> result = null; //獲取所有網絡接口 List<InetAddress> inetAddresses = getLocalAllInetAddress(); if(inetAddresses != null && inetAddresses.size() > 0){ result = inetAddresses.stream().map(InetAddress::getHostAddress).distinct().map(String::toLowerCase).collect(Collectors.toList()); } return result; } @Override protected List<String> getMacAddress() throws Exception { List<String> result = null; //1. 獲取所有網絡接口 List<InetAddress> inetAddresses = getLocalAllInetAddress(); if(inetAddresses != null && inetAddresses.size() > 0){ //2. 獲取所有網絡接口的Mac地址 result = inetAddresses.stream().map(this::getMacByInetAddress).distinct().collect(Collectors.toList()); } return result; } @Override protected String getCPUSerial() throws Exception { //序列號 String serialNumber = ""; //使用dmidecode命令獲取CPU序列號 String[] shell = {"/bin/bash","-c","dmidecode -t processor | grep 'ID' | awk -F ':' '{print $2}' | head -n 1"}; Process process = Runtime.getRuntime().exec(shell); process.getOutputStream().close(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = reader.readLine().trim(); if(StringUtils.isNotBlank(line)){ serialNumber = line; } reader.close(); return serialNumber; } @Override protected String getMainBoardSerial() throws Exception { //序列號 String serialNumber = ""; //使用dmidecode命令獲取主板序列號 String[] shell = {"/bin/bash","-c","dmidecode | grep 'Serial Number' | awk -F ':' '{print $2}' | head -n 1"}; Process process = Runtime.getRuntime().exec(shell); process.getOutputStream().close(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = reader.readLine().trim(); if(StringUtils.isNotBlank(line)){ serialNumber = line; } reader.close(); return serialNumber; } } 復制代碼
獲取客戶Windows服務器的基本信息:
package cn.zifangsky.license; import java.net.InetAddress; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; /** * 用於獲取客戶Windows服務器的基本信息 * * @author zifangsky * @date 2018/4/23 * @since 1.0.0 */ public class WindowsServerInfos extends AbstractServerInfos { @Override protected List<String> getIpAddress() throws Exception { List<String> result = null; //獲取所有網絡接口 List<InetAddress> inetAddresses = getLocalAllInetAddress(); if(inetAddresses != null && inetAddresses.size() > 0){ result = inetAddresses.stream().map(InetAddress::getHostAddress).distinct().map(String::toLowerCase).collect(Collectors.toList()); } return result; } @Override protected List<String> getMacAddress() throws Exception { List<String> result = null; //1. 獲取所有網絡接口 List<InetAddress> inetAddresses = getLocalAllInetAddress(); if(inetAddresses != null && inetAddresses.size() > 0){ //2. 獲取所有網絡接口的Mac地址 result = inetAddresses.stream().map(this::getMacByInetAddress).distinct().collect(Collectors.toList()); } return result; } @Override protected String getCPUSerial() throws Exception { //序列號 String serialNumber = ""; //使用WMIC獲取CPU序列號 Process process = Runtime.getRuntime().exec("wmic cpu get processorid"); process.getOutputStream().close(); Scanner scanner = new Scanner(process.getInputStream()); if(scanner.hasNext()){ scanner.next(); } if(scanner.hasNext()){ serialNumber = scanner.next().trim(); } scanner.close(); return serialNumber; } @Override protected String getMainBoardSerial() throws Exception { //序列號 String serialNumber = ""; //使用WMIC獲取主板序列號 Process process = Runtime.getRuntime().exec("wmic baseboard get serialnumber"); process.getOutputStream().close(); Scanner scanner = new Scanner(process.getInputStream()); if(scanner.hasNext()){ scanner.next(); } if(scanner.hasNext()){ serialNumber = scanner.next().trim(); } scanner.close(); return serialNumber; } } 復制代碼
注:這里使用了模板方法模式,將不變部分的算法封裝到抽象類,而基本方法的具體實現則由子類來實現。更多內容可以參考我之前寫的文檔:模板方法模式
自定義LicenseManager,用於增加額外的服務器硬件信息校驗:
package cn.zifangsky.license; import de.schlichtherle.license.LicenseContent; import de.schlichtherle.license.LicenseContentException; import de.schlichtherle.license.LicenseManager; import de.schlichtherle.license.LicenseNotary; import de.schlichtherle.license.LicenseParam; import de.schlichtherle.license.NoLicenseInstalledException; import de.schlichtherle.xml.GenericCertificate; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.beans.XMLDecoder; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.List; /** * 自定義LicenseManager,用於增加額外的服務器硬件信息校驗 * * @author zifangsky * @date 2018/4/23 * @since 1.0.0 */ public class CustomLicenseManager extends LicenseManager{ private static Logger logger = LogManager.getLogger(CustomLicenseManager.class); //XML編碼 private static final String XML_CHARSET = "UTF-8"; //默認BUFSIZE private static final int DEFAULT_BUFSIZE = 8 * 1024; public CustomLicenseManager() { } public CustomLicenseManager(LicenseParam param) { super(param); } /** * 復寫create方法 * @author zifangsky * @date 2018/4/23 10:36 * @since 1.0.0 * @param * @return byte[] */ @Override protected synchronized byte[] create( LicenseContent content, LicenseNotary notary) throws Exception { initialize(content); this.validateCreate(content); final GenericCertificate certificate = notary.sign(content); return getPrivacyGuard().cert2key(certificate); } /** * 復寫install方法,其中validate方法調用本類中的validate方法,校驗IP地址、Mac地址等其他信息 * @author zifangsky * @date 2018/4/23 10:40 * @since 1.0.0 * @param * @return de.schlichtherle.license.LicenseContent */ @Override protected synchronized LicenseContent install( final byte[] key, final LicenseNotary notary) throws Exception { final GenericCertificate certificate = getPrivacyGuard().key2cert(key); notary.verify(certificate); final LicenseContent content = (LicenseContent)this.load(certificate.getEncoded()); this.validate(content); setLicenseKey(key); setCertificate(certificate); return content; } /** * 復寫verify方法,調用本類中的validate方法,校驗IP地址、Mac地址等其他信息 * @author zifangsky * @date 2018/4/23 10:40 * @since 1.0.0 * @param * @return de.schlichtherle.license.LicenseContent */ @Override protected synchronized LicenseContent verify(final LicenseNotary notary) throws Exception { GenericCertificate certificate = getCertificate(); // Load license key from preferences, final byte[] key = getLicenseKey(); if (null == key){ throw new NoLicenseInstalledException(getLicenseParam().getSubject()); } certificate = getPrivacyGuard().key2cert(key); notary.verify(certificate); final LicenseContent content = (LicenseContent)this.load(certificate.getEncoded()); this.validate(content); setCertificate(certificate); return content; } /** * 校驗生成證書的參數信息 * @author zifangsky * @date 2018/5/2 15:43 * @since 1.0.0 * @param content 證書正文 */ protected synchronized void validateCreate(final LicenseContent content) throws LicenseContentException { final LicenseParam param = getLicenseParam(); final Date now = new Date(); final Date notBefore = content.getNotBefore(); final Date notAfter = content.getNotAfter(); if (null != notAfter && now.after(notAfter)){ throw new LicenseContentException("證書失效時間不能早於當前時間"); } if (null != notBefore && null != notAfter && notAfter.before(notBefore)){ throw new LicenseContentException("證書生效時間不能晚於證書失效時間"); } final String consumerType = content.getConsumerType(); if (null == consumerType){ throw new LicenseContentException("用戶類型不能為空"); } } /** * 復寫validate方法,增加IP地址、Mac地址等其他信息校驗 * @author zifangsky * @date 2018/4/23 10:40 * @since 1.0.0 * @param content LicenseContent */ @Override protected synchronized void validate(final LicenseContent content) throws LicenseContentException { //1. 首先調用父類的validate方法 super.validate(content); //2. 然后校驗自定義的License參數 //License中可被允許的參數信息 LicenseCheckModel expectedCheckModel = (LicenseCheckModel) content.getExtra(); //當前服務器真實的參數信息 LicenseCheckModel serverCheckModel = getServerInfos(); if(expectedCheckModel != null && serverCheckModel != null){ //校驗IP地址 if(!checkIpAddress(expectedCheckModel.getIpAddress(),serverCheckModel.getIpAddress())){ throw new LicenseContentException("當前服務器的IP沒在授權范圍內"); } //校驗Mac地址 if(!checkIpAddress(expectedCheckModel.getMacAddress(),serverCheckModel.getMacAddress())){ throw new LicenseContentException("當前服務器的Mac地址沒在授權范圍內"); } //校驗主板序列號 if(!checkSerial(expectedCheckModel.getMainBoardSerial(),serverCheckModel.getMainBoardSerial())){ throw new LicenseContentException("當前服務器的主板序列號沒在授權范圍內"); } //校驗CPU序列號 if(!checkSerial(expectedCheckModel.getCpuSerial(),serverCheckModel.getCpuSerial())){ throw new LicenseContentException("當前服務器的CPU序列號沒在授權范圍內"); } }else{ throw new LicenseContentException("不能獲取服務器硬件信息"); } } /** * 重寫XMLDecoder解析XML * @author zifangsky * @date 2018/4/25 14:02 * @since 1.0.0 * @param encoded XML類型字符串 * @return java.lang.Object */ private Object load(String encoded){ BufferedInputStream inputStream = null; XMLDecoder decoder = null; try { inputStream = new BufferedInputStream(new ByteArrayInputStream(encoded.getBytes(XML_CHARSET))); decoder = new XMLDecoder(new BufferedInputStream(inputStream, DEFAULT_BUFSIZE),null,null); return decoder.readObject(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } finally { try { if(decoder != null){ decoder.close(); } if(inputStream != null){ inputStream.close(); } } catch (Exception e) { logger.error("XMLDecoder解析XML失敗",e); } } return null; } /** * 獲取當前服務器需要額外校驗的License參數 * @author zifangsky * @date 2018/4/23 14:33 * @since 1.0.0 * @return demo.LicenseCheckModel */ private LicenseCheckModel getServerInfos(){ //操作系統類型 String osName = System.getProperty("os.name").toLowerCase(); AbstractServerInfos abstractServerInfos = null; //根據不同操作系統類型選擇不同的數據獲取方法 if (osName.startsWith("windows")) { abstractServerInfos = new WindowsServerInfos(); } else if (osName.startsWith("linux")) { abstractServerInfos = new LinuxServerInfos(); }else{//其他服務器類型 abstractServerInfos = new LinuxServerInfos(); } return abstractServerInfos.getServerInfos(); }