cert.html 24 KB

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