cert.html 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. <style>
  2. .expired.certdate{
  3. font-weight: bolder;
  4. color: #bd001c;
  5. }
  6. .valid.certdate{
  7. color: #31c071;
  8. }
  9. </style>
  10. <div class="standardContainer">
  11. <div class="ui basic segment">
  12. <h2>TLS / SSL Certificates</h2>
  13. <p>Setup TLS cert for different domains of your reverse proxy server names</p>
  14. </div>
  15. <div class="ui divider"></div>
  16. <h3>Hosts Certificates</h3>
  17. <p>Provide certificates for multiple domains reverse proxy</p>
  18. <div class="ui fluid form">
  19. <div class="three fields">
  20. <div class="field">
  21. <label>Server Name (Domain)</label>
  22. <input type="text" id="certdomain" placeholder="example.com / blog.example.com">
  23. <small><i class="exclamation circle yellow icon"></i> Match the server name with your CN/DNS entry in certificate for faster resolve time</small>
  24. </div>
  25. <div class="field">
  26. <label>Public Key (.pem)</label>
  27. <input type="file" id="pubkeySelector" onchange="handleFileSelect(event, 'pub')">
  28. <small>or .crt files in order systems</small>
  29. </div>
  30. <div class="field">
  31. <label>Private Key (.key)</label>
  32. <input type="file" id="prikeySelector" onchange="handleFileSelect(event, 'pri')">
  33. </div>
  34. </div>
  35. <button class="ui basic button" onclick="handleDomainUploadByKeypress();"><i class="ui teal upload icon"></i> Upload</button><br>
  36. <small>You have intermediate certificate? <a style="cursor:pointer;" onclick="showSideWrapper('snippet/intermediateCertConv.html');">Open Conversion Tool</a></small>
  37. </div>
  38. <div id="certUploadSuccMsg" class="ui green message" style="display:none;">
  39. <i class="ui checkmark icon"></i> Certificate for domain <span id="certUploadingDomain"></span> uploaded.
  40. </div>
  41. <div class="ui message">
  42. <h4>Tips about Server Names & SNI</h4>
  43. <div class="ui bulleted list">
  44. <div class="item">
  45. If you have two subdomains like <code>a.example.com</code> and <code>b.example.com</code> ,
  46. for faster response speed, you might want to setup them one by one (i.e. having two seperate certificate for
  47. <code>a.example.com</code> and <code>b.example.com</code>).
  48. </div>
  49. <div class="item">
  50. If you have a wildcard certificate that covers <code>*.example.com</code>,
  51. you can just enter <code>example.com</code> as server name to add a certificate.
  52. </div>
  53. <div class="item">
  54. If you have a certificate contain multiple host, you can enter the first domain in your certificate
  55. and Zoraxy will try to match the remaining CN/DNS for you.
  56. </div>
  57. </div>
  58. </div>
  59. <p>Current list of loaded certificates</p>
  60. <div>
  61. <div style="width: 100%; overflow-x: auto; margin-bottom: 1em;">
  62. <table class="ui sortable unstackable basic celled table">
  63. <thead>
  64. <tr><th>Domain</th>
  65. <th>Last Update</th>
  66. <th>Expire At</th>
  67. <th>DNS Challenge</th>
  68. <th class="no-sort">Renew</th>
  69. <th class="no-sort">Remove</th>
  70. </tr></thead>
  71. <tbody id="certifiedDomainList">
  72. </tbody>
  73. </table>
  74. </div>
  75. <button class="ui basic button" onclick="initManagedDomainCertificateList();"><i class="green refresh icon"></i> Refresh List</button>
  76. </div>
  77. <div class="ui divider"></div>
  78. <h3>Fallback Certificate</h3>
  79. <p>When there are no matching certificate for the requested server name, reverse proxy router will always fallback to this one.<br>Note that you need both of them uploaded for it to fallback properly</p>
  80. <table class="ui very basic unstackable celled table">
  81. <thead>
  82. <tr><th class="no-sort">Key Type</th>
  83. <th class="no-sort">Found</th>
  84. </tr></thead>
  85. <tbody>
  86. <tr>
  87. <td><i class="globe icon"></i> Fallback Public Key</td>
  88. <td id="pubkeyExists"></td>
  89. </tr>
  90. <tr>
  91. <td><i class="lock icon"></i> Fallback Private Key</td>
  92. <td id="prikeyExists"></td>
  93. </tr>
  94. </tbody>
  95. </table>
  96. <p style="margin-bottom: 0.4em;"><i class="ui upload icon"></i> Upload Default Keypairs</p>
  97. <div class="ui buttons">
  98. <button class="ui basic grey button" onclick="uploadPublicKey();"><i class="globe icon"></i> Public Key</button>
  99. <button class="ui basic black button" onclick="uploadPrivateKey();"><i class="black lock icon"></i> Private Key</button>
  100. </div>
  101. <div class="ui divider"></div>
  102. <h3>Certificate Authority (CA) and Auto Renew (ACME)</h3>
  103. <p>Management features regarding CA and ACME</p>
  104. <h4>Prefered Certificate Authority</h4>
  105. <p>The default CA to use when create a new subdomain proxy endpoint with TLS certificate</p>
  106. <div class="ui fluid form">
  107. <div class="field">
  108. <label>Preferred CA</label>
  109. <div class="ui selection dropdown" id="defaultCA">
  110. <input type="hidden" name="defaultCA">
  111. <i class="dropdown icon"></i>
  112. <div class="default text">Let's Encrypt</div>
  113. <div class="menu">
  114. <div class="item" data-value="Let's Encrypt">Let's Encrypt</div>
  115. <div class="item" data-value="Buypass">Buypass</div>
  116. <div class="item" data-value="ZeroSSL">ZeroSSL</div>
  117. </div>
  118. </div>
  119. </div>
  120. <div class="field">
  121. <label>ACME Email</label>
  122. <input id="prefACMEEmail" type="text" placeholder="ACME Email">
  123. </div>
  124. <button class="ui basic icon button" onclick="saveDefaultCA();"><i class="ui blue save icon"></i> Save Settings</button>
  125. </div><br>
  126. <h5>Certificate Renew / Generation (ACME) Settings</h5>
  127. <div class="ui basic segment acmeRenewStateWrapper">
  128. <h4 class="ui header" id="acmeAutoRenewer">
  129. <i class="white remove icon"></i>
  130. <div class="content">
  131. <span id="acmeAutoRenewerStatus">Disabled</span>
  132. <div class="sub header">ACME Auto-Renewer</div>
  133. </div>
  134. </h4>
  135. </div>
  136. <p>This tool provide you a graphical interface to setup auto certificate renew on your (sub)domains. You can also manually generate a certificate if one of your domain do not have certificate.</p>
  137. <button class="ui basic button" onclick="openACMEManager();"><i class="yellow external icon"></i> Open ACME Tool</button>
  138. </div>
  139. <script>
  140. var uploadPendingPublicKey = undefined;
  141. var uploadPendingPrivateKey = undefined;
  142. $("#defaultCA").dropdown();
  143. //Renew certificate by button press
  144. function renewCertificate(domain, dns, btn=undefined){
  145. let defaultCA = $("#defaultCA").dropdown("get value");
  146. if (defaultCA.trim() == ""){
  147. defaultCA = "Let's Encrypt";
  148. }
  149. //Get a new cert using ACME
  150. msgbox("Requesting certificate via " + defaultCA +"...");
  151. //Request ACME for certificate
  152. if (btn != undefined){
  153. $(btn).addClass('disabled');
  154. $(btn).html(`<i class="ui loading spinner icon"></i>`);
  155. }
  156. obtainCertificate(domain, dns, defaultCA.trim(), function(succ){
  157. if (btn != undefined){
  158. $(btn).removeClass('disabled');
  159. if (succ){
  160. $(btn).html(`<i class="ui green check icon"></i>`);
  161. }else{
  162. $(btn).html(`<i class="ui red times icon"></i>`);
  163. }
  164. setTimeout(function(){
  165. initManagedDomainCertificateList();
  166. }, 3000);
  167. }
  168. });
  169. }
  170. /*
  171. Obtain Certificate via ACME
  172. */
  173. // Obtain certificate from API, only support one domain
  174. function obtainCertificate(domains, dns, usingCa = "Let's Encrypt", callback=undefined) {
  175. //Load the ACME email from server side
  176. let acmeEmail = "";
  177. $.get("/api/acme/autoRenew/email", function(data){
  178. if (data != "" && data != undefined && data != null){
  179. acmeEmail = data;
  180. }
  181. let filename = "";
  182. let email = acmeEmail;
  183. if (acmeEmail == ""){
  184. msgbox("Unable to obtain certificate: ACME email not set", false, 8000);
  185. if (callback != undefined){
  186. callback(false);
  187. }
  188. return;
  189. }
  190. if (filename.trim() == "" && !domains.includes(",")){
  191. //Zoraxy filename are the matching name for domains.
  192. //Use the same as domains
  193. filename = domains;
  194. }else if (filename != "" && !domains.includes(",")){
  195. //Invalid settings. Force the filename to be same as domain
  196. //if there are only 1 domain
  197. filename = domains;
  198. }else{
  199. msgbox("Filename cannot be empty for certs containing multiple domains.")
  200. if (callback != undefined){
  201. callback(false);
  202. }
  203. return;
  204. }
  205. //Filename cannot contain wildcards, and wildcards are possible with DNS challenges
  206. filename = filename.replace("*", "_");
  207. $.ajax({
  208. url: "/api/acme/obtainCert",
  209. method: "GET",
  210. data: {
  211. domains: domains,
  212. filename: filename,
  213. email: email,
  214. ca: usingCa,
  215. dns: dns
  216. },
  217. success: function(response) {
  218. if (response.error) {
  219. console.log("Error:", response.error);
  220. // Show error message
  221. msgbox(response.error, false, 12000);
  222. if (callback != undefined){
  223. callback(false);
  224. }
  225. } else {
  226. console.log("Certificate installed successfully");
  227. // Show success message
  228. msgbox("Certificate installed successfully");
  229. if (callback != undefined){
  230. callback(true);
  231. }
  232. }
  233. },
  234. error: function(error) {
  235. console.log("Failed to install certificate:", error);
  236. }
  237. });
  238. });
  239. }
  240. //Delete the certificate by its domain
  241. function deleteCertificate(domain){
  242. if (confirm("Confirm delete certificate for " + domain + " ?")){
  243. $.cjax({
  244. url: "/api/cert/delete",
  245. method: "POST",
  246. data: {domain: domain},
  247. success: function(data){
  248. if (data.error != undefined){
  249. msgbox(data.error, false, 5000);
  250. }else{
  251. initManagedDomainCertificateList();
  252. initDefaultKeypairCheck();
  253. }
  254. }
  255. });
  256. }
  257. }
  258. function initAcmeStatus(){
  259. //Initialize the current default CA options
  260. $.get("/api/acme/autoRenew/email", function(data){
  261. $("#prefACMEEmail").val(data);
  262. if (data.trim() == ""){
  263. //acme email is not yet set
  264. $(".renewButton").addClass('disabled');
  265. }else{
  266. $(".renewButton").removeClass('disabled');
  267. }
  268. });
  269. $.get("/api/acme/autoRenew/ca", function(data){
  270. $("#defaultCA").dropdown("set value", data);
  271. });
  272. $.get("/api/acme/autoRenew/enable", function(data){
  273. setACMEEnableStates(data);
  274. })
  275. }
  276. //Set the status of the acme enable icon
  277. function setACMEEnableStates(enabled){
  278. $("#acmeAutoRenewerStatus").text(enabled?"Enabled":"Disabled");
  279. if (enabled){
  280. $(".acmeRenewStateWrapper").addClass("enabled");
  281. }else{
  282. $(".acmeRenewStateWrapper").removeClass("enabled");
  283. }
  284. $("#acmeAutoRenewer").find("i").attr("class", enabled?"white circle check icon":"white circle times icon");
  285. }
  286. initAcmeStatus();
  287. function saveDefaultCA(){
  288. let newDefaultEmail = $("#prefACMEEmail").val().trim();
  289. let newDefaultCA = $("#defaultCA").dropdown("get value");
  290. if (newDefaultEmail == ""){
  291. msgbox("Invalid acme email given", false);
  292. return;
  293. }
  294. $.cjax({
  295. url: "/api/acme/autoRenew/email",
  296. method: "POST",
  297. data: {"set": newDefaultEmail},
  298. success: function(data){
  299. if (data.error != undefined){
  300. msgbox(data.error, false);
  301. }else{
  302. //Update the renew button states
  303. $(".renewButton").removeClass('disabled');
  304. }
  305. }
  306. });
  307. $.cjax({
  308. url: "/api/acme/autoRenew/ca",
  309. data: {"set": newDefaultCA},
  310. method: "POST",
  311. success: function(data){
  312. if (data.error != undefined){
  313. msgbox(data.error, false);
  314. }
  315. }
  316. });
  317. msgbox("Settings updated");
  318. }
  319. //List the stored certificates
  320. function initManagedDomainCertificateList(){
  321. $.get("/api/cert/list?date=true", function(data){
  322. if (data.error != undefined){
  323. msgbox(data.error, false, 5000);
  324. }else{
  325. $("#certifiedDomainList").html("");
  326. data.sort((a,b) => {
  327. return a.Domain > b.Domain
  328. });
  329. data.forEach(entry => {
  330. let isExpired = entry.RemainingDays <= 0;
  331. let entryDomainRenewKey = entry.Domain;
  332. if (entryDomainRenewKey.includes("_.")){
  333. entryDomainRenewKey = entryDomainRenewKey.replace("_.","*.");
  334. }
  335. $("#certifiedDomainList").append(`<tr>
  336. <td><a style="cursor: pointer;" title="Download certificate" onclick="handleCertDownload('${entry.Domain}');">${entry.Domain}</a></td>
  337. <td>${entry.LastModifiedDate}</td>
  338. <td class="${isExpired?"expired":"valid"} certdate">${entry.ExpireDate} (${!isExpired?entry.RemainingDays+" days left":"Expired"})</td>
  339. <td><i class="${entry.UseDNS?"green check": "red times"} icon"></i></td>
  340. <td><button title="Renew Certificate" class="ui mini basic icon button renewButton" onclick="renewCertificate('${entryDomainRenewKey}', '${entry.UseDNS}', this);"><i class="ui green refresh icon"></i></button></td>
  341. <td><button title="Delete key-pair" class="ui mini basic red icon button" onclick="deleteCertificate('${entry.Domain}');"><i class="ui red trash icon"></i></button></td>
  342. </tr>`);
  343. });
  344. if (data.length == 0){
  345. $("#certifiedDomainList").append(`<tr>
  346. <td colspan="4"><i class="ui times red circle icon"></i> No valid keypairs found</td>
  347. </tr>`);
  348. }
  349. }
  350. })
  351. }
  352. initManagedDomainCertificateList();
  353. function openACMEManager(){
  354. showSideWrapper('snippet/acme.html');
  355. }
  356. function handleDomainUploadByKeypress(){
  357. handleDomainKeysUpload(function(){
  358. $("#certUploadingDomain").text($("#certdomain").val().trim());
  359. //After uploaded, reset the file selector
  360. document.getElementById('pubkeySelector').value = '';
  361. document.getElementById('prikeySelector').value = '';
  362. document.getElementById('certdomain').value = '';
  363. uploadPendingPublicKey = undefined;
  364. uploadPendingPrivateKey = undefined;
  365. //Show succ
  366. $("#certUploadSuccMsg").stop().finish().slideDown("fast").delay(3000).slideUp("fast");
  367. initManagedDomainCertificateList();
  368. });
  369. }
  370. function handleCertDownload(certName){
  371. $.get("/api/cert/download?seek=true&certname=" + certName, function(data){
  372. if (data.error != undefined){
  373. //Error resolving certificate
  374. msgbox(data.error, false);
  375. }else{
  376. //Continue to download
  377. window.open("/api/cert/download?certname=" + certName);
  378. }
  379. });
  380. }
  381. //Handle domain keys upload
  382. function handleDomainKeysUpload(callback=undefined){
  383. let domain = $("#certdomain").val();
  384. if (domain.trim() == ""){
  385. msgbox("Missing domain", false, 5000);
  386. return;
  387. }
  388. if (uploadPendingPublicKey && uploadPendingPrivateKey && typeof uploadPendingPublicKey === 'object' && typeof uploadPendingPrivateKey === 'object') {
  389. const publicKeyForm = new FormData();
  390. const csrfToken = document.querySelector('meta[name="zoraxy.csrf.Token"]').getAttribute("content");
  391. publicKeyForm.append('file', uploadPendingPublicKey, 'publicKey');
  392. const privateKeyForm = new FormData();
  393. privateKeyForm.append('file', uploadPendingPrivateKey, 'privateKey');
  394. const publicKeyRequest = new XMLHttpRequest();
  395. publicKeyRequest.open('POST', '/api/cert/upload?ktype=pub&domain=' + domain);
  396. publicKeyRequest.setRequestHeader('X-CSRF-Token', csrfToken);
  397. publicKeyRequest.onreadystatechange = function() {
  398. if (publicKeyRequest.readyState === XMLHttpRequest.DONE) {
  399. if (publicKeyRequest.status !== 200) {
  400. msgbox('Error uploading public key: ' + publicKeyRequest.statusText, false, 5000);
  401. }
  402. if (callback != undefined){
  403. callback();
  404. }
  405. }
  406. };
  407. publicKeyRequest.send(publicKeyForm);
  408. const privateKeyRequest = new XMLHttpRequest();
  409. privateKeyRequest.open('POST', '/api/cert/upload?ktype=pri&domain=' + domain);
  410. privateKeyRequest.setRequestHeader('X-CSRF-Token', csrfToken);
  411. privateKeyRequest.onreadystatechange = function() {
  412. if (privateKeyRequest.readyState === XMLHttpRequest.DONE) {
  413. if (privateKeyRequest.status !== 200) {
  414. msgbox('Error uploading private key: ' + privateKeyRequest.statusText, false, 5000);
  415. }
  416. if (callback != undefined){
  417. callback();
  418. }
  419. }
  420. };
  421. privateKeyRequest.send(privateKeyForm);
  422. } else {
  423. msgbox('One or both of the files is missing or not a file object');
  424. }
  425. }
  426. //Handlers for selecting domain based key pairs
  427. //ktype = {"pub" / "pri"}
  428. function handleFileSelect(event, ktype="pub") {
  429. const file = event.target.files[0];
  430. if (ktype == "pub"){
  431. uploadPendingPublicKey = file;
  432. }else if (ktype == "pri"){
  433. uploadPendingPrivateKey = file;
  434. }
  435. }
  436. //Check if the default keypairs exists
  437. function initDefaultKeypairCheck(){
  438. $.get("/api/cert/checkDefault", function(data){
  439. let tick = `<i class="ui green checkmark icon"></i>`;
  440. let cross = `<i class="ui red times icon"></i>`;
  441. $("#pubkeyExists").html(data.DefaultPubExists?tick:cross);
  442. $("#prikeyExists").html(data.DefaultPriExists?tick:cross);
  443. });
  444. }
  445. initDefaultKeypairCheck();
  446. function uploadPrivateKey(){
  447. // create file input element
  448. const input = document.createElement('input');
  449. input.type = 'file';
  450. // add change listener to file input
  451. input.addEventListener('change', () => {
  452. // create form data object
  453. const formData = new FormData();
  454. const csrfToken = document.querySelector('meta[name="zoraxy.csrf.Token"]').getAttribute("content");
  455. // add selected file to form data
  456. formData.append('file', input.files[0]);
  457. // send form data to server
  458. fetch('/api/cert/upload?ktype=pri', {
  459. method: 'POST',
  460. body: formData,
  461. headers: {
  462. 'X-CSRF-Token': csrfToken
  463. }
  464. })
  465. .then(response => {
  466. initDefaultKeypairCheck();
  467. if (response.ok) {
  468. msgbox('File upload successful!');
  469. } else {
  470. response.text().then(text => {
  471. msgbox(text, false, 5000);
  472. });
  473. //console.log(response.text());
  474. //alert('File upload failed!');
  475. }
  476. })
  477. .catch(error => {
  478. msgbox('An error occurred while uploading the file.', false, 5000);
  479. console.error(error);
  480. });
  481. });
  482. // click file input to open file selector
  483. input.click();
  484. }
  485. function uploadPublicKey() {
  486. // create file input element
  487. const input = document.createElement('input');
  488. const csrfToken = document.querySelector('meta[name="zoraxy.csrf.Token"]').getAttribute("content");
  489. input.type = 'file';
  490. // add change listener to file input
  491. input.addEventListener('change', () => {
  492. // create form data object
  493. const formData = new FormData();
  494. // add selected file to form data
  495. formData.append('file', input.files[0]);
  496. // send form data to server
  497. fetch('/api/cert/upload?ktype=pub', {
  498. method: 'POST',
  499. body: formData,
  500. headers: {
  501. 'X-CSRF-Token': csrfToken
  502. }
  503. })
  504. .then(response => {
  505. if (response.ok) {
  506. msgbox('File upload successful!');
  507. initDefaultKeypairCheck();
  508. } else {
  509. response.text().then(text => {
  510. msgbox(text, false, 5000);
  511. });
  512. //console.log(response.text());
  513. //alert('File upload failed!');
  514. }
  515. })
  516. .catch(error => {
  517. msgbox('An error occurred while uploading the file.', false, 5000);
  518. console.error(error);
  519. });
  520. });
  521. // click file input to open file selector
  522. input.click();
  523. }
  524. </script>